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); v.setFullYear(y);}\n"
1396 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1397 + "{v = new Date(y, m, d, h, i); v.setFullYear(y);}\n"
1398 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1399 + "{v = new Date(y, m, d, h); v.setFullYear(y);}\n"
1400 + "else if (y >= 0 && m >= 0 && d > 0)\n"
1401 + "{v = new Date(y, m, d); v.setFullYear(y);}\n"
1402 + "else if (y >= 0 && m >= 0)\n"
1403 + "{v = new Date(y, m); v.setFullYear(y);}\n"
1404 + "else if (y >= 0)\n"
1405 + "{v = new Date(y); v.setFullYear(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 = Math.max(0,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?
5154 Roo.log(["UpdateNode" , from, to]);
5155 if (from.nodeType != to.nodeType) {
5156 Roo.log(["ReplaceChild - mismatch notType" , to, from ]);
5157 from.parentNode.replaceChild(to, from);
5160 if (from.nodeType == 3) {
5161 // assume it's text?!
5162 if (from.data == to.data) {
5165 from.data = to.data;
5169 // assume 'to' doesnt have '1/3 nodetypes!
5170 if (from.nodeType !=1 || from.tagName != to.tagName) {
5171 Roo.log(["ReplaceChild" , from, to ]);
5172 from.parentNode.replaceChild(to, from);
5175 // compare attributes
5176 var ar = Array.from(from.attributes);
5177 for(var i = 0; i< ar.length;i++) {
5178 if (to.hasAttribute(ar[i].name)) {
5181 if (ar[i].name == 'id') { // always keep ids?
5184 from.removeAttribute(ar[i].name);
5187 for(var i = 0; i< ar.length;i++) {
5188 if (from.getAttribute(ar[i].name) == to.getAttribute(ar[i].name)) {
5191 from.setAttribute(ar[i].name, to.getAttribute(ar[i].name));
5194 var far = Array.from(from.childNodes);
5195 var tar = Array.from(to.childNodes);
5196 // if the lengths are different.. then it's probably a editable content change, rather than
5197 // a change of the block definition..
5199 // this did notwork , as our rebuilt nodes did not include ID's so did not match at all.
5200 /*if (from.innerHTML == to.innerHTML) {
5203 if (far.length != tar.length) {
5204 from.innerHTML = to.innerHTML;
5209 for(var i = 0; i < Math.max(tar.length, far.length); i++) {
5210 if (i >= far.length) {
5211 from.appendChild(tar[i]);
5212 Roo.log(["add", tar[i]]);
5214 } else if ( i >= tar.length) {
5215 from.removeChild(far[i]);
5216 Roo.log(["remove", far[i]]);
5219 updateNode(far[i], tar[i]);
5231 /** True to force the use of DOM instead of html fragments @type Boolean */
5235 * Returns the markup for the passed Element(s) config
5236 * @param {Object} o The Dom object spec (and children)
5239 markup : function(o){
5240 return createHtml(o);
5244 * Applies a style specification to an element
5245 * @param {String/HTMLElement} el The element to apply styles to
5246 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
5247 * a function which returns such a specification.
5249 applyStyles : function(el, styles){
5252 if(typeof styles == "string"){
5253 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
5255 while ((matches = re.exec(styles)) != null){
5256 el.setStyle(matches[1], matches[2]);
5258 }else if (typeof styles == "object"){
5259 for (var style in styles){
5260 el.setStyle(style, styles[style]);
5262 }else if (typeof styles == "function"){
5263 Roo.DomHelper.applyStyles(el, styles.call());
5269 * Inserts an HTML fragment into the Dom
5270 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
5271 * @param {HTMLElement} el The context element
5272 * @param {String} html The HTML fragmenet
5273 * @return {HTMLElement} The new node
5275 insertHtml : function(where, el, html){
5276 where = where.toLowerCase();
5277 if(el.insertAdjacentHTML){
5278 if(tableRe.test(el.tagName)){
5280 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
5286 el.insertAdjacentHTML('BeforeBegin', html);
5287 return el.previousSibling;
5289 el.insertAdjacentHTML('AfterBegin', html);
5290 return el.firstChild;
5292 el.insertAdjacentHTML('BeforeEnd', html);
5293 return el.lastChild;
5295 el.insertAdjacentHTML('AfterEnd', html);
5296 return el.nextSibling;
5298 throw 'Illegal insertion point -> "' + where + '"';
5300 var range = el.ownerDocument.createRange();
5304 range.setStartBefore(el);
5305 frag = range.createContextualFragment(html);
5306 el.parentNode.insertBefore(frag, el);
5307 return el.previousSibling;
5310 range.setStartBefore(el.firstChild);
5311 frag = range.createContextualFragment(html);
5312 el.insertBefore(frag, el.firstChild);
5313 return el.firstChild;
5315 el.innerHTML = html;
5316 return el.firstChild;
5320 range.setStartAfter(el.lastChild);
5321 frag = range.createContextualFragment(html);
5322 el.appendChild(frag);
5323 return el.lastChild;
5325 el.innerHTML = html;
5326 return el.lastChild;
5329 range.setStartAfter(el);
5330 frag = range.createContextualFragment(html);
5331 el.parentNode.insertBefore(frag, el.nextSibling);
5332 return el.nextSibling;
5334 throw 'Illegal insertion point -> "' + where + '"';
5338 * Creates new Dom element(s) and inserts them before el
5339 * @param {String/HTMLElement/Element} el The context element
5340 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5341 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5342 * @return {HTMLElement/Roo.Element} The new node
5344 insertBefore : function(el, o, returnElement){
5345 return this.doInsert(el, o, returnElement, "beforeBegin");
5349 * Creates new Dom element(s) and inserts them after el
5350 * @param {String/HTMLElement/Element} el The context element
5351 * @param {Object} o The Dom object spec (and children)
5352 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5353 * @return {HTMLElement/Roo.Element} The new node
5355 insertAfter : function(el, o, returnElement){
5356 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
5360 * Creates new Dom element(s) and inserts them as the first child of el
5361 * @param {String/HTMLElement/Element} el The context element
5362 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5363 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5364 * @return {HTMLElement/Roo.Element} The new node
5366 insertFirst : function(el, o, returnElement){
5367 return this.doInsert(el, o, returnElement, "afterBegin");
5371 doInsert : function(el, o, returnElement, pos, sibling){
5372 el = Roo.getDom(el);
5374 if(this.useDom || o.ns){
5375 newNode = createDom(o, null);
5376 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
5378 var html = createHtml(o);
5379 newNode = this.insertHtml(pos, el, html);
5381 return returnElement ? Roo.get(newNode, true) : newNode;
5385 * Creates new Dom element(s) and appends them to el
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 append : function(el, o, returnElement){
5392 el = Roo.getDom(el);
5394 if(this.useDom || o.ns){
5395 newNode = createDom(o, null);
5396 el.appendChild(newNode);
5398 var html = createHtml(o);
5399 newNode = this.insertHtml("beforeEnd", el, html);
5401 return returnElement ? Roo.get(newNode, true) : newNode;
5405 * Creates new Dom element(s) and overwrites the contents of el with them
5406 * @param {String/HTMLElement/Element} el The context element
5407 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5408 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5409 * @return {HTMLElement/Roo.Element} The new node
5411 overwrite : function(el, o, returnElement)
5413 el = Roo.getDom(el);
5416 while (el.childNodes.length) {
5417 el.removeChild(el.firstChild);
5421 el.innerHTML = createHtml(o);
5424 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5428 * Creates a new Roo.DomHelper.Template from the Dom object spec
5429 * @param {Object} o The Dom object spec (and children)
5430 * @return {Roo.DomHelper.Template} The new template
5432 createTemplate : function(o){
5433 var html = createHtml(o);
5434 return new Roo.Template(html);
5437 * Updates the first element with the spec from the o (replacing if necessary)
5438 * This iterates through the children, and updates attributes / children etc..
5439 * @param {String/HTMLElement/Element} el The context element
5440 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5443 update : function(el, o)
5445 updateNode(Roo.getDom(el), createDom(o));
5454 * Ext JS Library 1.1.1
5455 * Copyright(c) 2006-2007, Ext JS, LLC.
5457 * Originally Released Under LGPL - original licence link has changed is not relivant.
5460 * <script type="text/javascript">
5464 * @class Roo.Template
5465 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
5466 * For a list of available format functions, see {@link Roo.util.Format}.<br />
5469 var t = new Roo.Template({
5470 html : '<div name="{id}">' +
5471 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
5473 myformat: function (value, allValues) {
5474 return 'XX' + value;
5477 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
5479 * For more information see this blog post with examples:
5480 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
5481 - Create Elements using DOM, HTML fragments and Templates</a>.
5483 * @param {Object} cfg - Configuration object.
5485 Roo.Template = function(cfg){
5487 if(cfg instanceof Array){
5489 }else if(arguments.length > 1){
5490 cfg = Array.prototype.join.call(arguments, "");
5494 if (typeof(cfg) == 'object') {
5505 Roo.Template.prototype = {
5508 * @cfg {Function} onLoad Called after the template has been loaded and complied (usually from a remove source)
5514 * @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..
5515 * it should be fixed so that template is observable...
5519 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
5527 * Returns an HTML fragment of this template with the specified values applied.
5528 * @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'})
5529 * @return {String} The HTML fragment
5534 applyTemplate : function(values){
5535 //Roo.log(["applyTemplate", values]);
5539 return this.compiled(values);
5541 var useF = this.disableFormats !== true;
5542 var fm = Roo.util.Format, tpl = this;
5543 var fn = function(m, name, format, args){
5545 if(format.substr(0, 5) == "this."){
5546 return tpl.call(format.substr(5), values[name], values);
5549 // quoted values are required for strings in compiled templates,
5550 // but for non compiled we need to strip them
5551 // quoted reversed for jsmin
5552 var re = /^\s*['"](.*)["']\s*$/;
5553 args = args.split(',');
5554 for(var i = 0, len = args.length; i < len; i++){
5555 args[i] = args[i].replace(re, "$1");
5557 args = [values[name]].concat(args);
5559 args = [values[name]];
5561 return fm[format].apply(fm, args);
5564 return values[name] !== undefined ? values[name] : "";
5567 return this.html.replace(this.re, fn);
5585 this.loading = true;
5586 this.compiled = false;
5588 var cx = new Roo.data.Connection();
5592 success : function (response) {
5596 _t.set(response.responseText,true);
5602 failure : function(response) {
5603 Roo.log("Template failed to load from " + _t.url);
5610 * Sets the HTML used as the template and optionally compiles it.
5611 * @param {String} html
5612 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
5613 * @return {Roo.Template} this
5615 set : function(html, compile){
5617 this.compiled = false;
5625 * True to disable format functions (defaults to false)
5628 disableFormats : false,
5631 * The regular expression used to match template variables
5635 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
5638 * Compiles the template into an internal function, eliminating the RegEx overhead.
5639 * @return {Roo.Template} this
5641 compile : function(){
5642 var fm = Roo.util.Format;
5643 var useF = this.disableFormats !== true;
5644 var sep = Roo.isGecko ? "+" : ",";
5645 var fn = function(m, name, format, args){
5647 args = args ? ',' + args : "";
5648 if(format.substr(0, 5) != "this."){
5649 format = "fm." + format + '(';
5651 format = 'this.call("'+ format.substr(5) + '", ';
5655 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
5657 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
5660 // branched to use + in gecko and [].join() in others
5662 body = "this.compiled = function(values){ return '" +
5663 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
5666 body = ["this.compiled = function(values){ return ['"];
5667 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
5668 body.push("'].join('');};");
5669 body = body.join('');
5679 // private function used to call members
5680 call : function(fnName, value, allValues){
5681 return this[fnName](value, allValues);
5685 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
5686 * @param {String/HTMLElement/Roo.Element} el The context element
5687 * @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'})
5688 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5689 * @return {HTMLElement/Roo.Element} The new node or Element
5691 insertFirst: function(el, values, returnElement){
5692 return this.doInsert('afterBegin', el, values, returnElement);
5696 * Applies the supplied values to the template and inserts the new node(s) before el.
5697 * @param {String/HTMLElement/Roo.Element} el The context element
5698 * @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'})
5699 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5700 * @return {HTMLElement/Roo.Element} The new node or Element
5702 insertBefore: function(el, values, returnElement){
5703 return this.doInsert('beforeBegin', el, values, returnElement);
5707 * Applies the supplied values to the template and inserts the new node(s) after el.
5708 * @param {String/HTMLElement/Roo.Element} el The context element
5709 * @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'})
5710 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5711 * @return {HTMLElement/Roo.Element} The new node or Element
5713 insertAfter : function(el, values, returnElement){
5714 return this.doInsert('afterEnd', el, values, returnElement);
5718 * Applies the supplied values to the template and appends the new node(s) to el.
5719 * @param {String/HTMLElement/Roo.Element} el The context element
5720 * @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'})
5721 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5722 * @return {HTMLElement/Roo.Element} The new node or Element
5724 append : function(el, values, returnElement){
5725 return this.doInsert('beforeEnd', el, values, returnElement);
5728 doInsert : function(where, el, values, returnEl){
5729 el = Roo.getDom(el);
5730 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
5731 return returnEl ? Roo.get(newNode, true) : newNode;
5735 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
5736 * @param {String/HTMLElement/Roo.Element} el The context element
5737 * @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'})
5738 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5739 * @return {HTMLElement/Roo.Element} The new node or Element
5741 overwrite : function(el, values, returnElement){
5742 el = Roo.getDom(el);
5743 el.innerHTML = this.applyTemplate(values);
5744 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5748 * Alias for {@link #applyTemplate}
5751 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
5754 Roo.DomHelper.Template = Roo.Template;
5757 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
5758 * @param {String/HTMLElement} el A DOM element or its id
5759 * @returns {Roo.Template} The created template
5762 Roo.Template.from = function(el){
5763 el = Roo.getDom(el);
5764 return new Roo.Template(el.value || el.innerHTML);
5767 * Ext JS Library 1.1.1
5768 * Copyright(c) 2006-2007, Ext JS, LLC.
5770 * Originally Released Under LGPL - original licence link has changed is not relivant.
5773 * <script type="text/javascript">
5778 * This is code is also distributed under MIT license for use
5779 * with jQuery and prototype JavaScript libraries.
5782 * @class Roo.DomQuery
5783 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).
5785 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>
5788 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.
5790 <h4>Element Selectors:</h4>
5792 <li> <b>*</b> any element</li>
5793 <li> <b>E</b> an element with the tag E</li>
5794 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
5795 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
5796 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
5797 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
5799 <h4>Attribute Selectors:</h4>
5800 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
5802 <li> <b>E[foo]</b> has an attribute "foo"</li>
5803 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
5804 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
5805 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
5806 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
5807 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
5808 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
5810 <h4>Pseudo Classes:</h4>
5812 <li> <b>E:first-child</b> E is the first child of its parent</li>
5813 <li> <b>E:last-child</b> E is the last child of its parent</li>
5814 <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>
5815 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
5816 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
5817 <li> <b>E:only-child</b> E is the only child of its parent</li>
5818 <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>
5819 <li> <b>E:first</b> the first E in the resultset</li>
5820 <li> <b>E:last</b> the last E in the resultset</li>
5821 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
5822 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
5823 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
5824 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
5825 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
5826 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
5827 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
5828 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
5829 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
5831 <h4>CSS Value Selectors:</h4>
5833 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
5834 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
5835 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
5836 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
5837 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
5838 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
5842 Roo.DomQuery = function(){
5843 var cache = {}, simpleCache = {}, valueCache = {};
5844 var nonSpace = /\S/;
5845 var trimRe = /^\s+|\s+$/g;
5846 var tplRe = /\{(\d+)\}/g;
5847 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
5848 var tagTokenRe = /^(#)?([\w-\*]+)/;
5849 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
5851 function child(p, index){
5853 var n = p.firstChild;
5855 if(n.nodeType == 1){
5866 while((n = n.nextSibling) && n.nodeType != 1);
5871 while((n = n.previousSibling) && n.nodeType != 1);
5875 function children(d){
5876 var n = d.firstChild, ni = -1;
5878 var nx = n.nextSibling;
5879 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
5889 function byClassName(c, a, v){
5893 var r = [], ri = -1, cn;
5894 for(var i = 0, ci; ci = c[i]; i++){
5898 ( (ci instanceof SVGElement) ? ci.className.baseVal : ci.className)
5899 +' ').indexOf(v) != -1){
5906 function attrValue(n, attr){
5907 if(!n.tagName && typeof n.length != "undefined"){
5916 if(attr == "class" || attr == "className"){
5917 return (n instanceof SVGElement) ? n.className.baseVal : n.className;
5919 return n.getAttribute(attr) || n[attr];
5923 function getNodes(ns, mode, tagName){
5924 var result = [], ri = -1, cs;
5928 tagName = tagName || "*";
5929 if(typeof ns.getElementsByTagName != "undefined"){
5933 for(var i = 0, ni; ni = ns[i]; i++){
5934 cs = ni.getElementsByTagName(tagName);
5935 for(var j = 0, ci; ci = cs[j]; j++){
5939 }else if(mode == "/" || mode == ">"){
5940 var utag = tagName.toUpperCase();
5941 for(var i = 0, ni, cn; ni = ns[i]; i++){
5942 cn = ni.children || ni.childNodes;
5943 for(var j = 0, cj; cj = cn[j]; j++){
5944 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
5949 }else if(mode == "+"){
5950 var utag = tagName.toUpperCase();
5951 for(var i = 0, n; n = ns[i]; i++){
5952 while((n = n.nextSibling) && n.nodeType != 1);
5953 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
5957 }else if(mode == "~"){
5958 for(var i = 0, n; n = ns[i]; i++){
5959 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
5968 function concat(a, b){
5972 for(var i = 0, l = b.length; i < l; i++){
5978 function byTag(cs, tagName){
5979 if(cs.tagName || cs == document){
5985 var r = [], ri = -1;
5986 tagName = tagName.toLowerCase();
5987 for(var i = 0, ci; ci = cs[i]; i++){
5988 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
5995 function byId(cs, attr, id){
5996 if(cs.tagName || cs == document){
6002 var r = [], ri = -1;
6003 for(var i = 0,ci; ci = cs[i]; i++){
6004 if(ci && ci.id == id){
6012 function byAttribute(cs, attr, value, op, custom){
6013 var r = [], ri = -1, st = custom=="{";
6014 var f = Roo.DomQuery.operators[op];
6015 for(var i = 0, ci; ci = cs[i]; i++){
6018 a = Roo.DomQuery.getStyle(ci, attr);
6020 else if(attr == "class" || attr == "className"){
6021 a = (ci instanceof SVGElement) ? ci.className.baseVal : ci.className;
6022 }else if(attr == "for"){
6024 }else if(attr == "href"){
6025 a = ci.getAttribute("href", 2);
6027 a = ci.getAttribute(attr);
6029 if((f && f(a, value)) || (!f && a)){
6036 function byPseudo(cs, name, value){
6037 return Roo.DomQuery.pseudos[name](cs, value);
6040 // This is for IE MSXML which does not support expandos.
6041 // IE runs the same speed using setAttribute, however FF slows way down
6042 // and Safari completely fails so they need to continue to use expandos.
6043 var isIE = window.ActiveXObject ? true : false;
6045 // this eval is stop the compressor from
6046 // renaming the variable to something shorter
6048 /** eval:var:batch */
6053 function nodupIEXml(cs){
6055 cs[0].setAttribute("_nodup", d);
6057 for(var i = 1, len = cs.length; i < len; i++){
6059 if(!c.getAttribute("_nodup") != d){
6060 c.setAttribute("_nodup", d);
6064 for(var i = 0, len = cs.length; i < len; i++){
6065 cs[i].removeAttribute("_nodup");
6074 var len = cs.length, c, i, r = cs, cj, ri = -1;
6075 if(!len || typeof cs.nodeType != "undefined" || len == 1){
6078 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
6079 return nodupIEXml(cs);
6083 for(i = 1; c = cs[i]; i++){
6088 for(var j = 0; j < i; j++){
6091 for(j = i+1; cj = cs[j]; j++){
6103 function quickDiffIEXml(c1, c2){
6105 for(var i = 0, len = c1.length; i < len; i++){
6106 c1[i].setAttribute("_qdiff", d);
6109 for(var i = 0, len = c2.length; i < len; i++){
6110 if(c2[i].getAttribute("_qdiff") != d){
6111 r[r.length] = c2[i];
6114 for(var i = 0, len = c1.length; i < len; i++){
6115 c1[i].removeAttribute("_qdiff");
6120 function quickDiff(c1, c2){
6121 var len1 = c1.length;
6125 if(isIE && c1[0].selectSingleNode){
6126 return quickDiffIEXml(c1, c2);
6129 for(var i = 0; i < len1; i++){
6133 for(var i = 0, len = c2.length; i < len; i++){
6134 if(c2[i]._qdiff != d){
6135 r[r.length] = c2[i];
6141 function quickId(ns, mode, root, id){
6143 var d = root.ownerDocument || root;
6144 return d.getElementById(id);
6146 ns = getNodes(ns, mode, "*");
6147 return byId(ns, null, id);
6151 getStyle : function(el, name){
6152 return Roo.fly(el).getStyle(name);
6155 * Compiles a selector/xpath query into a reusable function. The returned function
6156 * takes one parameter "root" (optional), which is the context node from where the query should start.
6157 * @param {String} selector The selector/xpath query
6158 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
6159 * @return {Function}
6161 compile : function(path, type){
6162 type = type || "select";
6164 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
6165 var q = path, mode, lq;
6166 var tk = Roo.DomQuery.matchers;
6167 var tklen = tk.length;
6170 // accept leading mode switch
6171 var lmode = q.match(modeRe);
6172 if(lmode && lmode[1]){
6173 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
6174 q = q.replace(lmode[1], "");
6176 // strip leading slashes
6177 while(path.substr(0, 1)=="/"){
6178 path = path.substr(1);
6181 while(q && lq != q){
6183 var tm = q.match(tagTokenRe);
6184 if(type == "select"){
6187 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
6189 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
6191 q = q.replace(tm[0], "");
6192 }else if(q.substr(0, 1) != '@'){
6193 fn[fn.length] = 'n = getNodes(n, mode, "*");';
6198 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
6200 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
6202 q = q.replace(tm[0], "");
6205 while(!(mm = q.match(modeRe))){
6206 var matched = false;
6207 for(var j = 0; j < tklen; j++){
6209 var m = q.match(t.re);
6211 fn[fn.length] = t.select.replace(tplRe, function(x, i){
6214 q = q.replace(m[0], "");
6219 // prevent infinite loop on bad selector
6221 throw 'Error parsing selector, parsing failed at "' + q + '"';
6225 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
6226 q = q.replace(mm[1], "");
6229 fn[fn.length] = "return nodup(n);\n}";
6232 * list of variables that need from compression as they are used by eval.
6242 * eval:var:byClassName
6244 * eval:var:byAttribute
6245 * eval:var:attrValue
6253 * Selects a group of elements.
6254 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
6255 * @param {Node} root (optional) The start of the query (defaults to document).
6258 select : function(path, root, type){
6259 if(!root || root == document){
6262 if(typeof root == "string"){
6263 root = document.getElementById(root);
6265 var paths = path.split(",");
6267 for(var i = 0, len = paths.length; i < len; i++){
6268 var p = paths[i].replace(trimRe, "");
6270 cache[p] = Roo.DomQuery.compile(p);
6272 throw p + " is not a valid selector";
6275 var result = cache[p](root);
6276 if(result && result != document){
6277 results = results.concat(result);
6280 if(paths.length > 1){
6281 return nodup(results);
6287 * Selects a single element.
6288 * @param {String} selector The selector/xpath query
6289 * @param {Node} root (optional) The start of the query (defaults to document).
6292 selectNode : function(path, root){
6293 return Roo.DomQuery.select(path, root)[0];
6297 * Selects the value of a node, optionally replacing null with the defaultValue.
6298 * @param {String} selector The selector/xpath query
6299 * @param {Node} root (optional) The start of the query (defaults to document).
6300 * @param {String} defaultValue
6302 selectValue : function(path, root, defaultValue){
6303 path = path.replace(trimRe, "");
6304 if(!valueCache[path]){
6305 valueCache[path] = Roo.DomQuery.compile(path, "select");
6307 var n = valueCache[path](root);
6308 n = n[0] ? n[0] : n;
6309 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
6310 return ((v === null||v === undefined||v==='') ? defaultValue : v);
6314 * Selects the value of a node, parsing integers and floats.
6315 * @param {String} selector The selector/xpath query
6316 * @param {Node} root (optional) The start of the query (defaults to document).
6317 * @param {Number} defaultValue
6320 selectNumber : function(path, root, defaultValue){
6321 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
6322 return parseFloat(v);
6326 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
6327 * @param {String/HTMLElement/Array} el An element id, element or array of elements
6328 * @param {String} selector The simple selector to test
6331 is : function(el, ss){
6332 if(typeof el == "string"){
6333 el = document.getElementById(el);
6335 var isArray = (el instanceof Array);
6336 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
6337 return isArray ? (result.length == el.length) : (result.length > 0);
6341 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
6342 * @param {Array} el An array of elements to filter
6343 * @param {String} selector The simple selector to test
6344 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
6345 * the selector instead of the ones that match
6348 filter : function(els, ss, nonMatches){
6349 ss = ss.replace(trimRe, "");
6350 if(!simpleCache[ss]){
6351 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
6353 var result = simpleCache[ss](els);
6354 return nonMatches ? quickDiff(result, els) : result;
6358 * Collection of matching regular expressions and code snippets.
6362 select: 'n = byClassName(n, null, " {1} ");'
6364 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
6365 select: 'n = byPseudo(n, "{1}", "{2}");'
6367 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
6368 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
6371 select: 'n = byId(n, null, "{1}");'
6374 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
6379 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
6380 * 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, > <.
6383 "=" : function(a, v){
6386 "!=" : function(a, v){
6389 "^=" : function(a, v){
6390 return a && a.substr(0, v.length) == v;
6392 "$=" : function(a, v){
6393 return a && a.substr(a.length-v.length) == v;
6395 "*=" : function(a, v){
6396 return a && a.indexOf(v) !== -1;
6398 "%=" : function(a, v){
6399 return (a % v) == 0;
6401 "|=" : function(a, v){
6402 return a && (a == v || a.substr(0, v.length+1) == v+'-');
6404 "~=" : function(a, v){
6405 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
6410 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
6411 * and the argument (if any) supplied in the selector.
6414 "first-child" : function(c){
6415 var r = [], ri = -1, n;
6416 for(var i = 0, ci; ci = n = c[i]; i++){
6417 while((n = n.previousSibling) && n.nodeType != 1);
6425 "last-child" : function(c){
6426 var r = [], ri = -1, n;
6427 for(var i = 0, ci; ci = n = c[i]; i++){
6428 while((n = n.nextSibling) && n.nodeType != 1);
6436 "nth-child" : function(c, a) {
6437 var r = [], ri = -1;
6438 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
6439 var f = (m[1] || 1) - 0, l = m[2] - 0;
6440 for(var i = 0, n; n = c[i]; i++){
6441 var pn = n.parentNode;
6442 if (batch != pn._batch) {
6444 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
6445 if(cn.nodeType == 1){
6452 if (l == 0 || n.nodeIndex == l){
6455 } else if ((n.nodeIndex + l) % f == 0){
6463 "only-child" : function(c){
6464 var r = [], ri = -1;;
6465 for(var i = 0, ci; ci = c[i]; i++){
6466 if(!prev(ci) && !next(ci)){
6473 "empty" : function(c){
6474 var r = [], ri = -1;
6475 for(var i = 0, ci; ci = c[i]; i++){
6476 var cns = ci.childNodes, j = 0, cn, empty = true;
6479 if(cn.nodeType == 1 || cn.nodeType == 3){
6491 "contains" : function(c, v){
6492 var r = [], ri = -1;
6493 for(var i = 0, ci; ci = c[i]; i++){
6494 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
6501 "nodeValue" : function(c, v){
6502 var r = [], ri = -1;
6503 for(var i = 0, ci; ci = c[i]; i++){
6504 if(ci.firstChild && ci.firstChild.nodeValue == v){
6511 "checked" : function(c){
6512 var r = [], ri = -1;
6513 for(var i = 0, ci; ci = c[i]; i++){
6514 if(ci.checked == true){
6521 "not" : function(c, ss){
6522 return Roo.DomQuery.filter(c, ss, true);
6525 "odd" : function(c){
6526 return this["nth-child"](c, "odd");
6529 "even" : function(c){
6530 return this["nth-child"](c, "even");
6533 "nth" : function(c, a){
6534 return c[a-1] || [];
6537 "first" : function(c){
6541 "last" : function(c){
6542 return c[c.length-1] || [];
6545 "has" : function(c, ss){
6546 var s = Roo.DomQuery.select;
6547 var r = [], ri = -1;
6548 for(var i = 0, ci; ci = c[i]; i++){
6549 if(s(ss, ci).length > 0){
6556 "next" : function(c, ss){
6557 var is = Roo.DomQuery.is;
6558 var r = [], ri = -1;
6559 for(var i = 0, ci; ci = c[i]; i++){
6568 "prev" : function(c, ss){
6569 var is = Roo.DomQuery.is;
6570 var r = [], ri = -1;
6571 for(var i = 0, ci; ci = c[i]; i++){
6584 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
6585 * @param {String} path The selector/xpath query
6586 * @param {Node} root (optional) The start of the query (defaults to document).
6591 Roo.query = Roo.DomQuery.select;
6594 * Ext JS Library 1.1.1
6595 * Copyright(c) 2006-2007, Ext JS, LLC.
6597 * Originally Released Under LGPL - original licence link has changed is not relivant.
6600 * <script type="text/javascript">
6604 * @class Roo.util.Observable
6605 * Base class that provides a common interface for publishing events. Subclasses are expected to
6606 * to have a property "events" with all the events defined.<br>
6609 Employee = function(name){
6616 Roo.extend(Employee, Roo.util.Observable);
6618 * @param {Object} config properties to use (incuding events / listeners)
6621 Roo.util.Observable = function(cfg){
6624 this.addEvents(cfg.events || {});
6626 delete cfg.events; // make sure
6629 Roo.apply(this, cfg);
6632 this.on(this.listeners);
6633 delete this.listeners;
6636 Roo.util.Observable.prototype = {
6638 * @cfg {Object} listeners list of events and functions to call for this object,
6642 'click' : function(e) {
6652 * Fires the specified event with the passed parameters (minus the event name).
6653 * @param {String} eventName
6654 * @param {Object...} args Variable number of parameters are passed to handlers
6655 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
6657 fireEvent : function(){
6658 var ce = this.events[arguments[0].toLowerCase()];
6659 if(typeof ce == "object"){
6660 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
6667 filterOptRe : /^(?:scope|delay|buffer|single)$/,
6670 * Appends an event handler to this component
6671 * @param {String} eventName The type of event to listen for
6672 * @param {Function} handler The method the event invokes
6673 * @param {Object} scope (optional) The scope in which to execute the handler
6674 * function. The handler function's "this" context.
6675 * @param {Object} options (optional) An object containing handler configuration
6676 * properties. This may contain any of the following properties:<ul>
6677 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6678 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6679 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6680 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6681 * by the specified number of milliseconds. If the event fires again within that time, the original
6682 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6685 * <b>Combining Options</b><br>
6686 * Using the options argument, it is possible to combine different types of listeners:<br>
6688 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
6690 el.on('click', this.onClick, this, {
6697 * <b>Attaching multiple handlers in 1 call</b><br>
6698 * The method also allows for a single argument to be passed which is a config object containing properties
6699 * which specify multiple handlers.
6708 fn: this.onMouseOver,
6712 fn: this.onMouseOut,
6718 * Or a shorthand syntax which passes the same scope object to all handlers:
6721 'click': this.onClick,
6722 'mouseover': this.onMouseOver,
6723 'mouseout': this.onMouseOut,
6728 addListener : function(eventName, fn, scope, o){
6729 if(typeof eventName == "object"){
6732 if(this.filterOptRe.test(e)){
6735 if(typeof o[e] == "function"){
6737 this.addListener(e, o[e], o.scope, o);
6739 // individual options
6740 this.addListener(e, o[e].fn, o[e].scope, o[e]);
6745 o = (!o || typeof o == "boolean") ? {} : o;
6746 eventName = eventName.toLowerCase();
6747 var ce = this.events[eventName] || true;
6748 if(typeof ce == "boolean"){
6749 ce = new Roo.util.Event(this, eventName);
6750 this.events[eventName] = ce;
6752 ce.addListener(fn, scope, o);
6756 * Removes a listener
6757 * @param {String} eventName The type of event to listen for
6758 * @param {Function} handler The handler to remove
6759 * @param {Object} scope (optional) The scope (this object) for the handler
6761 removeListener : function(eventName, fn, scope){
6762 var ce = this.events[eventName.toLowerCase()];
6763 if(typeof ce == "object"){
6764 ce.removeListener(fn, scope);
6769 * Removes all listeners for this object
6771 purgeListeners : function(){
6772 for(var evt in this.events){
6773 if(typeof this.events[evt] == "object"){
6774 this.events[evt].clearListeners();
6779 relayEvents : function(o, events){
6780 var createHandler = function(ename){
6783 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
6786 for(var i = 0, len = events.length; i < len; i++){
6787 var ename = events[i];
6788 if(!this.events[ename]){
6789 this.events[ename] = true;
6791 o.on(ename, createHandler(ename), this);
6796 * Used to define events on this Observable
6797 * @param {Object} object The object with the events defined
6799 addEvents : function(o){
6803 Roo.applyIf(this.events, o);
6807 * Checks to see if this object has any listeners for a specified event
6808 * @param {String} eventName The name of the event to check for
6809 * @return {Boolean} True if the event is being listened for, else false
6811 hasListener : function(eventName){
6812 var e = this.events[eventName];
6813 return typeof e == "object" && e.listeners.length > 0;
6817 * Appends an event handler to this element (shorthand for addListener)
6818 * @param {String} eventName The type of event to listen for
6819 * @param {Function} handler The method the event invokes
6820 * @param {Object} scope (optional) The scope in which to execute the handler
6821 * function. The handler function's "this" context.
6822 * @param {Object} options (optional)
6825 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
6827 * Removes a listener (shorthand for removeListener)
6828 * @param {String} eventName The type of event to listen for
6829 * @param {Function} handler The handler to remove
6830 * @param {Object} scope (optional) The scope (this object) for the handler
6833 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
6836 * Starts capture on the specified Observable. All events will be passed
6837 * to the supplied function with the event name + standard signature of the event
6838 * <b>before</b> the event is fired. If the supplied function returns false,
6839 * the event will not fire.
6840 * @param {Observable} o The Observable to capture
6841 * @param {Function} fn The function to call
6842 * @param {Object} scope (optional) The scope (this object) for the fn
6845 Roo.util.Observable.capture = function(o, fn, scope){
6846 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
6850 * Removes <b>all</b> added captures from the Observable.
6851 * @param {Observable} o The Observable to release
6854 Roo.util.Observable.releaseCapture = function(o){
6855 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
6860 var createBuffered = function(h, o, scope){
6861 var task = new Roo.util.DelayedTask();
6863 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
6867 var createSingle = function(h, e, fn, scope){
6869 e.removeListener(fn, scope);
6870 return h.apply(scope, arguments);
6874 var createDelayed = function(h, o, scope){
6876 var args = Array.prototype.slice.call(arguments, 0);
6877 setTimeout(function(){
6878 h.apply(scope, args);
6883 Roo.util.Event = function(obj, name){
6886 this.listeners = [];
6889 Roo.util.Event.prototype = {
6890 addListener : function(fn, scope, options){
6891 var o = options || {};
6892 scope = scope || this.obj;
6893 if(!this.isListening(fn, scope)){
6894 var l = {fn: fn, scope: scope, options: o};
6897 h = createDelayed(h, o, scope);
6900 h = createSingle(h, this, fn, scope);
6903 h = createBuffered(h, o, scope);
6906 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
6907 this.listeners.push(l);
6909 this.listeners = this.listeners.slice(0);
6910 this.listeners.push(l);
6915 findListener : function(fn, scope){
6916 scope = scope || this.obj;
6917 var ls = this.listeners;
6918 for(var i = 0, len = ls.length; i < len; i++){
6920 if(l.fn == fn && l.scope == scope){
6927 isListening : function(fn, scope){
6928 return this.findListener(fn, scope) != -1;
6931 removeListener : function(fn, scope){
6933 if((index = this.findListener(fn, scope)) != -1){
6935 this.listeners.splice(index, 1);
6937 this.listeners = this.listeners.slice(0);
6938 this.listeners.splice(index, 1);
6945 clearListeners : function(){
6946 this.listeners = [];
6950 var ls = this.listeners, scope, len = ls.length;
6953 var args = Array.prototype.slice.call(arguments, 0);
6954 for(var i = 0; i < len; i++){
6956 if(l.fireFn.apply(l.scope||this.obj||window, args) === false){
6957 this.firing = false;
6961 this.firing = false;
6968 * Copyright(c) 2007-2017, Roo J Solutions Ltd
6975 * @class Roo.Document
6976 * @extends Roo.util.Observable
6977 * This is a convience class to wrap up the main document loading code.. , rather than adding Roo.onReady(......)
6979 * @param {Object} config the methods and properties of the 'base' class for the application.
6981 * Generic Page handler - implement this to start your app..
6984 * MyProject = new Roo.Document({
6986 'load' : true // your events..
6989 'ready' : function() {
6990 // fired on Roo.onReady()
6995 Roo.Document = function(cfg) {
7000 Roo.util.Observable.call(this,cfg);
7004 Roo.onReady(function() {
7005 _this.fireEvent('ready');
7011 Roo.extend(Roo.Document, Roo.util.Observable, {});/*
7013 * Ext JS Library 1.1.1
7014 * Copyright(c) 2006-2007, Ext JS, LLC.
7016 * Originally Released Under LGPL - original licence link has changed is not relivant.
7019 * <script type="text/javascript">
7023 * @class Roo.EventManager
7024 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
7025 * several useful events directly.
7026 * See {@link Roo.EventObject} for more details on normalized event objects.
7029 Roo.EventManager = function(){
7030 var docReadyEvent, docReadyProcId, docReadyState = false;
7031 var resizeEvent, resizeTask, textEvent, textSize;
7032 var E = Roo.lib.Event;
7033 var D = Roo.lib.Dom;
7038 var fireDocReady = function(){
7040 docReadyState = true;
7043 clearInterval(docReadyProcId);
7045 if(Roo.isGecko || Roo.isOpera) {
7046 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
7049 var defer = document.getElementById("ie-deferred-loader");
7051 defer.onreadystatechange = null;
7052 defer.parentNode.removeChild(defer);
7056 docReadyEvent.fire();
7057 docReadyEvent.clearListeners();
7062 var initDocReady = function(){
7063 docReadyEvent = new Roo.util.Event();
7064 if(Roo.isGecko || Roo.isOpera) {
7065 document.addEventListener("DOMContentLoaded", fireDocReady, false);
7067 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
7068 var defer = document.getElementById("ie-deferred-loader");
7069 defer.onreadystatechange = function(){
7070 if(this.readyState == "complete"){
7074 }else if(Roo.isSafari){
7075 docReadyProcId = setInterval(function(){
7076 var rs = document.readyState;
7077 if(rs == "complete") {
7082 // no matter what, make sure it fires on load
7083 E.on(window, "load", fireDocReady);
7086 var createBuffered = function(h, o){
7087 var task = new Roo.util.DelayedTask(h);
7089 // create new event object impl so new events don't wipe out properties
7090 e = new Roo.EventObjectImpl(e);
7091 task.delay(o.buffer, h, null, [e]);
7095 var createSingle = function(h, el, ename, fn){
7097 Roo.EventManager.removeListener(el, ename, fn);
7102 var createDelayed = function(h, o){
7104 // create new event object impl so new events don't wipe out properties
7105 e = new Roo.EventObjectImpl(e);
7106 setTimeout(function(){
7111 var transitionEndVal = false;
7113 var transitionEnd = function()
7115 if (transitionEndVal) {
7116 return transitionEndVal;
7118 var el = document.createElement('div');
7120 var transEndEventNames = {
7121 WebkitTransition : 'webkitTransitionEnd',
7122 MozTransition : 'transitionend',
7123 OTransition : 'oTransitionEnd otransitionend',
7124 transition : 'transitionend'
7127 for (var name in transEndEventNames) {
7128 if (el.style[name] !== undefined) {
7129 transitionEndVal = transEndEventNames[name];
7130 return transitionEndVal ;
7137 var listen = function(element, ename, opt, fn, scope)
7139 var o = (!opt || typeof opt == "boolean") ? {} : opt;
7140 fn = fn || o.fn; scope = scope || o.scope;
7141 var el = Roo.getDom(element);
7145 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
7148 if (ename == 'transitionend') {
7149 ename = transitionEnd();
7151 var h = function(e){
7152 e = Roo.EventObject.setEvent(e);
7155 t = e.getTarget(o.delegate, el);
7162 if(o.stopEvent === true){
7165 if(o.preventDefault === true){
7168 if(o.stopPropagation === true){
7169 e.stopPropagation();
7172 if(o.normalized === false){
7176 fn.call(scope || el, e, t, o);
7179 h = createDelayed(h, o);
7182 h = createSingle(h, el, ename, fn);
7185 h = createBuffered(h, o);
7188 fn._handlers = fn._handlers || [];
7191 fn._handlers.push([Roo.id(el), ename, h]);
7195 E.on(el, ename, h); // this adds the actuall listener to the object..
7198 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
7199 el.addEventListener("DOMMouseScroll", h, false);
7200 E.on(window, 'unload', function(){
7201 el.removeEventListener("DOMMouseScroll", h, false);
7204 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7205 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
7210 var stopListening = function(el, ename, fn){
7211 var id = Roo.id(el), hds = fn._handlers, hd = fn;
7213 for(var i = 0, len = hds.length; i < len; i++){
7215 if(h[0] == id && h[1] == ename){
7222 E.un(el, ename, hd);
7223 el = Roo.getDom(el);
7224 if(ename == "mousewheel" && el.addEventListener){
7225 el.removeEventListener("DOMMouseScroll", hd, false);
7227 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7228 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
7232 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
7239 * @scope Roo.EventManager
7244 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
7245 * object with a Roo.EventObject
7246 * @param {Function} fn The method the event invokes
7247 * @param {Object} scope An object that becomes the scope of the handler
7248 * @param {boolean} override If true, the obj passed in becomes
7249 * the execution scope of the listener
7250 * @return {Function} The wrapped function
7253 wrap : function(fn, scope, override){
7255 Roo.EventObject.setEvent(e);
7256 fn.call(override ? scope || window : window, Roo.EventObject, scope);
7261 * Appends an event handler to an element (shorthand for addListener)
7262 * @param {String/HTMLElement} element The html element or id to assign the
7263 * @param {String} eventName The type of event to listen for
7264 * @param {Function} handler The method the event invokes
7265 * @param {Object} scope (optional) The scope in which to execute the handler
7266 * function. The handler function's "this" context.
7267 * @param {Object} options (optional) An object containing handler configuration
7268 * properties. This may contain any of the following properties:<ul>
7269 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7270 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7271 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7272 * <li>preventDefault {Boolean} True to prevent the default action</li>
7273 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7274 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7275 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7276 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7277 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7278 * by the specified number of milliseconds. If the event fires again within that time, the original
7279 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7282 * <b>Combining Options</b><br>
7283 * Using the options argument, it is possible to combine different types of listeners:<br>
7285 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7287 el.on('click', this.onClick, this, {
7294 * <b>Attaching multiple handlers in 1 call</b><br>
7295 * The method also allows for a single argument to be passed which is a config object containing properties
7296 * which specify multiple handlers.
7306 fn: this.onMouseOver
7315 * Or a shorthand syntax:<br>
7318 'click' : this.onClick,
7319 'mouseover' : this.onMouseOver,
7320 'mouseout' : this.onMouseOut
7324 addListener : function(element, eventName, fn, scope, options){
7325 if(typeof eventName == "object"){
7331 if(typeof o[e] == "function"){
7333 listen(element, e, o, o[e], o.scope);
7335 // individual options
7336 listen(element, e, o[e]);
7341 return listen(element, eventName, options, fn, scope);
7345 * Removes an event handler
7347 * @param {String/HTMLElement} element The id or html element to remove the
7349 * @param {String} eventName The type of event
7350 * @param {Function} fn
7351 * @return {Boolean} True if a listener was actually removed
7353 removeListener : function(element, eventName, fn){
7354 return stopListening(element, eventName, fn);
7358 * Fires when the document is ready (before onload and before images are loaded). Can be
7359 * accessed shorthanded Roo.onReady().
7360 * @param {Function} fn The method the event invokes
7361 * @param {Object} scope An object that becomes the scope of the handler
7362 * @param {boolean} options
7364 onDocumentReady : function(fn, scope, options){
7365 if(docReadyState){ // if it already fired
7366 docReadyEvent.addListener(fn, scope, options);
7367 docReadyEvent.fire();
7368 docReadyEvent.clearListeners();
7374 docReadyEvent.addListener(fn, scope, options);
7378 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
7379 * @param {Function} fn The method the event invokes
7380 * @param {Object} scope An object that becomes the scope of the handler
7381 * @param {boolean} options
7383 onWindowResize : function(fn, scope, options)
7386 resizeEvent = new Roo.util.Event();
7387 resizeTask = new Roo.util.DelayedTask(function(){
7388 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7390 E.on(window, "resize", function()
7393 resizeTask.delay(50);
7395 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7399 resizeEvent.addListener(fn, scope, options);
7403 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
7404 * @param {Function} fn The method the event invokes
7405 * @param {Object} scope An object that becomes the scope of the handler
7406 * @param {boolean} options
7408 onTextResize : function(fn, scope, options){
7410 textEvent = new Roo.util.Event();
7411 var textEl = new Roo.Element(document.createElement('div'));
7412 textEl.dom.className = 'x-text-resize';
7413 textEl.dom.innerHTML = 'X';
7414 textEl.appendTo(document.body);
7415 textSize = textEl.dom.offsetHeight;
7416 setInterval(function(){
7417 if(textEl.dom.offsetHeight != textSize){
7418 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
7420 }, this.textResizeInterval);
7422 textEvent.addListener(fn, scope, options);
7426 * Removes the passed window resize listener.
7427 * @param {Function} fn The method the event invokes
7428 * @param {Object} scope The scope of handler
7430 removeResizeListener : function(fn, scope){
7432 resizeEvent.removeListener(fn, scope);
7437 fireResize : function(){
7439 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7443 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
7447 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
7449 textResizeInterval : 50
7454 * @scopeAlias pub=Roo.EventManager
7458 * Appends an event handler to an element (shorthand for addListener)
7459 * @param {String/HTMLElement} element The html element or id to assign the
7460 * @param {String} eventName The type of event to listen for
7461 * @param {Function} handler The method the event invokes
7462 * @param {Object} scope (optional) The scope in which to execute the handler
7463 * function. The handler function's "this" context.
7464 * @param {Object} options (optional) An object containing handler configuration
7465 * properties. This may contain any of the following properties:<ul>
7466 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7467 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7468 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7469 * <li>preventDefault {Boolean} True to prevent the default action</li>
7470 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7471 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7472 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7473 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7474 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7475 * by the specified number of milliseconds. If the event fires again within that time, the original
7476 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7479 * <b>Combining Options</b><br>
7480 * Using the options argument, it is possible to combine different types of listeners:<br>
7482 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7484 el.on('click', this.onClick, this, {
7491 * <b>Attaching multiple handlers in 1 call</b><br>
7492 * The method also allows for a single argument to be passed which is a config object containing properties
7493 * which specify multiple handlers.
7503 fn: this.onMouseOver
7512 * Or a shorthand syntax:<br>
7515 'click' : this.onClick,
7516 'mouseover' : this.onMouseOver,
7517 'mouseout' : this.onMouseOut
7521 pub.on = pub.addListener;
7522 pub.un = pub.removeListener;
7524 pub.stoppedMouseDownEvent = new Roo.util.Event();
7528 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
7529 * @param {Function} fn The method the event invokes
7530 * @param {Object} scope An object that becomes the scope of the handler
7531 * @param {boolean} override If true, the obj passed in becomes
7532 * the execution scope of the listener
7536 Roo.onReady = Roo.EventManager.onDocumentReady;
7538 Roo.onReady(function(){
7539 var bd = Roo.get(document.body);
7544 : Roo.isIE11 ? "roo-ie11"
7545 : Roo.isEdge ? "roo-edge"
7546 : Roo.isGecko ? "roo-gecko"
7547 : Roo.isOpera ? "roo-opera"
7548 : Roo.isSafari ? "roo-safari" : ""];
7551 cls.push("roo-mac");
7554 cls.push("roo-linux");
7557 cls.push("roo-ios");
7560 cls.push("roo-touch");
7562 if(Roo.isBorderBox){
7563 cls.push('roo-border-box');
7565 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
7566 var p = bd.dom.parentNode;
7568 p.className += ' roo-strict';
7571 bd.addClass(cls.join(' '));
7575 * @class Roo.EventObject
7576 * EventObject exposes the Yahoo! UI Event functionality directly on the object
7577 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
7580 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
7582 var target = e.getTarget();
7585 var myDiv = Roo.get("myDiv");
7586 myDiv.on("click", handleClick);
7588 Roo.EventManager.on("myDiv", 'click', handleClick);
7589 Roo.EventManager.addListener("myDiv", 'click', handleClick);
7593 Roo.EventObject = function(){
7595 var E = Roo.lib.Event;
7597 // safari keypress events for special keys return bad keycodes
7600 63235 : 39, // right
7603 63276 : 33, // page up
7604 63277 : 34, // page down
7605 63272 : 46, // delete
7610 // normalize button clicks
7611 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
7612 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
7614 Roo.EventObjectImpl = function(e){
7616 this.setEvent(e.browserEvent || e);
7619 Roo.EventObjectImpl.prototype = {
7621 * Used to fix doc tools.
7622 * @scope Roo.EventObject.prototype
7628 /** The normal browser event */
7629 browserEvent : null,
7630 /** The button pressed in a mouse event */
7632 /** True if the shift key was down during the event */
7634 /** True if the control key was down during the event */
7636 /** True if the alt key was down during the event */
7695 setEvent : function(e){
7696 if(e == this || (e && e.browserEvent)){ // already wrapped
7699 this.browserEvent = e;
7701 // normalize buttons
7702 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
7703 if(e.type == 'click' && this.button == -1){
7707 this.shiftKey = e.shiftKey;
7708 // mac metaKey behaves like ctrlKey
7709 this.ctrlKey = e.ctrlKey || e.metaKey;
7710 this.altKey = e.altKey;
7711 // in getKey these will be normalized for the mac
7712 this.keyCode = e.keyCode;
7713 // keyup warnings on firefox.
7714 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
7715 // cache the target for the delayed and or buffered events
7716 this.target = E.getTarget(e);
7718 this.xy = E.getXY(e);
7721 this.shiftKey = false;
7722 this.ctrlKey = false;
7723 this.altKey = false;
7733 * Stop the event (preventDefault and stopPropagation)
7735 stopEvent : function(){
7736 if(this.browserEvent){
7737 if(this.browserEvent.type == 'mousedown'){
7738 Roo.EventManager.stoppedMouseDownEvent.fire(this);
7740 E.stopEvent(this.browserEvent);
7745 * Prevents the browsers default handling of the event.
7747 preventDefault : function(){
7748 if(this.browserEvent){
7749 E.preventDefault(this.browserEvent);
7754 isNavKeyPress : function(){
7755 var k = this.keyCode;
7756 k = Roo.isSafari ? (safariKeys[k] || k) : k;
7757 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
7760 isSpecialKey : function(){
7761 var k = this.keyCode;
7762 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
7763 (k == 16) || (k == 17) ||
7764 (k >= 18 && k <= 20) ||
7765 (k >= 33 && k <= 35) ||
7766 (k >= 36 && k <= 39) ||
7767 (k >= 44 && k <= 45);
7770 * Cancels bubbling of the event.
7772 stopPropagation : function(){
7773 if(this.browserEvent){
7774 if(this.type == 'mousedown'){
7775 Roo.EventManager.stoppedMouseDownEvent.fire(this);
7777 E.stopPropagation(this.browserEvent);
7782 * Gets the key code for the event.
7785 getCharCode : function(){
7786 return this.charCode || this.keyCode;
7790 * Returns a normalized keyCode for the event.
7791 * @return {Number} The key code
7793 getKey : function(){
7794 var k = this.keyCode || this.charCode;
7795 return Roo.isSafari ? (safariKeys[k] || k) : k;
7799 * Gets the x coordinate of the event.
7802 getPageX : function(){
7807 * Gets the y coordinate of the event.
7810 getPageY : function(){
7815 * Gets the time of the event.
7818 getTime : function(){
7819 if(this.browserEvent){
7820 return E.getTime(this.browserEvent);
7826 * Gets the page coordinates of the event.
7827 * @return {Array} The xy values like [x, y]
7834 * Gets the target for the event.
7835 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
7836 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7837 search as a number or element (defaults to 10 || document.body)
7838 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7839 * @return {HTMLelement}
7841 getTarget : function(selector, maxDepth, returnEl){
7842 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
7845 * Gets the related target.
7846 * @return {HTMLElement}
7848 getRelatedTarget : function(){
7849 if(this.browserEvent){
7850 return E.getRelatedTarget(this.browserEvent);
7856 * Normalizes mouse wheel delta across browsers
7857 * @return {Number} The delta
7859 getWheelDelta : function(){
7860 var e = this.browserEvent;
7862 if(e.wheelDelta){ /* IE/Opera. */
7863 delta = e.wheelDelta/120;
7864 }else if(e.detail){ /* Mozilla case. */
7865 delta = -e.detail/3;
7871 * Returns true if the control, meta, shift or alt key was pressed during this event.
7874 hasModifier : function(){
7875 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
7879 * Returns true if the target of this event equals el or is a child of el
7880 * @param {String/HTMLElement/Element} el
7881 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
7884 within : function(el, related){
7885 var t = this[related ? "getRelatedTarget" : "getTarget"]();
7886 return t && Roo.fly(el).contains(t);
7889 getPoint : function(){
7890 return new Roo.lib.Point(this.xy[0], this.xy[1]);
7894 return new Roo.EventObjectImpl();
7899 * Ext JS Library 1.1.1
7900 * Copyright(c) 2006-2007, Ext JS, LLC.
7902 * Originally Released Under LGPL - original licence link has changed is not relivant.
7905 * <script type="text/javascript">
7909 // was in Composite Element!??!?!
7912 var D = Roo.lib.Dom;
7913 var E = Roo.lib.Event;
7914 var A = Roo.lib.Anim;
7916 // local style camelizing for speed
7918 var camelRe = /(-[a-z])/gi;
7919 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
7920 var view = document.defaultView;
7923 * @class Roo.Element
7924 * Represents an Element in the DOM.<br><br>
7927 var el = Roo.get("my-div");
7930 var el = getEl("my-div");
7932 // or with a DOM element
7933 var el = Roo.get(myDivElement);
7935 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
7936 * each call instead of constructing a new one.<br><br>
7937 * <b>Animations</b><br />
7938 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
7939 * should either be a boolean (true) or an object literal with animation options. The animation options are:
7941 Option Default Description
7942 --------- -------- ---------------------------------------------
7943 duration .35 The duration of the animation in seconds
7944 easing easeOut The YUI easing method
7945 callback none A function to execute when the anim completes
7946 scope this The scope (this) of the callback function
7948 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
7949 * manipulate the animation. Here's an example:
7951 var el = Roo.get("my-div");
7956 // default animation
7957 el.setWidth(100, true);
7959 // animation with some options set
7966 // using the "anim" property to get the Anim object
7972 el.setWidth(100, opt);
7974 if(opt.anim.isAnimated()){
7978 * <b> Composite (Collections of) Elements</b><br />
7979 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
7980 * @constructor Create a new Element directly.
7981 * @param {String/HTMLElement} element
7982 * @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).
7984 Roo.Element = function(element, forceNew)
7986 var dom = typeof element == "string" ?
7987 document.getElementById(element) : element;
7989 this.listeners = {};
7991 if(!dom){ // invalid id/element
7995 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
7996 return Roo.Element.cache[id];
8006 * The DOM element ID
8009 this.id = id || Roo.id(dom);
8011 return this; // assumed for cctor?
8014 var El = Roo.Element;
8018 * The element's default display mode (defaults to "")
8021 originalDisplay : "",
8024 // note this is overridden in BS version..
8027 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
8033 * Sets the element's visibility mode. When setVisible() is called it
8034 * will use this to determine whether to set the visibility or the display property.
8035 * @param visMode Element.VISIBILITY or Element.DISPLAY
8036 * @return {Roo.Element} this
8038 setVisibilityMode : function(visMode){
8039 this.visibilityMode = visMode;
8043 * Convenience method for setVisibilityMode(Element.DISPLAY)
8044 * @param {String} display (optional) What to set display to when visible
8045 * @return {Roo.Element} this
8047 enableDisplayMode : function(display){
8048 this.setVisibilityMode(El.DISPLAY);
8049 if(typeof display != "undefined") { this.originalDisplay = display; }
8054 * 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)
8055 * @param {String} selector The simple selector to test
8056 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8057 search as a number or element (defaults to 10 || document.body)
8058 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8059 * @return {HTMLElement} The matching DOM node (or null if no match was found)
8061 findParent : function(simpleSelector, maxDepth, returnEl){
8062 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
8063 maxDepth = maxDepth || 50;
8064 if(typeof maxDepth != "number"){
8065 stopEl = Roo.getDom(maxDepth);
8068 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
8069 if(dq.is(p, simpleSelector)){
8070 return returnEl ? Roo.get(p) : p;
8080 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
8081 * @param {String} selector The simple selector to test
8082 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8083 search as a number or element (defaults to 10 || document.body)
8084 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8085 * @return {HTMLElement} The matching DOM node (or null if no match was found)
8087 findParentNode : function(simpleSelector, maxDepth, returnEl){
8088 var p = Roo.fly(this.dom.parentNode, '_internal');
8089 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
8093 * Looks at the scrollable parent element
8095 findScrollableParent : function()
8097 var overflowRegex = /(auto|scroll)/;
8099 if(this.getStyle('position') === 'fixed'){
8100 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8103 var excludeStaticParent = this.getStyle('position') === "absolute";
8105 for (var parent = this; (parent = Roo.get(parent.dom.parentNode));){
8107 if (excludeStaticParent && parent.getStyle('position') === "static") {
8111 if (overflowRegex.test(parent.getStyle('overflow') + parent.getStyle('overflow-x') + parent.getStyle('overflow-y'))){
8115 if(parent.dom.nodeName.toLowerCase() == 'body'){
8116 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8120 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8124 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
8125 * This is a shortcut for findParentNode() that always returns an Roo.Element.
8126 * @param {String} selector The simple selector to test
8127 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8128 search as a number or element (defaults to 10 || document.body)
8129 * @return {Roo.Element} The matching DOM node (or null if no match was found)
8131 up : function(simpleSelector, maxDepth){
8132 return this.findParentNode(simpleSelector, maxDepth, true);
8138 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
8139 * @param {String} selector The simple selector to test
8140 * @return {Boolean} True if this element matches the selector, else false
8142 is : function(simpleSelector){
8143 return Roo.DomQuery.is(this.dom, simpleSelector);
8147 * Perform animation on this element.
8148 * @param {Object} args The YUI animation control args
8149 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
8150 * @param {Function} onComplete (optional) Function to call when animation completes
8151 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
8152 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
8153 * @return {Roo.Element} this
8155 animate : function(args, duration, onComplete, easing, animType){
8156 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
8161 * @private Internal animation call
8163 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
8164 animType = animType || 'run';
8166 var anim = Roo.lib.Anim[animType](
8168 (opt.duration || defaultDur) || .35,
8169 (opt.easing || defaultEase) || 'easeOut',
8171 Roo.callback(cb, this);
8172 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
8180 // private legacy anim prep
8181 preanim : function(a, i){
8182 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
8186 * Removes worthless text nodes
8187 * @param {Boolean} forceReclean (optional) By default the element
8188 * keeps track if it has been cleaned already so
8189 * you can call this over and over. However, if you update the element and
8190 * need to force a reclean, you can pass true.
8192 clean : function(forceReclean){
8193 if(this.isCleaned && forceReclean !== true){
8197 var d = this.dom, n = d.firstChild, ni = -1;
8199 var nx = n.nextSibling;
8200 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
8207 this.isCleaned = true;
8212 calcOffsetsTo : function(el){
8215 var restorePos = false;
8216 if(el.getStyle('position') == 'static'){
8217 el.position('relative');
8222 while(op && op != d && op.tagName != 'HTML'){
8225 op = op.offsetParent;
8228 el.position('static');
8234 * Scrolls this element into view within the passed container.
8235 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
8236 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
8237 * @return {Roo.Element} this
8239 scrollIntoView : function(container, hscroll){
8240 var c = Roo.getDom(container) || document.body;
8243 var o = this.calcOffsetsTo(c),
8246 b = t+el.offsetHeight,
8247 r = l+el.offsetWidth;
8249 var ch = c.clientHeight;
8250 var ct = parseInt(c.scrollTop, 10);
8251 var cl = parseInt(c.scrollLeft, 10);
8253 var cr = cl + c.clientWidth;
8261 if(hscroll !== false){
8265 c.scrollLeft = r-c.clientWidth;
8272 scrollChildIntoView : function(child, hscroll){
8273 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
8277 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
8278 * the new height may not be available immediately.
8279 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
8280 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
8281 * @param {Function} onComplete (optional) Function to call when animation completes
8282 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
8283 * @return {Roo.Element} this
8285 autoHeight : function(animate, duration, onComplete, easing){
8286 var oldHeight = this.getHeight();
8288 this.setHeight(1); // force clipping
8289 setTimeout(function(){
8290 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
8292 this.setHeight(height);
8294 if(typeof onComplete == "function"){
8298 this.setHeight(oldHeight); // restore original height
8299 this.setHeight(height, animate, duration, function(){
8301 if(typeof onComplete == "function") { onComplete(); }
8302 }.createDelegate(this), easing);
8304 }.createDelegate(this), 0);
8309 * Returns true if this element is an ancestor of the passed element
8310 * @param {HTMLElement/String} el The element to check
8311 * @return {Boolean} True if this element is an ancestor of el, else false
8313 contains : function(el){
8314 if(!el){return false;}
8315 return D.isAncestor(this.dom, el.dom ? el.dom : el);
8319 * Checks whether the element is currently visible using both visibility and display properties.
8320 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
8321 * @return {Boolean} True if the element is currently visible, else false
8323 isVisible : function(deep) {
8324 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
8325 if(deep !== true || !vis){
8328 var p = this.dom.parentNode;
8329 while(p && p.tagName.toLowerCase() != "body"){
8330 if(!Roo.fly(p, '_isVisible').isVisible()){
8339 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
8340 * @param {String} selector The CSS selector
8341 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
8342 * @return {CompositeElement/CompositeElementLite} The composite element
8344 select : function(selector, unique){
8345 return El.select(selector, unique, this.dom);
8349 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
8350 * @param {String} selector The CSS selector
8351 * @return {Array} An array of the matched nodes
8353 query : function(selector, unique){
8354 return Roo.DomQuery.select(selector, this.dom);
8358 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
8359 * @param {String} selector The CSS selector
8360 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8361 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8363 child : function(selector, returnDom){
8364 var n = Roo.DomQuery.selectNode(selector, this.dom);
8365 return returnDom ? n : Roo.get(n);
8369 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
8370 * @param {String} selector The CSS selector
8371 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8372 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8374 down : function(selector, returnDom){
8375 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
8376 return returnDom ? n : Roo.get(n);
8380 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
8381 * @param {String} group The group the DD object is member of
8382 * @param {Object} config The DD config object
8383 * @param {Object} overrides An object containing methods to override/implement on the DD object
8384 * @return {Roo.dd.DD} The DD object
8386 initDD : function(group, config, overrides){
8387 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
8388 return Roo.apply(dd, overrides);
8392 * Initializes a {@link Roo.dd.DDProxy} object for this element.
8393 * @param {String} group The group the DDProxy object is member of
8394 * @param {Object} config The DDProxy config object
8395 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
8396 * @return {Roo.dd.DDProxy} The DDProxy object
8398 initDDProxy : function(group, config, overrides){
8399 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
8400 return Roo.apply(dd, overrides);
8404 * Initializes a {@link Roo.dd.DDTarget} object for this element.
8405 * @param {String} group The group the DDTarget object is member of
8406 * @param {Object} config The DDTarget config object
8407 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
8408 * @return {Roo.dd.DDTarget} The DDTarget object
8410 initDDTarget : function(group, config, overrides){
8411 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
8412 return Roo.apply(dd, overrides);
8416 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
8417 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
8418 * @param {Boolean} visible Whether the element is visible
8419 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8420 * @return {Roo.Element} this
8422 setVisible : function(visible, animate){
8424 if(this.visibilityMode == El.DISPLAY){
8425 this.setDisplayed(visible);
8428 this.dom.style.visibility = visible ? "visible" : "hidden";
8431 // closure for composites
8433 var visMode = this.visibilityMode;
8435 this.setOpacity(.01);
8436 this.setVisible(true);
8438 this.anim({opacity: { to: (visible?1:0) }},
8439 this.preanim(arguments, 1),
8440 null, .35, 'easeIn', function(){
8442 if(visMode == El.DISPLAY){
8443 dom.style.display = "none";
8445 dom.style.visibility = "hidden";
8447 Roo.get(dom).setOpacity(1);
8455 * Returns true if display is not "none"
8458 isDisplayed : function() {
8459 return this.getStyle("display") != "none";
8463 * Toggles the element's visibility or display, depending on visibility mode.
8464 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8465 * @return {Roo.Element} this
8467 toggle : function(animate){
8468 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
8473 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
8474 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
8475 * @return {Roo.Element} this
8477 setDisplayed : function(value) {
8478 if(typeof value == "boolean"){
8479 value = value ? this.originalDisplay : "none";
8481 this.setStyle("display", value);
8486 * Tries to focus the element. Any exceptions are caught and ignored.
8487 * @return {Roo.Element} this
8489 focus : function() {
8497 * Tries to blur the element. Any exceptions are caught and ignored.
8498 * @return {Roo.Element} this
8508 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
8509 * @param {String/Array} className The CSS class to add, or an array of classes
8510 * @return {Roo.Element} this
8512 addClass : function(className){
8513 if(className instanceof Array){
8514 for(var i = 0, len = className.length; i < len; i++) {
8515 this.addClass(className[i]);
8518 if(className && !this.hasClass(className)){
8519 if (this.dom instanceof SVGElement) {
8520 this.dom.className.baseVal =this.dom.className.baseVal + " " + className;
8522 this.dom.className = this.dom.className + " " + className;
8530 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
8531 * @param {String/Array} className The CSS class to add, or an array of classes
8532 * @return {Roo.Element} this
8534 radioClass : function(className){
8535 var siblings = this.dom.parentNode.childNodes;
8536 for(var i = 0; i < siblings.length; i++) {
8537 var s = siblings[i];
8538 if(s.nodeType == 1){
8539 Roo.get(s).removeClass(className);
8542 this.addClass(className);
8547 * Removes one or more CSS classes from the element.
8548 * @param {String/Array} className The CSS class to remove, or an array of classes
8549 * @return {Roo.Element} this
8551 removeClass : function(className){
8553 var cn = this.dom instanceof SVGElement ? this.dom.className.baseVal : this.dom.className;
8554 if(!className || !cn){
8557 if(className instanceof Array){
8558 for(var i = 0, len = className.length; i < len; i++) {
8559 this.removeClass(className[i]);
8562 if(this.hasClass(className)){
8563 var re = this.classReCache[className];
8565 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
8566 this.classReCache[className] = re;
8568 if (this.dom instanceof SVGElement) {
8569 this.dom.className.baseVal = cn.replace(re, " ");
8571 this.dom.className = cn.replace(re, " ");
8582 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
8583 * @param {String} className The CSS class to toggle
8584 * @return {Roo.Element} this
8586 toggleClass : function(className){
8587 if(this.hasClass(className)){
8588 this.removeClass(className);
8590 this.addClass(className);
8596 * Checks if the specified CSS class exists on this element's DOM node.
8597 * @param {String} className The CSS class to check for
8598 * @return {Boolean} True if the class exists, else false
8600 hasClass : function(className){
8601 if (this.dom instanceof SVGElement) {
8602 return className && (' '+this.dom.className.baseVal +' ').indexOf(' '+className+' ') != -1;
8604 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
8608 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
8609 * @param {String} oldClassName The CSS class to replace
8610 * @param {String} newClassName The replacement CSS class
8611 * @return {Roo.Element} this
8613 replaceClass : function(oldClassName, newClassName){
8614 this.removeClass(oldClassName);
8615 this.addClass(newClassName);
8620 * Returns an object with properties matching the styles requested.
8621 * For example, el.getStyles('color', 'font-size', 'width') might return
8622 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
8623 * @param {String} style1 A style name
8624 * @param {String} style2 A style name
8625 * @param {String} etc.
8626 * @return {Object} The style object
8628 getStyles : function(){
8629 var a = arguments, len = a.length, r = {};
8630 for(var i = 0; i < len; i++){
8631 r[a[i]] = this.getStyle(a[i]);
8637 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
8638 * @param {String} property The style property whose value is returned.
8639 * @return {String} The current value of the style property for this element.
8641 getStyle : function(){
8642 return view && view.getComputedStyle ?
8644 var el = this.dom, v, cs, camel;
8645 if(prop == 'float'){
8648 if(el.style && (v = el.style[prop])){
8651 if(cs = view.getComputedStyle(el, "")){
8652 if(!(camel = propCache[prop])){
8653 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8660 var el = this.dom, v, cs, camel;
8661 if(prop == 'opacity'){
8662 if(typeof el.style.filter == 'string'){
8663 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
8665 var fv = parseFloat(m[1]);
8667 return fv ? fv / 100 : 0;
8672 }else if(prop == 'float'){
8673 prop = "styleFloat";
8675 if(!(camel = propCache[prop])){
8676 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8678 if(v = el.style[camel]){
8681 if(cs = el.currentStyle){
8689 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
8690 * @param {String/Object} property The style property to be set, or an object of multiple styles.
8691 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
8692 * @return {Roo.Element} this
8694 setStyle : function(prop, value){
8695 if(typeof prop == "string"){
8697 if (prop == 'float') {
8698 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
8703 if(!(camel = propCache[prop])){
8704 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8707 if(camel == 'opacity') {
8708 this.setOpacity(value);
8710 this.dom.style[camel] = value;
8713 for(var style in prop){
8714 if(typeof prop[style] != "function"){
8715 this.setStyle(style, prop[style]);
8723 * More flexible version of {@link #setStyle} for setting style properties.
8724 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
8725 * a function which returns such a specification.
8726 * @return {Roo.Element} this
8728 applyStyles : function(style){
8729 Roo.DomHelper.applyStyles(this.dom, style);
8734 * 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).
8735 * @return {Number} The X position of the element
8738 return D.getX(this.dom);
8742 * 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).
8743 * @return {Number} The Y position of the element
8746 return D.getY(this.dom);
8750 * 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).
8751 * @return {Array} The XY position of the element
8754 return D.getXY(this.dom);
8758 * 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).
8759 * @param {Number} The X position of the element
8760 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8761 * @return {Roo.Element} this
8763 setX : function(x, animate){
8765 D.setX(this.dom, x);
8767 this.setXY([x, this.getY()], this.preanim(arguments, 1));
8773 * 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).
8774 * @param {Number} The Y position of the element
8775 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8776 * @return {Roo.Element} this
8778 setY : function(y, animate){
8780 D.setY(this.dom, y);
8782 this.setXY([this.getX(), y], this.preanim(arguments, 1));
8788 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
8789 * @param {String} left The left CSS property value
8790 * @return {Roo.Element} this
8792 setLeft : function(left){
8793 this.setStyle("left", this.addUnits(left));
8798 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
8799 * @param {String} top The top CSS property value
8800 * @return {Roo.Element} this
8802 setTop : function(top){
8803 this.setStyle("top", this.addUnits(top));
8808 * Sets the element's CSS right style.
8809 * @param {String} right The right CSS property value
8810 * @return {Roo.Element} this
8812 setRight : function(right){
8813 this.setStyle("right", this.addUnits(right));
8818 * Sets the element's CSS bottom style.
8819 * @param {String} bottom The bottom CSS property value
8820 * @return {Roo.Element} this
8822 setBottom : function(bottom){
8823 this.setStyle("bottom", this.addUnits(bottom));
8828 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8829 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8830 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
8831 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8832 * @return {Roo.Element} this
8834 setXY : function(pos, animate){
8836 D.setXY(this.dom, pos);
8838 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
8844 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8845 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8846 * @param {Number} x X value for new position (coordinates are page-based)
8847 * @param {Number} y Y value for new position (coordinates are page-based)
8848 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8849 * @return {Roo.Element} this
8851 setLocation : function(x, y, animate){
8852 this.setXY([x, y], this.preanim(arguments, 2));
8857 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8858 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8859 * @param {Number} x X value for new position (coordinates are page-based)
8860 * @param {Number} y Y value for new position (coordinates are page-based)
8861 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8862 * @return {Roo.Element} this
8864 moveTo : function(x, y, animate){
8865 this.setXY([x, y], this.preanim(arguments, 2));
8870 * Returns the region of the given element.
8871 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
8872 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
8874 getRegion : function(){
8875 return D.getRegion(this.dom);
8879 * Returns the offset height of the element
8880 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
8881 * @return {Number} The element's height
8883 getHeight : function(contentHeight){
8884 var h = this.dom.offsetHeight || 0;
8885 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
8889 * Returns the offset width of the element
8890 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
8891 * @return {Number} The element's width
8893 getWidth : function(contentWidth){
8894 var w = this.dom.offsetWidth || 0;
8895 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
8899 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
8900 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
8901 * if a height has not been set using CSS.
8904 getComputedHeight : function(){
8905 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
8907 h = parseInt(this.getStyle('height'), 10) || 0;
8908 if(!this.isBorderBox()){
8909 h += this.getFrameWidth('tb');
8916 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
8917 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
8918 * if a width has not been set using CSS.
8921 getComputedWidth : function(){
8922 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
8924 w = parseInt(this.getStyle('width'), 10) || 0;
8925 if(!this.isBorderBox()){
8926 w += this.getFrameWidth('lr');
8933 * Returns the size of the element.
8934 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
8935 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
8937 getSize : function(contentSize){
8938 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
8942 * Returns the width and height of the viewport.
8943 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
8945 getViewSize : function(){
8946 var d = this.dom, doc = document, aw = 0, ah = 0;
8947 if(d == doc || d == doc.body){
8948 return {width : D.getViewWidth(), height: D.getViewHeight()};
8951 width : d.clientWidth,
8952 height: d.clientHeight
8958 * Returns the value of the "value" attribute
8959 * @param {Boolean} asNumber true to parse the value as a number
8960 * @return {String/Number}
8962 getValue : function(asNumber){
8963 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
8967 adjustWidth : function(width){
8968 if(typeof width == "number"){
8969 if(this.autoBoxAdjust && !this.isBorderBox()){
8970 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
8980 adjustHeight : function(height){
8981 if(typeof height == "number"){
8982 if(this.autoBoxAdjust && !this.isBorderBox()){
8983 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
8993 * Set the width of the element
8994 * @param {Number} width The new width
8995 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8996 * @return {Roo.Element} this
8998 setWidth : function(width, animate){
8999 width = this.adjustWidth(width);
9001 this.dom.style.width = this.addUnits(width);
9003 this.anim({width: {to: width}}, this.preanim(arguments, 1));
9009 * Set the height of the element
9010 * @param {Number} height The new height
9011 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9012 * @return {Roo.Element} this
9014 setHeight : function(height, animate){
9015 height = this.adjustHeight(height);
9017 this.dom.style.height = this.addUnits(height);
9019 this.anim({height: {to: height}}, this.preanim(arguments, 1));
9025 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
9026 * @param {Number} width The new width
9027 * @param {Number} height The new height
9028 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9029 * @return {Roo.Element} this
9031 setSize : function(width, height, animate){
9032 if(typeof width == "object"){ // in case of object from getSize()
9033 height = width.height; width = width.width;
9035 width = this.adjustWidth(width); height = this.adjustHeight(height);
9037 this.dom.style.width = this.addUnits(width);
9038 this.dom.style.height = this.addUnits(height);
9040 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
9046 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
9047 * @param {Number} x X value for new position (coordinates are page-based)
9048 * @param {Number} y Y value for new position (coordinates are page-based)
9049 * @param {Number} width The new width
9050 * @param {Number} height The new height
9051 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9052 * @return {Roo.Element} this
9054 setBounds : function(x, y, width, height, animate){
9056 this.setSize(width, height);
9057 this.setLocation(x, y);
9059 width = this.adjustWidth(width); height = this.adjustHeight(height);
9060 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
9061 this.preanim(arguments, 4), 'motion');
9067 * 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.
9068 * @param {Roo.lib.Region} region The region to fill
9069 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9070 * @return {Roo.Element} this
9072 setRegion : function(region, animate){
9073 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
9078 * Appends an event handler
9080 * @param {String} eventName The type of event to append
9081 * @param {Function} fn The method the event invokes
9082 * @param {Object} scope (optional) The scope (this object) of the fn
9083 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
9085 addListener : function(eventName, fn, scope, options)
9087 if (eventName == 'dblclick') { // doublclick (touchstart) - faked on touch.
9088 this.addListener('touchstart', this.onTapHandler, this);
9091 // we need to handle a special case where dom element is a svg element.
9092 // in this case we do not actua
9097 if (this.dom instanceof SVGElement && !(this.dom instanceof SVGSVGElement)) {
9098 if (typeof(this.listeners[eventName]) == 'undefined') {
9099 this.listeners[eventName] = new Roo.util.Event(this, eventName);
9101 this.listeners[eventName].addListener(fn, scope, options);
9106 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
9111 onTapHandler : function(event)
9113 if(!this.tapedTwice) {
9114 this.tapedTwice = true;
9116 setTimeout( function() {
9117 s.tapedTwice = false;
9121 event.preventDefault();
9122 var revent = new MouseEvent('dblclick', {
9128 this.dom.dispatchEvent(revent);
9129 //action on double tap goes below
9134 * Removes an event handler from this element
9135 * @param {String} eventName the type of event to remove
9136 * @param {Function} fn the method the event invokes
9137 * @param {Function} scope (needed for svg fake listeners)
9138 * @return {Roo.Element} this
9140 removeListener : function(eventName, fn, scope){
9141 Roo.EventManager.removeListener(this.dom, eventName, fn);
9142 if (typeof(this.listeners) == 'undefined' || typeof(this.listeners[eventName]) == 'undefined') {
9145 this.listeners[eventName].removeListener(fn, scope);
9150 * Removes all previous added listeners from this element
9151 * @return {Roo.Element} this
9153 removeAllListeners : function(){
9154 E.purgeElement(this.dom);
9155 this.listeners = {};
9159 relayEvent : function(eventName, observable){
9160 this.on(eventName, function(e){
9161 observable.fireEvent(eventName, e);
9167 * Set the opacity of the element
9168 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
9169 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9170 * @return {Roo.Element} this
9172 setOpacity : function(opacity, animate){
9174 var s = this.dom.style;
9177 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
9178 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
9180 s.opacity = opacity;
9183 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
9189 * Gets the left X coordinate
9190 * @param {Boolean} local True to get the local css position instead of page coordinate
9193 getLeft : function(local){
9197 return parseInt(this.getStyle("left"), 10) || 0;
9202 * Gets the right X coordinate of the element (element X position + element width)
9203 * @param {Boolean} local True to get the local css position instead of page coordinate
9206 getRight : function(local){
9208 return this.getX() + this.getWidth();
9210 return (this.getLeft(true) + this.getWidth()) || 0;
9215 * Gets the top Y coordinate
9216 * @param {Boolean} local True to get the local css position instead of page coordinate
9219 getTop : function(local) {
9223 return parseInt(this.getStyle("top"), 10) || 0;
9228 * Gets the bottom Y coordinate of the element (element Y position + element height)
9229 * @param {Boolean} local True to get the local css position instead of page coordinate
9232 getBottom : function(local){
9234 return this.getY() + this.getHeight();
9236 return (this.getTop(true) + this.getHeight()) || 0;
9241 * Initializes positioning on this element. If a desired position is not passed, it will make the
9242 * the element positioned relative IF it is not already positioned.
9243 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
9244 * @param {Number} zIndex (optional) The zIndex to apply
9245 * @param {Number} x (optional) Set the page X position
9246 * @param {Number} y (optional) Set the page Y position
9248 position : function(pos, zIndex, x, y){
9250 if(this.getStyle('position') == 'static'){
9251 this.setStyle('position', 'relative');
9254 this.setStyle("position", pos);
9257 this.setStyle("z-index", zIndex);
9259 if(x !== undefined && y !== undefined){
9261 }else if(x !== undefined){
9263 }else if(y !== undefined){
9269 * Clear positioning back to the default when the document was loaded
9270 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
9271 * @return {Roo.Element} this
9273 clearPositioning : function(value){
9281 "position" : "static"
9287 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
9288 * snapshot before performing an update and then restoring the element.
9291 getPositioning : function(){
9292 var l = this.getStyle("left");
9293 var t = this.getStyle("top");
9295 "position" : this.getStyle("position"),
9297 "right" : l ? "" : this.getStyle("right"),
9299 "bottom" : t ? "" : this.getStyle("bottom"),
9300 "z-index" : this.getStyle("z-index")
9305 * Gets the width of the border(s) for the specified side(s)
9306 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9307 * passing lr would get the border (l)eft width + the border (r)ight width.
9308 * @return {Number} The width of the sides passed added together
9310 getBorderWidth : function(side){
9311 return this.addStyles(side, El.borders);
9315 * Gets the width of the padding(s) for the specified side(s)
9316 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9317 * passing lr would get the padding (l)eft + the padding (r)ight.
9318 * @return {Number} The padding of the sides passed added together
9320 getPadding : function(side){
9321 return this.addStyles(side, El.paddings);
9325 * Set positioning with an object returned by getPositioning().
9326 * @param {Object} posCfg
9327 * @return {Roo.Element} this
9329 setPositioning : function(pc){
9330 this.applyStyles(pc);
9331 if(pc.right == "auto"){
9332 this.dom.style.right = "";
9334 if(pc.bottom == "auto"){
9335 this.dom.style.bottom = "";
9341 fixDisplay : function(){
9342 if(this.getStyle("display") == "none"){
9343 this.setStyle("visibility", "hidden");
9344 this.setStyle("display", this.originalDisplay); // first try reverting to default
9345 if(this.getStyle("display") == "none"){ // if that fails, default to block
9346 this.setStyle("display", "block");
9352 * Quick set left and top adding default units
9353 * @param {String} left The left CSS property value
9354 * @param {String} top The top CSS property value
9355 * @return {Roo.Element} this
9357 setLeftTop : function(left, top){
9358 this.dom.style.left = this.addUnits(left);
9359 this.dom.style.top = this.addUnits(top);
9364 * Move this element relative to its current position.
9365 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9366 * @param {Number} distance How far to move the element in pixels
9367 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9368 * @return {Roo.Element} this
9370 move : function(direction, distance, animate){
9371 var xy = this.getXY();
9372 direction = direction.toLowerCase();
9376 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
9380 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
9385 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
9390 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
9397 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
9398 * @return {Roo.Element} this
9401 if(!this.isClipped){
9402 this.isClipped = true;
9403 this.originalClip = {
9404 "o": this.getStyle("overflow"),
9405 "x": this.getStyle("overflow-x"),
9406 "y": this.getStyle("overflow-y")
9408 this.setStyle("overflow", "hidden");
9409 this.setStyle("overflow-x", "hidden");
9410 this.setStyle("overflow-y", "hidden");
9416 * Return clipping (overflow) to original clipping before clip() was called
9417 * @return {Roo.Element} this
9419 unclip : function(){
9421 this.isClipped = false;
9422 var o = this.originalClip;
9423 if(o.o){this.setStyle("overflow", o.o);}
9424 if(o.x){this.setStyle("overflow-x", o.x);}
9425 if(o.y){this.setStyle("overflow-y", o.y);}
9432 * Gets the x,y coordinates specified by the anchor position on the element.
9433 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
9434 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
9435 * {width: (target width), height: (target height)} (defaults to the element's current size)
9436 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
9437 * @return {Array} [x, y] An array containing the element's x and y coordinates
9439 getAnchorXY : function(anchor, local, s){
9440 //Passing a different size is useful for pre-calculating anchors,
9441 //especially for anchored animations that change the el size.
9443 var w, h, vp = false;
9446 if(d == document.body || d == document){
9448 w = D.getViewWidth(); h = D.getViewHeight();
9450 w = this.getWidth(); h = this.getHeight();
9453 w = s.width; h = s.height;
9455 var x = 0, y = 0, r = Math.round;
9456 switch((anchor || "tl").toLowerCase()){
9498 var sc = this.getScroll();
9499 return [x + sc.left, y + sc.top];
9501 //Add the element's offset xy
9502 var o = this.getXY();
9503 return [x+o[0], y+o[1]];
9507 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
9508 * supported position values.
9509 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9510 * @param {String} position The position to align to.
9511 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9512 * @return {Array} [x, y]
9514 getAlignToXY : function(el, p, o)
9519 throw "Element.alignTo with an element that doesn't exist";
9521 var c = false; //constrain to viewport
9522 var p1 = "", p2 = "";
9529 }else if(p.indexOf("-") == -1){
9532 p = p.toLowerCase();
9533 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
9535 throw "Element.alignTo with an invalid alignment " + p;
9537 p1 = m[1]; p2 = m[2]; c = !!m[3];
9539 //Subtract the aligned el's internal xy from the target's offset xy
9540 //plus custom offset to get the aligned el's new offset xy
9541 var a1 = this.getAnchorXY(p1, true);
9542 var a2 = el.getAnchorXY(p2, false);
9543 var x = a2[0] - a1[0] + o[0];
9544 var y = a2[1] - a1[1] + o[1];
9546 //constrain the aligned el to viewport if necessary
9547 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
9548 // 5px of margin for ie
9549 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
9551 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
9552 //perpendicular to the vp border, allow the aligned el to slide on that border,
9553 //otherwise swap the aligned el to the opposite border of the target.
9554 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
9555 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
9556 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t") );
9557 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
9560 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
9561 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
9563 if((x+w) > dw + scrollX){
9564 x = swapX ? r.left-w : dw+scrollX-w;
9567 x = swapX ? r.right : scrollX;
9569 if((y+h) > dh + scrollY){
9570 y = swapY ? r.top-h : dh+scrollY-h;
9573 y = swapY ? r.bottom : scrollY;
9580 getConstrainToXY : function(){
9581 var os = {top:0, left:0, bottom:0, right: 0};
9583 return function(el, local, offsets, proposedXY){
9585 offsets = offsets ? Roo.applyIf(offsets, os) : os;
9587 var vw, vh, vx = 0, vy = 0;
9588 if(el.dom == document.body || el.dom == document){
9589 vw = Roo.lib.Dom.getViewWidth();
9590 vh = Roo.lib.Dom.getViewHeight();
9592 vw = el.dom.clientWidth;
9593 vh = el.dom.clientHeight;
9595 var vxy = el.getXY();
9601 var s = el.getScroll();
9603 vx += offsets.left + s.left;
9604 vy += offsets.top + s.top;
9606 vw -= offsets.right;
9607 vh -= offsets.bottom;
9612 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
9613 var x = xy[0], y = xy[1];
9614 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
9616 // only move it if it needs it
9619 // first validate right/bottom
9628 // then make sure top/left isn't negative
9637 return moved ? [x, y] : false;
9642 adjustForConstraints : function(xy, parent, offsets){
9643 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
9647 * Aligns this element with another element relative to the specified anchor points. If the other element is the
9648 * document it aligns it to the viewport.
9649 * The position parameter is optional, and can be specified in any one of the following formats:
9651 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
9652 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
9653 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
9654 * deprecated in favor of the newer two anchor syntax below</i>.</li>
9655 * <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
9656 * element's anchor point, and the second value is used as the target's anchor point.</li>
9658 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
9659 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
9660 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
9661 * that specified in order to enforce the viewport constraints.
9662 * Following are all of the supported anchor positions:
9665 ----- -----------------------------
9666 tl The top left corner (default)
9667 t The center of the top edge
9668 tr The top right corner
9669 l The center of the left edge
9670 c In the center of the element
9671 r The center of the right edge
9672 bl The bottom left corner
9673 b The center of the bottom edge
9674 br The bottom right corner
9678 // align el to other-el using the default positioning ("tl-bl", non-constrained)
9679 el.alignTo("other-el");
9681 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
9682 el.alignTo("other-el", "tr?");
9684 // align the bottom right corner of el with the center left edge of other-el
9685 el.alignTo("other-el", "br-l?");
9687 // align the center of el with the bottom left corner of other-el and
9688 // adjust the x position by -6 pixels (and the y position by 0)
9689 el.alignTo("other-el", "c-bl", [-6, 0]);
9691 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9692 * @param {String} position The position to align to.
9693 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9694 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9695 * @return {Roo.Element} this
9697 alignTo : function(element, position, offsets, animate){
9698 var xy = this.getAlignToXY(element, position, offsets);
9699 this.setXY(xy, this.preanim(arguments, 3));
9704 * Anchors an element to another element and realigns it when the window is resized.
9705 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9706 * @param {String} position The position to align to.
9707 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9708 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
9709 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
9710 * is a number, it is used as the buffer delay (defaults to 50ms).
9711 * @param {Function} callback The function to call after the animation finishes
9712 * @return {Roo.Element} this
9714 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
9715 var action = function(){
9716 this.alignTo(el, alignment, offsets, animate);
9717 Roo.callback(callback, this);
9719 Roo.EventManager.onWindowResize(action, this);
9720 var tm = typeof monitorScroll;
9721 if(tm != 'undefined'){
9722 Roo.EventManager.on(window, 'scroll', action, this,
9723 {buffer: tm == 'number' ? monitorScroll : 50});
9725 action.call(this); // align immediately
9729 * Clears any opacity settings from this element. Required in some cases for IE.
9730 * @return {Roo.Element} this
9732 clearOpacity : function(){
9733 if (window.ActiveXObject) {
9734 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
9735 this.dom.style.filter = "";
9738 this.dom.style.opacity = "";
9739 this.dom.style["-moz-opacity"] = "";
9740 this.dom.style["-khtml-opacity"] = "";
9746 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
9747 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9748 * @return {Roo.Element} this
9750 hide : function(animate){
9751 this.setVisible(false, this.preanim(arguments, 0));
9756 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
9757 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9758 * @return {Roo.Element} this
9760 show : function(animate){
9761 this.setVisible(true, this.preanim(arguments, 0));
9766 * @private Test if size has a unit, otherwise appends the default
9768 addUnits : function(size){
9769 return Roo.Element.addUnits(size, this.defaultUnit);
9773 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
9774 * @return {Roo.Element} this
9776 beginMeasure : function(){
9778 if(el.offsetWidth || el.offsetHeight){
9779 return this; // offsets work already
9782 var p = this.dom, b = document.body; // start with this element
9783 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
9784 var pe = Roo.get(p);
9785 if(pe.getStyle('display') == 'none'){
9786 changed.push({el: p, visibility: pe.getStyle("visibility")});
9787 p.style.visibility = "hidden";
9788 p.style.display = "block";
9792 this._measureChanged = changed;
9798 * Restores displays to before beginMeasure was called
9799 * @return {Roo.Element} this
9801 endMeasure : function(){
9802 var changed = this._measureChanged;
9804 for(var i = 0, len = changed.length; i < len; i++) {
9806 r.el.style.visibility = r.visibility;
9807 r.el.style.display = "none";
9809 this._measureChanged = null;
9815 * Update the innerHTML of this element, optionally searching for and processing scripts
9816 * @param {String} html The new HTML
9817 * @param {Boolean} loadScripts (optional) true to look for and process scripts
9818 * @param {Function} callback For async script loading you can be noticed when the update completes
9819 * @return {Roo.Element} this
9821 update : function(html, loadScripts, callback){
9822 if(typeof html == "undefined"){
9825 if(loadScripts !== true){
9826 this.dom.innerHTML = html;
9827 if(typeof callback == "function"){
9835 html += '<span id="' + id + '"></span>';
9837 E.onAvailable(id, function(){
9838 var hd = document.getElementsByTagName("head")[0];
9839 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
9840 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
9841 var typeRe = /\stype=([\'\"])(.*?)\1/i;
9844 while(match = re.exec(html)){
9845 var attrs = match[1];
9846 var srcMatch = attrs ? attrs.match(srcRe) : false;
9847 if(srcMatch && srcMatch[2]){
9848 var s = document.createElement("script");
9849 s.src = srcMatch[2];
9850 var typeMatch = attrs.match(typeRe);
9851 if(typeMatch && typeMatch[2]){
9852 s.type = typeMatch[2];
9855 }else if(match[2] && match[2].length > 0){
9856 if(window.execScript) {
9857 window.execScript(match[2]);
9865 window.eval(match[2]);
9869 var el = document.getElementById(id);
9870 if(el){el.parentNode.removeChild(el);}
9871 if(typeof callback == "function"){
9875 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
9880 * Direct access to the UpdateManager update() method (takes the same parameters).
9881 * @param {String/Function} url The url for this request or a function to call to get the url
9882 * @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}
9883 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
9884 * @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.
9885 * @return {Roo.Element} this
9888 var um = this.getUpdateManager();
9889 um.update.apply(um, arguments);
9894 * Gets this element's UpdateManager
9895 * @return {Roo.UpdateManager} The UpdateManager
9897 getUpdateManager : function(){
9898 if(!this.updateManager){
9899 this.updateManager = new Roo.UpdateManager(this);
9901 return this.updateManager;
9905 * Disables text selection for this element (normalized across browsers)
9906 * @return {Roo.Element} this
9908 unselectable : function(){
9909 this.dom.unselectable = "on";
9910 this.swallowEvent("selectstart", true);
9911 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
9912 this.addClass("x-unselectable");
9917 * Calculates the x, y to center this element on the screen
9918 * @return {Array} The x, y values [x, y]
9920 getCenterXY : function(){
9921 return this.getAlignToXY(document, 'c-c');
9925 * Centers the Element in either the viewport, or another Element.
9926 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
9928 center : function(centerIn){
9929 this.alignTo(centerIn || document, 'c-c');
9934 * Tests various css rules/browsers to determine if this element uses a border box
9937 isBorderBox : function(){
9938 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
9942 * Return a box {x, y, width, height} that can be used to set another elements
9943 * size/location to match this element.
9944 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
9945 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
9946 * @return {Object} box An object in the format {x, y, width, height}
9948 getBox : function(contentBox, local){
9953 var left = parseInt(this.getStyle("left"), 10) || 0;
9954 var top = parseInt(this.getStyle("top"), 10) || 0;
9957 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
9959 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
9961 var l = this.getBorderWidth("l")+this.getPadding("l");
9962 var r = this.getBorderWidth("r")+this.getPadding("r");
9963 var t = this.getBorderWidth("t")+this.getPadding("t");
9964 var b = this.getBorderWidth("b")+this.getPadding("b");
9965 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)};
9967 bx.right = bx.x + bx.width;
9968 bx.bottom = bx.y + bx.height;
9973 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
9974 for more information about the sides.
9975 * @param {String} sides
9978 getFrameWidth : function(sides, onlyContentBox){
9979 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
9983 * 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.
9984 * @param {Object} box The box to fill {x, y, width, height}
9985 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
9986 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9987 * @return {Roo.Element} this
9989 setBox : function(box, adjust, animate){
9990 var w = box.width, h = box.height;
9991 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
9992 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
9993 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
9995 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
10000 * Forces the browser to repaint this element
10001 * @return {Roo.Element} this
10003 repaint : function(){
10004 var dom = this.dom;
10005 this.addClass("x-repaint");
10006 setTimeout(function(){
10007 Roo.get(dom).removeClass("x-repaint");
10013 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
10014 * then it returns the calculated width of the sides (see getPadding)
10015 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
10016 * @return {Object/Number}
10018 getMargins : function(side){
10021 top: parseInt(this.getStyle("margin-top"), 10) || 0,
10022 left: parseInt(this.getStyle("margin-left"), 10) || 0,
10023 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
10024 right: parseInt(this.getStyle("margin-right"), 10) || 0
10027 return this.addStyles(side, El.margins);
10032 addStyles : function(sides, styles){
10034 for(var i = 0, len = sides.length; i < len; i++){
10035 v = this.getStyle(styles[sides.charAt(i)]);
10037 w = parseInt(v, 10);
10045 * Creates a proxy element of this element
10046 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
10047 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
10048 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
10049 * @return {Roo.Element} The new proxy element
10051 createProxy : function(config, renderTo, matchBox){
10053 renderTo = Roo.getDom(renderTo);
10055 renderTo = document.body;
10057 config = typeof config == "object" ?
10058 config : {tag : "div", cls: config};
10059 var proxy = Roo.DomHelper.append(renderTo, config, true);
10061 proxy.setBox(this.getBox());
10067 * Puts a mask over this element to disable user interaction. Requires core.css.
10068 * This method can only be applied to elements which accept child nodes.
10069 * @param {String} msg (optional) A message to display in the mask
10070 * @param {String} msgCls (optional) A css class to apply to the msg element - use no-spinner to hide the spinner on bootstrap
10071 * @return {Element} The mask element
10073 mask : function(msg, msgCls)
10075 if(this.getStyle("position") == "static" && this.dom.tagName !== 'BODY'){
10076 this.setStyle("position", "relative");
10079 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
10082 this.addClass("x-masked");
10083 this._mask.setDisplayed(true);
10087 var dom = this.dom;
10088 while (dom && dom.style) {
10089 if (!isNaN(parseInt(dom.style.zIndex))) {
10090 z = Math.max(z, parseInt(dom.style.zIndex));
10092 dom = dom.parentNode;
10094 // if we are masking the body - then it hides everything..
10095 if (this.dom == document.body) {
10097 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
10098 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
10101 if(typeof msg == 'string'){
10102 if(!this._maskMsg){
10103 this._maskMsg = Roo.DomHelper.append(this.dom, {
10104 cls: "roo-el-mask-msg",
10108 cls: 'fa fa-spinner fa-spin'
10116 var mm = this._maskMsg;
10117 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
10118 if (mm.dom.lastChild) { // weird IE issue?
10119 mm.dom.lastChild.innerHTML = msg;
10121 mm.setDisplayed(true);
10123 mm.setStyle('z-index', z + 102);
10125 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
10126 this._mask.setHeight(this.getHeight());
10128 this._mask.setStyle('z-index', z + 100);
10134 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
10135 * it is cached for reuse.
10137 unmask : function(removeEl){
10139 if(removeEl === true){
10140 this._mask.remove();
10143 this._maskMsg.remove();
10144 delete this._maskMsg;
10147 this._mask.setDisplayed(false);
10149 this._maskMsg.setDisplayed(false);
10153 this.removeClass("x-masked");
10157 * Returns true if this element is masked
10158 * @return {Boolean}
10160 isMasked : function(){
10161 return this._mask && this._mask.isVisible();
10165 * Creates an iframe shim for this element to keep selects and other windowed objects from
10167 * @return {Roo.Element} The new shim element
10169 createShim : function(){
10170 var el = document.createElement('iframe');
10171 el.frameBorder = 'no';
10172 el.className = 'roo-shim';
10173 if(Roo.isIE && Roo.isSecure){
10174 el.src = Roo.SSL_SECURE_URL;
10176 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
10177 shim.autoBoxAdjust = false;
10182 * Removes this element from the DOM and deletes it from the cache
10184 remove : function(){
10185 if(this.dom.parentNode){
10186 this.dom.parentNode.removeChild(this.dom);
10188 delete El.cache[this.dom.id];
10192 * Sets up event handlers to add and remove a css class when the mouse is over this element
10193 * @param {String} className
10194 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
10195 * mouseout events for children elements
10196 * @return {Roo.Element} this
10198 addClassOnOver : function(className, preventFlicker){
10199 this.on("mouseover", function(){
10200 Roo.fly(this, '_internal').addClass(className);
10202 var removeFn = function(e){
10203 if(preventFlicker !== true || !e.within(this, true)){
10204 Roo.fly(this, '_internal').removeClass(className);
10207 this.on("mouseout", removeFn, this.dom);
10212 * Sets up event handlers to add and remove a css class when this element has the focus
10213 * @param {String} className
10214 * @return {Roo.Element} this
10216 addClassOnFocus : function(className){
10217 this.on("focus", function(){
10218 Roo.fly(this, '_internal').addClass(className);
10220 this.on("blur", function(){
10221 Roo.fly(this, '_internal').removeClass(className);
10226 * 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)
10227 * @param {String} className
10228 * @return {Roo.Element} this
10230 addClassOnClick : function(className){
10231 var dom = this.dom;
10232 this.on("mousedown", function(){
10233 Roo.fly(dom, '_internal').addClass(className);
10234 var d = Roo.get(document);
10235 var fn = function(){
10236 Roo.fly(dom, '_internal').removeClass(className);
10237 d.removeListener("mouseup", fn);
10239 d.on("mouseup", fn);
10245 * Stops the specified event from bubbling and optionally prevents the default action
10246 * @param {String} eventName
10247 * @param {Boolean} preventDefault (optional) true to prevent the default action too
10248 * @return {Roo.Element} this
10250 swallowEvent : function(eventName, preventDefault){
10251 var fn = function(e){
10252 e.stopPropagation();
10253 if(preventDefault){
10254 e.preventDefault();
10257 if(eventName instanceof Array){
10258 for(var i = 0, len = eventName.length; i < len; i++){
10259 this.on(eventName[i], fn);
10263 this.on(eventName, fn);
10270 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
10273 * Sizes this element to its parent element's dimensions performing
10274 * neccessary box adjustments.
10275 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
10276 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
10277 * @return {Roo.Element} this
10279 fitToParent : function(monitorResize, targetParent) {
10280 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
10281 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
10282 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
10285 var p = Roo.get(targetParent || this.dom.parentNode);
10286 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
10287 if (monitorResize === true) {
10288 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
10289 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
10295 * Gets the next sibling, skipping text nodes
10296 * @return {HTMLElement} The next sibling or null
10298 getNextSibling : function(){
10299 var n = this.dom.nextSibling;
10300 while(n && n.nodeType != 1){
10307 * Gets the previous sibling, skipping text nodes
10308 * @return {HTMLElement} The previous sibling or null
10310 getPrevSibling : function(){
10311 var n = this.dom.previousSibling;
10312 while(n && n.nodeType != 1){
10313 n = n.previousSibling;
10320 * Appends the passed element(s) to this element
10321 * @param {String/HTMLElement/Array/Element/CompositeElement} el
10322 * @return {Roo.Element} this
10324 appendChild: function(el){
10331 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
10332 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
10333 * automatically generated with the specified attributes.
10334 * @param {HTMLElement} insertBefore (optional) a child element of this element
10335 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
10336 * @return {Roo.Element} The new child element
10338 createChild: function(config, insertBefore, returnDom){
10339 config = config || {tag:'div'};
10341 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
10343 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
10347 * Appends this element to the passed element
10348 * @param {String/HTMLElement/Element} el The new parent element
10349 * @return {Roo.Element} this
10351 appendTo: function(el){
10352 el = Roo.getDom(el);
10353 el.appendChild(this.dom);
10358 * Inserts this element before the passed element in the DOM
10359 * @param {String/HTMLElement/Element} el The element to insert before
10360 * @return {Roo.Element} this
10362 insertBefore: function(el){
10363 el = Roo.getDom(el);
10364 el.parentNode.insertBefore(this.dom, el);
10369 * Inserts this element after the passed element in the DOM
10370 * @param {String/HTMLElement/Element} el The element to insert after
10371 * @return {Roo.Element} this
10373 insertAfter: function(el){
10374 el = Roo.getDom(el);
10375 el.parentNode.insertBefore(this.dom, el.nextSibling);
10380 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
10381 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10382 * @return {Roo.Element} The new child
10384 insertFirst: function(el, returnDom){
10386 if(typeof el == 'object' && !el.nodeType){ // dh config
10387 return this.createChild(el, this.dom.firstChild, returnDom);
10389 el = Roo.getDom(el);
10390 this.dom.insertBefore(el, this.dom.firstChild);
10391 return !returnDom ? Roo.get(el) : el;
10396 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
10397 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10398 * @param {String} where (optional) 'before' or 'after' defaults to before
10399 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10400 * @return {Roo.Element} the inserted Element
10402 insertSibling: function(el, where, returnDom){
10403 where = where ? where.toLowerCase() : 'before';
10405 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
10407 if(typeof el == 'object' && !el.nodeType){ // dh config
10408 if(where == 'after' && !this.dom.nextSibling){
10409 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
10411 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
10415 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
10416 where == 'before' ? this.dom : this.dom.nextSibling);
10425 * Creates and wraps this element with another element
10426 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
10427 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10428 * @return {HTMLElement/Element} The newly created wrapper element
10430 wrap: function(config, returnDom){
10432 config = {tag: "div"};
10434 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
10435 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
10440 * Replaces the passed element with this element
10441 * @param {String/HTMLElement/Element} el The element to replace
10442 * @return {Roo.Element} this
10444 replace: function(el){
10446 this.insertBefore(el);
10452 * Inserts an html fragment into this element
10453 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
10454 * @param {String} html The HTML fragment
10455 * @param {Boolean} returnEl True to return an Roo.Element
10456 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
10458 insertHtml : function(where, html, returnEl){
10459 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
10460 return returnEl ? Roo.get(el) : el;
10464 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
10465 * @param {Object} o The object with the attributes
10466 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
10467 * @return {Roo.Element} this
10469 set : function(o, useSet){
10471 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
10472 for(var attr in o){
10473 if(attr == "style" || typeof o[attr] == "function") { continue; }
10475 el.className = o["cls"];
10478 el.setAttribute(attr, o[attr]);
10480 el[attr] = o[attr];
10485 Roo.DomHelper.applyStyles(el, o.style);
10491 * Convenience method for constructing a KeyMap
10492 * @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:
10493 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
10494 * @param {Function} fn The function to call
10495 * @param {Object} scope (optional) The scope of the function
10496 * @return {Roo.KeyMap} The KeyMap created
10498 addKeyListener : function(key, fn, scope){
10500 if(typeof key != "object" || key instanceof Array){
10516 return new Roo.KeyMap(this, config);
10520 * Creates a KeyMap for this element
10521 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
10522 * @return {Roo.KeyMap} The KeyMap created
10524 addKeyMap : function(config){
10525 return new Roo.KeyMap(this, config);
10529 * Returns true if this element is scrollable.
10530 * @return {Boolean}
10532 isScrollable : function(){
10533 var dom = this.dom;
10534 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
10538 * 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().
10539 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
10540 * @param {Number} value The new scroll value
10541 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10542 * @return {Element} this
10545 scrollTo : function(side, value, animate){
10546 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
10547 if(!animate || !A){
10548 this.dom[prop] = value;
10550 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
10551 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
10557 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
10558 * within this element's scrollable range.
10559 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
10560 * @param {Number} distance How far to scroll the element in pixels
10561 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10562 * @return {Boolean} Returns true if a scroll was triggered or false if the element
10563 * was scrolled as far as it could go.
10565 scroll : function(direction, distance, animate){
10566 if(!this.isScrollable()){
10570 var l = el.scrollLeft, t = el.scrollTop;
10571 var w = el.scrollWidth, h = el.scrollHeight;
10572 var cw = el.clientWidth, ch = el.clientHeight;
10573 direction = direction.toLowerCase();
10574 var scrolled = false;
10575 var a = this.preanim(arguments, 2);
10580 var v = Math.min(l + distance, w-cw);
10581 this.scrollTo("left", v, a);
10588 var v = Math.max(l - distance, 0);
10589 this.scrollTo("left", v, a);
10597 var v = Math.max(t - distance, 0);
10598 this.scrollTo("top", v, a);
10606 var v = Math.min(t + distance, h-ch);
10607 this.scrollTo("top", v, a);
10616 * Translates the passed page coordinates into left/top css values for this element
10617 * @param {Number/Array} x The page x or an array containing [x, y]
10618 * @param {Number} y The page y
10619 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
10621 translatePoints : function(x, y){
10622 if(typeof x == 'object' || x instanceof Array){
10623 y = x[1]; x = x[0];
10625 var p = this.getStyle('position');
10626 var o = this.getXY();
10628 var l = parseInt(this.getStyle('left'), 10);
10629 var t = parseInt(this.getStyle('top'), 10);
10632 l = (p == "relative") ? 0 : this.dom.offsetLeft;
10635 t = (p == "relative") ? 0 : this.dom.offsetTop;
10638 return {left: (x - o[0] + l), top: (y - o[1] + t)};
10642 * Returns the current scroll position of the element.
10643 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
10645 getScroll : function(){
10646 var d = this.dom, doc = document;
10647 if(d == doc || d == doc.body){
10648 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
10649 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
10650 return {left: l, top: t};
10652 return {left: d.scrollLeft, top: d.scrollTop};
10657 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
10658 * are convert to standard 6 digit hex color.
10659 * @param {String} attr The css attribute
10660 * @param {String} defaultValue The default value to use when a valid color isn't found
10661 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
10664 getColor : function(attr, defaultValue, prefix){
10665 var v = this.getStyle(attr);
10666 if(!v || v == "transparent" || v == "inherit") {
10667 return defaultValue;
10669 var color = typeof prefix == "undefined" ? "#" : prefix;
10670 if(v.substr(0, 4) == "rgb("){
10671 var rvs = v.slice(4, v.length -1).split(",");
10672 for(var i = 0; i < 3; i++){
10673 var h = parseInt(rvs[i]).toString(16);
10680 if(v.substr(0, 1) == "#"){
10681 if(v.length == 4) {
10682 for(var i = 1; i < 4; i++){
10683 var c = v.charAt(i);
10686 }else if(v.length == 7){
10687 color += v.substr(1);
10691 return(color.length > 5 ? color.toLowerCase() : defaultValue);
10695 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
10696 * gradient background, rounded corners and a 4-way shadow.
10697 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
10698 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
10699 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
10700 * @return {Roo.Element} this
10702 boxWrap : function(cls){
10703 cls = cls || 'x-box';
10704 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
10705 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
10710 * Returns the value of a namespaced attribute from the element's underlying DOM node.
10711 * @param {String} namespace The namespace in which to look for the attribute
10712 * @param {String} name The attribute name
10713 * @return {String} The attribute value
10715 getAttributeNS : Roo.isIE ? function(ns, name){
10717 var type = typeof d[ns+":"+name];
10718 if(type != 'undefined' && type != 'unknown'){
10719 return d[ns+":"+name];
10722 } : function(ns, name){
10724 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
10729 * Sets or Returns the value the dom attribute value
10730 * @param {String|Object} name The attribute name (or object to set multiple attributes)
10731 * @param {String} value (optional) The value to set the attribute to
10732 * @return {String} The attribute value
10734 attr : function(name){
10735 if (arguments.length > 1) {
10736 this.dom.setAttribute(name, arguments[1]);
10737 return arguments[1];
10739 if (typeof(name) == 'object') {
10740 for(var i in name) {
10741 this.attr(i, name[i]);
10747 if (!this.dom.hasAttribute(name)) {
10750 return this.dom.getAttribute(name);
10757 var ep = El.prototype;
10760 * Appends an event handler (Shorthand for addListener)
10761 * @param {String} eventName The type of event to append
10762 * @param {Function} fn The method the event invokes
10763 * @param {Object} scope (optional) The scope (this object) of the fn
10764 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
10767 ep.on = ep.addListener;
10768 // backwards compat
10769 ep.mon = ep.addListener;
10772 * Removes an event handler from this element (shorthand for removeListener)
10773 * @param {String} eventName the type of event to remove
10774 * @param {Function} fn the method the event invokes
10775 * @return {Roo.Element} this
10778 ep.un = ep.removeListener;
10781 * true to automatically adjust width and height settings for box-model issues (default to true)
10783 ep.autoBoxAdjust = true;
10786 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
10789 El.addUnits = function(v, defaultUnit){
10790 if(v === "" || v == "auto"){
10793 if(v === undefined){
10796 if(typeof v == "number" || !El.unitPattern.test(v)){
10797 return v + (defaultUnit || 'px');
10802 // special markup used throughout Roo when box wrapping elements
10803 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>';
10805 * Visibility mode constant - Use visibility to hide element
10811 * Visibility mode constant - Use display to hide element
10817 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
10818 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
10819 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
10831 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
10832 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
10833 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
10834 * @return {Element} The Element object
10837 El.get = function(el){
10839 if(!el){ return null; }
10840 if(typeof el == "string"){ // element id
10841 if(!(elm = document.getElementById(el))){
10844 if(ex = El.cache[el]){
10847 ex = El.cache[el] = new El(elm);
10850 }else if(el.tagName){ // dom element
10854 if(ex = El.cache[id]){
10857 ex = El.cache[id] = new El(el);
10860 }else if(el instanceof El){
10862 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
10863 // catch case where it hasn't been appended
10864 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
10867 }else if(el.isComposite){
10869 }else if(el instanceof Array){
10870 return El.select(el);
10871 }else if(el == document){
10872 // create a bogus element object representing the document object
10874 var f = function(){};
10875 f.prototype = El.prototype;
10877 docEl.dom = document;
10885 El.uncache = function(el){
10886 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
10888 delete El.cache[a[i].id || a[i]];
10894 // Garbage collection - uncache elements/purge listeners on orphaned elements
10895 // so we don't hold a reference and cause the browser to retain them
10896 El.garbageCollect = function(){
10897 if(!Roo.enableGarbageCollector){
10898 clearInterval(El.collectorThread);
10901 for(var eid in El.cache){
10902 var el = El.cache[eid], d = el.dom;
10903 // -------------------------------------------------------
10904 // Determining what is garbage:
10905 // -------------------------------------------------------
10907 // dom node is null, definitely garbage
10908 // -------------------------------------------------------
10910 // no parentNode == direct orphan, definitely garbage
10911 // -------------------------------------------------------
10912 // !d.offsetParent && !document.getElementById(eid)
10913 // display none elements have no offsetParent so we will
10914 // also try to look it up by it's id. However, check
10915 // offsetParent first so we don't do unneeded lookups.
10916 // This enables collection of elements that are not orphans
10917 // directly, but somewhere up the line they have an orphan
10919 // -------------------------------------------------------
10920 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
10921 delete El.cache[eid];
10922 if(d && Roo.enableListenerCollection){
10928 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
10932 El.Flyweight = function(dom){
10935 El.Flyweight.prototype = El.prototype;
10937 El._flyweights = {};
10939 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
10940 * the dom node can be overwritten by other code.
10941 * @param {String/HTMLElement} el The dom node or id
10942 * @param {String} named (optional) Allows for creation of named reusable flyweights to
10943 * prevent conflicts (e.g. internally Roo uses "_internal")
10945 * @return {Element} The shared Element object
10947 El.fly = function(el, named){
10948 named = named || '_global';
10949 el = Roo.getDom(el);
10953 if(!El._flyweights[named]){
10954 El._flyweights[named] = new El.Flyweight();
10956 El._flyweights[named].dom = el;
10957 return El._flyweights[named];
10961 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
10962 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
10963 * Shorthand of {@link Roo.Element#get}
10964 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
10965 * @return {Element} The Element object
10971 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
10972 * the dom node can be overwritten by other code.
10973 * Shorthand of {@link Roo.Element#fly}
10974 * @param {String/HTMLElement} el The dom node or id
10975 * @param {String} named (optional) Allows for creation of named reusable flyweights to
10976 * prevent conflicts (e.g. internally Roo uses "_internal")
10978 * @return {Element} The shared Element object
10984 // speedy lookup for elements never to box adjust
10985 var noBoxAdjust = Roo.isStrict ? {
10988 input:1, select:1, textarea:1
10990 if(Roo.isIE || Roo.isGecko){
10991 noBoxAdjust['button'] = 1;
10995 Roo.EventManager.on(window, 'unload', function(){
10997 delete El._flyweights;
11005 Roo.Element.selectorFunction = Roo.DomQuery.select;
11008 Roo.Element.select = function(selector, unique, root){
11010 if(typeof selector == "string"){
11011 els = Roo.Element.selectorFunction(selector, root);
11012 }else if(selector.length !== undefined){
11015 throw "Invalid selector";
11017 if(unique === true){
11018 return new Roo.CompositeElement(els);
11020 return new Roo.CompositeElementLite(els);
11024 * Selects elements based on the passed CSS selector to enable working on them as 1.
11025 * @param {String/Array} selector The CSS selector or an array of elements
11026 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
11027 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
11028 * @return {CompositeElementLite/CompositeElement}
11032 Roo.select = Roo.Element.select;
11049 * Ext JS Library 1.1.1
11050 * Copyright(c) 2006-2007, Ext JS, LLC.
11052 * Originally Released Under LGPL - original licence link has changed is not relivant.
11055 * <script type="text/javascript">
11060 //Notifies Element that fx methods are available
11061 Roo.enableFx = true;
11065 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
11066 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
11067 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
11068 * Element effects to work.</p><br/>
11070 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
11071 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
11072 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
11073 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
11074 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
11075 * expected results and should be done with care.</p><br/>
11077 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
11078 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
11081 ----- -----------------------------
11082 tl The top left corner
11083 t The center of the top edge
11084 tr The top right corner
11085 l The center of the left edge
11086 r The center of the right edge
11087 bl The bottom left corner
11088 b The center of the bottom edge
11089 br The bottom right corner
11091 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
11092 * below are common options that can be passed to any Fx method.</b>
11093 * @cfg {Function} callback A function called when the effect is finished
11094 * @cfg {Object} scope The scope of the effect function
11095 * @cfg {String} easing A valid Easing value for the effect
11096 * @cfg {String} afterCls A css class to apply after the effect
11097 * @cfg {Number} duration The length of time (in seconds) that the effect should last
11098 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
11099 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
11100 * effects that end with the element being visually hidden, ignored otherwise)
11101 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
11102 * a function which returns such a specification that will be applied to the Element after the effect finishes
11103 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
11104 * @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
11105 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
11109 * Slides the element into view. An anchor point can be optionally passed to set the point of
11110 * origin for the slide effect. This function automatically handles wrapping the element with
11111 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11114 // default: slide the element in from the top
11117 // custom: slide the element in from the right with a 2-second duration
11118 el.slideIn('r', { duration: 2 });
11120 // common config options shown with default values
11126 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11127 * @param {Object} options (optional) Object literal with any of the Fx config options
11128 * @return {Roo.Element} The Element
11130 slideIn : function(anchor, o){
11131 var el = this.getFxEl();
11134 el.queueFx(o, function(){
11136 anchor = anchor || "t";
11138 // fix display to visibility
11141 // restore values after effect
11142 var r = this.getFxRestore();
11143 var b = this.getBox();
11144 // fixed size for slide
11148 var wrap = this.fxWrap(r.pos, o, "hidden");
11150 var st = this.dom.style;
11151 st.visibility = "visible";
11152 st.position = "absolute";
11154 // clear out temp styles after slide and unwrap
11155 var after = function(){
11156 el.fxUnwrap(wrap, r.pos, o);
11157 st.width = r.width;
11158 st.height = r.height;
11161 // time to calc the positions
11162 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
11164 switch(anchor.toLowerCase()){
11166 wrap.setSize(b.width, 0);
11167 st.left = st.bottom = "0";
11171 wrap.setSize(0, b.height);
11172 st.right = st.top = "0";
11176 wrap.setSize(0, b.height);
11177 wrap.setX(b.right);
11178 st.left = st.top = "0";
11179 a = {width: bw, points: pt};
11182 wrap.setSize(b.width, 0);
11183 wrap.setY(b.bottom);
11184 st.left = st.top = "0";
11185 a = {height: bh, points: pt};
11188 wrap.setSize(0, 0);
11189 st.right = st.bottom = "0";
11190 a = {width: bw, height: bh};
11193 wrap.setSize(0, 0);
11194 wrap.setY(b.y+b.height);
11195 st.right = st.top = "0";
11196 a = {width: bw, height: bh, points: pt};
11199 wrap.setSize(0, 0);
11200 wrap.setXY([b.right, b.bottom]);
11201 st.left = st.top = "0";
11202 a = {width: bw, height: bh, points: pt};
11205 wrap.setSize(0, 0);
11206 wrap.setX(b.x+b.width);
11207 st.left = st.bottom = "0";
11208 a = {width: bw, height: bh, points: pt};
11211 this.dom.style.visibility = "visible";
11214 arguments.callee.anim = wrap.fxanim(a,
11224 * Slides the element out of view. An anchor point can be optionally passed to set the end point
11225 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
11226 * 'hidden') but block elements will still take up space in the document. The element must be removed
11227 * from the DOM using the 'remove' config option if desired. This function automatically handles
11228 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11231 // default: slide the element out to the top
11234 // custom: slide the element out to the right with a 2-second duration
11235 el.slideOut('r', { duration: 2 });
11237 // common config options shown with default values
11245 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11246 * @param {Object} options (optional) Object literal with any of the Fx config options
11247 * @return {Roo.Element} The Element
11249 slideOut : function(anchor, o){
11250 var el = this.getFxEl();
11253 el.queueFx(o, function(){
11255 anchor = anchor || "t";
11257 // restore values after effect
11258 var r = this.getFxRestore();
11260 var b = this.getBox();
11261 // fixed size for slide
11265 var wrap = this.fxWrap(r.pos, o, "visible");
11267 var st = this.dom.style;
11268 st.visibility = "visible";
11269 st.position = "absolute";
11273 var after = function(){
11275 el.setDisplayed(false);
11280 el.fxUnwrap(wrap, r.pos, o);
11282 st.width = r.width;
11283 st.height = r.height;
11288 var a, zero = {to: 0};
11289 switch(anchor.toLowerCase()){
11291 st.left = st.bottom = "0";
11292 a = {height: zero};
11295 st.right = st.top = "0";
11299 st.left = st.top = "0";
11300 a = {width: zero, points: {to:[b.right, b.y]}};
11303 st.left = st.top = "0";
11304 a = {height: zero, points: {to:[b.x, b.bottom]}};
11307 st.right = st.bottom = "0";
11308 a = {width: zero, height: zero};
11311 st.right = st.top = "0";
11312 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
11315 st.left = st.top = "0";
11316 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
11319 st.left = st.bottom = "0";
11320 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
11324 arguments.callee.anim = wrap.fxanim(a,
11334 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
11335 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
11336 * The element must be removed from the DOM using the 'remove' config option if desired.
11342 // common config options shown with default values
11350 * @param {Object} options (optional) Object literal with any of the Fx config options
11351 * @return {Roo.Element} The Element
11353 puff : function(o){
11354 var el = this.getFxEl();
11357 el.queueFx(o, function(){
11358 this.clearOpacity();
11361 // restore values after effect
11362 var r = this.getFxRestore();
11363 var st = this.dom.style;
11365 var after = function(){
11367 el.setDisplayed(false);
11374 el.setPositioning(r.pos);
11375 st.width = r.width;
11376 st.height = r.height;
11381 var width = this.getWidth();
11382 var height = this.getHeight();
11384 arguments.callee.anim = this.fxanim({
11385 width : {to: this.adjustWidth(width * 2)},
11386 height : {to: this.adjustHeight(height * 2)},
11387 points : {by: [-(width * .5), -(height * .5)]},
11389 fontSize: {to:200, unit: "%"}
11400 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
11401 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
11402 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
11408 // all config options shown with default values
11416 * @param {Object} options (optional) Object literal with any of the Fx config options
11417 * @return {Roo.Element} The Element
11419 switchOff : function(o){
11420 var el = this.getFxEl();
11423 el.queueFx(o, function(){
11424 this.clearOpacity();
11427 // restore values after effect
11428 var r = this.getFxRestore();
11429 var st = this.dom.style;
11431 var after = function(){
11433 el.setDisplayed(false);
11439 el.setPositioning(r.pos);
11440 st.width = r.width;
11441 st.height = r.height;
11446 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
11447 this.clearOpacity();
11451 points:{by:[0, this.getHeight() * .5]}
11452 }, o, 'motion', 0.3, 'easeIn', after);
11453 }).defer(100, this);
11460 * Highlights the Element by setting a color (applies to the background-color by default, but can be
11461 * changed using the "attr" config option) and then fading back to the original color. If no original
11462 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
11465 // default: highlight background to yellow
11468 // custom: highlight foreground text to blue for 2 seconds
11469 el.highlight("0000ff", { attr: 'color', duration: 2 });
11471 // common config options shown with default values
11472 el.highlight("ffff9c", {
11473 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
11474 endColor: (current color) or "ffffff",
11479 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
11480 * @param {Object} options (optional) Object literal with any of the Fx config options
11481 * @return {Roo.Element} The Element
11483 highlight : function(color, o){
11484 var el = this.getFxEl();
11487 el.queueFx(o, function(){
11488 color = color || "ffff9c";
11489 attr = o.attr || "backgroundColor";
11491 this.clearOpacity();
11494 var origColor = this.getColor(attr);
11495 var restoreColor = this.dom.style[attr];
11496 endColor = (o.endColor || origColor) || "ffffff";
11498 var after = function(){
11499 el.dom.style[attr] = restoreColor;
11504 a[attr] = {from: color, to: endColor};
11505 arguments.callee.anim = this.fxanim(a,
11515 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
11518 // default: a single light blue ripple
11521 // custom: 3 red ripples lasting 3 seconds total
11522 el.frame("ff0000", 3, { duration: 3 });
11524 // common config options shown with default values
11525 el.frame("C3DAF9", 1, {
11526 duration: 1 //duration of entire animation (not each individual ripple)
11527 // Note: Easing is not configurable and will be ignored if included
11530 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
11531 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
11532 * @param {Object} options (optional) Object literal with any of the Fx config options
11533 * @return {Roo.Element} The Element
11535 frame : function(color, count, o){
11536 var el = this.getFxEl();
11539 el.queueFx(o, function(){
11540 color = color || "#C3DAF9";
11541 if(color.length == 6){
11542 color = "#" + color;
11544 count = count || 1;
11545 duration = o.duration || 1;
11548 var b = this.getBox();
11549 var animFn = function(){
11550 var proxy = this.createProxy({
11553 visbility:"hidden",
11554 position:"absolute",
11555 "z-index":"35000", // yee haw
11556 border:"0px solid " + color
11559 var scale = Roo.isBorderBox ? 2 : 1;
11561 top:{from:b.y, to:b.y - 20},
11562 left:{from:b.x, to:b.x - 20},
11563 borderWidth:{from:0, to:10},
11564 opacity:{from:1, to:0},
11565 height:{from:b.height, to:(b.height + (20*scale))},
11566 width:{from:b.width, to:(b.width + (20*scale))}
11567 }, duration, function(){
11571 animFn.defer((duration/2)*1000, this);
11582 * Creates a pause before any subsequent queued effects begin. If there are
11583 * no effects queued after the pause it will have no effect.
11588 * @param {Number} seconds The length of time to pause (in seconds)
11589 * @return {Roo.Element} The Element
11591 pause : function(seconds){
11592 var el = this.getFxEl();
11595 el.queueFx(o, function(){
11596 setTimeout(function(){
11598 }, seconds * 1000);
11604 * Fade an element in (from transparent to opaque). The ending opacity can be specified
11605 * using the "endOpacity" config option.
11608 // default: fade in from opacity 0 to 100%
11611 // custom: fade in from opacity 0 to 75% over 2 seconds
11612 el.fadeIn({ endOpacity: .75, duration: 2});
11614 // common config options shown with default values
11616 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
11621 * @param {Object} options (optional) Object literal with any of the Fx config options
11622 * @return {Roo.Element} The Element
11624 fadeIn : function(o){
11625 var el = this.getFxEl();
11627 el.queueFx(o, function(){
11628 this.setOpacity(0);
11630 this.dom.style.visibility = 'visible';
11631 var to = o.endOpacity || 1;
11632 arguments.callee.anim = this.fxanim({opacity:{to:to}},
11633 o, null, .5, "easeOut", function(){
11635 this.clearOpacity();
11644 * Fade an element out (from opaque to transparent). The ending opacity can be specified
11645 * using the "endOpacity" config option.
11648 // default: fade out from the element's current opacity to 0
11651 // custom: fade out from the element's current opacity to 25% over 2 seconds
11652 el.fadeOut({ endOpacity: .25, duration: 2});
11654 // common config options shown with default values
11656 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
11663 * @param {Object} options (optional) Object literal with any of the Fx config options
11664 * @return {Roo.Element} The Element
11666 fadeOut : function(o){
11667 var el = this.getFxEl();
11669 el.queueFx(o, function(){
11670 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
11671 o, null, .5, "easeOut", function(){
11672 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
11673 this.dom.style.display = "none";
11675 this.dom.style.visibility = "hidden";
11677 this.clearOpacity();
11685 * Animates the transition of an element's dimensions from a starting height/width
11686 * to an ending height/width.
11689 // change height and width to 100x100 pixels
11690 el.scale(100, 100);
11692 // common config options shown with default values. The height and width will default to
11693 // the element's existing values if passed as null.
11696 [element's height], {
11701 * @param {Number} width The new width (pass undefined to keep the original width)
11702 * @param {Number} height The new height (pass undefined to keep the original height)
11703 * @param {Object} options (optional) Object literal with any of the Fx config options
11704 * @return {Roo.Element} The Element
11706 scale : function(w, h, o){
11707 this.shift(Roo.apply({}, o, {
11715 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
11716 * Any of these properties not specified in the config object will not be changed. This effect
11717 * requires that at least one new dimension, position or opacity setting must be passed in on
11718 * the config object in order for the function to have any effect.
11721 // slide the element horizontally to x position 200 while changing the height and opacity
11722 el.shift({ x: 200, height: 50, opacity: .8 });
11724 // common config options shown with default values.
11726 width: [element's width],
11727 height: [element's height],
11728 x: [element's x position],
11729 y: [element's y position],
11730 opacity: [element's opacity],
11735 * @param {Object} options Object literal with any of the Fx config options
11736 * @return {Roo.Element} The Element
11738 shift : function(o){
11739 var el = this.getFxEl();
11741 el.queueFx(o, function(){
11742 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
11743 if(w !== undefined){
11744 a.width = {to: this.adjustWidth(w)};
11746 if(h !== undefined){
11747 a.height = {to: this.adjustHeight(h)};
11749 if(x !== undefined || y !== undefined){
11751 x !== undefined ? x : this.getX(),
11752 y !== undefined ? y : this.getY()
11755 if(op !== undefined){
11756 a.opacity = {to: op};
11758 if(o.xy !== undefined){
11759 a.points = {to: o.xy};
11761 arguments.callee.anim = this.fxanim(a,
11762 o, 'motion', .35, "easeOut", function(){
11770 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
11771 * ending point of the effect.
11774 // default: slide the element downward while fading out
11777 // custom: slide the element out to the right with a 2-second duration
11778 el.ghost('r', { duration: 2 });
11780 // common config options shown with default values
11788 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
11789 * @param {Object} options (optional) Object literal with any of the Fx config options
11790 * @return {Roo.Element} The Element
11792 ghost : function(anchor, o){
11793 var el = this.getFxEl();
11796 el.queueFx(o, function(){
11797 anchor = anchor || "b";
11799 // restore values after effect
11800 var r = this.getFxRestore();
11801 var w = this.getWidth(),
11802 h = this.getHeight();
11804 var st = this.dom.style;
11806 var after = function(){
11808 el.setDisplayed(false);
11814 el.setPositioning(r.pos);
11815 st.width = r.width;
11816 st.height = r.height;
11821 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
11822 switch(anchor.toLowerCase()){
11849 arguments.callee.anim = this.fxanim(a,
11859 * Ensures that all effects queued after syncFx is called on the element are
11860 * run concurrently. This is the opposite of {@link #sequenceFx}.
11861 * @return {Roo.Element} The Element
11863 syncFx : function(){
11864 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
11873 * Ensures that all effects queued after sequenceFx is called on the element are
11874 * run in sequence. This is the opposite of {@link #syncFx}.
11875 * @return {Roo.Element} The Element
11877 sequenceFx : function(){
11878 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
11880 concurrent : false,
11887 nextFx : function(){
11888 var ef = this.fxQueue[0];
11895 * Returns true if the element has any effects actively running or queued, else returns false.
11896 * @return {Boolean} True if element has active effects, else false
11898 hasActiveFx : function(){
11899 return this.fxQueue && this.fxQueue[0];
11903 * Stops any running effects and clears the element's internal effects queue if it contains
11904 * any additional effects that haven't started yet.
11905 * @return {Roo.Element} The Element
11907 stopFx : function(){
11908 if(this.hasActiveFx()){
11909 var cur = this.fxQueue[0];
11910 if(cur && cur.anim && cur.anim.isAnimated()){
11911 this.fxQueue = [cur]; // clear out others
11912 cur.anim.stop(true);
11919 beforeFx : function(o){
11920 if(this.hasActiveFx() && !o.concurrent){
11931 * Returns true if the element is currently blocking so that no other effect can be queued
11932 * until this effect is finished, else returns false if blocking is not set. This is commonly
11933 * used to ensure that an effect initiated by a user action runs to completion prior to the
11934 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
11935 * @return {Boolean} True if blocking, else false
11937 hasFxBlock : function(){
11938 var q = this.fxQueue;
11939 return q && q[0] && q[0].block;
11943 queueFx : function(o, fn){
11947 if(!this.hasFxBlock()){
11948 Roo.applyIf(o, this.fxDefaults);
11950 var run = this.beforeFx(o);
11951 fn.block = o.block;
11952 this.fxQueue.push(fn);
11964 fxWrap : function(pos, o, vis){
11966 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
11969 wrapXY = this.getXY();
11971 var div = document.createElement("div");
11972 div.style.visibility = vis;
11973 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
11974 wrap.setPositioning(pos);
11975 if(wrap.getStyle("position") == "static"){
11976 wrap.position("relative");
11978 this.clearPositioning('auto');
11980 wrap.dom.appendChild(this.dom);
11982 wrap.setXY(wrapXY);
11989 fxUnwrap : function(wrap, pos, o){
11990 this.clearPositioning();
11991 this.setPositioning(pos);
11993 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
11999 getFxRestore : function(){
12000 var st = this.dom.style;
12001 return {pos: this.getPositioning(), width: st.width, height : st.height};
12005 afterFx : function(o){
12007 this.applyStyles(o.afterStyle);
12010 this.addClass(o.afterCls);
12012 if(o.remove === true){
12015 Roo.callback(o.callback, o.scope, [this]);
12017 this.fxQueue.shift();
12023 getFxEl : function(){ // support for composite element fx
12024 return Roo.get(this.dom);
12028 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
12029 animType = animType || 'run';
12031 var anim = Roo.lib.Anim[animType](
12033 (opt.duration || defaultDur) || .35,
12034 (opt.easing || defaultEase) || 'easeOut',
12036 Roo.callback(cb, this);
12045 // backwords compat
12046 Roo.Fx.resize = Roo.Fx.scale;
12048 //When included, Roo.Fx is automatically applied to Element so that all basic
12049 //effects are available directly via the Element API
12050 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
12052 * Ext JS Library 1.1.1
12053 * Copyright(c) 2006-2007, Ext JS, LLC.
12055 * Originally Released Under LGPL - original licence link has changed is not relivant.
12058 * <script type="text/javascript">
12063 * @class Roo.CompositeElement
12064 * Standard composite class. Creates a Roo.Element for every element in the collection.
12066 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12067 * actions will be performed on all the elements in this collection.</b>
12069 * All methods return <i>this</i> and can be chained.
12071 var els = Roo.select("#some-el div.some-class", true);
12072 // or select directly from an existing element
12073 var el = Roo.get('some-el');
12074 el.select('div.some-class', true);
12076 els.setWidth(100); // all elements become 100 width
12077 els.hide(true); // all elements fade out and hide
12079 els.setWidth(100).hide(true);
12082 Roo.CompositeElement = function(els){
12083 this.elements = [];
12084 this.addElements(els);
12086 Roo.CompositeElement.prototype = {
12088 addElements : function(els){
12092 if(typeof els == "string"){
12093 els = Roo.Element.selectorFunction(els);
12095 var yels = this.elements;
12096 var index = yels.length-1;
12097 for(var i = 0, len = els.length; i < len; i++) {
12098 yels[++index] = Roo.get(els[i]);
12104 * Clears this composite and adds the elements returned by the passed selector.
12105 * @param {String/Array} els A string CSS selector, an array of elements or an element
12106 * @return {CompositeElement} this
12108 fill : function(els){
12109 this.elements = [];
12115 * Filters this composite to only elements that match the passed selector.
12116 * @param {String} selector A string CSS selector
12117 * @param {Boolean} inverse return inverse filter (not matches)
12118 * @return {CompositeElement} this
12120 filter : function(selector, inverse){
12122 inverse = inverse || false;
12123 this.each(function(el){
12124 var match = inverse ? !el.is(selector) : el.is(selector);
12126 els[els.length] = el.dom;
12133 invoke : function(fn, args){
12134 var els = this.elements;
12135 for(var i = 0, len = els.length; i < len; i++) {
12136 Roo.Element.prototype[fn].apply(els[i], args);
12141 * Adds elements to this composite.
12142 * @param {String/Array} els A string CSS selector, an array of elements or an element
12143 * @return {CompositeElement} this
12145 add : function(els){
12146 if(typeof els == "string"){
12147 this.addElements(Roo.Element.selectorFunction(els));
12148 }else if(els.length !== undefined){
12149 this.addElements(els);
12151 this.addElements([els]);
12156 * Calls the passed function passing (el, this, index) for each element in this composite.
12157 * @param {Function} fn The function to call
12158 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12159 * @return {CompositeElement} this
12161 each : function(fn, scope){
12162 var els = this.elements;
12163 for(var i = 0, len = els.length; i < len; i++){
12164 if(fn.call(scope || els[i], els[i], this, i) === false) {
12172 * Returns the Element object at the specified index
12173 * @param {Number} index
12174 * @return {Roo.Element}
12176 item : function(index){
12177 return this.elements[index] || null;
12181 * Returns the first Element
12182 * @return {Roo.Element}
12184 first : function(){
12185 return this.item(0);
12189 * Returns the last Element
12190 * @return {Roo.Element}
12193 return this.item(this.elements.length-1);
12197 * Returns the number of elements in this composite
12200 getCount : function(){
12201 return this.elements.length;
12205 * Returns true if this composite contains the passed element
12208 contains : function(el){
12209 return this.indexOf(el) !== -1;
12213 * Returns true if this composite contains the passed element
12216 indexOf : function(el){
12217 return this.elements.indexOf(Roo.get(el));
12222 * Removes the specified element(s).
12223 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
12224 * or an array of any of those.
12225 * @param {Boolean} removeDom (optional) True to also remove the element from the document
12226 * @return {CompositeElement} this
12228 removeElement : function(el, removeDom){
12229 if(el instanceof Array){
12230 for(var i = 0, len = el.length; i < len; i++){
12231 this.removeElement(el[i]);
12235 var index = typeof el == 'number' ? el : this.indexOf(el);
12238 var d = this.elements[index];
12242 d.parentNode.removeChild(d);
12245 this.elements.splice(index, 1);
12251 * Replaces the specified element with the passed element.
12252 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
12254 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
12255 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
12256 * @return {CompositeElement} this
12258 replaceElement : function(el, replacement, domReplace){
12259 var index = typeof el == 'number' ? el : this.indexOf(el);
12262 this.elements[index].replaceWith(replacement);
12264 this.elements.splice(index, 1, Roo.get(replacement))
12271 * Removes all elements.
12273 clear : function(){
12274 this.elements = [];
12278 Roo.CompositeElement.createCall = function(proto, fnName){
12279 if(!proto[fnName]){
12280 proto[fnName] = function(){
12281 return this.invoke(fnName, arguments);
12285 for(var fnName in Roo.Element.prototype){
12286 if(typeof Roo.Element.prototype[fnName] == "function"){
12287 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
12293 * Ext JS Library 1.1.1
12294 * Copyright(c) 2006-2007, Ext JS, LLC.
12296 * Originally Released Under LGPL - original licence link has changed is not relivant.
12299 * <script type="text/javascript">
12303 * @class Roo.CompositeElementLite
12304 * @extends Roo.CompositeElement
12305 * Flyweight composite class. Reuses the same Roo.Element for element operations.
12307 var els = Roo.select("#some-el div.some-class");
12308 // or select directly from an existing element
12309 var el = Roo.get('some-el');
12310 el.select('div.some-class');
12312 els.setWidth(100); // all elements become 100 width
12313 els.hide(true); // all elements fade out and hide
12315 els.setWidth(100).hide(true);
12316 </code></pre><br><br>
12317 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12318 * actions will be performed on all the elements in this collection.</b>
12320 Roo.CompositeElementLite = function(els){
12321 Roo.CompositeElementLite.superclass.constructor.call(this, els);
12322 this.el = new Roo.Element.Flyweight();
12324 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
12325 addElements : function(els){
12327 if(els instanceof Array){
12328 this.elements = this.elements.concat(els);
12330 var yels = this.elements;
12331 var index = yels.length-1;
12332 for(var i = 0, len = els.length; i < len; i++) {
12333 yels[++index] = els[i];
12339 invoke : function(fn, args){
12340 var els = this.elements;
12342 for(var i = 0, len = els.length; i < len; i++) {
12344 Roo.Element.prototype[fn].apply(el, args);
12349 * Returns a flyweight Element of the dom element object at the specified index
12350 * @param {Number} index
12351 * @return {Roo.Element}
12353 item : function(index){
12354 if(!this.elements[index]){
12357 this.el.dom = this.elements[index];
12361 // fixes scope with flyweight
12362 addListener : function(eventName, handler, scope, opt){
12363 var els = this.elements;
12364 for(var i = 0, len = els.length; i < len; i++) {
12365 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
12371 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
12372 * passed is the flyweight (shared) Roo.Element instance, so if you require a
12373 * a reference to the dom node, use el.dom.</b>
12374 * @param {Function} fn The function to call
12375 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12376 * @return {CompositeElement} this
12378 each : function(fn, scope){
12379 var els = this.elements;
12381 for(var i = 0, len = els.length; i < len; i++){
12383 if(fn.call(scope || el, el, this, i) === false){
12390 indexOf : function(el){
12391 return this.elements.indexOf(Roo.getDom(el));
12394 replaceElement : function(el, replacement, domReplace){
12395 var index = typeof el == 'number' ? el : this.indexOf(el);
12397 replacement = Roo.getDom(replacement);
12399 var d = this.elements[index];
12400 d.parentNode.insertBefore(replacement, d);
12401 d.parentNode.removeChild(d);
12403 this.elements.splice(index, 1, replacement);
12408 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
12412 * Ext JS Library 1.1.1
12413 * Copyright(c) 2006-2007, Ext JS, LLC.
12415 * Originally Released Under LGPL - original licence link has changed is not relivant.
12418 * <script type="text/javascript">
12424 * @class Roo.data.Connection
12425 * @extends Roo.util.Observable
12426 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
12427 * either to a configured URL, or to a URL specified at request time.
12429 * Requests made by this class are asynchronous, and will return immediately. No data from
12430 * the server will be available to the statement immediately following the {@link #request} call.
12431 * To process returned data, use a callback in the request options object, or an event listener.
12433 * Note: If you are doing a file upload, you will not get a normal response object sent back to
12434 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
12435 * The response object is created using the innerHTML of the IFRAME's document as the responseText
12436 * property and, if present, the IFRAME's XML document as the responseXML property.
12438 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
12439 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
12440 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
12441 * standard DOM methods.
12443 * @param {Object} config a configuration object.
12445 Roo.data.Connection = function(config){
12446 Roo.apply(this, config);
12449 * @event beforerequest
12450 * Fires before a network request is made to retrieve a data object.
12451 * @param {Connection} conn This Connection object.
12452 * @param {Object} options The options config object passed to the {@link #request} method.
12454 "beforerequest" : true,
12456 * @event requestcomplete
12457 * Fires if the request was successfully completed.
12458 * @param {Connection} conn This Connection object.
12459 * @param {Object} response The XHR object containing the response data.
12460 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12461 * @param {Object} options The options config object passed to the {@link #request} method.
12463 "requestcomplete" : true,
12465 * @event requestexception
12466 * Fires if an error HTTP status was returned from the server.
12467 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
12468 * @param {Connection} conn This Connection object.
12469 * @param {Object} response The XHR object containing the response data.
12470 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12471 * @param {Object} options The options config object passed to the {@link #request} method.
12473 "requestexception" : true
12475 Roo.data.Connection.superclass.constructor.call(this);
12478 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
12480 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
12483 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
12484 * extra parameters to each request made by this object. (defaults to undefined)
12487 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
12488 * to each request made by this object. (defaults to undefined)
12491 * @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)
12494 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12498 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
12504 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12507 disableCaching: true,
12510 * Sends an HTTP request to a remote server.
12511 * @param {Object} options An object which may contain the following properties:<ul>
12512 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
12513 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
12514 * request, a url encoded string or a function to call to get either.</li>
12515 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
12516 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
12517 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
12518 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
12519 * <li>options {Object} The parameter to the request call.</li>
12520 * <li>success {Boolean} True if the request succeeded.</li>
12521 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12523 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
12524 * The callback is passed the following parameters:<ul>
12525 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12526 * <li>options {Object} The parameter to the request call.</li>
12528 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
12529 * The callback is passed the following parameters:<ul>
12530 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12531 * <li>options {Object} The parameter to the request call.</li>
12533 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
12534 * for the callback function. Defaults to the browser window.</li>
12535 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
12536 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
12537 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
12538 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
12539 * params for the post data. Any params will be appended to the URL.</li>
12540 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
12542 * @return {Number} transactionId
12544 request : function(o){
12545 if(this.fireEvent("beforerequest", this, o) !== false){
12548 if(typeof p == "function"){
12549 p = p.call(o.scope||window, o);
12551 if(typeof p == "object"){
12552 p = Roo.urlEncode(o.params);
12554 if(this.extraParams){
12555 var extras = Roo.urlEncode(this.extraParams);
12556 p = p ? (p + '&' + extras) : extras;
12559 var url = o.url || this.url;
12560 if(typeof url == 'function'){
12561 url = url.call(o.scope||window, o);
12565 var form = Roo.getDom(o.form);
12566 url = url || form.action;
12568 var enctype = form.getAttribute("enctype");
12571 return this.doFormDataUpload(o, url);
12574 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
12575 return this.doFormUpload(o, p, url);
12577 var f = Roo.lib.Ajax.serializeForm(form);
12578 p = p ? (p + '&' + f) : f;
12581 if (!o.form && o.formData) {
12582 o.formData = o.formData === true ? new FormData() : o.formData;
12583 for (var k in o.params) {
12584 o.formData.append(k,o.params[k]);
12587 return this.doFormDataUpload(o, url);
12591 var hs = o.headers;
12592 if(this.defaultHeaders){
12593 hs = Roo.apply(hs || {}, this.defaultHeaders);
12600 success: this.handleResponse,
12601 failure: this.handleFailure,
12603 argument: {options: o},
12604 timeout : o.timeout || this.timeout
12607 var method = o.method||this.method||(p ? "POST" : "GET");
12609 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
12610 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
12613 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
12617 }else if(this.autoAbort !== false){
12621 if((method == 'GET' && p) || o.xmlData){
12622 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
12625 Roo.lib.Ajax.useDefaultHeader = typeof(o.headers) == 'undefined' || typeof(o.headers['Content-Type']) == 'undefined';
12626 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
12627 Roo.lib.Ajax.useDefaultHeader == true;
12628 return this.transId;
12630 Roo.callback(o.callback, o.scope, [o, null, null]);
12636 * Determine whether this object has a request outstanding.
12637 * @param {Number} transactionId (Optional) defaults to the last transaction
12638 * @return {Boolean} True if there is an outstanding request.
12640 isLoading : function(transId){
12642 return Roo.lib.Ajax.isCallInProgress(transId);
12644 return this.transId ? true : false;
12649 * Aborts any outstanding request.
12650 * @param {Number} transactionId (Optional) defaults to the last transaction
12652 abort : function(transId){
12653 if(transId || this.isLoading()){
12654 Roo.lib.Ajax.abort(transId || this.transId);
12659 handleResponse : function(response){
12660 this.transId = false;
12661 var options = response.argument.options;
12662 response.argument = options ? options.argument : null;
12663 this.fireEvent("requestcomplete", this, response, options);
12664 Roo.callback(options.success, options.scope, [response, options]);
12665 Roo.callback(options.callback, options.scope, [options, true, response]);
12669 handleFailure : function(response, e){
12670 this.transId = false;
12671 var options = response.argument.options;
12672 response.argument = options ? options.argument : null;
12673 this.fireEvent("requestexception", this, response, options, e);
12674 Roo.callback(options.failure, options.scope, [response, options]);
12675 Roo.callback(options.callback, options.scope, [options, false, response]);
12679 doFormUpload : function(o, ps, url){
12681 var frame = document.createElement('iframe');
12684 frame.className = 'x-hidden';
12686 frame.src = Roo.SSL_SECURE_URL;
12688 document.body.appendChild(frame);
12691 document.frames[id].name = id;
12694 var form = Roo.getDom(o.form);
12696 form.method = 'POST';
12697 form.enctype = form.encoding = 'multipart/form-data';
12703 if(ps){ // add dynamic params
12705 ps = Roo.urlDecode(ps, false);
12707 if(ps.hasOwnProperty(k)){
12708 hd = document.createElement('input');
12709 hd.type = 'hidden';
12712 form.appendChild(hd);
12719 var r = { // bogus response object
12724 r.argument = o ? o.argument : null;
12729 doc = frame.contentWindow.document;
12731 doc = (frame.contentDocument || window.frames[id].document);
12733 if(doc && doc.body){
12734 r.responseText = doc.body.innerHTML;
12736 if(doc && doc.XMLDocument){
12737 r.responseXML = doc.XMLDocument;
12739 r.responseXML = doc;
12746 Roo.EventManager.removeListener(frame, 'load', cb, this);
12748 this.fireEvent("requestcomplete", this, r, o);
12749 Roo.callback(o.success, o.scope, [r, o]);
12750 Roo.callback(o.callback, o.scope, [o, true, r]);
12752 setTimeout(function(){document.body.removeChild(frame);}, 100);
12755 Roo.EventManager.on(frame, 'load', cb, this);
12758 if(hiddens){ // remove dynamic params
12759 for(var i = 0, len = hiddens.length; i < len; i++){
12760 form.removeChild(hiddens[i]);
12764 // this is a 'formdata version???'
12767 doFormDataUpload : function(o, url)
12771 var form = Roo.getDom(o.form);
12772 form.enctype = form.encoding = 'multipart/form-data';
12773 formData = o.formData === true ? new FormData(form) : o.formData;
12775 formData = o.formData === true ? new FormData() : o.formData;
12780 success: this.handleResponse,
12781 failure: this.handleFailure,
12783 argument: {options: o},
12784 timeout : o.timeout || this.timeout
12787 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
12791 }else if(this.autoAbort !== false){
12795 //Roo.lib.Ajax.defaultPostHeader = null;
12796 Roo.lib.Ajax.useDefaultHeader = false;
12797 this.transId = Roo.lib.Ajax.request( "POST", url, cb, formData, o);
12798 Roo.lib.Ajax.useDefaultHeader = true;
12806 * Ext JS Library 1.1.1
12807 * Copyright(c) 2006-2007, Ext JS, LLC.
12809 * Originally Released Under LGPL - original licence link has changed is not relivant.
12812 * <script type="text/javascript">
12816 * Global Ajax request class.
12819 * @extends Roo.data.Connection
12822 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
12823 * @cfg {Object} extraParams An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
12824 * @cfg {Object} defaultHeaders An object containing request headers which are added to each request made by this object. (defaults to undefined)
12825 * @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)
12826 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12827 * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
12828 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12830 Roo.Ajax = new Roo.data.Connection({
12839 * Serialize the passed form into a url encoded string
12841 * @param {String/HTMLElement} form
12844 serializeForm : function(form){
12845 return Roo.lib.Ajax.serializeForm(form);
12849 * Ext JS Library 1.1.1
12850 * Copyright(c) 2006-2007, Ext JS, LLC.
12852 * Originally Released Under LGPL - original licence link has changed is not relivant.
12855 * <script type="text/javascript">
12860 * @class Roo.UpdateManager
12861 * @extends Roo.util.Observable
12862 * Provides AJAX-style update for Element object.<br><br>
12865 * // Get it from a Roo.Element object
12866 * var el = Roo.get("foo");
12867 * var mgr = el.getUpdateManager();
12868 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
12870 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
12872 * // or directly (returns the same UpdateManager instance)
12873 * var mgr = new Roo.UpdateManager("myElementId");
12874 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
12875 * mgr.on("update", myFcnNeedsToKnow);
12877 // short handed call directly from the element object
12878 Roo.get("foo").load({
12882 text: "Loading Foo..."
12886 * Create new UpdateManager directly.
12887 * @param {String/HTMLElement/Roo.Element} el The element to update
12888 * @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).
12890 Roo.UpdateManager = function(el, forceNew){
12892 if(!forceNew && el.updateManager){
12893 return el.updateManager;
12896 * The Element object
12897 * @type Roo.Element
12901 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
12904 this.defaultUrl = null;
12908 * @event beforeupdate
12909 * Fired before an update is made, return false from your handler and the update is cancelled.
12910 * @param {Roo.Element} el
12911 * @param {String/Object/Function} url
12912 * @param {String/Object} params
12914 "beforeupdate": true,
12917 * Fired after successful update is made.
12918 * @param {Roo.Element} el
12919 * @param {Object} oResponseObject The response Object
12924 * Fired on update failure.
12925 * @param {Roo.Element} el
12926 * @param {Object} oResponseObject The response Object
12930 var d = Roo.UpdateManager.defaults;
12932 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
12935 this.sslBlankUrl = d.sslBlankUrl;
12937 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
12940 this.disableCaching = d.disableCaching;
12942 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
12945 this.indicatorText = d.indicatorText;
12947 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
12950 this.showLoadIndicator = d.showLoadIndicator;
12952 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
12955 this.timeout = d.timeout;
12958 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
12961 this.loadScripts = d.loadScripts;
12964 * Transaction object of current executing transaction
12966 this.transaction = null;
12971 this.autoRefreshProcId = null;
12973 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
12976 this.refreshDelegate = this.refresh.createDelegate(this);
12978 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
12981 this.updateDelegate = this.update.createDelegate(this);
12983 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
12986 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
12990 this.successDelegate = this.processSuccess.createDelegate(this);
12994 this.failureDelegate = this.processFailure.createDelegate(this);
12996 if(!this.renderer){
12998 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
13000 this.renderer = new Roo.UpdateManager.BasicRenderer();
13003 Roo.UpdateManager.superclass.constructor.call(this);
13006 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
13008 * Get the Element this UpdateManager is bound to
13009 * @return {Roo.Element} The element
13011 getEl : function(){
13015 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
13016 * @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:
13019 url: "your-url.php",<br/>
13020 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
13021 callback: yourFunction,<br/>
13022 scope: yourObject, //(optional scope) <br/>
13023 discardUrl: false, <br/>
13024 nocache: false,<br/>
13025 text: "Loading...",<br/>
13027 scripts: false<br/>
13030 * The only required property is url. The optional properties nocache, text and scripts
13031 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
13032 * @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}
13033 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13034 * @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.
13036 update : function(url, params, callback, discardUrl){
13037 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
13038 var method = this.method,
13040 if(typeof url == "object"){ // must be config object
13043 params = params || cfg.params;
13044 callback = callback || cfg.callback;
13045 discardUrl = discardUrl || cfg.discardUrl;
13046 if(callback && cfg.scope){
13047 callback = callback.createDelegate(cfg.scope);
13049 if(typeof cfg.method != "undefined"){method = cfg.method;};
13050 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
13051 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
13052 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
13053 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
13055 this.showLoading();
13057 this.defaultUrl = url;
13059 if(typeof url == "function"){
13060 url = url.call(this);
13063 method = method || (params ? "POST" : "GET");
13064 if(method == "GET"){
13065 url = this.prepareUrl(url);
13068 var o = Roo.apply(cfg ||{}, {
13071 success: this.successDelegate,
13072 failure: this.failureDelegate,
13073 callback: undefined,
13074 timeout: (this.timeout*1000),
13075 argument: {"url": url, "form": null, "callback": callback, "params": params}
13077 Roo.log("updated manager called with timeout of " + o.timeout);
13078 this.transaction = Roo.Ajax.request(o);
13083 * 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.
13084 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
13085 * @param {String/HTMLElement} form The form Id or form element
13086 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
13087 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
13088 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13090 formUpdate : function(form, url, reset, callback){
13091 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
13092 if(typeof url == "function"){
13093 url = url.call(this);
13095 form = Roo.getDom(form);
13096 this.transaction = Roo.Ajax.request({
13099 success: this.successDelegate,
13100 failure: this.failureDelegate,
13101 timeout: (this.timeout*1000),
13102 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
13104 this.showLoading.defer(1, this);
13109 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
13110 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13112 refresh : function(callback){
13113 if(this.defaultUrl == null){
13116 this.update(this.defaultUrl, null, callback, true);
13120 * Set this element to auto refresh.
13121 * @param {Number} interval How often to update (in seconds).
13122 * @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)
13123 * @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}
13124 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13125 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
13127 startAutoRefresh : function(interval, url, params, callback, refreshNow){
13129 this.update(url || this.defaultUrl, params, callback, true);
13131 if(this.autoRefreshProcId){
13132 clearInterval(this.autoRefreshProcId);
13134 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
13138 * Stop auto refresh on this element.
13140 stopAutoRefresh : function(){
13141 if(this.autoRefreshProcId){
13142 clearInterval(this.autoRefreshProcId);
13143 delete this.autoRefreshProcId;
13147 isAutoRefreshing : function(){
13148 return this.autoRefreshProcId ? true : false;
13151 * Called to update the element to "Loading" state. Override to perform custom action.
13153 showLoading : function(){
13154 if(this.showLoadIndicator){
13155 this.el.update(this.indicatorText);
13160 * Adds unique parameter to query string if disableCaching = true
13163 prepareUrl : function(url){
13164 if(this.disableCaching){
13165 var append = "_dc=" + (new Date().getTime());
13166 if(url.indexOf("?") !== -1){
13167 url += "&" + append;
13169 url += "?" + append;
13178 processSuccess : function(response){
13179 this.transaction = null;
13180 if(response.argument.form && response.argument.reset){
13181 try{ // put in try/catch since some older FF releases had problems with this
13182 response.argument.form.reset();
13185 if(this.loadScripts){
13186 this.renderer.render(this.el, response, this,
13187 this.updateComplete.createDelegate(this, [response]));
13189 this.renderer.render(this.el, response, this);
13190 this.updateComplete(response);
13194 updateComplete : function(response){
13195 this.fireEvent("update", this.el, response);
13196 if(typeof response.argument.callback == "function"){
13197 response.argument.callback(this.el, true, response);
13204 processFailure : function(response){
13205 this.transaction = null;
13206 this.fireEvent("failure", this.el, response);
13207 if(typeof response.argument.callback == "function"){
13208 response.argument.callback(this.el, false, response);
13213 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
13214 * @param {Object} renderer The object implementing the render() method
13216 setRenderer : function(renderer){
13217 this.renderer = renderer;
13220 getRenderer : function(){
13221 return this.renderer;
13225 * Set the defaultUrl used for updates
13226 * @param {String/Function} defaultUrl The url or a function to call to get the url
13228 setDefaultUrl : function(defaultUrl){
13229 this.defaultUrl = defaultUrl;
13233 * Aborts the executing transaction
13235 abort : function(){
13236 if(this.transaction){
13237 Roo.Ajax.abort(this.transaction);
13242 * Returns true if an update is in progress
13243 * @return {Boolean}
13245 isUpdating : function(){
13246 if(this.transaction){
13247 return Roo.Ajax.isLoading(this.transaction);
13254 * @class Roo.UpdateManager.defaults
13255 * @static (not really - but it helps the doc tool)
13256 * The defaults collection enables customizing the default properties of UpdateManager
13258 Roo.UpdateManager.defaults = {
13260 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
13266 * True to process scripts by default (Defaults to false).
13269 loadScripts : false,
13272 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
13275 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
13277 * Whether to append unique parameter on get request to disable caching (Defaults to false).
13280 disableCaching : false,
13282 * Whether to show indicatorText when loading (Defaults to true).
13285 showLoadIndicator : true,
13287 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
13290 indicatorText : '<div class="loading-indicator">Loading...</div>'
13294 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
13296 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
13297 * @param {String/HTMLElement/Roo.Element} el The element to update
13298 * @param {String} url The url
13299 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
13300 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
13303 * @member Roo.UpdateManager
13305 Roo.UpdateManager.updateElement = function(el, url, params, options){
13306 var um = Roo.get(el, true).getUpdateManager();
13307 Roo.apply(um, options);
13308 um.update(url, params, options ? options.callback : null);
13310 // alias for backwards compat
13311 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
13313 * @class Roo.UpdateManager.BasicRenderer
13314 * Default Content renderer. Updates the elements innerHTML with the responseText.
13316 Roo.UpdateManager.BasicRenderer = function(){};
13318 Roo.UpdateManager.BasicRenderer.prototype = {
13320 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
13321 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
13322 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
13323 * @param {Roo.Element} el The element being rendered
13324 * @param {Object} response The YUI Connect response object
13325 * @param {UpdateManager} updateManager The calling update manager
13326 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
13328 render : function(el, response, updateManager, callback){
13329 el.update(response.responseText, updateManager.loadScripts, callback);
13335 * (c)) Alan Knowles
13341 * @class Roo.DomTemplate
13342 * @extends Roo.Template
13343 * An effort at a dom based template engine..
13345 * Similar to XTemplate, except it uses dom parsing to create the template..
13347 * Supported features:
13352 {a_variable} - output encoded.
13353 {a_variable.format:("Y-m-d")} - call a method on the variable
13354 {a_variable:raw} - unencoded output
13355 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
13356 {a_variable:this.method_on_template(...)} - call a method on the template object.
13361 <div roo-for="a_variable or condition.."></div>
13362 <div roo-if="a_variable or condition"></div>
13363 <div roo-exec="some javascript"></div>
13364 <div roo-name="named_template"></div>
13369 Roo.DomTemplate = function()
13371 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
13378 Roo.extend(Roo.DomTemplate, Roo.Template, {
13380 * id counter for sub templates.
13384 * flag to indicate if dom parser is inside a pre,
13385 * it will strip whitespace if not.
13390 * The various sub templates
13398 * basic tag replacing syntax
13401 * // you can fake an object call by doing this
13405 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
13406 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
13408 iterChild : function (node, method) {
13410 var oldPre = this.inPre;
13411 if (node.tagName == 'PRE') {
13414 for( var i = 0; i < node.childNodes.length; i++) {
13415 method.call(this, node.childNodes[i]);
13417 this.inPre = oldPre;
13423 * compile the template
13425 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
13428 compile: function()
13432 // covert the html into DOM...
13436 doc = document.implementation.createHTMLDocument("");
13437 doc.documentElement.innerHTML = this.html ;
13438 div = doc.documentElement;
13440 // old IE... - nasty -- it causes all sorts of issues.. with
13441 // images getting pulled from server..
13442 div = document.createElement('div');
13443 div.innerHTML = this.html;
13445 //doc.documentElement.innerHTML = htmlBody
13451 this.iterChild(div, function(n) {_t.compileNode(n, true); });
13453 var tpls = this.tpls;
13455 // create a top level template from the snippet..
13457 //Roo.log(div.innerHTML);
13464 body : div.innerHTML,
13477 Roo.each(tpls, function(tp){
13478 this.compileTpl(tp);
13479 this.tpls[tp.id] = tp;
13482 this.master = tpls[0];
13488 compileNode : function(node, istop) {
13493 // skip anything not a tag..
13494 if (node.nodeType != 1) {
13495 if (node.nodeType == 3 && !this.inPre) {
13496 // reduce white space..
13497 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
13520 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
13521 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
13522 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
13523 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
13529 // just itterate children..
13530 this.iterChild(node,this.compileNode);
13533 tpl.uid = this.id++;
13534 tpl.value = node.getAttribute('roo-' + tpl.attr);
13535 node.removeAttribute('roo-'+ tpl.attr);
13536 if (tpl.attr != 'name') {
13537 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
13538 node.parentNode.replaceChild(placeholder, node);
13541 var placeholder = document.createElement('span');
13542 placeholder.className = 'roo-tpl-' + tpl.value;
13543 node.parentNode.replaceChild(placeholder, node);
13546 // parent now sees '{domtplXXXX}
13547 this.iterChild(node,this.compileNode);
13549 // we should now have node body...
13550 var div = document.createElement('div');
13551 div.appendChild(node);
13553 // this has the unfortunate side effect of converting tagged attributes
13554 // eg. href="{...}" into %7C...%7D
13555 // this has been fixed by searching for those combo's although it's a bit hacky..
13558 tpl.body = div.innerHTML;
13565 switch (tpl.value) {
13566 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
13567 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
13568 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
13573 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13577 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13581 tpl.id = tpl.value; // replace non characters???
13587 this.tpls.push(tpl);
13597 * Compile a segment of the template into a 'sub-template'
13603 compileTpl : function(tpl)
13605 var fm = Roo.util.Format;
13606 var useF = this.disableFormats !== true;
13608 var sep = Roo.isGecko ? "+\n" : ",\n";
13610 var undef = function(str) {
13611 Roo.debug && Roo.log("Property not found :" + str);
13615 //Roo.log(tpl.body);
13619 var fn = function(m, lbrace, name, format, args)
13622 //Roo.log(arguments);
13623 args = args ? args.replace(/\\'/g,"'") : args;
13624 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
13625 if (typeof(format) == 'undefined') {
13626 format = 'htmlEncode';
13628 if (format == 'raw' ) {
13632 if(name.substr(0, 6) == 'domtpl'){
13633 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
13636 // build an array of options to determine if value is undefined..
13638 // basically get 'xxxx.yyyy' then do
13639 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
13640 // (function () { Roo.log("Property not found"); return ''; })() :
13645 Roo.each(name.split('.'), function(st) {
13646 lookfor += (lookfor.length ? '.': '') + st;
13647 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
13650 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
13653 if(format && useF){
13655 args = args ? ',' + args : "";
13657 if(format.substr(0, 5) != "this."){
13658 format = "fm." + format + '(';
13660 format = 'this.call("'+ format.substr(5) + '", ';
13664 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
13667 if (args && args.length) {
13668 // called with xxyx.yuu:(test,test)
13670 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
13672 // raw.. - :raw modifier..
13673 return "'"+ sep + udef_st + name + ")"+sep+"'";
13677 // branched to use + in gecko and [].join() in others
13679 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
13680 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
13683 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
13684 body.push(tpl.body.replace(/(\r\n|\n)/g,
13685 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
13686 body.push("'].join('');};};");
13687 body = body.join('');
13690 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
13692 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
13699 * same as applyTemplate, except it's done to one of the subTemplates
13700 * when using named templates, you can do:
13702 * var str = pl.applySubTemplate('your-name', values);
13705 * @param {Number} id of the template
13706 * @param {Object} values to apply to template
13707 * @param {Object} parent (normaly the instance of this object)
13709 applySubTemplate : function(id, values, parent)
13713 var t = this.tpls[id];
13717 if(t.ifCall && !t.ifCall.call(this, values, parent)){
13718 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
13722 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
13729 if(t.execCall && t.execCall.call(this, values, parent)){
13733 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
13739 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
13740 parent = t.target ? values : parent;
13741 if(t.forCall && vs instanceof Array){
13743 for(var i = 0, len = vs.length; i < len; i++){
13745 buf[buf.length] = t.compiled.call(this, vs[i], parent);
13747 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
13749 //Roo.log(t.compiled);
13753 return buf.join('');
13756 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
13761 return t.compiled.call(this, vs, parent);
13763 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
13765 //Roo.log(t.compiled);
13773 applyTemplate : function(values){
13774 return this.master.compiled.call(this, values, {});
13775 //var s = this.subs;
13778 apply : function(){
13779 return this.applyTemplate.apply(this, arguments);
13784 Roo.DomTemplate.from = function(el){
13785 el = Roo.getDom(el);
13786 return new Roo.Domtemplate(el.value || el.innerHTML);
13789 * Ext JS Library 1.1.1
13790 * Copyright(c) 2006-2007, Ext JS, LLC.
13792 * Originally Released Under LGPL - original licence link has changed is not relivant.
13795 * <script type="text/javascript">
13799 * @class Roo.util.DelayedTask
13800 * Provides a convenient method of performing setTimeout where a new
13801 * timeout cancels the old timeout. An example would be performing validation on a keypress.
13802 * You can use this class to buffer
13803 * the keypress events for a certain number of milliseconds, and perform only if they stop
13804 * for that amount of time.
13805 * @constructor The parameters to this constructor serve as defaults and are not required.
13806 * @param {Function} fn (optional) The default function to timeout
13807 * @param {Object} scope (optional) The default scope of that timeout
13808 * @param {Array} args (optional) The default Array of arguments
13810 Roo.util.DelayedTask = function(fn, scope, args){
13811 var id = null, d, t;
13813 var call = function(){
13814 var now = new Date().getTime();
13818 fn.apply(scope, args || []);
13822 * Cancels any pending timeout and queues a new one
13823 * @param {Number} delay The milliseconds to delay
13824 * @param {Function} newFn (optional) Overrides function passed to constructor
13825 * @param {Object} newScope (optional) Overrides scope passed to constructor
13826 * @param {Array} newArgs (optional) Overrides args passed to constructor
13828 this.delay = function(delay, newFn, newScope, newArgs){
13829 if(id && delay != d){
13833 t = new Date().getTime();
13835 scope = newScope || scope;
13836 args = newArgs || args;
13838 id = setInterval(call, d);
13843 * Cancel the last queued timeout
13845 this.cancel = function(){
13853 * Ext JS Library 1.1.1
13854 * Copyright(c) 2006-2007, Ext JS, LLC.
13856 * Originally Released Under LGPL - original licence link has changed is not relivant.
13859 * <script type="text/javascript">
13862 * @class Roo.util.TaskRunner
13863 * Manage background tasks - not sure why this is better that setInterval?
13868 Roo.util.TaskRunner = function(interval){
13869 interval = interval || 10;
13870 var tasks = [], removeQueue = [];
13872 var running = false;
13874 var stopThread = function(){
13880 var startThread = function(){
13883 id = setInterval(runTasks, interval);
13887 var removeTask = function(task){
13888 removeQueue.push(task);
13894 var runTasks = function(){
13895 if(removeQueue.length > 0){
13896 for(var i = 0, len = removeQueue.length; i < len; i++){
13897 tasks.remove(removeQueue[i]);
13900 if(tasks.length < 1){
13905 var now = new Date().getTime();
13906 for(var i = 0, len = tasks.length; i < len; ++i){
13908 var itime = now - t.taskRunTime;
13909 if(t.interval <= itime){
13910 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
13911 t.taskRunTime = now;
13912 if(rt === false || t.taskRunCount === t.repeat){
13917 if(t.duration && t.duration <= (now - t.taskStartTime)){
13924 * Queues a new task.
13925 * @param {Object} task
13927 * Task property : interval = how frequent to run.
13928 * Task object should implement
13930 * Task object may implement
13931 * function onStop()
13933 this.start = function(task){
13935 task.taskStartTime = new Date().getTime();
13936 task.taskRunTime = 0;
13937 task.taskRunCount = 0;
13943 * @param {Object} task
13945 this.stop = function(task){
13952 this.stopAll = function(){
13954 for(var i = 0, len = tasks.length; i < len; i++){
13955 if(tasks[i].onStop){
13964 Roo.TaskMgr = new Roo.util.TaskRunner();/*
13966 * Ext JS Library 1.1.1
13967 * Copyright(c) 2006-2007, Ext JS, LLC.
13969 * Originally Released Under LGPL - original licence link has changed is not relivant.
13972 * <script type="text/javascript">
13977 * @class Roo.util.MixedCollection
13978 * @extends Roo.util.Observable
13979 * A Collection class that maintains both numeric indexes and keys and exposes events.
13981 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
13982 * collection (defaults to false)
13983 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
13984 * and return the key value for that item. This is used when available to look up the key on items that
13985 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
13986 * equivalent to providing an implementation for the {@link #getKey} method.
13988 Roo.util.MixedCollection = function(allowFunctions, keyFn){
13996 * Fires when the collection is cleared.
14001 * Fires when an item is added to the collection.
14002 * @param {Number} index The index at which the item was added.
14003 * @param {Object} o The item added.
14004 * @param {String} key The key associated with the added item.
14009 * Fires when an item is replaced in the collection.
14010 * @param {String} key he key associated with the new added.
14011 * @param {Object} old The item being replaced.
14012 * @param {Object} new The new item.
14017 * Fires when an item is removed from the collection.
14018 * @param {Object} o The item being removed.
14019 * @param {String} key (optional) The key associated with the removed item.
14024 this.allowFunctions = allowFunctions === true;
14026 this.getKey = keyFn;
14028 Roo.util.MixedCollection.superclass.constructor.call(this);
14031 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
14032 allowFunctions : false,
14035 * Adds an item to the collection.
14036 * @param {String} key The key to associate with the item
14037 * @param {Object} o The item to add.
14038 * @return {Object} The item added.
14040 add : function(key, o){
14041 if(arguments.length == 1){
14043 key = this.getKey(o);
14045 if(typeof key == "undefined" || key === null){
14047 this.items.push(o);
14048 this.keys.push(null);
14050 var old = this.map[key];
14052 return this.replace(key, o);
14055 this.items.push(o);
14057 this.keys.push(key);
14059 this.fireEvent("add", this.length-1, o, key);
14064 * MixedCollection has a generic way to fetch keys if you implement getKey.
14067 var mc = new Roo.util.MixedCollection();
14068 mc.add(someEl.dom.id, someEl);
14069 mc.add(otherEl.dom.id, otherEl);
14073 var mc = new Roo.util.MixedCollection();
14074 mc.getKey = function(el){
14080 // or via the constructor
14081 var mc = new Roo.util.MixedCollection(false, function(el){
14087 * @param o {Object} The item for which to find the key.
14088 * @return {Object} The key for the passed item.
14090 getKey : function(o){
14095 * Replaces an item in the collection.
14096 * @param {String} key The key associated with the item to replace, or the item to replace.
14097 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
14098 * @return {Object} The new item.
14100 replace : function(key, o){
14101 if(arguments.length == 1){
14103 key = this.getKey(o);
14105 var old = this.item(key);
14106 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
14107 return this.add(key, o);
14109 var index = this.indexOfKey(key);
14110 this.items[index] = o;
14112 this.fireEvent("replace", key, old, o);
14117 * Adds all elements of an Array or an Object to the collection.
14118 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
14119 * an Array of values, each of which are added to the collection.
14121 addAll : function(objs){
14122 if(arguments.length > 1 || objs instanceof Array){
14123 var args = arguments.length > 1 ? arguments : objs;
14124 for(var i = 0, len = args.length; i < len; i++){
14128 for(var key in objs){
14129 if(this.allowFunctions || typeof objs[key] != "function"){
14130 this.add(key, objs[key]);
14137 * Executes the specified function once for every item in the collection, passing each
14138 * item as the first and only parameter. returning false from the function will stop the iteration.
14139 * @param {Function} fn The function to execute for each item.
14140 * @param {Object} scope (optional) The scope in which to execute the function.
14142 each : function(fn, scope){
14143 var items = [].concat(this.items); // each safe for removal
14144 for(var i = 0, len = items.length; i < len; i++){
14145 if(fn.call(scope || items[i], items[i], i, len) === false){
14152 * Executes the specified function once for every key in the collection, passing each
14153 * key, and its associated item as the first two parameters.
14154 * @param {Function} fn The function to execute for each item.
14155 * @param {Object} scope (optional) The scope in which to execute the function.
14157 eachKey : function(fn, scope){
14158 for(var i = 0, len = this.keys.length; i < len; i++){
14159 fn.call(scope || window, this.keys[i], this.items[i], i, len);
14164 * Returns the first item in the collection which elicits a true return value from the
14165 * passed selection function.
14166 * @param {Function} fn The selection function to execute for each item.
14167 * @param {Object} scope (optional) The scope in which to execute the function.
14168 * @return {Object} The first item in the collection which returned true from the selection function.
14170 find : function(fn, scope){
14171 for(var i = 0, len = this.items.length; i < len; i++){
14172 if(fn.call(scope || window, this.items[i], this.keys[i])){
14173 return this.items[i];
14180 * Inserts an item at the specified index in the collection.
14181 * @param {Number} index The index to insert the item at.
14182 * @param {String} key The key to associate with the new item, or the item itself.
14183 * @param {Object} o (optional) If the second parameter was a key, the new item.
14184 * @return {Object} The item inserted.
14186 insert : function(index, key, o){
14187 if(arguments.length == 2){
14189 key = this.getKey(o);
14191 if(index >= this.length){
14192 return this.add(key, o);
14195 this.items.splice(index, 0, o);
14196 if(typeof key != "undefined" && key != null){
14199 this.keys.splice(index, 0, key);
14200 this.fireEvent("add", index, o, key);
14205 * Removed an item from the collection.
14206 * @param {Object} o The item to remove.
14207 * @return {Object} The item removed.
14209 remove : function(o){
14210 return this.removeAt(this.indexOf(o));
14214 * Remove an item from a specified index in the collection.
14215 * @param {Number} index The index within the collection of the item to remove.
14217 removeAt : function(index){
14218 if(index < this.length && index >= 0){
14220 var o = this.items[index];
14221 this.items.splice(index, 1);
14222 var key = this.keys[index];
14223 if(typeof key != "undefined"){
14224 delete this.map[key];
14226 this.keys.splice(index, 1);
14227 this.fireEvent("remove", o, key);
14232 * Removed an item associated with the passed key fom the collection.
14233 * @param {String} key The key of the item to remove.
14235 removeKey : function(key){
14236 return this.removeAt(this.indexOfKey(key));
14240 * Returns the number of items in the collection.
14241 * @return {Number} the number of items in the collection.
14243 getCount : function(){
14244 return this.length;
14248 * Returns index within the collection of the passed Object.
14249 * @param {Object} o The item to find the index of.
14250 * @return {Number} index of the item.
14252 indexOf : function(o){
14253 if(!this.items.indexOf){
14254 for(var i = 0, len = this.items.length; i < len; i++){
14255 if(this.items[i] == o) {
14261 return this.items.indexOf(o);
14266 * Returns index within the collection of the passed key.
14267 * @param {String} key The key to find the index of.
14268 * @return {Number} index of the key.
14270 indexOfKey : function(key){
14271 if(!this.keys.indexOf){
14272 for(var i = 0, len = this.keys.length; i < len; i++){
14273 if(this.keys[i] == key) {
14279 return this.keys.indexOf(key);
14284 * Returns the item associated with the passed key OR index. Key has priority over index.
14285 * @param {String/Number} key The key or index of the item.
14286 * @return {Object} The item associated with the passed key.
14288 item : function(key){
14289 if (key === 'length') {
14292 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
14293 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
14297 * Returns the item at the specified index.
14298 * @param {Number} index The index of the item.
14301 itemAt : function(index){
14302 return this.items[index];
14306 * Returns the item associated with the passed key.
14307 * @param {String/Number} key The key of the item.
14308 * @return {Object} The item associated with the passed key.
14310 key : function(key){
14311 return this.map[key];
14315 * Returns true if the collection contains the passed Object as an item.
14316 * @param {Object} o The Object to look for in the collection.
14317 * @return {Boolean} True if the collection contains the Object as an item.
14319 contains : function(o){
14320 return this.indexOf(o) != -1;
14324 * Returns true if the collection contains the passed Object as a key.
14325 * @param {String} key The key to look for in the collection.
14326 * @return {Boolean} True if the collection contains the Object as a key.
14328 containsKey : function(key){
14329 return typeof this.map[key] != "undefined";
14333 * Removes all items from the collection.
14335 clear : function(){
14340 this.fireEvent("clear");
14344 * Returns the first item in the collection.
14345 * @return {Object} the first item in the collection..
14347 first : function(){
14348 return this.items[0];
14352 * Returns the last item in the collection.
14353 * @return {Object} the last item in the collection..
14356 return this.items[this.length-1];
14359 _sort : function(property, dir, fn){
14360 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
14361 fn = fn || function(a, b){
14364 var c = [], k = this.keys, items = this.items;
14365 for(var i = 0, len = items.length; i < len; i++){
14366 c[c.length] = {key: k[i], value: items[i], index: i};
14368 c.sort(function(a, b){
14369 var v = fn(a[property], b[property]) * dsc;
14371 v = (a.index < b.index ? -1 : 1);
14375 for(var i = 0, len = c.length; i < len; i++){
14376 items[i] = c[i].value;
14379 this.fireEvent("sort", this);
14383 * Sorts this collection with the passed comparison function
14384 * @param {String} direction (optional) "ASC" or "DESC"
14385 * @param {Function} fn (optional) comparison function
14387 sort : function(dir, fn){
14388 this._sort("value", dir, fn);
14392 * Sorts this collection by keys
14393 * @param {String} direction (optional) "ASC" or "DESC"
14394 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
14396 keySort : function(dir, fn){
14397 this._sort("key", dir, fn || function(a, b){
14398 return String(a).toUpperCase()-String(b).toUpperCase();
14403 * Returns a range of items in this collection
14404 * @param {Number} startIndex (optional) defaults to 0
14405 * @param {Number} endIndex (optional) default to the last item
14406 * @return {Array} An array of items
14408 getRange : function(start, end){
14409 var items = this.items;
14410 if(items.length < 1){
14413 start = start || 0;
14414 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
14417 for(var i = start; i <= end; i++) {
14418 r[r.length] = items[i];
14421 for(var i = start; i >= end; i--) {
14422 r[r.length] = items[i];
14429 * Filter the <i>objects</i> in this collection by a specific property.
14430 * Returns a new collection that has been filtered.
14431 * @param {String} property A property on your objects
14432 * @param {String/RegExp} value Either string that the property values
14433 * should start with or a RegExp to test against the property
14434 * @return {MixedCollection} The new filtered collection
14436 filter : function(property, value){
14437 if(!value.exec){ // not a regex
14438 value = String(value);
14439 if(value.length == 0){
14440 return this.clone();
14442 value = new RegExp("^" + Roo.escapeRe(value), "i");
14444 return this.filterBy(function(o){
14445 return o && value.test(o[property]);
14450 * Filter by a function. * Returns a new collection that has been filtered.
14451 * The passed function will be called with each
14452 * object in the collection. If the function returns true, the value is included
14453 * otherwise it is filtered.
14454 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
14455 * @param {Object} scope (optional) The scope of the function (defaults to this)
14456 * @return {MixedCollection} The new filtered collection
14458 filterBy : function(fn, scope){
14459 var r = new Roo.util.MixedCollection();
14460 r.getKey = this.getKey;
14461 var k = this.keys, it = this.items;
14462 for(var i = 0, len = it.length; i < len; i++){
14463 if(fn.call(scope||this, it[i], k[i])){
14464 r.add(k[i], it[i]);
14471 * Creates a duplicate of this collection
14472 * @return {MixedCollection}
14474 clone : function(){
14475 var r = new Roo.util.MixedCollection();
14476 var k = this.keys, it = this.items;
14477 for(var i = 0, len = it.length; i < len; i++){
14478 r.add(k[i], it[i]);
14480 r.getKey = this.getKey;
14485 * Returns the item associated with the passed key or index.
14487 * @param {String/Number} key The key or index of the item.
14488 * @return {Object} The item associated with the passed key.
14490 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
14492 * Ext JS Library 1.1.1
14493 * Copyright(c) 2006-2007, Ext JS, LLC.
14495 * Originally Released Under LGPL - original licence link has changed is not relivant.
14498 * <script type="text/javascript">
14501 * @class Roo.util.JSON
14502 * Modified version of Douglas Crockford"s json.js that doesn"t
14503 * mess with the Object prototype
14504 * http://www.json.org/js.html
14507 Roo.util.JSON = new (function(){
14508 var useHasOwn = {}.hasOwnProperty ? true : false;
14510 // crashes Safari in some instances
14511 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
14513 var pad = function(n) {
14514 return n < 10 ? "0" + n : n;
14527 var encodeString = function(s){
14528 if (/["\\\x00-\x1f]/.test(s)) {
14529 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
14534 c = b.charCodeAt();
14536 Math.floor(c / 16).toString(16) +
14537 (c % 16).toString(16);
14540 return '"' + s + '"';
14543 var encodeArray = function(o){
14544 var a = ["["], b, i, l = o.length, v;
14545 for (i = 0; i < l; i += 1) {
14547 switch (typeof v) {
14556 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
14564 var encodeDate = function(o){
14565 return '"' + o.getFullYear() + "-" +
14566 pad(o.getMonth() + 1) + "-" +
14567 pad(o.getDate()) + "T" +
14568 pad(o.getHours()) + ":" +
14569 pad(o.getMinutes()) + ":" +
14570 pad(o.getSeconds()) + '"';
14574 * Encodes an Object, Array or other value
14575 * @param {Mixed} o The variable to encode
14576 * @return {String} The JSON string
14578 this.encode = function(o)
14580 // should this be extended to fully wrap stringify..
14582 if(typeof o == "undefined" || o === null){
14584 }else if(o instanceof Array){
14585 return encodeArray(o);
14586 }else if(o instanceof Date){
14587 return encodeDate(o);
14588 }else if(typeof o == "string"){
14589 return encodeString(o);
14590 }else if(typeof o == "number"){
14591 return isFinite(o) ? String(o) : "null";
14592 }else if(typeof o == "boolean"){
14595 var a = ["{"], b, i, v;
14597 if(!useHasOwn || o.hasOwnProperty(i)) {
14599 switch (typeof v) {
14608 a.push(this.encode(i), ":",
14609 v === null ? "null" : this.encode(v));
14620 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
14621 * @param {String} json The JSON string
14622 * @return {Object} The resulting object
14624 this.decode = function(json){
14626 return /** eval:var:json */ eval("(" + json + ')');
14630 * Shorthand for {@link Roo.util.JSON#encode}
14631 * @member Roo encode
14633 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
14635 * Shorthand for {@link Roo.util.JSON#decode}
14636 * @member Roo decode
14638 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
14641 * Ext JS Library 1.1.1
14642 * Copyright(c) 2006-2007, Ext JS, LLC.
14644 * Originally Released Under LGPL - original licence link has changed is not relivant.
14647 * <script type="text/javascript">
14651 * @class Roo.util.Format
14652 * Reusable data formatting functions
14655 Roo.util.Format = function(){
14656 var trimRe = /^\s+|\s+$/g;
14659 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
14660 * @param {String} value The string to truncate
14661 * @param {Number} length The maximum length to allow before truncating
14662 * @return {String} The converted text
14664 ellipsis : function(value, len){
14665 if(value && value.length > len){
14666 return value.substr(0, len-3)+"...";
14672 * Checks a reference and converts it to empty string if it is undefined
14673 * @param {Mixed} value Reference to check
14674 * @return {Mixed} Empty string if converted, otherwise the original value
14676 undef : function(value){
14677 return typeof value != "undefined" ? value : "";
14681 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
14682 * @param {String} value The string to encode
14683 * @return {String} The encoded text
14685 htmlEncode : function(value){
14686 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
14690 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
14691 * @param {String} value The string to decode
14692 * @return {String} The decoded text
14694 htmlDecode : function(value){
14695 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
14699 * Trims any whitespace from either side of a string
14700 * @param {String} value The text to trim
14701 * @return {String} The trimmed text
14703 trim : function(value){
14704 return String(value).replace(trimRe, "");
14708 * Returns a substring from within an original string
14709 * @param {String} value The original text
14710 * @param {Number} start The start index of the substring
14711 * @param {Number} length The length of the substring
14712 * @return {String} The substring
14714 substr : function(value, start, length){
14715 return String(value).substr(start, length);
14719 * Converts a string to all lower case letters
14720 * @param {String} value The text to convert
14721 * @return {String} The converted text
14723 lowercase : function(value){
14724 return String(value).toLowerCase();
14728 * Converts a string to all upper case letters
14729 * @param {String} value The text to convert
14730 * @return {String} The converted text
14732 uppercase : function(value){
14733 return String(value).toUpperCase();
14737 * Converts the first character only of a string to upper case
14738 * @param {String} value The text to convert
14739 * @return {String} The converted text
14741 capitalize : function(value){
14742 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
14746 call : function(value, fn){
14747 if(arguments.length > 2){
14748 var args = Array.prototype.slice.call(arguments, 2);
14749 args.unshift(value);
14751 return /** eval:var:value */ eval(fn).apply(window, args);
14753 /** eval:var:value */
14754 return /** eval:var:value */ eval(fn).call(window, value);
14760 * safer version of Math.toFixed..??/
14761 * @param {Number/String} value The numeric value to format
14762 * @param {Number/String} value Decimal places
14763 * @return {String} The formatted currency string
14765 toFixed : function(v, n)
14767 // why not use to fixed - precision is buggered???
14769 return Math.round(v-0);
14771 var fact = Math.pow(10,n+1);
14772 v = (Math.round((v-0)*fact))/fact;
14773 var z = (''+fact).substring(2);
14774 if (v == Math.floor(v)) {
14775 return Math.floor(v) + '.' + z;
14778 // now just padd decimals..
14779 var ps = String(v).split('.');
14780 var fd = (ps[1] + z);
14781 var r = fd.substring(0,n);
14782 var rm = fd.substring(n);
14784 return ps[0] + '.' + r;
14786 r*=1; // turn it into a number;
14788 if (String(r).length != n) {
14791 r = String(r).substring(1); // chop the end off.
14794 return ps[0] + '.' + r;
14799 * Format a number as US currency
14800 * @param {Number/String} value The numeric value to format
14801 * @return {String} The formatted currency string
14803 usMoney : function(v){
14804 return '$' + Roo.util.Format.number(v);
14809 * eventually this should probably emulate php's number_format
14810 * @param {Number/String} value The numeric value to format
14811 * @param {Number} decimals number of decimal places
14812 * @param {String} delimiter for thousands (default comma)
14813 * @return {String} The formatted currency string
14815 number : function(v, decimals, thousandsDelimiter)
14817 // multiply and round.
14818 decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
14819 thousandsDelimiter = typeof(thousandsDelimiter) == 'undefined' ? ',' : thousandsDelimiter;
14821 var mul = Math.pow(10, decimals);
14822 var zero = String(mul).substring(1);
14823 v = (Math.round((v-0)*mul))/mul;
14825 // if it's '0' number.. then
14827 //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
14829 var ps = v.split('.');
14832 var r = /(\d+)(\d{3})/;
14835 if(thousandsDelimiter.length != 0) {
14836 whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsDelimiter );
14841 (decimals ? ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
14842 // does not have decimals
14843 (decimals ? ('.' + zero) : '');
14846 return whole + sub ;
14850 * Parse a value into a formatted date using the specified format pattern.
14851 * @param {Mixed} value The value to format
14852 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
14853 * @return {String} The formatted date string
14855 date : function(v, format){
14859 if(!(v instanceof Date)){
14860 v = new Date(Date.parse(v));
14862 return v.dateFormat(format || Roo.util.Format.defaults.date);
14866 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
14867 * @param {String} format Any valid date format string
14868 * @return {Function} The date formatting function
14870 dateRenderer : function(format){
14871 return function(v){
14872 return Roo.util.Format.date(v, format);
14877 stripTagsRE : /<\/?[^>]+>/gi,
14880 * Strips all HTML tags
14881 * @param {Mixed} value The text from which to strip tags
14882 * @return {String} The stripped text
14884 stripTags : function(v){
14885 return !v ? v : String(v).replace(this.stripTagsRE, "");
14889 * Size in Mb,Gb etc.
14890 * @param {Number} value The number to be formated
14891 * @param {number} decimals how many decimal places
14892 * @return {String} the formated string
14894 size : function(value, decimals)
14896 var sizes = ['b', 'k', 'M', 'G', 'T'];
14900 var i = parseInt(Math.floor(Math.log(value) / Math.log(1024)));
14901 return Roo.util.Format.number(value/ Math.pow(1024, i) ,decimals) + sizes[i];
14908 Roo.util.Format.defaults = {
14912 * Ext JS Library 1.1.1
14913 * Copyright(c) 2006-2007, Ext JS, LLC.
14915 * Originally Released Under LGPL - original licence link has changed is not relivant.
14918 * <script type="text/javascript">
14925 * @class Roo.MasterTemplate
14926 * @extends Roo.Template
14927 * Provides a template that can have child templates. The syntax is:
14929 var t = new Roo.MasterTemplate(
14930 '<select name="{name}">',
14931 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
14934 t.add('options', {value: 'foo', text: 'bar'});
14935 // or you can add multiple child elements in one shot
14936 t.addAll('options', [
14937 {value: 'foo', text: 'bar'},
14938 {value: 'foo2', text: 'bar2'},
14939 {value: 'foo3', text: 'bar3'}
14941 // then append, applying the master template values
14942 t.append('my-form', {name: 'my-select'});
14944 * A name attribute for the child template is not required if you have only one child
14945 * template or you want to refer to them by index.
14947 Roo.MasterTemplate = function(){
14948 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
14949 this.originalHtml = this.html;
14951 var m, re = this.subTemplateRe;
14954 while(m = re.exec(this.html)){
14955 var name = m[1], content = m[2];
14960 tpl : new Roo.Template(content)
14963 st[name] = st[subIndex];
14965 st[subIndex].tpl.compile();
14966 st[subIndex].tpl.call = this.call.createDelegate(this);
14969 this.subCount = subIndex;
14972 Roo.extend(Roo.MasterTemplate, Roo.Template, {
14974 * The regular expression used to match sub templates
14978 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
14981 * Applies the passed values to a child template.
14982 * @param {String/Number} name (optional) The name or index of the child template
14983 * @param {Array/Object} values The values to be applied to the template
14984 * @return {MasterTemplate} this
14986 add : function(name, values){
14987 if(arguments.length == 1){
14988 values = arguments[0];
14991 var s = this.subs[name];
14992 s.buffer[s.buffer.length] = s.tpl.apply(values);
14997 * Applies all the passed values to a child template.
14998 * @param {String/Number} name (optional) The name or index of the child template
14999 * @param {Array} values The values to be applied to the template, this should be an array of objects.
15000 * @param {Boolean} reset (optional) True to reset the template first
15001 * @return {MasterTemplate} this
15003 fill : function(name, values, reset){
15005 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
15013 for(var i = 0, len = values.length; i < len; i++){
15014 this.add(name, values[i]);
15020 * Resets the template for reuse
15021 * @return {MasterTemplate} this
15023 reset : function(){
15025 for(var i = 0; i < this.subCount; i++){
15031 applyTemplate : function(values){
15033 var replaceIndex = -1;
15034 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
15035 return s[++replaceIndex].buffer.join("");
15037 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
15040 apply : function(){
15041 return this.applyTemplate.apply(this, arguments);
15044 compile : function(){return this;}
15048 * Alias for fill().
15051 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
15053 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
15054 * var tpl = Roo.MasterTemplate.from('element-id');
15055 * @param {String/HTMLElement} el
15056 * @param {Object} config
15059 Roo.MasterTemplate.from = function(el, config){
15060 el = Roo.getDom(el);
15061 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
15064 * Ext JS Library 1.1.1
15065 * Copyright(c) 2006-2007, Ext JS, LLC.
15067 * Originally Released Under LGPL - original licence link has changed is not relivant.
15070 * <script type="text/javascript">
15075 * @class Roo.util.CSS
15076 * Utility class for manipulating CSS rules
15080 Roo.util.CSS = function(){
15082 var doc = document;
15084 var camelRe = /(-[a-z])/gi;
15085 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
15089 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
15090 * tag and appended to the HEAD of the document.
15091 * @param {String|Object} cssText The text containing the css rules
15092 * @param {String} id An id to add to the stylesheet for later removal
15093 * @return {StyleSheet}
15095 createStyleSheet : function(cssText, id){
15097 var head = doc.getElementsByTagName("head")[0];
15098 var nrules = doc.createElement("style");
15099 nrules.setAttribute("type", "text/css");
15101 nrules.setAttribute("id", id);
15103 if (typeof(cssText) != 'string') {
15104 // support object maps..
15105 // not sure if this a good idea..
15106 // perhaps it should be merged with the general css handling
15107 // and handle js style props.
15108 var cssTextNew = [];
15109 for(var n in cssText) {
15111 for(var k in cssText[n]) {
15112 citems.push( k + ' : ' +cssText[n][k] + ';' );
15114 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
15117 cssText = cssTextNew.join("\n");
15123 head.appendChild(nrules);
15124 ss = nrules.styleSheet;
15125 ss.cssText = cssText;
15128 nrules.appendChild(doc.createTextNode(cssText));
15130 nrules.cssText = cssText;
15132 head.appendChild(nrules);
15133 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
15135 this.cacheStyleSheet(ss);
15140 * Removes a style or link tag by id
15141 * @param {String} id The id of the tag
15143 removeStyleSheet : function(id){
15144 var existing = doc.getElementById(id);
15146 existing.parentNode.removeChild(existing);
15151 * Dynamically swaps an existing stylesheet reference for a new one
15152 * @param {String} id The id of an existing link tag to remove
15153 * @param {String} url The href of the new stylesheet to include
15155 swapStyleSheet : function(id, url){
15156 this.removeStyleSheet(id);
15157 var ss = doc.createElement("link");
15158 ss.setAttribute("rel", "stylesheet");
15159 ss.setAttribute("type", "text/css");
15160 ss.setAttribute("id", id);
15161 ss.setAttribute("href", url);
15162 doc.getElementsByTagName("head")[0].appendChild(ss);
15166 * Refresh the rule cache if you have dynamically added stylesheets
15167 * @return {Object} An object (hash) of rules indexed by selector
15169 refreshCache : function(){
15170 return this.getRules(true);
15174 cacheStyleSheet : function(stylesheet){
15178 try{// try catch for cross domain access issue
15179 var ssRules = stylesheet.cssRules || stylesheet.rules;
15180 for(var j = ssRules.length-1; j >= 0; --j){
15181 rules[ssRules[j].selectorText] = ssRules[j];
15187 * Gets all css rules for the document
15188 * @param {Boolean} refreshCache true to refresh the internal cache
15189 * @return {Object} An object (hash) of rules indexed by selector
15191 getRules : function(refreshCache){
15192 if(rules == null || refreshCache){
15194 var ds = doc.styleSheets;
15195 for(var i =0, len = ds.length; i < len; i++){
15197 this.cacheStyleSheet(ds[i]);
15205 * Gets an an individual CSS rule by selector(s)
15206 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
15207 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
15208 * @return {CSSRule} The CSS rule or null if one is not found
15210 getRule : function(selector, refreshCache){
15211 var rs = this.getRules(refreshCache);
15212 if(!(selector instanceof Array)){
15213 return rs[selector];
15215 for(var i = 0; i < selector.length; i++){
15216 if(rs[selector[i]]){
15217 return rs[selector[i]];
15225 * Updates a rule property
15226 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
15227 * @param {String} property The css property
15228 * @param {String} value The new value for the property
15229 * @return {Boolean} true If a rule was found and updated
15231 updateRule : function(selector, property, value){
15232 if(!(selector instanceof Array)){
15233 var rule = this.getRule(selector);
15235 rule.style[property.replace(camelRe, camelFn)] = value;
15239 for(var i = 0; i < selector.length; i++){
15240 if(this.updateRule(selector[i], property, value)){
15250 * Ext JS Library 1.1.1
15251 * Copyright(c) 2006-2007, Ext JS, LLC.
15253 * Originally Released Under LGPL - original licence link has changed is not relivant.
15256 * <script type="text/javascript">
15262 * @class Roo.util.ClickRepeater
15263 * @extends Roo.util.Observable
15265 * A wrapper class which can be applied to any element. Fires a "click" event while the
15266 * mouse is pressed. The interval between firings may be specified in the config but
15267 * defaults to 10 milliseconds.
15269 * Optionally, a CSS class may be applied to the element during the time it is pressed.
15271 * @cfg {String/HTMLElement/Element} el The element to act as a button.
15272 * @cfg {Number} delay The initial delay before the repeating event begins firing.
15273 * Similar to an autorepeat key delay.
15274 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
15275 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
15276 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
15277 * "interval" and "delay" are ignored. "immediate" is honored.
15278 * @cfg {Boolean} preventDefault True to prevent the default click event
15279 * @cfg {Boolean} stopDefault True to stop the default click event
15282 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
15283 * 2007-02-02 jvs Renamed to ClickRepeater
15284 * 2007-02-03 jvs Modifications for FF Mac and Safari
15287 * @param {String/HTMLElement/Element} el The element to listen on
15288 * @param {Object} config
15290 Roo.util.ClickRepeater = function(el, config)
15292 this.el = Roo.get(el);
15293 this.el.unselectable();
15295 Roo.apply(this, config);
15300 * Fires when the mouse button is depressed.
15301 * @param {Roo.util.ClickRepeater} this
15303 "mousedown" : true,
15306 * Fires on a specified interval during the time the element is pressed.
15307 * @param {Roo.util.ClickRepeater} this
15312 * Fires when the mouse key is released.
15313 * @param {Roo.util.ClickRepeater} this
15318 this.el.on("mousedown", this.handleMouseDown, this);
15319 if(this.preventDefault || this.stopDefault){
15320 this.el.on("click", function(e){
15321 if(this.preventDefault){
15322 e.preventDefault();
15324 if(this.stopDefault){
15330 // allow inline handler
15332 this.on("click", this.handler, this.scope || this);
15335 Roo.util.ClickRepeater.superclass.constructor.call(this);
15338 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
15341 preventDefault : true,
15342 stopDefault : false,
15346 handleMouseDown : function(){
15347 clearTimeout(this.timer);
15349 if(this.pressClass){
15350 this.el.addClass(this.pressClass);
15352 this.mousedownTime = new Date();
15354 Roo.get(document).on("mouseup", this.handleMouseUp, this);
15355 this.el.on("mouseout", this.handleMouseOut, this);
15357 this.fireEvent("mousedown", this);
15358 this.fireEvent("click", this);
15360 this.timer = this.click.defer(this.delay || this.interval, this);
15364 click : function(){
15365 this.fireEvent("click", this);
15366 this.timer = this.click.defer(this.getInterval(), this);
15370 getInterval: function(){
15371 if(!this.accelerate){
15372 return this.interval;
15374 var pressTime = this.mousedownTime.getElapsed();
15375 if(pressTime < 500){
15377 }else if(pressTime < 1700){
15379 }else if(pressTime < 2600){
15381 }else if(pressTime < 3500){
15383 }else if(pressTime < 4400){
15385 }else if(pressTime < 5300){
15387 }else if(pressTime < 6200){
15395 handleMouseOut : function(){
15396 clearTimeout(this.timer);
15397 if(this.pressClass){
15398 this.el.removeClass(this.pressClass);
15400 this.el.on("mouseover", this.handleMouseReturn, this);
15404 handleMouseReturn : function(){
15405 this.el.un("mouseover", this.handleMouseReturn);
15406 if(this.pressClass){
15407 this.el.addClass(this.pressClass);
15413 handleMouseUp : function(){
15414 clearTimeout(this.timer);
15415 this.el.un("mouseover", this.handleMouseReturn);
15416 this.el.un("mouseout", this.handleMouseOut);
15417 Roo.get(document).un("mouseup", this.handleMouseUp);
15418 this.el.removeClass(this.pressClass);
15419 this.fireEvent("mouseup", this);
15422 * @class Roo.util.Clipboard
15428 Roo.util.Clipboard = {
15430 * Writes a string to the clipboard - using the Clipboard API if https, otherwise using text area.
15431 * @param {String} text to copy to clipboard
15433 write : function(text) {
15434 // navigator clipboard api needs a secure context (https)
15435 if (navigator.clipboard && window.isSecureContext) {
15436 // navigator clipboard api method'
15437 navigator.clipboard.writeText(text);
15440 // text area method
15441 var ta = document.createElement("textarea");
15443 // make the textarea out of viewport
15444 ta.style.position = "fixed";
15445 ta.style.left = "-999999px";
15446 ta.style.top = "-999999px";
15447 document.body.appendChild(ta);
15450 document.execCommand('copy');
15460 * Ext JS Library 1.1.1
15461 * Copyright(c) 2006-2007, Ext JS, LLC.
15463 * Originally Released Under LGPL - original licence link has changed is not relivant.
15466 * <script type="text/javascript">
15471 * @class Roo.KeyNav
15472 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
15473 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
15474 * way to implement custom navigation schemes for any UI component.</p>
15475 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
15476 * pageUp, pageDown, del, home, end. Usage:</p>
15478 var nav = new Roo.KeyNav("my-element", {
15479 "left" : function(e){
15480 this.moveLeft(e.ctrlKey);
15482 "right" : function(e){
15483 this.moveRight(e.ctrlKey);
15485 "enter" : function(e){
15492 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15493 * @param {Object} config The config
15495 Roo.KeyNav = function(el, config){
15496 this.el = Roo.get(el);
15497 Roo.apply(this, config);
15498 if(!this.disabled){
15499 this.disabled = true;
15504 Roo.KeyNav.prototype = {
15506 * @cfg {Boolean} disabled
15507 * True to disable this KeyNav instance (defaults to false)
15511 * @cfg {String} defaultEventAction
15512 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
15513 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
15514 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
15516 defaultEventAction: "stopEvent",
15518 * @cfg {Boolean} forceKeyDown
15519 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
15520 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
15521 * handle keydown instead of keypress.
15523 forceKeyDown : false,
15526 prepareEvent : function(e){
15527 var k = e.getKey();
15528 var h = this.keyToHandler[k];
15529 //if(h && this[h]){
15530 // e.stopPropagation();
15532 if(Roo.isSafari && h && k >= 37 && k <= 40){
15538 relay : function(e){
15539 var k = e.getKey();
15540 var h = this.keyToHandler[k];
15542 if(this.doRelay(e, this[h], h) !== true){
15543 e[this.defaultEventAction]();
15549 doRelay : function(e, h, hname){
15550 return h.call(this.scope || this, e);
15553 // possible handlers
15567 // quick lookup hash
15584 * Enable this KeyNav
15586 enable: function(){
15588 // ie won't do special keys on keypress, no one else will repeat keys with keydown
15589 // the EventObject will normalize Safari automatically
15590 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15591 this.el.on("keydown", this.relay, this);
15593 this.el.on("keydown", this.prepareEvent, this);
15594 this.el.on("keypress", this.relay, this);
15596 this.disabled = false;
15601 * Disable this KeyNav
15603 disable: function(){
15604 if(!this.disabled){
15605 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15606 this.el.un("keydown", this.relay);
15608 this.el.un("keydown", this.prepareEvent);
15609 this.el.un("keypress", this.relay);
15611 this.disabled = true;
15616 * Ext JS Library 1.1.1
15617 * Copyright(c) 2006-2007, Ext JS, LLC.
15619 * Originally Released Under LGPL - original licence link has changed is not relivant.
15622 * <script type="text/javascript">
15627 * @class Roo.KeyMap
15628 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
15629 * The constructor accepts the same config object as defined by {@link #addBinding}.
15630 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
15631 * combination it will call the function with this signature (if the match is a multi-key
15632 * combination the callback will still be called only once): (String key, Roo.EventObject e)
15633 * A KeyMap can also handle a string representation of keys.<br />
15636 // map one key by key code
15637 var map = new Roo.KeyMap("my-element", {
15638 key: 13, // or Roo.EventObject.ENTER
15643 // map multiple keys to one action by string
15644 var map = new Roo.KeyMap("my-element", {
15650 // map multiple keys to multiple actions by strings and array of codes
15651 var map = new Roo.KeyMap("my-element", [
15654 fn: function(){ alert("Return was pressed"); }
15657 fn: function(){ alert('a, b or c was pressed'); }
15662 fn: function(){ alert('Control + shift + tab was pressed.'); }
15666 * <b>Note: A KeyMap starts enabled</b>
15668 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15669 * @param {Object} config The config (see {@link #addBinding})
15670 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
15672 Roo.KeyMap = function(el, config, eventName){
15673 this.el = Roo.get(el);
15674 this.eventName = eventName || "keydown";
15675 this.bindings = [];
15677 this.addBinding(config);
15682 Roo.KeyMap.prototype = {
15684 * True to stop the event from bubbling and prevent the default browser action if the
15685 * key was handled by the KeyMap (defaults to false)
15691 * Add a new binding to this KeyMap. The following config object properties are supported:
15693 Property Type Description
15694 ---------- --------------- ----------------------------------------------------------------------
15695 key String/Array A single keycode or an array of keycodes to handle
15696 shift Boolean True to handle key only when shift is pressed (defaults to false)
15697 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
15698 alt Boolean True to handle key only when alt is pressed (defaults to false)
15699 fn Function The function to call when KeyMap finds the expected key combination
15700 scope Object The scope of the callback function
15706 var map = new Roo.KeyMap(document, {
15707 key: Roo.EventObject.ENTER,
15712 //Add a new binding to the existing KeyMap later
15720 * @param {Object/Array} config A single KeyMap config or an array of configs
15722 addBinding : function(config){
15723 if(config instanceof Array){
15724 for(var i = 0, len = config.length; i < len; i++){
15725 this.addBinding(config[i]);
15729 var keyCode = config.key,
15730 shift = config.shift,
15731 ctrl = config.ctrl,
15734 scope = config.scope;
15735 if(typeof keyCode == "string"){
15737 var keyString = keyCode.toUpperCase();
15738 for(var j = 0, len = keyString.length; j < len; j++){
15739 ks.push(keyString.charCodeAt(j));
15743 var keyArray = keyCode instanceof Array;
15744 var handler = function(e){
15745 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
15746 var k = e.getKey();
15748 for(var i = 0, len = keyCode.length; i < len; i++){
15749 if(keyCode[i] == k){
15750 if(this.stopEvent){
15753 fn.call(scope || window, k, e);
15759 if(this.stopEvent){
15762 fn.call(scope || window, k, e);
15767 this.bindings.push(handler);
15771 * Shorthand for adding a single key listener
15772 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
15773 * following options:
15774 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
15775 * @param {Function} fn The function to call
15776 * @param {Object} scope (optional) The scope of the function
15778 on : function(key, fn, scope){
15779 var keyCode, shift, ctrl, alt;
15780 if(typeof key == "object" && !(key instanceof Array)){
15799 handleKeyDown : function(e){
15800 if(this.enabled){ //just in case
15801 var b = this.bindings;
15802 for(var i = 0, len = b.length; i < len; i++){
15803 b[i].call(this, e);
15809 * Returns true if this KeyMap is enabled
15810 * @return {Boolean}
15812 isEnabled : function(){
15813 return this.enabled;
15817 * Enables this KeyMap
15819 enable: function(){
15821 this.el.on(this.eventName, this.handleKeyDown, this);
15822 this.enabled = true;
15827 * Disable this KeyMap
15829 disable: function(){
15831 this.el.removeListener(this.eventName, this.handleKeyDown, this);
15832 this.enabled = false;
15837 * Ext JS Library 1.1.1
15838 * Copyright(c) 2006-2007, Ext JS, LLC.
15840 * Originally Released Under LGPL - original licence link has changed is not relivant.
15843 * <script type="text/javascript">
15848 * @class Roo.util.TextMetrics
15849 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
15850 * wide, in pixels, a given block of text will be.
15853 Roo.util.TextMetrics = function(){
15857 * Measures the size of the specified text
15858 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
15859 * that can affect the size of the rendered text
15860 * @param {String} text The text to measure
15861 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
15862 * in order to accurately measure the text height
15863 * @return {Object} An object containing the text's size {width: (width), height: (height)}
15865 measure : function(el, text, fixedWidth){
15867 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
15870 shared.setFixedWidth(fixedWidth || 'auto');
15871 return shared.getSize(text);
15875 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
15876 * the overhead of multiple calls to initialize the style properties on each measurement.
15877 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
15878 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
15879 * in order to accurately measure the text height
15880 * @return {Roo.util.TextMetrics.Instance} instance The new instance
15882 createInstance : function(el, fixedWidth){
15883 return Roo.util.TextMetrics.Instance(el, fixedWidth);
15889 * @class Roo.util.TextMetrics.Instance
15890 * Instance of TextMetrics Calcuation
15892 * Create a new TextMetrics Instance
15893 * @param {Object} bindto
15894 * @param {Boolean} fixedWidth
15897 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth)
15899 var ml = new Roo.Element(document.createElement('div'));
15900 document.body.appendChild(ml.dom);
15901 ml.position('absolute');
15902 ml.setLeftTop(-1000, -1000);
15906 ml.setWidth(fixedWidth);
15911 * Returns the size of the specified text based on the internal element's style and width properties
15912 * @param {String} text The text to measure
15913 * @return {Object} An object containing the text's size {width: (width), height: (height)}
15915 getSize : function(text){
15917 var s = ml.getSize();
15923 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
15924 * that can affect the size of the rendered text
15925 * @param {String/HTMLElement} el The element, dom node or id
15927 bind : function(el){
15929 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
15934 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
15935 * to set a fixed width in order to accurately measure the text height.
15936 * @param {Number} width The width to set on the element
15938 setFixedWidth : function(width){
15939 ml.setWidth(width);
15943 * Returns the measured width of the specified text
15944 * @param {String} text The text to measure
15945 * @return {Number} width The width in pixels
15947 getWidth : function(text){
15948 ml.dom.style.width = 'auto';
15949 return this.getSize(text).width;
15953 * Returns the measured height of the specified text. For multiline text, be sure to call
15954 * {@link #setFixedWidth} if necessary.
15955 * @param {String} text The text to measure
15956 * @return {Number} height The height in pixels
15958 getHeight : function(text){
15959 return this.getSize(text).height;
15963 instance.bind(bindTo);
15968 // backwards compat
15969 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
15971 * Ext JS Library 1.1.1
15972 * Copyright(c) 2006-2007, Ext JS, LLC.
15974 * Originally Released Under LGPL - original licence link has changed is not relivant.
15977 * <script type="text/javascript">
15981 * @class Roo.state.Provider
15982 * Abstract base class for state provider implementations. This class provides methods
15983 * for encoding and decoding <b>typed</b> variables including dates and defines the
15984 * Provider interface.
15986 Roo.state.Provider = function(){
15988 * @event statechange
15989 * Fires when a state change occurs.
15990 * @param {Provider} this This state provider
15991 * @param {String} key The state key which was changed
15992 * @param {String} value The encoded value for the state
15995 "statechange": true
15998 Roo.state.Provider.superclass.constructor.call(this);
16000 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
16002 * Returns the current value for a key
16003 * @param {String} name The key name
16004 * @param {Mixed} defaultValue A default value to return if the key's value is not found
16005 * @return {Mixed} The state data
16007 get : function(name, defaultValue){
16008 return typeof this.state[name] == "undefined" ?
16009 defaultValue : this.state[name];
16013 * Clears a value from the state
16014 * @param {String} name The key name
16016 clear : function(name){
16017 delete this.state[name];
16018 this.fireEvent("statechange", this, name, null);
16022 * Sets the value for a key
16023 * @param {String} name The key name
16024 * @param {Mixed} value The value to set
16026 set : function(name, value){
16027 this.state[name] = value;
16028 this.fireEvent("statechange", this, name, value);
16032 * Decodes a string previously encoded with {@link #encodeValue}.
16033 * @param {String} value The value to decode
16034 * @return {Mixed} The decoded value
16036 decodeValue : function(cookie){
16037 var re = /^(a|n|d|b|s|o)\:(.*)$/;
16038 var matches = re.exec(unescape(cookie));
16039 if(!matches || !matches[1]) {
16040 return; // non state cookie
16042 var type = matches[1];
16043 var v = matches[2];
16046 return parseFloat(v);
16048 return new Date(Date.parse(v));
16053 var values = v.split("^");
16054 for(var i = 0, len = values.length; i < len; i++){
16055 all.push(this.decodeValue(values[i]));
16060 var values = v.split("^");
16061 for(var i = 0, len = values.length; i < len; i++){
16062 var kv = values[i].split("=");
16063 all[kv[0]] = this.decodeValue(kv[1]);
16072 * Encodes a value including type information. Decode with {@link #decodeValue}.
16073 * @param {Mixed} value The value to encode
16074 * @return {String} The encoded value
16076 encodeValue : function(v){
16078 if(typeof v == "number"){
16080 }else if(typeof v == "boolean"){
16081 enc = "b:" + (v ? "1" : "0");
16082 }else if(v instanceof Date){
16083 enc = "d:" + v.toGMTString();
16084 }else if(v instanceof Array){
16086 for(var i = 0, len = v.length; i < len; i++){
16087 flat += this.encodeValue(v[i]);
16093 }else if(typeof v == "object"){
16096 if(typeof v[key] != "function"){
16097 flat += key + "=" + this.encodeValue(v[key]) + "^";
16100 enc = "o:" + flat.substring(0, flat.length-1);
16104 return escape(enc);
16110 * Ext JS Library 1.1.1
16111 * Copyright(c) 2006-2007, Ext JS, LLC.
16113 * Originally Released Under LGPL - original licence link has changed is not relivant.
16116 * <script type="text/javascript">
16119 * @class Roo.state.Manager
16120 * This is the global state manager. By default all components that are "state aware" check this class
16121 * for state information if you don't pass them a custom state provider. In order for this class
16122 * to be useful, it must be initialized with a provider when your application initializes.
16124 // in your initialization function
16126 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
16128 // supposed you have a {@link Roo.BorderLayout}
16129 var layout = new Roo.BorderLayout(...);
16130 layout.restoreState();
16131 // or a {Roo.BasicDialog}
16132 var dialog = new Roo.BasicDialog(...);
16133 dialog.restoreState();
16137 Roo.state.Manager = function(){
16138 var provider = new Roo.state.Provider();
16142 * Configures the default state provider for your application
16143 * @param {Provider} stateProvider The state provider to set
16145 setProvider : function(stateProvider){
16146 provider = stateProvider;
16150 * Returns the current value for a key
16151 * @param {String} name The key name
16152 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
16153 * @return {Mixed} The state data
16155 get : function(key, defaultValue){
16156 return provider.get(key, defaultValue);
16160 * Sets the value for a key
16161 * @param {String} name The key name
16162 * @param {Mixed} value The state data
16164 set : function(key, value){
16165 provider.set(key, value);
16169 * Clears a value from the state
16170 * @param {String} name The key name
16172 clear : function(key){
16173 provider.clear(key);
16177 * Gets the currently configured state provider
16178 * @return {Provider} The state provider
16180 getProvider : function(){
16187 * Ext JS Library 1.1.1
16188 * Copyright(c) 2006-2007, Ext JS, LLC.
16190 * Originally Released Under LGPL - original licence link has changed is not relivant.
16193 * <script type="text/javascript">
16196 * @class Roo.state.CookieProvider
16197 * @extends Roo.state.Provider
16198 * The default Provider implementation which saves state via cookies.
16201 var cp = new Roo.state.CookieProvider({
16203 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
16204 domain: "roojs.com"
16206 Roo.state.Manager.setProvider(cp);
16208 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
16209 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
16210 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
16211 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
16212 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
16213 * domain the page is running on including the 'www' like 'www.roojs.com')
16214 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
16216 * Create a new CookieProvider
16217 * @param {Object} config The configuration object
16219 Roo.state.CookieProvider = function(config){
16220 Roo.state.CookieProvider.superclass.constructor.call(this);
16222 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
16223 this.domain = null;
16224 this.secure = false;
16225 Roo.apply(this, config);
16226 this.state = this.readCookies();
16229 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
16231 set : function(name, value){
16232 if(typeof value == "undefined" || value === null){
16236 this.setCookie(name, value);
16237 Roo.state.CookieProvider.superclass.set.call(this, name, value);
16241 clear : function(name){
16242 this.clearCookie(name);
16243 Roo.state.CookieProvider.superclass.clear.call(this, name);
16247 readCookies : function(){
16249 var c = document.cookie + ";";
16250 var re = /\s?(.*?)=(.*?);/g;
16252 while((matches = re.exec(c)) != null){
16253 var name = matches[1];
16254 var value = matches[2];
16255 if(name && name.substring(0,3) == "ys-"){
16256 cookies[name.substr(3)] = this.decodeValue(value);
16263 setCookie : function(name, value){
16264 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
16265 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
16266 ((this.path == null) ? "" : ("; path=" + this.path)) +
16267 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16268 ((this.secure == true) ? "; secure" : "");
16272 clearCookie : function(name){
16273 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
16274 ((this.path == null) ? "" : ("; path=" + this.path)) +
16275 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16276 ((this.secure == true) ? "; secure" : "");
16280 * Ext JS Library 1.1.1
16281 * Copyright(c) 2006-2007, Ext JS, LLC.
16283 * Originally Released Under LGPL - original licence link has changed is not relivant.
16286 * <script type="text/javascript">
16291 * @class Roo.ComponentMgr
16292 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
16295 Roo.ComponentMgr = function(){
16296 var all = new Roo.util.MixedCollection();
16300 * Registers a component.
16301 * @param {Roo.Component} c The component
16303 register : function(c){
16308 * Unregisters a component.
16309 * @param {Roo.Component} c The component
16311 unregister : function(c){
16316 * Returns a component by id
16317 * @param {String} id The component id
16319 get : function(id){
16320 return all.get(id);
16324 * Registers a function that will be called when a specified component is added to ComponentMgr
16325 * @param {String} id The component id
16326 * @param {Funtction} fn The callback function
16327 * @param {Object} scope The scope of the callback
16329 onAvailable : function(id, fn, scope){
16330 all.on("add", function(index, o){
16332 fn.call(scope || o, o);
16333 all.un("add", fn, scope);
16340 * Ext JS Library 1.1.1
16341 * Copyright(c) 2006-2007, Ext JS, LLC.
16343 * Originally Released Under LGPL - original licence link has changed is not relivant.
16346 * <script type="text/javascript">
16350 * @class Roo.Component
16351 * @extends Roo.util.Observable
16352 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
16353 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
16354 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
16355 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
16356 * All visual components (widgets) that require rendering into a layout should subclass Component.
16358 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
16359 * 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
16360 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
16362 Roo.Component = function(config){
16363 config = config || {};
16364 if(config.tagName || config.dom || typeof config == "string"){ // element object
16365 config = {el: config, id: config.id || config};
16367 this.initialConfig = config;
16369 Roo.apply(this, config);
16373 * Fires after the component is disabled.
16374 * @param {Roo.Component} this
16379 * Fires after the component is enabled.
16380 * @param {Roo.Component} this
16384 * @event beforeshow
16385 * Fires before the component is shown. Return false to stop the show.
16386 * @param {Roo.Component} this
16391 * Fires after the component is shown.
16392 * @param {Roo.Component} this
16396 * @event beforehide
16397 * Fires before the component is hidden. Return false to stop the hide.
16398 * @param {Roo.Component} this
16403 * Fires after the component is hidden.
16404 * @param {Roo.Component} this
16408 * @event beforerender
16409 * Fires before the component is rendered. Return false to stop the render.
16410 * @param {Roo.Component} this
16412 beforerender : true,
16415 * Fires after the component is rendered.
16416 * @param {Roo.Component} this
16420 * @event beforedestroy
16421 * Fires before the component is destroyed. Return false to stop the destroy.
16422 * @param {Roo.Component} this
16424 beforedestroy : true,
16427 * Fires after the component is destroyed.
16428 * @param {Roo.Component} this
16433 this.id = "roo-comp-" + (++Roo.Component.AUTO_ID);
16435 Roo.ComponentMgr.register(this);
16436 Roo.Component.superclass.constructor.call(this);
16437 this.initComponent();
16438 if(this.renderTo){ // not supported by all components yet. use at your own risk!
16439 this.render(this.renderTo);
16440 delete this.renderTo;
16445 Roo.Component.AUTO_ID = 1000;
16447 Roo.extend(Roo.Component, Roo.util.Observable, {
16449 * @scope Roo.Component.prototype
16451 * true if this component is hidden. Read-only.
16456 * true if this component is disabled. Read-only.
16461 * true if this component has been rendered. Read-only.
16465 /** @cfg {String} disableClass
16466 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
16468 disabledClass : "x-item-disabled",
16469 /** @cfg {Boolean} allowDomMove
16470 * Whether the component can move the Dom node when rendering (defaults to true).
16472 allowDomMove : true,
16473 /** @cfg {String} hideMode (display|visibility)
16474 * How this component should hidden. Supported values are
16475 * "visibility" (css visibility), "offsets" (negative offset position) and
16476 * "display" (css display) - defaults to "display".
16478 hideMode: 'display',
16481 ctype : "Roo.Component",
16484 * @cfg {String} actionMode
16485 * which property holds the element that used for hide() / show() / disable() / enable()
16486 * default is 'el' for forms you probably want to set this to fieldEl
16491 getActionEl : function(){
16492 return this[this.actionMode];
16495 initComponent : Roo.emptyFn,
16497 * If this is a lazy rendering component, render it to its container element.
16498 * @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.
16500 render : function(container, position){
16506 if(this.fireEvent("beforerender", this) === false){
16510 if(!container && this.el){
16511 this.el = Roo.get(this.el);
16512 container = this.el.dom.parentNode;
16513 this.allowDomMove = false;
16515 this.container = Roo.get(container);
16516 this.rendered = true;
16517 if(position !== undefined){
16518 if(typeof position == 'number'){
16519 position = this.container.dom.childNodes[position];
16521 position = Roo.getDom(position);
16524 this.onRender(this.container, position || null);
16526 this.el.addClass(this.cls);
16530 this.el.applyStyles(this.style);
16533 this.fireEvent("render", this);
16534 this.afterRender(this.container);
16547 // default function is not really useful
16548 onRender : function(ct, position){
16550 this.el = Roo.get(this.el);
16551 if(this.allowDomMove !== false){
16552 ct.dom.insertBefore(this.el.dom, position);
16558 getAutoCreate : function(){
16559 var cfg = typeof this.autoCreate == "object" ?
16560 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
16561 if(this.id && !cfg.id){
16568 afterRender : Roo.emptyFn,
16571 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
16572 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
16574 destroy : function(){
16575 if(this.fireEvent("beforedestroy", this) !== false){
16576 this.purgeListeners();
16577 this.beforeDestroy();
16579 this.el.removeAllListeners();
16581 if(this.actionMode == "container"){
16582 this.container.remove();
16586 Roo.ComponentMgr.unregister(this);
16587 this.fireEvent("destroy", this);
16592 beforeDestroy : function(){
16597 onDestroy : function(){
16602 * Returns the underlying {@link Roo.Element}.
16603 * @return {Roo.Element} The element
16605 getEl : function(){
16610 * Returns the id of this component.
16613 getId : function(){
16618 * Try to focus this component.
16619 * @param {Boolean} selectText True to also select the text in this component (if applicable)
16620 * @return {Roo.Component} this
16622 focus : function(selectText){
16625 if(selectText === true){
16626 this.el.dom.select();
16641 * Disable this component.
16642 * @return {Roo.Component} this
16644 disable : function(){
16648 this.disabled = true;
16649 this.fireEvent("disable", this);
16654 onDisable : function(){
16655 this.getActionEl().addClass(this.disabledClass);
16656 this.el.dom.disabled = true;
16660 * Enable this component.
16661 * @return {Roo.Component} this
16663 enable : function(){
16667 this.disabled = false;
16668 this.fireEvent("enable", this);
16673 onEnable : function(){
16674 this.getActionEl().removeClass(this.disabledClass);
16675 this.el.dom.disabled = false;
16679 * Convenience function for setting disabled/enabled by boolean.
16680 * @param {Boolean} disabled
16682 setDisabled : function(disabled){
16683 this[disabled ? "disable" : "enable"]();
16687 * Show this component.
16688 * @return {Roo.Component} this
16691 if(this.fireEvent("beforeshow", this) !== false){
16692 this.hidden = false;
16696 this.fireEvent("show", this);
16702 onShow : function(){
16703 var ae = this.getActionEl();
16704 if(this.hideMode == 'visibility'){
16705 ae.dom.style.visibility = "visible";
16706 }else if(this.hideMode == 'offsets'){
16707 ae.removeClass('x-hidden');
16709 ae.dom.style.display = "";
16714 * Hide this component.
16715 * @return {Roo.Component} this
16718 if(this.fireEvent("beforehide", this) !== false){
16719 this.hidden = true;
16723 this.fireEvent("hide", this);
16729 onHide : function(){
16730 var ae = this.getActionEl();
16731 if(this.hideMode == 'visibility'){
16732 ae.dom.style.visibility = "hidden";
16733 }else if(this.hideMode == 'offsets'){
16734 ae.addClass('x-hidden');
16736 ae.dom.style.display = "none";
16741 * Convenience function to hide or show this component by boolean.
16742 * @param {Boolean} visible True to show, false to hide
16743 * @return {Roo.Component} this
16745 setVisible: function(visible){
16755 * Returns true if this component is visible.
16757 isVisible : function(){
16758 return this.getActionEl().isVisible();
16761 cloneConfig : function(overrides){
16762 overrides = overrides || {};
16763 var id = overrides.id || Roo.id();
16764 var cfg = Roo.applyIf(overrides, this.initialConfig);
16765 cfg.id = id; // prevent dup id
16766 return new this.constructor(cfg);
16770 * Ext JS Library 1.1.1
16771 * Copyright(c) 2006-2007, Ext JS, LLC.
16773 * Originally Released Under LGPL - original licence link has changed is not relivant.
16776 * <script type="text/javascript">
16780 * @class Roo.BoxComponent
16781 * @extends Roo.Component
16782 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
16783 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
16784 * container classes should subclass BoxComponent so that they will work consistently when nested within other Roo
16785 * layout containers.
16787 * @param {Roo.Element/String/Object} config The configuration options.
16789 Roo.BoxComponent = function(config){
16790 Roo.Component.call(this, config);
16794 * Fires after the component is resized.
16795 * @param {Roo.Component} this
16796 * @param {Number} adjWidth The box-adjusted width that was set
16797 * @param {Number} adjHeight The box-adjusted height that was set
16798 * @param {Number} rawWidth The width that was originally specified
16799 * @param {Number} rawHeight The height that was originally specified
16804 * Fires after the component is moved.
16805 * @param {Roo.Component} this
16806 * @param {Number} x The new x position
16807 * @param {Number} y The new y position
16813 Roo.extend(Roo.BoxComponent, Roo.Component, {
16814 // private, set in afterRender to signify that the component has been rendered
16816 // private, used to defer height settings to subclasses
16817 deferHeight: false,
16818 /** @cfg {Number} width
16819 * width (optional) size of component
16821 /** @cfg {Number} height
16822 * height (optional) size of component
16826 * Sets the width and height of the component. This method fires the resize event. This method can accept
16827 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
16828 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
16829 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
16830 * @return {Roo.BoxComponent} this
16832 setSize : function(w, h){
16833 // support for standard size objects
16834 if(typeof w == 'object'){
16839 if(!this.boxReady){
16845 // prevent recalcs when not needed
16846 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
16849 this.lastSize = {width: w, height: h};
16851 var adj = this.adjustSize(w, h);
16852 var aw = adj.width, ah = adj.height;
16853 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
16854 var rz = this.getResizeEl();
16855 if(!this.deferHeight && aw !== undefined && ah !== undefined){
16856 rz.setSize(aw, ah);
16857 }else if(!this.deferHeight && ah !== undefined){
16859 }else if(aw !== undefined){
16862 this.onResize(aw, ah, w, h);
16863 this.fireEvent('resize', this, aw, ah, w, h);
16869 * Gets the current size of the component's underlying element.
16870 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
16872 getSize : function(){
16873 return this.el.getSize();
16877 * Gets the current XY position of the component's underlying element.
16878 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
16879 * @return {Array} The XY position of the element (e.g., [100, 200])
16881 getPosition : function(local){
16882 if(local === true){
16883 return [this.el.getLeft(true), this.el.getTop(true)];
16885 return this.xy || this.el.getXY();
16889 * Gets the current box measurements of the component's underlying element.
16890 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
16891 * @returns {Object} box An object in the format {x, y, width, height}
16893 getBox : function(local){
16894 var s = this.el.getSize();
16896 s.x = this.el.getLeft(true);
16897 s.y = this.el.getTop(true);
16899 var xy = this.xy || this.el.getXY();
16907 * Sets the current box measurements of the component's underlying element.
16908 * @param {Object} box An object in the format {x, y, width, height}
16909 * @returns {Roo.BoxComponent} this
16911 updateBox : function(box){
16912 this.setSize(box.width, box.height);
16913 this.setPagePosition(box.x, box.y);
16918 getResizeEl : function(){
16919 return this.resizeEl || this.el;
16923 getPositionEl : function(){
16924 return this.positionEl || this.el;
16928 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
16929 * This method fires the move event.
16930 * @param {Number} left The new left
16931 * @param {Number} top The new top
16932 * @returns {Roo.BoxComponent} this
16934 setPosition : function(x, y){
16937 if(!this.boxReady){
16940 var adj = this.adjustPosition(x, y);
16941 var ax = adj.x, ay = adj.y;
16943 var el = this.getPositionEl();
16944 if(ax !== undefined || ay !== undefined){
16945 if(ax !== undefined && ay !== undefined){
16946 el.setLeftTop(ax, ay);
16947 }else if(ax !== undefined){
16949 }else if(ay !== undefined){
16952 this.onPosition(ax, ay);
16953 this.fireEvent('move', this, ax, ay);
16959 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
16960 * This method fires the move event.
16961 * @param {Number} x The new x position
16962 * @param {Number} y The new y position
16963 * @returns {Roo.BoxComponent} this
16965 setPagePosition : function(x, y){
16968 if(!this.boxReady){
16971 if(x === undefined || y === undefined){ // cannot translate undefined points
16974 var p = this.el.translatePoints(x, y);
16975 this.setPosition(p.left, p.top);
16980 onRender : function(ct, position){
16981 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
16983 this.resizeEl = Roo.get(this.resizeEl);
16985 if(this.positionEl){
16986 this.positionEl = Roo.get(this.positionEl);
16991 afterRender : function(){
16992 Roo.BoxComponent.superclass.afterRender.call(this);
16993 this.boxReady = true;
16994 this.setSize(this.width, this.height);
16995 if(this.x || this.y){
16996 this.setPosition(this.x, this.y);
16998 if(this.pageX || this.pageY){
16999 this.setPagePosition(this.pageX, this.pageY);
17004 * Force the component's size to recalculate based on the underlying element's current height and width.
17005 * @returns {Roo.BoxComponent} this
17007 syncSize : function(){
17008 delete this.lastSize;
17009 this.setSize(this.el.getWidth(), this.el.getHeight());
17014 * Called after the component is resized, this method is empty by default but can be implemented by any
17015 * subclass that needs to perform custom logic after a resize occurs.
17016 * @param {Number} adjWidth The box-adjusted width that was set
17017 * @param {Number} adjHeight The box-adjusted height that was set
17018 * @param {Number} rawWidth The width that was originally specified
17019 * @param {Number} rawHeight The height that was originally specified
17021 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
17026 * Called after the component is moved, this method is empty by default but can be implemented by any
17027 * subclass that needs to perform custom logic after a move occurs.
17028 * @param {Number} x The new x position
17029 * @param {Number} y The new y position
17031 onPosition : function(x, y){
17036 adjustSize : function(w, h){
17037 if(this.autoWidth){
17040 if(this.autoHeight){
17043 return {width : w, height: h};
17047 adjustPosition : function(x, y){
17048 return {x : x, y: y};
17052 * Ext JS Library 1.1.1
17053 * Copyright(c) 2006-2007, Ext JS, LLC.
17055 * Originally Released Under LGPL - original licence link has changed is not relivant.
17058 * <script type="text/javascript">
17063 * @extends Roo.Element
17064 * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
17065 * automatic maintaining of shadow/shim positions.
17066 * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
17067 * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
17068 * you can pass a string with a CSS class name. False turns off the shadow.
17069 * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
17070 * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
17071 * @cfg {String} cls CSS class to add to the element
17072 * @cfg {Number} zindex Starting z-index (defaults to 11000)
17073 * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
17075 * @param {Object} config An object with config options.
17076 * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
17079 Roo.Layer = function(config, existingEl){
17080 config = config || {};
17081 var dh = Roo.DomHelper;
17082 var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
17084 this.dom = Roo.getDom(existingEl);
17087 var o = config.dh || {tag: "div", cls: "x-layer"};
17088 this.dom = dh.append(pel, o);
17091 this.addClass(config.cls);
17093 this.constrain = config.constrain !== false;
17094 this.visibilityMode = Roo.Element.VISIBILITY;
17096 this.id = this.dom.id = config.id;
17098 this.id = Roo.id(this.dom);
17100 this.zindex = config.zindex || this.getZIndex();
17101 this.position("absolute", this.zindex);
17103 this.shadowOffset = config.shadowOffset || 4;
17104 this.shadow = new Roo.Shadow({
17105 offset : this.shadowOffset,
17106 mode : config.shadow
17109 this.shadowOffset = 0;
17111 this.useShim = config.shim !== false && Roo.useShims;
17112 this.useDisplay = config.useDisplay;
17116 var supr = Roo.Element.prototype;
17118 // shims are shared among layer to keep from having 100 iframes
17121 Roo.extend(Roo.Layer, Roo.Element, {
17123 getZIndex : function(){
17124 return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
17127 getShim : function(){
17134 var shim = shims.shift();
17136 shim = this.createShim();
17137 shim.enableDisplayMode('block');
17138 shim.dom.style.display = 'none';
17139 shim.dom.style.visibility = 'visible';
17141 var pn = this.dom.parentNode;
17142 if(shim.dom.parentNode != pn){
17143 pn.insertBefore(shim.dom, this.dom);
17145 shim.setStyle('z-index', this.getZIndex()-2);
17150 hideShim : function(){
17152 this.shim.setDisplayed(false);
17153 shims.push(this.shim);
17158 disableShadow : function(){
17160 this.shadowDisabled = true;
17161 this.shadow.hide();
17162 this.lastShadowOffset = this.shadowOffset;
17163 this.shadowOffset = 0;
17167 enableShadow : function(show){
17169 this.shadowDisabled = false;
17170 this.shadowOffset = this.lastShadowOffset;
17171 delete this.lastShadowOffset;
17179 // this code can execute repeatedly in milliseconds (i.e. during a drag) so
17180 // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
17181 sync : function(doShow){
17182 var sw = this.shadow;
17183 if(!this.updating && this.isVisible() && (sw || this.useShim)){
17184 var sh = this.getShim();
17186 var w = this.getWidth(),
17187 h = this.getHeight();
17189 var l = this.getLeft(true),
17190 t = this.getTop(true);
17192 if(sw && !this.shadowDisabled){
17193 if(doShow && !sw.isVisible()){
17196 sw.realign(l, t, w, h);
17202 // fit the shim behind the shadow, so it is shimmed too
17203 var a = sw.adjusts, s = sh.dom.style;
17204 s.left = (Math.min(l, l+a.l))+"px";
17205 s.top = (Math.min(t, t+a.t))+"px";
17206 s.width = (w+a.w)+"px";
17207 s.height = (h+a.h)+"px";
17214 sh.setLeftTop(l, t);
17221 destroy : function(){
17224 this.shadow.hide();
17226 this.removeAllListeners();
17227 var pn = this.dom.parentNode;
17229 pn.removeChild(this.dom);
17231 Roo.Element.uncache(this.id);
17234 remove : function(){
17239 beginUpdate : function(){
17240 this.updating = true;
17244 endUpdate : function(){
17245 this.updating = false;
17250 hideUnders : function(negOffset){
17252 this.shadow.hide();
17258 constrainXY : function(){
17259 if(this.constrain){
17260 var vw = Roo.lib.Dom.getViewWidth(),
17261 vh = Roo.lib.Dom.getViewHeight();
17262 var s = Roo.get(document).getScroll();
17264 var xy = this.getXY();
17265 var x = xy[0], y = xy[1];
17266 var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
17267 // only move it if it needs it
17269 // first validate right/bottom
17270 if((x + w) > vw+s.left){
17271 x = vw - w - this.shadowOffset;
17274 if((y + h) > vh+s.top){
17275 y = vh - h - this.shadowOffset;
17278 // then make sure top/left isn't negative
17289 var ay = this.avoidY;
17290 if(y <= ay && (y+h) >= ay){
17296 supr.setXY.call(this, xy);
17302 isVisible : function(){
17303 return this.visible;
17307 showAction : function(){
17308 this.visible = true; // track visibility to prevent getStyle calls
17309 if(this.useDisplay === true){
17310 this.setDisplayed("");
17311 }else if(this.lastXY){
17312 supr.setXY.call(this, this.lastXY);
17313 }else if(this.lastLT){
17314 supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
17319 hideAction : function(){
17320 this.visible = false;
17321 if(this.useDisplay === true){
17322 this.setDisplayed(false);
17324 this.setLeftTop(-10000,-10000);
17328 // overridden Element method
17329 setVisible : function(v, a, d, c, e){
17334 var cb = function(){
17339 }.createDelegate(this);
17340 supr.setVisible.call(this, true, true, d, cb, e);
17343 this.hideUnders(true);
17352 }.createDelegate(this);
17354 supr.setVisible.call(this, v, a, d, cb, e);
17363 storeXY : function(xy){
17364 delete this.lastLT;
17368 storeLeftTop : function(left, top){
17369 delete this.lastXY;
17370 this.lastLT = [left, top];
17374 beforeFx : function(){
17375 this.beforeAction();
17376 return Roo.Layer.superclass.beforeFx.apply(this, arguments);
17380 afterFx : function(){
17381 Roo.Layer.superclass.afterFx.apply(this, arguments);
17382 this.sync(this.isVisible());
17386 beforeAction : function(){
17387 if(!this.updating && this.shadow){
17388 this.shadow.hide();
17392 // overridden Element method
17393 setLeft : function(left){
17394 this.storeLeftTop(left, this.getTop(true));
17395 supr.setLeft.apply(this, arguments);
17399 setTop : function(top){
17400 this.storeLeftTop(this.getLeft(true), top);
17401 supr.setTop.apply(this, arguments);
17405 setLeftTop : function(left, top){
17406 this.storeLeftTop(left, top);
17407 supr.setLeftTop.apply(this, arguments);
17411 setXY : function(xy, a, d, c, e){
17413 this.beforeAction();
17415 var cb = this.createCB(c);
17416 supr.setXY.call(this, xy, a, d, cb, e);
17423 createCB : function(c){
17434 // overridden Element method
17435 setX : function(x, a, d, c, e){
17436 this.setXY([x, this.getY()], a, d, c, e);
17439 // overridden Element method
17440 setY : function(y, a, d, c, e){
17441 this.setXY([this.getX(), y], a, d, c, e);
17444 // overridden Element method
17445 setSize : function(w, h, a, d, c, e){
17446 this.beforeAction();
17447 var cb = this.createCB(c);
17448 supr.setSize.call(this, w, h, a, d, cb, e);
17454 // overridden Element method
17455 setWidth : function(w, a, d, c, e){
17456 this.beforeAction();
17457 var cb = this.createCB(c);
17458 supr.setWidth.call(this, w, a, d, cb, e);
17464 // overridden Element method
17465 setHeight : function(h, a, d, c, e){
17466 this.beforeAction();
17467 var cb = this.createCB(c);
17468 supr.setHeight.call(this, h, a, d, cb, e);
17474 // overridden Element method
17475 setBounds : function(x, y, w, h, a, d, c, e){
17476 this.beforeAction();
17477 var cb = this.createCB(c);
17479 this.storeXY([x, y]);
17480 supr.setXY.call(this, [x, y]);
17481 supr.setSize.call(this, w, h, a, d, cb, e);
17484 supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
17490 * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
17491 * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
17492 * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
17493 * @param {Number} zindex The new z-index to set
17494 * @return {this} The Layer
17496 setZIndex : function(zindex){
17497 this.zindex = zindex;
17498 this.setStyle("z-index", zindex + 2);
17500 this.shadow.setZIndex(zindex + 1);
17503 this.shim.setStyle("z-index", zindex);
17508 * Original code for Roojs - LGPL
17509 * <script type="text/javascript">
17513 * @class Roo.XComponent
17514 * A delayed Element creator...
17515 * Or a way to group chunks of interface together.
17516 * technically this is a wrapper around a tree of Roo elements (which defines a 'module'),
17517 * used in conjunction with XComponent.build() it will create an instance of each element,
17518 * then call addxtype() to build the User interface.
17520 * Mypart.xyx = new Roo.XComponent({
17522 parent : 'Mypart.xyz', // empty == document.element.!!
17526 disabled : function() {}
17528 tree : function() { // return an tree of xtype declared components
17532 xtype : 'NestedLayoutPanel',
17539 * It can be used to build a big heiracy, with parent etc.
17540 * or you can just use this to render a single compoent to a dom element
17541 * MYPART.render(Roo.Element | String(id) | dom_element )
17548 * Roo is designed primarily as a single page application, so the UI build for a standard interface will
17549 * expect a single 'TOP' level module normally indicated by the 'parent' of the XComponent definition being defined as false.
17551 * Each sub module is expected to have a parent pointing to the class name of it's parent module.
17553 * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
17554 * - if mulitple topModules exist, the last one is defined as the top module.
17558 * When the top level or multiple modules are to embedded into a existing HTML page,
17559 * the parent element can container '#id' of the element where the module will be drawn.
17563 * Unlike classic Roo, the bootstrap tends not to be used as a single page.
17564 * it relies more on a include mechanism, where sub modules are included into an outer page.
17565 * This is normally managed by the builder tools using Roo.apply( options, Included.Sub.Module )
17567 * Bootstrap Roo Included elements
17569 * Our builder application needs the ability to preview these sub compoennts. They will normally have parent=false set,
17570 * hence confusing the component builder as it thinks there are multiple top level elements.
17572 * String Over-ride & Translations
17574 * Our builder application writes all the strings as _strings and _named_strings. This is to enable the translation of elements,
17575 * and also the 'overlaying of string values - needed when different versions of the same application with different text content
17576 * are needed. @see Roo.XComponent.overlayString
17580 * @extends Roo.util.Observable
17582 * @param cfg {Object} configuration of component
17585 Roo.XComponent = function(cfg) {
17586 Roo.apply(this, cfg);
17590 * Fires when this the componnt is built
17591 * @param {Roo.XComponent} c the component
17596 this.region = this.region || 'center'; // default..
17597 Roo.XComponent.register(this);
17598 this.modules = false;
17599 this.el = false; // where the layout goes..
17603 Roo.extend(Roo.XComponent, Roo.util.Observable, {
17606 * The created element (with Roo.factory())
17607 * @type {Roo.Layout}
17613 * for BC - use el in new code
17614 * @type {Roo.Layout}
17620 * for BC - use el in new code
17621 * @type {Roo.Layout}
17626 * @cfg {Function|boolean} disabled
17627 * If this module is disabled by some rule, return true from the funtion
17632 * @cfg {String} parent
17633 * Name of parent element which it get xtype added to..
17638 * @cfg {String} order
17639 * Used to set the order in which elements are created (usefull for multiple tabs)
17644 * @cfg {String} name
17645 * String to display while loading.
17649 * @cfg {String} region
17650 * Region to render component to (defaults to center)
17655 * @cfg {Array} items
17656 * A single item array - the first element is the root of the tree..
17657 * It's done this way to stay compatible with the Xtype system...
17663 * The method that retuns the tree of parts that make up this compoennt
17670 * render element to dom or tree
17671 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
17674 render : function(el)
17678 var hp = this.parent ? 1 : 0;
17679 Roo.debug && Roo.log(this);
17681 var tree = this._tree ? this._tree() : this.tree();
17684 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
17685 // if parent is a '#.....' string, then let's use that..
17686 var ename = this.parent.substr(1);
17687 this.parent = false;
17688 Roo.debug && Roo.log(ename);
17690 case 'bootstrap-body':
17691 if (typeof(tree.el) != 'undefined' && tree.el == document.body) {
17692 // this is the BorderLayout standard?
17693 this.parent = { el : true };
17696 if (["Nest", "Content", "Grid", "Tree"].indexOf(tree.xtype) > -1) {
17697 // need to insert stuff...
17699 el : new Roo.bootstrap.layout.Border({
17700 el : document.body,
17706 tabPosition: 'top',
17707 //resizeTabs: true,
17708 alwaysShowTabs: true,
17718 if (typeof(Roo.bootstrap.Body) != 'undefined' ) {
17719 this.parent = { el : new Roo.bootstrap.Body() };
17720 Roo.debug && Roo.log("setting el to doc body");
17723 throw "Container is bootstrap body, but Roo.bootstrap.Body is not defined";
17727 this.parent = { el : true};
17730 el = Roo.get(ename);
17731 if (typeof(Roo.bootstrap) != 'undefined' && tree['|xns'] == 'Roo.bootstrap') {
17732 this.parent = { el : true};
17739 if (!el && !this.parent) {
17740 Roo.debug && Roo.log("Warning - element can not be found :#" + ename );
17745 Roo.debug && Roo.log("EL:");
17746 Roo.debug && Roo.log(el);
17747 Roo.debug && Roo.log("this.parent.el:");
17748 Roo.debug && Roo.log(this.parent.el);
17751 // altertive root elements ??? - we need a better way to indicate these.
17752 var is_alt = Roo.XComponent.is_alt ||
17753 (typeof(tree.el) != 'undefined' && tree.el == document.body) ||
17754 (typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) ||
17755 (typeof(Roo.mailer) != 'undefined' && tree.xns == Roo.mailer) ;
17759 if (!this.parent && is_alt) {
17760 //el = Roo.get(document.body);
17761 this.parent = { el : true };
17766 if (!this.parent) {
17768 Roo.debug && Roo.log("no parent - creating one");
17770 el = el ? Roo.get(el) : false;
17772 if (typeof(Roo.BorderLayout) == 'undefined' ) {
17775 el : new Roo.bootstrap.layout.Border({
17776 el: el || document.body,
17782 tabPosition: 'top',
17783 //resizeTabs: true,
17784 alwaysShowTabs: false,
17787 overflow: 'visible'
17793 // it's a top level one..
17795 el : new Roo.BorderLayout(el || document.body, {
17800 tabPosition: 'top',
17801 //resizeTabs: true,
17802 alwaysShowTabs: el && hp? false : true,
17803 hideTabs: el || !hp ? true : false,
17811 if (!this.parent.el) {
17812 // probably an old style ctor, which has been disabled.
17816 // The 'tree' method is '_tree now'
17818 tree.region = tree.region || this.region;
17819 var is_body = false;
17820 if (this.parent.el === true) {
17821 // bootstrap... - body..
17825 this.parent.el = Roo.factory(tree);
17829 this.el = this.parent.el.addxtype(tree, undefined, is_body);
17830 this.fireEvent('built', this);
17832 this.panel = this.el;
17833 this.layout = this.panel.layout;
17834 this.parentLayout = this.parent.layout || false;
17840 Roo.apply(Roo.XComponent, {
17842 * @property hideProgress
17843 * true to disable the building progress bar.. usefull on single page renders.
17846 hideProgress : false,
17848 * @property buildCompleted
17849 * True when the builder has completed building the interface.
17852 buildCompleted : false,
17855 * @property topModule
17856 * the upper most module - uses document.element as it's constructor.
17863 * @property modules
17864 * array of modules to be created by registration system.
17865 * @type {Array} of Roo.XComponent
17870 * @property elmodules
17871 * array of modules to be created by which use #ID
17872 * @type {Array} of Roo.XComponent
17879 * Is an alternative Root - normally used by bootstrap or other systems,
17880 * where the top element in the tree can wrap 'body'
17881 * @type {boolean} (default false)
17886 * @property build_from_html
17887 * Build elements from html - used by bootstrap HTML stuff
17888 * - this is cleared after build is completed
17889 * @type {boolean} (default false)
17892 build_from_html : false,
17894 * Register components to be built later.
17896 * This solves the following issues
17897 * - Building is not done on page load, but after an authentication process has occured.
17898 * - Interface elements are registered on page load
17899 * - Parent Interface elements may not be loaded before child, so this handles that..
17906 module : 'Pman.Tab.projectMgr',
17908 parent : 'Pman.layout',
17909 disabled : false, // or use a function..
17912 * * @param {Object} details about module
17914 register : function(obj) {
17916 Roo.XComponent.event.fireEvent('register', obj);
17917 switch(typeof(obj.disabled) ) {
17923 if ( obj.disabled() ) {
17929 if (obj.disabled || obj.region == '#disabled') {
17935 this.modules.push(obj);
17939 * convert a string to an object..
17940 * eg. 'AAA.BBB' -> finds AAA.BBB
17944 toObject : function(str)
17946 if (!str || typeof(str) == 'object') {
17949 if (str.substring(0,1) == '#') {
17953 var ar = str.split('.');
17958 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
17960 throw "Module not found : " + str;
17964 throw "Module not found : " + str;
17966 Roo.each(ar, function(e) {
17967 if (typeof(o[e]) == 'undefined') {
17968 throw "Module not found : " + str;
17979 * move modules into their correct place in the tree..
17982 preBuild : function ()
17985 Roo.each(this.modules , function (obj)
17987 Roo.XComponent.event.fireEvent('beforebuild', obj);
17989 var opar = obj.parent;
17991 obj.parent = this.toObject(opar);
17993 Roo.debug && Roo.log("parent:toObject failed: " + e.toString());
17998 Roo.debug && Roo.log("GOT top level module");
17999 Roo.debug && Roo.log(obj);
18000 obj.modules = new Roo.util.MixedCollection(false,
18001 function(o) { return o.order + '' }
18003 this.topModule = obj;
18006 // parent is a string (usually a dom element name..)
18007 if (typeof(obj.parent) == 'string') {
18008 this.elmodules.push(obj);
18011 if (obj.parent.constructor != Roo.XComponent) {
18012 Roo.debug && Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
18014 if (!obj.parent.modules) {
18015 obj.parent.modules = new Roo.util.MixedCollection(false,
18016 function(o) { return o.order + '' }
18019 if (obj.parent.disabled) {
18020 obj.disabled = true;
18022 obj.parent.modules.add(obj);
18027 * make a list of modules to build.
18028 * @return {Array} list of modules.
18031 buildOrder : function()
18034 var cmp = function(a,b) {
18035 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
18037 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
18038 throw "No top level modules to build";
18041 // make a flat list in order of modules to build.
18042 var mods = this.topModule ? [ this.topModule ] : [];
18045 // elmodules (is a list of DOM based modules )
18046 Roo.each(this.elmodules, function(e) {
18048 if (!this.topModule &&
18049 typeof(e.parent) == 'string' &&
18050 e.parent.substring(0,1) == '#' &&
18051 Roo.get(e.parent.substr(1))
18054 _this.topModule = e;
18060 // add modules to their parents..
18061 var addMod = function(m) {
18062 Roo.debug && Roo.log("build Order: add: " + m.name);
18065 if (m.modules && !m.disabled) {
18066 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
18067 m.modules.keySort('ASC', cmp );
18068 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
18070 m.modules.each(addMod);
18072 Roo.debug && Roo.log("build Order: no child modules");
18074 // not sure if this is used any more..
18076 m.finalize.name = m.name + " (clean up) ";
18077 mods.push(m.finalize);
18081 if (this.topModule && this.topModule.modules) {
18082 this.topModule.modules.keySort('ASC', cmp );
18083 this.topModule.modules.each(addMod);
18089 * Build the registered modules.
18090 * @param {Object} parent element.
18091 * @param {Function} optional method to call after module has been added.
18095 build : function(opts)
18098 if (typeof(opts) != 'undefined') {
18099 Roo.apply(this,opts);
18103 var mods = this.buildOrder();
18105 //this.allmods = mods;
18106 //Roo.debug && Roo.log(mods);
18108 if (!mods.length) { // should not happen
18109 throw "NO modules!!!";
18113 var msg = "Building Interface...";
18114 // flash it up as modal - so we store the mask!?
18115 if (!this.hideProgress && Roo.MessageBox) {
18116 Roo.MessageBox.show({ title: 'loading' });
18117 Roo.MessageBox.show({
18118 title: "Please wait...",
18128 var total = mods.length;
18131 var progressRun = function() {
18132 if (!mods.length) {
18133 Roo.debug && Roo.log('hide?');
18134 if (!this.hideProgress && Roo.MessageBox) {
18135 Roo.MessageBox.hide();
18137 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
18139 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
18145 var m = mods.shift();
18148 Roo.debug && Roo.log(m);
18149 // not sure if this is supported any more.. - modules that are are just function
18150 if (typeof(m) == 'function') {
18152 return progressRun.defer(10, _this);
18156 msg = "Building Interface " + (total - mods.length) +
18158 (m.name ? (' - ' + m.name) : '');
18159 Roo.debug && Roo.log(msg);
18160 if (!_this.hideProgress && Roo.MessageBox) {
18161 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
18165 // is the module disabled?
18166 var disabled = (typeof(m.disabled) == 'function') ?
18167 m.disabled.call(m.module.disabled) : m.disabled;
18171 return progressRun(); // we do not update the display!
18179 // it's 10 on top level, and 1 on others??? why...
18180 return progressRun.defer(10, _this);
18183 progressRun.defer(1, _this);
18189 * Overlay a set of modified strings onto a component
18190 * This is dependant on our builder exporting the strings and 'named strings' elements.
18192 * @param {Object} element to overlay on - eg. Pman.Dialog.Login
18193 * @param {Object} associative array of 'named' string and it's new value.
18196 overlayStrings : function( component, strings )
18198 if (typeof(component['_named_strings']) == 'undefined') {
18199 throw "ERROR: component does not have _named_strings";
18201 for ( var k in strings ) {
18202 var md = typeof(component['_named_strings'][k]) == 'undefined' ? false : component['_named_strings'][k];
18203 if (md !== false) {
18204 component['_strings'][md] = strings[k];
18206 Roo.log('could not find named string: ' + k + ' in');
18207 Roo.log(component);
18222 * wrapper for event.on - aliased later..
18223 * Typically use to register a event handler for register:
18225 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
18234 Roo.XComponent.event = new Roo.util.Observable({
18238 * Fires when an Component is registered,
18239 * set the disable property on the Component to stop registration.
18240 * @param {Roo.XComponent} c the component being registerd.
18245 * @event beforebuild
18246 * Fires before each Component is built
18247 * can be used to apply permissions.
18248 * @param {Roo.XComponent} c the component being registerd.
18251 'beforebuild' : true,
18253 * @event buildcomplete
18254 * Fires on the top level element when all elements have been built
18255 * @param {Roo.XComponent} the top level component.
18257 'buildcomplete' : true
18262 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);
18265 * marked - a markdown parser
18266 * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
18267 * https://github.com/chjj/marked
18273 * Roo.Markdown - is a very crude wrapper around marked..
18277 * alert( Roo.Markdown.toHtml("Markdown *rocks*.") );
18279 * Note: move the sample code to the bottom of this
18280 * file before uncommenting it.
18285 Roo.Markdown.toHtml = function(text) {
18287 var c = new Roo.Markdown.marked.setOptions({
18288 renderer: new Roo.Markdown.marked.Renderer(),
18299 text = text.replace(/\\\n/g,' ');
18300 return Roo.Markdown.marked(text);
18305 // Wraps all "globals" so that the only thing
18306 // exposed is makeHtml().
18312 * eval:var:unescape
18320 var escape = function (html, encode) {
18322 .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
18323 .replace(/</g, '<')
18324 .replace(/>/g, '>')
18325 .replace(/"/g, '"')
18326 .replace(/'/g, ''');
18329 var unescape = function (html) {
18330 // explicitly match decimal, hex, and named HTML entities
18331 return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
18332 n = n.toLowerCase();
18333 if (n === 'colon') { return ':'; }
18334 if (n.charAt(0) === '#') {
18335 return n.charAt(1) === 'x'
18336 ? String.fromCharCode(parseInt(n.substring(2), 16))
18337 : String.fromCharCode(+n.substring(1));
18343 var replace = function (regex, opt) {
18344 regex = regex.source;
18346 return function self(name, val) {
18347 if (!name) { return new RegExp(regex, opt); }
18348 val = val.source || val;
18349 val = val.replace(/(^|[^\[])\^/g, '$1');
18350 regex = regex.replace(name, val);
18359 var noop = function () {}
18365 var merge = function (obj) {
18370 for (; i < arguments.length; i++) {
18371 target = arguments[i];
18372 for (key in target) {
18373 if (Object.prototype.hasOwnProperty.call(target, key)) {
18374 obj[key] = target[key];
18384 * Block-Level Grammar
18392 code: /^( {4}[^\n]+\n*)+/,
18394 hr: /^( *[-*_]){3,} *(?:\n+|$)/,
18395 heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
18397 lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
18398 blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
18399 list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
18400 html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
18401 def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
18403 paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
18407 block.bullet = /(?:[*+-]|\d+\.)/;
18408 block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
18409 block.item = replace(block.item, 'gm')
18410 (/bull/g, block.bullet)
18413 block.list = replace(block.list)
18414 (/bull/g, block.bullet)
18415 ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
18416 ('def', '\\n+(?=' + block.def.source + ')')
18419 block.blockquote = replace(block.blockquote)
18423 block._tag = '(?!(?:'
18424 + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
18425 + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
18426 + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
18428 block.html = replace(block.html)
18429 ('comment', /<!--[\s\S]*?-->/)
18430 ('closed', /<(tag)[\s\S]+?<\/\1>/)
18431 ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
18432 (/tag/g, block._tag)
18435 block.paragraph = replace(block.paragraph)
18437 ('heading', block.heading)
18438 ('lheading', block.lheading)
18439 ('blockquote', block.blockquote)
18440 ('tag', '<' + block._tag)
18445 * Normal Block Grammar
18448 block.normal = merge({}, block);
18451 * GFM Block Grammar
18454 block.gfm = merge({}, block.normal, {
18455 fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
18457 heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
18460 block.gfm.paragraph = replace(block.paragraph)
18462 + block.gfm.fences.source.replace('\\1', '\\2') + '|'
18463 + block.list.source.replace('\\1', '\\3') + '|')
18467 * GFM + Tables Block Grammar
18470 block.tables = merge({}, block.gfm, {
18471 nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
18472 table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
18479 var Lexer = function (options) {
18481 this.tokens.links = {};
18482 this.options = options || marked.defaults;
18483 this.rules = block.normal;
18485 if (this.options.gfm) {
18486 if (this.options.tables) {
18487 this.rules = block.tables;
18489 this.rules = block.gfm;
18495 * Expose Block Rules
18498 Lexer.rules = block;
18501 * Static Lex Method
18504 Lexer.lex = function(src, options) {
18505 var lexer = new Lexer(options);
18506 return lexer.lex(src);
18513 Lexer.prototype.lex = function(src) {
18515 .replace(/\r\n|\r/g, '\n')
18516 .replace(/\t/g, ' ')
18517 .replace(/\u00a0/g, ' ')
18518 .replace(/\u2424/g, '\n');
18520 return this.token(src, true);
18527 Lexer.prototype.token = function(src, top, bq) {
18528 var src = src.replace(/^ +$/gm, '')
18541 if (cap = this.rules.newline.exec(src)) {
18542 src = src.substring(cap[0].length);
18543 if (cap[0].length > 1) {
18551 if (cap = this.rules.code.exec(src)) {
18552 src = src.substring(cap[0].length);
18553 cap = cap[0].replace(/^ {4}/gm, '');
18556 text: !this.options.pedantic
18557 ? cap.replace(/\n+$/, '')
18564 if (cap = this.rules.fences.exec(src)) {
18565 src = src.substring(cap[0].length);
18575 if (cap = this.rules.heading.exec(src)) {
18576 src = src.substring(cap[0].length);
18579 depth: cap[1].length,
18585 // table no leading pipe (gfm)
18586 if (top && (cap = this.rules.nptable.exec(src))) {
18587 src = src.substring(cap[0].length);
18591 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
18592 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
18593 cells: cap[3].replace(/\n$/, '').split('\n')
18596 for (i = 0; i < item.align.length; i++) {
18597 if (/^ *-+: *$/.test(item.align[i])) {
18598 item.align[i] = 'right';
18599 } else if (/^ *:-+: *$/.test(item.align[i])) {
18600 item.align[i] = 'center';
18601 } else if (/^ *:-+ *$/.test(item.align[i])) {
18602 item.align[i] = 'left';
18604 item.align[i] = null;
18608 for (i = 0; i < item.cells.length; i++) {
18609 item.cells[i] = item.cells[i].split(/ *\| */);
18612 this.tokens.push(item);
18618 if (cap = this.rules.lheading.exec(src)) {
18619 src = src.substring(cap[0].length);
18622 depth: cap[2] === '=' ? 1 : 2,
18629 if (cap = this.rules.hr.exec(src)) {
18630 src = src.substring(cap[0].length);
18638 if (cap = this.rules.blockquote.exec(src)) {
18639 src = src.substring(cap[0].length);
18642 type: 'blockquote_start'
18645 cap = cap[0].replace(/^ *> ?/gm, '');
18647 // Pass `top` to keep the current
18648 // "toplevel" state. This is exactly
18649 // how markdown.pl works.
18650 this.token(cap, top, true);
18653 type: 'blockquote_end'
18660 if (cap = this.rules.list.exec(src)) {
18661 src = src.substring(cap[0].length);
18665 type: 'list_start',
18666 ordered: bull.length > 1
18669 // Get each top-level item.
18670 cap = cap[0].match(this.rules.item);
18676 for (; i < l; i++) {
18679 // Remove the list item's bullet
18680 // so it is seen as the next token.
18681 space = item.length;
18682 item = item.replace(/^ *([*+-]|\d+\.) +/, '');
18684 // Outdent whatever the
18685 // list item contains. Hacky.
18686 if (~item.indexOf('\n ')) {
18687 space -= item.length;
18688 item = !this.options.pedantic
18689 ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
18690 : item.replace(/^ {1,4}/gm, '');
18693 // Determine whether the next list item belongs here.
18694 // Backpedal if it does not belong in this list.
18695 if (this.options.smartLists && i !== l - 1) {
18696 b = block.bullet.exec(cap[i + 1])[0];
18697 if (bull !== b && !(bull.length > 1 && b.length > 1)) {
18698 src = cap.slice(i + 1).join('\n') + src;
18703 // Determine whether item is loose or not.
18704 // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
18705 // for discount behavior.
18706 loose = next || /\n\n(?!\s*$)/.test(item);
18708 next = item.charAt(item.length - 1) === '\n';
18709 if (!loose) { loose = next; }
18714 ? 'loose_item_start'
18715 : 'list_item_start'
18719 this.token(item, false, bq);
18722 type: 'list_item_end'
18734 if (cap = this.rules.html.exec(src)) {
18735 src = src.substring(cap[0].length);
18737 type: this.options.sanitize
18740 pre: !this.options.sanitizer
18741 && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
18748 if ((!bq && top) && (cap = this.rules.def.exec(src))) {
18749 src = src.substring(cap[0].length);
18750 this.tokens.links[cap[1].toLowerCase()] = {
18758 if (top && (cap = this.rules.table.exec(src))) {
18759 src = src.substring(cap[0].length);
18763 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
18764 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
18765 cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
18768 for (i = 0; i < item.align.length; i++) {
18769 if (/^ *-+: *$/.test(item.align[i])) {
18770 item.align[i] = 'right';
18771 } else if (/^ *:-+: *$/.test(item.align[i])) {
18772 item.align[i] = 'center';
18773 } else if (/^ *:-+ *$/.test(item.align[i])) {
18774 item.align[i] = 'left';
18776 item.align[i] = null;
18780 for (i = 0; i < item.cells.length; i++) {
18781 item.cells[i] = item.cells[i]
18782 .replace(/^ *\| *| *\| *$/g, '')
18786 this.tokens.push(item);
18791 // top-level paragraph
18792 if (top && (cap = this.rules.paragraph.exec(src))) {
18793 src = src.substring(cap[0].length);
18796 text: cap[1].charAt(cap[1].length - 1) === '\n'
18797 ? cap[1].slice(0, -1)
18804 if (cap = this.rules.text.exec(src)) {
18805 // Top-level should never reach here.
18806 src = src.substring(cap[0].length);
18816 Error('Infinite loop on byte: ' + src.charCodeAt(0));
18820 return this.tokens;
18824 * Inline-Level Grammar
18828 escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
18829 autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
18831 tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
18832 link: /^!?\[(inside)\]\(href\)/,
18833 reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
18834 nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
18835 strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
18836 em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
18837 code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
18838 br: /^ {2,}\n(?!\s*$)/,
18840 text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
18843 inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
18844 inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
18846 inline.link = replace(inline.link)
18847 ('inside', inline._inside)
18848 ('href', inline._href)
18851 inline.reflink = replace(inline.reflink)
18852 ('inside', inline._inside)
18856 * Normal Inline Grammar
18859 inline.normal = merge({}, inline);
18862 * Pedantic Inline Grammar
18865 inline.pedantic = merge({}, inline.normal, {
18866 strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
18867 em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
18871 * GFM Inline Grammar
18874 inline.gfm = merge({}, inline.normal, {
18875 escape: replace(inline.escape)('])', '~|])')(),
18876 url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
18877 del: /^~~(?=\S)([\s\S]*?\S)~~/,
18878 text: replace(inline.text)
18880 ('|', '|https?://|')
18885 * GFM + Line Breaks Inline Grammar
18888 inline.breaks = merge({}, inline.gfm, {
18889 br: replace(inline.br)('{2,}', '*')(),
18890 text: replace(inline.gfm.text)('{2,}', '*')()
18894 * Inline Lexer & Compiler
18897 var InlineLexer = function (links, options) {
18898 this.options = options || marked.defaults;
18899 this.links = links;
18900 this.rules = inline.normal;
18901 this.renderer = this.options.renderer || new Renderer;
18902 this.renderer.options = this.options;
18906 Error('Tokens array requires a `links` property.');
18909 if (this.options.gfm) {
18910 if (this.options.breaks) {
18911 this.rules = inline.breaks;
18913 this.rules = inline.gfm;
18915 } else if (this.options.pedantic) {
18916 this.rules = inline.pedantic;
18921 * Expose Inline Rules
18924 InlineLexer.rules = inline;
18927 * Static Lexing/Compiling Method
18930 InlineLexer.output = function(src, links, options) {
18931 var inline = new InlineLexer(links, options);
18932 return inline.output(src);
18939 InlineLexer.prototype.output = function(src) {
18948 if (cap = this.rules.escape.exec(src)) {
18949 src = src.substring(cap[0].length);
18955 if (cap = this.rules.autolink.exec(src)) {
18956 src = src.substring(cap[0].length);
18957 if (cap[2] === '@') {
18958 text = cap[1].charAt(6) === ':'
18959 ? this.mangle(cap[1].substring(7))
18960 : this.mangle(cap[1]);
18961 href = this.mangle('mailto:') + text;
18963 text = escape(cap[1]);
18966 out += this.renderer.link(href, null, text);
18971 if (!this.inLink && (cap = this.rules.url.exec(src))) {
18972 src = src.substring(cap[0].length);
18973 text = escape(cap[1]);
18975 out += this.renderer.link(href, null, text);
18980 if (cap = this.rules.tag.exec(src)) {
18981 if (!this.inLink && /^<a /i.test(cap[0])) {
18982 this.inLink = true;
18983 } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
18984 this.inLink = false;
18986 src = src.substring(cap[0].length);
18987 out += this.options.sanitize
18988 ? this.options.sanitizer
18989 ? this.options.sanitizer(cap[0])
18996 if (cap = this.rules.link.exec(src)) {
18997 src = src.substring(cap[0].length);
18998 this.inLink = true;
18999 out += this.outputLink(cap, {
19003 this.inLink = false;
19008 if ((cap = this.rules.reflink.exec(src))
19009 || (cap = this.rules.nolink.exec(src))) {
19010 src = src.substring(cap[0].length);
19011 link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
19012 link = this.links[link.toLowerCase()];
19013 if (!link || !link.href) {
19014 out += cap[0].charAt(0);
19015 src = cap[0].substring(1) + src;
19018 this.inLink = true;
19019 out += this.outputLink(cap, link);
19020 this.inLink = false;
19025 if (cap = this.rules.strong.exec(src)) {
19026 src = src.substring(cap[0].length);
19027 out += this.renderer.strong(this.output(cap[2] || cap[1]));
19032 if (cap = this.rules.em.exec(src)) {
19033 src = src.substring(cap[0].length);
19034 out += this.renderer.em(this.output(cap[2] || cap[1]));
19039 if (cap = this.rules.code.exec(src)) {
19040 src = src.substring(cap[0].length);
19041 out += this.renderer.codespan(escape(cap[2], true));
19046 if (cap = this.rules.br.exec(src)) {
19047 src = src.substring(cap[0].length);
19048 out += this.renderer.br();
19053 if (cap = this.rules.del.exec(src)) {
19054 src = src.substring(cap[0].length);
19055 out += this.renderer.del(this.output(cap[1]));
19060 if (cap = this.rules.text.exec(src)) {
19061 src = src.substring(cap[0].length);
19062 out += this.renderer.text(escape(this.smartypants(cap[0])));
19068 Error('Infinite loop on byte: ' + src.charCodeAt(0));
19079 InlineLexer.prototype.outputLink = function(cap, link) {
19080 var href = escape(link.href)
19081 , title = link.title ? escape(link.title) : null;
19083 return cap[0].charAt(0) !== '!'
19084 ? this.renderer.link(href, title, this.output(cap[1]))
19085 : this.renderer.image(href, title, escape(cap[1]));
19089 * Smartypants Transformations
19092 InlineLexer.prototype.smartypants = function(text) {
19093 if (!this.options.smartypants) { return text; }
19096 .replace(/---/g, '\u2014')
19098 .replace(/--/g, '\u2013')
19100 .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
19101 // closing singles & apostrophes
19102 .replace(/'/g, '\u2019')
19104 .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
19106 .replace(/"/g, '\u201d')
19108 .replace(/\.{3}/g, '\u2026');
19115 InlineLexer.prototype.mangle = function(text) {
19116 if (!this.options.mangle) { return text; }
19122 for (; i < l; i++) {
19123 ch = text.charCodeAt(i);
19124 if (Math.random() > 0.5) {
19125 ch = 'x' + ch.toString(16);
19127 out += '&#' + ch + ';';
19138 * eval:var:Renderer
19141 var Renderer = function (options) {
19142 this.options = options || {};
19145 Renderer.prototype.code = function(code, lang, escaped) {
19146 if (this.options.highlight) {
19147 var out = this.options.highlight(code, lang);
19148 if (out != null && out !== code) {
19153 // hack!!! - it's already escapeD?
19158 return '<pre><code>'
19159 + (escaped ? code : escape(code, true))
19160 + '\n</code></pre>';
19163 return '<pre><code class="'
19164 + this.options.langPrefix
19165 + escape(lang, true)
19167 + (escaped ? code : escape(code, true))
19168 + '\n</code></pre>\n';
19171 Renderer.prototype.blockquote = function(quote) {
19172 return '<blockquote>\n' + quote + '</blockquote>\n';
19175 Renderer.prototype.html = function(html) {
19179 Renderer.prototype.heading = function(text, level, raw) {
19183 + this.options.headerPrefix
19184 + raw.toLowerCase().replace(/[^\w]+/g, '-')
19192 Renderer.prototype.hr = function() {
19193 return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
19196 Renderer.prototype.list = function(body, ordered) {
19197 var type = ordered ? 'ol' : 'ul';
19198 return '<' + type + '>\n' + body + '</' + type + '>\n';
19201 Renderer.prototype.listitem = function(text) {
19202 return '<li>' + text + '</li>\n';
19205 Renderer.prototype.paragraph = function(text) {
19206 return '<p>' + text + '</p>\n';
19209 Renderer.prototype.table = function(header, body) {
19210 return '<table class="table table-striped">\n'
19220 Renderer.prototype.tablerow = function(content) {
19221 return '<tr>\n' + content + '</tr>\n';
19224 Renderer.prototype.tablecell = function(content, flags) {
19225 var type = flags.header ? 'th' : 'td';
19226 var tag = flags.align
19227 ? '<' + type + ' style="text-align:' + flags.align + '">'
19228 : '<' + type + '>';
19229 return tag + content + '</' + type + '>\n';
19232 // span level renderer
19233 Renderer.prototype.strong = function(text) {
19234 return '<strong>' + text + '</strong>';
19237 Renderer.prototype.em = function(text) {
19238 return '<em>' + text + '</em>';
19241 Renderer.prototype.codespan = function(text) {
19242 return '<code>' + text + '</code>';
19245 Renderer.prototype.br = function() {
19246 return this.options.xhtml ? '<br/>' : '<br>';
19249 Renderer.prototype.del = function(text) {
19250 return '<del>' + text + '</del>';
19253 Renderer.prototype.link = function(href, title, text) {
19254 if (this.options.sanitize) {
19256 var prot = decodeURIComponent(unescape(href))
19257 .replace(/[^\w:]/g, '')
19262 if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
19266 var out = '<a href="' + href + '"';
19268 out += ' title="' + title + '"';
19270 out += '>' + text + '</a>';
19274 Renderer.prototype.image = function(href, title, text) {
19275 var out = '<img src="' + href + '" alt="' + text + '"';
19277 out += ' title="' + title + '"';
19279 out += this.options.xhtml ? '/>' : '>';
19283 Renderer.prototype.text = function(text) {
19288 * Parsing & Compiling
19294 var Parser= function (options) {
19297 this.options = options || marked.defaults;
19298 this.options.renderer = this.options.renderer || new Renderer;
19299 this.renderer = this.options.renderer;
19300 this.renderer.options = this.options;
19304 * Static Parse Method
19307 Parser.parse = function(src, options, renderer) {
19308 var parser = new Parser(options, renderer);
19309 return parser.parse(src);
19316 Parser.prototype.parse = function(src) {
19317 this.inline = new InlineLexer(src.links, this.options, this.renderer);
19318 this.tokens = src.reverse();
19321 while (this.next()) {
19332 Parser.prototype.next = function() {
19333 return this.token = this.tokens.pop();
19337 * Preview Next Token
19340 Parser.prototype.peek = function() {
19341 return this.tokens[this.tokens.length - 1] || 0;
19345 * Parse Text Tokens
19348 Parser.prototype.parseText = function() {
19349 var body = this.token.text;
19351 while (this.peek().type === 'text') {
19352 body += '\n' + this.next().text;
19355 return this.inline.output(body);
19359 * Parse Current Token
19362 Parser.prototype.tok = function() {
19363 switch (this.token.type) {
19368 return this.renderer.hr();
19371 return this.renderer.heading(
19372 this.inline.output(this.token.text),
19377 return this.renderer.code(this.token.text,
19379 this.token.escaped);
19392 for (i = 0; i < this.token.header.length; i++) {
19393 flags = { header: true, align: this.token.align[i] };
19394 cell += this.renderer.tablecell(
19395 this.inline.output(this.token.header[i]),
19396 { header: true, align: this.token.align[i] }
19399 header += this.renderer.tablerow(cell);
19401 for (i = 0; i < this.token.cells.length; i++) {
19402 row = this.token.cells[i];
19405 for (j = 0; j < row.length; j++) {
19406 cell += this.renderer.tablecell(
19407 this.inline.output(row[j]),
19408 { header: false, align: this.token.align[j] }
19412 body += this.renderer.tablerow(cell);
19414 return this.renderer.table(header, body);
19416 case 'blockquote_start': {
19419 while (this.next().type !== 'blockquote_end') {
19420 body += this.tok();
19423 return this.renderer.blockquote(body);
19425 case 'list_start': {
19427 , ordered = this.token.ordered;
19429 while (this.next().type !== 'list_end') {
19430 body += this.tok();
19433 return this.renderer.list(body, ordered);
19435 case 'list_item_start': {
19438 while (this.next().type !== 'list_item_end') {
19439 body += this.token.type === 'text'
19444 return this.renderer.listitem(body);
19446 case 'loose_item_start': {
19449 while (this.next().type !== 'list_item_end') {
19450 body += this.tok();
19453 return this.renderer.listitem(body);
19456 var html = !this.token.pre && !this.options.pedantic
19457 ? this.inline.output(this.token.text)
19459 return this.renderer.html(html);
19461 case 'paragraph': {
19462 return this.renderer.paragraph(this.inline.output(this.token.text));
19465 return this.renderer.paragraph(this.parseText());
19477 var marked = function (src, opt, callback) {
19478 if (callback || typeof opt === 'function') {
19484 opt = merge({}, marked.defaults, opt || {});
19486 var highlight = opt.highlight
19492 tokens = Lexer.lex(src, opt)
19494 return callback(e);
19497 pending = tokens.length;
19501 var done = function(err) {
19503 opt.highlight = highlight;
19504 return callback(err);
19510 out = Parser.parse(tokens, opt);
19515 opt.highlight = highlight;
19519 : callback(null, out);
19522 if (!highlight || highlight.length < 3) {
19526 delete opt.highlight;
19528 if (!pending) { return done(); }
19530 for (; i < tokens.length; i++) {
19532 if (token.type !== 'code') {
19533 return --pending || done();
19535 return highlight(token.text, token.lang, function(err, code) {
19536 if (err) { return done(err); }
19537 if (code == null || code === token.text) {
19538 return --pending || done();
19541 token.escaped = true;
19542 --pending || done();
19550 if (opt) { opt = merge({}, marked.defaults, opt); }
19551 return Parser.parse(Lexer.lex(src, opt), opt);
19553 e.message += '\nPlease report this to https://github.com/chjj/marked.';
19554 if ((opt || marked.defaults).silent) {
19555 return '<p>An error occured:</p><pre>'
19556 + escape(e.message + '', true)
19568 marked.setOptions = function(opt) {
19569 merge(marked.defaults, opt);
19573 marked.defaults = {
19584 langPrefix: 'lang-',
19585 smartypants: false,
19587 renderer: new Renderer,
19595 marked.Parser = Parser;
19596 marked.parser = Parser.parse;
19598 marked.Renderer = Renderer;
19600 marked.Lexer = Lexer;
19601 marked.lexer = Lexer.lex;
19603 marked.InlineLexer = InlineLexer;
19604 marked.inlineLexer = InlineLexer.output;
19606 marked.parse = marked;
19608 Roo.Markdown.marked = marked;
19612 * Ext JS Library 1.1.1
19613 * Copyright(c) 2006-2007, Ext JS, LLC.
19615 * Originally Released Under LGPL - original licence link has changed is not relivant.
19618 * <script type="text/javascript">
19624 * These classes are derivatives of the similarly named classes in the YUI Library.
19625 * The original license:
19626 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
19627 * Code licensed under the BSD License:
19628 * http://developer.yahoo.net/yui/license.txt
19633 var Event=Roo.EventManager;
19634 var Dom=Roo.lib.Dom;
19637 * @class Roo.dd.DragDrop
19638 * @extends Roo.util.Observable
19639 * Defines the interface and base operation of items that that can be
19640 * dragged or can be drop targets. It was designed to be extended, overriding
19641 * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
19642 * Up to three html elements can be associated with a DragDrop instance:
19644 * <li>linked element: the element that is passed into the constructor.
19645 * This is the element which defines the boundaries for interaction with
19646 * other DragDrop objects.</li>
19647 * <li>handle element(s): The drag operation only occurs if the element that
19648 * was clicked matches a handle element. By default this is the linked
19649 * element, but there are times that you will want only a portion of the
19650 * linked element to initiate the drag operation, and the setHandleElId()
19651 * method provides a way to define this.</li>
19652 * <li>drag element: this represents the element that would be moved along
19653 * with the cursor during a drag operation. By default, this is the linked
19654 * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
19655 * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
19658 * This class should not be instantiated until the onload event to ensure that
19659 * the associated elements are available.
19660 * The following would define a DragDrop obj that would interact with any
19661 * other DragDrop obj in the "group1" group:
19663 * dd = new Roo.dd.DragDrop("div1", "group1");
19665 * Since none of the event handlers have been implemented, nothing would
19666 * actually happen if you were to run the code above. Normally you would
19667 * override this class or one of the default implementations, but you can
19668 * also override the methods you want on an instance of the class...
19670 * dd.onDragDrop = function(e, id) {
19671 * alert("dd was dropped on " + id);
19675 * @param {String} id of the element that is linked to this instance
19676 * @param {String} sGroup the group of related DragDrop objects
19677 * @param {object} config an object containing configurable attributes
19678 * Valid properties for DragDrop:
19679 * padding, isTarget, maintainOffset, primaryButtonOnly
19681 Roo.dd.DragDrop = function(id, sGroup, config) {
19683 this.init(id, sGroup, config);
19688 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
19691 * The id of the element associated with this object. This is what we
19692 * refer to as the "linked element" because the size and position of
19693 * this element is used to determine when the drag and drop objects have
19701 * Configuration attributes passed into the constructor
19708 * The id of the element that will be dragged. By default this is same
19709 * as the linked element , but could be changed to another element. Ex:
19711 * @property dragElId
19718 * the id of the element that initiates the drag operation. By default
19719 * this is the linked element, but could be changed to be a child of this
19720 * element. This lets us do things like only starting the drag when the
19721 * header element within the linked html element is clicked.
19722 * @property handleElId
19729 * An associative array of HTML tags that will be ignored if clicked.
19730 * @property invalidHandleTypes
19731 * @type {string: string}
19733 invalidHandleTypes: null,
19736 * An associative array of ids for elements that will be ignored if clicked
19737 * @property invalidHandleIds
19738 * @type {string: string}
19740 invalidHandleIds: null,
19743 * An indexted array of css class names for elements that will be ignored
19745 * @property invalidHandleClasses
19748 invalidHandleClasses: null,
19751 * The linked element's absolute X position at the time the drag was
19753 * @property startPageX
19760 * The linked element's absolute X position at the time the drag was
19762 * @property startPageY
19769 * The group defines a logical collection of DragDrop objects that are
19770 * related. Instances only get events when interacting with other
19771 * DragDrop object in the same group. This lets us define multiple
19772 * groups using a single DragDrop subclass if we want.
19774 * @type {string: string}
19779 * Individual drag/drop instances can be locked. This will prevent
19780 * onmousedown start drag.
19788 * Lock this instance
19791 lock: function() { this.locked = true; },
19794 * Unlock this instace
19797 unlock: function() { this.locked = false; },
19800 * By default, all insances can be a drop target. This can be disabled by
19801 * setting isTarget to false.
19808 * The padding configured for this drag and drop object for calculating
19809 * the drop zone intersection with this object.
19816 * Cached reference to the linked element
19817 * @property _domRef
19823 * Internal typeof flag
19824 * @property __ygDragDrop
19827 __ygDragDrop: true,
19830 * Set to true when horizontal contraints are applied
19831 * @property constrainX
19838 * Set to true when vertical contraints are applied
19839 * @property constrainY
19846 * The left constraint
19854 * The right constraint
19862 * The up constraint
19871 * The down constraint
19879 * Maintain offsets when we resetconstraints. Set to true when you want
19880 * the position of the element relative to its parent to stay the same
19881 * when the page changes
19883 * @property maintainOffset
19886 maintainOffset: false,
19889 * Array of pixel locations the element will snap to if we specified a
19890 * horizontal graduation/interval. This array is generated automatically
19891 * when you define a tick interval.
19898 * Array of pixel locations the element will snap to if we specified a
19899 * vertical graduation/interval. This array is generated automatically
19900 * when you define a tick interval.
19907 * By default the drag and drop instance will only respond to the primary
19908 * button click (left button for a right-handed mouse). Set to true to
19909 * allow drag and drop to start with any mouse click that is propogated
19911 * @property primaryButtonOnly
19914 primaryButtonOnly: true,
19917 * The availabe property is false until the linked dom element is accessible.
19918 * @property available
19924 * By default, drags can only be initiated if the mousedown occurs in the
19925 * region the linked element is. This is done in part to work around a
19926 * bug in some browsers that mis-report the mousedown if the previous
19927 * mouseup happened outside of the window. This property is set to true
19928 * if outer handles are defined.
19930 * @property hasOuterHandles
19934 hasOuterHandles: false,
19937 * Code that executes immediately before the startDrag event
19938 * @method b4StartDrag
19941 b4StartDrag: function(x, y) { },
19944 * Abstract method called after a drag/drop object is clicked
19945 * and the drag or mousedown time thresholds have beeen met.
19946 * @method startDrag
19947 * @param {int} X click location
19948 * @param {int} Y click location
19950 startDrag: function(x, y) { /* override this */ },
19953 * Code that executes immediately before the onDrag event
19957 b4Drag: function(e) { },
19960 * Abstract method called during the onMouseMove event while dragging an
19963 * @param {Event} e the mousemove event
19965 onDrag: function(e) { /* override this */ },
19968 * Abstract method called when this element fist begins hovering over
19969 * another DragDrop obj
19970 * @method onDragEnter
19971 * @param {Event} e the mousemove event
19972 * @param {String|DragDrop[]} id In POINT mode, the element
19973 * id this is hovering over. In INTERSECT mode, an array of one or more
19974 * dragdrop items being hovered over.
19976 onDragEnter: function(e, id) { /* override this */ },
19979 * Code that executes immediately before the onDragOver event
19980 * @method b4DragOver
19983 b4DragOver: function(e) { },
19986 * Abstract method called when this element is hovering over another
19988 * @method onDragOver
19989 * @param {Event} e the mousemove event
19990 * @param {String|DragDrop[]} id In POINT mode, the element
19991 * id this is hovering over. In INTERSECT mode, an array of dd items
19992 * being hovered over.
19994 onDragOver: function(e, id) { /* override this */ },
19997 * Code that executes immediately before the onDragOut event
19998 * @method b4DragOut
20001 b4DragOut: function(e) { },
20004 * Abstract method called when we are no longer hovering over an element
20005 * @method onDragOut
20006 * @param {Event} e the mousemove event
20007 * @param {String|DragDrop[]} id In POINT mode, the element
20008 * id this was hovering over. In INTERSECT mode, an array of dd items
20009 * that the mouse is no longer over.
20011 onDragOut: function(e, id) { /* override this */ },
20014 * Code that executes immediately before the onDragDrop event
20015 * @method b4DragDrop
20018 b4DragDrop: function(e) { },
20021 * Abstract method called when this item is dropped on another DragDrop
20023 * @method onDragDrop
20024 * @param {Event} e the mouseup event
20025 * @param {String|DragDrop[]} id In POINT mode, the element
20026 * id this was dropped on. In INTERSECT mode, an array of dd items this
20029 onDragDrop: function(e, id) { /* override this */ },
20032 * Abstract method called when this item is dropped on an area with no
20034 * @method onInvalidDrop
20035 * @param {Event} e the mouseup event
20037 onInvalidDrop: function(e) { /* override this */ },
20040 * Code that executes immediately before the endDrag event
20041 * @method b4EndDrag
20044 b4EndDrag: function(e) { },
20047 * Fired when we are done dragging the object
20049 * @param {Event} e the mouseup event
20051 endDrag: function(e) { /* override this */ },
20054 * Code executed immediately before the onMouseDown event
20055 * @method b4MouseDown
20056 * @param {Event} e the mousedown event
20059 b4MouseDown: function(e) { },
20062 * Event handler that fires when a drag/drop obj gets a mousedown
20063 * @method onMouseDown
20064 * @param {Event} e the mousedown event
20066 onMouseDown: function(e) { /* override this */ },
20069 * Event handler that fires when a drag/drop obj gets a mouseup
20070 * @method onMouseUp
20071 * @param {Event} e the mouseup event
20073 onMouseUp: function(e) { /* override this */ },
20076 * Override the onAvailable method to do what is needed after the initial
20077 * position was determined.
20078 * @method onAvailable
20080 onAvailable: function () {
20084 * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
20087 defaultPadding : {left:0, right:0, top:0, bottom:0},
20090 * Initializes the drag drop object's constraints to restrict movement to a certain element.
20094 var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
20095 { dragElId: "existingProxyDiv" });
20096 dd.startDrag = function(){
20097 this.constrainTo("parent-id");
20100 * Or you can initalize it using the {@link Roo.Element} object:
20102 Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
20103 startDrag : function(){
20104 this.constrainTo("parent-id");
20108 * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
20109 * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
20110 * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
20111 * an object containing the sides to pad. For example: {right:10, bottom:10}
20112 * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
20114 constrainTo : function(constrainTo, pad, inContent){
20115 if(typeof pad == "number"){
20116 pad = {left: pad, right:pad, top:pad, bottom:pad};
20118 pad = pad || this.defaultPadding;
20119 var b = Roo.get(this.getEl()).getBox();
20120 var ce = Roo.get(constrainTo);
20121 var s = ce.getScroll();
20122 var c, cd = ce.dom;
20123 if(cd == document.body){
20124 c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
20127 c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
20131 var topSpace = b.y - c.y;
20132 var leftSpace = b.x - c.x;
20134 this.resetConstraints();
20135 this.setXConstraint(leftSpace - (pad.left||0), // left
20136 c.width - leftSpace - b.width - (pad.right||0) //right
20138 this.setYConstraint(topSpace - (pad.top||0), //top
20139 c.height - topSpace - b.height - (pad.bottom||0) //bottom
20144 * Returns a reference to the linked element
20146 * @return {HTMLElement} the html element
20148 getEl: function() {
20149 if (!this._domRef) {
20150 this._domRef = Roo.getDom(this.id);
20153 return this._domRef;
20157 * Returns a reference to the actual element to drag. By default this is
20158 * the same as the html element, but it can be assigned to another
20159 * element. An example of this can be found in Roo.dd.DDProxy
20160 * @method getDragEl
20161 * @return {HTMLElement} the html element
20163 getDragEl: function() {
20164 return Roo.getDom(this.dragElId);
20168 * Sets up the DragDrop object. Must be called in the constructor of any
20169 * Roo.dd.DragDrop subclass
20171 * @param id the id of the linked element
20172 * @param {String} sGroup the group of related items
20173 * @param {object} config configuration attributes
20175 init: function(id, sGroup, config) {
20176 this.initTarget(id, sGroup, config);
20177 if (!Roo.isTouch) {
20178 Event.on(this.id, "mousedown", this.handleMouseDown, this);
20180 Event.on(this.id, "touchstart", this.handleMouseDown, this);
20181 // Event.on(this.id, "selectstart", Event.preventDefault);
20185 * Initializes Targeting functionality only... the object does not
20186 * get a mousedown handler.
20187 * @method initTarget
20188 * @param id the id of the linked element
20189 * @param {String} sGroup the group of related items
20190 * @param {object} config configuration attributes
20192 initTarget: function(id, sGroup, config) {
20194 // configuration attributes
20195 this.config = config || {};
20197 // create a local reference to the drag and drop manager
20198 this.DDM = Roo.dd.DDM;
20199 // initialize the groups array
20202 // assume that we have an element reference instead of an id if the
20203 // parameter is not a string
20204 if (typeof id !== "string") {
20211 // add to an interaction group
20212 this.addToGroup((sGroup) ? sGroup : "default");
20214 // We don't want to register this as the handle with the manager
20215 // so we just set the id rather than calling the setter.
20216 this.handleElId = id;
20218 // the linked element is the element that gets dragged by default
20219 this.setDragElId(id);
20221 // by default, clicked anchors will not start drag operations.
20222 this.invalidHandleTypes = { A: "A" };
20223 this.invalidHandleIds = {};
20224 this.invalidHandleClasses = [];
20226 this.applyConfig();
20228 this.handleOnAvailable();
20232 * Applies the configuration parameters that were passed into the constructor.
20233 * This is supposed to happen at each level through the inheritance chain. So
20234 * a DDProxy implentation will execute apply config on DDProxy, DD, and
20235 * DragDrop in order to get all of the parameters that are available in
20237 * @method applyConfig
20239 applyConfig: function() {
20241 // configurable properties:
20242 // padding, isTarget, maintainOffset, primaryButtonOnly
20243 this.padding = this.config.padding || [0, 0, 0, 0];
20244 this.isTarget = (this.config.isTarget !== false);
20245 this.maintainOffset = (this.config.maintainOffset);
20246 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
20251 * Executed when the linked element is available
20252 * @method handleOnAvailable
20255 handleOnAvailable: function() {
20256 this.available = true;
20257 this.resetConstraints();
20258 this.onAvailable();
20262 * Configures the padding for the target zone in px. Effectively expands
20263 * (or reduces) the virtual object size for targeting calculations.
20264 * Supports css-style shorthand; if only one parameter is passed, all sides
20265 * will have that padding, and if only two are passed, the top and bottom
20266 * will have the first param, the left and right the second.
20267 * @method setPadding
20268 * @param {int} iTop Top pad
20269 * @param {int} iRight Right pad
20270 * @param {int} iBot Bot pad
20271 * @param {int} iLeft Left pad
20273 setPadding: function(iTop, iRight, iBot, iLeft) {
20274 // this.padding = [iLeft, iRight, iTop, iBot];
20275 if (!iRight && 0 !== iRight) {
20276 this.padding = [iTop, iTop, iTop, iTop];
20277 } else if (!iBot && 0 !== iBot) {
20278 this.padding = [iTop, iRight, iTop, iRight];
20280 this.padding = [iTop, iRight, iBot, iLeft];
20285 * Stores the initial placement of the linked element.
20286 * @method setInitialPosition
20287 * @param {int} diffX the X offset, default 0
20288 * @param {int} diffY the Y offset, default 0
20290 setInitPosition: function(diffX, diffY) {
20291 var el = this.getEl();
20293 if (!this.DDM.verifyEl(el)) {
20297 var dx = diffX || 0;
20298 var dy = diffY || 0;
20300 var p = Dom.getXY( el );
20302 this.initPageX = p[0] - dx;
20303 this.initPageY = p[1] - dy;
20305 this.lastPageX = p[0];
20306 this.lastPageY = p[1];
20309 this.setStartPosition(p);
20313 * Sets the start position of the element. This is set when the obj
20314 * is initialized, the reset when a drag is started.
20315 * @method setStartPosition
20316 * @param pos current position (from previous lookup)
20319 setStartPosition: function(pos) {
20320 var p = pos || Dom.getXY( this.getEl() );
20321 this.deltaSetXY = null;
20323 this.startPageX = p[0];
20324 this.startPageY = p[1];
20328 * Add this instance to a group of related drag/drop objects. All
20329 * instances belong to at least one group, and can belong to as many
20330 * groups as needed.
20331 * @method addToGroup
20332 * @param sGroup {string} the name of the group
20334 addToGroup: function(sGroup) {
20335 this.groups[sGroup] = true;
20336 this.DDM.regDragDrop(this, sGroup);
20340 * Remove's this instance from the supplied interaction group
20341 * @method removeFromGroup
20342 * @param {string} sGroup The group to drop
20344 removeFromGroup: function(sGroup) {
20345 if (this.groups[sGroup]) {
20346 delete this.groups[sGroup];
20349 this.DDM.removeDDFromGroup(this, sGroup);
20353 * Allows you to specify that an element other than the linked element
20354 * will be moved with the cursor during a drag
20355 * @method setDragElId
20356 * @param id {string} the id of the element that will be used to initiate the drag
20358 setDragElId: function(id) {
20359 this.dragElId = id;
20363 * Allows you to specify a child of the linked element that should be
20364 * used to initiate the drag operation. An example of this would be if
20365 * you have a content div with text and links. Clicking anywhere in the
20366 * content area would normally start the drag operation. Use this method
20367 * to specify that an element inside of the content div is the element
20368 * that starts the drag operation.
20369 * @method setHandleElId
20370 * @param id {string} the id of the element that will be used to
20371 * initiate the drag.
20373 setHandleElId: function(id) {
20374 if (typeof id !== "string") {
20377 this.handleElId = id;
20378 this.DDM.regHandle(this.id, id);
20382 * Allows you to set an element outside of the linked element as a drag
20384 * @method setOuterHandleElId
20385 * @param id the id of the element that will be used to initiate the drag
20387 setOuterHandleElId: function(id) {
20388 if (typeof id !== "string") {
20391 Event.on(id, "mousedown",
20392 this.handleMouseDown, this);
20393 this.setHandleElId(id);
20395 this.hasOuterHandles = true;
20399 * Remove all drag and drop hooks for this element
20402 unreg: function() {
20403 Event.un(this.id, "mousedown",
20404 this.handleMouseDown);
20405 Event.un(this.id, "touchstart",
20406 this.handleMouseDown);
20407 this._domRef = null;
20408 this.DDM._remove(this);
20411 destroy : function(){
20416 * Returns true if this instance is locked, or the drag drop mgr is locked
20417 * (meaning that all drag/drop is disabled on the page.)
20419 * @return {boolean} true if this obj or all drag/drop is locked, else
20422 isLocked: function() {
20423 return (this.DDM.isLocked() || this.locked);
20427 * Fired when this object is clicked
20428 * @method handleMouseDown
20430 * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
20433 handleMouseDown: function(e, oDD){
20435 if (!Roo.isTouch && this.primaryButtonOnly && e.button != 0) {
20436 //Roo.log('not touch/ button !=0');
20439 if (e.browserEvent.touches && e.browserEvent.touches.length != 1) {
20440 return; // double touch..
20444 if (this.isLocked()) {
20445 //Roo.log('locked');
20449 this.DDM.refreshCache(this.groups);
20450 // Roo.log([Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e)]);
20451 var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
20452 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
20453 //Roo.log('no outer handes or not over target');
20456 // Roo.log('check validator');
20457 if (this.clickValidator(e)) {
20458 // Roo.log('validate success');
20459 // set the initial element position
20460 this.setStartPosition();
20463 this.b4MouseDown(e);
20464 this.onMouseDown(e);
20466 this.DDM.handleMouseDown(e, this);
20468 this.DDM.stopEvent(e);
20476 clickValidator: function(e) {
20477 var target = e.getTarget();
20478 return ( this.isValidHandleChild(target) &&
20479 (this.id == this.handleElId ||
20480 this.DDM.handleWasClicked(target, this.id)) );
20484 * Allows you to specify a tag name that should not start a drag operation
20485 * when clicked. This is designed to facilitate embedding links within a
20486 * drag handle that do something other than start the drag.
20487 * @method addInvalidHandleType
20488 * @param {string} tagName the type of element to exclude
20490 addInvalidHandleType: function(tagName) {
20491 var type = tagName.toUpperCase();
20492 this.invalidHandleTypes[type] = type;
20496 * Lets you to specify an element id for a child of a drag handle
20497 * that should not initiate a drag
20498 * @method addInvalidHandleId
20499 * @param {string} id the element id of the element you wish to ignore
20501 addInvalidHandleId: function(id) {
20502 if (typeof id !== "string") {
20505 this.invalidHandleIds[id] = id;
20509 * Lets you specify a css class of elements that will not initiate a drag
20510 * @method addInvalidHandleClass
20511 * @param {string} cssClass the class of the elements you wish to ignore
20513 addInvalidHandleClass: function(cssClass) {
20514 this.invalidHandleClasses.push(cssClass);
20518 * Unsets an excluded tag name set by addInvalidHandleType
20519 * @method removeInvalidHandleType
20520 * @param {string} tagName the type of element to unexclude
20522 removeInvalidHandleType: function(tagName) {
20523 var type = tagName.toUpperCase();
20524 // this.invalidHandleTypes[type] = null;
20525 delete this.invalidHandleTypes[type];
20529 * Unsets an invalid handle id
20530 * @method removeInvalidHandleId
20531 * @param {string} id the id of the element to re-enable
20533 removeInvalidHandleId: function(id) {
20534 if (typeof id !== "string") {
20537 delete this.invalidHandleIds[id];
20541 * Unsets an invalid css class
20542 * @method removeInvalidHandleClass
20543 * @param {string} cssClass the class of the element(s) you wish to
20546 removeInvalidHandleClass: function(cssClass) {
20547 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
20548 if (this.invalidHandleClasses[i] == cssClass) {
20549 delete this.invalidHandleClasses[i];
20555 * Checks the tag exclusion list to see if this click should be ignored
20556 * @method isValidHandleChild
20557 * @param {HTMLElement} node the HTMLElement to evaluate
20558 * @return {boolean} true if this is a valid tag type, false if not
20560 isValidHandleChild: function(node) {
20563 // var n = (node.nodeName == "#text") ? node.parentNode : node;
20566 nodeName = node.nodeName.toUpperCase();
20568 nodeName = node.nodeName;
20570 valid = valid && !this.invalidHandleTypes[nodeName];
20571 valid = valid && !this.invalidHandleIds[node.id];
20573 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
20574 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
20583 * Create the array of horizontal tick marks if an interval was specified
20584 * in setXConstraint().
20585 * @method setXTicks
20588 setXTicks: function(iStartX, iTickSize) {
20590 this.xTickSize = iTickSize;
20594 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
20596 this.xTicks[this.xTicks.length] = i;
20601 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
20603 this.xTicks[this.xTicks.length] = i;
20608 this.xTicks.sort(this.DDM.numericSort) ;
20612 * Create the array of vertical tick marks if an interval was specified in
20613 * setYConstraint().
20614 * @method setYTicks
20617 setYTicks: function(iStartY, iTickSize) {
20619 this.yTickSize = iTickSize;
20623 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
20625 this.yTicks[this.yTicks.length] = i;
20630 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
20632 this.yTicks[this.yTicks.length] = i;
20637 this.yTicks.sort(this.DDM.numericSort) ;
20641 * By default, the element can be dragged any place on the screen. Use
20642 * this method to limit the horizontal travel of the element. Pass in
20643 * 0,0 for the parameters if you want to lock the drag to the y axis.
20644 * @method setXConstraint
20645 * @param {int} iLeft the number of pixels the element can move to the left
20646 * @param {int} iRight the number of pixels the element can move to the
20648 * @param {int} iTickSize optional parameter for specifying that the
20650 * should move iTickSize pixels at a time.
20652 setXConstraint: function(iLeft, iRight, iTickSize) {
20653 this.leftConstraint = iLeft;
20654 this.rightConstraint = iRight;
20656 this.minX = this.initPageX - iLeft;
20657 this.maxX = this.initPageX + iRight;
20658 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
20660 this.constrainX = true;
20664 * Clears any constraints applied to this instance. Also clears ticks
20665 * since they can't exist independent of a constraint at this time.
20666 * @method clearConstraints
20668 clearConstraints: function() {
20669 this.constrainX = false;
20670 this.constrainY = false;
20675 * Clears any tick interval defined for this instance
20676 * @method clearTicks
20678 clearTicks: function() {
20679 this.xTicks = null;
20680 this.yTicks = null;
20681 this.xTickSize = 0;
20682 this.yTickSize = 0;
20686 * By default, the element can be dragged any place on the screen. Set
20687 * this to limit the vertical travel of the element. Pass in 0,0 for the
20688 * parameters if you want to lock the drag to the x axis.
20689 * @method setYConstraint
20690 * @param {int} iUp the number of pixels the element can move up
20691 * @param {int} iDown the number of pixels the element can move down
20692 * @param {int} iTickSize optional parameter for specifying that the
20693 * element should move iTickSize pixels at a time.
20695 setYConstraint: function(iUp, iDown, iTickSize) {
20696 this.topConstraint = iUp;
20697 this.bottomConstraint = iDown;
20699 this.minY = this.initPageY - iUp;
20700 this.maxY = this.initPageY + iDown;
20701 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
20703 this.constrainY = true;
20708 * resetConstraints must be called if you manually reposition a dd element.
20709 * @method resetConstraints
20710 * @param {boolean} maintainOffset
20712 resetConstraints: function() {
20715 // Maintain offsets if necessary
20716 if (this.initPageX || this.initPageX === 0) {
20717 // figure out how much this thing has moved
20718 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
20719 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
20721 this.setInitPosition(dx, dy);
20723 // This is the first time we have detected the element's position
20725 this.setInitPosition();
20728 if (this.constrainX) {
20729 this.setXConstraint( this.leftConstraint,
20730 this.rightConstraint,
20734 if (this.constrainY) {
20735 this.setYConstraint( this.topConstraint,
20736 this.bottomConstraint,
20742 * Normally the drag element is moved pixel by pixel, but we can specify
20743 * that it move a number of pixels at a time. This method resolves the
20744 * location when we have it set up like this.
20746 * @param {int} val where we want to place the object
20747 * @param {int[]} tickArray sorted array of valid points
20748 * @return {int} the closest tick
20751 getTick: function(val, tickArray) {
20754 // If tick interval is not defined, it is effectively 1 pixel,
20755 // so we return the value passed to us.
20757 } else if (tickArray[0] >= val) {
20758 // The value is lower than the first tick, so we return the first
20760 return tickArray[0];
20762 for (var i=0, len=tickArray.length; i<len; ++i) {
20764 if (tickArray[next] && tickArray[next] >= val) {
20765 var diff1 = val - tickArray[i];
20766 var diff2 = tickArray[next] - val;
20767 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
20771 // The value is larger than the last tick, so we return the last
20773 return tickArray[tickArray.length - 1];
20780 * @return {string} string representation of the dd obj
20782 toString: function() {
20783 return ("DragDrop " + this.id);
20791 * Ext JS Library 1.1.1
20792 * Copyright(c) 2006-2007, Ext JS, LLC.
20794 * Originally Released Under LGPL - original licence link has changed is not relivant.
20797 * <script type="text/javascript">
20802 * The drag and drop utility provides a framework for building drag and drop
20803 * applications. In addition to enabling drag and drop for specific elements,
20804 * the drag and drop elements are tracked by the manager class, and the
20805 * interactions between the various elements are tracked during the drag and
20806 * the implementing code is notified about these important moments.
20809 // Only load the library once. Rewriting the manager class would orphan
20810 // existing drag and drop instances.
20811 if (!Roo.dd.DragDropMgr) {
20814 * @class Roo.dd.DragDropMgr
20815 * DragDropMgr is a singleton that tracks the element interaction for
20816 * all DragDrop items in the window. Generally, you will not call
20817 * this class directly, but it does have helper methods that could
20818 * be useful in your DragDrop implementations.
20821 Roo.dd.DragDropMgr = function() {
20823 var Event = Roo.EventManager;
20828 * Two dimensional Array of registered DragDrop objects. The first
20829 * dimension is the DragDrop item group, the second the DragDrop
20832 * @type {string: string}
20839 * Array of element ids defined as drag handles. Used to determine
20840 * if the element that generated the mousedown event is actually the
20841 * handle and not the html element itself.
20842 * @property handleIds
20843 * @type {string: string}
20850 * the DragDrop object that is currently being dragged
20851 * @property dragCurrent
20859 * the DragDrop object(s) that are being hovered over
20860 * @property dragOvers
20868 * the X distance between the cursor and the object being dragged
20877 * the Y distance between the cursor and the object being dragged
20886 * Flag to determine if we should prevent the default behavior of the
20887 * events we define. By default this is true, but this can be set to
20888 * false if you need the default behavior (not recommended)
20889 * @property preventDefault
20893 preventDefault: true,
20896 * Flag to determine if we should stop the propagation of the events
20897 * we generate. This is true by default but you may want to set it to
20898 * false if the html element contains other features that require the
20900 * @property stopPropagation
20904 stopPropagation: true,
20907 * Internal flag that is set to true when drag and drop has been
20909 * @property initialized
20916 * All drag and drop can be disabled.
20924 * Called the first time an element is registered.
20930 this.initialized = true;
20934 * In point mode, drag and drop interaction is defined by the
20935 * location of the cursor during the drag/drop
20943 * In intersect mode, drag and drop interactio nis defined by the
20944 * overlap of two or more drag and drop objects.
20945 * @property INTERSECT
20952 * The current drag and drop mode. Default: POINT
20960 * Runs method on all drag and drop objects
20961 * @method _execOnAll
20965 _execOnAll: function(sMethod, args) {
20966 for (var i in this.ids) {
20967 for (var j in this.ids[i]) {
20968 var oDD = this.ids[i][j];
20969 if (! this.isTypeOfDD(oDD)) {
20972 oDD[sMethod].apply(oDD, args);
20978 * Drag and drop initialization. Sets up the global event handlers
20983 _onLoad: function() {
20987 if (!Roo.isTouch) {
20988 Event.on(document, "mouseup", this.handleMouseUp, this, true);
20989 Event.on(document, "mousemove", this.handleMouseMove, this, true);
20991 Event.on(document, "touchend", this.handleMouseUp, this, true);
20992 Event.on(document, "touchmove", this.handleMouseMove, this, true);
20994 Event.on(window, "unload", this._onUnload, this, true);
20995 Event.on(window, "resize", this._onResize, this, true);
20996 // Event.on(window, "mouseout", this._test);
21001 * Reset constraints on all drag and drop objs
21002 * @method _onResize
21006 _onResize: function(e) {
21007 this._execOnAll("resetConstraints", []);
21011 * Lock all drag and drop functionality
21015 lock: function() { this.locked = true; },
21018 * Unlock all drag and drop functionality
21022 unlock: function() { this.locked = false; },
21025 * Is drag and drop locked?
21027 * @return {boolean} True if drag and drop is locked, false otherwise.
21030 isLocked: function() { return this.locked; },
21033 * Location cache that is set for all drag drop objects when a drag is
21034 * initiated, cleared when the drag is finished.
21035 * @property locationCache
21042 * Set useCache to false if you want to force object the lookup of each
21043 * drag and drop linked element constantly during a drag.
21044 * @property useCache
21051 * The number of pixels that the mouse needs to move after the
21052 * mousedown before the drag is initiated. Default=3;
21053 * @property clickPixelThresh
21057 clickPixelThresh: 3,
21060 * The number of milliseconds after the mousedown event to initiate the
21061 * drag if we don't get a mouseup event. Default=1000
21062 * @property clickTimeThresh
21066 clickTimeThresh: 350,
21069 * Flag that indicates that either the drag pixel threshold or the
21070 * mousdown time threshold has been met
21071 * @property dragThreshMet
21076 dragThreshMet: false,
21079 * Timeout used for the click time threshold
21080 * @property clickTimeout
21085 clickTimeout: null,
21088 * The X position of the mousedown event stored for later use when a
21089 * drag threshold is met.
21098 * The Y position of the mousedown event stored for later use when a
21099 * drag threshold is met.
21108 * Each DragDrop instance must be registered with the DragDropMgr.
21109 * This is executed in DragDrop.init()
21110 * @method regDragDrop
21111 * @param {DragDrop} oDD the DragDrop object to register
21112 * @param {String} sGroup the name of the group this element belongs to
21115 regDragDrop: function(oDD, sGroup) {
21116 if (!this.initialized) { this.init(); }
21118 if (!this.ids[sGroup]) {
21119 this.ids[sGroup] = {};
21121 this.ids[sGroup][oDD.id] = oDD;
21125 * Removes the supplied dd instance from the supplied group. Executed
21126 * by DragDrop.removeFromGroup, so don't call this function directly.
21127 * @method removeDDFromGroup
21131 removeDDFromGroup: function(oDD, sGroup) {
21132 if (!this.ids[sGroup]) {
21133 this.ids[sGroup] = {};
21136 var obj = this.ids[sGroup];
21137 if (obj && obj[oDD.id]) {
21138 delete obj[oDD.id];
21143 * Unregisters a drag and drop item. This is executed in
21144 * DragDrop.unreg, use that method instead of calling this directly.
21149 _remove: function(oDD) {
21150 for (var g in oDD.groups) {
21151 if (g && this.ids[g][oDD.id]) {
21152 delete this.ids[g][oDD.id];
21155 delete this.handleIds[oDD.id];
21159 * Each DragDrop handle element must be registered. This is done
21160 * automatically when executing DragDrop.setHandleElId()
21161 * @method regHandle
21162 * @param {String} sDDId the DragDrop id this element is a handle for
21163 * @param {String} sHandleId the id of the element that is the drag
21167 regHandle: function(sDDId, sHandleId) {
21168 if (!this.handleIds[sDDId]) {
21169 this.handleIds[sDDId] = {};
21171 this.handleIds[sDDId][sHandleId] = sHandleId;
21175 * Utility function to determine if a given element has been
21176 * registered as a drag drop item.
21177 * @method isDragDrop
21178 * @param {String} id the element id to check
21179 * @return {boolean} true if this element is a DragDrop item,
21183 isDragDrop: function(id) {
21184 return ( this.getDDById(id) ) ? true : false;
21188 * Returns the drag and drop instances that are in all groups the
21189 * passed in instance belongs to.
21190 * @method getRelated
21191 * @param {DragDrop} p_oDD the obj to get related data for
21192 * @param {boolean} bTargetsOnly if true, only return targetable objs
21193 * @return {DragDrop[]} the related instances
21196 getRelated: function(p_oDD, bTargetsOnly) {
21198 for (var i in p_oDD.groups) {
21199 for (j in this.ids[i]) {
21200 var dd = this.ids[i][j];
21201 if (! this.isTypeOfDD(dd)) {
21204 if (!bTargetsOnly || dd.isTarget) {
21205 oDDs[oDDs.length] = dd;
21214 * Returns true if the specified dd target is a legal target for
21215 * the specifice drag obj
21216 * @method isLegalTarget
21217 * @param {DragDrop} the drag obj
21218 * @param {DragDrop} the target
21219 * @return {boolean} true if the target is a legal target for the
21223 isLegalTarget: function (oDD, oTargetDD) {
21224 var targets = this.getRelated(oDD, true);
21225 for (var i=0, len=targets.length;i<len;++i) {
21226 if (targets[i].id == oTargetDD.id) {
21235 * My goal is to be able to transparently determine if an object is
21236 * typeof DragDrop, and the exact subclass of DragDrop. typeof
21237 * returns "object", oDD.constructor.toString() always returns
21238 * "DragDrop" and not the name of the subclass. So for now it just
21239 * evaluates a well-known variable in DragDrop.
21240 * @method isTypeOfDD
21241 * @param {Object} the object to evaluate
21242 * @return {boolean} true if typeof oDD = DragDrop
21245 isTypeOfDD: function (oDD) {
21246 return (oDD && oDD.__ygDragDrop);
21250 * Utility function to determine if a given element has been
21251 * registered as a drag drop handle for the given Drag Drop object.
21253 * @param {String} id the element id to check
21254 * @return {boolean} true if this element is a DragDrop handle, false
21258 isHandle: function(sDDId, sHandleId) {
21259 return ( this.handleIds[sDDId] &&
21260 this.handleIds[sDDId][sHandleId] );
21264 * Returns the DragDrop instance for a given id
21265 * @method getDDById
21266 * @param {String} id the id of the DragDrop object
21267 * @return {DragDrop} the drag drop object, null if it is not found
21270 getDDById: function(id) {
21271 for (var i in this.ids) {
21272 if (this.ids[i][id]) {
21273 return this.ids[i][id];
21280 * Fired after a registered DragDrop object gets the mousedown event.
21281 * Sets up the events required to track the object being dragged
21282 * @method handleMouseDown
21283 * @param {Event} e the event
21284 * @param oDD the DragDrop object being dragged
21288 handleMouseDown: function(e, oDD) {
21290 Roo.QuickTips.disable();
21292 this.currentTarget = e.getTarget();
21294 this.dragCurrent = oDD;
21296 var el = oDD.getEl();
21298 // track start position
21299 this.startX = e.getPageX();
21300 this.startY = e.getPageY();
21302 this.deltaX = this.startX - el.offsetLeft;
21303 this.deltaY = this.startY - el.offsetTop;
21305 this.dragThreshMet = false;
21307 this.clickTimeout = setTimeout(
21309 var DDM = Roo.dd.DDM;
21310 DDM.startDrag(DDM.startX, DDM.startY);
21312 this.clickTimeThresh );
21316 * Fired when either the drag pixel threshol or the mousedown hold
21317 * time threshold has been met.
21318 * @method startDrag
21319 * @param x {int} the X position of the original mousedown
21320 * @param y {int} the Y position of the original mousedown
21323 startDrag: function(x, y) {
21324 clearTimeout(this.clickTimeout);
21325 if (this.dragCurrent) {
21326 this.dragCurrent.b4StartDrag(x, y);
21327 this.dragCurrent.startDrag(x, y);
21329 this.dragThreshMet = true;
21333 * Internal function to handle the mouseup event. Will be invoked
21334 * from the context of the document.
21335 * @method handleMouseUp
21336 * @param {Event} e the event
21340 handleMouseUp: function(e) {
21343 Roo.QuickTips.enable();
21345 if (! this.dragCurrent) {
21349 clearTimeout(this.clickTimeout);
21351 if (this.dragThreshMet) {
21352 this.fireEvents(e, true);
21362 * Utility to stop event propagation and event default, if these
21363 * features are turned on.
21364 * @method stopEvent
21365 * @param {Event} e the event as returned by this.getEvent()
21368 stopEvent: function(e){
21369 if(this.stopPropagation) {
21370 e.stopPropagation();
21373 if (this.preventDefault) {
21374 e.preventDefault();
21379 * Internal function to clean up event handlers after the drag
21380 * operation is complete
21382 * @param {Event} e the event
21386 stopDrag: function(e) {
21387 // Fire the drag end event for the item that was dragged
21388 if (this.dragCurrent) {
21389 if (this.dragThreshMet) {
21390 this.dragCurrent.b4EndDrag(e);
21391 this.dragCurrent.endDrag(e);
21394 this.dragCurrent.onMouseUp(e);
21397 this.dragCurrent = null;
21398 this.dragOvers = {};
21402 * Internal function to handle the mousemove event. Will be invoked
21403 * from the context of the html element.
21405 * @TODO figure out what we can do about mouse events lost when the
21406 * user drags objects beyond the window boundary. Currently we can
21407 * detect this in internet explorer by verifying that the mouse is
21408 * down during the mousemove event. Firefox doesn't give us the
21409 * button state on the mousemove event.
21410 * @method handleMouseMove
21411 * @param {Event} e the event
21415 handleMouseMove: function(e) {
21416 if (! this.dragCurrent) {
21420 // var button = e.which || e.button;
21422 // check for IE mouseup outside of page boundary
21423 if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
21425 return this.handleMouseUp(e);
21428 if (!this.dragThreshMet) {
21429 var diffX = Math.abs(this.startX - e.getPageX());
21430 var diffY = Math.abs(this.startY - e.getPageY());
21431 if (diffX > this.clickPixelThresh ||
21432 diffY > this.clickPixelThresh) {
21433 this.startDrag(this.startX, this.startY);
21437 if (this.dragThreshMet) {
21438 this.dragCurrent.b4Drag(e);
21439 this.dragCurrent.onDrag(e);
21440 if(!this.dragCurrent.moveOnly){
21441 this.fireEvents(e, false);
21451 * Iterates over all of the DragDrop elements to find ones we are
21452 * hovering over or dropping on
21453 * @method fireEvents
21454 * @param {Event} e the event
21455 * @param {boolean} isDrop is this a drop op or a mouseover op?
21459 fireEvents: function(e, isDrop) {
21460 var dc = this.dragCurrent;
21462 // If the user did the mouse up outside of the window, we could
21463 // get here even though we have ended the drag.
21464 if (!dc || dc.isLocked()) {
21468 var pt = e.getPoint();
21470 // cache the previous dragOver array
21476 var enterEvts = [];
21478 // Check to see if the object(s) we were hovering over is no longer
21479 // being hovered over so we can fire the onDragOut event
21480 for (var i in this.dragOvers) {
21482 var ddo = this.dragOvers[i];
21484 if (! this.isTypeOfDD(ddo)) {
21488 if (! this.isOverTarget(pt, ddo, this.mode)) {
21489 outEvts.push( ddo );
21492 oldOvers[i] = true;
21493 delete this.dragOvers[i];
21496 for (var sGroup in dc.groups) {
21498 if ("string" != typeof sGroup) {
21502 for (i in this.ids[sGroup]) {
21503 var oDD = this.ids[sGroup][i];
21504 if (! this.isTypeOfDD(oDD)) {
21508 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
21509 if (this.isOverTarget(pt, oDD, this.mode)) {
21510 // look for drop interactions
21512 dropEvts.push( oDD );
21513 // look for drag enter and drag over interactions
21516 // initial drag over: dragEnter fires
21517 if (!oldOvers[oDD.id]) {
21518 enterEvts.push( oDD );
21519 // subsequent drag overs: dragOver fires
21521 overEvts.push( oDD );
21524 this.dragOvers[oDD.id] = oDD;
21532 if (outEvts.length) {
21533 dc.b4DragOut(e, outEvts);
21534 dc.onDragOut(e, outEvts);
21537 if (enterEvts.length) {
21538 dc.onDragEnter(e, enterEvts);
21541 if (overEvts.length) {
21542 dc.b4DragOver(e, overEvts);
21543 dc.onDragOver(e, overEvts);
21546 if (dropEvts.length) {
21547 dc.b4DragDrop(e, dropEvts);
21548 dc.onDragDrop(e, dropEvts);
21552 // fire dragout events
21554 for (i=0, len=outEvts.length; i<len; ++i) {
21555 dc.b4DragOut(e, outEvts[i].id);
21556 dc.onDragOut(e, outEvts[i].id);
21559 // fire enter events
21560 for (i=0,len=enterEvts.length; i<len; ++i) {
21561 // dc.b4DragEnter(e, oDD.id);
21562 dc.onDragEnter(e, enterEvts[i].id);
21565 // fire over events
21566 for (i=0,len=overEvts.length; i<len; ++i) {
21567 dc.b4DragOver(e, overEvts[i].id);
21568 dc.onDragOver(e, overEvts[i].id);
21571 // fire drop events
21572 for (i=0, len=dropEvts.length; i<len; ++i) {
21573 dc.b4DragDrop(e, dropEvts[i].id);
21574 dc.onDragDrop(e, dropEvts[i].id);
21579 // notify about a drop that did not find a target
21580 if (isDrop && !dropEvts.length) {
21581 dc.onInvalidDrop(e);
21587 * Helper function for getting the best match from the list of drag
21588 * and drop objects returned by the drag and drop events when we are
21589 * in INTERSECT mode. It returns either the first object that the
21590 * cursor is over, or the object that has the greatest overlap with
21591 * the dragged element.
21592 * @method getBestMatch
21593 * @param {DragDrop[]} dds The array of drag and drop objects
21595 * @return {DragDrop} The best single match
21598 getBestMatch: function(dds) {
21600 // Return null if the input is not what we expect
21601 //if (!dds || !dds.length || dds.length == 0) {
21603 // If there is only one item, it wins
21604 //} else if (dds.length == 1) {
21606 var len = dds.length;
21611 // Loop through the targeted items
21612 for (var i=0; i<len; ++i) {
21614 // If the cursor is over the object, it wins. If the
21615 // cursor is over multiple matches, the first one we come
21617 if (dd.cursorIsOver) {
21620 // Otherwise the object with the most overlap wins
21623 winner.overlap.getArea() < dd.overlap.getArea()) {
21634 * Refreshes the cache of the top-left and bottom-right points of the
21635 * drag and drop objects in the specified group(s). This is in the
21636 * format that is stored in the drag and drop instance, so typical
21639 * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
21643 * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
21645 * @TODO this really should be an indexed array. Alternatively this
21646 * method could accept both.
21647 * @method refreshCache
21648 * @param {Object} groups an associative array of groups to refresh
21651 refreshCache: function(groups) {
21652 for (var sGroup in groups) {
21653 if ("string" != typeof sGroup) {
21656 for (var i in this.ids[sGroup]) {
21657 var oDD = this.ids[sGroup][i];
21659 if (this.isTypeOfDD(oDD)) {
21660 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
21661 var loc = this.getLocation(oDD);
21663 this.locationCache[oDD.id] = loc;
21665 delete this.locationCache[oDD.id];
21666 // this will unregister the drag and drop object if
21667 // the element is not in a usable state
21676 * This checks to make sure an element exists and is in the DOM. The
21677 * main purpose is to handle cases where innerHTML is used to remove
21678 * drag and drop objects from the DOM. IE provides an 'unspecified
21679 * error' when trying to access the offsetParent of such an element
21681 * @param {HTMLElement} el the element to check
21682 * @return {boolean} true if the element looks usable
21685 verifyEl: function(el) {
21690 parent = el.offsetParent;
21693 parent = el.offsetParent;
21704 * Returns a Region object containing the drag and drop element's position
21705 * and size, including the padding configured for it
21706 * @method getLocation
21707 * @param {DragDrop} oDD the drag and drop object to get the
21709 * @return {Roo.lib.Region} a Region object representing the total area
21710 * the element occupies, including any padding
21711 * the instance is configured for.
21714 getLocation: function(oDD) {
21715 if (! this.isTypeOfDD(oDD)) {
21719 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
21722 pos= Roo.lib.Dom.getXY(el);
21730 x2 = x1 + el.offsetWidth;
21732 y2 = y1 + el.offsetHeight;
21734 t = y1 - oDD.padding[0];
21735 r = x2 + oDD.padding[1];
21736 b = y2 + oDD.padding[2];
21737 l = x1 - oDD.padding[3];
21739 return new Roo.lib.Region( t, r, b, l );
21743 * Checks the cursor location to see if it over the target
21744 * @method isOverTarget
21745 * @param {Roo.lib.Point} pt The point to evaluate
21746 * @param {DragDrop} oTarget the DragDrop object we are inspecting
21747 * @return {boolean} true if the mouse is over the target
21751 isOverTarget: function(pt, oTarget, intersect) {
21752 // use cache if available
21753 var loc = this.locationCache[oTarget.id];
21754 if (!loc || !this.useCache) {
21755 loc = this.getLocation(oTarget);
21756 this.locationCache[oTarget.id] = loc;
21764 oTarget.cursorIsOver = loc.contains( pt );
21766 // DragDrop is using this as a sanity check for the initial mousedown
21767 // in this case we are done. In POINT mode, if the drag obj has no
21768 // contraints, we are also done. Otherwise we need to evaluate the
21769 // location of the target as related to the actual location of the
21770 // dragged element.
21771 var dc = this.dragCurrent;
21772 if (!dc || !dc.getTargetCoord ||
21773 (!intersect && !dc.constrainX && !dc.constrainY)) {
21774 return oTarget.cursorIsOver;
21777 oTarget.overlap = null;
21779 // Get the current location of the drag element, this is the
21780 // location of the mouse event less the delta that represents
21781 // where the original mousedown happened on the element. We
21782 // need to consider constraints and ticks as well.
21783 var pos = dc.getTargetCoord(pt.x, pt.y);
21785 var el = dc.getDragEl();
21786 var curRegion = new Roo.lib.Region( pos.y,
21787 pos.x + el.offsetWidth,
21788 pos.y + el.offsetHeight,
21791 var overlap = curRegion.intersect(loc);
21794 oTarget.overlap = overlap;
21795 return (intersect) ? true : oTarget.cursorIsOver;
21802 * unload event handler
21803 * @method _onUnload
21807 _onUnload: function(e, me) {
21808 Roo.dd.DragDropMgr.unregAll();
21812 * Cleans up the drag and drop events and objects.
21817 unregAll: function() {
21819 if (this.dragCurrent) {
21821 this.dragCurrent = null;
21824 this._execOnAll("unreg", []);
21826 for (i in this.elementCache) {
21827 delete this.elementCache[i];
21830 this.elementCache = {};
21835 * A cache of DOM elements
21836 * @property elementCache
21843 * Get the wrapper for the DOM element specified
21844 * @method getElWrapper
21845 * @param {String} id the id of the element to get
21846 * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
21848 * @deprecated This wrapper isn't that useful
21851 getElWrapper: function(id) {
21852 var oWrapper = this.elementCache[id];
21853 if (!oWrapper || !oWrapper.el) {
21854 oWrapper = this.elementCache[id] =
21855 new this.ElementWrapper(Roo.getDom(id));
21861 * Returns the actual DOM element
21862 * @method getElement
21863 * @param {String} id the id of the elment to get
21864 * @return {Object} The element
21865 * @deprecated use Roo.getDom instead
21868 getElement: function(id) {
21869 return Roo.getDom(id);
21873 * Returns the style property for the DOM element (i.e.,
21874 * document.getElById(id).style)
21876 * @param {String} id the id of the elment to get
21877 * @return {Object} The style property of the element
21878 * @deprecated use Roo.getDom instead
21881 getCss: function(id) {
21882 var el = Roo.getDom(id);
21883 return (el) ? el.style : null;
21887 * Inner class for cached elements
21888 * @class DragDropMgr.ElementWrapper
21893 ElementWrapper: function(el) {
21898 this.el = el || null;
21903 this.id = this.el && el.id;
21905 * A reference to the style property
21908 this.css = this.el && el.style;
21912 * Returns the X position of an html element
21914 * @param el the element for which to get the position
21915 * @return {int} the X coordinate
21917 * @deprecated use Roo.lib.Dom.getX instead
21920 getPosX: function(el) {
21921 return Roo.lib.Dom.getX(el);
21925 * Returns the Y position of an html element
21927 * @param el the element for which to get the position
21928 * @return {int} the Y coordinate
21929 * @deprecated use Roo.lib.Dom.getY instead
21932 getPosY: function(el) {
21933 return Roo.lib.Dom.getY(el);
21937 * Swap two nodes. In IE, we use the native method, for others we
21938 * emulate the IE behavior
21940 * @param n1 the first node to swap
21941 * @param n2 the other node to swap
21944 swapNode: function(n1, n2) {
21948 var p = n2.parentNode;
21949 var s = n2.nextSibling;
21952 p.insertBefore(n1, n2);
21953 } else if (n2 == n1.nextSibling) {
21954 p.insertBefore(n2, n1);
21956 n1.parentNode.replaceChild(n2, n1);
21957 p.insertBefore(n1, s);
21963 * Returns the current scroll position
21964 * @method getScroll
21968 getScroll: function () {
21969 var t, l, dde=document.documentElement, db=document.body;
21970 if (dde && (dde.scrollTop || dde.scrollLeft)) {
21972 l = dde.scrollLeft;
21979 return { top: t, left: l };
21983 * Returns the specified element style property
21985 * @param {HTMLElement} el the element
21986 * @param {string} styleProp the style property
21987 * @return {string} The value of the style property
21988 * @deprecated use Roo.lib.Dom.getStyle
21991 getStyle: function(el, styleProp) {
21992 return Roo.fly(el).getStyle(styleProp);
21996 * Gets the scrollTop
21997 * @method getScrollTop
21998 * @return {int} the document's scrollTop
22001 getScrollTop: function () { return this.getScroll().top; },
22004 * Gets the scrollLeft
22005 * @method getScrollLeft
22006 * @return {int} the document's scrollTop
22009 getScrollLeft: function () { return this.getScroll().left; },
22012 * Sets the x/y position of an element to the location of the
22015 * @param {HTMLElement} moveEl The element to move
22016 * @param {HTMLElement} targetEl The position reference element
22019 moveToEl: function (moveEl, targetEl) {
22020 var aCoord = Roo.lib.Dom.getXY(targetEl);
22021 Roo.lib.Dom.setXY(moveEl, aCoord);
22025 * Numeric array sort function
22026 * @method numericSort
22029 numericSort: function(a, b) { return (a - b); },
22033 * @property _timeoutCount
22040 * Trying to make the load order less important. Without this we get
22041 * an error if this file is loaded before the Event Utility.
22042 * @method _addListeners
22046 _addListeners: function() {
22047 var DDM = Roo.dd.DDM;
22048 if ( Roo.lib.Event && document ) {
22051 if (DDM._timeoutCount > 2000) {
22053 setTimeout(DDM._addListeners, 10);
22054 if (document && document.body) {
22055 DDM._timeoutCount += 1;
22062 * Recursively searches the immediate parent and all child nodes for
22063 * the handle element in order to determine wheter or not it was
22065 * @method handleWasClicked
22066 * @param node the html element to inspect
22069 handleWasClicked: function(node, id) {
22070 if (this.isHandle(id, node.id)) {
22073 // check to see if this is a text node child of the one we want
22074 var p = node.parentNode;
22077 if (this.isHandle(id, p.id)) {
22092 // shorter alias, save a few bytes
22093 Roo.dd.DDM = Roo.dd.DragDropMgr;
22094 Roo.dd.DDM._addListeners();
22098 * Ext JS Library 1.1.1
22099 * Copyright(c) 2006-2007, Ext JS, LLC.
22101 * Originally Released Under LGPL - original licence link has changed is not relivant.
22104 * <script type="text/javascript">
22109 * A DragDrop implementation where the linked element follows the
22110 * mouse cursor during a drag.
22111 * @extends Roo.dd.DragDrop
22113 * @param {String} id the id of the linked element
22114 * @param {String} sGroup the group of related DragDrop items
22115 * @param {object} config an object containing configurable attributes
22116 * Valid properties for DD:
22119 Roo.dd.DD = function(id, sGroup, config) {
22121 this.init(id, sGroup, config);
22125 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
22128 * When set to true, the utility automatically tries to scroll the browser
22129 * window wehn a drag and drop element is dragged near the viewport boundary.
22130 * Defaults to true.
22137 * Sets the pointer offset to the distance between the linked element's top
22138 * left corner and the location the element was clicked
22139 * @method autoOffset
22140 * @param {int} iPageX the X coordinate of the click
22141 * @param {int} iPageY the Y coordinate of the click
22143 autoOffset: function(iPageX, iPageY) {
22144 var x = iPageX - this.startPageX;
22145 var y = iPageY - this.startPageY;
22146 this.setDelta(x, y);
22150 * Sets the pointer offset. You can call this directly to force the
22151 * offset to be in a particular location (e.g., pass in 0,0 to set it
22152 * to the center of the object)
22154 * @param {int} iDeltaX the distance from the left
22155 * @param {int} iDeltaY the distance from the top
22157 setDelta: function(iDeltaX, iDeltaY) {
22158 this.deltaX = iDeltaX;
22159 this.deltaY = iDeltaY;
22163 * Sets the drag element to the location of the mousedown or click event,
22164 * maintaining the cursor location relative to the location on the element
22165 * that was clicked. Override this if you want to place the element in a
22166 * location other than where the cursor is.
22167 * @method setDragElPos
22168 * @param {int} iPageX the X coordinate of the mousedown or drag event
22169 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22171 setDragElPos: function(iPageX, iPageY) {
22172 // the first time we do this, we are going to check to make sure
22173 // the element has css positioning
22175 var el = this.getDragEl();
22176 this.alignElWithMouse(el, iPageX, iPageY);
22180 * Sets the element to the location of the mousedown or click event,
22181 * maintaining the cursor location relative to the location on the element
22182 * that was clicked. Override this if you want to place the element in a
22183 * location other than where the cursor is.
22184 * @method alignElWithMouse
22185 * @param {HTMLElement} el the element to move
22186 * @param {int} iPageX the X coordinate of the mousedown or drag event
22187 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22189 alignElWithMouse: function(el, iPageX, iPageY) {
22190 var oCoord = this.getTargetCoord(iPageX, iPageY);
22191 var fly = el.dom ? el : Roo.fly(el);
22192 if (!this.deltaSetXY) {
22193 var aCoord = [oCoord.x, oCoord.y];
22195 var newLeft = fly.getLeft(true);
22196 var newTop = fly.getTop(true);
22197 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
22199 fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
22202 this.cachePosition(oCoord.x, oCoord.y);
22203 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
22208 * Saves the most recent position so that we can reset the constraints and
22209 * tick marks on-demand. We need to know this so that we can calculate the
22210 * number of pixels the element is offset from its original position.
22211 * @method cachePosition
22212 * @param iPageX the current x position (optional, this just makes it so we
22213 * don't have to look it up again)
22214 * @param iPageY the current y position (optional, this just makes it so we
22215 * don't have to look it up again)
22217 cachePosition: function(iPageX, iPageY) {
22219 this.lastPageX = iPageX;
22220 this.lastPageY = iPageY;
22222 var aCoord = Roo.lib.Dom.getXY(this.getEl());
22223 this.lastPageX = aCoord[0];
22224 this.lastPageY = aCoord[1];
22229 * Auto-scroll the window if the dragged object has been moved beyond the
22230 * visible window boundary.
22231 * @method autoScroll
22232 * @param {int} x the drag element's x position
22233 * @param {int} y the drag element's y position
22234 * @param {int} h the height of the drag element
22235 * @param {int} w the width of the drag element
22238 autoScroll: function(x, y, h, w) {
22241 // The client height
22242 var clientH = Roo.lib.Dom.getViewWidth();
22244 // The client width
22245 var clientW = Roo.lib.Dom.getViewHeight();
22247 // The amt scrolled down
22248 var st = this.DDM.getScrollTop();
22250 // The amt scrolled right
22251 var sl = this.DDM.getScrollLeft();
22253 // Location of the bottom of the element
22256 // Location of the right of the element
22259 // The distance from the cursor to the bottom of the visible area,
22260 // adjusted so that we don't scroll if the cursor is beyond the
22261 // element drag constraints
22262 var toBot = (clientH + st - y - this.deltaY);
22264 // The distance from the cursor to the right of the visible area
22265 var toRight = (clientW + sl - x - this.deltaX);
22268 // How close to the edge the cursor must be before we scroll
22269 // var thresh = (document.all) ? 100 : 40;
22272 // How many pixels to scroll per autoscroll op. This helps to reduce
22273 // clunky scrolling. IE is more sensitive about this ... it needs this
22274 // value to be higher.
22275 var scrAmt = (document.all) ? 80 : 30;
22277 // Scroll down if we are near the bottom of the visible page and the
22278 // obj extends below the crease
22279 if ( bot > clientH && toBot < thresh ) {
22280 window.scrollTo(sl, st + scrAmt);
22283 // Scroll up if the window is scrolled down and the top of the object
22284 // goes above the top border
22285 if ( y < st && st > 0 && y - st < thresh ) {
22286 window.scrollTo(sl, st - scrAmt);
22289 // Scroll right if the obj is beyond the right border and the cursor is
22290 // near the border.
22291 if ( right > clientW && toRight < thresh ) {
22292 window.scrollTo(sl + scrAmt, st);
22295 // Scroll left if the window has been scrolled to the right and the obj
22296 // extends past the left border
22297 if ( x < sl && sl > 0 && x - sl < thresh ) {
22298 window.scrollTo(sl - scrAmt, st);
22304 * Finds the location the element should be placed if we want to move
22305 * it to where the mouse location less the click offset would place us.
22306 * @method getTargetCoord
22307 * @param {int} iPageX the X coordinate of the click
22308 * @param {int} iPageY the Y coordinate of the click
22309 * @return an object that contains the coordinates (Object.x and Object.y)
22312 getTargetCoord: function(iPageX, iPageY) {
22315 var x = iPageX - this.deltaX;
22316 var y = iPageY - this.deltaY;
22318 if (this.constrainX) {
22319 if (x < this.minX) { x = this.minX; }
22320 if (x > this.maxX) { x = this.maxX; }
22323 if (this.constrainY) {
22324 if (y < this.minY) { y = this.minY; }
22325 if (y > this.maxY) { y = this.maxY; }
22328 x = this.getTick(x, this.xTicks);
22329 y = this.getTick(y, this.yTicks);
22336 * Sets up config options specific to this class. Overrides
22337 * Roo.dd.DragDrop, but all versions of this method through the
22338 * inheritance chain are called
22340 applyConfig: function() {
22341 Roo.dd.DD.superclass.applyConfig.call(this);
22342 this.scroll = (this.config.scroll !== false);
22346 * Event that fires prior to the onMouseDown event. Overrides
22349 b4MouseDown: function(e) {
22350 // this.resetConstraints();
22351 this.autoOffset(e.getPageX(),
22356 * Event that fires prior to the onDrag event. Overrides
22359 b4Drag: function(e) {
22360 this.setDragElPos(e.getPageX(),
22364 toString: function() {
22365 return ("DD " + this.id);
22368 //////////////////////////////////////////////////////////////////////////
22369 // Debugging ygDragDrop events that can be overridden
22370 //////////////////////////////////////////////////////////////////////////
22372 startDrag: function(x, y) {
22375 onDrag: function(e) {
22378 onDragEnter: function(e, id) {
22381 onDragOver: function(e, id) {
22384 onDragOut: function(e, id) {
22387 onDragDrop: function(e, id) {
22390 endDrag: function(e) {
22397 * Ext JS Library 1.1.1
22398 * Copyright(c) 2006-2007, Ext JS, LLC.
22400 * Originally Released Under LGPL - original licence link has changed is not relivant.
22403 * <script type="text/javascript">
22407 * @class Roo.dd.DDProxy
22408 * A DragDrop implementation that inserts an empty, bordered div into
22409 * the document that follows the cursor during drag operations. At the time of
22410 * the click, the frame div is resized to the dimensions of the linked html
22411 * element, and moved to the exact location of the linked element.
22413 * References to the "frame" element refer to the single proxy element that
22414 * was created to be dragged in place of all DDProxy elements on the
22417 * @extends Roo.dd.DD
22419 * @param {String} id the id of the linked html element
22420 * @param {String} sGroup the group of related DragDrop objects
22421 * @param {object} config an object containing configurable attributes
22422 * Valid properties for DDProxy in addition to those in DragDrop:
22423 * resizeFrame, centerFrame, dragElId
22425 Roo.dd.DDProxy = function(id, sGroup, config) {
22427 this.init(id, sGroup, config);
22433 * The default drag frame div id
22434 * @property Roo.dd.DDProxy.dragElId
22438 Roo.dd.DDProxy.dragElId = "ygddfdiv";
22440 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
22443 * By default we resize the drag frame to be the same size as the element
22444 * we want to drag (this is to get the frame effect). We can turn it off
22445 * if we want a different behavior.
22446 * @property resizeFrame
22452 * By default the frame is positioned exactly where the drag element is, so
22453 * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
22454 * you do not have constraints on the obj is to have the drag frame centered
22455 * around the cursor. Set centerFrame to true for this effect.
22456 * @property centerFrame
22459 centerFrame: false,
22462 * Creates the proxy element if it does not yet exist
22463 * @method createFrame
22465 createFrame: function() {
22467 var body = document.body;
22469 if (!body || !body.firstChild) {
22470 setTimeout( function() { self.createFrame(); }, 50 );
22474 var div = this.getDragEl();
22477 div = document.createElement("div");
22478 div.id = this.dragElId;
22481 s.position = "absolute";
22482 s.visibility = "hidden";
22484 s.border = "2px solid #aaa";
22487 // appendChild can blow up IE if invoked prior to the window load event
22488 // while rendering a table. It is possible there are other scenarios
22489 // that would cause this to happen as well.
22490 body.insertBefore(div, body.firstChild);
22495 * Initialization for the drag frame element. Must be called in the
22496 * constructor of all subclasses
22497 * @method initFrame
22499 initFrame: function() {
22500 this.createFrame();
22503 applyConfig: function() {
22504 Roo.dd.DDProxy.superclass.applyConfig.call(this);
22506 this.resizeFrame = (this.config.resizeFrame !== false);
22507 this.centerFrame = (this.config.centerFrame);
22508 this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
22512 * Resizes the drag frame to the dimensions of the clicked object, positions
22513 * it over the object, and finally displays it
22514 * @method showFrame
22515 * @param {int} iPageX X click position
22516 * @param {int} iPageY Y click position
22519 showFrame: function(iPageX, iPageY) {
22520 var el = this.getEl();
22521 var dragEl = this.getDragEl();
22522 var s = dragEl.style;
22524 this._resizeProxy();
22526 if (this.centerFrame) {
22527 this.setDelta( Math.round(parseInt(s.width, 10)/2),
22528 Math.round(parseInt(s.height, 10)/2) );
22531 this.setDragElPos(iPageX, iPageY);
22533 Roo.fly(dragEl).show();
22537 * The proxy is automatically resized to the dimensions of the linked
22538 * element when a drag is initiated, unless resizeFrame is set to false
22539 * @method _resizeProxy
22542 _resizeProxy: function() {
22543 if (this.resizeFrame) {
22544 var el = this.getEl();
22545 Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
22549 // overrides Roo.dd.DragDrop
22550 b4MouseDown: function(e) {
22551 var x = e.getPageX();
22552 var y = e.getPageY();
22553 this.autoOffset(x, y);
22554 this.setDragElPos(x, y);
22557 // overrides Roo.dd.DragDrop
22558 b4StartDrag: function(x, y) {
22559 // show the drag frame
22560 this.showFrame(x, y);
22563 // overrides Roo.dd.DragDrop
22564 b4EndDrag: function(e) {
22565 Roo.fly(this.getDragEl()).hide();
22568 // overrides Roo.dd.DragDrop
22569 // By default we try to move the element to the last location of the frame.
22570 // This is so that the default behavior mirrors that of Roo.dd.DD.
22571 endDrag: function(e) {
22573 var lel = this.getEl();
22574 var del = this.getDragEl();
22576 // Show the drag frame briefly so we can get its position
22577 del.style.visibility = "";
22580 // Hide the linked element before the move to get around a Safari
22582 lel.style.visibility = "hidden";
22583 Roo.dd.DDM.moveToEl(lel, del);
22584 del.style.visibility = "hidden";
22585 lel.style.visibility = "";
22590 beforeMove : function(){
22594 afterDrag : function(){
22598 toString: function() {
22599 return ("DDProxy " + this.id);
22605 * Ext JS Library 1.1.1
22606 * Copyright(c) 2006-2007, Ext JS, LLC.
22608 * Originally Released Under LGPL - original licence link has changed is not relivant.
22611 * <script type="text/javascript">
22615 * @class Roo.dd.DDTarget
22616 * A DragDrop implementation that does not move, but can be a drop
22617 * target. You would get the same result by simply omitting implementation
22618 * for the event callbacks, but this way we reduce the processing cost of the
22619 * event listener and the callbacks.
22620 * @extends Roo.dd.DragDrop
22622 * @param {String} id the id of the element that is a drop target
22623 * @param {String} sGroup the group of related DragDrop objects
22624 * @param {object} config an object containing configurable attributes
22625 * Valid properties for DDTarget in addition to those in
22629 Roo.dd.DDTarget = function(id, sGroup, config) {
22631 this.initTarget(id, sGroup, config);
22633 if (config && (config.listeners || config.events)) {
22634 Roo.dd.DragDrop.superclass.constructor.call(this, {
22635 listeners : config.listeners || {},
22636 events : config.events || {}
22641 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
22642 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
22643 toString: function() {
22644 return ("DDTarget " + this.id);
22649 * Ext JS Library 1.1.1
22650 * Copyright(c) 2006-2007, Ext JS, LLC.
22652 * Originally Released Under LGPL - original licence link has changed is not relivant.
22655 * <script type="text/javascript">
22660 * @class Roo.dd.ScrollManager
22661 * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
22662 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
22665 Roo.dd.ScrollManager = function(){
22666 var ddm = Roo.dd.DragDropMgr;
22673 var onStop = function(e){
22678 var triggerRefresh = function(){
22679 if(ddm.dragCurrent){
22680 ddm.refreshCache(ddm.dragCurrent.groups);
22684 var doScroll = function(){
22685 if(ddm.dragCurrent){
22686 var dds = Roo.dd.ScrollManager;
22688 if(proc.el.scroll(proc.dir, dds.increment)){
22692 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
22697 var clearProc = function(){
22699 clearInterval(proc.id);
22706 var startProc = function(el, dir){
22707 Roo.log('scroll startproc');
22711 proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
22714 var onFire = function(e, isDrop){
22716 if(isDrop || !ddm.dragCurrent){ return; }
22717 var dds = Roo.dd.ScrollManager;
22718 if(!dragEl || dragEl != ddm.dragCurrent){
22719 dragEl = ddm.dragCurrent;
22720 // refresh regions on drag start
22721 dds.refreshCache();
22724 var xy = Roo.lib.Event.getXY(e);
22725 var pt = new Roo.lib.Point(xy[0], xy[1]);
22726 for(var id in els){
22727 var el = els[id], r = el._region;
22728 if(r && r.contains(pt) && el.isScrollable()){
22729 if(r.bottom - pt.y <= dds.thresh){
22731 startProc(el, "down");
22734 }else if(r.right - pt.x <= dds.thresh){
22736 startProc(el, "left");
22739 }else if(pt.y - r.top <= dds.thresh){
22741 startProc(el, "up");
22744 }else if(pt.x - r.left <= dds.thresh){
22746 startProc(el, "right");
22755 ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
22756 ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
22760 * Registers new overflow element(s) to auto scroll
22761 * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
22763 register : function(el){
22764 if(el instanceof Array){
22765 for(var i = 0, len = el.length; i < len; i++) {
22766 this.register(el[i]);
22772 Roo.dd.ScrollManager.els = els;
22776 * Unregisters overflow element(s) so they are no longer scrolled
22777 * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
22779 unregister : function(el){
22780 if(el instanceof Array){
22781 for(var i = 0, len = el.length; i < len; i++) {
22782 this.unregister(el[i]);
22791 * The number of pixels from the edge of a container the pointer needs to be to
22792 * trigger scrolling (defaults to 25)
22798 * The number of pixels to scroll in each scroll increment (defaults to 50)
22804 * The frequency of scrolls in milliseconds (defaults to 500)
22810 * True to animate the scroll (defaults to true)
22816 * The animation duration in seconds -
22817 * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
22823 * Manually trigger a cache refresh.
22825 refreshCache : function(){
22826 for(var id in els){
22827 if(typeof els[id] == 'object'){ // for people extending the object prototype
22828 els[id]._region = els[id].getRegion();
22835 * Ext JS Library 1.1.1
22836 * Copyright(c) 2006-2007, Ext JS, LLC.
22838 * Originally Released Under LGPL - original licence link has changed is not relivant.
22841 * <script type="text/javascript">
22846 * @class Roo.dd.Registry
22847 * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
22848 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
22851 Roo.dd.Registry = function(){
22854 var autoIdSeed = 0;
22856 var getId = function(el, autogen){
22857 if(typeof el == "string"){
22861 if(!id && autogen !== false){
22862 id = "roodd-" + (++autoIdSeed);
22870 * Register a drag drop element
22871 * @param {String|HTMLElement} element The id or DOM node to register
22872 * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
22873 * in drag drop operations. You can populate this object with any arbitrary properties that your own code
22874 * knows how to interpret, plus there are some specific properties known to the Registry that should be
22875 * populated in the data object (if applicable):
22877 Value Description<br />
22878 --------- ------------------------------------------<br />
22879 handles Array of DOM nodes that trigger dragging<br />
22880 for the element being registered<br />
22881 isHandle True if the element passed in triggers<br />
22882 dragging itself, else false
22885 register : function(el, data){
22887 if(typeof el == "string"){
22888 el = document.getElementById(el);
22891 elements[getId(el)] = data;
22892 if(data.isHandle !== false){
22893 handles[data.ddel.id] = data;
22896 var hs = data.handles;
22897 for(var i = 0, len = hs.length; i < len; i++){
22898 handles[getId(hs[i])] = data;
22904 * Unregister a drag drop element
22905 * @param {String|HTMLElement} element The id or DOM node to unregister
22907 unregister : function(el){
22908 var id = getId(el, false);
22909 var data = elements[id];
22911 delete elements[id];
22913 var hs = data.handles;
22914 for(var i = 0, len = hs.length; i < len; i++){
22915 delete handles[getId(hs[i], false)];
22922 * Returns the handle registered for a DOM Node by id
22923 * @param {String|HTMLElement} id The DOM node or id to look up
22924 * @return {Object} handle The custom handle data
22926 getHandle : function(id){
22927 if(typeof id != "string"){ // must be element?
22930 return handles[id];
22934 * Returns the handle that is registered for the DOM node that is the target of the event
22935 * @param {Event} e The event
22936 * @return {Object} handle The custom handle data
22938 getHandleFromEvent : function(e){
22939 var t = Roo.lib.Event.getTarget(e);
22940 return t ? handles[t.id] : null;
22944 * Returns a custom data object that is registered for a DOM node by id
22945 * @param {String|HTMLElement} id The DOM node or id to look up
22946 * @return {Object} data The custom data
22948 getTarget : function(id){
22949 if(typeof id != "string"){ // must be element?
22952 return elements[id];
22956 * Returns a custom data object that is registered for the DOM node that is the target of the event
22957 * @param {Event} e The event
22958 * @return {Object} data The custom data
22960 getTargetFromEvent : function(e){
22961 var t = Roo.lib.Event.getTarget(e);
22962 return t ? elements[t.id] || handles[t.id] : null;
22967 * Ext JS Library 1.1.1
22968 * Copyright(c) 2006-2007, Ext JS, LLC.
22970 * Originally Released Under LGPL - original licence link has changed is not relivant.
22973 * <script type="text/javascript">
22978 * @class Roo.dd.StatusProxy
22979 * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
22980 * default drag proxy used by all Roo.dd components.
22982 * @param {Object} config
22984 Roo.dd.StatusProxy = function(config){
22985 Roo.apply(this, config);
22986 this.id = this.id || Roo.id();
22987 this.el = new Roo.Layer({
22989 id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
22990 {tag: "div", cls: "x-dd-drop-icon"},
22991 {tag: "div", cls: "x-dd-drag-ghost"}
22994 shadow: !config || config.shadow !== false
22996 this.ghost = Roo.get(this.el.dom.childNodes[1]);
22997 this.dropStatus = this.dropNotAllowed;
23000 Roo.dd.StatusProxy.prototype = {
23002 * @cfg {String} dropAllowed
23003 * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
23005 dropAllowed : "x-dd-drop-ok",
23007 * @cfg {String} dropNotAllowed
23008 * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
23010 dropNotAllowed : "x-dd-drop-nodrop",
23013 * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
23014 * over the current target element.
23015 * @param {String} cssClass The css class for the new drop status indicator image
23017 setStatus : function(cssClass){
23018 cssClass = cssClass || this.dropNotAllowed;
23019 if(this.dropStatus != cssClass){
23020 this.el.replaceClass(this.dropStatus, cssClass);
23021 this.dropStatus = cssClass;
23026 * Resets the status indicator to the default dropNotAllowed value
23027 * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
23029 reset : function(clearGhost){
23030 this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
23031 this.dropStatus = this.dropNotAllowed;
23033 this.ghost.update("");
23038 * Updates the contents of the ghost element
23039 * @param {String} html The html that will replace the current innerHTML of the ghost element
23041 update : function(html){
23042 if(typeof html == "string"){
23043 this.ghost.update(html);
23045 this.ghost.update("");
23046 html.style.margin = "0";
23047 this.ghost.dom.appendChild(html);
23049 // ensure float = none set?? cant remember why though.
23050 var el = this.ghost.dom.firstChild;
23052 Roo.fly(el).setStyle('float', 'none');
23057 * Returns the underlying proxy {@link Roo.Layer}
23058 * @return {Roo.Layer} el
23060 getEl : function(){
23065 * Returns the ghost element
23066 * @return {Roo.Element} el
23068 getGhost : function(){
23074 * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
23076 hide : function(clear){
23084 * Stops the repair animation if it's currently running
23087 if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
23093 * Displays this proxy
23100 * Force the Layer to sync its shadow and shim positions to the element
23107 * Causes the proxy to return to its position of origin via an animation. Should be called after an
23108 * invalid drop operation by the item being dragged.
23109 * @param {Array} xy The XY position of the element ([x, y])
23110 * @param {Function} callback The function to call after the repair is complete
23111 * @param {Object} scope The scope in which to execute the callback
23113 repair : function(xy, callback, scope){
23114 this.callback = callback;
23115 this.scope = scope;
23116 if(xy && this.animRepair !== false){
23117 this.el.addClass("x-dd-drag-repair");
23118 this.el.hideUnders(true);
23119 this.anim = this.el.shift({
23120 duration: this.repairDuration || .5,
23124 callback: this.afterRepair,
23128 this.afterRepair();
23133 afterRepair : function(){
23135 if(typeof this.callback == "function"){
23136 this.callback.call(this.scope || this);
23138 this.callback = null;
23143 * Ext JS Library 1.1.1
23144 * Copyright(c) 2006-2007, Ext JS, LLC.
23146 * Originally Released Under LGPL - original licence link has changed is not relivant.
23149 * <script type="text/javascript">
23153 * @class Roo.dd.DragSource
23154 * @extends Roo.dd.DDProxy
23155 * A simple class that provides the basic implementation needed to make any element draggable.
23157 * @param {String/HTMLElement/Element} el The container element
23158 * @param {Object} config
23160 Roo.dd.DragSource = function(el, config){
23161 this.el = Roo.get(el);
23162 this.dragData = {};
23164 Roo.apply(this, config);
23167 this.proxy = new Roo.dd.StatusProxy();
23170 Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
23171 {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
23173 this.dragging = false;
23176 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
23178 * @cfg {String} dropAllowed
23179 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23181 dropAllowed : "x-dd-drop-ok",
23183 * @cfg {String} dropNotAllowed
23184 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23186 dropNotAllowed : "x-dd-drop-nodrop",
23189 * Returns the data object associated with this drag source
23190 * @return {Object} data An object containing arbitrary data
23192 getDragData : function(e){
23193 return this.dragData;
23197 onDragEnter : function(e, id){
23198 var target = Roo.dd.DragDropMgr.getDDById(id);
23199 this.cachedTarget = target;
23200 if(this.beforeDragEnter(target, e, id) !== false){
23201 if(target.isNotifyTarget){
23202 var status = target.notifyEnter(this, e, this.dragData);
23203 this.proxy.setStatus(status);
23205 this.proxy.setStatus(this.dropAllowed);
23208 if(this.afterDragEnter){
23210 * An empty function by default, but provided so that you can perform a custom action
23211 * when the dragged item enters the drop target by providing an implementation.
23212 * @param {Roo.dd.DragDrop} target The drop target
23213 * @param {Event} e The event object
23214 * @param {String} id The id of the dragged element
23215 * @method afterDragEnter
23217 this.afterDragEnter(target, e, id);
23223 * An empty function by default, but provided so that you can perform a custom action
23224 * before the dragged item enters the drop target and optionally cancel the onDragEnter.
23225 * @param {Roo.dd.DragDrop} target The drop target
23226 * @param {Event} e The event object
23227 * @param {String} id The id of the dragged element
23228 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23230 beforeDragEnter : function(target, e, id){
23235 alignElWithMouse: function() {
23236 Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
23241 onDragOver : function(e, id){
23242 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23243 if(this.beforeDragOver(target, e, id) !== false){
23244 if(target.isNotifyTarget){
23245 var status = target.notifyOver(this, e, this.dragData);
23246 this.proxy.setStatus(status);
23249 if(this.afterDragOver){
23251 * An empty function by default, but provided so that you can perform a custom action
23252 * while the dragged item is over the drop target by providing an implementation.
23253 * @param {Roo.dd.DragDrop} target The drop target
23254 * @param {Event} e The event object
23255 * @param {String} id The id of the dragged element
23256 * @method afterDragOver
23258 this.afterDragOver(target, e, id);
23264 * An empty function by default, but provided so that you can perform a custom action
23265 * while the dragged item is over the drop target and optionally cancel the onDragOver.
23266 * @param {Roo.dd.DragDrop} target The drop target
23267 * @param {Event} e The event object
23268 * @param {String} id The id of the dragged element
23269 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23271 beforeDragOver : function(target, e, id){
23276 onDragOut : function(e, id){
23277 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23278 if(this.beforeDragOut(target, e, id) !== false){
23279 if(target.isNotifyTarget){
23280 target.notifyOut(this, e, this.dragData);
23282 this.proxy.reset();
23283 if(this.afterDragOut){
23285 * An empty function by default, but provided so that you can perform a custom action
23286 * after the dragged item is dragged out of the target without dropping.
23287 * @param {Roo.dd.DragDrop} target The drop target
23288 * @param {Event} e The event object
23289 * @param {String} id The id of the dragged element
23290 * @method afterDragOut
23292 this.afterDragOut(target, e, id);
23295 this.cachedTarget = null;
23299 * An empty function by default, but provided so that you can perform a custom action before the dragged
23300 * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
23301 * @param {Roo.dd.DragDrop} target The drop target
23302 * @param {Event} e The event object
23303 * @param {String} id The id of the dragged element
23304 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23306 beforeDragOut : function(target, e, id){
23311 onDragDrop : function(e, id){
23312 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23313 if(this.beforeDragDrop(target, e, id) !== false){
23314 if(target.isNotifyTarget){
23315 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
23316 this.onValidDrop(target, e, id);
23318 this.onInvalidDrop(target, e, id);
23321 this.onValidDrop(target, e, id);
23324 if(this.afterDragDrop){
23326 * An empty function by default, but provided so that you can perform a custom action
23327 * after a valid drag drop has occurred by providing an implementation.
23328 * @param {Roo.dd.DragDrop} target The drop target
23329 * @param {Event} e The event object
23330 * @param {String} id The id of the dropped element
23331 * @method afterDragDrop
23333 this.afterDragDrop(target, e, id);
23336 delete this.cachedTarget;
23340 * An empty function by default, but provided so that you can perform a custom action before the dragged
23341 * item is dropped onto the target and optionally cancel the onDragDrop.
23342 * @param {Roo.dd.DragDrop} target The drop target
23343 * @param {Event} e The event object
23344 * @param {String} id The id of the dragged element
23345 * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
23347 beforeDragDrop : function(target, e, id){
23352 onValidDrop : function(target, e, id){
23354 if(this.afterValidDrop){
23356 * An empty function by default, but provided so that you can perform a custom action
23357 * after a valid drop has occurred by providing an implementation.
23358 * @param {Object} target The target DD
23359 * @param {Event} e The event object
23360 * @param {String} id The id of the dropped element
23361 * @method afterInvalidDrop
23363 this.afterValidDrop(target, e, id);
23368 getRepairXY : function(e, data){
23369 return this.el.getXY();
23373 onInvalidDrop : function(target, e, id){
23374 this.beforeInvalidDrop(target, e, id);
23375 if(this.cachedTarget){
23376 if(this.cachedTarget.isNotifyTarget){
23377 this.cachedTarget.notifyOut(this, e, this.dragData);
23379 this.cacheTarget = null;
23381 this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
23383 if(this.afterInvalidDrop){
23385 * An empty function by default, but provided so that you can perform a custom action
23386 * after an invalid drop has occurred by providing an implementation.
23387 * @param {Event} e The event object
23388 * @param {String} id The id of the dropped element
23389 * @method afterInvalidDrop
23391 this.afterInvalidDrop(e, id);
23396 afterRepair : function(){
23398 this.el.highlight(this.hlColor || "c3daf9");
23400 this.dragging = false;
23404 * An empty function by default, but provided so that you can perform a custom action after an invalid
23405 * drop has occurred.
23406 * @param {Roo.dd.DragDrop} target The drop target
23407 * @param {Event} e The event object
23408 * @param {String} id The id of the dragged element
23409 * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
23411 beforeInvalidDrop : function(target, e, id){
23416 handleMouseDown : function(e){
23417 if(this.dragging) {
23420 var data = this.getDragData(e);
23421 if(data && this.onBeforeDrag(data, e) !== false){
23422 this.dragData = data;
23424 Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
23429 * An empty function by default, but provided so that you can perform a custom action before the initial
23430 * drag event begins and optionally cancel it.
23431 * @param {Object} data An object containing arbitrary data to be shared with drop targets
23432 * @param {Event} e The event object
23433 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23435 onBeforeDrag : function(data, e){
23440 * An empty function by default, but provided so that you can perform a custom action once the initial
23441 * drag event has begun. The drag cannot be canceled from this function.
23442 * @param {Number} x The x position of the click on the dragged object
23443 * @param {Number} y The y position of the click on the dragged object
23445 onStartDrag : Roo.emptyFn,
23447 // private - YUI override
23448 startDrag : function(x, y){
23449 this.proxy.reset();
23450 this.dragging = true;
23451 this.proxy.update("");
23452 this.onInitDrag(x, y);
23457 onInitDrag : function(x, y){
23458 var clone = this.el.dom.cloneNode(true);
23459 clone.id = Roo.id(); // prevent duplicate ids
23460 this.proxy.update(clone);
23461 this.onStartDrag(x, y);
23466 * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
23467 * @return {Roo.dd.StatusProxy} proxy The StatusProxy
23469 getProxy : function(){
23474 * Hides the drag source's {@link Roo.dd.StatusProxy}
23476 hideProxy : function(){
23478 this.proxy.reset(true);
23479 this.dragging = false;
23483 triggerCacheRefresh : function(){
23484 Roo.dd.DDM.refreshCache(this.groups);
23487 // private - override to prevent hiding
23488 b4EndDrag: function(e) {
23491 // private - override to prevent moving
23492 endDrag : function(e){
23493 this.onEndDrag(this.dragData, e);
23497 onEndDrag : function(data, e){
23500 // private - pin to cursor
23501 autoOffset : function(x, y) {
23502 this.setDelta(-12, -20);
23506 * Ext JS Library 1.1.1
23507 * Copyright(c) 2006-2007, Ext JS, LLC.
23509 * Originally Released Under LGPL - original licence link has changed is not relivant.
23512 * <script type="text/javascript">
23517 * @class Roo.dd.DropTarget
23518 * @extends Roo.dd.DDTarget
23519 * A simple class that provides the basic implementation needed to make any element a drop target that can have
23520 * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
23522 * @param {String/HTMLElement/Element} el The container element
23523 * @param {Object} config
23525 Roo.dd.DropTarget = function(el, config){
23526 this.el = Roo.get(el);
23528 var listeners = false; ;
23529 if (config && config.listeners) {
23530 listeners= config.listeners;
23531 delete config.listeners;
23533 Roo.apply(this, config);
23535 if(this.containerScroll){
23536 Roo.dd.ScrollManager.register(this.el);
23540 * @scope Roo.dd.DropTarget
23545 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
23546 * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
23547 * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
23549 * IMPORTANT : it should set this.valid to true|false
23551 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23552 * @param {Event} e The event
23553 * @param {Object} data An object containing arbitrary data supplied by the drag source
23559 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
23560 * This method will be called on every mouse movement while the drag source is over the drop target.
23561 * This default implementation simply returns the dropAllowed config value.
23563 * IMPORTANT : it should set this.valid to true|false
23565 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23566 * @param {Event} e The event
23567 * @param {Object} data An object containing arbitrary data supplied by the drag source
23573 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
23574 * out of the target without dropping. This default implementation simply removes the CSS class specified by
23575 * overClass (if any) from the drop element.
23578 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23579 * @param {Event} e The event
23580 * @param {Object} data An object containing arbitrary data supplied by the drag source
23586 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
23587 * been dropped on it. This method has no default implementation and returns false, so you must provide an
23588 * implementation that does something to process the drop event and returns true so that the drag source's
23589 * repair action does not run.
23591 * IMPORTANT : it should set this.success
23593 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23594 * @param {Event} e The event
23595 * @param {Object} data An object containing arbitrary data supplied by the drag source
23601 Roo.dd.DropTarget.superclass.constructor.call( this,
23603 this.ddGroup || this.group,
23606 listeners : listeners || {}
23614 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
23616 * @cfg {String} overClass
23617 * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
23620 * @cfg {String} ddGroup
23621 * The drag drop group to handle drop events for
23625 * @cfg {String} dropAllowed
23626 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23628 dropAllowed : "x-dd-drop-ok",
23630 * @cfg {String} dropNotAllowed
23631 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23633 dropNotAllowed : "x-dd-drop-nodrop",
23635 * @cfg {boolean} success
23636 * set this after drop listener..
23640 * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
23641 * if the drop point is valid for over/enter..
23648 isNotifyTarget : true,
23653 notifyEnter : function(dd, e, data)
23656 this.fireEvent('enter', dd, e, data);
23657 if(this.overClass){
23658 this.el.addClass(this.overClass);
23660 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23661 this.valid ? this.dropAllowed : this.dropNotAllowed
23668 notifyOver : function(dd, e, data)
23671 this.fireEvent('over', dd, e, data);
23672 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23673 this.valid ? this.dropAllowed : this.dropNotAllowed
23680 notifyOut : function(dd, e, data)
23682 this.fireEvent('out', dd, e, data);
23683 if(this.overClass){
23684 this.el.removeClass(this.overClass);
23691 notifyDrop : function(dd, e, data)
23693 this.success = false;
23694 this.fireEvent('drop', dd, e, data);
23695 return this.success;
23699 * Ext JS Library 1.1.1
23700 * Copyright(c) 2006-2007, Ext JS, LLC.
23702 * Originally Released Under LGPL - original licence link has changed is not relivant.
23705 * <script type="text/javascript">
23710 * @class Roo.dd.DragZone
23711 * @extends Roo.dd.DragSource
23712 * This class provides a container DD instance that proxies for multiple child node sources.<br />
23713 * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
23715 * @param {String/HTMLElement/Element} el The container element
23716 * @param {Object} config
23718 Roo.dd.DragZone = function(el, config){
23719 Roo.dd.DragZone.superclass.constructor.call(this, el, config);
23720 if(this.containerScroll){
23721 Roo.dd.ScrollManager.register(this.el);
23725 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
23727 * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
23728 * for auto scrolling during drag operations.
23731 * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
23732 * method after a failed drop (defaults to "c3daf9" - light blue)
23736 * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
23737 * for a valid target to drag based on the mouse down. Override this method
23738 * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
23739 * object has a "ddel" attribute (with an HTML Element) for other functions to work.
23740 * @param {EventObject} e The mouse down event
23741 * @return {Object} The dragData
23743 getDragData : function(e){
23744 return Roo.dd.Registry.getHandleFromEvent(e);
23748 * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
23749 * this.dragData.ddel
23750 * @param {Number} x The x position of the click on the dragged object
23751 * @param {Number} y The y position of the click on the dragged object
23752 * @return {Boolean} true to continue the drag, false to cancel
23754 onInitDrag : function(x, y){
23755 this.proxy.update(this.dragData.ddel.cloneNode(true));
23756 this.onStartDrag(x, y);
23761 * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
23763 afterRepair : function(){
23765 Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
23767 this.dragging = false;
23771 * Called before a repair of an invalid drop to get the XY to animate to. By default returns
23772 * the XY of this.dragData.ddel
23773 * @param {EventObject} e The mouse up event
23774 * @return {Array} The xy location (e.g. [100, 200])
23776 getRepairXY : function(e){
23777 return Roo.Element.fly(this.dragData.ddel).getXY();
23781 * Ext JS Library 1.1.1
23782 * Copyright(c) 2006-2007, Ext JS, LLC.
23784 * Originally Released Under LGPL - original licence link has changed is not relivant.
23787 * <script type="text/javascript">
23790 * @class Roo.dd.DropZone
23791 * @extends Roo.dd.DropTarget
23792 * This class provides a container DD instance that proxies for multiple child node targets.<br />
23793 * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
23795 * @param {String/HTMLElement/Element} el The container element
23796 * @param {Object} config
23798 Roo.dd.DropZone = function(el, config){
23799 Roo.dd.DropZone.superclass.constructor.call(this, el, config);
23802 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
23804 * Returns a custom data object associated with the DOM node that is the target of the event. By default
23805 * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
23806 * provide your own custom lookup.
23807 * @param {Event} e The event
23808 * @return {Object} data The custom data
23810 getTargetFromEvent : function(e){
23811 return Roo.dd.Registry.getTargetFromEvent(e);
23815 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
23816 * that it has registered. This method has no default implementation and should be overridden to provide
23817 * node-specific processing if necessary.
23818 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23819 * {@link #getTargetFromEvent} for this node)
23820 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23821 * @param {Event} e The event
23822 * @param {Object} data An object containing arbitrary data supplied by the drag source
23824 onNodeEnter : function(n, dd, e, data){
23829 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
23830 * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
23831 * overridden to provide the proper feedback.
23832 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23833 * {@link #getTargetFromEvent} for this node)
23834 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23835 * @param {Event} e The event
23836 * @param {Object} data An object containing arbitrary data supplied by the drag source
23837 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23838 * underlying {@link Roo.dd.StatusProxy} can be updated
23840 onNodeOver : function(n, dd, e, data){
23841 return this.dropAllowed;
23845 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
23846 * the drop node without dropping. This method has no default implementation and should be overridden to provide
23847 * node-specific processing if necessary.
23848 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23849 * {@link #getTargetFromEvent} for this node)
23850 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23851 * @param {Event} e The event
23852 * @param {Object} data An object containing arbitrary data supplied by the drag source
23854 onNodeOut : function(n, dd, e, data){
23859 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
23860 * the drop node. The default implementation returns false, so it should be overridden to provide the
23861 * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
23862 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23863 * {@link #getTargetFromEvent} for this node)
23864 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23865 * @param {Event} e The event
23866 * @param {Object} data An object containing arbitrary data supplied by the drag source
23867 * @return {Boolean} True if the drop was valid, else false
23869 onNodeDrop : function(n, dd, e, data){
23874 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
23875 * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
23876 * it should be overridden to provide the proper feedback if necessary.
23877 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23878 * @param {Event} e The event
23879 * @param {Object} data An object containing arbitrary data supplied by the drag source
23880 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23881 * underlying {@link Roo.dd.StatusProxy} can be updated
23883 onContainerOver : function(dd, e, data){
23884 return this.dropNotAllowed;
23888 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
23889 * but not on any of its registered drop nodes. The default implementation returns false, so it should be
23890 * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
23891 * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
23892 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23893 * @param {Event} e The event
23894 * @param {Object} data An object containing arbitrary data supplied by the drag source
23895 * @return {Boolean} True if the drop was valid, else false
23897 onContainerDrop : function(dd, e, data){
23902 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
23903 * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
23904 * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
23905 * you should override this method and provide a custom implementation.
23906 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23907 * @param {Event} e The event
23908 * @param {Object} data An object containing arbitrary data supplied by the drag source
23909 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23910 * underlying {@link Roo.dd.StatusProxy} can be updated
23912 notifyEnter : function(dd, e, data){
23913 return this.dropNotAllowed;
23917 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
23918 * This method will be called on every mouse movement while the drag source is over the drop zone.
23919 * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
23920 * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
23921 * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
23922 * registered node, it will call {@link #onContainerOver}.
23923 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23924 * @param {Event} e The event
23925 * @param {Object} data An object containing arbitrary data supplied by the drag source
23926 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23927 * underlying {@link Roo.dd.StatusProxy} can be updated
23929 notifyOver : function(dd, e, data){
23930 var n = this.getTargetFromEvent(e);
23931 if(!n){ // not over valid drop target
23932 if(this.lastOverNode){
23933 this.onNodeOut(this.lastOverNode, dd, e, data);
23934 this.lastOverNode = null;
23936 return this.onContainerOver(dd, e, data);
23938 if(this.lastOverNode != n){
23939 if(this.lastOverNode){
23940 this.onNodeOut(this.lastOverNode, dd, e, data);
23942 this.onNodeEnter(n, dd, e, data);
23943 this.lastOverNode = n;
23945 return this.onNodeOver(n, dd, e, data);
23949 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
23950 * out of the zone without dropping. If the drag source is currently over a registered node, the notification
23951 * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
23952 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23953 * @param {Event} e The event
23954 * @param {Object} data An object containing arbitrary data supplied by the drag zone
23956 notifyOut : function(dd, e, data){
23957 if(this.lastOverNode){
23958 this.onNodeOut(this.lastOverNode, dd, e, data);
23959 this.lastOverNode = null;
23964 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
23965 * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
23966 * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
23967 * otherwise it will call {@link #onContainerDrop}.
23968 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23969 * @param {Event} e The event
23970 * @param {Object} data An object containing arbitrary data supplied by the drag source
23971 * @return {Boolean} True if the drop was valid, else false
23973 notifyDrop : function(dd, e, data){
23974 if(this.lastOverNode){
23975 this.onNodeOut(this.lastOverNode, dd, e, data);
23976 this.lastOverNode = null;
23978 var n = this.getTargetFromEvent(e);
23980 this.onNodeDrop(n, dd, e, data) :
23981 this.onContainerDrop(dd, e, data);
23985 triggerCacheRefresh : function(){
23986 Roo.dd.DDM.refreshCache(this.groups);
23990 * Ext JS Library 1.1.1
23991 * Copyright(c) 2006-2007, Ext JS, LLC.
23993 * Originally Released Under LGPL - original licence link has changed is not relivant.
23996 * <script type="text/javascript">
24001 * @class Roo.data.SortTypes
24003 * Defines the default sorting (casting?) comparison functions used when sorting data.
24005 Roo.data.SortTypes = {
24007 * Default sort that does nothing
24008 * @param {Mixed} s The value being converted
24009 * @return {Mixed} The comparison value
24011 none : function(s){
24016 * The regular expression used to strip tags
24020 stripTagsRE : /<\/?[^>]+>/gi,
24023 * Strips all HTML tags to sort on text only
24024 * @param {Mixed} s The value being converted
24025 * @return {String} The comparison value
24027 asText : function(s){
24028 return String(s).replace(this.stripTagsRE, "");
24032 * Strips all HTML tags to sort on text only - Case insensitive
24033 * @param {Mixed} s The value being converted
24034 * @return {String} The comparison value
24036 asUCText : function(s){
24037 return String(s).toUpperCase().replace(this.stripTagsRE, "");
24041 * Case insensitive string
24042 * @param {Mixed} s The value being converted
24043 * @return {String} The comparison value
24045 asUCString : function(s) {
24046 return String(s).toUpperCase();
24051 * @param {Mixed} s The value being converted
24052 * @return {Number} The comparison value
24054 asDate : function(s) {
24058 if(s instanceof Date){
24059 return s.getTime();
24061 return Date.parse(String(s));
24066 * @param {Mixed} s The value being converted
24067 * @return {Float} The comparison value
24069 asFloat : function(s) {
24070 var val = parseFloat(String(s).replace(/,/g, ""));
24079 * @param {Mixed} s The value being converted
24080 * @return {Number} The comparison value
24082 asInt : function(s) {
24083 var val = parseInt(String(s).replace(/,/g, ""));
24091 * Ext JS Library 1.1.1
24092 * Copyright(c) 2006-2007, Ext JS, LLC.
24094 * Originally Released Under LGPL - original licence link has changed is not relivant.
24097 * <script type="text/javascript">
24101 * @class Roo.data.Record
24102 * Instances of this class encapsulate both record <em>definition</em> information, and record
24103 * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
24104 * to access Records cached in an {@link Roo.data.Store} object.<br>
24106 * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
24107 * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
24110 * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
24112 * This constructor should not be used to create Record objects. Instead, use the constructor generated by
24113 * {@link #create}. The parameters are the same.
24114 * @param {Array} data An associative Array of data values keyed by the field name.
24115 * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
24116 * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
24117 * not specified an integer id is generated.
24119 Roo.data.Record = function(data, id){
24120 this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
24125 * Generate a constructor for a specific record layout.
24126 * @param {Array} o An Array of field definition objects which specify field names, and optionally,
24127 * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
24128 * Each field definition object may contain the following properties: <ul>
24129 * <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,
24130 * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
24131 * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
24132 * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
24133 * is being used, then this is a string containing the javascript expression to reference the data relative to
24134 * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
24135 * to the data item relative to the record element. If the mapping expression is the same as the field name,
24136 * this may be omitted.</p></li>
24137 * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
24138 * <ul><li>auto (Default, implies no conversion)</li>
24143 * <li>date</li></ul></p></li>
24144 * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
24145 * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
24146 * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
24147 * by the Reader into an object that will be stored in the Record. It is passed the
24148 * following parameters:<ul>
24149 * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
24151 * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
24153 * <br>usage:<br><pre><code>
24154 var TopicRecord = Roo.data.Record.create(
24155 {name: 'title', mapping: 'topic_title'},
24156 {name: 'author', mapping: 'username'},
24157 {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
24158 {name: 'lastPost', mapping: 'post_time', type: 'date'},
24159 {name: 'lastPoster', mapping: 'user2'},
24160 {name: 'excerpt', mapping: 'post_text'}
24163 var myNewRecord = new TopicRecord({
24164 title: 'Do my job please',
24167 lastPost: new Date(),
24168 lastPoster: 'Animal',
24169 excerpt: 'No way dude!'
24171 myStore.add(myNewRecord);
24176 Roo.data.Record.create = function(o){
24177 var f = function(){
24178 f.superclass.constructor.apply(this, arguments);
24180 Roo.extend(f, Roo.data.Record);
24181 var p = f.prototype;
24182 p.fields = new Roo.util.MixedCollection(false, function(field){
24185 for(var i = 0, len = o.length; i < len; i++){
24186 p.fields.add(new Roo.data.Field(o[i]));
24188 f.getField = function(name){
24189 return p.fields.get(name);
24194 Roo.data.Record.AUTO_ID = 1000;
24195 Roo.data.Record.EDIT = 'edit';
24196 Roo.data.Record.REJECT = 'reject';
24197 Roo.data.Record.COMMIT = 'commit';
24199 Roo.data.Record.prototype = {
24201 * Readonly flag - true if this record has been modified.
24210 join : function(store){
24211 this.store = store;
24215 * Set the named field to the specified value.
24216 * @param {String} name The name of the field to set.
24217 * @param {Object} value The value to set the field to.
24219 set : function(name, value){
24220 if(this.data[name] == value){
24224 if(!this.modified){
24225 this.modified = {};
24227 if(typeof this.modified[name] == 'undefined'){
24228 this.modified[name] = this.data[name];
24230 this.data[name] = value;
24231 if(!this.editing && this.store){
24232 this.store.afterEdit(this);
24237 * Get the value of the named field.
24238 * @param {String} name The name of the field to get the value of.
24239 * @return {Object} The value of the field.
24241 get : function(name){
24242 return this.data[name];
24246 beginEdit : function(){
24247 this.editing = true;
24248 this.modified = {};
24252 cancelEdit : function(){
24253 this.editing = false;
24254 delete this.modified;
24258 endEdit : function(){
24259 this.editing = false;
24260 if(this.dirty && this.store){
24261 this.store.afterEdit(this);
24266 * Usually called by the {@link Roo.data.Store} which owns the Record.
24267 * Rejects all changes made to the Record since either creation, or the last commit operation.
24268 * Modified fields are reverted to their original values.
24270 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
24271 * of reject operations.
24273 reject : function(){
24274 var m = this.modified;
24276 if(typeof m[n] != "function"){
24277 this.data[n] = m[n];
24280 this.dirty = false;
24281 delete this.modified;
24282 this.editing = false;
24284 this.store.afterReject(this);
24289 * Usually called by the {@link Roo.data.Store} which owns the Record.
24290 * Commits all changes made to the Record since either creation, or the last commit operation.
24292 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
24293 * of commit operations.
24295 commit : function(){
24296 this.dirty = false;
24297 delete this.modified;
24298 this.editing = false;
24300 this.store.afterCommit(this);
24305 hasError : function(){
24306 return this.error != null;
24310 clearError : function(){
24315 * Creates a copy of this record.
24316 * @param {String} id (optional) A new record id if you don't want to use this record's id
24319 copy : function(newId) {
24320 return new this.constructor(Roo.apply({}, this.data), newId || this.id);
24324 * Ext JS Library 1.1.1
24325 * Copyright(c) 2006-2007, Ext JS, LLC.
24327 * Originally Released Under LGPL - original licence link has changed is not relivant.
24330 * <script type="text/javascript">
24336 * @class Roo.data.Store
24337 * @extends Roo.util.Observable
24338 * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
24339 * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
24341 * 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
24342 * has no knowledge of the format of the data returned by the Proxy.<br>
24344 * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
24345 * instances from the data object. These records are cached and made available through accessor functions.
24347 * Creates a new Store.
24348 * @param {Object} config A config object containing the objects needed for the Store to access data,
24349 * and read the data into Records.
24351 Roo.data.Store = function(config){
24352 this.data = new Roo.util.MixedCollection(false);
24353 this.data.getKey = function(o){
24356 this.baseParams = {};
24358 this.paramNames = {
24363 "multisort" : "_multisort"
24366 if(config && config.data){
24367 this.inlineData = config.data;
24368 delete config.data;
24371 Roo.apply(this, config);
24373 if(this.reader){ // reader passed
24374 this.reader = Roo.factory(this.reader, Roo.data);
24375 this.reader.xmodule = this.xmodule || false;
24376 if(!this.recordType){
24377 this.recordType = this.reader.recordType;
24379 if(this.reader.onMetaChange){
24380 this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
24384 if(this.recordType){
24385 this.fields = this.recordType.prototype.fields;
24387 this.modified = [];
24391 * @event datachanged
24392 * Fires when the data cache has changed, and a widget which is using this Store
24393 * as a Record cache should refresh its view.
24394 * @param {Store} this
24396 datachanged : true,
24398 * @event metachange
24399 * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
24400 * @param {Store} this
24401 * @param {Object} meta The JSON metadata
24406 * Fires when Records have been added to the Store
24407 * @param {Store} this
24408 * @param {Roo.data.Record[]} records The array of Records added
24409 * @param {Number} index The index at which the record(s) were added
24414 * Fires when a Record has been removed from the Store
24415 * @param {Store} this
24416 * @param {Roo.data.Record} record The Record that was removed
24417 * @param {Number} index The index at which the record was removed
24422 * Fires when a Record has been updated
24423 * @param {Store} this
24424 * @param {Roo.data.Record} record The Record that was updated
24425 * @param {String} operation The update operation being performed. Value may be one of:
24427 Roo.data.Record.EDIT
24428 Roo.data.Record.REJECT
24429 Roo.data.Record.COMMIT
24435 * Fires when the data cache has been cleared.
24436 * @param {Store} this
24440 * @event beforeload
24441 * Fires before a request is made for a new data object. If the beforeload handler returns false
24442 * the load action will be canceled.
24443 * @param {Store} this
24444 * @param {Object} options The loading options that were specified (see {@link #load} for details)
24448 * @event beforeloadadd
24449 * Fires after a new set of Records has been loaded.
24450 * @param {Store} this
24451 * @param {Roo.data.Record[]} records The Records that were loaded
24452 * @param {Object} options The loading options that were specified (see {@link #load} for details)
24454 beforeloadadd : true,
24457 * Fires after a new set of Records has been loaded, before they are added to the store.
24458 * @param {Store} this
24459 * @param {Roo.data.Record[]} records The Records that were loaded
24460 * @param {Object} options The loading options that were specified (see {@link #load} for details)
24461 * @params {Object} return from reader
24465 * @event loadexception
24466 * Fires if an exception occurs in the Proxy during loading.
24467 * Called with the signature of the Proxy's "loadexception" event.
24468 * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
24471 * @param {Object} return from JsonData.reader() - success, totalRecords, records
24472 * @param {Object} load options
24473 * @param {Object} jsonData from your request (normally this contains the Exception)
24475 loadexception : true
24479 this.proxy = Roo.factory(this.proxy, Roo.data);
24480 this.proxy.xmodule = this.xmodule || false;
24481 this.relayEvents(this.proxy, ["loadexception"]);
24483 this.sortToggle = {};
24484 this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
24486 Roo.data.Store.superclass.constructor.call(this);
24488 if(this.inlineData){
24489 this.loadData(this.inlineData);
24490 delete this.inlineData;
24494 Roo.extend(Roo.data.Store, Roo.util.Observable, {
24496 * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
24497 * without a remote query - used by combo/forms at present.
24501 * @cfg {Roo.data.DataProxy} proxy [required] The Proxy object which provides access to a data object.
24504 * @cfg {Array} data Inline data to be loaded when the store is initialized.
24507 * @cfg {Roo.data.DataReader} reader [required] The Reader object which processes the data object and returns
24508 * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
24511 * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
24512 * on any HTTP request
24515 * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
24518 * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
24522 * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
24523 * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
24525 remoteSort : false,
24528 * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
24529 * loaded or when a record is removed. (defaults to false).
24531 pruneModifiedRecords : false,
24534 lastOptions : null,
24537 * Add Records to the Store and fires the add event.
24538 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
24540 add : function(records){
24541 records = [].concat(records);
24542 for(var i = 0, len = records.length; i < len; i++){
24543 records[i].join(this);
24545 var index = this.data.length;
24546 this.data.addAll(records);
24547 this.fireEvent("add", this, records, index);
24551 * Remove a Record from the Store and fires the remove event.
24552 * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
24554 remove : function(record){
24555 var index = this.data.indexOf(record);
24556 this.data.removeAt(index);
24558 if(this.pruneModifiedRecords){
24559 this.modified.remove(record);
24561 this.fireEvent("remove", this, record, index);
24565 * Remove all Records from the Store and fires the clear event.
24567 removeAll : function(){
24569 if(this.pruneModifiedRecords){
24570 this.modified = [];
24572 this.fireEvent("clear", this);
24576 * Inserts Records to the Store at the given index and fires the add event.
24577 * @param {Number} index The start index at which to insert the passed Records.
24578 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
24580 insert : function(index, records){
24581 records = [].concat(records);
24582 for(var i = 0, len = records.length; i < len; i++){
24583 this.data.insert(index, records[i]);
24584 records[i].join(this);
24586 this.fireEvent("add", this, records, index);
24590 * Get the index within the cache of the passed Record.
24591 * @param {Roo.data.Record} record The Roo.data.Record object to to find.
24592 * @return {Number} The index of the passed Record. Returns -1 if not found.
24594 indexOf : function(record){
24595 return this.data.indexOf(record);
24599 * Get the index within the cache of the Record with the passed id.
24600 * @param {String} id The id of the Record to find.
24601 * @return {Number} The index of the Record. Returns -1 if not found.
24603 indexOfId : function(id){
24604 return this.data.indexOfKey(id);
24608 * Get the Record with the specified id.
24609 * @param {String} id The id of the Record to find.
24610 * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
24612 getById : function(id){
24613 return this.data.key(id);
24617 * Get the Record at the specified index.
24618 * @param {Number} index The index of the Record to find.
24619 * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
24621 getAt : function(index){
24622 return this.data.itemAt(index);
24626 * Returns a range of Records between specified indices.
24627 * @param {Number} startIndex (optional) The starting index (defaults to 0)
24628 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
24629 * @return {Roo.data.Record[]} An array of Records
24631 getRange : function(start, end){
24632 return this.data.getRange(start, end);
24636 storeOptions : function(o){
24637 o = Roo.apply({}, o);
24640 this.lastOptions = o;
24644 * Loads the Record cache from the configured Proxy using the configured Reader.
24646 * If using remote paging, then the first load call must specify the <em>start</em>
24647 * and <em>limit</em> properties in the options.params property to establish the initial
24648 * position within the dataset, and the number of Records to cache on each read from the Proxy.
24650 * <strong>It is important to note that for remote data sources, loading is asynchronous,
24651 * and this call will return before the new data has been loaded. Perform any post-processing
24652 * in a callback function, or in a "load" event handler.</strong>
24654 * @param {Object} options An object containing properties which control loading options:<ul>
24655 * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
24656 * <li>params.data {Object} if you are using a MemoryProxy / JsonReader, use this as the data to load stuff..
24659 data : data, // array of key=>value data like JsonReader
24660 total : data.length,
24666 * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
24667 * passed the following arguments:<ul>
24668 * <li>r : Roo.data.Record[]</li>
24669 * <li>options: Options object from the load call</li>
24670 * <li>success: Boolean success indicator</li></ul></li>
24671 * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
24672 * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
24675 load : function(options){
24676 options = options || {};
24677 if(this.fireEvent("beforeload", this, options) !== false){
24678 this.storeOptions(options);
24679 var p = Roo.apply(options.params || {}, this.baseParams);
24680 // if meta was not loaded from remote source.. try requesting it.
24681 if (!this.reader.metaFromRemote) {
24682 p._requestMeta = 1;
24684 if(this.sortInfo && this.remoteSort){
24685 var pn = this.paramNames;
24686 p[pn["sort"]] = this.sortInfo.field;
24687 p[pn["dir"]] = this.sortInfo.direction;
24689 if (this.multiSort) {
24690 var pn = this.paramNames;
24691 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
24694 this.proxy.load(p, this.reader, this.loadRecords, this, options);
24699 * Reloads the Record cache from the configured Proxy using the configured Reader and
24700 * the options from the last load operation performed.
24701 * @param {Object} options (optional) An object containing properties which may override the options
24702 * used in the last load operation. See {@link #load} for details (defaults to null, in which case
24703 * the most recently used options are reused).
24705 reload : function(options){
24706 this.load(Roo.applyIf(options||{}, this.lastOptions));
24710 // Called as a callback by the Reader during a load operation.
24711 loadRecords : function(o, options, success){
24714 if(success !== false){
24715 this.fireEvent("load", this, [], options, o);
24717 if(options.callback){
24718 options.callback.call(options.scope || this, [], options, false);
24722 // if data returned failure - throw an exception.
24723 if (o.success === false) {
24724 // show a message if no listener is registered.
24725 if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
24726 Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
24728 // loadmask wil be hooked into this..
24729 this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
24732 var r = o.records, t = o.totalRecords || r.length;
24734 this.fireEvent("beforeloadadd", this, r, options, o);
24736 if(!options || options.add !== true){
24737 if(this.pruneModifiedRecords){
24738 this.modified = [];
24740 for(var i = 0, len = r.length; i < len; i++){
24744 this.data = this.snapshot;
24745 delete this.snapshot;
24748 this.data.addAll(r);
24749 this.totalLength = t;
24751 this.fireEvent("datachanged", this);
24753 this.totalLength = Math.max(t, this.data.length+r.length);
24757 if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
24759 var e = new Roo.data.Record({});
24761 e.set(this.parent.displayField, this.parent.emptyTitle);
24762 e.set(this.parent.valueField, '');
24767 this.fireEvent("load", this, r, options, o);
24768 if(options.callback){
24769 options.callback.call(options.scope || this, r, options, true);
24775 * Loads data from a passed data block. A Reader which understands the format of the data
24776 * must have been configured in the constructor.
24777 * @param {Object} data The data block from which to read the Records. The format of the data expected
24778 * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
24779 * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
24781 loadData : function(o, append){
24782 var r = this.reader.readRecords(o);
24783 this.loadRecords(r, {add: append}, true);
24787 * using 'cn' the nested child reader read the child array into it's child stores.
24788 * @param {Object} rec The record with a 'children array
24790 loadDataFromChildren : function(rec)
24792 this.loadData(this.reader.toLoadData(rec));
24797 * Gets the number of cached records.
24799 * <em>If using paging, this may not be the total size of the dataset. If the data object
24800 * used by the Reader contains the dataset size, then the getTotalCount() function returns
24801 * the data set size</em>
24803 getCount : function(){
24804 return this.data.length || 0;
24808 * Gets the total number of records in the dataset as returned by the server.
24810 * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
24811 * the dataset size</em>
24813 getTotalCount : function(){
24814 return this.totalLength || 0;
24818 * Returns the sort state of the Store as an object with two properties:
24820 field {String} The name of the field by which the Records are sorted
24821 direction {String} The sort order, "ASC" or "DESC"
24824 getSortState : function(){
24825 return this.sortInfo;
24829 applySort : function(){
24830 if(this.sortInfo && !this.remoteSort){
24831 var s = this.sortInfo, f = s.field;
24832 var st = this.fields.get(f).sortType;
24833 var fn = function(r1, r2){
24834 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
24835 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
24837 this.data.sort(s.direction, fn);
24838 if(this.snapshot && this.snapshot != this.data){
24839 this.snapshot.sort(s.direction, fn);
24845 * Sets the default sort column and order to be used by the next load operation.
24846 * @param {String} fieldName The name of the field to sort by.
24847 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
24849 setDefaultSort : function(field, dir){
24850 this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
24854 * Sort the Records.
24855 * If remote sorting is used, the sort is performed on the server, and the cache is
24856 * reloaded. If local sorting is used, the cache is sorted internally.
24857 * @param {String} fieldName The name of the field to sort by.
24858 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
24860 sort : function(fieldName, dir){
24861 var f = this.fields.get(fieldName);
24863 this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
24865 if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
24866 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
24871 this.sortToggle[f.name] = dir;
24872 this.sortInfo = {field: f.name, direction: dir};
24873 if(!this.remoteSort){
24875 this.fireEvent("datachanged", this);
24877 this.load(this.lastOptions);
24882 * Calls the specified function for each of the Records in the cache.
24883 * @param {Function} fn The function to call. The Record is passed as the first parameter.
24884 * Returning <em>false</em> aborts and exits the iteration.
24885 * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
24887 each : function(fn, scope){
24888 this.data.each(fn, scope);
24892 * Gets all records modified since the last commit. Modified records are persisted across load operations
24893 * (e.g., during paging).
24894 * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
24896 getModifiedRecords : function(){
24897 return this.modified;
24901 createFilterFn : function(property, value, anyMatch){
24902 if(!value.exec){ // not a regex
24903 value = String(value);
24904 if(value.length == 0){
24907 value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
24909 return function(r){
24910 return value.test(r.data[property]);
24915 * Sums the value of <i>property</i> for each record between start and end and returns the result.
24916 * @param {String} property A field on your records
24917 * @param {Number} start The record index to start at (defaults to 0)
24918 * @param {Number} end The last record index to include (defaults to length - 1)
24919 * @return {Number} The sum
24921 sum : function(property, start, end){
24922 var rs = this.data.items, v = 0;
24923 start = start || 0;
24924 end = (end || end === 0) ? end : rs.length-1;
24926 for(var i = start; i <= end; i++){
24927 v += (rs[i].data[property] || 0);
24933 * Filter the records by a specified property.
24934 * @param {String} field A field on your records
24935 * @param {String/RegExp} value Either a string that the field
24936 * should start with or a RegExp to test against the field
24937 * @param {Boolean} anyMatch True to match any part not just the beginning
24939 filter : function(property, value, anyMatch){
24940 var fn = this.createFilterFn(property, value, anyMatch);
24941 return fn ? this.filterBy(fn) : this.clearFilter();
24945 * Filter by a function. The specified function will be called with each
24946 * record in this data source. If the function returns true the record is included,
24947 * otherwise it is filtered.
24948 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
24949 * @param {Object} scope (optional) The scope of the function (defaults to this)
24951 filterBy : function(fn, scope){
24952 this.snapshot = this.snapshot || this.data;
24953 this.data = this.queryBy(fn, scope||this);
24954 this.fireEvent("datachanged", this);
24958 * Query the records by a specified property.
24959 * @param {String} field A field on your records
24960 * @param {String/RegExp} value Either a string that the field
24961 * should start with or a RegExp to test against the field
24962 * @param {Boolean} anyMatch True to match any part not just the beginning
24963 * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
24965 query : function(property, value, anyMatch){
24966 var fn = this.createFilterFn(property, value, anyMatch);
24967 return fn ? this.queryBy(fn) : this.data.clone();
24971 * Query by a function. The specified function will be called with each
24972 * record in this data source. If the function returns true the record is included
24974 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
24975 * @param {Object} scope (optional) The scope of the function (defaults to this)
24976 @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
24978 queryBy : function(fn, scope){
24979 var data = this.snapshot || this.data;
24980 return data.filterBy(fn, scope||this);
24984 * Collects unique values for a particular dataIndex from this store.
24985 * @param {String} dataIndex The property to collect
24986 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
24987 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
24988 * @return {Array} An array of the unique values
24990 collect : function(dataIndex, allowNull, bypassFilter){
24991 var d = (bypassFilter === true && this.snapshot) ?
24992 this.snapshot.items : this.data.items;
24993 var v, sv, r = [], l = {};
24994 for(var i = 0, len = d.length; i < len; i++){
24995 v = d[i].data[dataIndex];
24997 if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
25006 * Revert to a view of the Record cache with no filtering applied.
25007 * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
25009 clearFilter : function(suppressEvent){
25010 if(this.snapshot && this.snapshot != this.data){
25011 this.data = this.snapshot;
25012 delete this.snapshot;
25013 if(suppressEvent !== true){
25014 this.fireEvent("datachanged", this);
25020 afterEdit : function(record){
25021 if(this.modified.indexOf(record) == -1){
25022 this.modified.push(record);
25024 this.fireEvent("update", this, record, Roo.data.Record.EDIT);
25028 afterReject : function(record){
25029 this.modified.remove(record);
25030 this.fireEvent("update", this, record, Roo.data.Record.REJECT);
25034 afterCommit : function(record){
25035 this.modified.remove(record);
25036 this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
25040 * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
25041 * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
25043 commitChanges : function(){
25044 var m = this.modified.slice(0);
25045 this.modified = [];
25046 for(var i = 0, len = m.length; i < len; i++){
25052 * Cancel outstanding changes on all changed records.
25054 rejectChanges : function(){
25055 var m = this.modified.slice(0);
25056 this.modified = [];
25057 for(var i = 0, len = m.length; i < len; i++){
25062 onMetaChange : function(meta, rtype, o){
25063 this.recordType = rtype;
25064 this.fields = rtype.prototype.fields;
25065 delete this.snapshot;
25066 this.sortInfo = meta.sortInfo || this.sortInfo;
25067 this.modified = [];
25068 this.fireEvent('metachange', this, this.reader.meta);
25071 moveIndex : function(data, type)
25073 var index = this.indexOf(data);
25075 var newIndex = index + type;
25079 this.insert(newIndex, data);
25084 * Ext JS Library 1.1.1
25085 * Copyright(c) 2006-2007, Ext JS, LLC.
25087 * Originally Released Under LGPL - original licence link has changed is not relivant.
25090 * <script type="text/javascript">
25094 * @class Roo.data.SimpleStore
25095 * @extends Roo.data.Store
25096 * Small helper class to make creating Stores from Array data easier.
25097 * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
25098 * @cfg {Array} fields An array of field definition objects, or field name strings.
25099 * @cfg {Object} an existing reader (eg. copied from another store)
25100 * @cfg {Array} data The multi-dimensional array of data
25101 * @cfg {Roo.data.DataProxy} proxy [not-required]
25102 * @cfg {Roo.data.Reader} reader [not-required]
25104 * @param {Object} config
25106 Roo.data.SimpleStore = function(config)
25108 Roo.data.SimpleStore.superclass.constructor.call(this, {
25110 reader: typeof(config.reader) != 'undefined' ? config.reader : new Roo.data.ArrayReader({
25113 Roo.data.Record.create(config.fields)
25115 proxy : new Roo.data.MemoryProxy(config.data)
25119 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
25121 * Ext JS Library 1.1.1
25122 * Copyright(c) 2006-2007, Ext JS, LLC.
25124 * Originally Released Under LGPL - original licence link has changed is not relivant.
25127 * <script type="text/javascript">
25132 * @extends Roo.data.Store
25133 * @class Roo.data.JsonStore
25134 * Small helper class to make creating Stores for JSON data easier. <br/>
25136 var store = new Roo.data.JsonStore({
25137 url: 'get-images.php',
25139 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
25142 * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
25143 * JsonReader and HttpProxy (unless inline data is provided).</b>
25144 * @cfg {Array} fields An array of field definition objects, or field name strings.
25146 * @param {Object} config
25148 Roo.data.JsonStore = function(c){
25149 Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
25150 proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
25151 reader: new Roo.data.JsonReader(c, c.fields)
25154 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
25156 * Ext JS Library 1.1.1
25157 * Copyright(c) 2006-2007, Ext JS, LLC.
25159 * Originally Released Under LGPL - original licence link has changed is not relivant.
25162 * <script type="text/javascript">
25166 Roo.data.Field = function(config){
25167 if(typeof config == "string"){
25168 config = {name: config};
25170 Roo.apply(this, config);
25173 this.type = "auto";
25176 var st = Roo.data.SortTypes;
25177 // named sortTypes are supported, here we look them up
25178 if(typeof this.sortType == "string"){
25179 this.sortType = st[this.sortType];
25182 // set default sortType for strings and dates
25183 if(!this.sortType){
25186 this.sortType = st.asUCString;
25189 this.sortType = st.asDate;
25192 this.sortType = st.none;
25197 var stripRe = /[\$,%]/g;
25199 // prebuilt conversion function for this field, instead of
25200 // switching every time we're reading a value
25202 var cv, dateFormat = this.dateFormat;
25207 cv = function(v){ return v; };
25210 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
25214 return v !== undefined && v !== null && v !== '' ?
25215 parseInt(String(v).replace(stripRe, ""), 10) : '';
25220 return v !== undefined && v !== null && v !== '' ?
25221 parseFloat(String(v).replace(stripRe, ""), 10) : '';
25226 cv = function(v){ return v === true || v === "true" || v == 1; };
25233 if(v instanceof Date){
25237 if(dateFormat == "timestamp"){
25238 return new Date(v*1000);
25240 return Date.parseDate(v, dateFormat);
25242 var parsed = Date.parse(v);
25243 return parsed ? new Date(parsed) : null;
25252 Roo.data.Field.prototype = {
25260 * Ext JS Library 1.1.1
25261 * Copyright(c) 2006-2007, Ext JS, LLC.
25263 * Originally Released Under LGPL - original licence link has changed is not relivant.
25266 * <script type="text/javascript">
25269 // Base class for reading structured data from a data source. This class is intended to be
25270 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
25273 * @class Roo.data.DataReader
25275 * Base class for reading structured data from a data source. This class is intended to be
25276 * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
25279 Roo.data.DataReader = function(meta, recordType){
25283 this.recordType = recordType instanceof Array ?
25284 Roo.data.Record.create(recordType) : recordType;
25287 Roo.data.DataReader.prototype = {
25290 readerType : 'Data',
25292 * Create an empty record
25293 * @param {Object} data (optional) - overlay some values
25294 * @return {Roo.data.Record} record created.
25296 newRow : function(d) {
25298 this.recordType.prototype.fields.each(function(c) {
25300 case 'int' : da[c.name] = 0; break;
25301 case 'date' : da[c.name] = new Date(); break;
25302 case 'float' : da[c.name] = 0.0; break;
25303 case 'boolean' : da[c.name] = false; break;
25304 default : da[c.name] = ""; break;
25308 return new this.recordType(Roo.apply(da, d));
25314 * Ext JS Library 1.1.1
25315 * Copyright(c) 2006-2007, Ext JS, LLC.
25317 * Originally Released Under LGPL - original licence link has changed is not relivant.
25320 * <script type="text/javascript">
25324 * @class Roo.data.DataProxy
25325 * @extends Roo.util.Observable
25327 * This class is an abstract base class for implementations which provide retrieval of
25328 * unformatted data objects.<br>
25330 * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
25331 * (of the appropriate type which knows how to parse the data object) to provide a block of
25332 * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
25334 * Custom implementations must implement the load method as described in
25335 * {@link Roo.data.HttpProxy#load}.
25337 Roo.data.DataProxy = function(){
25340 * @event beforeload
25341 * Fires before a network request is made to retrieve a data object.
25342 * @param {Object} This DataProxy object.
25343 * @param {Object} params The params parameter to the load function.
25348 * Fires before the load method's callback is called.
25349 * @param {Object} This DataProxy object.
25350 * @param {Object} o The data object.
25351 * @param {Object} arg The callback argument object passed to the load function.
25355 * @event loadexception
25356 * Fires if an Exception occurs during data retrieval.
25357 * @param {Object} This DataProxy object.
25358 * @param {Object} o The data object.
25359 * @param {Object} arg The callback argument object passed to the load function.
25360 * @param {Object} e The Exception.
25362 loadexception : true
25364 Roo.data.DataProxy.superclass.constructor.call(this);
25367 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
25370 * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
25374 * Ext JS Library 1.1.1
25375 * Copyright(c) 2006-2007, Ext JS, LLC.
25377 * Originally Released Under LGPL - original licence link has changed is not relivant.
25380 * <script type="text/javascript">
25383 * @class Roo.data.MemoryProxy
25384 * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
25385 * to the Reader when its load method is called.
25387 * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
25389 Roo.data.MemoryProxy = function(data){
25393 Roo.data.MemoryProxy.superclass.constructor.call(this);
25397 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
25400 * Load data from the requested source (in this case an in-memory
25401 * data object passed to the constructor), read the data object into
25402 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
25403 * process that block using the passed callback.
25404 * @param {Object} params This parameter is not used by the MemoryProxy class.
25405 * @param {Roo.data.DataReader} reader The Reader object which converts the data
25406 * object into a block of Roo.data.Records.
25407 * @param {Function} callback The function into which to pass the block of Roo.data.records.
25408 * The function must be passed <ul>
25409 * <li>The Record block object</li>
25410 * <li>The "arg" argument from the load function</li>
25411 * <li>A boolean success indicator</li>
25413 * @param {Object} scope The scope in which to call the callback
25414 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
25416 load : function(params, reader, callback, scope, arg){
25417 params = params || {};
25420 result = reader.readRecords(params.data ? params.data :this.data);
25422 this.fireEvent("loadexception", this, arg, null, e);
25423 callback.call(scope, null, arg, false);
25426 callback.call(scope, result, arg, true);
25430 update : function(params, records){
25435 * Ext JS Library 1.1.1
25436 * Copyright(c) 2006-2007, Ext JS, LLC.
25438 * Originally Released Under LGPL - original licence link has changed is not relivant.
25441 * <script type="text/javascript">
25444 * @class Roo.data.HttpProxy
25445 * @extends Roo.data.DataProxy
25446 * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
25447 * configured to reference a certain URL.<br><br>
25449 * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
25450 * from which the running page was served.<br><br>
25452 * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
25454 * Be aware that to enable the browser to parse an XML document, the server must set
25455 * the Content-Type header in the HTTP response to "text/xml".
25457 * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
25458 * an {@link Roo.data.Connection} object. If a Connection config is passed, the singleton {@link Roo.Ajax} object
25459 * will be used to make the request.
25461 Roo.data.HttpProxy = function(conn){
25462 Roo.data.HttpProxy.superclass.constructor.call(this);
25463 // is conn a conn config or a real conn?
25465 this.useAjax = !conn || !conn.events;
25469 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
25470 // thse are take from connection...
25473 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
25476 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
25477 * extra parameters to each request made by this object. (defaults to undefined)
25480 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
25481 * to each request made by this object. (defaults to undefined)
25484 * @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)
25487 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
25490 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
25496 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
25500 * Return the {@link Roo.data.Connection} object being used by this Proxy.
25501 * @return {Connection} The Connection object. This object may be used to subscribe to events on
25502 * a finer-grained basis than the DataProxy events.
25504 getConnection : function(){
25505 return this.useAjax ? Roo.Ajax : this.conn;
25509 * Load data from the configured {@link Roo.data.Connection}, read the data object into
25510 * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
25511 * process that block using the passed callback.
25512 * @param {Object} params An object containing properties which are to be used as HTTP parameters
25513 * for the request to the remote server.
25514 * @param {Roo.data.DataReader} reader The Reader object which converts the data
25515 * object into a block of Roo.data.Records.
25516 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
25517 * The function must be passed <ul>
25518 * <li>The Record block object</li>
25519 * <li>The "arg" argument from the load function</li>
25520 * <li>A boolean success indicator</li>
25522 * @param {Object} scope The scope in which to call the callback
25523 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
25525 load : function(params, reader, callback, scope, arg){
25526 if(this.fireEvent("beforeload", this, params) !== false){
25528 params : params || {},
25530 callback : callback,
25535 callback : this.loadResponse,
25539 Roo.applyIf(o, this.conn);
25540 if(this.activeRequest){
25541 Roo.Ajax.abort(this.activeRequest);
25543 this.activeRequest = Roo.Ajax.request(o);
25545 this.conn.request(o);
25548 callback.call(scope||this, null, arg, false);
25553 loadResponse : function(o, success, response){
25554 delete this.activeRequest;
25556 this.fireEvent("loadexception", this, o, response);
25557 o.request.callback.call(o.request.scope, null, o.request.arg, false);
25562 result = o.reader.read(response);
25565 o.raw = { errorMsg : response.responseText };
25566 this.fireEvent("loadexception", this, o, response, e);
25567 o.request.callback.call(o.request.scope, o, o.request.arg, false);
25571 this.fireEvent("load", this, o, o.request.arg);
25572 o.request.callback.call(o.request.scope, result, o.request.arg, true);
25576 update : function(dataSet){
25581 updateResponse : function(dataSet){
25586 * Ext JS Library 1.1.1
25587 * Copyright(c) 2006-2007, Ext JS, LLC.
25589 * Originally Released Under LGPL - original licence link has changed is not relivant.
25592 * <script type="text/javascript">
25596 * @class Roo.data.ScriptTagProxy
25597 * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
25598 * other than the originating domain of the running page.<br><br>
25600 * <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
25601 * of the running page, you must use this class, rather than DataProxy.</em><br><br>
25603 * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
25604 * source code that is used as the source inside a <script> tag.<br><br>
25606 * In order for the browser to process the returned data, the server must wrap the data object
25607 * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
25608 * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
25609 * depending on whether the callback name was passed:
25612 boolean scriptTag = false;
25613 String cb = request.getParameter("callback");
25616 response.setContentType("text/javascript");
25618 response.setContentType("application/x-json");
25620 Writer out = response.getWriter();
25622 out.write(cb + "(");
25624 out.print(dataBlock.toJsonString());
25631 * @param {Object} config A configuration object.
25633 Roo.data.ScriptTagProxy = function(config){
25634 Roo.data.ScriptTagProxy.superclass.constructor.call(this);
25635 Roo.apply(this, config);
25636 this.head = document.getElementsByTagName("head")[0];
25639 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
25641 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
25643 * @cfg {String} url The URL from which to request the data object.
25646 * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
25650 * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
25651 * the server the name of the callback function set up by the load call to process the returned data object.
25652 * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
25653 * javascript output which calls this named function passing the data object as its only parameter.
25655 callbackParam : "callback",
25657 * @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
25658 * name to the request.
25663 * Load data from the configured URL, read the data object into
25664 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
25665 * process that block using the passed callback.
25666 * @param {Object} params An object containing properties which are to be used as HTTP parameters
25667 * for the request to the remote server.
25668 * @param {Roo.data.DataReader} reader The Reader object which converts the data
25669 * object into a block of Roo.data.Records.
25670 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
25671 * The function must be passed <ul>
25672 * <li>The Record block object</li>
25673 * <li>The "arg" argument from the load function</li>
25674 * <li>A boolean success indicator</li>
25676 * @param {Object} scope The scope in which to call the callback
25677 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
25679 load : function(params, reader, callback, scope, arg){
25680 if(this.fireEvent("beforeload", this, params) !== false){
25682 var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
25684 var url = this.url;
25685 url += (url.indexOf("?") != -1 ? "&" : "?") + p;
25687 url += "&_dc=" + (new Date().getTime());
25689 var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
25692 cb : "stcCallback"+transId,
25693 scriptId : "stcScript"+transId,
25697 callback : callback,
25703 window[trans.cb] = function(o){
25704 conn.handleResponse(o, trans);
25707 url += String.format("&{0}={1}", this.callbackParam, trans.cb);
25709 if(this.autoAbort !== false){
25713 trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
25715 var script = document.createElement("script");
25716 script.setAttribute("src", url);
25717 script.setAttribute("type", "text/javascript");
25718 script.setAttribute("id", trans.scriptId);
25719 this.head.appendChild(script);
25721 this.trans = trans;
25723 callback.call(scope||this, null, arg, false);
25728 isLoading : function(){
25729 return this.trans ? true : false;
25733 * Abort the current server request.
25735 abort : function(){
25736 if(this.isLoading()){
25737 this.destroyTrans(this.trans);
25742 destroyTrans : function(trans, isLoaded){
25743 this.head.removeChild(document.getElementById(trans.scriptId));
25744 clearTimeout(trans.timeoutId);
25746 window[trans.cb] = undefined;
25748 delete window[trans.cb];
25751 // if hasn't been loaded, wait for load to remove it to prevent script error
25752 window[trans.cb] = function(){
25753 window[trans.cb] = undefined;
25755 delete window[trans.cb];
25762 handleResponse : function(o, trans){
25763 this.trans = false;
25764 this.destroyTrans(trans, true);
25767 result = trans.reader.readRecords(o);
25769 this.fireEvent("loadexception", this, o, trans.arg, e);
25770 trans.callback.call(trans.scope||window, null, trans.arg, false);
25773 this.fireEvent("load", this, o, trans.arg);
25774 trans.callback.call(trans.scope||window, result, trans.arg, true);
25778 handleFailure : function(trans){
25779 this.trans = false;
25780 this.destroyTrans(trans, false);
25781 this.fireEvent("loadexception", this, null, trans.arg);
25782 trans.callback.call(trans.scope||window, null, trans.arg, false);
25786 * Ext JS Library 1.1.1
25787 * Copyright(c) 2006-2007, Ext JS, LLC.
25789 * Originally Released Under LGPL - original licence link has changed is not relivant.
25792 * <script type="text/javascript">
25796 * @class Roo.data.JsonReader
25797 * @extends Roo.data.DataReader
25798 * Data reader class to create an Array of Roo.data.Record objects from a JSON response
25799 * based on mappings in a provided Roo.data.Record constructor.
25801 * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
25802 * in the reply previously.
25807 var RecordDef = Roo.data.Record.create([
25808 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
25809 {name: 'occupation'} // This field will use "occupation" as the mapping.
25811 var myReader = new Roo.data.JsonReader({
25812 totalProperty: "results", // The property which contains the total dataset size (optional)
25813 root: "rows", // The property which contains an Array of row objects
25814 id: "id" // The property within each row object that provides an ID for the record (optional)
25818 * This would consume a JSON file like this:
25820 { 'results': 2, 'rows': [
25821 { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
25822 { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
25825 * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
25826 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
25827 * paged from the remote server.
25828 * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
25829 * @cfg {String} root name of the property which contains the Array of row objects.
25830 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
25831 * @cfg {Array} fields Array of field definition objects
25833 * Create a new JsonReader
25834 * @param {Object} meta Metadata configuration options
25835 * @param {Object} recordType Either an Array of field definition objects,
25836 * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
25838 Roo.data.JsonReader = function(meta, recordType){
25841 // set some defaults:
25842 Roo.applyIf(meta, {
25843 totalProperty: 'total',
25844 successProperty : 'success',
25849 Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
25851 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
25853 readerType : 'Json',
25856 * @prop {Boolean} metaFromRemote - if the meta data was loaded from the remote source.
25857 * Used by Store query builder to append _requestMeta to params.
25860 metaFromRemote : false,
25862 * This method is only used by a DataProxy which has retrieved data from a remote server.
25863 * @param {Object} response The XHR object which contains the JSON data in its responseText.
25864 * @return {Object} data A data block which is used by an Roo.data.Store object as
25865 * a cache of Roo.data.Records.
25867 read : function(response){
25868 var json = response.responseText;
25870 var o = /* eval:var:o */ eval("("+json+")");
25872 throw {message: "JsonReader.read: Json object not found"};
25878 this.metaFromRemote = true;
25879 this.meta = o.metaData;
25880 this.recordType = Roo.data.Record.create(o.metaData.fields);
25881 this.onMetaChange(this.meta, this.recordType, o);
25883 return this.readRecords(o);
25886 // private function a store will implement
25887 onMetaChange : function(meta, recordType, o){
25894 simpleAccess: function(obj, subsc) {
25901 getJsonAccessor: function(){
25903 return function(expr) {
25905 return(re.test(expr))
25906 ? new Function("obj", "return obj." + expr)
25911 return Roo.emptyFn;
25916 * Create a data block containing Roo.data.Records from an XML document.
25917 * @param {Object} o An object which contains an Array of row objects in the property specified
25918 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
25919 * which contains the total size of the dataset.
25920 * @return {Object} data A data block which is used by an Roo.data.Store object as
25921 * a cache of Roo.data.Records.
25923 readRecords : function(o){
25925 * After any data loads, the raw JSON data is available for further custom processing.
25929 var s = this.meta, Record = this.recordType,
25930 f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
25932 // Generate extraction functions for the totalProperty, the root, the id, and for each field
25934 if(s.totalProperty) {
25935 this.getTotal = this.getJsonAccessor(s.totalProperty);
25937 if(s.successProperty) {
25938 this.getSuccess = this.getJsonAccessor(s.successProperty);
25940 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
25942 var g = this.getJsonAccessor(s.id);
25943 this.getId = function(rec) {
25945 return (r === undefined || r === "") ? null : r;
25948 this.getId = function(){return null;};
25951 for(var jj = 0; jj < fl; jj++){
25953 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
25954 this.ef[jj] = this.getJsonAccessor(map);
25958 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
25959 if(s.totalProperty){
25960 var vt = parseInt(this.getTotal(o), 10);
25965 if(s.successProperty){
25966 var vs = this.getSuccess(o);
25967 if(vs === false || vs === 'false'){
25972 for(var i = 0; i < c; i++){
25975 var id = this.getId(n);
25976 for(var j = 0; j < fl; j++){
25978 var v = this.ef[j](n);
25980 Roo.log('missing convert for ' + f.name);
25984 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
25988 raw : { errorMsg : "JSON Reader Error: fields or metadata not available to create Record" },
25994 var record = new Record(values, id);
25996 records[i] = record;
26002 totalRecords : totalRecords
26005 // used when loading children.. @see loadDataFromChildren
26006 toLoadData: function(rec)
26008 // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
26009 var data = typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
26010 return { data : data, total : data.length };
26015 * Ext JS Library 1.1.1
26016 * Copyright(c) 2006-2007, Ext JS, LLC.
26018 * Originally Released Under LGPL - original licence link has changed is not relivant.
26021 * <script type="text/javascript">
26025 * @class Roo.data.XmlReader
26026 * @extends Roo.data.DataReader
26027 * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
26028 * based on mappings in a provided Roo.data.Record constructor.<br><br>
26030 * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
26031 * header in the HTTP response must be set to "text/xml".</em>
26035 var RecordDef = Roo.data.Record.create([
26036 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
26037 {name: 'occupation'} // This field will use "occupation" as the mapping.
26039 var myReader = new Roo.data.XmlReader({
26040 totalRecords: "results", // The element which contains the total dataset size (optional)
26041 record: "row", // The repeated element which contains row information
26042 id: "id" // The element within the row that provides an ID for the record (optional)
26046 * This would consume an XML file like this:
26050 <results>2</results>
26053 <name>Bill</name>
26054 <occupation>Gardener</occupation>
26058 <name>Ben</name>
26059 <occupation>Horticulturalist</occupation>
26063 * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
26064 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
26065 * paged from the remote server.
26066 * @cfg {String} record The DomQuery path to the repeated element which contains record information.
26067 * @cfg {String} success The DomQuery path to the success attribute used by forms.
26068 * @cfg {String} id The DomQuery path relative from the record element to the element that contains
26069 * a record identifier value.
26071 * Create a new XmlReader
26072 * @param {Object} meta Metadata configuration options
26073 * @param {Mixed} recordType The definition of the data record type to produce. This can be either a valid
26074 * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
26075 * Roo.data.Record.create. See the {@link Roo.data.Record} class for more details.
26077 Roo.data.XmlReader = function(meta, recordType){
26079 Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
26081 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
26083 readerType : 'Xml',
26086 * This method is only used by a DataProxy which has retrieved data from a remote server.
26087 * @param {Object} response The XHR object which contains the parsed XML document. The response is expected
26088 * to contain a method called 'responseXML' that returns an XML document object.
26089 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
26090 * a cache of Roo.data.Records.
26092 read : function(response){
26093 var doc = response.responseXML;
26095 throw {message: "XmlReader.read: XML Document not available"};
26097 return this.readRecords(doc);
26101 * Create a data block containing Roo.data.Records from an XML document.
26102 * @param {Object} doc A parsed XML document.
26103 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
26104 * a cache of Roo.data.Records.
26106 readRecords : function(doc){
26108 * After any data loads/reads, the raw XML Document is available for further custom processing.
26109 * @type XMLDocument
26111 this.xmlData = doc;
26112 var root = doc.documentElement || doc;
26113 var q = Roo.DomQuery;
26114 var recordType = this.recordType, fields = recordType.prototype.fields;
26115 var sid = this.meta.id;
26116 var totalRecords = 0, success = true;
26117 if(this.meta.totalRecords){
26118 totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
26121 if(this.meta.success){
26122 var sv = q.selectValue(this.meta.success, root, true);
26123 success = sv !== false && sv !== 'false';
26126 var ns = q.select(this.meta.record, root);
26127 for(var i = 0, len = ns.length; i < len; i++) {
26130 var id = sid ? q.selectValue(sid, n) : undefined;
26131 for(var j = 0, jlen = fields.length; j < jlen; j++){
26132 var f = fields.items[j];
26133 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
26135 values[f.name] = v;
26137 var record = new recordType(values, id);
26139 records[records.length] = record;
26145 totalRecords : totalRecords || records.length
26150 * Ext JS Library 1.1.1
26151 * Copyright(c) 2006-2007, Ext JS, LLC.
26153 * Originally Released Under LGPL - original licence link has changed is not relivant.
26156 * <script type="text/javascript">
26160 * @class Roo.data.ArrayReader
26161 * @extends Roo.data.DataReader
26162 * Data reader class to create an Array of Roo.data.Record objects from an Array.
26163 * Each element of that Array represents a row of data fields. The
26164 * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
26165 * of the field definition if it exists, or the field's ordinal position in the definition.<br>
26169 var RecordDef = Roo.data.Record.create([
26170 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
26171 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
26173 var myReader = new Roo.data.ArrayReader({
26174 id: 0 // The subscript within row Array that provides an ID for the Record (optional)
26178 * This would consume an Array like this:
26180 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
26184 * Create a new JsonReader
26185 * @param {Object} meta Metadata configuration options.
26186 * @param {Object|Array} recordType Either an Array of field definition objects
26188 * @cfg {Array} fields Array of field definition objects
26189 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
26190 * as specified to {@link Roo.data.Record#create},
26191 * or an {@link Roo.data.Record} object
26194 * created using {@link Roo.data.Record#create}.
26196 Roo.data.ArrayReader = function(meta, recordType)
26198 Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
26201 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
26204 * Create a data block containing Roo.data.Records from an XML document.
26205 * @param {Object} o An Array of row objects which represents the dataset.
26206 * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
26207 * a cache of Roo.data.Records.
26209 readRecords : function(o)
26211 var sid = this.meta ? this.meta.id : null;
26212 var recordType = this.recordType, fields = recordType.prototype.fields;
26215 for(var i = 0; i < root.length; i++){
26218 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
26219 for(var j = 0, jlen = fields.length; j < jlen; j++){
26220 var f = fields.items[j];
26221 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
26222 var v = n[k] !== undefined ? n[k] : f.defaultValue;
26224 values[f.name] = v;
26226 var record = new recordType(values, id);
26228 records[records.length] = record;
26232 totalRecords : records.length
26235 // used when loading children.. @see loadDataFromChildren
26236 toLoadData: function(rec)
26238 // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
26239 return typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
26246 * Ext JS Library 1.1.1
26247 * Copyright(c) 2006-2007, Ext JS, LLC.
26249 * Originally Released Under LGPL - original licence link has changed is not relivant.
26252 * <script type="text/javascript">
26257 * @class Roo.data.Tree
26258 * @extends Roo.util.Observable
26259 * Represents a tree data structure and bubbles all the events for its nodes. The nodes
26260 * in the tree have most standard DOM functionality.
26262 * @param {Node} root (optional) The root node
26264 Roo.data.Tree = function(root){
26265 this.nodeHash = {};
26267 * The root node for this tree
26272 this.setRootNode(root);
26277 * Fires when a new child node is appended to a node in this tree.
26278 * @param {Tree} tree The owner tree
26279 * @param {Node} parent The parent node
26280 * @param {Node} node The newly appended node
26281 * @param {Number} index The index of the newly appended node
26286 * Fires when a child node is removed from a node in this tree.
26287 * @param {Tree} tree The owner tree
26288 * @param {Node} parent The parent node
26289 * @param {Node} node The child node removed
26294 * Fires when a node is moved to a new location in the tree
26295 * @param {Tree} tree The owner tree
26296 * @param {Node} node The node moved
26297 * @param {Node} oldParent The old parent of this node
26298 * @param {Node} newParent The new parent of this node
26299 * @param {Number} index The index it was moved to
26304 * Fires when a new child node is inserted in a node in this tree.
26305 * @param {Tree} tree The owner tree
26306 * @param {Node} parent The parent node
26307 * @param {Node} node The child node inserted
26308 * @param {Node} refNode The child node the node was inserted before
26312 * @event beforeappend
26313 * Fires before a new child is appended to a node in this tree, return false to cancel the append.
26314 * @param {Tree} tree The owner tree
26315 * @param {Node} parent The parent node
26316 * @param {Node} node The child node to be appended
26318 "beforeappend" : true,
26320 * @event beforeremove
26321 * Fires before a child is removed from a node in this tree, return false to cancel the remove.
26322 * @param {Tree} tree The owner tree
26323 * @param {Node} parent The parent node
26324 * @param {Node} node The child node to be removed
26326 "beforeremove" : true,
26328 * @event beforemove
26329 * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
26330 * @param {Tree} tree The owner tree
26331 * @param {Node} node The node being moved
26332 * @param {Node} oldParent The parent of the node
26333 * @param {Node} newParent The new parent the node is moving to
26334 * @param {Number} index The index it is being moved to
26336 "beforemove" : true,
26338 * @event beforeinsert
26339 * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
26340 * @param {Tree} tree The owner tree
26341 * @param {Node} parent The parent node
26342 * @param {Node} node The child node to be inserted
26343 * @param {Node} refNode The child node the node is being inserted before
26345 "beforeinsert" : true
26348 Roo.data.Tree.superclass.constructor.call(this);
26351 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
26352 pathSeparator: "/",
26354 proxyNodeEvent : function(){
26355 return this.fireEvent.apply(this, arguments);
26359 * Returns the root node for this tree.
26362 getRootNode : function(){
26367 * Sets the root node for this tree.
26368 * @param {Node} node
26371 setRootNode : function(node){
26373 node.ownerTree = this;
26374 node.isRoot = true;
26375 this.registerNode(node);
26380 * Gets a node in this tree by its id.
26381 * @param {String} id
26384 getNodeById : function(id){
26385 return this.nodeHash[id];
26388 registerNode : function(node){
26389 this.nodeHash[node.id] = node;
26392 unregisterNode : function(node){
26393 delete this.nodeHash[node.id];
26396 toString : function(){
26397 return "[Tree"+(this.id?" "+this.id:"")+"]";
26402 * @class Roo.data.Node
26403 * @extends Roo.util.Observable
26404 * @cfg {Boolean} leaf true if this node is a leaf and does not have children
26405 * @cfg {String} id The id for this node. If one is not specified, one is generated.
26407 * @param {Object} attributes The attributes/config for the node
26409 Roo.data.Node = function(attributes){
26411 * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
26414 this.attributes = attributes || {};
26415 this.leaf = this.attributes.leaf;
26417 * The node id. @type String
26419 this.id = this.attributes.id;
26421 this.id = Roo.id(null, "ynode-");
26422 this.attributes.id = this.id;
26427 * All child nodes of this node. @type Array
26429 this.childNodes = [];
26430 if(!this.childNodes.indexOf){ // indexOf is a must
26431 this.childNodes.indexOf = function(o){
26432 for(var i = 0, len = this.length; i < len; i++){
26441 * The parent node for this node. @type Node
26443 this.parentNode = null;
26445 * The first direct child node of this node, or null if this node has no child nodes. @type Node
26447 this.firstChild = null;
26449 * The last direct child node of this node, or null if this node has no child nodes. @type Node
26451 this.lastChild = null;
26453 * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
26455 this.previousSibling = null;
26457 * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
26459 this.nextSibling = null;
26464 * Fires when a new child node is appended
26465 * @param {Tree} tree The owner tree
26466 * @param {Node} this This node
26467 * @param {Node} node The newly appended node
26468 * @param {Number} index The index of the newly appended node
26473 * Fires when a child node is removed
26474 * @param {Tree} tree The owner tree
26475 * @param {Node} this This node
26476 * @param {Node} node The removed node
26481 * Fires when this node is moved to a new location in the tree
26482 * @param {Tree} tree The owner tree
26483 * @param {Node} this This node
26484 * @param {Node} oldParent The old parent of this node
26485 * @param {Node} newParent The new parent of this node
26486 * @param {Number} index The index it was moved to
26491 * Fires when a new child node is inserted.
26492 * @param {Tree} tree The owner tree
26493 * @param {Node} this This node
26494 * @param {Node} node The child node inserted
26495 * @param {Node} refNode The child node the node was inserted before
26499 * @event beforeappend
26500 * Fires before a new child is appended, return false to cancel the append.
26501 * @param {Tree} tree The owner tree
26502 * @param {Node} this This node
26503 * @param {Node} node The child node to be appended
26505 "beforeappend" : true,
26507 * @event beforeremove
26508 * Fires before a child is removed, return false to cancel the remove.
26509 * @param {Tree} tree The owner tree
26510 * @param {Node} this This node
26511 * @param {Node} node The child node to be removed
26513 "beforeremove" : true,
26515 * @event beforemove
26516 * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
26517 * @param {Tree} tree The owner tree
26518 * @param {Node} this This node
26519 * @param {Node} oldParent The parent of this node
26520 * @param {Node} newParent The new parent this node is moving to
26521 * @param {Number} index The index it is being moved to
26523 "beforemove" : true,
26525 * @event beforeinsert
26526 * Fires before a new child is inserted, return false to cancel the insert.
26527 * @param {Tree} tree The owner tree
26528 * @param {Node} this This node
26529 * @param {Node} node The child node to be inserted
26530 * @param {Node} refNode The child node the node is being inserted before
26532 "beforeinsert" : true
26534 this.listeners = this.attributes.listeners;
26535 Roo.data.Node.superclass.constructor.call(this);
26538 Roo.extend(Roo.data.Node, Roo.util.Observable, {
26539 fireEvent : function(evtName){
26540 // first do standard event for this node
26541 if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
26544 // then bubble it up to the tree if the event wasn't cancelled
26545 var ot = this.getOwnerTree();
26547 if(ot.proxyNodeEvent.apply(ot, arguments) === false){
26555 * Returns true if this node is a leaf
26556 * @return {Boolean}
26558 isLeaf : function(){
26559 return this.leaf === true;
26563 setFirstChild : function(node){
26564 this.firstChild = node;
26568 setLastChild : function(node){
26569 this.lastChild = node;
26574 * Returns true if this node is the last child of its parent
26575 * @return {Boolean}
26577 isLast : function(){
26578 return (!this.parentNode ? true : this.parentNode.lastChild == this);
26582 * Returns true if this node is the first child of its parent
26583 * @return {Boolean}
26585 isFirst : function(){
26586 return (!this.parentNode ? true : this.parentNode.firstChild == this);
26589 hasChildNodes : function(){
26590 return !this.isLeaf() && this.childNodes.length > 0;
26594 * Insert node(s) as the last child node of this node.
26595 * @param {Node/Array} node The node or Array of nodes to append
26596 * @return {Node} The appended node if single append, or null if an array was passed
26598 appendChild : function(node){
26600 if(node instanceof Array){
26602 }else if(arguments.length > 1){
26606 // if passed an array or multiple args do them one by one
26608 for(var i = 0, len = multi.length; i < len; i++) {
26609 this.appendChild(multi[i]);
26612 if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
26615 var index = this.childNodes.length;
26616 var oldParent = node.parentNode;
26617 // it's a move, make sure we move it cleanly
26619 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
26622 oldParent.removeChild(node);
26625 index = this.childNodes.length;
26627 this.setFirstChild(node);
26629 this.childNodes.push(node);
26630 node.parentNode = this;
26631 var ps = this.childNodes[index-1];
26633 node.previousSibling = ps;
26634 ps.nextSibling = node;
26636 node.previousSibling = null;
26638 node.nextSibling = null;
26639 this.setLastChild(node);
26640 node.setOwnerTree(this.getOwnerTree());
26641 this.fireEvent("append", this.ownerTree, this, node, index);
26642 if(this.ownerTree) {
26643 this.ownerTree.fireEvent("appendnode", this, node, index);
26646 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
26653 * Removes a child node from this node.
26654 * @param {Node} node The node to remove
26655 * @return {Node} The removed node
26657 removeChild : function(node){
26658 var index = this.childNodes.indexOf(node);
26662 if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
26666 // remove it from childNodes collection
26667 this.childNodes.splice(index, 1);
26670 if(node.previousSibling){
26671 node.previousSibling.nextSibling = node.nextSibling;
26673 if(node.nextSibling){
26674 node.nextSibling.previousSibling = node.previousSibling;
26677 // update child refs
26678 if(this.firstChild == node){
26679 this.setFirstChild(node.nextSibling);
26681 if(this.lastChild == node){
26682 this.setLastChild(node.previousSibling);
26685 node.setOwnerTree(null);
26686 // clear any references from the node
26687 node.parentNode = null;
26688 node.previousSibling = null;
26689 node.nextSibling = null;
26690 this.fireEvent("remove", this.ownerTree, this, node);
26695 * Inserts the first node before the second node in this nodes childNodes collection.
26696 * @param {Node} node The node to insert
26697 * @param {Node} refNode The node to insert before (if null the node is appended)
26698 * @return {Node} The inserted node
26700 insertBefore : function(node, refNode){
26701 if(!refNode){ // like standard Dom, refNode can be null for append
26702 return this.appendChild(node);
26705 if(node == refNode){
26709 if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
26712 var index = this.childNodes.indexOf(refNode);
26713 var oldParent = node.parentNode;
26714 var refIndex = index;
26716 // when moving internally, indexes will change after remove
26717 if(oldParent == this && this.childNodes.indexOf(node) < index){
26721 // it's a move, make sure we move it cleanly
26723 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
26726 oldParent.removeChild(node);
26729 this.setFirstChild(node);
26731 this.childNodes.splice(refIndex, 0, node);
26732 node.parentNode = this;
26733 var ps = this.childNodes[refIndex-1];
26735 node.previousSibling = ps;
26736 ps.nextSibling = node;
26738 node.previousSibling = null;
26740 node.nextSibling = refNode;
26741 refNode.previousSibling = node;
26742 node.setOwnerTree(this.getOwnerTree());
26743 this.fireEvent("insert", this.ownerTree, this, node, refNode);
26745 node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
26751 * Returns the child node at the specified index.
26752 * @param {Number} index
26755 item : function(index){
26756 return this.childNodes[index];
26760 * Replaces one child node in this node with another.
26761 * @param {Node} newChild The replacement node
26762 * @param {Node} oldChild The node to replace
26763 * @return {Node} The replaced node
26765 replaceChild : function(newChild, oldChild){
26766 this.insertBefore(newChild, oldChild);
26767 this.removeChild(oldChild);
26772 * Returns the index of a child node
26773 * @param {Node} node
26774 * @return {Number} The index of the node or -1 if it was not found
26776 indexOf : function(child){
26777 return this.childNodes.indexOf(child);
26781 * Returns the tree this node is in.
26784 getOwnerTree : function(){
26785 // if it doesn't have one, look for one
26786 if(!this.ownerTree){
26790 this.ownerTree = p.ownerTree;
26796 return this.ownerTree;
26800 * Returns depth of this node (the root node has a depth of 0)
26803 getDepth : function(){
26806 while(p.parentNode){
26814 setOwnerTree : function(tree){
26815 // if it's move, we need to update everyone
26816 if(tree != this.ownerTree){
26817 if(this.ownerTree){
26818 this.ownerTree.unregisterNode(this);
26820 this.ownerTree = tree;
26821 var cs = this.childNodes;
26822 for(var i = 0, len = cs.length; i < len; i++) {
26823 cs[i].setOwnerTree(tree);
26826 tree.registerNode(this);
26832 * Returns the path for this node. The path can be used to expand or select this node programmatically.
26833 * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
26834 * @return {String} The path
26836 getPath : function(attr){
26837 attr = attr || "id";
26838 var p = this.parentNode;
26839 var b = [this.attributes[attr]];
26841 b.unshift(p.attributes[attr]);
26844 var sep = this.getOwnerTree().pathSeparator;
26845 return sep + b.join(sep);
26849 * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
26850 * function call will be the scope provided or the current node. The arguments to the function
26851 * will be the args provided or the current node. If the function returns false at any point,
26852 * the bubble is stopped.
26853 * @param {Function} fn The function to call
26854 * @param {Object} scope (optional) The scope of the function (defaults to current node)
26855 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
26857 bubble : function(fn, scope, args){
26860 if(fn.call(scope || p, args || p) === false){
26868 * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
26869 * function call will be the scope provided or the current node. The arguments to the function
26870 * will be the args provided or the current node. If the function returns false at any point,
26871 * the cascade is stopped on that branch.
26872 * @param {Function} fn The function to call
26873 * @param {Object} scope (optional) The scope of the function (defaults to current node)
26874 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
26876 cascade : function(fn, scope, args){
26877 if(fn.call(scope || this, args || this) !== false){
26878 var cs = this.childNodes;
26879 for(var i = 0, len = cs.length; i < len; i++) {
26880 cs[i].cascade(fn, scope, args);
26886 * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
26887 * function call will be the scope provided or the current node. The arguments to the function
26888 * will be the args provided or the current node. If the function returns false at any point,
26889 * the iteration stops.
26890 * @param {Function} fn The function to call
26891 * @param {Object} scope (optional) The scope of the function (defaults to current node)
26892 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
26894 eachChild : function(fn, scope, args){
26895 var cs = this.childNodes;
26896 for(var i = 0, len = cs.length; i < len; i++) {
26897 if(fn.call(scope || this, args || cs[i]) === false){
26904 * Finds the first child that has the attribute with the specified value.
26905 * @param {String} attribute The attribute name
26906 * @param {Mixed} value The value to search for
26907 * @return {Node} The found child or null if none was found
26909 findChild : function(attribute, value){
26910 var cs = this.childNodes;
26911 for(var i = 0, len = cs.length; i < len; i++) {
26912 if(cs[i].attributes[attribute] == value){
26920 * Finds the first child by a custom function. The child matches if the function passed
26922 * @param {Function} fn
26923 * @param {Object} scope (optional)
26924 * @return {Node} The found child or null if none was found
26926 findChildBy : function(fn, scope){
26927 var cs = this.childNodes;
26928 for(var i = 0, len = cs.length; i < len; i++) {
26929 if(fn.call(scope||cs[i], cs[i]) === true){
26937 * Sorts this nodes children using the supplied sort function
26938 * @param {Function} fn
26939 * @param {Object} scope (optional)
26941 sort : function(fn, scope){
26942 var cs = this.childNodes;
26943 var len = cs.length;
26945 var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
26947 for(var i = 0; i < len; i++){
26949 n.previousSibling = cs[i-1];
26950 n.nextSibling = cs[i+1];
26952 this.setFirstChild(n);
26955 this.setLastChild(n);
26962 * Returns true if this node is an ancestor (at any point) of the passed node.
26963 * @param {Node} node
26964 * @return {Boolean}
26966 contains : function(node){
26967 return node.isAncestor(this);
26971 * Returns true if the passed node is an ancestor (at any point) of this node.
26972 * @param {Node} node
26973 * @return {Boolean}
26975 isAncestor : function(node){
26976 var p = this.parentNode;
26986 toString : function(){
26987 return "[Node"+(this.id?" "+this.id:"")+"]";
26991 * Ext JS Library 1.1.1
26992 * Copyright(c) 2006-2007, Ext JS, LLC.
26994 * Originally Released Under LGPL - original licence link has changed is not relivant.
26997 * <script type="text/javascript">
27002 * @class Roo.Shadow
27003 * Simple class that can provide a shadow effect for any element. Note that the element MUST be absolutely positioned,
27004 * and the shadow does not provide any shimming. This should be used only in simple cases -- for more advanced
27005 * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
27007 * Create a new Shadow
27008 * @param {Object} config The config object
27010 Roo.Shadow = function(config){
27011 Roo.apply(this, config);
27012 if(typeof this.mode != "string"){
27013 this.mode = this.defaultMode;
27015 var o = this.offset, a = {h: 0};
27016 var rad = Math.floor(this.offset/2);
27017 switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
27023 a.l -= this.offset + rad;
27024 a.t -= this.offset + rad;
27035 a.l -= (this.offset - rad);
27036 a.t -= this.offset + rad;
27038 a.w -= (this.offset - rad)*2;
27049 a.l -= (this.offset - rad);
27050 a.t -= (this.offset - rad);
27052 a.w -= (this.offset + rad + 1);
27053 a.h -= (this.offset + rad);
27062 Roo.Shadow.prototype = {
27064 * @cfg {String} mode
27065 * The shadow display mode. Supports the following options:<br />
27066 * sides: Shadow displays on both sides and bottom only<br />
27067 * frame: Shadow displays equally on all four sides<br />
27068 * drop: Traditional bottom-right drop shadow (default)
27072 * @cfg {String} offset
27073 * The number of pixels to offset the shadow from the element (defaults to 4)
27078 defaultMode: "drop",
27081 * Displays the shadow under the target element
27082 * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
27084 show : function(target){
27085 target = Roo.get(target);
27087 this.el = Roo.Shadow.Pool.pull();
27088 if(this.el.dom.nextSibling != target.dom){
27089 this.el.insertBefore(target);
27092 this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
27094 this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
27097 target.getLeft(true),
27098 target.getTop(true),
27102 this.el.dom.style.display = "block";
27106 * Returns true if the shadow is visible, else false
27108 isVisible : function(){
27109 return this.el ? true : false;
27113 * Direct alignment when values are already available. Show must be called at least once before
27114 * calling this method to ensure it is initialized.
27115 * @param {Number} left The target element left position
27116 * @param {Number} top The target element top position
27117 * @param {Number} width The target element width
27118 * @param {Number} height The target element height
27120 realign : function(l, t, w, h){
27124 var a = this.adjusts, d = this.el.dom, s = d.style;
27126 s.left = (l+a.l)+"px";
27127 s.top = (t+a.t)+"px";
27128 var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
27130 if(s.width != sws || s.height != shs){
27134 var cn = d.childNodes;
27135 var sww = Math.max(0, (sw-12))+"px";
27136 cn[0].childNodes[1].style.width = sww;
27137 cn[1].childNodes[1].style.width = sww;
27138 cn[2].childNodes[1].style.width = sww;
27139 cn[1].style.height = Math.max(0, (sh-12))+"px";
27145 * Hides this shadow
27149 this.el.dom.style.display = "none";
27150 Roo.Shadow.Pool.push(this.el);
27156 * Adjust the z-index of this shadow
27157 * @param {Number} zindex The new z-index
27159 setZIndex : function(z){
27162 this.el.setStyle("z-index", z);
27167 // Private utility class that manages the internal Shadow cache
27168 Roo.Shadow.Pool = function(){
27170 var markup = Roo.isIE ?
27171 '<div class="x-ie-shadow"></div>' :
27172 '<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>';
27175 var sh = p.shift();
27177 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
27178 sh.autoBoxAdjust = false;
27183 push : function(sh){
27189 * Ext JS Library 1.1.1
27190 * Copyright(c) 2006-2007, Ext JS, LLC.
27192 * Originally Released Under LGPL - original licence link has changed is not relivant.
27195 * <script type="text/javascript">
27200 * @class Roo.SplitBar
27201 * @extends Roo.util.Observable
27202 * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
27206 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
27207 Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
27208 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
27209 split.minSize = 100;
27210 split.maxSize = 600;
27211 split.animate = true;
27212 split.on('moved', splitterMoved);
27215 * Create a new SplitBar
27216 * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar.
27217 * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged
27218 * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
27219 * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or
27220 Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
27221 position of the SplitBar).
27223 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
27226 this.el = Roo.get(dragElement, true);
27227 this.el.dom.unselectable = "on";
27229 this.resizingEl = Roo.get(resizingElement, true);
27233 * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
27234 * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
27237 this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
27240 * The minimum size of the resizing element. (Defaults to 0)
27246 * The maximum size of the resizing element. (Defaults to 2000)
27249 this.maxSize = 2000;
27252 * Whether to animate the transition to the new size
27255 this.animate = false;
27258 * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
27261 this.useShim = false;
27266 if(!existingProxy){
27268 this.proxy = Roo.SplitBar.createProxy(this.orientation);
27270 this.proxy = Roo.get(existingProxy).dom;
27273 this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
27276 this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
27279 this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
27282 this.dragSpecs = {};
27285 * @private The adapter to use to positon and resize elements
27287 this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
27288 this.adapter.init(this);
27290 if(this.orientation == Roo.SplitBar.HORIZONTAL){
27292 this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
27293 this.el.addClass("x-splitbar-h");
27296 this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
27297 this.el.addClass("x-splitbar-v");
27303 * Fires when the splitter is moved (alias for {@link #event-moved})
27304 * @param {Roo.SplitBar} this
27305 * @param {Number} newSize the new width or height
27310 * Fires when the splitter is moved
27311 * @param {Roo.SplitBar} this
27312 * @param {Number} newSize the new width or height
27316 * @event beforeresize
27317 * Fires before the splitter is dragged
27318 * @param {Roo.SplitBar} this
27320 "beforeresize" : true,
27322 "beforeapply" : true
27325 Roo.util.Observable.call(this);
27328 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
27329 onStartProxyDrag : function(x, y){
27330 this.fireEvent("beforeresize", this);
27332 var o = Roo.DomHelper.insertFirst(document.body, {cls: "x-drag-overlay", html: " "}, true);
27334 o.enableDisplayMode("block");
27335 // all splitbars share the same overlay
27336 Roo.SplitBar.prototype.overlay = o;
27338 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
27339 this.overlay.show();
27340 Roo.get(this.proxy).setDisplayed("block");
27341 var size = this.adapter.getElementSize(this);
27342 this.activeMinSize = this.getMinimumSize();;
27343 this.activeMaxSize = this.getMaximumSize();;
27344 var c1 = size - this.activeMinSize;
27345 var c2 = Math.max(this.activeMaxSize - size, 0);
27346 if(this.orientation == Roo.SplitBar.HORIZONTAL){
27347 this.dd.resetConstraints();
27348 this.dd.setXConstraint(
27349 this.placement == Roo.SplitBar.LEFT ? c1 : c2,
27350 this.placement == Roo.SplitBar.LEFT ? c2 : c1
27352 this.dd.setYConstraint(0, 0);
27354 this.dd.resetConstraints();
27355 this.dd.setXConstraint(0, 0);
27356 this.dd.setYConstraint(
27357 this.placement == Roo.SplitBar.TOP ? c1 : c2,
27358 this.placement == Roo.SplitBar.TOP ? c2 : c1
27361 this.dragSpecs.startSize = size;
27362 this.dragSpecs.startPoint = [x, y];
27363 Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
27367 * @private Called after the drag operation by the DDProxy
27369 onEndProxyDrag : function(e){
27370 Roo.get(this.proxy).setDisplayed(false);
27371 var endPoint = Roo.lib.Event.getXY(e);
27373 this.overlay.hide();
27376 if(this.orientation == Roo.SplitBar.HORIZONTAL){
27377 newSize = this.dragSpecs.startSize +
27378 (this.placement == Roo.SplitBar.LEFT ?
27379 endPoint[0] - this.dragSpecs.startPoint[0] :
27380 this.dragSpecs.startPoint[0] - endPoint[0]
27383 newSize = this.dragSpecs.startSize +
27384 (this.placement == Roo.SplitBar.TOP ?
27385 endPoint[1] - this.dragSpecs.startPoint[1] :
27386 this.dragSpecs.startPoint[1] - endPoint[1]
27389 newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
27390 if(newSize != this.dragSpecs.startSize){
27391 if(this.fireEvent('beforeapply', this, newSize) !== false){
27392 this.adapter.setElementSize(this, newSize);
27393 this.fireEvent("moved", this, newSize);
27394 this.fireEvent("resize", this, newSize);
27400 * Get the adapter this SplitBar uses
27401 * @return The adapter object
27403 getAdapter : function(){
27404 return this.adapter;
27408 * Set the adapter this SplitBar uses
27409 * @param {Object} adapter A SplitBar adapter object
27411 setAdapter : function(adapter){
27412 this.adapter = adapter;
27413 this.adapter.init(this);
27417 * Gets the minimum size for the resizing element
27418 * @return {Number} The minimum size
27420 getMinimumSize : function(){
27421 return this.minSize;
27425 * Sets the minimum size for the resizing element
27426 * @param {Number} minSize The minimum size
27428 setMinimumSize : function(minSize){
27429 this.minSize = minSize;
27433 * Gets the maximum size for the resizing element
27434 * @return {Number} The maximum size
27436 getMaximumSize : function(){
27437 return this.maxSize;
27441 * Sets the maximum size for the resizing element
27442 * @param {Number} maxSize The maximum size
27444 setMaximumSize : function(maxSize){
27445 this.maxSize = maxSize;
27449 * Sets the initialize size for the resizing element
27450 * @param {Number} size The initial size
27452 setCurrentSize : function(size){
27453 var oldAnimate = this.animate;
27454 this.animate = false;
27455 this.adapter.setElementSize(this, size);
27456 this.animate = oldAnimate;
27460 * Destroy this splitbar.
27461 * @param {Boolean} removeEl True to remove the element
27463 destroy : function(removeEl){
27465 this.shim.remove();
27468 this.proxy.parentNode.removeChild(this.proxy);
27476 * @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.
27478 Roo.SplitBar.createProxy = function(dir){
27479 var proxy = new Roo.Element(document.createElement("div"));
27480 proxy.unselectable();
27481 var cls = 'x-splitbar-proxy';
27482 proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
27483 document.body.appendChild(proxy.dom);
27488 * @class Roo.SplitBar.BasicLayoutAdapter
27489 * Default Adapter. It assumes the splitter and resizing element are not positioned
27490 * elements and only gets/sets the width of the element. Generally used for table based layouts.
27492 Roo.SplitBar.BasicLayoutAdapter = function(){
27495 Roo.SplitBar.BasicLayoutAdapter.prototype = {
27496 // do nothing for now
27497 init : function(s){
27501 * Called before drag operations to get the current size of the resizing element.
27502 * @param {Roo.SplitBar} s The SplitBar using this adapter
27504 getElementSize : function(s){
27505 if(s.orientation == Roo.SplitBar.HORIZONTAL){
27506 return s.resizingEl.getWidth();
27508 return s.resizingEl.getHeight();
27513 * Called after drag operations to set the size of the resizing element.
27514 * @param {Roo.SplitBar} s The SplitBar using this adapter
27515 * @param {Number} newSize The new size to set
27516 * @param {Function} onComplete A function to be invoked when resizing is complete
27518 setElementSize : function(s, newSize, onComplete){
27519 if(s.orientation == Roo.SplitBar.HORIZONTAL){
27521 s.resizingEl.setWidth(newSize);
27523 onComplete(s, newSize);
27526 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
27531 s.resizingEl.setHeight(newSize);
27533 onComplete(s, newSize);
27536 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
27543 *@class Roo.SplitBar.AbsoluteLayoutAdapter
27544 * @extends Roo.SplitBar.BasicLayoutAdapter
27545 * Adapter that moves the splitter element to align with the resized sizing element.
27546 * Used with an absolute positioned SplitBar.
27547 * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
27548 * document.body, make sure you assign an id to the body element.
27550 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
27551 this.basic = new Roo.SplitBar.BasicLayoutAdapter();
27552 this.container = Roo.get(container);
27555 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
27556 init : function(s){
27557 this.basic.init(s);
27560 getElementSize : function(s){
27561 return this.basic.getElementSize(s);
27564 setElementSize : function(s, newSize, onComplete){
27565 this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
27568 moveSplitter : function(s){
27569 var yes = Roo.SplitBar;
27570 switch(s.placement){
27572 s.el.setX(s.resizingEl.getRight());
27575 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
27578 s.el.setY(s.resizingEl.getBottom());
27581 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
27588 * Orientation constant - Create a vertical SplitBar
27592 Roo.SplitBar.VERTICAL = 1;
27595 * Orientation constant - Create a horizontal SplitBar
27599 Roo.SplitBar.HORIZONTAL = 2;
27602 * Placement constant - The resizing element is to the left of the splitter element
27606 Roo.SplitBar.LEFT = 1;
27609 * Placement constant - The resizing element is to the right of the splitter element
27613 Roo.SplitBar.RIGHT = 2;
27616 * Placement constant - The resizing element is positioned above the splitter element
27620 Roo.SplitBar.TOP = 3;
27623 * Placement constant - The resizing element is positioned under splitter element
27627 Roo.SplitBar.BOTTOM = 4;
27630 * Ext JS Library 1.1.1
27631 * Copyright(c) 2006-2007, Ext JS, LLC.
27633 * Originally Released Under LGPL - original licence link has changed is not relivant.
27636 * <script type="text/javascript">
27641 * @extends Roo.util.Observable
27642 * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template.
27643 * This class also supports single and multi selection modes. <br>
27644 * Create a data model bound view:
27646 var store = new Roo.data.Store(...);
27648 var view = new Roo.View({
27650 tpl : '<div id="{0}">{2} - {1}</div>', // auto create template
27652 singleSelect: true,
27653 selectedClass: "ydataview-selected",
27657 // listen for node click?
27658 view.on("click", function(vw, index, node, e){
27659 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
27663 dataModel.load("foobar.xml");
27665 For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
27667 * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
27668 * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
27670 * Note: old style constructor is still suported (container, template, config)
27673 * Create a new View
27674 * @param {Object} config The config object
27677 Roo.View = function(config, depreciated_tpl, depreciated_config){
27679 this.parent = false;
27681 if (typeof(depreciated_tpl) == 'undefined') {
27682 // new way.. - universal constructor.
27683 Roo.apply(this, config);
27684 this.el = Roo.get(this.el);
27687 this.el = Roo.get(config);
27688 this.tpl = depreciated_tpl;
27689 Roo.apply(this, depreciated_config);
27691 this.wrapEl = this.el.wrap().wrap();
27692 ///this.el = this.wrapEla.appendChild(document.createElement("div"));
27695 if(typeof(this.tpl) == "string"){
27696 this.tpl = new Roo.Template(this.tpl);
27698 // support xtype ctors..
27699 this.tpl = new Roo.factory(this.tpl, Roo);
27703 this.tpl.compile();
27708 * @event beforeclick
27709 * Fires before a click is processed. Returns false to cancel the default action.
27710 * @param {Roo.View} this
27711 * @param {Number} index The index of the target node
27712 * @param {HTMLElement} node The target node
27713 * @param {Roo.EventObject} e The raw event object
27715 "beforeclick" : true,
27718 * Fires when a template node is clicked.
27719 * @param {Roo.View} this
27720 * @param {Number} index The index of the target node
27721 * @param {HTMLElement} node The target node
27722 * @param {Roo.EventObject} e The raw event object
27727 * Fires when a template node is double clicked.
27728 * @param {Roo.View} this
27729 * @param {Number} index The index of the target node
27730 * @param {HTMLElement} node The target node
27731 * @param {Roo.EventObject} e The raw event object
27735 * @event contextmenu
27736 * Fires when a template node is right clicked.
27737 * @param {Roo.View} this
27738 * @param {Number} index The index of the target node
27739 * @param {HTMLElement} node The target node
27740 * @param {Roo.EventObject} e The raw event object
27742 "contextmenu" : true,
27744 * @event selectionchange
27745 * Fires when the selected nodes change.
27746 * @param {Roo.View} this
27747 * @param {Array} selections Array of the selected nodes
27749 "selectionchange" : true,
27752 * @event beforeselect
27753 * Fires before a selection is made. If any handlers return false, the selection is cancelled.
27754 * @param {Roo.View} this
27755 * @param {HTMLElement} node The node to be selected
27756 * @param {Array} selections Array of currently selected nodes
27758 "beforeselect" : true,
27760 * @event preparedata
27761 * Fires on every row to render, to allow you to change the data.
27762 * @param {Roo.View} this
27763 * @param {Object} data to be rendered (change this)
27765 "preparedata" : true
27773 "click": this.onClick,
27774 "dblclick": this.onDblClick,
27775 "contextmenu": this.onContextMenu,
27779 this.selections = [];
27781 this.cmp = new Roo.CompositeElementLite([]);
27783 this.store = Roo.factory(this.store, Roo.data);
27784 this.setStore(this.store, true);
27787 if ( this.footer && this.footer.xtype) {
27789 var fctr = this.wrapEl.appendChild(document.createElement("div"));
27791 this.footer.dataSource = this.store;
27792 this.footer.container = fctr;
27793 this.footer = Roo.factory(this.footer, Roo);
27794 fctr.insertFirst(this.el);
27796 // this is a bit insane - as the paging toolbar seems to detach the el..
27797 // dom.parentNode.parentNode.parentNode
27798 // they get detached?
27802 Roo.View.superclass.constructor.call(this);
27807 Roo.extend(Roo.View, Roo.util.Observable, {
27810 * @cfg {Roo.data.Store} store Data store to load data from.
27815 * @cfg {String|Roo.Element} el The container element.
27820 * @cfg {String|Roo.Template} tpl The template used by this View
27824 * @cfg {String} dataName the named area of the template to use as the data area
27825 * Works with domtemplates roo-name="name"
27829 * @cfg {String} selectedClass The css class to add to selected nodes
27831 selectedClass : "x-view-selected",
27833 * @cfg {String} emptyText The empty text to show when nothing is loaded.
27838 * @cfg {String} text to display on mask (default Loading)
27842 * @cfg {Boolean} multiSelect Allow multiple selection
27844 multiSelect : false,
27846 * @cfg {Boolean} singleSelect Allow single selection
27848 singleSelect: false,
27851 * @cfg {Boolean} toggleSelect - selecting
27853 toggleSelect : false,
27856 * @cfg {Boolean} tickable - selecting
27861 * Returns the element this view is bound to.
27862 * @return {Roo.Element}
27864 getEl : function(){
27865 return this.wrapEl;
27871 * Refreshes the view. - called by datachanged on the store. - do not call directly.
27873 refresh : function(){
27874 //Roo.log('refresh');
27877 // if we are using something like 'domtemplate', then
27878 // the what gets used is:
27879 // t.applySubtemplate(NAME, data, wrapping data..)
27880 // the outer template then get' applied with
27881 // the store 'extra data'
27882 // and the body get's added to the
27883 // roo-name="data" node?
27884 // <span class='roo-tpl-{name}'></span> ?????
27888 this.clearSelections();
27889 this.el.update("");
27891 var records = this.store.getRange();
27892 if(records.length < 1) {
27894 // is this valid?? = should it render a template??
27896 this.el.update(this.emptyText);
27900 if (this.dataName) {
27901 this.el.update(t.apply(this.store.meta)); //????
27902 el = this.el.child('.roo-tpl-' + this.dataName);
27905 for(var i = 0, len = records.length; i < len; i++){
27906 var data = this.prepareData(records[i].data, i, records[i]);
27907 this.fireEvent("preparedata", this, data, i, records[i]);
27909 var d = Roo.apply({}, data);
27912 Roo.apply(d, {'roo-id' : Roo.id()});
27916 Roo.each(this.parent.item, function(item){
27917 if(item[_this.parent.valueField] != data[_this.parent.valueField]){
27920 Roo.apply(d, {'roo-data-checked' : 'checked'});
27924 html[html.length] = Roo.util.Format.trim(
27926 t.applySubtemplate(this.dataName, d, this.store.meta) :
27933 el.update(html.join(""));
27934 this.nodes = el.dom.childNodes;
27935 this.updateIndexes(0);
27940 * Function to override to reformat the data that is sent to
27941 * the template for each node.
27942 * DEPRICATED - use the preparedata event handler.
27943 * @param {Array/Object} data The raw data (array of colData for a data model bound view or
27944 * a JSON object for an UpdateManager bound view).
27946 prepareData : function(data, index, record)
27948 this.fireEvent("preparedata", this, data, index, record);
27952 onUpdate : function(ds, record){
27953 // Roo.log('on update');
27954 this.clearSelections();
27955 var index = this.store.indexOf(record);
27956 var n = this.nodes[index];
27957 this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
27958 n.parentNode.removeChild(n);
27959 this.updateIndexes(index, index);
27965 onAdd : function(ds, records, index)
27967 //Roo.log(['on Add', ds, records, index] );
27968 this.clearSelections();
27969 if(this.nodes.length == 0){
27973 var n = this.nodes[index];
27974 for(var i = 0, len = records.length; i < len; i++){
27975 var d = this.prepareData(records[i].data, i, records[i]);
27977 this.tpl.insertBefore(n, d);
27980 this.tpl.append(this.el, d);
27983 this.updateIndexes(index);
27986 onRemove : function(ds, record, index){
27987 // Roo.log('onRemove');
27988 this.clearSelections();
27989 var el = this.dataName ?
27990 this.el.child('.roo-tpl-' + this.dataName) :
27993 el.dom.removeChild(this.nodes[index]);
27994 this.updateIndexes(index);
27998 * Refresh an individual node.
27999 * @param {Number} index
28001 refreshNode : function(index){
28002 this.onUpdate(this.store, this.store.getAt(index));
28005 updateIndexes : function(startIndex, endIndex){
28006 var ns = this.nodes;
28007 startIndex = startIndex || 0;
28008 endIndex = endIndex || ns.length - 1;
28009 for(var i = startIndex; i <= endIndex; i++){
28010 ns[i].nodeIndex = i;
28015 * Changes the data store this view uses and refresh the view.
28016 * @param {Store} store
28018 setStore : function(store, initial){
28019 if(!initial && this.store){
28020 this.store.un("datachanged", this.refresh);
28021 this.store.un("add", this.onAdd);
28022 this.store.un("remove", this.onRemove);
28023 this.store.un("update", this.onUpdate);
28024 this.store.un("clear", this.refresh);
28025 this.store.un("beforeload", this.onBeforeLoad);
28026 this.store.un("load", this.onLoad);
28027 this.store.un("loadexception", this.onLoad);
28031 store.on("datachanged", this.refresh, this);
28032 store.on("add", this.onAdd, this);
28033 store.on("remove", this.onRemove, this);
28034 store.on("update", this.onUpdate, this);
28035 store.on("clear", this.refresh, this);
28036 store.on("beforeload", this.onBeforeLoad, this);
28037 store.on("load", this.onLoad, this);
28038 store.on("loadexception", this.onLoad, this);
28046 * onbeforeLoad - masks the loading area.
28049 onBeforeLoad : function(store,opts)
28051 //Roo.log('onBeforeLoad');
28053 this.el.update("");
28055 this.el.mask(this.mask ? this.mask : "Loading" );
28057 onLoad : function ()
28064 * Returns the template node the passed child belongs to or null if it doesn't belong to one.
28065 * @param {HTMLElement} node
28066 * @return {HTMLElement} The template node
28068 findItemFromChild : function(node){
28069 var el = this.dataName ?
28070 this.el.child('.roo-tpl-' + this.dataName,true) :
28073 if(!node || node.parentNode == el){
28076 var p = node.parentNode;
28077 while(p && p != el){
28078 if(p.parentNode == el){
28087 onClick : function(e){
28088 var item = this.findItemFromChild(e.getTarget());
28090 var index = this.indexOf(item);
28091 if(this.onItemClick(item, index, e) !== false){
28092 this.fireEvent("click", this, index, item, e);
28095 this.clearSelections();
28100 onContextMenu : function(e){
28101 var item = this.findItemFromChild(e.getTarget());
28103 this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
28108 onDblClick : function(e){
28109 var item = this.findItemFromChild(e.getTarget());
28111 this.fireEvent("dblclick", this, this.indexOf(item), item, e);
28115 onItemClick : function(item, index, e)
28117 if(this.fireEvent("beforeclick", this, index, item, e) === false){
28120 if (this.toggleSelect) {
28121 var m = this.isSelected(item) ? 'unselect' : 'select';
28124 _t[m](item, true, false);
28127 if(this.multiSelect || this.singleSelect){
28128 if(this.multiSelect && e.shiftKey && this.lastSelection){
28129 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
28131 this.select(item, this.multiSelect && e.ctrlKey);
28132 this.lastSelection = item;
28135 if(!this.tickable){
28136 e.preventDefault();
28144 * Get the number of selected nodes.
28147 getSelectionCount : function(){
28148 return this.selections.length;
28152 * Get the currently selected nodes.
28153 * @return {Array} An array of HTMLElements
28155 getSelectedNodes : function(){
28156 return this.selections;
28160 * Get the indexes of the selected nodes.
28163 getSelectedIndexes : function(){
28164 var indexes = [], s = this.selections;
28165 for(var i = 0, len = s.length; i < len; i++){
28166 indexes.push(s[i].nodeIndex);
28172 * Clear all selections
28173 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
28175 clearSelections : function(suppressEvent){
28176 if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
28177 this.cmp.elements = this.selections;
28178 this.cmp.removeClass(this.selectedClass);
28179 this.selections = [];
28180 if(!suppressEvent){
28181 this.fireEvent("selectionchange", this, this.selections);
28187 * Returns true if the passed node is selected
28188 * @param {HTMLElement/Number} node The node or node index
28189 * @return {Boolean}
28191 isSelected : function(node){
28192 var s = this.selections;
28196 node = this.getNode(node);
28197 return s.indexOf(node) !== -1;
28202 * @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
28203 * @param {Boolean} keepExisting (optional) true to keep existing selections
28204 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
28206 select : function(nodeInfo, keepExisting, suppressEvent){
28207 if(nodeInfo instanceof Array){
28209 this.clearSelections(true);
28211 for(var i = 0, len = nodeInfo.length; i < len; i++){
28212 this.select(nodeInfo[i], true, true);
28216 var node = this.getNode(nodeInfo);
28217 if(!node || this.isSelected(node)){
28218 return; // already selected.
28221 this.clearSelections(true);
28224 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
28225 Roo.fly(node).addClass(this.selectedClass);
28226 this.selections.push(node);
28227 if(!suppressEvent){
28228 this.fireEvent("selectionchange", this, this.selections);
28236 * @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
28237 * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
28238 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
28240 unselect : function(nodeInfo, keepExisting, suppressEvent)
28242 if(nodeInfo instanceof Array){
28243 Roo.each(this.selections, function(s) {
28244 this.unselect(s, nodeInfo);
28248 var node = this.getNode(nodeInfo);
28249 if(!node || !this.isSelected(node)){
28250 //Roo.log("not selected");
28251 return; // not selected.
28255 Roo.each(this.selections, function(s) {
28257 Roo.fly(node).removeClass(this.selectedClass);
28264 this.selections= ns;
28265 this.fireEvent("selectionchange", this, this.selections);
28269 * Gets a template node.
28270 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
28271 * @return {HTMLElement} The node or null if it wasn't found
28273 getNode : function(nodeInfo){
28274 if(typeof nodeInfo == "string"){
28275 return document.getElementById(nodeInfo);
28276 }else if(typeof nodeInfo == "number"){
28277 return this.nodes[nodeInfo];
28283 * Gets a range template nodes.
28284 * @param {Number} startIndex
28285 * @param {Number} endIndex
28286 * @return {Array} An array of nodes
28288 getNodes : function(start, end){
28289 var ns = this.nodes;
28290 start = start || 0;
28291 end = typeof end == "undefined" ? ns.length - 1 : end;
28294 for(var i = start; i <= end; i++){
28298 for(var i = start; i >= end; i--){
28306 * Finds the index of the passed node
28307 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
28308 * @return {Number} The index of the node or -1
28310 indexOf : function(node){
28311 node = this.getNode(node);
28312 if(typeof node.nodeIndex == "number"){
28313 return node.nodeIndex;
28315 var ns = this.nodes;
28316 for(var i = 0, len = ns.length; i < len; i++){
28326 * Ext JS Library 1.1.1
28327 * Copyright(c) 2006-2007, Ext JS, LLC.
28329 * Originally Released Under LGPL - original licence link has changed is not relivant.
28332 * <script type="text/javascript">
28336 * @class Roo.JsonView
28337 * @extends Roo.View
28338 * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
28340 var view = new Roo.JsonView({
28341 container: "my-element",
28342 tpl: '<div id="{id}">{foo} - {bar}</div>', // auto create template
28347 // listen for node click?
28348 view.on("click", function(vw, index, node, e){
28349 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
28352 // direct load of JSON data
28353 view.load("foobar.php");
28355 // Example from my blog list
28356 var tpl = new Roo.Template(
28357 '<div class="entry">' +
28358 '<a class="entry-title" href="{link}">{title}</a>' +
28359 "<h4>{date} by {author} | {comments} Comments</h4>{description}" +
28360 "</div><hr />"
28363 var moreView = new Roo.JsonView({
28364 container : "entry-list",
28368 moreView.on("beforerender", this.sortEntries, this);
28370 url: "/blog/get-posts.php",
28371 params: "allposts=true",
28372 text: "Loading Blog Entries..."
28376 * Note: old code is supported with arguments : (container, template, config)
28380 * Create a new JsonView
28382 * @param {Object} config The config object
28385 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
28388 Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
28390 var um = this.el.getUpdateManager();
28391 um.setRenderer(this);
28392 um.on("update", this.onLoad, this);
28393 um.on("failure", this.onLoadException, this);
28396 * @event beforerender
28397 * Fires before rendering of the downloaded JSON data.
28398 * @param {Roo.JsonView} this
28399 * @param {Object} data The JSON data loaded
28403 * Fires when data is loaded.
28404 * @param {Roo.JsonView} this
28405 * @param {Object} data The JSON data loaded
28406 * @param {Object} response The raw Connect response object
28409 * @event loadexception
28410 * Fires when loading fails.
28411 * @param {Roo.JsonView} this
28412 * @param {Object} response The raw Connect response object
28415 'beforerender' : true,
28417 'loadexception' : true
28420 Roo.extend(Roo.JsonView, Roo.View, {
28422 * @type {String} The root property in the loaded JSON object that contains the data
28427 * Refreshes the view.
28429 refresh : function(){
28430 this.clearSelections();
28431 this.el.update("");
28433 var o = this.jsonData;
28434 if(o && o.length > 0){
28435 for(var i = 0, len = o.length; i < len; i++){
28436 var data = this.prepareData(o[i], i, o);
28437 html[html.length] = this.tpl.apply(data);
28440 html.push(this.emptyText);
28442 this.el.update(html.join(""));
28443 this.nodes = this.el.dom.childNodes;
28444 this.updateIndexes(0);
28448 * 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.
28449 * @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:
28452 url: "your-url.php",
28453 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
28454 callback: yourFunction,
28455 scope: yourObject, //(optional scope)
28458 text: "Loading...",
28463 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
28464 * 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.
28465 * @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}
28466 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
28467 * @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.
28470 var um = this.el.getUpdateManager();
28471 um.update.apply(um, arguments);
28474 // note - render is a standard framework call...
28475 // using it for the response is really flaky... - it's called by UpdateManager normally, except when called by the XComponent/addXtype.
28476 render : function(el, response){
28478 this.clearSelections();
28479 this.el.update("");
28482 if (response != '') {
28483 o = Roo.util.JSON.decode(response.responseText);
28486 o = o[this.jsonRoot];
28492 * The current JSON data or null
28495 this.beforeRender();
28500 * Get the number of records in the current JSON dataset
28503 getCount : function(){
28504 return this.jsonData ? this.jsonData.length : 0;
28508 * Returns the JSON object for the specified node(s)
28509 * @param {HTMLElement/Array} node The node or an array of nodes
28510 * @return {Object/Array} If you pass in an array, you get an array back, otherwise
28511 * you get the JSON object for the node
28513 getNodeData : function(node){
28514 if(node instanceof Array){
28516 for(var i = 0, len = node.length; i < len; i++){
28517 data.push(this.getNodeData(node[i]));
28521 return this.jsonData[this.indexOf(node)] || null;
28524 beforeRender : function(){
28525 this.snapshot = this.jsonData;
28527 this.sort.apply(this, this.sortInfo);
28529 this.fireEvent("beforerender", this, this.jsonData);
28532 onLoad : function(el, o){
28533 this.fireEvent("load", this, this.jsonData, o);
28536 onLoadException : function(el, o){
28537 this.fireEvent("loadexception", this, o);
28541 * Filter the data by a specific property.
28542 * @param {String} property A property on your JSON objects
28543 * @param {String/RegExp} value Either string that the property values
28544 * should start with, or a RegExp to test against the property
28546 filter : function(property, value){
28549 var ss = this.snapshot;
28550 if(typeof value == "string"){
28551 var vlen = value.length;
28553 this.clearFilter();
28556 value = value.toLowerCase();
28557 for(var i = 0, len = ss.length; i < len; i++){
28559 if(o[property].substr(0, vlen).toLowerCase() == value){
28563 } else if(value.exec){ // regex?
28564 for(var i = 0, len = ss.length; i < len; i++){
28566 if(value.test(o[property])){
28573 this.jsonData = data;
28579 * Filter by a function. The passed function will be called with each
28580 * object in the current dataset. If the function returns true the value is kept,
28581 * otherwise it is filtered.
28582 * @param {Function} fn
28583 * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
28585 filterBy : function(fn, scope){
28588 var ss = this.snapshot;
28589 for(var i = 0, len = ss.length; i < len; i++){
28591 if(fn.call(scope || this, o)){
28595 this.jsonData = data;
28601 * Clears the current filter.
28603 clearFilter : function(){
28604 if(this.snapshot && this.jsonData != this.snapshot){
28605 this.jsonData = this.snapshot;
28612 * Sorts the data for this view and refreshes it.
28613 * @param {String} property A property on your JSON objects to sort on
28614 * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
28615 * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
28617 sort : function(property, dir, sortType){
28618 this.sortInfo = Array.prototype.slice.call(arguments, 0);
28621 var dsc = dir && dir.toLowerCase() == "desc";
28622 var f = function(o1, o2){
28623 var v1 = sortType ? sortType(o1[p]) : o1[p];
28624 var v2 = sortType ? sortType(o2[p]) : o2[p];
28627 return dsc ? +1 : -1;
28628 } else if(v1 > v2){
28629 return dsc ? -1 : +1;
28634 this.jsonData.sort(f);
28636 if(this.jsonData != this.snapshot){
28637 this.snapshot.sort(f);
28643 * Ext JS Library 1.1.1
28644 * Copyright(c) 2006-2007, Ext JS, LLC.
28646 * Originally Released Under LGPL - original licence link has changed is not relivant.
28649 * <script type="text/javascript">
28654 * @class Roo.ColorPalette
28655 * @extends Roo.Component
28656 * Simple color palette class for choosing colors. The palette can be rendered to any container.<br />
28657 * Here's an example of typical usage:
28659 var cp = new Roo.ColorPalette({value:'993300'}); // initial selected color
28660 cp.render('my-div');
28662 cp.on('select', function(palette, selColor){
28663 // do something with selColor
28667 * Create a new ColorPalette
28668 * @param {Object} config The config object
28670 Roo.ColorPalette = function(config){
28671 Roo.ColorPalette.superclass.constructor.call(this, config);
28675 * Fires when a color is selected
28676 * @param {ColorPalette} this
28677 * @param {String} color The 6-digit color hex code (without the # symbol)
28683 this.on("select", this.handler, this.scope, true);
28686 Roo.extend(Roo.ColorPalette, Roo.Component, {
28688 * @cfg {String} itemCls
28689 * The CSS class to apply to the containing element (defaults to "x-color-palette")
28691 itemCls : "x-color-palette",
28693 * @cfg {String} value
28694 * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol). Note that
28695 * the hex codes are case-sensitive.
28698 clickEvent:'click',
28700 ctype: "Roo.ColorPalette",
28703 * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
28705 allowReselect : false,
28708 * <p>An array of 6-digit color hex code strings (without the # symbol). This array can contain any number
28709 * of colors, and each hex code should be unique. The width of the palette is controlled via CSS by adjusting
28710 * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
28711 * of colors with the width setting until the box is symmetrical.</p>
28712 * <p>You can override individual colors if needed:</p>
28714 var cp = new Roo.ColorPalette();
28715 cp.colors[0] = "FF0000"; // change the first box to red
28718 Or you can provide a custom array of your own for complete control:
28720 var cp = new Roo.ColorPalette();
28721 cp.colors = ["000000", "993300", "333300"];
28726 "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
28727 "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
28728 "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
28729 "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
28730 "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
28734 onRender : function(container, position){
28735 var t = new Roo.MasterTemplate(
28736 '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on"> </span></em></a></tpl>'
28738 var c = this.colors;
28739 for(var i = 0, len = c.length; i < len; i++){
28742 var el = document.createElement("div");
28743 el.className = this.itemCls;
28745 container.dom.insertBefore(el, position);
28746 this.el = Roo.get(el);
28747 this.el.on(this.clickEvent, this.handleClick, this, {delegate: "a"});
28748 if(this.clickEvent != 'click'){
28749 this.el.on('click', Roo.emptyFn, this, {delegate: "a", preventDefault:true});
28754 afterRender : function(){
28755 Roo.ColorPalette.superclass.afterRender.call(this);
28757 var s = this.value;
28764 handleClick : function(e, t){
28765 e.preventDefault();
28766 if(!this.disabled){
28767 var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
28768 this.select(c.toUpperCase());
28773 * Selects the specified color in the palette (fires the select event)
28774 * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
28776 select : function(color){
28777 color = color.replace("#", "");
28778 if(color != this.value || this.allowReselect){
28781 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
28783 el.child("a.color-"+color).addClass("x-color-palette-sel");
28784 this.value = color;
28785 this.fireEvent("select", this, color);
28790 * Ext JS Library 1.1.1
28791 * Copyright(c) 2006-2007, Ext JS, LLC.
28793 * Originally Released Under LGPL - original licence link has changed is not relivant.
28796 * <script type="text/javascript">
28800 * @class Roo.DatePicker
28801 * @extends Roo.Component
28802 * Simple date picker class.
28804 * Create a new DatePicker
28805 * @param {Object} config The config object
28807 Roo.DatePicker = function(config){
28808 Roo.DatePicker.superclass.constructor.call(this, config);
28810 this.value = config && config.value ?
28811 config.value.clearTime() : new Date().clearTime();
28816 * Fires when a date is selected
28817 * @param {DatePicker} this
28818 * @param {Date} date The selected date
28822 * @event monthchange
28823 * Fires when the displayed month changes
28824 * @param {DatePicker} this
28825 * @param {Date} date The selected month
28827 'monthchange': true
28831 this.on("select", this.handler, this.scope || this);
28833 // build the disabledDatesRE
28834 if(!this.disabledDatesRE && this.disabledDates){
28835 var dd = this.disabledDates;
28837 for(var i = 0; i < dd.length; i++){
28839 if(i != dd.length-1) {
28843 this.disabledDatesRE = new RegExp(re + ")");
28847 Roo.extend(Roo.DatePicker, Roo.Component, {
28849 * @cfg {String} todayText
28850 * The text to display on the button that selects the current date (defaults to "Today")
28852 todayText : "Today",
28854 * @cfg {String} okText
28855 * The text to display on the ok button
28857 okText : " OK ", //   to give the user extra clicking room
28859 * @cfg {String} cancelText
28860 * The text to display on the cancel button
28862 cancelText : "Cancel",
28864 * @cfg {String} todayTip
28865 * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
28867 todayTip : "{0} (Spacebar)",
28869 * @cfg {Date} minDate
28870 * Minimum allowable date (JavaScript date object, defaults to null)
28874 * @cfg {Date} maxDate
28875 * Maximum allowable date (JavaScript date object, defaults to null)
28879 * @cfg {String} minText
28880 * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
28882 minText : "This date is before the minimum date",
28884 * @cfg {String} maxText
28885 * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
28887 maxText : "This date is after the maximum date",
28889 * @cfg {String} format
28890 * The default date format string which can be overriden for localization support. The format must be
28891 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
28895 * @cfg {Array} disabledDays
28896 * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
28898 disabledDays : null,
28900 * @cfg {String} disabledDaysText
28901 * The tooltip to display when the date falls on a disabled day (defaults to "")
28903 disabledDaysText : "",
28905 * @cfg {RegExp} disabledDatesRE
28906 * JavaScript regular expression used to disable a pattern of dates (defaults to null)
28908 disabledDatesRE : null,
28910 * @cfg {String} disabledDatesText
28911 * The tooltip text to display when the date falls on a disabled date (defaults to "")
28913 disabledDatesText : "",
28915 * @cfg {Boolean} constrainToViewport
28916 * True to constrain the date picker to the viewport (defaults to true)
28918 constrainToViewport : true,
28920 * @cfg {Array} monthNames
28921 * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
28923 monthNames : Date.monthNames,
28925 * @cfg {Array} dayNames
28926 * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
28928 dayNames : Date.dayNames,
28930 * @cfg {String} nextText
28931 * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
28933 nextText: 'Next Month (Control+Right)',
28935 * @cfg {String} prevText
28936 * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
28938 prevText: 'Previous Month (Control+Left)',
28940 * @cfg {String} monthYearText
28941 * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
28943 monthYearText: 'Choose a month (Control+Up/Down to move years)',
28945 * @cfg {Number} startDay
28946 * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
28950 * @cfg {Bool} showClear
28951 * Show a clear button (usefull for date form elements that can be blank.)
28957 * Sets the value of the date field
28958 * @param {Date} value The date to set
28960 setValue : function(value){
28961 var old = this.value;
28963 if (typeof(value) == 'string') {
28965 value = Date.parseDate(value, this.format);
28968 value = new Date();
28971 this.value = value.clearTime(true);
28973 this.update(this.value);
28978 * Gets the current selected value of the date field
28979 * @return {Date} The selected date
28981 getValue : function(){
28986 focus : function(){
28988 this.update(this.activeDate);
28993 onRender : function(container, position){
28996 '<table cellspacing="0">',
28997 '<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>',
28998 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
28999 var dn = this.dayNames;
29000 for(var i = 0; i < 7; i++){
29001 var d = this.startDay+i;
29005 m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
29007 m[m.length] = "</tr></thead><tbody><tr>";
29008 for(var i = 0; i < 42; i++) {
29009 if(i % 7 == 0 && i != 0){
29010 m[m.length] = "</tr><tr>";
29012 m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
29014 m[m.length] = '</tr></tbody></table></td></tr><tr>'+
29015 '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
29017 var el = document.createElement("div");
29018 el.className = "x-date-picker";
29019 el.innerHTML = m.join("");
29021 container.dom.insertBefore(el, position);
29023 this.el = Roo.get(el);
29024 this.eventEl = Roo.get(el.firstChild);
29026 new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
29027 handler: this.showPrevMonth,
29029 preventDefault:true,
29033 new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
29034 handler: this.showNextMonth,
29036 preventDefault:true,
29040 this.eventEl.on("mousewheel", this.handleMouseWheel, this);
29042 this.monthPicker = this.el.down('div.x-date-mp');
29043 this.monthPicker.enableDisplayMode('block');
29045 var kn = new Roo.KeyNav(this.eventEl, {
29046 "left" : function(e){
29048 this.showPrevMonth() :
29049 this.update(this.activeDate.add("d", -1));
29052 "right" : function(e){
29054 this.showNextMonth() :
29055 this.update(this.activeDate.add("d", 1));
29058 "up" : function(e){
29060 this.showNextYear() :
29061 this.update(this.activeDate.add("d", -7));
29064 "down" : function(e){
29066 this.showPrevYear() :
29067 this.update(this.activeDate.add("d", 7));
29070 "pageUp" : function(e){
29071 this.showNextMonth();
29074 "pageDown" : function(e){
29075 this.showPrevMonth();
29078 "enter" : function(e){
29079 e.stopPropagation();
29086 this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"});
29088 this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday, this);
29090 this.el.unselectable();
29092 this.cells = this.el.select("table.x-date-inner tbody td");
29093 this.textNodes = this.el.query("table.x-date-inner tbody span");
29095 this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
29097 tooltip: this.monthYearText
29100 this.mbtn.on('click', this.showMonthPicker, this);
29101 this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
29104 var today = (new Date()).dateFormat(this.format);
29106 var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
29107 if (this.showClear) {
29108 baseTb.add( new Roo.Toolbar.Fill());
29111 text: String.format(this.todayText, today),
29112 tooltip: String.format(this.todayTip, today),
29113 handler: this.selectToday,
29117 //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
29120 if (this.showClear) {
29122 baseTb.add( new Roo.Toolbar.Fill());
29125 cls: 'x-btn-icon x-btn-clear',
29126 handler: function() {
29128 this.fireEvent("select", this, '');
29138 this.update(this.value);
29141 createMonthPicker : function(){
29142 if(!this.monthPicker.dom.firstChild){
29143 var buf = ['<table border="0" cellspacing="0">'];
29144 for(var i = 0; i < 6; i++){
29146 '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
29147 '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
29149 '<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>' :
29150 '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
29154 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
29156 '</button><button type="button" class="x-date-mp-cancel">',
29158 '</button></td></tr>',
29161 this.monthPicker.update(buf.join(''));
29162 this.monthPicker.on('click', this.onMonthClick, this);
29163 this.monthPicker.on('dblclick', this.onMonthDblClick, this);
29165 this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
29166 this.mpYears = this.monthPicker.select('td.x-date-mp-year');
29168 this.mpMonths.each(function(m, a, i){
29171 m.dom.xmonth = 5 + Math.round(i * .5);
29173 m.dom.xmonth = Math.round((i-1) * .5);
29179 showMonthPicker : function(){
29180 this.createMonthPicker();
29181 var size = this.el.getSize();
29182 this.monthPicker.setSize(size);
29183 this.monthPicker.child('table').setSize(size);
29185 this.mpSelMonth = (this.activeDate || this.value).getMonth();
29186 this.updateMPMonth(this.mpSelMonth);
29187 this.mpSelYear = (this.activeDate || this.value).getFullYear();
29188 this.updateMPYear(this.mpSelYear);
29190 this.monthPicker.slideIn('t', {duration:.2});
29193 updateMPYear : function(y){
29195 var ys = this.mpYears.elements;
29196 for(var i = 1; i <= 10; i++){
29197 var td = ys[i-1], y2;
29199 y2 = y + Math.round(i * .5);
29200 td.firstChild.innerHTML = y2;
29203 y2 = y - (5-Math.round(i * .5));
29204 td.firstChild.innerHTML = y2;
29207 this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
29211 updateMPMonth : function(sm){
29212 this.mpMonths.each(function(m, a, i){
29213 m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
29217 selectMPMonth: function(m){
29221 onMonthClick : function(e, t){
29223 var el = new Roo.Element(t), pn;
29224 if(el.is('button.x-date-mp-cancel')){
29225 this.hideMonthPicker();
29227 else if(el.is('button.x-date-mp-ok')){
29228 this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
29229 this.hideMonthPicker();
29231 else if(pn = el.up('td.x-date-mp-month', 2)){
29232 this.mpMonths.removeClass('x-date-mp-sel');
29233 pn.addClass('x-date-mp-sel');
29234 this.mpSelMonth = pn.dom.xmonth;
29236 else if(pn = el.up('td.x-date-mp-year', 2)){
29237 this.mpYears.removeClass('x-date-mp-sel');
29238 pn.addClass('x-date-mp-sel');
29239 this.mpSelYear = pn.dom.xyear;
29241 else if(el.is('a.x-date-mp-prev')){
29242 this.updateMPYear(this.mpyear-10);
29244 else if(el.is('a.x-date-mp-next')){
29245 this.updateMPYear(this.mpyear+10);
29249 onMonthDblClick : function(e, t){
29251 var el = new Roo.Element(t), pn;
29252 if(pn = el.up('td.x-date-mp-month', 2)){
29253 this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
29254 this.hideMonthPicker();
29256 else if(pn = el.up('td.x-date-mp-year', 2)){
29257 this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
29258 this.hideMonthPicker();
29262 hideMonthPicker : function(disableAnim){
29263 if(this.monthPicker){
29264 if(disableAnim === true){
29265 this.monthPicker.hide();
29267 this.monthPicker.slideOut('t', {duration:.2});
29273 showPrevMonth : function(e){
29274 this.update(this.activeDate.add("mo", -1));
29278 showNextMonth : function(e){
29279 this.update(this.activeDate.add("mo", 1));
29283 showPrevYear : function(){
29284 this.update(this.activeDate.add("y", -1));
29288 showNextYear : function(){
29289 this.update(this.activeDate.add("y", 1));
29293 handleMouseWheel : function(e){
29294 var delta = e.getWheelDelta();
29296 this.showPrevMonth();
29298 } else if(delta < 0){
29299 this.showNextMonth();
29305 handleDateClick : function(e, t){
29307 if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
29308 this.setValue(new Date(t.dateValue));
29309 this.fireEvent("select", this, this.value);
29314 selectToday : function(){
29315 this.setValue(new Date().clearTime());
29316 this.fireEvent("select", this, this.value);
29320 update : function(date)
29322 var vd = this.activeDate;
29323 this.activeDate = date;
29325 var t = date.getTime();
29326 if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
29327 this.cells.removeClass("x-date-selected");
29328 this.cells.each(function(c){
29329 if(c.dom.firstChild.dateValue == t){
29330 c.addClass("x-date-selected");
29331 setTimeout(function(){
29332 try{c.dom.firstChild.focus();}catch(e){}
29341 var days = date.getDaysInMonth();
29342 var firstOfMonth = date.getFirstDateOfMonth();
29343 var startingPos = firstOfMonth.getDay()-this.startDay;
29345 if(startingPos <= this.startDay){
29349 var pm = date.add("mo", -1);
29350 var prevStart = pm.getDaysInMonth()-startingPos;
29352 var cells = this.cells.elements;
29353 var textEls = this.textNodes;
29354 days += startingPos;
29356 // convert everything to numbers so it's fast
29357 var day = 86400000;
29358 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
29359 var today = new Date().clearTime().getTime();
29360 var sel = date.clearTime().getTime();
29361 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
29362 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
29363 var ddMatch = this.disabledDatesRE;
29364 var ddText = this.disabledDatesText;
29365 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
29366 var ddaysText = this.disabledDaysText;
29367 var format = this.format;
29369 var setCellClass = function(cal, cell){
29371 var t = d.getTime();
29372 cell.firstChild.dateValue = t;
29374 cell.className += " x-date-today";
29375 cell.title = cal.todayText;
29378 cell.className += " x-date-selected";
29379 setTimeout(function(){
29380 try{cell.firstChild.focus();}catch(e){}
29385 cell.className = " x-date-disabled";
29386 cell.title = cal.minText;
29390 cell.className = " x-date-disabled";
29391 cell.title = cal.maxText;
29395 if(ddays.indexOf(d.getDay()) != -1){
29396 cell.title = ddaysText;
29397 cell.className = " x-date-disabled";
29400 if(ddMatch && format){
29401 var fvalue = d.dateFormat(format);
29402 if(ddMatch.test(fvalue)){
29403 cell.title = ddText.replace("%0", fvalue);
29404 cell.className = " x-date-disabled";
29410 for(; i < startingPos; i++) {
29411 textEls[i].innerHTML = (++prevStart);
29412 d.setDate(d.getDate()+1);
29413 cells[i].className = "x-date-prevday";
29414 setCellClass(this, cells[i]);
29416 for(; i < days; i++){
29417 intDay = i - startingPos + 1;
29418 textEls[i].innerHTML = (intDay);
29419 d.setDate(d.getDate()+1);
29420 cells[i].className = "x-date-active";
29421 setCellClass(this, cells[i]);
29424 for(; i < 42; i++) {
29425 textEls[i].innerHTML = (++extraDays);
29426 d.setDate(d.getDate()+1);
29427 cells[i].className = "x-date-nextday";
29428 setCellClass(this, cells[i]);
29431 this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
29432 this.fireEvent('monthchange', this, date);
29434 if(!this.internalRender){
29435 var main = this.el.dom.firstChild;
29436 var w = main.offsetWidth;
29437 this.el.setWidth(w + this.el.getBorderWidth("lr"));
29438 Roo.fly(main).setWidth(w);
29439 this.internalRender = true;
29440 // opera does not respect the auto grow header center column
29441 // then, after it gets a width opera refuses to recalculate
29442 // without a second pass
29443 if(Roo.isOpera && !this.secondPass){
29444 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
29445 this.secondPass = true;
29446 this.update.defer(10, this, [date]);
29454 * Ext JS Library 1.1.1
29455 * Copyright(c) 2006-2007, Ext JS, LLC.
29457 * Originally Released Under LGPL - original licence link has changed is not relivant.
29460 * <script type="text/javascript">
29463 * @class Roo.TabPanel
29464 * @extends Roo.util.Observable
29465 * A lightweight tab container.
29469 // basic tabs 1, built from existing content
29470 var tabs = new Roo.TabPanel("tabs1");
29471 tabs.addTab("script", "View Script");
29472 tabs.addTab("markup", "View Markup");
29473 tabs.activate("script");
29475 // more advanced tabs, built from javascript
29476 var jtabs = new Roo.TabPanel("jtabs");
29477 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
29479 // set up the UpdateManager
29480 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
29481 var updater = tab2.getUpdateManager();
29482 updater.setDefaultUrl("ajax1.htm");
29483 tab2.on('activate', updater.refresh, updater, true);
29485 // Use setUrl for Ajax loading
29486 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
29487 tab3.setUrl("ajax2.htm", null, true);
29490 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
29493 jtabs.activate("jtabs-1");
29496 * Create a new TabPanel.
29497 * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
29498 * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
29500 Roo.TabPanel = function(container, config){
29502 * The container element for this TabPanel.
29503 * @type Roo.Element
29505 this.el = Roo.get(container, true);
29507 if(typeof config == "boolean"){
29508 this.tabPosition = config ? "bottom" : "top";
29510 Roo.apply(this, config);
29513 if(this.tabPosition == "bottom"){
29514 this.bodyEl = Roo.get(this.createBody(this.el.dom));
29515 this.el.addClass("x-tabs-bottom");
29517 this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
29518 this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
29519 this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
29521 Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
29523 if(this.tabPosition != "bottom"){
29524 /** The body element that contains {@link Roo.TabPanelItem} bodies. +
29525 * @type Roo.Element
29527 this.bodyEl = Roo.get(this.createBody(this.el.dom));
29528 this.el.addClass("x-tabs-top");
29532 this.bodyEl.setStyle("position", "relative");
29534 this.active = null;
29535 this.activateDelegate = this.activate.createDelegate(this);
29540 * Fires when the active tab changes
29541 * @param {Roo.TabPanel} this
29542 * @param {Roo.TabPanelItem} activePanel The new active tab
29546 * @event beforetabchange
29547 * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
29548 * @param {Roo.TabPanel} this
29549 * @param {Object} e Set cancel to true on this object to cancel the tab change
29550 * @param {Roo.TabPanelItem} tab The tab being changed to
29552 "beforetabchange" : true
29555 Roo.EventManager.onWindowResize(this.onResize, this);
29556 this.cpad = this.el.getPadding("lr");
29557 this.hiddenCount = 0;
29560 // toolbar on the tabbar support...
29561 if (this.toolbar) {
29562 var tcfg = this.toolbar;
29563 tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');
29564 this.toolbar = new Roo.Toolbar(tcfg);
29565 if (Roo.isSafari) {
29566 var tbl = tcfg.container.child('table', true);
29567 tbl.setAttribute('width', '100%');
29574 Roo.TabPanel.superclass.constructor.call(this);
29577 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
29579 *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
29581 tabPosition : "top",
29583 *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
29585 currentTabWidth : 0,
29587 *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
29591 *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
29595 *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
29597 preferredTabWidth : 175,
29599 *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
29601 resizeTabs : false,
29603 *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
29605 monitorResize : true,
29607 *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar.
29612 * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
29613 * @param {String} id The id of the div to use <b>or create</b>
29614 * @param {String} text The text for the tab
29615 * @param {String} content (optional) Content to put in the TabPanelItem body
29616 * @param {Boolean} closable (optional) True to create a close icon on the tab
29617 * @return {Roo.TabPanelItem} The created TabPanelItem
29619 addTab : function(id, text, content, closable){
29620 var item = new Roo.TabPanelItem(this, id, text, closable);
29621 this.addTabItem(item);
29623 item.setContent(content);
29629 * Returns the {@link Roo.TabPanelItem} with the specified id/index
29630 * @param {String/Number} id The id or index of the TabPanelItem to fetch.
29631 * @return {Roo.TabPanelItem}
29633 getTab : function(id){
29634 return this.items[id];
29638 * Hides the {@link Roo.TabPanelItem} with the specified id/index
29639 * @param {String/Number} id The id or index of the TabPanelItem to hide.
29641 hideTab : function(id){
29642 var t = this.items[id];
29645 this.hiddenCount++;
29646 this.autoSizeTabs();
29651 * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
29652 * @param {String/Number} id The id or index of the TabPanelItem to unhide.
29654 unhideTab : function(id){
29655 var t = this.items[id];
29657 t.setHidden(false);
29658 this.hiddenCount--;
29659 this.autoSizeTabs();
29664 * Adds an existing {@link Roo.TabPanelItem}.
29665 * @param {Roo.TabPanelItem} item The TabPanelItem to add
29667 addTabItem : function(item){
29668 this.items[item.id] = item;
29669 this.items.push(item);
29670 if(this.resizeTabs){
29671 item.setWidth(this.currentTabWidth || this.preferredTabWidth);
29672 this.autoSizeTabs();
29679 * Removes a {@link Roo.TabPanelItem}.
29680 * @param {String/Number} id The id or index of the TabPanelItem to remove.
29682 removeTab : function(id){
29683 var items = this.items;
29684 var tab = items[id];
29685 if(!tab) { return; }
29686 var index = items.indexOf(tab);
29687 if(this.active == tab && items.length > 1){
29688 var newTab = this.getNextAvailable(index);
29693 this.stripEl.dom.removeChild(tab.pnode.dom);
29694 if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
29695 this.bodyEl.dom.removeChild(tab.bodyEl.dom);
29697 items.splice(index, 1);
29698 delete this.items[tab.id];
29699 tab.fireEvent("close", tab);
29700 tab.purgeListeners();
29701 this.autoSizeTabs();
29704 getNextAvailable : function(start){
29705 var items = this.items;
29707 // look for a next tab that will slide over to
29708 // replace the one being removed
29709 while(index < items.length){
29710 var item = items[++index];
29711 if(item && !item.isHidden()){
29715 // if one isn't found select the previous tab (on the left)
29718 var item = items[--index];
29719 if(item && !item.isHidden()){
29727 * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
29728 * @param {String/Number} id The id or index of the TabPanelItem to disable.
29730 disableTab : function(id){
29731 var tab = this.items[id];
29732 if(tab && this.active != tab){
29738 * Enables a {@link Roo.TabPanelItem} that is disabled.
29739 * @param {String/Number} id The id or index of the TabPanelItem to enable.
29741 enableTab : function(id){
29742 var tab = this.items[id];
29747 * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
29748 * @param {String/Number} id The id or index of the TabPanelItem to activate.
29749 * @return {Roo.TabPanelItem} The TabPanelItem.
29751 activate : function(id){
29752 var tab = this.items[id];
29756 if(tab == this.active || tab.disabled){
29760 this.fireEvent("beforetabchange", this, e, tab);
29761 if(e.cancel !== true && !tab.disabled){
29763 this.active.hide();
29765 this.active = this.items[id];
29766 this.active.show();
29767 this.fireEvent("tabchange", this, this.active);
29773 * Gets the active {@link Roo.TabPanelItem}.
29774 * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
29776 getActiveTab : function(){
29777 return this.active;
29781 * Updates the tab body element to fit the height of the container element
29782 * for overflow scrolling
29783 * @param {Number} targetHeight (optional) Override the starting height from the elements height
29785 syncHeight : function(targetHeight){
29786 var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
29787 var bm = this.bodyEl.getMargins();
29788 var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
29789 this.bodyEl.setHeight(newHeight);
29793 onResize : function(){
29794 if(this.monitorResize){
29795 this.autoSizeTabs();
29800 * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
29802 beginUpdate : function(){
29803 this.updating = true;
29807 * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
29809 endUpdate : function(){
29810 this.updating = false;
29811 this.autoSizeTabs();
29815 * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
29817 autoSizeTabs : function(){
29818 var count = this.items.length;
29819 var vcount = count - this.hiddenCount;
29820 if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
29823 var w = Math.max(this.el.getWidth() - this.cpad, 10);
29824 var availWidth = Math.floor(w / vcount);
29825 var b = this.stripBody;
29826 if(b.getWidth() > w){
29827 var tabs = this.items;
29828 this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
29829 if(availWidth < this.minTabWidth){
29830 /*if(!this.sleft){ // incomplete scrolling code
29831 this.createScrollButtons();
29834 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
29837 if(this.currentTabWidth < this.preferredTabWidth){
29838 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
29844 * Returns the number of tabs in this TabPanel.
29847 getCount : function(){
29848 return this.items.length;
29852 * Resizes all the tabs to the passed width
29853 * @param {Number} The new width
29855 setTabWidth : function(width){
29856 this.currentTabWidth = width;
29857 for(var i = 0, len = this.items.length; i < len; i++) {
29858 if(!this.items[i].isHidden()) {
29859 this.items[i].setWidth(width);
29865 * Destroys this TabPanel
29866 * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
29868 destroy : function(removeEl){
29869 Roo.EventManager.removeResizeListener(this.onResize, this);
29870 for(var i = 0, len = this.items.length; i < len; i++){
29871 this.items[i].purgeListeners();
29873 if(removeEl === true){
29874 this.el.update("");
29881 * @class Roo.TabPanelItem
29882 * @extends Roo.util.Observable
29883 * Represents an individual item (tab plus body) in a TabPanel.
29884 * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
29885 * @param {String} id The id of this TabPanelItem
29886 * @param {String} text The text for the tab of this TabPanelItem
29887 * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
29889 Roo.TabPanelItem = function(tabPanel, id, text, closable){
29891 * The {@link Roo.TabPanel} this TabPanelItem belongs to
29892 * @type Roo.TabPanel
29894 this.tabPanel = tabPanel;
29896 * The id for this TabPanelItem
29901 this.disabled = false;
29905 this.loaded = false;
29906 this.closable = closable;
29909 * The body element for this TabPanelItem.
29910 * @type Roo.Element
29912 this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
29913 this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
29914 this.bodyEl.setStyle("display", "block");
29915 this.bodyEl.setStyle("zoom", "1");
29918 var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
29920 this.el = Roo.get(els.el, true);
29921 this.inner = Roo.get(els.inner, true);
29922 this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
29923 this.pnode = Roo.get(els.el.parentNode, true);
29924 this.el.on("mousedown", this.onTabMouseDown, this);
29925 this.el.on("click", this.onTabClick, this);
29928 var c = Roo.get(els.close, true);
29929 c.dom.title = this.closeText;
29930 c.addClassOnOver("close-over");
29931 c.on("click", this.closeClick, this);
29937 * Fires when this tab becomes the active tab.
29938 * @param {Roo.TabPanel} tabPanel The parent TabPanel
29939 * @param {Roo.TabPanelItem} this
29943 * @event beforeclose
29944 * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
29945 * @param {Roo.TabPanelItem} this
29946 * @param {Object} e Set cancel to true on this object to cancel the close.
29948 "beforeclose": true,
29951 * Fires when this tab is closed.
29952 * @param {Roo.TabPanelItem} this
29956 * @event deactivate
29957 * Fires when this tab is no longer the active tab.
29958 * @param {Roo.TabPanel} tabPanel The parent TabPanel
29959 * @param {Roo.TabPanelItem} this
29961 "deactivate" : true
29963 this.hidden = false;
29965 Roo.TabPanelItem.superclass.constructor.call(this);
29968 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
29969 purgeListeners : function(){
29970 Roo.util.Observable.prototype.purgeListeners.call(this);
29971 this.el.removeAllListeners();
29974 * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
29977 this.pnode.addClass("on");
29980 this.tabPanel.stripWrap.repaint();
29982 this.fireEvent("activate", this.tabPanel, this);
29986 * Returns true if this tab is the active tab.
29987 * @return {Boolean}
29989 isActive : function(){
29990 return this.tabPanel.getActiveTab() == this;
29994 * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
29997 this.pnode.removeClass("on");
29999 this.fireEvent("deactivate", this.tabPanel, this);
30002 hideAction : function(){
30003 this.bodyEl.hide();
30004 this.bodyEl.setStyle("position", "absolute");
30005 this.bodyEl.setLeft("-20000px");
30006 this.bodyEl.setTop("-20000px");
30009 showAction : function(){
30010 this.bodyEl.setStyle("position", "relative");
30011 this.bodyEl.setTop("");
30012 this.bodyEl.setLeft("");
30013 this.bodyEl.show();
30017 * Set the tooltip for the tab.
30018 * @param {String} tooltip The tab's tooltip
30020 setTooltip : function(text){
30021 if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
30022 this.textEl.dom.qtip = text;
30023 this.textEl.dom.removeAttribute('title');
30025 this.textEl.dom.title = text;
30029 onTabClick : function(e){
30030 e.preventDefault();
30031 this.tabPanel.activate(this.id);
30034 onTabMouseDown : function(e){
30035 e.preventDefault();
30036 this.tabPanel.activate(this.id);
30039 getWidth : function(){
30040 return this.inner.getWidth();
30043 setWidth : function(width){
30044 var iwidth = width - this.pnode.getPadding("lr");
30045 this.inner.setWidth(iwidth);
30046 this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
30047 this.pnode.setWidth(width);
30051 * Show or hide the tab
30052 * @param {Boolean} hidden True to hide or false to show.
30054 setHidden : function(hidden){
30055 this.hidden = hidden;
30056 this.pnode.setStyle("display", hidden ? "none" : "");
30060 * Returns true if this tab is "hidden"
30061 * @return {Boolean}
30063 isHidden : function(){
30064 return this.hidden;
30068 * Returns the text for this tab
30071 getText : function(){
30075 autoSize : function(){
30076 //this.el.beginMeasure();
30077 this.textEl.setWidth(1);
30079 * #2804 [new] Tabs in Roojs
30080 * increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
30082 this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
30083 //this.el.endMeasure();
30087 * Sets the text for the tab (Note: this also sets the tooltip text)
30088 * @param {String} text The tab's text and tooltip
30090 setText : function(text){
30092 this.textEl.update(text);
30093 this.setTooltip(text);
30094 if(!this.tabPanel.resizeTabs){
30099 * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
30101 activate : function(){
30102 this.tabPanel.activate(this.id);
30106 * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
30108 disable : function(){
30109 if(this.tabPanel.active != this){
30110 this.disabled = true;
30111 this.pnode.addClass("disabled");
30116 * Enables this TabPanelItem if it was previously disabled.
30118 enable : function(){
30119 this.disabled = false;
30120 this.pnode.removeClass("disabled");
30124 * Sets the content for this TabPanelItem.
30125 * @param {String} content The content
30126 * @param {Boolean} loadScripts true to look for and load scripts
30128 setContent : function(content, loadScripts){
30129 this.bodyEl.update(content, loadScripts);
30133 * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
30134 * @return {Roo.UpdateManager} The UpdateManager
30136 getUpdateManager : function(){
30137 return this.bodyEl.getUpdateManager();
30141 * Set a URL to be used to load the content for this TabPanelItem.
30142 * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
30143 * @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)
30144 * @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)
30145 * @return {Roo.UpdateManager} The UpdateManager
30147 setUrl : function(url, params, loadOnce){
30148 if(this.refreshDelegate){
30149 this.un('activate', this.refreshDelegate);
30151 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
30152 this.on("activate", this.refreshDelegate);
30153 return this.bodyEl.getUpdateManager();
30157 _handleRefresh : function(url, params, loadOnce){
30158 if(!loadOnce || !this.loaded){
30159 var updater = this.bodyEl.getUpdateManager();
30160 updater.update(url, params, this._setLoaded.createDelegate(this));
30165 * Forces a content refresh from the URL specified in the {@link #setUrl} method.
30166 * Will fail silently if the setUrl method has not been called.
30167 * This does not activate the panel, just updates its content.
30169 refresh : function(){
30170 if(this.refreshDelegate){
30171 this.loaded = false;
30172 this.refreshDelegate();
30177 _setLoaded : function(){
30178 this.loaded = true;
30182 closeClick : function(e){
30185 this.fireEvent("beforeclose", this, o);
30186 if(o.cancel !== true){
30187 this.tabPanel.removeTab(this.id);
30191 * The text displayed in the tooltip for the close icon.
30194 closeText : "Close this tab"
30198 Roo.TabPanel.prototype.createStrip = function(container){
30199 var strip = document.createElement("div");
30200 strip.className = "x-tabs-wrap";
30201 container.appendChild(strip);
30205 Roo.TabPanel.prototype.createStripList = function(strip){
30206 // div wrapper for retard IE
30207 // returns the "tr" element.
30208 strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
30209 '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
30210 '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
30211 return strip.firstChild.firstChild.firstChild.firstChild;
30214 Roo.TabPanel.prototype.createBody = function(container){
30215 var body = document.createElement("div");
30216 Roo.id(body, "tab-body");
30217 Roo.fly(body).addClass("x-tabs-body");
30218 container.appendChild(body);
30222 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
30223 var body = Roo.getDom(id);
30225 body = document.createElement("div");
30228 Roo.fly(body).addClass("x-tabs-item-body");
30229 bodyEl.insertBefore(body, bodyEl.firstChild);
30233 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
30234 var td = document.createElement("td");
30235 stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
30236 //stripEl.appendChild(td);
30238 td.className = "x-tabs-closable";
30239 if(!this.closeTpl){
30240 this.closeTpl = new Roo.Template(
30241 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
30242 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
30243 '<div unselectable="on" class="close-icon"> </div></em></span></a>'
30246 var el = this.closeTpl.overwrite(td, {"text": text});
30247 var close = el.getElementsByTagName("div")[0];
30248 var inner = el.getElementsByTagName("em")[0];
30249 return {"el": el, "close": close, "inner": inner};
30252 this.tabTpl = new Roo.Template(
30253 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
30254 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
30257 var el = this.tabTpl.overwrite(td, {"text": text});
30258 var inner = el.getElementsByTagName("em")[0];
30259 return {"el": el, "inner": inner};
30263 * Ext JS Library 1.1.1
30264 * Copyright(c) 2006-2007, Ext JS, LLC.
30266 * Originally Released Under LGPL - original licence link has changed is not relivant.
30269 * <script type="text/javascript">
30273 * @class Roo.Button
30274 * @extends Roo.util.Observable
30275 * Simple Button class
30276 * @cfg {String} text The button text
30277 * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
30278 * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
30279 * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
30280 * @cfg {Object} scope The scope of the handler
30281 * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
30282 * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
30283 * @cfg {Boolean} hidden True to start hidden (defaults to false)
30284 * @cfg {Boolean} disabled True to start disabled (defaults to false)
30285 * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
30286 * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
30287 applies if enableToggle = true)
30288 * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
30289 * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
30290 an {@link Roo.util.ClickRepeater} config object (defaults to false).
30292 * Create a new button
30293 * @param {Object} config The config object
30295 Roo.Button = function(renderTo, config)
30299 renderTo = config.renderTo || false;
30302 Roo.apply(this, config);
30306 * Fires when this button is clicked
30307 * @param {Button} this
30308 * @param {EventObject} e The click event
30313 * Fires when the "pressed" state of this button changes (only if enableToggle = true)
30314 * @param {Button} this
30315 * @param {Boolean} pressed
30320 * Fires when the mouse hovers over the button
30321 * @param {Button} this
30322 * @param {Event} e The event object
30324 'mouseover' : true,
30327 * Fires when the mouse exits the button
30328 * @param {Button} this
30329 * @param {Event} e The event object
30334 * Fires when the button is rendered
30335 * @param {Button} this
30340 this.menu = Roo.menu.MenuMgr.get(this.menu);
30342 // register listeners first!! - so render can be captured..
30343 Roo.util.Observable.call(this);
30345 this.render(renderTo);
30351 Roo.extend(Roo.Button, Roo.util.Observable, {
30357 * Read-only. True if this button is hidden
30362 * Read-only. True if this button is disabled
30367 * Read-only. True if this button is pressed (only if enableToggle = true)
30373 * @cfg {Number} tabIndex
30374 * The DOM tabIndex for this button (defaults to undefined)
30376 tabIndex : undefined,
30379 * @cfg {Boolean} enableToggle
30380 * True to enable pressed/not pressed toggling (defaults to false)
30382 enableToggle: false,
30384 * @cfg {Roo.menu.Menu} menu
30385 * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
30389 * @cfg {String} menuAlign
30390 * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
30392 menuAlign : "tl-bl?",
30395 * @cfg {String} iconCls
30396 * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
30398 iconCls : undefined,
30400 * @cfg {String} type
30401 * The button's type, corresponding to the DOM input element type attribute. Either "submit," "reset" or "button" (default).
30406 menuClassTarget: 'tr',
30409 * @cfg {String} clickEvent
30410 * The type of event to map to the button's event handler (defaults to 'click')
30412 clickEvent : 'click',
30415 * @cfg {Boolean} handleMouseEvents
30416 * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
30418 handleMouseEvents : true,
30421 * @cfg {String} tooltipType
30422 * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
30424 tooltipType : 'qtip',
30427 * @cfg {String} cls
30428 * A CSS class to apply to the button's main element.
30432 * @cfg {Roo.Template} template (Optional)
30433 * An {@link Roo.Template} with which to create the Button's main element. This Template must
30434 * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
30435 * require code modifications if required elements (e.g. a button) aren't present.
30439 render : function(renderTo){
30441 if(this.hideParent){
30442 this.parentEl = Roo.get(renderTo);
30444 if(!this.dhconfig){
30445 if(!this.template){
30446 if(!Roo.Button.buttonTemplate){
30447 // hideous table template
30448 Roo.Button.buttonTemplate = new Roo.Template(
30449 '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
30450 '<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>',
30451 "</tr></tbody></table>");
30453 this.template = Roo.Button.buttonTemplate;
30455 btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
30456 var btnEl = btn.child("button:first");
30457 btnEl.on('focus', this.onFocus, this);
30458 btnEl.on('blur', this.onBlur, this);
30460 btn.addClass(this.cls);
30463 btnEl.setStyle('background-image', 'url(' +this.icon +')');
30466 btnEl.addClass(this.iconCls);
30468 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
30471 if(this.tabIndex !== undefined){
30472 btnEl.dom.tabIndex = this.tabIndex;
30475 if(typeof this.tooltip == 'object'){
30476 Roo.QuickTips.tips(Roo.apply({
30480 btnEl.dom[this.tooltipType] = this.tooltip;
30484 btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
30488 this.el.dom.id = this.el.id = this.id;
30491 this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
30492 this.menu.on("show", this.onMenuShow, this);
30493 this.menu.on("hide", this.onMenuHide, this);
30495 btn.addClass("x-btn");
30496 if(Roo.isIE && !Roo.isIE7){
30497 this.autoWidth.defer(1, this);
30501 if(this.handleMouseEvents){
30502 btn.on("mouseover", this.onMouseOver, this);
30503 btn.on("mouseout", this.onMouseOut, this);
30504 btn.on("mousedown", this.onMouseDown, this);
30506 btn.on(this.clickEvent, this.onClick, this);
30507 //btn.on("mouseup", this.onMouseUp, this);
30514 Roo.ButtonToggleMgr.register(this);
30516 this.el.addClass("x-btn-pressed");
30519 var repeater = new Roo.util.ClickRepeater(btn,
30520 typeof this.repeat == "object" ? this.repeat : {}
30522 repeater.on("click", this.onClick, this);
30525 this.fireEvent('render', this);
30529 * Returns the button's underlying element
30530 * @return {Roo.Element} The element
30532 getEl : function(){
30537 * Destroys this Button and removes any listeners.
30539 destroy : function(){
30540 Roo.ButtonToggleMgr.unregister(this);
30541 this.el.removeAllListeners();
30542 this.purgeListeners();
30547 autoWidth : function(){
30549 this.el.setWidth("auto");
30550 if(Roo.isIE7 && Roo.isStrict){
30551 var ib = this.el.child('button');
30552 if(ib && ib.getWidth() > 20){
30554 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
30559 this.el.beginMeasure();
30561 if(this.el.getWidth() < this.minWidth){
30562 this.el.setWidth(this.minWidth);
30565 this.el.endMeasure();
30572 * Assigns this button's click handler
30573 * @param {Function} handler The function to call when the button is clicked
30574 * @param {Object} scope (optional) Scope for the function passed in
30576 setHandler : function(handler, scope){
30577 this.handler = handler;
30578 this.scope = scope;
30582 * Sets this button's text
30583 * @param {String} text The button text
30585 setText : function(text){
30588 this.el.child("td.x-btn-center button.x-btn-text").update(text);
30594 * Gets the text for this button
30595 * @return {String} The button text
30597 getText : function(){
30605 this.hidden = false;
30607 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
30615 this.hidden = true;
30617 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
30622 * Convenience function for boolean show/hide
30623 * @param {Boolean} visible True to show, false to hide
30625 setVisible: function(visible){
30634 * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
30635 * @param {Boolean} state (optional) Force a particular state
30637 toggle : function(state){
30638 state = state === undefined ? !this.pressed : state;
30639 if(state != this.pressed){
30641 this.el.addClass("x-btn-pressed");
30642 this.pressed = true;
30643 this.fireEvent("toggle", this, true);
30645 this.el.removeClass("x-btn-pressed");
30646 this.pressed = false;
30647 this.fireEvent("toggle", this, false);
30649 if(this.toggleHandler){
30650 this.toggleHandler.call(this.scope || this, this, state);
30658 focus : function(){
30659 this.el.child('button:first').focus();
30663 * Disable this button
30665 disable : function(){
30667 this.el.addClass("x-btn-disabled");
30669 this.disabled = true;
30673 * Enable this button
30675 enable : function(){
30677 this.el.removeClass("x-btn-disabled");
30679 this.disabled = false;
30683 * Convenience function for boolean enable/disable
30684 * @param {Boolean} enabled True to enable, false to disable
30686 setDisabled : function(v){
30687 this[v !== true ? "enable" : "disable"]();
30691 onClick : function(e)
30694 e.preventDefault();
30699 if(!this.disabled){
30700 if(this.enableToggle){
30703 if(this.menu && !this.menu.isVisible()){
30704 this.menu.show(this.el, this.menuAlign);
30706 this.fireEvent("click", this, e);
30708 this.el.removeClass("x-btn-over");
30709 this.handler.call(this.scope || this, this, e);
30714 onMouseOver : function(e){
30715 if(!this.disabled){
30716 this.el.addClass("x-btn-over");
30717 this.fireEvent('mouseover', this, e);
30721 onMouseOut : function(e){
30722 if(!e.within(this.el, true)){
30723 this.el.removeClass("x-btn-over");
30724 this.fireEvent('mouseout', this, e);
30728 onFocus : function(e){
30729 if(!this.disabled){
30730 this.el.addClass("x-btn-focus");
30734 onBlur : function(e){
30735 this.el.removeClass("x-btn-focus");
30738 onMouseDown : function(e){
30739 if(!this.disabled && e.button == 0){
30740 this.el.addClass("x-btn-click");
30741 Roo.get(document).on('mouseup', this.onMouseUp, this);
30745 onMouseUp : function(e){
30747 this.el.removeClass("x-btn-click");
30748 Roo.get(document).un('mouseup', this.onMouseUp, this);
30752 onMenuShow : function(e){
30753 this.el.addClass("x-btn-menu-active");
30756 onMenuHide : function(e){
30757 this.el.removeClass("x-btn-menu-active");
30761 // Private utility class used by Button
30762 Roo.ButtonToggleMgr = function(){
30765 function toggleGroup(btn, state){
30767 var g = groups[btn.toggleGroup];
30768 for(var i = 0, l = g.length; i < l; i++){
30770 g[i].toggle(false);
30777 register : function(btn){
30778 if(!btn.toggleGroup){
30781 var g = groups[btn.toggleGroup];
30783 g = groups[btn.toggleGroup] = [];
30786 btn.on("toggle", toggleGroup);
30789 unregister : function(btn){
30790 if(!btn.toggleGroup){
30793 var g = groups[btn.toggleGroup];
30796 btn.un("toggle", toggleGroup);
30802 * Ext JS Library 1.1.1
30803 * Copyright(c) 2006-2007, Ext JS, LLC.
30805 * Originally Released Under LGPL - original licence link has changed is not relivant.
30808 * <script type="text/javascript">
30812 * @class Roo.SplitButton
30813 * @extends Roo.Button
30814 * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
30815 * click event of the button. Typically this would be used to display a dropdown menu that provides additional
30816 * options to the primary button action, but any custom handler can provide the arrowclick implementation.
30817 * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
30818 * @cfg {String} arrowTooltip The title attribute of the arrow
30820 * Create a new menu button
30821 * @param {String/HTMLElement/Element} renderTo The element to append the button to
30822 * @param {Object} config The config object
30824 Roo.SplitButton = function(renderTo, config){
30825 Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
30827 * @event arrowclick
30828 * Fires when this button's arrow is clicked
30829 * @param {SplitButton} this
30830 * @param {EventObject} e The click event
30832 this.addEvents({"arrowclick":true});
30835 Roo.extend(Roo.SplitButton, Roo.Button, {
30836 render : function(renderTo){
30837 // this is one sweet looking template!
30838 var tpl = new Roo.Template(
30839 '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
30840 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
30841 '<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>',
30842 "</tbody></table></td><td>",
30843 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
30844 '<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>',
30845 "</tbody></table></td></tr></table>"
30847 var btn = tpl.append(renderTo, [this.text, this.type], true);
30848 var btnEl = btn.child("button");
30850 btn.addClass(this.cls);
30853 btnEl.setStyle('background-image', 'url(' +this.icon +')');
30856 btnEl.addClass(this.iconCls);
30858 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
30862 if(this.handleMouseEvents){
30863 btn.on("mouseover", this.onMouseOver, this);
30864 btn.on("mouseout", this.onMouseOut, this);
30865 btn.on("mousedown", this.onMouseDown, this);
30866 btn.on("mouseup", this.onMouseUp, this);
30868 btn.on(this.clickEvent, this.onClick, this);
30870 if(typeof this.tooltip == 'object'){
30871 Roo.QuickTips.tips(Roo.apply({
30875 btnEl.dom[this.tooltipType] = this.tooltip;
30878 if(this.arrowTooltip){
30879 btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
30888 this.el.addClass("x-btn-pressed");
30890 if(Roo.isIE && !Roo.isIE7){
30891 this.autoWidth.defer(1, this);
30896 this.menu.on("show", this.onMenuShow, this);
30897 this.menu.on("hide", this.onMenuHide, this);
30899 this.fireEvent('render', this);
30903 autoWidth : function(){
30905 var tbl = this.el.child("table:first");
30906 var tbl2 = this.el.child("table:last");
30907 this.el.setWidth("auto");
30908 tbl.setWidth("auto");
30909 if(Roo.isIE7 && Roo.isStrict){
30910 var ib = this.el.child('button:first');
30911 if(ib && ib.getWidth() > 20){
30913 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
30918 this.el.beginMeasure();
30920 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
30921 tbl.setWidth(this.minWidth-tbl2.getWidth());
30924 this.el.endMeasure();
30927 this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
30931 * Sets this button's click handler
30932 * @param {Function} handler The function to call when the button is clicked
30933 * @param {Object} scope (optional) Scope for the function passed above
30935 setHandler : function(handler, scope){
30936 this.handler = handler;
30937 this.scope = scope;
30941 * Sets this button's arrow click handler
30942 * @param {Function} handler The function to call when the arrow is clicked
30943 * @param {Object} scope (optional) Scope for the function passed above
30945 setArrowHandler : function(handler, scope){
30946 this.arrowHandler = handler;
30947 this.scope = scope;
30953 focus : function(){
30955 this.el.child("button:first").focus();
30960 onClick : function(e){
30961 e.preventDefault();
30962 if(!this.disabled){
30963 if(e.getTarget(".x-btn-menu-arrow-wrap")){
30964 if(this.menu && !this.menu.isVisible()){
30965 this.menu.show(this.el, this.menuAlign);
30967 this.fireEvent("arrowclick", this, e);
30968 if(this.arrowHandler){
30969 this.arrowHandler.call(this.scope || this, this, e);
30972 this.fireEvent("click", this, e);
30974 this.handler.call(this.scope || this, this, e);
30980 onMouseDown : function(e){
30981 if(!this.disabled){
30982 Roo.fly(e.getTarget("table")).addClass("x-btn-click");
30986 onMouseUp : function(e){
30987 Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
30992 // backwards compat
30993 Roo.MenuButton = Roo.SplitButton;/*
30995 * Ext JS Library 1.1.1
30996 * Copyright(c) 2006-2007, Ext JS, LLC.
30998 * Originally Released Under LGPL - original licence link has changed is not relivant.
31001 * <script type="text/javascript">
31005 * @class Roo.Toolbar
31006 * @children Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
31007 * Basic Toolbar class.
31009 * Creates a new Toolbar
31010 * @param {Object} container The config object
31012 Roo.Toolbar = function(container, buttons, config)
31014 /// old consturctor format still supported..
31015 if(container instanceof Array){ // omit the container for later rendering
31016 buttons = container;
31020 if (typeof(container) == 'object' && container.xtype) {
31021 config = container;
31022 container = config.container;
31023 buttons = config.buttons || []; // not really - use items!!
31026 if (config && config.items) {
31027 xitems = config.items;
31028 delete config.items;
31030 Roo.apply(this, config);
31031 this.buttons = buttons;
31034 this.render(container);
31036 this.xitems = xitems;
31037 Roo.each(xitems, function(b) {
31043 Roo.Toolbar.prototype = {
31045 * @cfg {Array} items
31046 * array of button configs or elements to add (will be converted to a MixedCollection)
31050 * @cfg {String/HTMLElement/Element} container
31051 * The id or element that will contain the toolbar
31054 render : function(ct){
31055 this.el = Roo.get(ct);
31057 this.el.addClass(this.cls);
31059 // using a table allows for vertical alignment
31060 // 100% width is needed by Safari...
31061 this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
31062 this.tr = this.el.child("tr", true);
31064 this.items = new Roo.util.MixedCollection(false, function(o){
31065 return o.id || ("item" + (++autoId));
31068 this.add.apply(this, this.buttons);
31069 delete this.buttons;
31074 * Adds element(s) to the toolbar -- this function takes a variable number of
31075 * arguments of mixed type and adds them to the toolbar.
31076 * @param {Mixed} arg1 The following types of arguments are all valid:<br />
31078 * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
31079 * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
31080 * <li>Field: Any form field (equivalent to {@link #addField})</li>
31081 * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
31082 * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
31083 * Note that there are a few special strings that are treated differently as explained nRoo.</li>
31084 * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
31085 * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
31086 * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
31088 * @param {Mixed} arg2
31089 * @param {Mixed} etc.
31092 var a = arguments, l = a.length;
31093 for(var i = 0; i < l; i++){
31098 _add : function(el) {
31101 el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
31104 if (el.applyTo){ // some kind of form field
31105 return this.addField(el);
31107 if (el.render){ // some kind of Toolbar.Item
31108 return this.addItem(el);
31110 if (typeof el == "string"){ // string
31111 if(el == "separator" || el == "-"){
31112 return this.addSeparator();
31115 return this.addSpacer();
31118 return this.addFill();
31120 return this.addText(el);
31123 if(el.tagName){ // element
31124 return this.addElement(el);
31126 if(typeof el == "object"){ // must be button config?
31127 return this.addButton(el);
31129 // and now what?!?!
31135 * Add an Xtype element
31136 * @param {Object} xtype Xtype Object
31137 * @return {Object} created Object
31139 addxtype : function(e){
31140 return this.add(e);
31144 * Returns the Element for this toolbar.
31145 * @return {Roo.Element}
31147 getEl : function(){
31153 * @return {Roo.Toolbar.Item} The separator item
31155 addSeparator : function(){
31156 return this.addItem(new Roo.Toolbar.Separator());
31160 * Adds a spacer element
31161 * @return {Roo.Toolbar.Spacer} The spacer item
31163 addSpacer : function(){
31164 return this.addItem(new Roo.Toolbar.Spacer());
31168 * Adds a fill element that forces subsequent additions to the right side of the toolbar
31169 * @return {Roo.Toolbar.Fill} The fill item
31171 addFill : function(){
31172 return this.addItem(new Roo.Toolbar.Fill());
31176 * Adds any standard HTML element to the toolbar
31177 * @param {String/HTMLElement/Element} el The element or id of the element to add
31178 * @return {Roo.Toolbar.Item} The element's item
31180 addElement : function(el){
31181 return this.addItem(new Roo.Toolbar.Item(el));
31184 * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
31185 * @type Roo.util.MixedCollection
31190 * Adds any Toolbar.Item or subclass
31191 * @param {Roo.Toolbar.Item} item
31192 * @return {Roo.Toolbar.Item} The item
31194 addItem : function(item){
31195 var td = this.nextBlock();
31197 this.items.add(item);
31202 * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
31203 * @param {Object/Array} config A button config or array of configs
31204 * @return {Roo.Toolbar.Button/Array}
31206 addButton : function(config){
31207 if(config instanceof Array){
31209 for(var i = 0, len = config.length; i < len; i++) {
31210 buttons.push(this.addButton(config[i]));
31215 if(!(config instanceof Roo.Toolbar.Button)){
31217 new Roo.Toolbar.SplitButton(config) :
31218 new Roo.Toolbar.Button(config);
31220 var td = this.nextBlock();
31227 * Adds text to the toolbar
31228 * @param {String} text The text to add
31229 * @return {Roo.Toolbar.Item} The element's item
31231 addText : function(text){
31232 return this.addItem(new Roo.Toolbar.TextItem(text));
31236 * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
31237 * @param {Number} index The index where the item is to be inserted
31238 * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
31239 * @return {Roo.Toolbar.Button/Item}
31241 insertButton : function(index, item){
31242 if(item instanceof Array){
31244 for(var i = 0, len = item.length; i < len; i++) {
31245 buttons.push(this.insertButton(index + i, item[i]));
31249 if (!(item instanceof Roo.Toolbar.Button)){
31250 item = new Roo.Toolbar.Button(item);
31252 var td = document.createElement("td");
31253 this.tr.insertBefore(td, this.tr.childNodes[index]);
31255 this.items.insert(index, item);
31260 * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
31261 * @param {Object} config
31262 * @return {Roo.Toolbar.Item} The element's item
31264 addDom : function(config, returnEl){
31265 var td = this.nextBlock();
31266 Roo.DomHelper.overwrite(td, config);
31267 var ti = new Roo.Toolbar.Item(td.firstChild);
31269 this.items.add(ti);
31274 * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
31275 * @type Roo.util.MixedCollection
31280 * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
31281 * Note: the field should not have been rendered yet. For a field that has already been
31282 * rendered, use {@link #addElement}.
31283 * @param {Roo.form.Field} field
31284 * @return {Roo.ToolbarItem}
31288 addField : function(field) {
31289 if (!this.fields) {
31291 this.fields = new Roo.util.MixedCollection(false, function(o){
31292 return o.id || ("item" + (++autoId));
31297 var td = this.nextBlock();
31299 var ti = new Roo.Toolbar.Item(td.firstChild);
31301 this.items.add(ti);
31302 this.fields.add(field);
31313 this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
31314 this.el.child('div').hide();
31322 this.el.child('div').show();
31326 nextBlock : function(){
31327 var td = document.createElement("td");
31328 this.tr.appendChild(td);
31333 destroy : function(){
31334 if(this.items){ // rendered?
31335 Roo.destroy.apply(Roo, this.items.items);
31337 if(this.fields){ // rendered?
31338 Roo.destroy.apply(Roo, this.fields.items);
31340 Roo.Element.uncache(this.el, this.tr);
31345 * @class Roo.Toolbar.Item
31346 * The base class that other classes should extend in order to get some basic common toolbar item functionality.
31348 * Creates a new Item
31349 * @param {HTMLElement} el
31351 Roo.Toolbar.Item = function(el){
31353 if (typeof (el.xtype) != 'undefined') {
31358 this.el = Roo.getDom(el);
31359 this.id = Roo.id(this.el);
31360 this.hidden = false;
31365 * Fires when the button is rendered
31366 * @param {Button} this
31370 Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
31372 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
31373 //Roo.Toolbar.Item.prototype = {
31376 * Get this item's HTML Element
31377 * @return {HTMLElement}
31379 getEl : function(){
31384 render : function(td){
31387 td.appendChild(this.el);
31389 this.fireEvent('render', this);
31393 * Removes and destroys this item.
31395 destroy : function(){
31396 this.td.parentNode.removeChild(this.td);
31403 this.hidden = false;
31404 this.td.style.display = "";
31411 this.hidden = true;
31412 this.td.style.display = "none";
31416 * Convenience function for boolean show/hide.
31417 * @param {Boolean} visible true to show/false to hide
31419 setVisible: function(visible){
31428 * Try to focus this item.
31430 focus : function(){
31431 Roo.fly(this.el).focus();
31435 * Disables this item.
31437 disable : function(){
31438 Roo.fly(this.td).addClass("x-item-disabled");
31439 this.disabled = true;
31440 this.el.disabled = true;
31444 * Enables this item.
31446 enable : function(){
31447 Roo.fly(this.td).removeClass("x-item-disabled");
31448 this.disabled = false;
31449 this.el.disabled = false;
31455 * @class Roo.Toolbar.Separator
31456 * @extends Roo.Toolbar.Item
31457 * A simple toolbar separator class
31459 * Creates a new Separator
31461 Roo.Toolbar.Separator = function(cfg){
31463 var s = document.createElement("span");
31464 s.className = "ytb-sep";
31469 Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
31471 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
31472 enable:Roo.emptyFn,
31473 disable:Roo.emptyFn,
31478 * @class Roo.Toolbar.Spacer
31479 * @extends Roo.Toolbar.Item
31480 * A simple element that adds extra horizontal space to a toolbar.
31482 * Creates a new Spacer
31484 Roo.Toolbar.Spacer = function(cfg){
31485 var s = document.createElement("div");
31486 s.className = "ytb-spacer";
31490 Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
31492 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
31493 enable:Roo.emptyFn,
31494 disable:Roo.emptyFn,
31499 * @class Roo.Toolbar.Fill
31500 * @extends Roo.Toolbar.Spacer
31501 * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
31503 * Creates a new Spacer
31505 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
31507 render : function(td){
31508 td.style.width = '100%';
31509 Roo.Toolbar.Fill.superclass.render.call(this, td);
31514 * @class Roo.Toolbar.TextItem
31515 * @extends Roo.Toolbar.Item
31516 * A simple class that renders text directly into a toolbar.
31518 * Creates a new TextItem
31519 * @cfg {string} text
31521 Roo.Toolbar.TextItem = function(cfg){
31522 var text = cfg || "";
31523 if (typeof(cfg) == 'object') {
31524 text = cfg.text || "";
31528 var s = document.createElement("span");
31529 s.className = "ytb-text";
31530 s.innerHTML = text;
31535 Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg || s);
31537 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
31540 enable:Roo.emptyFn,
31541 disable:Roo.emptyFn,
31544 * Shows this button
31547 this.hidden = false;
31548 this.el.style.display = "";
31552 * Hides this button
31555 this.hidden = true;
31556 this.el.style.display = "none";
31562 * @class Roo.Toolbar.Button
31563 * @extends Roo.Button
31564 * A button that renders into a toolbar.
31566 * Creates a new Button
31567 * @param {Object} config A standard {@link Roo.Button} config object
31569 Roo.Toolbar.Button = function(config){
31570 Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
31572 Roo.extend(Roo.Toolbar.Button, Roo.Button,
31576 render : function(td){
31578 Roo.Toolbar.Button.superclass.render.call(this, td);
31582 * Removes and destroys this button
31584 destroy : function(){
31585 Roo.Toolbar.Button.superclass.destroy.call(this);
31586 this.td.parentNode.removeChild(this.td);
31590 * Shows this button
31593 this.hidden = false;
31594 this.td.style.display = "";
31598 * Hides this button
31601 this.hidden = true;
31602 this.td.style.display = "none";
31606 * Disables this item
31608 disable : function(){
31609 Roo.fly(this.td).addClass("x-item-disabled");
31610 this.disabled = true;
31614 * Enables this item
31616 enable : function(){
31617 Roo.fly(this.td).removeClass("x-item-disabled");
31618 this.disabled = false;
31621 // backwards compat
31622 Roo.ToolbarButton = Roo.Toolbar.Button;
31625 * @class Roo.Toolbar.SplitButton
31626 * @extends Roo.SplitButton
31627 * A menu button that renders into a toolbar.
31629 * Creates a new SplitButton
31630 * @param {Object} config A standard {@link Roo.SplitButton} config object
31632 Roo.Toolbar.SplitButton = function(config){
31633 Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
31635 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
31636 render : function(td){
31638 Roo.Toolbar.SplitButton.superclass.render.call(this, td);
31642 * Removes and destroys this button
31644 destroy : function(){
31645 Roo.Toolbar.SplitButton.superclass.destroy.call(this);
31646 this.td.parentNode.removeChild(this.td);
31650 * Shows this button
31653 this.hidden = false;
31654 this.td.style.display = "";
31658 * Hides this button
31661 this.hidden = true;
31662 this.td.style.display = "none";
31666 // backwards compat
31667 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
31669 * Ext JS Library 1.1.1
31670 * Copyright(c) 2006-2007, Ext JS, LLC.
31672 * Originally Released Under LGPL - original licence link has changed is not relivant.
31675 * <script type="text/javascript">
31679 * @class Roo.PagingToolbar
31680 * @extends Roo.Toolbar
31681 * @children Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
31682 * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
31684 * Create a new PagingToolbar
31685 * @param {Object} config The config object
31687 Roo.PagingToolbar = function(el, ds, config)
31689 // old args format still supported... - xtype is prefered..
31690 if (typeof(el) == 'object' && el.xtype) {
31691 // created from xtype...
31693 ds = el.dataSource;
31694 el = config.container;
31697 if (config.items) {
31698 items = config.items;
31702 Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
31705 this.renderButtons(this.el);
31708 // supprot items array.
31710 Roo.each(items, function(e) {
31711 this.add(Roo.factory(e));
31716 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
31719 * @cfg {String/HTMLElement/Element} container
31720 * container The id or element that will contain the toolbar
31723 * @cfg {Boolean} displayInfo
31724 * True to display the displayMsg (defaults to false)
31729 * @cfg {Number} pageSize
31730 * The number of records to display per page (defaults to 20)
31734 * @cfg {String} displayMsg
31735 * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
31737 displayMsg : 'Displaying {0} - {1} of {2}',
31739 * @cfg {String} emptyMsg
31740 * The message to display when no records are found (defaults to "No data to display")
31742 emptyMsg : 'No data to display',
31744 * Customizable piece of the default paging text (defaults to "Page")
31747 beforePageText : "Page",
31749 * Customizable piece of the default paging text (defaults to "of %0")
31752 afterPageText : "of {0}",
31754 * Customizable piece of the default paging text (defaults to "First Page")
31757 firstText : "First Page",
31759 * Customizable piece of the default paging text (defaults to "Previous Page")
31762 prevText : "Previous Page",
31764 * Customizable piece of the default paging text (defaults to "Next Page")
31767 nextText : "Next Page",
31769 * Customizable piece of the default paging text (defaults to "Last Page")
31772 lastText : "Last Page",
31774 * Customizable piece of the default paging text (defaults to "Refresh")
31777 refreshText : "Refresh",
31780 renderButtons : function(el){
31781 Roo.PagingToolbar.superclass.render.call(this, el);
31782 this.first = this.addButton({
31783 tooltip: this.firstText,
31784 cls: "x-btn-icon x-grid-page-first",
31786 handler: this.onClick.createDelegate(this, ["first"])
31788 this.prev = this.addButton({
31789 tooltip: this.prevText,
31790 cls: "x-btn-icon x-grid-page-prev",
31792 handler: this.onClick.createDelegate(this, ["prev"])
31794 //this.addSeparator();
31795 this.add(this.beforePageText);
31796 this.field = Roo.get(this.addDom({
31801 cls: "x-grid-page-number"
31803 this.field.on("keydown", this.onPagingKeydown, this);
31804 this.field.on("focus", function(){this.dom.select();});
31805 this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
31806 this.field.setHeight(18);
31807 //this.addSeparator();
31808 this.next = this.addButton({
31809 tooltip: this.nextText,
31810 cls: "x-btn-icon x-grid-page-next",
31812 handler: this.onClick.createDelegate(this, ["next"])
31814 this.last = this.addButton({
31815 tooltip: this.lastText,
31816 cls: "x-btn-icon x-grid-page-last",
31818 handler: this.onClick.createDelegate(this, ["last"])
31820 //this.addSeparator();
31821 this.loading = this.addButton({
31822 tooltip: this.refreshText,
31823 cls: "x-btn-icon x-grid-loading",
31824 handler: this.onClick.createDelegate(this, ["refresh"])
31827 if(this.displayInfo){
31828 this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
31833 updateInfo : function(){
31834 if(this.displayEl){
31835 var count = this.ds.getCount();
31836 var msg = count == 0 ?
31840 this.cursor+1, this.cursor+count, this.ds.getTotalCount()
31842 this.displayEl.update(msg);
31847 onLoad : function(ds, r, o){
31848 this.cursor = o.params ? o.params.start : 0;
31849 var d = this.getPageData(), ap = d.activePage, ps = d.pages;
31851 this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
31852 this.field.dom.value = ap;
31853 this.first.setDisabled(ap == 1);
31854 this.prev.setDisabled(ap == 1);
31855 this.next.setDisabled(ap == ps);
31856 this.last.setDisabled(ap == ps);
31857 this.loading.enable();
31862 getPageData : function(){
31863 var total = this.ds.getTotalCount();
31866 activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
31867 pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
31872 onLoadError : function(){
31873 this.loading.enable();
31877 onPagingKeydown : function(e){
31878 var k = e.getKey();
31879 var d = this.getPageData();
31881 var v = this.field.dom.value, pageNum;
31882 if(!v || isNaN(pageNum = parseInt(v, 10))){
31883 this.field.dom.value = d.activePage;
31886 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
31887 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
31890 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))
31892 var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
31893 this.field.dom.value = pageNum;
31894 this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
31897 else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
31899 var v = this.field.dom.value, pageNum;
31900 var increment = (e.shiftKey) ? 10 : 1;
31901 if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
31904 if(!v || isNaN(pageNum = parseInt(v, 10))) {
31905 this.field.dom.value = d.activePage;
31908 else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
31910 this.field.dom.value = parseInt(v, 10) + increment;
31911 pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
31912 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
31919 beforeLoad : function(){
31921 this.loading.disable();
31926 onClick : function(which){
31930 ds.load({params:{start: 0, limit: this.pageSize}});
31933 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
31936 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
31939 var total = ds.getTotalCount();
31940 var extra = total % this.pageSize;
31941 var lastStart = extra ? (total - extra) : total-this.pageSize;
31942 ds.load({params:{start: lastStart, limit: this.pageSize}});
31945 ds.load({params:{start: this.cursor, limit: this.pageSize}});
31951 * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
31952 * @param {Roo.data.Store} store The data store to unbind
31954 unbind : function(ds){
31955 ds.un("beforeload", this.beforeLoad, this);
31956 ds.un("load", this.onLoad, this);
31957 ds.un("loadexception", this.onLoadError, this);
31958 ds.un("remove", this.updateInfo, this);
31959 ds.un("add", this.updateInfo, this);
31960 this.ds = undefined;
31964 * Binds the paging toolbar to the specified {@link Roo.data.Store}
31965 * @param {Roo.data.Store} store The data store to bind
31967 bind : function(ds){
31968 ds.on("beforeload", this.beforeLoad, this);
31969 ds.on("load", this.onLoad, this);
31970 ds.on("loadexception", this.onLoadError, this);
31971 ds.on("remove", this.updateInfo, this);
31972 ds.on("add", this.updateInfo, this);
31977 * Ext JS Library 1.1.1
31978 * Copyright(c) 2006-2007, Ext JS, LLC.
31980 * Originally Released Under LGPL - original licence link has changed is not relivant.
31983 * <script type="text/javascript">
31987 * @class Roo.Resizable
31988 * @extends Roo.util.Observable
31989 * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
31990 * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
31991 * 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
31992 * the element will be wrapped for you automatically.</p>
31993 * <p>Here is the list of valid resize handles:</p>
31996 ------ -------------------
32005 'hd' horizontal drag
32008 * <p>Here's an example showing the creation of a typical Resizable:</p>
32010 var resizer = new Roo.Resizable("element-id", {
32018 resizer.on("resize", myHandler);
32020 * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
32021 * resizer.east.setDisplayed(false);</p>
32022 * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
32023 * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
32024 * resize operation's new size (defaults to [0, 0])
32025 * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
32026 * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
32027 * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
32028 * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
32029 * @cfg {Boolean} enabled False to disable resizing (defaults to true)
32030 * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
32031 * @cfg {Number} width The width of the element in pixels (defaults to null)
32032 * @cfg {Number} height The height of the element in pixels (defaults to null)
32033 * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
32034 * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
32035 * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
32036 * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
32037 * @cfg {Boolean} multiDirectional <b>Deprecated</b>. The old style of adding multi-direction resize handles, deprecated
32038 * in favor of the handles config option (defaults to false)
32039 * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
32040 * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
32041 * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
32042 * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
32043 * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
32044 * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
32045 * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
32046 * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
32047 * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
32048 * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
32049 * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
32051 * Create a new resizable component
32052 * @param {String/HTMLElement/Roo.Element} el The id or element to resize
32053 * @param {Object} config configuration options
32055 Roo.Resizable = function(el, config)
32057 this.el = Roo.get(el);
32059 if(config && config.wrap){
32060 config.resizeChild = this.el;
32061 this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
32062 this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
32063 this.el.setStyle("overflow", "hidden");
32064 this.el.setPositioning(config.resizeChild.getPositioning());
32065 config.resizeChild.clearPositioning();
32066 if(!config.width || !config.height){
32067 var csize = config.resizeChild.getSize();
32068 this.el.setSize(csize.width, csize.height);
32070 if(config.pinned && !config.adjustments){
32071 config.adjustments = "auto";
32075 this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
32076 this.proxy.unselectable();
32077 this.proxy.enableDisplayMode('block');
32079 Roo.apply(this, config);
32082 this.disableTrackOver = true;
32083 this.el.addClass("x-resizable-pinned");
32085 // if the element isn't positioned, make it relative
32086 var position = this.el.getStyle("position");
32087 if(position != "absolute" && position != "fixed"){
32088 this.el.setStyle("position", "relative");
32090 if(!this.handles){ // no handles passed, must be legacy style
32091 this.handles = 's,e,se';
32092 if(this.multiDirectional){
32093 this.handles += ',n,w';
32096 if(this.handles == "all"){
32097 this.handles = "n s e w ne nw se sw";
32099 var hs = this.handles.split(/\s*?[,;]\s*?| /);
32100 var ps = Roo.Resizable.positions;
32101 for(var i = 0, len = hs.length; i < len; i++){
32102 if(hs[i] && ps[hs[i]]){
32103 var pos = ps[hs[i]];
32104 this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
32108 this.corner = this.southeast;
32110 // updateBox = the box can move..
32111 if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
32112 this.updateBox = true;
32115 this.activeHandle = null;
32117 if(this.resizeChild){
32118 if(typeof this.resizeChild == "boolean"){
32119 this.resizeChild = Roo.get(this.el.dom.firstChild, true);
32121 this.resizeChild = Roo.get(this.resizeChild, true);
32125 if(this.adjustments == "auto"){
32126 var rc = this.resizeChild;
32127 var hw = this.west, he = this.east, hn = this.north, hs = this.south;
32128 if(rc && (hw || hn)){
32129 rc.position("relative");
32130 rc.setLeft(hw ? hw.el.getWidth() : 0);
32131 rc.setTop(hn ? hn.el.getHeight() : 0);
32133 this.adjustments = [
32134 (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
32135 (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
32139 if(this.draggable){
32140 this.dd = this.dynamic ?
32141 this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
32142 this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
32148 * @event beforeresize
32149 * Fired before resize is allowed. Set enabled to false to cancel resize.
32150 * @param {Roo.Resizable} this
32151 * @param {Roo.EventObject} e The mousedown event
32153 "beforeresize" : true,
32156 * Fired a resizing.
32157 * @param {Roo.Resizable} this
32158 * @param {Number} x The new x position
32159 * @param {Number} y The new y position
32160 * @param {Number} w The new w width
32161 * @param {Number} h The new h hight
32162 * @param {Roo.EventObject} e The mouseup event
32167 * Fired after a resize.
32168 * @param {Roo.Resizable} this
32169 * @param {Number} width The new width
32170 * @param {Number} height The new height
32171 * @param {Roo.EventObject} e The mouseup event
32176 if(this.width !== null && this.height !== null){
32177 this.resizeTo(this.width, this.height);
32179 this.updateChildSize();
32182 this.el.dom.style.zoom = 1;
32184 Roo.Resizable.superclass.constructor.call(this);
32187 Roo.extend(Roo.Resizable, Roo.util.Observable, {
32188 resizeChild : false,
32189 adjustments : [0, 0],
32199 multiDirectional : false,
32200 disableTrackOver : false,
32201 easing : 'easeOutStrong',
32202 widthIncrement : 0,
32203 heightIncrement : 0,
32207 preserveRatio : false,
32208 transparent: false,
32214 * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
32216 constrainTo: undefined,
32218 * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
32220 resizeRegion: undefined,
32224 * Perform a manual resize
32225 * @param {Number} width
32226 * @param {Number} height
32228 resizeTo : function(width, height){
32229 this.el.setSize(width, height);
32230 this.updateChildSize();
32231 this.fireEvent("resize", this, width, height, null);
32235 startSizing : function(e, handle){
32236 this.fireEvent("beforeresize", this, e);
32237 if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
32240 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: " "});
32241 this.overlay.unselectable();
32242 this.overlay.enableDisplayMode("block");
32243 this.overlay.on("mousemove", this.onMouseMove, this);
32244 this.overlay.on("mouseup", this.onMouseUp, this);
32246 this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
32248 this.resizing = true;
32249 this.startBox = this.el.getBox();
32250 this.startPoint = e.getXY();
32251 this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
32252 (this.startBox.y + this.startBox.height) - this.startPoint[1]];
32254 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
32255 this.overlay.show();
32257 if(this.constrainTo) {
32258 var ct = Roo.get(this.constrainTo);
32259 this.resizeRegion = ct.getRegion().adjust(
32260 ct.getFrameWidth('t'),
32261 ct.getFrameWidth('l'),
32262 -ct.getFrameWidth('b'),
32263 -ct.getFrameWidth('r')
32267 this.proxy.setStyle('visibility', 'hidden'); // workaround display none
32269 this.proxy.setBox(this.startBox);
32271 this.proxy.setStyle('visibility', 'visible');
32277 onMouseDown : function(handle, e){
32280 this.activeHandle = handle;
32281 this.startSizing(e, handle);
32286 onMouseUp : function(e){
32287 var size = this.resizeElement();
32288 this.resizing = false;
32290 this.overlay.hide();
32292 this.fireEvent("resize", this, size.width, size.height, e);
32296 updateChildSize : function(){
32298 if(this.resizeChild){
32300 var child = this.resizeChild;
32301 var adj = this.adjustments;
32302 if(el.dom.offsetWidth){
32303 var b = el.getSize(true);
32304 child.setSize(b.width+adj[0], b.height+adj[1]);
32306 // Second call here for IE
32307 // The first call enables instant resizing and
32308 // the second call corrects scroll bars if they
32311 setTimeout(function(){
32312 if(el.dom.offsetWidth){
32313 var b = el.getSize(true);
32314 child.setSize(b.width+adj[0], b.height+adj[1]);
32322 snap : function(value, inc, min){
32323 if(!inc || !value) {
32326 var newValue = value;
32327 var m = value % inc;
32330 newValue = value + (inc-m);
32332 newValue = value - m;
32335 return Math.max(min, newValue);
32339 resizeElement : function(){
32340 var box = this.proxy.getBox();
32341 if(this.updateBox){
32342 this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
32344 this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
32346 this.updateChildSize();
32354 constrain : function(v, diff, m, mx){
32357 }else if(v - diff > mx){
32364 onMouseMove : function(e){
32367 try{// try catch so if something goes wrong the user doesn't get hung
32369 if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
32373 //var curXY = this.startPoint;
32374 var curSize = this.curSize || this.startBox;
32375 var x = this.startBox.x, y = this.startBox.y;
32376 var ox = x, oy = y;
32377 var w = curSize.width, h = curSize.height;
32378 var ow = w, oh = h;
32379 var mw = this.minWidth, mh = this.minHeight;
32380 var mxw = this.maxWidth, mxh = this.maxHeight;
32381 var wi = this.widthIncrement;
32382 var hi = this.heightIncrement;
32384 var eventXY = e.getXY();
32385 var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
32386 var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
32388 var pos = this.activeHandle.position;
32393 w = Math.min(Math.max(mw, w), mxw);
32398 h = Math.min(Math.max(mh, h), mxh);
32403 w = Math.min(Math.max(mw, w), mxw);
32404 h = Math.min(Math.max(mh, h), mxh);
32407 diffY = this.constrain(h, diffY, mh, mxh);
32414 var adiffX = Math.abs(diffX);
32415 var sub = (adiffX % wi); // how much
32416 if (sub > (wi/2)) { // far enough to snap
32417 diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
32419 // remove difference..
32420 diffX = (diffX > 0) ? diffX-sub : diffX+sub;
32424 x = Math.max(this.minX, x);
32427 diffX = this.constrain(w, diffX, mw, mxw);
32433 w = Math.min(Math.max(mw, w), mxw);
32434 diffY = this.constrain(h, diffY, mh, mxh);
32439 diffX = this.constrain(w, diffX, mw, mxw);
32440 diffY = this.constrain(h, diffY, mh, mxh);
32447 diffX = this.constrain(w, diffX, mw, mxw);
32449 h = Math.min(Math.max(mh, h), mxh);
32455 var sw = this.snap(w, wi, mw);
32456 var sh = this.snap(h, hi, mh);
32457 if(sw != w || sh != h){
32480 if(this.preserveRatio){
32485 h = Math.min(Math.max(mh, h), mxh);
32490 w = Math.min(Math.max(mw, w), mxw);
32495 w = Math.min(Math.max(mw, w), mxw);
32501 w = Math.min(Math.max(mw, w), mxw);
32507 h = Math.min(Math.max(mh, h), mxh);
32515 h = Math.min(Math.max(mh, h), mxh);
32525 h = Math.min(Math.max(mh, h), mxh);
32533 if (pos == 'hdrag') {
32536 this.proxy.setBounds(x, y, w, h);
32538 this.resizeElement();
32542 this.fireEvent("resizing", this, x, y, w, h, e);
32546 handleOver : function(){
32548 this.el.addClass("x-resizable-over");
32553 handleOut : function(){
32554 if(!this.resizing){
32555 this.el.removeClass("x-resizable-over");
32560 * Returns the element this component is bound to.
32561 * @return {Roo.Element}
32563 getEl : function(){
32568 * Returns the resizeChild element (or null).
32569 * @return {Roo.Element}
32571 getResizeChild : function(){
32572 return this.resizeChild;
32574 groupHandler : function()
32579 * Destroys this resizable. If the element was wrapped and
32580 * removeEl is not true then the element remains.
32581 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
32583 destroy : function(removeEl){
32584 this.proxy.remove();
32586 this.overlay.removeAllListeners();
32587 this.overlay.remove();
32589 var ps = Roo.Resizable.positions;
32591 if(typeof ps[k] != "function" && this[ps[k]]){
32592 var h = this[ps[k]];
32593 h.el.removeAllListeners();
32598 this.el.update("");
32605 // hash to map config positions to true positions
32606 Roo.Resizable.positions = {
32607 n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast",
32612 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
32614 // only initialize the template if resizable is used
32615 var tpl = Roo.DomHelper.createTemplate(
32616 {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
32619 Roo.Resizable.Handle.prototype.tpl = tpl;
32621 this.position = pos;
32623 // show north drag fro topdra
32624 var handlepos = pos == 'hdrag' ? 'north' : pos;
32626 this.el = this.tpl.append(rz.el.dom, [handlepos], true);
32627 if (pos == 'hdrag') {
32628 this.el.setStyle('cursor', 'pointer');
32630 this.el.unselectable();
32632 this.el.setOpacity(0);
32634 this.el.on("mousedown", this.onMouseDown, this);
32635 if(!disableTrackOver){
32636 this.el.on("mouseover", this.onMouseOver, this);
32637 this.el.on("mouseout", this.onMouseOut, this);
32642 Roo.Resizable.Handle.prototype = {
32643 afterResize : function(rz){
32648 onMouseDown : function(e){
32649 this.rz.onMouseDown(this, e);
32652 onMouseOver : function(e){
32653 this.rz.handleOver(this, e);
32656 onMouseOut : function(e){
32657 this.rz.handleOut(this, e);
32661 * Ext JS Library 1.1.1
32662 * Copyright(c) 2006-2007, Ext JS, LLC.
32664 * Originally Released Under LGPL - original licence link has changed is not relivant.
32667 * <script type="text/javascript">
32671 * @class Roo.Editor
32672 * @extends Roo.Component
32673 * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
32675 * Create a new Editor
32676 * @param {Roo.form.Field} field The Field object (or descendant)
32677 * @param {Object} config The config object
32679 Roo.Editor = function(field, config){
32680 Roo.Editor.superclass.constructor.call(this, config);
32681 this.field = field;
32684 * @event beforestartedit
32685 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
32686 * false from the handler of this event.
32687 * @param {Editor} this
32688 * @param {Roo.Element} boundEl The underlying element bound to this editor
32689 * @param {Mixed} value The field value being set
32691 "beforestartedit" : true,
32694 * Fires when this editor is displayed
32695 * @param {Roo.Element} boundEl The underlying element bound to this editor
32696 * @param {Mixed} value The starting field value
32698 "startedit" : true,
32700 * @event beforecomplete
32701 * Fires after a change has been made to the field, but before the change is reflected in the underlying
32702 * field. Saving the change to the field can be canceled by returning false from the handler of this event.
32703 * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
32704 * event will not fire since no edit actually occurred.
32705 * @param {Editor} this
32706 * @param {Mixed} value The current field value
32707 * @param {Mixed} startValue The original field value
32709 "beforecomplete" : true,
32712 * Fires after editing is complete and any changed value has been written to the underlying field.
32713 * @param {Editor} this
32714 * @param {Mixed} value The current field value
32715 * @param {Mixed} startValue The original field value
32719 * @event specialkey
32720 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
32721 * {@link Roo.EventObject#getKey} to determine which key was pressed.
32722 * @param {Roo.form.Field} this
32723 * @param {Roo.EventObject} e The event object
32725 "specialkey" : true
32729 Roo.extend(Roo.Editor, Roo.Component, {
32731 * @cfg {Boolean/String} autosize
32732 * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
32733 * or "height" to adopt the height only (defaults to false)
32736 * @cfg {Boolean} revertInvalid
32737 * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
32738 * validation fails (defaults to true)
32741 * @cfg {Boolean} ignoreNoChange
32742 * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
32743 * the value has not changed (defaults to false). Applies only to string values - edits for other data types
32744 * will never be ignored.
32747 * @cfg {Boolean} hideEl
32748 * False to keep the bound element visible while the editor is displayed (defaults to true)
32751 * @cfg {Mixed} value
32752 * The data value of the underlying field (defaults to "")
32756 * @cfg {String} alignment
32757 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
32761 * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
32762 * for bottom-right shadow (defaults to "frame")
32766 * @cfg {Boolean} constrain True to constrain the editor to the viewport
32770 * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
32772 completeOnEnter : false,
32774 * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
32776 cancelOnEsc : false,
32778 * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
32783 onRender : function(ct, position){
32784 this.el = new Roo.Layer({
32785 shadow: this.shadow,
32791 constrain: this.constrain
32793 this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
32794 if(this.field.msgTarget != 'title'){
32795 this.field.msgTarget = 'qtip';
32797 this.field.render(this.el);
32799 this.field.el.dom.setAttribute('autocomplete', 'off');
32801 this.field.on("specialkey", this.onSpecialKey, this);
32802 if(this.swallowKeys){
32803 this.field.el.swallowEvent(['keydown','keypress']);
32806 this.field.on("blur", this.onBlur, this);
32807 if(this.field.grow){
32808 this.field.on("autosize", this.el.sync, this.el, {delay:1});
32812 onSpecialKey : function(field, e)
32814 //Roo.log('editor onSpecialKey');
32815 if(this.completeOnEnter && e.getKey() == e.ENTER){
32817 this.completeEdit();
32820 // do not fire special key otherwise it might hide close the editor...
32821 if(e.getKey() == e.ENTER){
32824 if(this.cancelOnEsc && e.getKey() == e.ESC){
32828 this.fireEvent('specialkey', field, e);
32833 * Starts the editing process and shows the editor.
32834 * @param {String/HTMLElement/Element} el The element to edit
32835 * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
32836 * to the innerHTML of el.
32838 startEdit : function(el, value){
32840 this.completeEdit();
32842 this.boundEl = Roo.get(el);
32843 var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
32844 if(!this.rendered){
32845 this.render(this.parentEl || document.body);
32847 if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
32850 this.startValue = v;
32851 this.field.setValue(v);
32853 var sz = this.boundEl.getSize();
32854 switch(this.autoSize){
32856 this.setSize(sz.width, "");
32859 this.setSize("", sz.height);
32862 this.setSize(sz.width, sz.height);
32865 this.el.alignTo(this.boundEl, this.alignment);
32866 this.editing = true;
32868 Roo.QuickTips.disable();
32874 * Sets the height and width of this editor.
32875 * @param {Number} width The new width
32876 * @param {Number} height The new height
32878 setSize : function(w, h){
32879 this.field.setSize(w, h);
32886 * Realigns the editor to the bound field based on the current alignment config value.
32888 realign : function(){
32889 this.el.alignTo(this.boundEl, this.alignment);
32893 * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
32894 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
32896 completeEdit : function(remainVisible){
32900 var v = this.getValue();
32901 if(this.revertInvalid !== false && !this.field.isValid()){
32902 v = this.startValue;
32903 this.cancelEdit(true);
32905 if(String(v) === String(this.startValue) && this.ignoreNoChange){
32906 this.editing = false;
32910 if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
32911 this.editing = false;
32912 if(this.updateEl && this.boundEl){
32913 this.boundEl.update(v);
32915 if(remainVisible !== true){
32918 this.fireEvent("complete", this, v, this.startValue);
32923 onShow : function(){
32925 if(this.hideEl !== false){
32926 this.boundEl.hide();
32929 if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
32930 this.fixIEFocus = true;
32931 this.deferredFocus.defer(50, this);
32933 this.field.focus();
32935 this.fireEvent("startedit", this.boundEl, this.startValue);
32938 deferredFocus : function(){
32940 this.field.focus();
32945 * Cancels the editing process and hides the editor without persisting any changes. The field value will be
32946 * reverted to the original starting value.
32947 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
32948 * cancel (defaults to false)
32950 cancelEdit : function(remainVisible){
32952 this.setValue(this.startValue);
32953 if(remainVisible !== true){
32960 onBlur : function(){
32961 if(this.allowBlur !== true && this.editing){
32962 this.completeEdit();
32967 onHide : function(){
32969 this.completeEdit();
32973 if(this.field.collapse){
32974 this.field.collapse();
32977 if(this.hideEl !== false){
32978 this.boundEl.show();
32981 Roo.QuickTips.enable();
32986 * Sets the data value of the editor
32987 * @param {Mixed} value Any valid value supported by the underlying field
32989 setValue : function(v){
32990 this.field.setValue(v);
32994 * Gets the data value of the editor
32995 * @return {Mixed} The data value
32997 getValue : function(){
32998 return this.field.getValue();
33002 * Ext JS Library 1.1.1
33003 * Copyright(c) 2006-2007, Ext JS, LLC.
33005 * Originally Released Under LGPL - original licence link has changed is not relivant.
33008 * <script type="text/javascript">
33012 * @class Roo.BasicDialog
33013 * @extends Roo.util.Observable
33014 * @parent none builder
33015 * Lightweight Dialog Class. The code below shows the creation of a typical dialog using existing HTML markup:
33017 var dlg = new Roo.BasicDialog("my-dlg", {
33026 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
33027 dlg.addButton('OK', dlg.hide, dlg); // Could call a save function instead of hiding
33028 dlg.addButton('Cancel', dlg.hide, dlg);
33031 <b>A Dialog should always be a direct child of the body element.</b>
33032 * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
33033 * @cfg {String} title Default text to display in the title bar (defaults to null)
33034 * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
33035 * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
33036 * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
33037 * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
33038 * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
33039 * (defaults to null with no animation)
33040 * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
33041 * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
33042 * property for valid values (defaults to 'all')
33043 * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
33044 * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
33045 * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
33046 * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
33047 * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
33048 * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
33049 * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
33050 * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
33051 * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
33052 * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
33053 * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
33054 * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
33055 * draggable = true (defaults to false)
33056 * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
33057 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
33058 * shadow (defaults to false)
33059 * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
33060 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
33061 * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
33062 * @cfg {Array} buttons Array of buttons
33063 * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
33065 * Create a new BasicDialog.
33066 * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
33067 * @param {Object} config Configuration options
33069 Roo.BasicDialog = function(el, config){
33070 this.el = Roo.get(el);
33071 var dh = Roo.DomHelper;
33072 if(!this.el && config && config.autoCreate){
33073 if(typeof config.autoCreate == "object"){
33074 if(!config.autoCreate.id){
33075 config.autoCreate.id = el;
33077 this.el = dh.append(document.body,
33078 config.autoCreate, true);
33080 this.el = dh.append(document.body,
33081 {tag: "div", id: el, style:'visibility:hidden;'}, true);
33085 el.setDisplayed(true);
33086 el.hide = this.hideAction;
33088 el.addClass("x-dlg");
33090 Roo.apply(this, config);
33092 this.proxy = el.createProxy("x-dlg-proxy");
33093 this.proxy.hide = this.hideAction;
33094 this.proxy.setOpacity(.5);
33098 el.setWidth(config.width);
33101 el.setHeight(config.height);
33103 this.size = el.getSize();
33104 if(typeof config.x != "undefined" && typeof config.y != "undefined"){
33105 this.xy = [config.x,config.y];
33107 this.xy = el.getCenterXY(true);
33109 /** The header element @type Roo.Element */
33110 this.header = el.child("> .x-dlg-hd");
33111 /** The body element @type Roo.Element */
33112 this.body = el.child("> .x-dlg-bd");
33113 /** The footer element @type Roo.Element */
33114 this.footer = el.child("> .x-dlg-ft");
33117 this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
33120 this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
33123 this.header.unselectable();
33125 this.header.update(this.title);
33127 // this element allows the dialog to be focused for keyboard event
33128 this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
33129 this.focusEl.swallowEvent("click", true);
33131 this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
33133 // wrap the body and footer for special rendering
33134 this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
33136 this.bwrap.dom.appendChild(this.footer.dom);
33139 this.bg = this.el.createChild({
33140 tag: "div", cls:"x-dlg-bg",
33141 html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
33143 this.centerBg = this.bg.child("div.x-dlg-bg-center");
33146 if(this.autoScroll !== false && !this.autoTabs){
33147 this.body.setStyle("overflow", "auto");
33150 this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
33152 if(this.closable !== false){
33153 this.el.addClass("x-dlg-closable");
33154 this.close = this.toolbox.createChild({cls:"x-dlg-close"});
33155 this.close.on("click", this.closeClick, this);
33156 this.close.addClassOnOver("x-dlg-close-over");
33158 if(this.collapsible !== false){
33159 this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
33160 this.collapseBtn.on("click", this.collapseClick, this);
33161 this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
33162 this.header.on("dblclick", this.collapseClick, this);
33164 if(this.resizable !== false){
33165 this.el.addClass("x-dlg-resizable");
33166 this.resizer = new Roo.Resizable(el, {
33167 minWidth: this.minWidth || 80,
33168 minHeight:this.minHeight || 80,
33169 handles: this.resizeHandles || "all",
33172 this.resizer.on("beforeresize", this.beforeResize, this);
33173 this.resizer.on("resize", this.onResize, this);
33175 if(this.draggable !== false){
33176 el.addClass("x-dlg-draggable");
33177 if (!this.proxyDrag) {
33178 var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
33181 var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
33183 dd.setHandleElId(this.header.id);
33184 dd.endDrag = this.endMove.createDelegate(this);
33185 dd.startDrag = this.startMove.createDelegate(this);
33186 dd.onDrag = this.onDrag.createDelegate(this);
33191 this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
33192 this.mask.enableDisplayMode("block");
33194 this.el.addClass("x-dlg-modal");
33197 this.shadow = new Roo.Shadow({
33198 mode : typeof this.shadow == "string" ? this.shadow : "sides",
33199 offset : this.shadowOffset
33202 this.shadowOffset = 0;
33204 if(Roo.useShims && this.shim !== false){
33205 this.shim = this.el.createShim();
33206 this.shim.hide = this.hideAction;
33214 if (this.buttons) {
33215 var bts= this.buttons;
33217 Roo.each(bts, function(b) {
33226 * Fires when a key is pressed
33227 * @param {Roo.BasicDialog} this
33228 * @param {Roo.EventObject} e
33233 * Fires when this dialog is moved by the user.
33234 * @param {Roo.BasicDialog} this
33235 * @param {Number} x The new page X
33236 * @param {Number} y The new page Y
33241 * Fires when this dialog is resized by the user.
33242 * @param {Roo.BasicDialog} this
33243 * @param {Number} width The new width
33244 * @param {Number} height The new height
33248 * @event beforehide
33249 * Fires before this dialog is hidden.
33250 * @param {Roo.BasicDialog} this
33252 "beforehide" : true,
33255 * Fires when this dialog is hidden.
33256 * @param {Roo.BasicDialog} this
33260 * @event beforeshow
33261 * Fires before this dialog is shown.
33262 * @param {Roo.BasicDialog} this
33264 "beforeshow" : true,
33267 * Fires when this dialog is shown.
33268 * @param {Roo.BasicDialog} this
33272 el.on("keydown", this.onKeyDown, this);
33273 el.on("mousedown", this.toFront, this);
33274 Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
33276 Roo.DialogManager.register(this);
33277 Roo.BasicDialog.superclass.constructor.call(this);
33280 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
33281 shadowOffset: Roo.isIE ? 6 : 5,
33284 minButtonWidth: 75,
33285 defaultButton: null,
33286 buttonAlign: "right",
33291 * Sets the dialog title text
33292 * @param {String} text The title text to display
33293 * @return {Roo.BasicDialog} this
33295 setTitle : function(text){
33296 this.header.update(text);
33301 closeClick : function(){
33306 collapseClick : function(){
33307 this[this.collapsed ? "expand" : "collapse"]();
33311 * Collapses the dialog to its minimized state (only the title bar is visible).
33312 * Equivalent to the user clicking the collapse dialog button.
33314 collapse : function(){
33315 if(!this.collapsed){
33316 this.collapsed = true;
33317 this.el.addClass("x-dlg-collapsed");
33318 this.restoreHeight = this.el.getHeight();
33319 this.resizeTo(this.el.getWidth(), this.header.getHeight());
33324 * Expands a collapsed dialog back to its normal state. Equivalent to the user
33325 * clicking the expand dialog button.
33327 expand : function(){
33328 if(this.collapsed){
33329 this.collapsed = false;
33330 this.el.removeClass("x-dlg-collapsed");
33331 this.resizeTo(this.el.getWidth(), this.restoreHeight);
33336 * Reinitializes the tabs component, clearing out old tabs and finding new ones.
33337 * @return {Roo.TabPanel} The tabs component
33339 initTabs : function(){
33340 var tabs = this.getTabs();
33341 while(tabs.getTab(0)){
33344 this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
33346 tabs.addTab(Roo.id(dom), dom.title);
33354 beforeResize : function(){
33355 this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
33359 onResize : function(){
33360 this.refreshSize();
33361 this.syncBodyHeight();
33362 this.adjustAssets();
33364 this.fireEvent("resize", this, this.size.width, this.size.height);
33368 onKeyDown : function(e){
33369 if(this.isVisible()){
33370 this.fireEvent("keydown", this, e);
33375 * Resizes the dialog.
33376 * @param {Number} width
33377 * @param {Number} height
33378 * @return {Roo.BasicDialog} this
33380 resizeTo : function(width, height){
33381 this.el.setSize(width, height);
33382 this.size = {width: width, height: height};
33383 this.syncBodyHeight();
33384 if(this.fixedcenter){
33387 if(this.isVisible()){
33388 this.constrainXY();
33389 this.adjustAssets();
33391 this.fireEvent("resize", this, width, height);
33397 * Resizes the dialog to fit the specified content size.
33398 * @param {Number} width
33399 * @param {Number} height
33400 * @return {Roo.BasicDialog} this
33402 setContentSize : function(w, h){
33403 h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
33404 w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
33405 //if(!this.el.isBorderBox()){
33406 h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
33407 w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
33410 h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
33411 w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
33413 this.resizeTo(w, h);
33418 * Adds a key listener for when this dialog is displayed. This allows you to hook in a function that will be
33419 * executed in response to a particular key being pressed while the dialog is active.
33420 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
33421 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
33422 * @param {Function} fn The function to call
33423 * @param {Object} scope (optional) The scope of the function
33424 * @return {Roo.BasicDialog} this
33426 addKeyListener : function(key, fn, scope){
33427 var keyCode, shift, ctrl, alt;
33428 if(typeof key == "object" && !(key instanceof Array)){
33429 keyCode = key["key"];
33430 shift = key["shift"];
33431 ctrl = key["ctrl"];
33436 var handler = function(dlg, e){
33437 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
33438 var k = e.getKey();
33439 if(keyCode instanceof Array){
33440 for(var i = 0, len = keyCode.length; i < len; i++){
33441 if(keyCode[i] == k){
33442 fn.call(scope || window, dlg, k, e);
33448 fn.call(scope || window, dlg, k, e);
33453 this.on("keydown", handler);
33458 * Returns the TabPanel component (creates it if it doesn't exist).
33459 * Note: If you wish to simply check for the existence of tabs without creating them,
33460 * check for a null 'tabs' property.
33461 * @return {Roo.TabPanel} The tabs component
33463 getTabs : function(){
33465 this.el.addClass("x-dlg-auto-tabs");
33466 this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
33467 this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
33473 * Adds a button to the footer section of the dialog.
33474 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
33475 * object or a valid Roo.DomHelper element config
33476 * @param {Function} handler The function called when the button is clicked
33477 * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
33478 * @return {Roo.Button} The new button
33480 addButton : function(config, handler, scope){
33481 var dh = Roo.DomHelper;
33483 this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
33485 if(!this.btnContainer){
33486 var tb = this.footer.createChild({
33488 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
33489 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
33491 this.btnContainer = tb.firstChild.firstChild.firstChild;
33496 minWidth: this.minButtonWidth,
33499 if(typeof config == "string"){
33500 bconfig.text = config;
33503 bconfig.dhconfig = config;
33505 Roo.apply(bconfig, config);
33509 if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
33510 bconfig.position = Math.max(0, bconfig.position);
33511 fc = this.btnContainer.childNodes[bconfig.position];
33514 var btn = new Roo.Button(
33516 this.btnContainer.insertBefore(document.createElement("td"),fc)
33517 : this.btnContainer.appendChild(document.createElement("td")),
33518 //Roo.get(this.btnContainer).createChild( { tag: 'td'}, fc ),
33521 this.syncBodyHeight();
33524 * Array of all the buttons that have been added to this dialog via addButton
33529 this.buttons.push(btn);
33534 * Sets the default button to be focused when the dialog is displayed.
33535 * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
33536 * @return {Roo.BasicDialog} this
33538 setDefaultButton : function(btn){
33539 this.defaultButton = btn;
33544 getHeaderFooterHeight : function(safe){
33547 height += this.header.getHeight();
33550 var fm = this.footer.getMargins();
33551 height += (this.footer.getHeight()+fm.top+fm.bottom);
33553 height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
33554 height += this.centerBg.getPadding("tb");
33559 syncBodyHeight : function()
33561 var bd = this.body, // the text
33562 cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
33564 var height = this.size.height - this.getHeaderFooterHeight(false);
33565 bd.setHeight(height-bd.getMargins("tb"));
33566 var hh = this.header.getHeight();
33567 var h = this.size.height-hh;
33570 bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
33571 bw.setHeight(h-cb.getPadding("tb"));
33573 bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
33574 bd.setWidth(bw.getWidth(true));
33576 this.tabs.syncHeight();
33578 this.tabs.el.repaint();
33584 * Restores the previous state of the dialog if Roo.state is configured.
33585 * @return {Roo.BasicDialog} this
33587 restoreState : function(){
33588 var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
33589 if(box && box.width){
33590 this.xy = [box.x, box.y];
33591 this.resizeTo(box.width, box.height);
33597 beforeShow : function(){
33599 if(this.fixedcenter){
33600 this.xy = this.el.getCenterXY(true);
33603 Roo.get(document.body).addClass("x-body-masked");
33604 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
33607 this.constrainXY();
33611 animShow : function(){
33612 var b = Roo.get(this.animateTarget).getBox();
33613 this.proxy.setSize(b.width, b.height);
33614 this.proxy.setLocation(b.x, b.y);
33616 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
33617 true, .35, this.showEl.createDelegate(this));
33621 * Shows the dialog.
33622 * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
33623 * @return {Roo.BasicDialog} this
33625 show : function(animateTarget){
33626 if (this.fireEvent("beforeshow", this) === false){
33629 if(this.syncHeightBeforeShow){
33630 this.syncBodyHeight();
33631 }else if(this.firstShow){
33632 this.firstShow = false;
33633 this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
33635 this.animateTarget = animateTarget || this.animateTarget;
33636 if(!this.el.isVisible()){
33638 if(this.animateTarget && Roo.get(this.animateTarget)){
33648 showEl : function(){
33650 this.el.setXY(this.xy);
33652 this.adjustAssets(true);
33655 // IE peekaboo bug - fix found by Dave Fenwick
33659 this.fireEvent("show", this);
33663 * Focuses the dialog. If a defaultButton is set, it will receive focus, otherwise the
33664 * dialog itself will receive focus.
33666 focus : function(){
33667 if(this.defaultButton){
33668 this.defaultButton.focus();
33670 this.focusEl.focus();
33675 constrainXY : function(){
33676 if(this.constraintoviewport !== false){
33677 if(!this.viewSize){
33678 if(this.container){
33679 var s = this.container.getSize();
33680 this.viewSize = [s.width, s.height];
33682 this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
33685 var s = Roo.get(this.container||document).getScroll();
33687 var x = this.xy[0], y = this.xy[1];
33688 var w = this.size.width, h = this.size.height;
33689 var vw = this.viewSize[0], vh = this.viewSize[1];
33690 // only move it if it needs it
33692 // first validate right/bottom
33693 if(x + w > vw+s.left){
33697 if(y + h > vh+s.top){
33701 // then make sure top/left isn't negative
33713 if(this.isVisible()){
33714 this.el.setLocation(x, y);
33715 this.adjustAssets();
33722 onDrag : function(){
33723 if(!this.proxyDrag){
33724 this.xy = this.el.getXY();
33725 this.adjustAssets();
33730 adjustAssets : function(doShow){
33731 var x = this.xy[0], y = this.xy[1];
33732 var w = this.size.width, h = this.size.height;
33733 if(doShow === true){
33735 this.shadow.show(this.el);
33741 if(this.shadow && this.shadow.isVisible()){
33742 this.shadow.show(this.el);
33744 if(this.shim && this.shim.isVisible()){
33745 this.shim.setBounds(x, y, w, h);
33750 adjustViewport : function(w, h){
33752 w = Roo.lib.Dom.getViewWidth();
33753 h = Roo.lib.Dom.getViewHeight();
33756 this.viewSize = [w, h];
33757 if(this.modal && this.mask.isVisible()){
33758 this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
33759 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
33761 if(this.isVisible()){
33762 this.constrainXY();
33767 * Destroys this dialog and all its supporting elements (including any tabs, shim,
33768 * shadow, proxy, mask, etc.) Also removes all event listeners.
33769 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
33771 destroy : function(removeEl){
33772 if(this.isVisible()){
33773 this.animateTarget = null;
33776 Roo.EventManager.removeResizeListener(this.adjustViewport, this);
33778 this.tabs.destroy(removeEl);
33791 for(var i = 0, len = this.buttons.length; i < len; i++){
33792 this.buttons[i].destroy();
33795 this.el.removeAllListeners();
33796 if(removeEl === true){
33797 this.el.update("");
33800 Roo.DialogManager.unregister(this);
33804 startMove : function(){
33805 if(this.proxyDrag){
33808 if(this.constraintoviewport !== false){
33809 this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
33814 endMove : function(){
33815 if(!this.proxyDrag){
33816 Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
33818 Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
33821 this.refreshSize();
33822 this.adjustAssets();
33824 this.fireEvent("move", this, this.xy[0], this.xy[1]);
33828 * Brings this dialog to the front of any other visible dialogs
33829 * @return {Roo.BasicDialog} this
33831 toFront : function(){
33832 Roo.DialogManager.bringToFront(this);
33837 * Sends this dialog to the back (under) of any other visible dialogs
33838 * @return {Roo.BasicDialog} this
33840 toBack : function(){
33841 Roo.DialogManager.sendToBack(this);
33846 * Centers this dialog in the viewport
33847 * @return {Roo.BasicDialog} this
33849 center : function(){
33850 var xy = this.el.getCenterXY(true);
33851 this.moveTo(xy[0], xy[1]);
33856 * Moves the dialog's top-left corner to the specified point
33857 * @param {Number} x
33858 * @param {Number} y
33859 * @return {Roo.BasicDialog} this
33861 moveTo : function(x, y){
33863 if(this.isVisible()){
33864 this.el.setXY(this.xy);
33865 this.adjustAssets();
33871 * Aligns the dialog to the specified element
33872 * @param {String/HTMLElement/Roo.Element} element The element to align to.
33873 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
33874 * @param {Array} offsets (optional) Offset the positioning by [x, y]
33875 * @return {Roo.BasicDialog} this
33877 alignTo : function(element, position, offsets){
33878 this.xy = this.el.getAlignToXY(element, position, offsets);
33879 if(this.isVisible()){
33880 this.el.setXY(this.xy);
33881 this.adjustAssets();
33887 * Anchors an element to another element and realigns it when the window is resized.
33888 * @param {String/HTMLElement/Roo.Element} element The element to align to.
33889 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
33890 * @param {Array} offsets (optional) Offset the positioning by [x, y]
33891 * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
33892 * is a number, it is used as the buffer delay (defaults to 50ms).
33893 * @return {Roo.BasicDialog} this
33895 anchorTo : function(el, alignment, offsets, monitorScroll){
33896 var action = function(){
33897 this.alignTo(el, alignment, offsets);
33899 Roo.EventManager.onWindowResize(action, this);
33900 var tm = typeof monitorScroll;
33901 if(tm != 'undefined'){
33902 Roo.EventManager.on(window, 'scroll', action, this,
33903 {buffer: tm == 'number' ? monitorScroll : 50});
33910 * Returns true if the dialog is visible
33911 * @return {Boolean}
33913 isVisible : function(){
33914 return this.el.isVisible();
33918 animHide : function(callback){
33919 var b = Roo.get(this.animateTarget).getBox();
33921 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
33923 this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
33924 this.hideEl.createDelegate(this, [callback]));
33928 * Hides the dialog.
33929 * @param {Function} callback (optional) Function to call when the dialog is hidden
33930 * @return {Roo.BasicDialog} this
33932 hide : function(callback){
33933 if (this.fireEvent("beforehide", this) === false){
33937 this.shadow.hide();
33942 // sometimes animateTarget seems to get set.. causing problems...
33943 // this just double checks..
33944 if(this.animateTarget && Roo.get(this.animateTarget)) {
33945 this.animHide(callback);
33948 this.hideEl(callback);
33954 hideEl : function(callback){
33958 Roo.get(document.body).removeClass("x-body-masked");
33960 this.fireEvent("hide", this);
33961 if(typeof callback == "function"){
33967 hideAction : function(){
33968 this.setLeft("-10000px");
33969 this.setTop("-10000px");
33970 this.setStyle("visibility", "hidden");
33974 refreshSize : function(){
33975 this.size = this.el.getSize();
33976 this.xy = this.el.getXY();
33977 Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
33981 // z-index is managed by the DialogManager and may be overwritten at any time
33982 setZIndex : function(index){
33984 this.mask.setStyle("z-index", index);
33987 this.shim.setStyle("z-index", ++index);
33990 this.shadow.setZIndex(++index);
33992 this.el.setStyle("z-index", ++index);
33994 this.proxy.setStyle("z-index", ++index);
33997 this.resizer.proxy.setStyle("z-index", ++index);
34000 this.lastZIndex = index;
34004 * Returns the element for this dialog
34005 * @return {Roo.Element} The underlying dialog Element
34007 getEl : function(){
34013 * @class Roo.DialogManager
34014 * Provides global access to BasicDialogs that have been created and
34015 * support for z-indexing (layering) multiple open dialogs.
34017 Roo.DialogManager = function(){
34019 var accessList = [];
34023 var sortDialogs = function(d1, d2){
34024 return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
34028 var orderDialogs = function(){
34029 accessList.sort(sortDialogs);
34030 var seed = Roo.DialogManager.zseed;
34031 for(var i = 0, len = accessList.length; i < len; i++){
34032 var dlg = accessList[i];
34034 dlg.setZIndex(seed + (i*10));
34041 * The starting z-index for BasicDialogs (defaults to 9000)
34042 * @type Number The z-index value
34047 register : function(dlg){
34048 list[dlg.id] = dlg;
34049 accessList.push(dlg);
34053 unregister : function(dlg){
34054 delete list[dlg.id];
34057 if(!accessList.indexOf){
34058 for( i = 0, len = accessList.length; i < len; i++){
34059 if(accessList[i] == dlg){
34060 accessList.splice(i, 1);
34065 i = accessList.indexOf(dlg);
34067 accessList.splice(i, 1);
34073 * Gets a registered dialog by id
34074 * @param {String/Object} id The id of the dialog or a dialog
34075 * @return {Roo.BasicDialog} this
34077 get : function(id){
34078 return typeof id == "object" ? id : list[id];
34082 * Brings the specified dialog to the front
34083 * @param {String/Object} dlg The id of the dialog or a dialog
34084 * @return {Roo.BasicDialog} this
34086 bringToFront : function(dlg){
34087 dlg = this.get(dlg);
34090 dlg._lastAccess = new Date().getTime();
34097 * Sends the specified dialog to the back
34098 * @param {String/Object} dlg The id of the dialog or a dialog
34099 * @return {Roo.BasicDialog} this
34101 sendToBack : function(dlg){
34102 dlg = this.get(dlg);
34103 dlg._lastAccess = -(new Date().getTime());
34109 * Hides all dialogs
34111 hideAll : function(){
34112 for(var id in list){
34113 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
34122 * @class Roo.LayoutDialog
34123 * @extends Roo.BasicDialog
34124 * @children Roo.ContentPanel
34125 * @parent builder none
34126 * Dialog which provides adjustments for working with a layout in a Dialog.
34127 * Add your necessary layout config options to the dialog's config.<br>
34128 * Example usage (including a nested layout):
34131 dialog = new Roo.LayoutDialog("download-dlg", {
34140 // layout config merges with the dialog config
34142 tabPosition: "top",
34143 alwaysShowTabs: true
34146 dialog.addKeyListener(27, dialog.hide, dialog);
34147 dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
34148 dialog.addButton("Build It!", this.getDownload, this);
34150 // we can even add nested layouts
34151 var innerLayout = new Roo.BorderLayout("dl-inner", {
34161 innerLayout.beginUpdate();
34162 innerLayout.add("east", new Roo.ContentPanel("dl-details"));
34163 innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
34164 innerLayout.endUpdate(true);
34166 var layout = dialog.getLayout();
34167 layout.beginUpdate();
34168 layout.add("center", new Roo.ContentPanel("standard-panel",
34169 {title: "Download the Source", fitToFrame:true}));
34170 layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
34171 {title: "Build your own roo.js"}));
34172 layout.getRegion("center").showPanel(sp);
34173 layout.endUpdate();
34177 * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
34178 * @param {Object} config configuration options
34180 Roo.LayoutDialog = function(el, cfg){
34183 if (typeof(cfg) == 'undefined') {
34184 config = Roo.apply({}, el);
34185 // not sure why we use documentElement here.. - it should always be body.
34186 // IE7 borks horribly if we use documentElement.
34187 // webkit also does not like documentElement - it creates a body element...
34188 el = Roo.get( document.body || document.documentElement ).createChild();
34189 //config.autoCreate = true;
34193 config.autoTabs = false;
34194 Roo.LayoutDialog.superclass.constructor.call(this, el, config);
34195 this.body.setStyle({overflow:"hidden", position:"relative"});
34196 this.layout = new Roo.BorderLayout(this.body.dom, config);
34197 this.layout.monitorWindowResize = false;
34198 this.el.addClass("x-dlg-auto-layout");
34199 // fix case when center region overwrites center function
34200 this.center = Roo.BasicDialog.prototype.center;
34201 this.on("show", this.layout.layout, this.layout, true);
34202 if (config.items) {
34203 var xitems = config.items;
34204 delete config.items;
34205 Roo.each(xitems, this.addxtype, this);
34210 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
34214 * @cfg {Roo.LayoutRegion} east
34217 * @cfg {Roo.LayoutRegion} west
34220 * @cfg {Roo.LayoutRegion} south
34223 * @cfg {Roo.LayoutRegion} north
34226 * @cfg {Roo.LayoutRegion} center
34229 * @cfg {Roo.Button} buttons[] Bottom buttons..
34234 * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
34237 endUpdate : function(){
34238 this.layout.endUpdate();
34242 * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
34245 beginUpdate : function(){
34246 this.layout.beginUpdate();
34250 * Get the BorderLayout for this dialog
34251 * @return {Roo.BorderLayout}
34253 getLayout : function(){
34254 return this.layout;
34257 showEl : function(){
34258 Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
34260 this.layout.layout();
34265 // Use the syncHeightBeforeShow config option to control this automatically
34266 syncBodyHeight : function(){
34267 Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
34268 if(this.layout){this.layout.layout();}
34272 * Add an xtype element (actually adds to the layout.)
34273 * @return {Object} xdata xtype object data.
34276 addxtype : function(c) {
34277 return this.layout.addxtype(c);
34281 * Ext JS Library 1.1.1
34282 * Copyright(c) 2006-2007, Ext JS, LLC.
34284 * Originally Released Under LGPL - original licence link has changed is not relivant.
34287 * <script type="text/javascript">
34291 * @class Roo.MessageBox
34292 * Utility class for generating different styles of message boxes. The alias Roo.Msg can also be used.
34296 Roo.Msg.alert('Status', 'Changes saved successfully.');
34298 // Prompt for user data:
34299 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
34301 // process text value...
34305 // Show a dialog using config options:
34307 title:'Save Changes?',
34308 msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
34309 buttons: Roo.Msg.YESNOCANCEL,
34316 Roo.MessageBox = function(){
34317 var dlg, opt, mask, waitTimer;
34318 var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
34319 var buttons, activeTextEl, bwidth;
34322 var handleButton = function(button){
34324 Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
34328 var handleHide = function(){
34329 if(opt && opt.cls){
34330 dlg.el.removeClass(opt.cls);
34333 Roo.TaskMgr.stop(waitTimer);
34339 var updateButtons = function(b){
34342 buttons["ok"].hide();
34343 buttons["cancel"].hide();
34344 buttons["yes"].hide();
34345 buttons["no"].hide();
34346 dlg.footer.dom.style.display = 'none';
34349 dlg.footer.dom.style.display = '';
34350 for(var k in buttons){
34351 if(typeof buttons[k] != "function"){
34354 buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
34355 width += buttons[k].el.getWidth()+15;
34365 var handleEsc = function(d, k, e){
34366 if(opt && opt.closable !== false){
34376 * Returns a reference to the underlying {@link Roo.BasicDialog} element
34377 * @return {Roo.BasicDialog} The BasicDialog element
34379 getDialog : function(){
34381 dlg = new Roo.BasicDialog("x-msg-box", {
34386 constraintoviewport:false,
34388 collapsible : false,
34391 width:400, height:100,
34392 buttonAlign:"center",
34393 closeClick : function(){
34394 if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
34395 handleButton("no");
34397 handleButton("cancel");
34401 dlg.on("hide", handleHide);
34403 dlg.addKeyListener(27, handleEsc);
34405 var bt = this.buttonText;
34406 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
34407 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
34408 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
34409 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
34410 bodyEl = dlg.body.createChild({
34412 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>'
34414 msgEl = bodyEl.dom.firstChild;
34415 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
34416 textboxEl.enableDisplayMode();
34417 textboxEl.addKeyListener([10,13], function(){
34418 if(dlg.isVisible() && opt && opt.buttons){
34419 if(opt.buttons.ok){
34420 handleButton("ok");
34421 }else if(opt.buttons.yes){
34422 handleButton("yes");
34426 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
34427 textareaEl.enableDisplayMode();
34428 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
34429 progressEl.enableDisplayMode();
34430 var pf = progressEl.dom.firstChild;
34432 pp = Roo.get(pf.firstChild);
34433 pp.setHeight(pf.offsetHeight);
34441 * Updates the message box body text
34442 * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
34443 * the XHTML-compliant non-breaking space character '&#160;')
34444 * @return {Roo.MessageBox} This message box
34446 updateText : function(text){
34447 if(!dlg.isVisible() && !opt.width){
34448 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
34450 msgEl.innerHTML = text || ' ';
34452 var cw = Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
34453 //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
34455 Math.min(opt.width || cw , this.maxWidth),
34456 Math.max(opt.minWidth || this.minWidth, bwidth)
34459 activeTextEl.setWidth(w);
34461 if(dlg.isVisible()){
34462 dlg.fixedcenter = false;
34464 // to big, make it scroll. = But as usual stupid IE does not support
34467 if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
34468 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
34469 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
34471 bodyEl.dom.style.height = '';
34472 bodyEl.dom.style.overflowY = '';
34475 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
34477 bodyEl.dom.style.overflowX = '';
34480 dlg.setContentSize(w, bodyEl.getHeight());
34481 if(dlg.isVisible()){
34482 dlg.fixedcenter = true;
34488 * Updates a progress-style message box's text and progress bar. Only relevant on message boxes
34489 * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
34490 * @param {Number} value Any number between 0 and 1 (e.g., .5)
34491 * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
34492 * @return {Roo.MessageBox} This message box
34494 updateProgress : function(value, text){
34496 this.updateText(text);
34498 if (pp) { // weird bug on my firefox - for some reason this is not defined
34499 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
34505 * Returns true if the message box is currently displayed
34506 * @return {Boolean} True if the message box is visible, else false
34508 isVisible : function(){
34509 return dlg && dlg.isVisible();
34513 * Hides the message box if it is displayed
34516 if(this.isVisible()){
34522 * Displays a new message box, or reinitializes an existing message box, based on the config options
34523 * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
34524 * The following config object properties are supported:
34526 Property Type Description
34527 ---------- --------------- ------------------------------------------------------------------------------------
34528 animEl String/Element An id or Element from which the message box should animate as it opens and
34529 closes (defaults to undefined)
34530 buttons Object/Boolean A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
34531 cancel:'Bar'}), or false to not show any buttons (defaults to false)
34532 closable Boolean False to hide the top-right close button (defaults to true). Note that
34533 progress and wait dialogs will ignore this property and always hide the
34534 close button as they can only be closed programmatically.
34535 cls String A custom CSS class to apply to the message box element
34536 defaultTextHeight Number The default height in pixels of the message box's multiline textarea if
34537 displayed (defaults to 75)
34538 fn Function A callback function to execute after closing the dialog. The arguments to the
34539 function will be btn (the name of the button that was clicked, if applicable,
34540 e.g. "ok"), and text (the value of the active text field, if applicable).
34541 Progress and wait dialogs will ignore this option since they do not respond to
34542 user actions and can only be closed programmatically, so any required function
34543 should be called by the same code after it closes the dialog.
34544 icon String A CSS class that provides a background image to be used as an icon for
34545 the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
34546 maxWidth Number The maximum width in pixels of the message box (defaults to 600)
34547 minWidth Number The minimum width in pixels of the message box (defaults to 100)
34548 modal Boolean False to allow user interaction with the page while the message box is
34549 displayed (defaults to true)
34550 msg String A string that will replace the existing message box body text (defaults
34551 to the XHTML-compliant non-breaking space character ' ')
34552 multiline Boolean True to prompt the user to enter multi-line text (defaults to false)
34553 progress Boolean True to display a progress bar (defaults to false)
34554 progressText String The text to display inside the progress bar if progress = true (defaults to '')
34555 prompt Boolean True to prompt the user to enter single-line text (defaults to false)
34556 proxyDrag Boolean True to display a lightweight proxy while dragging (defaults to false)
34557 title String The title text
34558 value String The string value to set into the active textbox element if displayed
34559 wait Boolean True to display a progress bar (defaults to false)
34560 width Number The width of the dialog in pixels
34567 msg: 'Please enter your address:',
34569 buttons: Roo.MessageBox.OKCANCEL,
34572 animEl: 'addAddressBtn'
34575 * @param {Object} config Configuration options
34576 * @return {Roo.MessageBox} This message box
34578 show : function(options)
34581 // this causes nightmares if you show one dialog after another
34582 // especially on callbacks..
34584 if(this.isVisible()){
34587 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
34588 Roo.log("Old Dialog Message:" + msgEl.innerHTML );
34589 Roo.log("New Dialog Message:" + options.msg )
34590 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
34591 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
34594 var d = this.getDialog();
34596 d.setTitle(opt.title || " ");
34597 d.close.setDisplayed(opt.closable !== false);
34598 activeTextEl = textboxEl;
34599 opt.prompt = opt.prompt || (opt.multiline ? true : false);
34604 textareaEl.setHeight(typeof opt.multiline == "number" ?
34605 opt.multiline : this.defaultTextHeight);
34606 activeTextEl = textareaEl;
34615 progressEl.setDisplayed(opt.progress === true);
34616 this.updateProgress(0);
34617 activeTextEl.dom.value = opt.value || "";
34619 dlg.setDefaultButton(activeTextEl);
34621 var bs = opt.buttons;
34624 db = buttons["ok"];
34625 }else if(bs && bs.yes){
34626 db = buttons["yes"];
34628 dlg.setDefaultButton(db);
34630 bwidth = updateButtons(opt.buttons);
34631 this.updateText(opt.msg);
34633 d.el.addClass(opt.cls);
34635 d.proxyDrag = opt.proxyDrag === true;
34636 d.modal = opt.modal !== false;
34637 d.mask = opt.modal !== false ? mask : false;
34638 if(!d.isVisible()){
34639 // force it to the end of the z-index stack so it gets a cursor in FF
34640 document.body.appendChild(dlg.el.dom);
34641 d.animateTarget = null;
34642 d.show(options.animEl);
34648 * Displays a message box with a progress bar. This message box has no buttons and is not closeable by
34649 * the user. You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
34650 * and closing the message box when the process is complete.
34651 * @param {String} title The title bar text
34652 * @param {String} msg The message box body text
34653 * @return {Roo.MessageBox} This message box
34655 progress : function(title, msg){
34662 minWidth: this.minProgressWidth,
34669 * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
34670 * If a callback function is passed it will be called after the user clicks the button, and the
34671 * id of the button that was clicked will be passed as the only parameter to the callback
34672 * (could also be the top-right close button).
34673 * @param {String} title The title bar text
34674 * @param {String} msg The message box body text
34675 * @param {Function} fn (optional) The callback function invoked after the message box is closed
34676 * @param {Object} scope (optional) The scope of the callback function
34677 * @return {Roo.MessageBox} This message box
34679 alert : function(title, msg, fn, scope){
34692 * Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
34693 * interaction while waiting for a long-running process to complete that does not have defined intervals.
34694 * You are responsible for closing the message box when the process is complete.
34695 * @param {String} msg The message box body text
34696 * @param {String} title (optional) The title bar text
34697 * @return {Roo.MessageBox} This message box
34699 wait : function(msg, title){
34710 waitTimer = Roo.TaskMgr.start({
34712 Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
34720 * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
34721 * If a callback function is passed it will be called after the user clicks either button, and the id of the
34722 * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
34723 * @param {String} title The title bar text
34724 * @param {String} msg The message box body text
34725 * @param {Function} fn (optional) The callback function invoked after the message box is closed
34726 * @param {Object} scope (optional) The scope of the callback function
34727 * @return {Roo.MessageBox} This message box
34729 confirm : function(title, msg, fn, scope){
34733 buttons: this.YESNO,
34742 * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
34743 * JavaScript's Window.prompt). The prompt can be a single-line or multi-line textbox. If a callback function
34744 * is passed it will be called after the user clicks either button, and the id of the button that was clicked
34745 * (could also be the top-right close button) and the text that was entered will be passed as the two
34746 * parameters to the callback.
34747 * @param {String} title The title bar text
34748 * @param {String} msg The message box body text
34749 * @param {Function} fn (optional) The callback function invoked after the message box is closed
34750 * @param {Object} scope (optional) The scope of the callback function
34751 * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
34752 * property, or the height in pixels to create the textbox (defaults to false / single-line)
34753 * @return {Roo.MessageBox} This message box
34755 prompt : function(title, msg, fn, scope, multiline){
34759 buttons: this.OKCANCEL,
34764 multiline: multiline,
34771 * Button config that displays a single OK button
34776 * Button config that displays Yes and No buttons
34779 YESNO : {yes:true, no:true},
34781 * Button config that displays OK and Cancel buttons
34784 OKCANCEL : {ok:true, cancel:true},
34786 * Button config that displays Yes, No and Cancel buttons
34789 YESNOCANCEL : {yes:true, no:true, cancel:true},
34792 * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
34795 defaultTextHeight : 75,
34797 * The maximum width in pixels of the message box (defaults to 600)
34802 * The minimum width in pixels of the message box (defaults to 100)
34807 * The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
34808 * for setting a different minimum width than text-only dialogs may need (defaults to 250)
34811 minProgressWidth : 250,
34813 * An object containing the default button text strings that can be overriden for localized language support.
34814 * Supported properties are: ok, cancel, yes and no.
34815 * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
34828 * Shorthand for {@link Roo.MessageBox}
34830 Roo.Msg = Roo.MessageBox;/*
34832 * Ext JS Library 1.1.1
34833 * Copyright(c) 2006-2007, Ext JS, LLC.
34835 * Originally Released Under LGPL - original licence link has changed is not relivant.
34838 * <script type="text/javascript">
34841 * @class Roo.QuickTips
34842 * Provides attractive and customizable tooltips for any element.
34845 Roo.QuickTips = function(){
34846 var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
34847 var ce, bd, xy, dd;
34848 var visible = false, disabled = true, inited = false;
34849 var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
34851 var onOver = function(e){
34855 var t = e.getTarget();
34856 if(!t || t.nodeType !== 1 || t == document || t == document.body){
34859 if(ce && t == ce.el){
34860 clearTimeout(hideProc);
34863 if(t && tagEls[t.id]){
34864 tagEls[t.id].el = t;
34865 showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
34868 var ttp, et = Roo.fly(t);
34869 var ns = cfg.namespace;
34870 if(tm.interceptTitles && t.title){
34873 t.removeAttribute("title");
34874 e.preventDefault();
34876 ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
34879 showProc = show.defer(tm.showDelay, tm, [{
34881 text: ttp.replace(/\\n/g,'<br/>'),
34882 width: et.getAttributeNS(ns, cfg.width),
34883 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
34884 title: et.getAttributeNS(ns, cfg.title),
34885 cls: et.getAttributeNS(ns, cfg.cls)
34890 var onOut = function(e){
34891 clearTimeout(showProc);
34892 var t = e.getTarget();
34893 if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
34894 hideProc = setTimeout(hide, tm.hideDelay);
34898 var onMove = function(e){
34904 if(tm.trackMouse && ce){
34909 var onDown = function(e){
34910 clearTimeout(showProc);
34911 clearTimeout(hideProc);
34913 if(tm.hideOnClick){
34916 tm.enable.defer(100, tm);
34921 var getPad = function(){
34922 return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
34925 var show = function(o){
34929 clearTimeout(dismissProc);
34931 if(removeCls){ // in case manually hidden
34932 el.removeClass(removeCls);
34936 el.addClass(ce.cls);
34937 removeCls = ce.cls;
34940 tipTitle.update(ce.title);
34943 tipTitle.update('');
34946 el.dom.style.width = tm.maxWidth+'px';
34947 //tipBody.dom.style.width = '';
34948 tipBodyText.update(o.text);
34949 var p = getPad(), w = ce.width;
34951 var td = tipBodyText.dom;
34952 var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
34953 if(aw > tm.maxWidth){
34955 }else if(aw < tm.minWidth){
34961 //tipBody.setWidth(w);
34962 el.setWidth(parseInt(w, 10) + p);
34963 if(ce.autoHide === false){
34964 close.setDisplayed(true);
34969 close.setDisplayed(false);
34975 el.avoidY = xy[1]-18;
34980 el.setStyle("visibility", "visible");
34981 el.fadeIn({callback: afterShow});
34987 var afterShow = function(){
34991 if(tm.autoDismiss && ce.autoHide !== false){
34992 dismissProc = setTimeout(hide, tm.autoDismissDelay);
34997 var hide = function(noanim){
34998 clearTimeout(dismissProc);
34999 clearTimeout(hideProc);
35001 if(el.isVisible()){
35003 if(noanim !== true && tm.animate){
35004 el.fadeOut({callback: afterHide});
35011 var afterHide = function(){
35014 el.removeClass(removeCls);
35021 * @cfg {Number} minWidth
35022 * The minimum width of the quick tip (defaults to 40)
35026 * @cfg {Number} maxWidth
35027 * The maximum width of the quick tip (defaults to 300)
35031 * @cfg {Boolean} interceptTitles
35032 * True to automatically use the element's DOM title value if available (defaults to false)
35034 interceptTitles : false,
35036 * @cfg {Boolean} trackMouse
35037 * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
35039 trackMouse : false,
35041 * @cfg {Boolean} hideOnClick
35042 * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
35044 hideOnClick : true,
35046 * @cfg {Number} showDelay
35047 * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
35051 * @cfg {Number} hideDelay
35052 * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
35056 * @cfg {Boolean} autoHide
35057 * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
35058 * Used in conjunction with hideDelay.
35063 * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
35064 * (defaults to true). Used in conjunction with autoDismissDelay.
35066 autoDismiss : true,
35069 * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
35071 autoDismissDelay : 5000,
35073 * @cfg {Boolean} animate
35074 * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
35079 * @cfg {String} title
35080 * Title text to display (defaults to ''). This can be any valid HTML markup.
35084 * @cfg {String} text
35085 * Body text to display (defaults to ''). This can be any valid HTML markup.
35089 * @cfg {String} cls
35090 * A CSS class to apply to the base quick tip element (defaults to '').
35094 * @cfg {Number} width
35095 * Width in pixels of the quick tip (defaults to auto). Width will be ignored if it exceeds the bounds of
35096 * minWidth or maxWidth.
35101 * Initialize and enable QuickTips for first use. This should be called once before the first attempt to access
35102 * or display QuickTips in a page.
35105 tm = Roo.QuickTips;
35106 cfg = tm.tagConfig;
35108 if(!Roo.isReady){ // allow calling of init() before onReady
35109 Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
35112 el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
35113 el.fxDefaults = {stopFx: true};
35114 // maximum custom styling
35115 //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>');
35116 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>');
35117 tipTitle = el.child('h3');
35118 tipTitle.enableDisplayMode("block");
35119 tipBody = el.child('div.x-tip-bd');
35120 tipBodyText = el.child('div.x-tip-bd-inner');
35121 //bdLeft = el.child('div.x-tip-bd-left');
35122 //bdRight = el.child('div.x-tip-bd-right');
35123 close = el.child('div.x-tip-close');
35124 close.enableDisplayMode("block");
35125 close.on("click", hide);
35126 var d = Roo.get(document);
35127 d.on("mousedown", onDown);
35128 d.on("mouseover", onOver);
35129 d.on("mouseout", onOut);
35130 d.on("mousemove", onMove);
35131 esc = d.addKeyListener(27, hide);
35134 dd = el.initDD("default", null, {
35135 onDrag : function(){
35139 dd.setHandleElId(tipTitle.id);
35148 * Configures a new quick tip instance and assigns it to a target element. The following config options
35151 Property Type Description
35152 ---------- --------------------- ------------------------------------------------------------------------
35153 target Element/String/Array An Element, id or array of ids that this quick tip should be tied to
35155 * @param {Object} config The config object
35157 register : function(config){
35158 var cs = config instanceof Array ? config : arguments;
35159 for(var i = 0, len = cs.length; i < len; i++) {
35161 var target = c.target;
35163 if(target instanceof Array){
35164 for(var j = 0, jlen = target.length; j < jlen; j++){
35165 tagEls[target[j]] = c;
35168 tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
35175 * Removes this quick tip from its element and destroys it.
35176 * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
35178 unregister : function(el){
35179 delete tagEls[Roo.id(el)];
35183 * Enable this quick tip.
35185 enable : function(){
35186 if(inited && disabled){
35188 if(locks.length < 1){
35195 * Disable this quick tip.
35197 disable : function(){
35199 clearTimeout(showProc);
35200 clearTimeout(hideProc);
35201 clearTimeout(dismissProc);
35209 * Returns true if the quick tip is enabled, else false.
35211 isEnabled : function(){
35217 namespace : "roo", // was ext?? this may break..
35218 alt_namespace : "ext",
35219 attribute : "qtip",
35229 // backwards compat
35230 Roo.QuickTips.tips = Roo.QuickTips.register;/*
35232 * Ext JS Library 1.1.1
35233 * Copyright(c) 2006-2007, Ext JS, LLC.
35235 * Originally Released Under LGPL - original licence link has changed is not relivant.
35238 * <script type="text/javascript">
35243 * @class Roo.tree.TreePanel
35244 * @extends Roo.data.Tree
35245 * @cfg {Roo.tree.TreeNode} root The root node
35246 * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
35247 * @cfg {Boolean} lines false to disable tree lines (defaults to true)
35248 * @cfg {Boolean} enableDD true to enable drag and drop
35249 * @cfg {Boolean} enableDrag true to enable just drag
35250 * @cfg {Boolean} enableDrop true to enable just drop
35251 * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
35252 * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
35253 * @cfg {String} ddGroup The DD group this TreePanel belongs to
35254 * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
35255 * @cfg {Boolean} ddScroll true to enable YUI body scrolling
35256 * @cfg {Boolean} containerScroll true to register this container with ScrollManager
35257 * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
35258 * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
35259 * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
35260 * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
35261 * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
35262 * @cfg {Roo.tree.TreeLoader} loader A TreeLoader for use with this TreePanel
35263 * @cfg {Roo.tree.TreeEditor} editor The TreeEditor to display when clicked.
35264 * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
35265 * @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>
35266 * @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>
35269 * @param {String/HTMLElement/Element} el The container element
35270 * @param {Object} config
35272 Roo.tree.TreePanel = function(el, config){
35274 var loader = false;
35276 root = config.root;
35277 delete config.root;
35279 if (config.loader) {
35280 loader = config.loader;
35281 delete config.loader;
35284 Roo.apply(this, config);
35285 Roo.tree.TreePanel.superclass.constructor.call(this);
35286 this.el = Roo.get(el);
35287 this.el.addClass('x-tree');
35288 //console.log(root);
35290 this.setRootNode( Roo.factory(root, Roo.tree));
35293 this.loader = Roo.factory(loader, Roo.tree);
35296 * Read-only. The id of the container element becomes this TreePanel's id.
35298 this.id = this.el.id;
35301 * @event beforeload
35302 * Fires before a node is loaded, return false to cancel
35303 * @param {Node} node The node being loaded
35305 "beforeload" : true,
35308 * Fires when a node is loaded
35309 * @param {Node} node The node that was loaded
35313 * @event textchange
35314 * Fires when the text for a node is changed
35315 * @param {Node} node The node
35316 * @param {String} text The new text
35317 * @param {String} oldText The old text
35319 "textchange" : true,
35321 * @event beforeexpand
35322 * Fires before a node is expanded, return false to cancel.
35323 * @param {Node} node The node
35324 * @param {Boolean} deep
35325 * @param {Boolean} anim
35327 "beforeexpand" : true,
35329 * @event beforecollapse
35330 * Fires before a node is collapsed, return false to cancel.
35331 * @param {Node} node The node
35332 * @param {Boolean} deep
35333 * @param {Boolean} anim
35335 "beforecollapse" : true,
35338 * Fires when a node is expanded
35339 * @param {Node} node The node
35343 * @event disabledchange
35344 * Fires when the disabled status of a node changes
35345 * @param {Node} node The node
35346 * @param {Boolean} disabled
35348 "disabledchange" : true,
35351 * Fires when a node is collapsed
35352 * @param {Node} node The node
35356 * @event beforeclick
35357 * Fires before click processing on a node. Return false to cancel the default action.
35358 * @param {Node} node The node
35359 * @param {Roo.EventObject} e The event object
35361 "beforeclick":true,
35363 * @event checkchange
35364 * Fires when a node with a checkbox's checked property changes
35365 * @param {Node} this This node
35366 * @param {Boolean} checked
35368 "checkchange":true,
35371 * Fires when a node is clicked
35372 * @param {Node} node The node
35373 * @param {Roo.EventObject} e The event object
35378 * Fires when a node is double clicked
35379 * @param {Node} node The node
35380 * @param {Roo.EventObject} e The event object
35384 * @event contextmenu
35385 * Fires when a node is right clicked
35386 * @param {Node} node The node
35387 * @param {Roo.EventObject} e The event object
35389 "contextmenu":true,
35391 * @event beforechildrenrendered
35392 * Fires right before the child nodes for a node are rendered
35393 * @param {Node} node The node
35395 "beforechildrenrendered":true,
35398 * Fires when a node starts being dragged
35399 * @param {Roo.tree.TreePanel} this
35400 * @param {Roo.tree.TreeNode} node
35401 * @param {event} e The raw browser event
35403 "startdrag" : true,
35406 * Fires when a drag operation is complete
35407 * @param {Roo.tree.TreePanel} this
35408 * @param {Roo.tree.TreeNode} node
35409 * @param {event} e The raw browser event
35414 * Fires when a dragged node is dropped on a valid DD target
35415 * @param {Roo.tree.TreePanel} this
35416 * @param {Roo.tree.TreeNode} node
35417 * @param {DD} dd The dd it was dropped on
35418 * @param {event} e The raw browser event
35422 * @event beforenodedrop
35423 * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
35424 * passed to handlers has the following properties:<br />
35425 * <ul style="padding:5px;padding-left:16px;">
35426 * <li>tree - The TreePanel</li>
35427 * <li>target - The node being targeted for the drop</li>
35428 * <li>data - The drag data from the drag source</li>
35429 * <li>point - The point of the drop - append, above or below</li>
35430 * <li>source - The drag source</li>
35431 * <li>rawEvent - Raw mouse event</li>
35432 * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
35433 * to be inserted by setting them on this object.</li>
35434 * <li>cancel - Set this to true to cancel the drop.</li>
35436 * @param {Object} dropEvent
35438 "beforenodedrop" : true,
35441 * Fires after a DD object is dropped on a node in this tree. The dropEvent
35442 * passed to handlers has the following properties:<br />
35443 * <ul style="padding:5px;padding-left:16px;">
35444 * <li>tree - The TreePanel</li>
35445 * <li>target - The node being targeted for the drop</li>
35446 * <li>data - The drag data from the drag source</li>
35447 * <li>point - The point of the drop - append, above or below</li>
35448 * <li>source - The drag source</li>
35449 * <li>rawEvent - Raw mouse event</li>
35450 * <li>dropNode - Dropped node(s).</li>
35452 * @param {Object} dropEvent
35456 * @event nodedragover
35457 * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
35458 * passed to handlers has the following properties:<br />
35459 * <ul style="padding:5px;padding-left:16px;">
35460 * <li>tree - The TreePanel</li>
35461 * <li>target - The node being targeted for the drop</li>
35462 * <li>data - The drag data from the drag source</li>
35463 * <li>point - The point of the drop - append, above or below</li>
35464 * <li>source - The drag source</li>
35465 * <li>rawEvent - Raw mouse event</li>
35466 * <li>dropNode - Drop node(s) provided by the source.</li>
35467 * <li>cancel - Set this to true to signal drop not allowed.</li>
35469 * @param {Object} dragOverEvent
35471 "nodedragover" : true,
35473 * @event appendnode
35474 * Fires when append node to the tree
35475 * @param {Roo.tree.TreePanel} this
35476 * @param {Roo.tree.TreeNode} node
35477 * @param {Number} index The index of the newly appended node
35479 "appendnode" : true
35482 if(this.singleExpand){
35483 this.on("beforeexpand", this.restrictExpand, this);
35486 this.editor.tree = this;
35487 this.editor = Roo.factory(this.editor, Roo.tree);
35490 if (this.selModel) {
35491 this.selModel = Roo.factory(this.selModel, Roo.tree);
35495 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
35496 rootVisible : true,
35497 animate: Roo.enableFx,
35500 hlDrop : Roo.enableFx,
35504 rendererTip: false,
35506 restrictExpand : function(node){
35507 var p = node.parentNode;
35509 if(p.expandedChild && p.expandedChild.parentNode == p){
35510 p.expandedChild.collapse();
35512 p.expandedChild = node;
35516 // private override
35517 setRootNode : function(node){
35518 Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
35519 if(!this.rootVisible){
35520 node.ui = new Roo.tree.RootTreeNodeUI(node);
35526 * Returns the container element for this TreePanel
35528 getEl : function(){
35533 * Returns the default TreeLoader for this TreePanel
35535 getLoader : function(){
35536 return this.loader;
35542 expandAll : function(){
35543 this.root.expand(true);
35547 * Collapse all nodes
35549 collapseAll : function(){
35550 this.root.collapse(true);
35554 * Returns the selection model used by this TreePanel
35556 getSelectionModel : function(){
35557 if(!this.selModel){
35558 this.selModel = new Roo.tree.DefaultSelectionModel();
35560 return this.selModel;
35564 * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
35565 * @param {String} attribute (optional) Defaults to null (return the actual nodes)
35566 * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
35569 getChecked : function(a, startNode){
35570 startNode = startNode || this.root;
35572 var f = function(){
35573 if(this.attributes.checked){
35574 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
35577 startNode.cascade(f);
35582 * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
35583 * @param {String} path
35584 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
35585 * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
35586 * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
35588 expandPath : function(path, attr, callback){
35589 attr = attr || "id";
35590 var keys = path.split(this.pathSeparator);
35591 var curNode = this.root;
35592 if(curNode.attributes[attr] != keys[1]){ // invalid root
35594 callback(false, null);
35599 var f = function(){
35600 if(++index == keys.length){
35602 callback(true, curNode);
35606 var c = curNode.findChild(attr, keys[index]);
35609 callback(false, curNode);
35614 c.expand(false, false, f);
35616 curNode.expand(false, false, f);
35620 * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
35621 * @param {String} path
35622 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
35623 * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
35624 * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
35626 selectPath : function(path, attr, callback){
35627 attr = attr || "id";
35628 var keys = path.split(this.pathSeparator);
35629 var v = keys.pop();
35630 if(keys.length > 0){
35631 var f = function(success, node){
35632 if(success && node){
35633 var n = node.findChild(attr, v);
35639 }else if(callback){
35640 callback(false, n);
35644 callback(false, n);
35648 this.expandPath(keys.join(this.pathSeparator), attr, f);
35650 this.root.select();
35652 callback(true, this.root);
35657 getTreeEl : function(){
35662 * Trigger rendering of this TreePanel
35664 render : function(){
35665 if (this.innerCt) {
35666 return this; // stop it rendering more than once!!
35669 this.innerCt = this.el.createChild({tag:"ul",
35670 cls:"x-tree-root-ct " +
35671 (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
35673 if(this.containerScroll){
35674 Roo.dd.ScrollManager.register(this.el);
35676 if((this.enableDD || this.enableDrop) && !this.dropZone){
35678 * The dropZone used by this tree if drop is enabled
35679 * @type Roo.tree.TreeDropZone
35681 this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
35682 ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
35685 if((this.enableDD || this.enableDrag) && !this.dragZone){
35687 * The dragZone used by this tree if drag is enabled
35688 * @type Roo.tree.TreeDragZone
35690 this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
35691 ddGroup: this.ddGroup || "TreeDD",
35692 scroll: this.ddScroll
35695 this.getSelectionModel().init(this);
35697 Roo.log("ROOT not set in tree");
35700 this.root.render();
35701 if(!this.rootVisible){
35702 this.root.renderChildren();
35708 * Ext JS Library 1.1.1
35709 * Copyright(c) 2006-2007, Ext JS, LLC.
35711 * Originally Released Under LGPL - original licence link has changed is not relivant.
35714 * <script type="text/javascript">
35719 * @class Roo.tree.DefaultSelectionModel
35720 * @extends Roo.util.Observable
35721 * The default single selection for a TreePanel.
35722 * @param {Object} cfg Configuration
35724 Roo.tree.DefaultSelectionModel = function(cfg){
35725 this.selNode = null;
35731 * @event selectionchange
35732 * Fires when the selected node changes
35733 * @param {DefaultSelectionModel} this
35734 * @param {TreeNode} node the new selection
35736 "selectionchange" : true,
35739 * @event beforeselect
35740 * Fires before the selected node changes, return false to cancel the change
35741 * @param {DefaultSelectionModel} this
35742 * @param {TreeNode} node the new selection
35743 * @param {TreeNode} node the old selection
35745 "beforeselect" : true
35748 Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
35751 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
35752 init : function(tree){
35754 tree.getTreeEl().on("keydown", this.onKeyDown, this);
35755 tree.on("click", this.onNodeClick, this);
35758 onNodeClick : function(node, e){
35759 if (e.ctrlKey && this.selNode == node) {
35760 this.unselect(node);
35768 * @param {TreeNode} node The node to select
35769 * @return {TreeNode} The selected node
35771 select : function(node){
35772 var last = this.selNode;
35773 if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
35775 last.ui.onSelectedChange(false);
35777 this.selNode = node;
35778 node.ui.onSelectedChange(true);
35779 this.fireEvent("selectionchange", this, node, last);
35786 * @param {TreeNode} node The node to unselect
35788 unselect : function(node){
35789 if(this.selNode == node){
35790 this.clearSelections();
35795 * Clear all selections
35797 clearSelections : function(){
35798 var n = this.selNode;
35800 n.ui.onSelectedChange(false);
35801 this.selNode = null;
35802 this.fireEvent("selectionchange", this, null);
35808 * Get the selected node
35809 * @return {TreeNode} The selected node
35811 getSelectedNode : function(){
35812 return this.selNode;
35816 * Returns true if the node is selected
35817 * @param {TreeNode} node The node to check
35818 * @return {Boolean}
35820 isSelected : function(node){
35821 return this.selNode == node;
35825 * Selects the node above the selected node in the tree, intelligently walking the nodes
35826 * @return TreeNode The new selection
35828 selectPrevious : function(){
35829 var s = this.selNode || this.lastSelNode;
35833 var ps = s.previousSibling;
35835 if(!ps.isExpanded() || ps.childNodes.length < 1){
35836 return this.select(ps);
35838 var lc = ps.lastChild;
35839 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
35842 return this.select(lc);
35844 } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
35845 return this.select(s.parentNode);
35851 * Selects the node above the selected node in the tree, intelligently walking the nodes
35852 * @return TreeNode The new selection
35854 selectNext : function(){
35855 var s = this.selNode || this.lastSelNode;
35859 if(s.firstChild && s.isExpanded()){
35860 return this.select(s.firstChild);
35861 }else if(s.nextSibling){
35862 return this.select(s.nextSibling);
35863 }else if(s.parentNode){
35865 s.parentNode.bubble(function(){
35866 if(this.nextSibling){
35867 newS = this.getOwnerTree().selModel.select(this.nextSibling);
35876 onKeyDown : function(e){
35877 var s = this.selNode || this.lastSelNode;
35878 // undesirable, but required
35883 var k = e.getKey();
35891 this.selectPrevious();
35894 e.preventDefault();
35895 if(s.hasChildNodes()){
35896 if(!s.isExpanded()){
35898 }else if(s.firstChild){
35899 this.select(s.firstChild, e);
35904 e.preventDefault();
35905 if(s.hasChildNodes() && s.isExpanded()){
35907 }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
35908 this.select(s.parentNode, e);
35916 * @class Roo.tree.MultiSelectionModel
35917 * @extends Roo.util.Observable
35918 * Multi selection for a TreePanel.
35919 * @param {Object} cfg Configuration
35921 Roo.tree.MultiSelectionModel = function(){
35922 this.selNodes = [];
35926 * @event selectionchange
35927 * Fires when the selected nodes change
35928 * @param {MultiSelectionModel} this
35929 * @param {Array} nodes Array of the selected nodes
35931 "selectionchange" : true
35933 Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
35937 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
35938 init : function(tree){
35940 tree.getTreeEl().on("keydown", this.onKeyDown, this);
35941 tree.on("click", this.onNodeClick, this);
35944 onNodeClick : function(node, e){
35945 this.select(node, e, e.ctrlKey);
35950 * @param {TreeNode} node The node to select
35951 * @param {EventObject} e (optional) An event associated with the selection
35952 * @param {Boolean} keepExisting True to retain existing selections
35953 * @return {TreeNode} The selected node
35955 select : function(node, e, keepExisting){
35956 if(keepExisting !== true){
35957 this.clearSelections(true);
35959 if(this.isSelected(node)){
35960 this.lastSelNode = node;
35963 this.selNodes.push(node);
35964 this.selMap[node.id] = node;
35965 this.lastSelNode = node;
35966 node.ui.onSelectedChange(true);
35967 this.fireEvent("selectionchange", this, this.selNodes);
35973 * @param {TreeNode} node The node to unselect
35975 unselect : function(node){
35976 if(this.selMap[node.id]){
35977 node.ui.onSelectedChange(false);
35978 var sn = this.selNodes;
35981 index = sn.indexOf(node);
35983 for(var i = 0, len = sn.length; i < len; i++){
35991 this.selNodes.splice(index, 1);
35993 delete this.selMap[node.id];
35994 this.fireEvent("selectionchange", this, this.selNodes);
35999 * Clear all selections
36001 clearSelections : function(suppressEvent){
36002 var sn = this.selNodes;
36004 for(var i = 0, len = sn.length; i < len; i++){
36005 sn[i].ui.onSelectedChange(false);
36007 this.selNodes = [];
36009 if(suppressEvent !== true){
36010 this.fireEvent("selectionchange", this, this.selNodes);
36016 * Returns true if the node is selected
36017 * @param {TreeNode} node The node to check
36018 * @return {Boolean}
36020 isSelected : function(node){
36021 return this.selMap[node.id] ? true : false;
36025 * Returns an array of the selected nodes
36028 getSelectedNodes : function(){
36029 return this.selNodes;
36032 onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
36034 selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
36036 selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
36039 * Ext JS Library 1.1.1
36040 * Copyright(c) 2006-2007, Ext JS, LLC.
36042 * Originally Released Under LGPL - original licence link has changed is not relivant.
36045 * <script type="text/javascript">
36049 * @class Roo.tree.TreeNode
36050 * @extends Roo.data.Node
36051 * @cfg {String} text The text for this node
36052 * @cfg {Boolean} expanded true to start the node expanded
36053 * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
36054 * @cfg {Boolean} allowDrop false if this node cannot be drop on
36055 * @cfg {Boolean} disabled true to start the node disabled
36056 * @cfg {String} icon The path to an icon for the node. The preferred way to do this
36057 * is to use the cls or iconCls attributes and add the icon via a CSS background image.
36058 * @cfg {String} cls A css class to be added to the node
36059 * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
36060 * @cfg {String} href URL of the link used for the node (defaults to #)
36061 * @cfg {String} hrefTarget target frame for the link
36062 * @cfg {String} qtip An Ext QuickTip for the node
36063 * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
36064 * @cfg {Boolean} singleClickExpand True for single click expand on this node
36065 * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
36066 * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
36067 * (defaults to undefined with no checkbox rendered)
36069 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
36071 Roo.tree.TreeNode = function(attributes){
36072 attributes = attributes || {};
36073 if(typeof attributes == "string"){
36074 attributes = {text: attributes};
36076 this.childrenRendered = false;
36077 this.rendered = false;
36078 Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
36079 this.expanded = attributes.expanded === true;
36080 this.isTarget = attributes.isTarget !== false;
36081 this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
36082 this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
36085 * Read-only. The text for this node. To change it use setText().
36088 this.text = attributes.text;
36090 * True if this node is disabled.
36093 this.disabled = attributes.disabled === true;
36097 * @event textchange
36098 * Fires when the text for this node is changed
36099 * @param {Node} this This node
36100 * @param {String} text The new text
36101 * @param {String} oldText The old text
36103 "textchange" : true,
36105 * @event beforeexpand
36106 * Fires before this node is expanded, return false to cancel.
36107 * @param {Node} this This node
36108 * @param {Boolean} deep
36109 * @param {Boolean} anim
36111 "beforeexpand" : true,
36113 * @event beforecollapse
36114 * Fires before this node is collapsed, return false to cancel.
36115 * @param {Node} this This node
36116 * @param {Boolean} deep
36117 * @param {Boolean} anim
36119 "beforecollapse" : true,
36122 * Fires when this node is expanded
36123 * @param {Node} this This node
36127 * @event disabledchange
36128 * Fires when the disabled status of this node changes
36129 * @param {Node} this This node
36130 * @param {Boolean} disabled
36132 "disabledchange" : true,
36135 * Fires when this node is collapsed
36136 * @param {Node} this This node
36140 * @event beforeclick
36141 * Fires before click processing. Return false to cancel the default action.
36142 * @param {Node} this This node
36143 * @param {Roo.EventObject} e The event object
36145 "beforeclick":true,
36147 * @event checkchange
36148 * Fires when a node with a checkbox's checked property changes
36149 * @param {Node} this This node
36150 * @param {Boolean} checked
36152 "checkchange":true,
36155 * Fires when this node is clicked
36156 * @param {Node} this This node
36157 * @param {Roo.EventObject} e The event object
36162 * Fires when this node is double clicked
36163 * @param {Node} this This node
36164 * @param {Roo.EventObject} e The event object
36168 * @event contextmenu
36169 * Fires when this node is right clicked
36170 * @param {Node} this This node
36171 * @param {Roo.EventObject} e The event object
36173 "contextmenu":true,
36175 * @event beforechildrenrendered
36176 * Fires right before the child nodes for this node are rendered
36177 * @param {Node} this This node
36179 "beforechildrenrendered":true
36182 var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
36185 * Read-only. The UI for this node
36188 this.ui = new uiClass(this);
36190 // finally support items[]
36191 if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
36196 Roo.each(this.attributes.items, function(c) {
36197 this.appendChild(Roo.factory(c,Roo.Tree));
36199 delete this.attributes.items;
36204 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
36205 preventHScroll: true,
36207 * Returns true if this node is expanded
36208 * @return {Boolean}
36210 isExpanded : function(){
36211 return this.expanded;
36215 * Returns the UI object for this node
36216 * @return {TreeNodeUI}
36218 getUI : function(){
36222 // private override
36223 setFirstChild : function(node){
36224 var of = this.firstChild;
36225 Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
36226 if(this.childrenRendered && of && node != of){
36227 of.renderIndent(true, true);
36230 this.renderIndent(true, true);
36234 // private override
36235 setLastChild : function(node){
36236 var ol = this.lastChild;
36237 Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
36238 if(this.childrenRendered && ol && node != ol){
36239 ol.renderIndent(true, true);
36242 this.renderIndent(true, true);
36246 // these methods are overridden to provide lazy rendering support
36247 // private override
36248 appendChild : function()
36250 var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
36251 if(node && this.childrenRendered){
36254 this.ui.updateExpandIcon();
36258 // private override
36259 removeChild : function(node){
36260 this.ownerTree.getSelectionModel().unselect(node);
36261 Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
36262 // if it's been rendered remove dom node
36263 if(this.childrenRendered){
36266 if(this.childNodes.length < 1){
36267 this.collapse(false, false);
36269 this.ui.updateExpandIcon();
36271 if(!this.firstChild) {
36272 this.childrenRendered = false;
36277 // private override
36278 insertBefore : function(node, refNode){
36279 var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
36280 if(newNode && refNode && this.childrenRendered){
36283 this.ui.updateExpandIcon();
36288 * Sets the text for this node
36289 * @param {String} text
36291 setText : function(text){
36292 var oldText = this.text;
36294 this.attributes.text = text;
36295 if(this.rendered){ // event without subscribing
36296 this.ui.onTextChange(this, text, oldText);
36298 this.fireEvent("textchange", this, text, oldText);
36302 * Triggers selection of this node
36304 select : function(){
36305 this.getOwnerTree().getSelectionModel().select(this);
36309 * Triggers deselection of this node
36311 unselect : function(){
36312 this.getOwnerTree().getSelectionModel().unselect(this);
36316 * Returns true if this node is selected
36317 * @return {Boolean}
36319 isSelected : function(){
36320 return this.getOwnerTree().getSelectionModel().isSelected(this);
36324 * Expand this node.
36325 * @param {Boolean} deep (optional) True to expand all children as well
36326 * @param {Boolean} anim (optional) false to cancel the default animation
36327 * @param {Function} callback (optional) A callback to be called when
36328 * expanding this node completes (does not wait for deep expand to complete).
36329 * Called with 1 parameter, this node.
36331 expand : function(deep, anim, callback){
36332 if(!this.expanded){
36333 if(this.fireEvent("beforeexpand", this, deep, anim) === false){
36336 if(!this.childrenRendered){
36337 this.renderChildren();
36339 this.expanded = true;
36341 if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
36342 this.ui.animExpand(function(){
36343 this.fireEvent("expand", this);
36344 if(typeof callback == "function"){
36348 this.expandChildNodes(true);
36350 }.createDelegate(this));
36354 this.fireEvent("expand", this);
36355 if(typeof callback == "function"){
36360 if(typeof callback == "function"){
36365 this.expandChildNodes(true);
36369 isHiddenRoot : function(){
36370 return this.isRoot && !this.getOwnerTree().rootVisible;
36374 * Collapse this node.
36375 * @param {Boolean} deep (optional) True to collapse all children as well
36376 * @param {Boolean} anim (optional) false to cancel the default animation
36378 collapse : function(deep, anim){
36379 if(this.expanded && !this.isHiddenRoot()){
36380 if(this.fireEvent("beforecollapse", this, deep, anim) === false){
36383 this.expanded = false;
36384 if((this.getOwnerTree().animate && anim !== false) || anim){
36385 this.ui.animCollapse(function(){
36386 this.fireEvent("collapse", this);
36388 this.collapseChildNodes(true);
36390 }.createDelegate(this));
36393 this.ui.collapse();
36394 this.fireEvent("collapse", this);
36398 var cs = this.childNodes;
36399 for(var i = 0, len = cs.length; i < len; i++) {
36400 cs[i].collapse(true, false);
36406 delayedExpand : function(delay){
36407 if(!this.expandProcId){
36408 this.expandProcId = this.expand.defer(delay, this);
36413 cancelExpand : function(){
36414 if(this.expandProcId){
36415 clearTimeout(this.expandProcId);
36417 this.expandProcId = false;
36421 * Toggles expanded/collapsed state of the node
36423 toggle : function(){
36432 * Ensures all parent nodes are expanded
36434 ensureVisible : function(callback){
36435 var tree = this.getOwnerTree();
36436 tree.expandPath(this.parentNode.getPath(), false, function(){
36437 tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
36438 Roo.callback(callback);
36439 }.createDelegate(this));
36443 * Expand all child nodes
36444 * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
36446 expandChildNodes : function(deep){
36447 var cs = this.childNodes;
36448 for(var i = 0, len = cs.length; i < len; i++) {
36449 cs[i].expand(deep);
36454 * Collapse all child nodes
36455 * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
36457 collapseChildNodes : function(deep){
36458 var cs = this.childNodes;
36459 for(var i = 0, len = cs.length; i < len; i++) {
36460 cs[i].collapse(deep);
36465 * Disables this node
36467 disable : function(){
36468 this.disabled = true;
36470 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
36471 this.ui.onDisableChange(this, true);
36473 this.fireEvent("disabledchange", this, true);
36477 * Enables this node
36479 enable : function(){
36480 this.disabled = false;
36481 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
36482 this.ui.onDisableChange(this, false);
36484 this.fireEvent("disabledchange", this, false);
36488 renderChildren : function(suppressEvent){
36489 if(suppressEvent !== false){
36490 this.fireEvent("beforechildrenrendered", this);
36492 var cs = this.childNodes;
36493 for(var i = 0, len = cs.length; i < len; i++){
36494 cs[i].render(true);
36496 this.childrenRendered = true;
36500 sort : function(fn, scope){
36501 Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
36502 if(this.childrenRendered){
36503 var cs = this.childNodes;
36504 for(var i = 0, len = cs.length; i < len; i++){
36505 cs[i].render(true);
36511 render : function(bulkRender){
36512 this.ui.render(bulkRender);
36513 if(!this.rendered){
36514 this.rendered = true;
36516 this.expanded = false;
36517 this.expand(false, false);
36523 renderIndent : function(deep, refresh){
36525 this.ui.childIndent = null;
36527 this.ui.renderIndent();
36528 if(deep === true && this.childrenRendered){
36529 var cs = this.childNodes;
36530 for(var i = 0, len = cs.length; i < len; i++){
36531 cs[i].renderIndent(true, refresh);
36537 * Ext JS Library 1.1.1
36538 * Copyright(c) 2006-2007, Ext JS, LLC.
36540 * Originally Released Under LGPL - original licence link has changed is not relivant.
36543 * <script type="text/javascript">
36547 * @class Roo.tree.AsyncTreeNode
36548 * @extends Roo.tree.TreeNode
36549 * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
36551 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
36553 Roo.tree.AsyncTreeNode = function(config){
36554 this.loaded = false;
36555 this.loading = false;
36556 Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
36558 * @event beforeload
36559 * Fires before this node is loaded, return false to cancel
36560 * @param {Node} this This node
36562 this.addEvents({'beforeload':true, 'load': true});
36565 * Fires when this node is loaded
36566 * @param {Node} this This node
36569 * The loader used by this node (defaults to using the tree's defined loader)
36574 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
36575 expand : function(deep, anim, callback){
36576 if(this.loading){ // if an async load is already running, waiting til it's done
36578 var f = function(){
36579 if(!this.loading){ // done loading
36580 clearInterval(timer);
36581 this.expand(deep, anim, callback);
36583 }.createDelegate(this);
36584 timer = setInterval(f, 200);
36588 if(this.fireEvent("beforeload", this) === false){
36591 this.loading = true;
36592 this.ui.beforeLoad(this);
36593 var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
36595 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
36599 Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
36603 * Returns true if this node is currently loading
36604 * @return {Boolean}
36606 isLoading : function(){
36607 return this.loading;
36610 loadComplete : function(deep, anim, callback){
36611 this.loading = false;
36612 this.loaded = true;
36613 this.ui.afterLoad(this);
36614 this.fireEvent("load", this);
36615 this.expand(deep, anim, callback);
36619 * Returns true if this node has been loaded
36620 * @return {Boolean}
36622 isLoaded : function(){
36623 return this.loaded;
36626 hasChildNodes : function(){
36627 if(!this.isLeaf() && !this.loaded){
36630 return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
36635 * Trigger a reload for this node
36636 * @param {Function} callback
36638 reload : function(callback){
36639 this.collapse(false, false);
36640 while(this.firstChild){
36641 this.removeChild(this.firstChild);
36643 this.childrenRendered = false;
36644 this.loaded = false;
36645 if(this.isHiddenRoot()){
36646 this.expanded = false;
36648 this.expand(false, false, callback);
36652 * Ext JS Library 1.1.1
36653 * Copyright(c) 2006-2007, Ext JS, LLC.
36655 * Originally Released Under LGPL - original licence link has changed is not relivant.
36658 * <script type="text/javascript">
36662 * @class Roo.tree.TreeNodeUI
36664 * @param {Object} node The node to render
36665 * The TreeNode UI implementation is separate from the
36666 * tree implementation. Unless you are customizing the tree UI,
36667 * you should never have to use this directly.
36669 Roo.tree.TreeNodeUI = function(node){
36671 this.rendered = false;
36672 this.animating = false;
36673 this.emptyIcon = Roo.BLANK_IMAGE_URL;
36676 Roo.tree.TreeNodeUI.prototype = {
36677 removeChild : function(node){
36679 this.ctNode.removeChild(node.ui.getEl());
36683 beforeLoad : function(){
36684 this.addClass("x-tree-node-loading");
36687 afterLoad : function(){
36688 this.removeClass("x-tree-node-loading");
36691 onTextChange : function(node, text, oldText){
36693 this.textNode.innerHTML = text;
36697 onDisableChange : function(node, state){
36698 this.disabled = state;
36700 this.addClass("x-tree-node-disabled");
36702 this.removeClass("x-tree-node-disabled");
36706 onSelectedChange : function(state){
36709 this.addClass("x-tree-selected");
36712 this.removeClass("x-tree-selected");
36716 onMove : function(tree, node, oldParent, newParent, index, refNode){
36717 this.childIndent = null;
36719 var targetNode = newParent.ui.getContainer();
36720 if(!targetNode){//target not rendered
36721 this.holder = document.createElement("div");
36722 this.holder.appendChild(this.wrap);
36725 var insertBefore = refNode ? refNode.ui.getEl() : null;
36727 targetNode.insertBefore(this.wrap, insertBefore);
36729 targetNode.appendChild(this.wrap);
36731 this.node.renderIndent(true);
36735 addClass : function(cls){
36737 Roo.fly(this.elNode).addClass(cls);
36741 removeClass : function(cls){
36743 Roo.fly(this.elNode).removeClass(cls);
36747 remove : function(){
36749 this.holder = document.createElement("div");
36750 this.holder.appendChild(this.wrap);
36754 fireEvent : function(){
36755 return this.node.fireEvent.apply(this.node, arguments);
36758 initEvents : function(){
36759 this.node.on("move", this.onMove, this);
36760 var E = Roo.EventManager;
36761 var a = this.anchor;
36763 var el = Roo.fly(a, '_treeui');
36765 if(Roo.isOpera){ // opera render bug ignores the CSS
36766 el.setStyle("text-decoration", "none");
36769 el.on("click", this.onClick, this);
36770 el.on("dblclick", this.onDblClick, this);
36773 Roo.EventManager.on(this.checkbox,
36774 Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
36777 el.on("contextmenu", this.onContextMenu, this);
36779 var icon = Roo.fly(this.iconNode);
36780 icon.on("click", this.onClick, this);
36781 icon.on("dblclick", this.onDblClick, this);
36782 icon.on("contextmenu", this.onContextMenu, this);
36783 E.on(this.ecNode, "click", this.ecClick, this, true);
36785 if(this.node.disabled){
36786 this.addClass("x-tree-node-disabled");
36788 if(this.node.hidden){
36789 this.addClass("x-tree-node-disabled");
36791 var ot = this.node.getOwnerTree();
36792 var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
36793 if(dd && (!this.node.isRoot || ot.rootVisible)){
36794 Roo.dd.Registry.register(this.elNode, {
36796 handles: this.getDDHandles(),
36802 getDDHandles : function(){
36803 return [this.iconNode, this.textNode];
36808 this.wrap.style.display = "none";
36814 this.wrap.style.display = "";
36818 onContextMenu : function(e){
36819 if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
36820 e.preventDefault();
36822 this.fireEvent("contextmenu", this.node, e);
36826 onClick : function(e){
36831 if(this.fireEvent("beforeclick", this.node, e) !== false){
36832 if(!this.disabled && this.node.attributes.href){
36833 this.fireEvent("click", this.node, e);
36836 e.preventDefault();
36841 if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
36842 this.node.toggle();
36845 this.fireEvent("click", this.node, e);
36851 onDblClick : function(e){
36852 e.preventDefault();
36857 this.toggleCheck();
36859 if(!this.animating && this.node.hasChildNodes()){
36860 this.node.toggle();
36862 this.fireEvent("dblclick", this.node, e);
36865 onCheckChange : function(){
36866 var checked = this.checkbox.checked;
36867 this.node.attributes.checked = checked;
36868 this.fireEvent('checkchange', this.node, checked);
36871 ecClick : function(e){
36872 if(!this.animating && this.node.hasChildNodes()){
36873 this.node.toggle();
36877 startDrop : function(){
36878 this.dropping = true;
36881 // delayed drop so the click event doesn't get fired on a drop
36882 endDrop : function(){
36883 setTimeout(function(){
36884 this.dropping = false;
36885 }.createDelegate(this), 50);
36888 expand : function(){
36889 this.updateExpandIcon();
36890 this.ctNode.style.display = "";
36893 focus : function(){
36894 if(!this.node.preventHScroll){
36895 try{this.anchor.focus();
36897 }else if(!Roo.isIE){
36899 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
36900 var l = noscroll.scrollLeft;
36901 this.anchor.focus();
36902 noscroll.scrollLeft = l;
36907 toggleCheck : function(value){
36908 var cb = this.checkbox;
36910 cb.checked = (value === undefined ? !cb.checked : value);
36916 this.anchor.blur();
36920 animExpand : function(callback){
36921 var ct = Roo.get(this.ctNode);
36923 if(!this.node.hasChildNodes()){
36924 this.updateExpandIcon();
36925 this.ctNode.style.display = "";
36926 Roo.callback(callback);
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 highlight : function(){
36943 var tree = this.node.getOwnerTree();
36944 Roo.fly(this.wrap).highlight(
36945 tree.hlColor || "C3DAF9",
36946 {endColor: tree.hlBaseColor}
36950 collapse : function(){
36951 this.updateExpandIcon();
36952 this.ctNode.style.display = "none";
36955 animCollapse : function(callback){
36956 var ct = Roo.get(this.ctNode);
36957 ct.enableDisplayMode('block');
36960 this.animating = true;
36961 this.updateExpandIcon();
36964 callback : function(){
36965 this.animating = false;
36966 Roo.callback(callback);
36969 duration: this.node.ownerTree.duration || .25
36973 getContainer : function(){
36974 return this.ctNode;
36977 getEl : function(){
36981 appendDDGhost : function(ghostNode){
36982 ghostNode.appendChild(this.elNode.cloneNode(true));
36985 getDDRepairXY : function(){
36986 return Roo.lib.Dom.getXY(this.iconNode);
36989 onRender : function(){
36993 render : function(bulkRender){
36994 var n = this.node, a = n.attributes;
36995 var targetNode = n.parentNode ?
36996 n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
36998 if(!this.rendered){
36999 this.rendered = true;
37001 this.renderElements(n, a, targetNode, bulkRender);
37004 if(this.textNode.setAttributeNS){
37005 this.textNode.setAttributeNS("ext", "qtip", a.qtip);
37007 this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
37010 this.textNode.setAttribute("ext:qtip", a.qtip);
37012 this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
37015 }else if(a.qtipCfg){
37016 a.qtipCfg.target = Roo.id(this.textNode);
37017 Roo.QuickTips.register(a.qtipCfg);
37020 if(!this.node.expanded){
37021 this.updateExpandIcon();
37024 if(bulkRender === true) {
37025 targetNode.appendChild(this.wrap);
37030 renderElements : function(n, a, targetNode, bulkRender)
37032 // add some indent caching, this helps performance when rendering a large tree
37033 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
37034 var t = n.getOwnerTree();
37035 var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
37036 if (typeof(n.attributes.html) != 'undefined') {
37037 txt = n.attributes.html;
37039 var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
37040 var cb = typeof a.checked == 'boolean';
37041 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
37042 var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
37043 '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
37044 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
37045 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
37046 cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
37047 '<a hidefocus="on" href="',href,'" tabIndex="1" ',
37048 a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "",
37049 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
37050 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
37053 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
37054 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
37055 n.nextSibling.ui.getEl(), buf.join(""));
37057 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
37060 this.elNode = this.wrap.childNodes[0];
37061 this.ctNode = this.wrap.childNodes[1];
37062 var cs = this.elNode.childNodes;
37063 this.indentNode = cs[0];
37064 this.ecNode = cs[1];
37065 this.iconNode = cs[2];
37068 this.checkbox = cs[3];
37071 this.anchor = cs[index];
37072 this.textNode = cs[index].firstChild;
37075 getAnchor : function(){
37076 return this.anchor;
37079 getTextEl : function(){
37080 return this.textNode;
37083 getIconEl : function(){
37084 return this.iconNode;
37087 isChecked : function(){
37088 return this.checkbox ? this.checkbox.checked : false;
37091 updateExpandIcon : function(){
37093 var n = this.node, c1, c2;
37094 var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
37095 var hasChild = n.hasChildNodes();
37099 c1 = "x-tree-node-collapsed";
37100 c2 = "x-tree-node-expanded";
37103 c1 = "x-tree-node-expanded";
37104 c2 = "x-tree-node-collapsed";
37107 this.removeClass("x-tree-node-leaf");
37108 this.wasLeaf = false;
37110 if(this.c1 != c1 || this.c2 != c2){
37111 Roo.fly(this.elNode).replaceClass(c1, c2);
37112 this.c1 = c1; this.c2 = c2;
37115 // this changes non-leafs into leafs if they have no children.
37116 // it's not very rational behaviour..
37118 if(!this.wasLeaf && this.node.leaf){
37119 Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
37122 this.wasLeaf = true;
37125 var ecc = "x-tree-ec-icon "+cls;
37126 if(this.ecc != ecc){
37127 this.ecNode.className = ecc;
37133 getChildIndent : function(){
37134 if(!this.childIndent){
37138 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
37140 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
37142 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
37147 this.childIndent = buf.join("");
37149 return this.childIndent;
37152 renderIndent : function(){
37155 var p = this.node.parentNode;
37157 indent = p.ui.getChildIndent();
37159 if(this.indentMarkup != indent){ // don't rerender if not required
37160 this.indentNode.innerHTML = indent;
37161 this.indentMarkup = indent;
37163 this.updateExpandIcon();
37168 Roo.tree.RootTreeNodeUI = function(){
37169 Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
37171 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
37172 render : function(){
37173 if(!this.rendered){
37174 var targetNode = this.node.ownerTree.innerCt.dom;
37175 this.node.expanded = true;
37176 targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
37177 this.wrap = this.ctNode = targetNode.firstChild;
37180 collapse : function(){
37182 expand : function(){
37186 * Ext JS Library 1.1.1
37187 * Copyright(c) 2006-2007, Ext JS, LLC.
37189 * Originally Released Under LGPL - original licence link has changed is not relivant.
37192 * <script type="text/javascript">
37195 * @class Roo.tree.TreeLoader
37196 * @extends Roo.util.Observable
37197 * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
37198 * nodes from a specified URL. The response must be a javascript Array definition
37199 * who's elements are node definition objects. eg:
37204 { 'id': 1, 'text': 'A folder Node', 'leaf': false },
37205 { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
37212 * The old style respose with just an array is still supported, but not recommended.
37215 * A server request is sent, and child nodes are loaded only when a node is expanded.
37216 * The loading node's id is passed to the server under the parameter name "node" to
37217 * enable the server to produce the correct child nodes.
37219 * To pass extra parameters, an event handler may be attached to the "beforeload"
37220 * event, and the parameters specified in the TreeLoader's baseParams property:
37222 myTreeLoader.on("beforeload", function(treeLoader, node) {
37223 this.baseParams.category = node.attributes.category;
37228 * This would pass an HTTP parameter called "category" to the server containing
37229 * the value of the Node's "category" attribute.
37231 * Creates a new Treeloader.
37232 * @param {Object} config A config object containing config properties.
37234 Roo.tree.TreeLoader = function(config){
37235 this.baseParams = {};
37236 this.requestMethod = "POST";
37237 Roo.apply(this, config);
37242 * @event beforeload
37243 * Fires before a network request is made to retrieve the Json text which specifies a node's children.
37244 * @param {Object} This TreeLoader object.
37245 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37246 * @param {Object} callback The callback function specified in the {@link #load} call.
37251 * Fires when the node has been successfuly loaded.
37252 * @param {Object} This TreeLoader object.
37253 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37254 * @param {Object} response The response object containing the data from the server.
37258 * @event loadexception
37259 * Fires if the network request failed.
37260 * @param {Object} This TreeLoader object.
37261 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37262 * @param {Object} response The response object containing the data from the server.
37264 loadexception : true,
37267 * Fires before a node is created, enabling you to return custom Node types
37268 * @param {Object} This TreeLoader object.
37269 * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
37274 Roo.tree.TreeLoader.superclass.constructor.call(this);
37277 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
37279 * @cfg {String} dataUrl The URL from which to request a Json string which
37280 * specifies an array of node definition object representing the child nodes
37284 * @cfg {String} requestMethod either GET or POST
37285 * defaults to POST (due to BC)
37289 * @cfg {Object} baseParams (optional) An object containing properties which
37290 * specify HTTP parameters to be passed to each request for child nodes.
37293 * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
37294 * created by this loader. If the attributes sent by the server have an attribute in this object,
37295 * they take priority.
37298 * @cfg {Object} uiProviders (optional) An object containing properties which
37300 * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
37301 * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
37302 * <i>uiProvider</i> attribute of a returned child node is a string rather
37303 * than a reference to a TreeNodeUI implementation, this that string value
37304 * is used as a property name in the uiProviders object. You can define the provider named
37305 * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
37310 * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
37311 * child nodes before loading.
37313 clearOnLoad : true,
37316 * @cfg {String} root (optional) Default to false. Use this to read data from an object
37317 * property on loading, rather than expecting an array. (eg. more compatible to a standard
37318 * Grid query { data : [ .....] }
37323 * @cfg {String} queryParam (optional)
37324 * Name of the query as it will be passed on the querystring (defaults to 'node')
37325 * eg. the request will be ?node=[id]
37332 * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
37333 * This is called automatically when a node is expanded, but may be used to reload
37334 * a node (or append new children if the {@link #clearOnLoad} option is false.)
37335 * @param {Roo.tree.TreeNode} node
37336 * @param {Function} callback
37338 load : function(node, callback){
37339 if(this.clearOnLoad){
37340 while(node.firstChild){
37341 node.removeChild(node.firstChild);
37344 if(node.attributes.children){ // preloaded json children
37345 var cs = node.attributes.children;
37346 for(var i = 0, len = cs.length; i < len; i++){
37347 node.appendChild(this.createNode(cs[i]));
37349 if(typeof callback == "function"){
37352 }else if(this.dataUrl){
37353 this.requestData(node, callback);
37357 getParams: function(node){
37358 var buf = [], bp = this.baseParams;
37359 for(var key in bp){
37360 if(typeof bp[key] != "function"){
37361 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
37364 var n = this.queryParam === false ? 'node' : this.queryParam;
37365 buf.push(n + "=", encodeURIComponent(node.id));
37366 return buf.join("");
37369 requestData : function(node, callback){
37370 if(this.fireEvent("beforeload", this, node, callback) !== false){
37371 this.transId = Roo.Ajax.request({
37372 method:this.requestMethod,
37373 url: this.dataUrl||this.url,
37374 success: this.handleResponse,
37375 failure: this.handleFailure,
37377 argument: {callback: callback, node: node},
37378 params: this.getParams(node)
37381 // if the load is cancelled, make sure we notify
37382 // the node that we are done
37383 if(typeof callback == "function"){
37389 isLoading : function(){
37390 return this.transId ? true : false;
37393 abort : function(){
37394 if(this.isLoading()){
37395 Roo.Ajax.abort(this.transId);
37400 createNode : function(attr)
37402 // apply baseAttrs, nice idea Corey!
37403 if(this.baseAttrs){
37404 Roo.applyIf(attr, this.baseAttrs);
37406 if(this.applyLoader !== false){
37407 attr.loader = this;
37409 // uiProvider = depreciated..
37411 if(typeof(attr.uiProvider) == 'string'){
37412 attr.uiProvider = this.uiProviders[attr.uiProvider] ||
37413 /** eval:var:attr */ eval(attr.uiProvider);
37415 if(typeof(this.uiProviders['default']) != 'undefined') {
37416 attr.uiProvider = this.uiProviders['default'];
37419 this.fireEvent('create', this, attr);
37421 attr.leaf = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
37423 new Roo.tree.TreeNode(attr) :
37424 new Roo.tree.AsyncTreeNode(attr));
37427 processResponse : function(response, node, callback)
37429 var json = response.responseText;
37432 var o = Roo.decode(json);
37434 if (this.root === false && typeof(o.success) != undefined) {
37435 this.root = 'data'; // the default behaviour for list like data..
37438 if (this.root !== false && !o.success) {
37439 // it's a failure condition.
37440 var a = response.argument;
37441 this.fireEvent("loadexception", this, a.node, response);
37442 Roo.log("Load failed - should have a handler really");
37448 if (this.root !== false) {
37452 for(var i = 0, len = o.length; i < len; i++){
37453 var n = this.createNode(o[i]);
37455 node.appendChild(n);
37458 if(typeof callback == "function"){
37459 callback(this, node);
37462 this.handleFailure(response);
37466 handleResponse : function(response){
37467 this.transId = false;
37468 var a = response.argument;
37469 this.processResponse(response, a.node, a.callback);
37470 this.fireEvent("load", this, a.node, response);
37473 handleFailure : function(response)
37475 // should handle failure better..
37476 this.transId = false;
37477 var a = response.argument;
37478 this.fireEvent("loadexception", this, a.node, response);
37479 if(typeof a.callback == "function"){
37480 a.callback(this, a.node);
37485 * Ext JS Library 1.1.1
37486 * Copyright(c) 2006-2007, Ext JS, LLC.
37488 * Originally Released Under LGPL - original licence link has changed is not relivant.
37491 * <script type="text/javascript">
37495 * @class Roo.tree.TreeFilter
37496 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
37497 * @param {TreePanel} tree
37498 * @param {Object} config (optional)
37500 Roo.tree.TreeFilter = function(tree, config){
37502 this.filtered = {};
37503 Roo.apply(this, config);
37506 Roo.tree.TreeFilter.prototype = {
37513 * Filter the data by a specific attribute.
37514 * @param {String/RegExp} value Either string that the attribute value
37515 * should start with or a RegExp to test against the attribute
37516 * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
37517 * @param {TreeNode} startNode (optional) The node to start the filter at.
37519 filter : function(value, attr, startNode){
37520 attr = attr || "text";
37522 if(typeof value == "string"){
37523 var vlen = value.length;
37524 // auto clear empty filter
37525 if(vlen == 0 && this.clearBlank){
37529 value = value.toLowerCase();
37531 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
37533 }else if(value.exec){ // regex?
37535 return value.test(n.attributes[attr]);
37538 throw 'Illegal filter type, must be string or regex';
37540 this.filterBy(f, null, startNode);
37544 * Filter by a function. The passed function will be called with each
37545 * node in the tree (or from the startNode). If the function returns true, the node is kept
37546 * otherwise it is filtered. If a node is filtered, its children are also filtered.
37547 * @param {Function} fn The filter function
37548 * @param {Object} scope (optional) The scope of the function (defaults to the current node)
37550 filterBy : function(fn, scope, startNode){
37551 startNode = startNode || this.tree.root;
37552 if(this.autoClear){
37555 var af = this.filtered, rv = this.reverse;
37556 var f = function(n){
37557 if(n == startNode){
37563 var m = fn.call(scope || n, n);
37571 startNode.cascade(f);
37574 if(typeof id != "function"){
37576 if(n && n.parentNode){
37577 n.parentNode.removeChild(n);
37585 * Clears the current filter. Note: with the "remove" option
37586 * set a filter cannot be cleared.
37588 clear : function(){
37590 var af = this.filtered;
37592 if(typeof id != "function"){
37599 this.filtered = {};
37604 * Ext JS Library 1.1.1
37605 * Copyright(c) 2006-2007, Ext JS, LLC.
37607 * Originally Released Under LGPL - original licence link has changed is not relivant.
37610 * <script type="text/javascript">
37615 * @class Roo.tree.TreeSorter
37616 * Provides sorting of nodes in a TreePanel
37618 * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
37619 * @cfg {String} property The named attribute on the node to sort by (defaults to text)
37620 * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
37621 * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
37622 * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
37623 * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
37625 * @param {TreePanel} tree
37626 * @param {Object} config
37628 Roo.tree.TreeSorter = function(tree, config){
37629 Roo.apply(this, config);
37630 tree.on("beforechildrenrendered", this.doSort, this);
37631 tree.on("append", this.updateSort, this);
37632 tree.on("insert", this.updateSort, this);
37634 var dsc = this.dir && this.dir.toLowerCase() == "desc";
37635 var p = this.property || "text";
37636 var sortType = this.sortType;
37637 var fs = this.folderSort;
37638 var cs = this.caseSensitive === true;
37639 var leafAttr = this.leafAttr || 'leaf';
37641 this.sortFn = function(n1, n2){
37643 if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
37646 if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
37650 var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
37651 var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
37653 return dsc ? +1 : -1;
37655 return dsc ? -1 : +1;
37662 Roo.tree.TreeSorter.prototype = {
37663 doSort : function(node){
37664 node.sort(this.sortFn);
37667 compareNodes : function(n1, n2){
37668 return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
37671 updateSort : function(tree, node){
37672 if(node.childrenRendered){
37673 this.doSort.defer(1, this, [node]);
37678 * Ext JS Library 1.1.1
37679 * Copyright(c) 2006-2007, Ext JS, LLC.
37681 * Originally Released Under LGPL - original licence link has changed is not relivant.
37684 * <script type="text/javascript">
37687 if(Roo.dd.DropZone){
37689 Roo.tree.TreeDropZone = function(tree, config){
37690 this.allowParentInsert = false;
37691 this.allowContainerDrop = false;
37692 this.appendOnly = false;
37693 Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
37695 this.lastInsertClass = "x-tree-no-status";
37696 this.dragOverData = {};
37699 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
37700 ddGroup : "TreeDD",
37703 expandDelay : 1000,
37705 expandNode : function(node){
37706 if(node.hasChildNodes() && !node.isExpanded()){
37707 node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
37711 queueExpand : function(node){
37712 this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
37715 cancelExpand : function(){
37716 if(this.expandProcId){
37717 clearTimeout(this.expandProcId);
37718 this.expandProcId = false;
37722 isValidDropPoint : function(n, pt, dd, e, data){
37723 if(!n || !data){ return false; }
37724 var targetNode = n.node;
37725 var dropNode = data.node;
37726 // default drop rules
37727 if(!(targetNode && targetNode.isTarget && pt)){
37730 if(pt == "append" && targetNode.allowChildren === false){
37733 if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
37736 if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
37739 // reuse the object
37740 var overEvent = this.dragOverData;
37741 overEvent.tree = this.tree;
37742 overEvent.target = targetNode;
37743 overEvent.data = data;
37744 overEvent.point = pt;
37745 overEvent.source = dd;
37746 overEvent.rawEvent = e;
37747 overEvent.dropNode = dropNode;
37748 overEvent.cancel = false;
37749 var result = this.tree.fireEvent("nodedragover", overEvent);
37750 return overEvent.cancel === false && result !== false;
37753 getDropPoint : function(e, n, dd)
37757 return tn.allowChildren !== false ? "append" : false; // always append for root
37759 var dragEl = n.ddel;
37760 var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
37761 var y = Roo.lib.Event.getPageY(e);
37762 //var noAppend = tn.allowChildren === false || tn.isLeaf();
37764 // we may drop nodes anywhere, as long as allowChildren has not been set to false..
37765 var noAppend = tn.allowChildren === false;
37766 if(this.appendOnly || tn.parentNode.allowChildren === false){
37767 return noAppend ? false : "append";
37769 var noBelow = false;
37770 if(!this.allowParentInsert){
37771 noBelow = tn.hasChildNodes() && tn.isExpanded();
37773 var q = (b - t) / (noAppend ? 2 : 3);
37774 if(y >= t && y < (t + q)){
37776 }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
37783 onNodeEnter : function(n, dd, e, data)
37785 this.cancelExpand();
37788 onNodeOver : function(n, dd, e, data)
37791 var pt = this.getDropPoint(e, n, dd);
37794 // auto node expand check
37795 if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
37796 this.queueExpand(node);
37797 }else if(pt != "append"){
37798 this.cancelExpand();
37801 // set the insert point style on the target node
37802 var returnCls = this.dropNotAllowed;
37803 if(this.isValidDropPoint(n, pt, dd, e, data)){
37808 returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
37809 cls = "x-tree-drag-insert-above";
37810 }else if(pt == "below"){
37811 returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
37812 cls = "x-tree-drag-insert-below";
37814 returnCls = "x-tree-drop-ok-append";
37815 cls = "x-tree-drag-append";
37817 if(this.lastInsertClass != cls){
37818 Roo.fly(el).replaceClass(this.lastInsertClass, cls);
37819 this.lastInsertClass = cls;
37826 onNodeOut : function(n, dd, e, data){
37828 this.cancelExpand();
37829 this.removeDropIndicators(n);
37832 onNodeDrop : function(n, dd, e, data){
37833 var point = this.getDropPoint(e, n, dd);
37834 var targetNode = n.node;
37835 targetNode.ui.startDrop();
37836 if(!this.isValidDropPoint(n, point, dd, e, data)){
37837 targetNode.ui.endDrop();
37840 // first try to find the drop node
37841 var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
37844 target: targetNode,
37849 dropNode: dropNode,
37852 var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
37853 if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
37854 targetNode.ui.endDrop();
37857 // allow target changing
37858 targetNode = dropEvent.target;
37859 if(point == "append" && !targetNode.isExpanded()){
37860 targetNode.expand(false, null, function(){
37861 this.completeDrop(dropEvent);
37862 }.createDelegate(this));
37864 this.completeDrop(dropEvent);
37869 completeDrop : function(de){
37870 var ns = de.dropNode, p = de.point, t = de.target;
37871 if(!(ns instanceof Array)){
37875 for(var i = 0, len = ns.length; i < len; i++){
37878 t.parentNode.insertBefore(n, t);
37879 }else if(p == "below"){
37880 t.parentNode.insertBefore(n, t.nextSibling);
37886 if(this.tree.hlDrop){
37890 this.tree.fireEvent("nodedrop", de);
37893 afterNodeMoved : function(dd, data, e, targetNode, dropNode){
37894 if(this.tree.hlDrop){
37895 dropNode.ui.focus();
37896 dropNode.ui.highlight();
37898 this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
37901 getTree : function(){
37905 removeDropIndicators : function(n){
37908 Roo.fly(el).removeClass([
37909 "x-tree-drag-insert-above",
37910 "x-tree-drag-insert-below",
37911 "x-tree-drag-append"]);
37912 this.lastInsertClass = "_noclass";
37916 beforeDragDrop : function(target, e, id){
37917 this.cancelExpand();
37921 afterRepair : function(data){
37922 if(data && Roo.enableFx){
37923 data.node.ui.highlight();
37933 * Ext JS Library 1.1.1
37934 * Copyright(c) 2006-2007, Ext JS, LLC.
37936 * Originally Released Under LGPL - original licence link has changed is not relivant.
37939 * <script type="text/javascript">
37943 if(Roo.dd.DragZone){
37944 Roo.tree.TreeDragZone = function(tree, config){
37945 Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
37949 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
37950 ddGroup : "TreeDD",
37952 onBeforeDrag : function(data, e){
37954 return n && n.draggable && !n.disabled;
37958 onInitDrag : function(e){
37959 var data = this.dragData;
37960 this.tree.getSelectionModel().select(data.node);
37961 this.proxy.update("");
37962 data.node.ui.appendDDGhost(this.proxy.ghost.dom);
37963 this.tree.fireEvent("startdrag", this.tree, data.node, e);
37966 getRepairXY : function(e, data){
37967 return data.node.ui.getDDRepairXY();
37970 onEndDrag : function(data, e){
37971 this.tree.fireEvent("enddrag", this.tree, data.node, e);
37976 onValidDrop : function(dd, e, id){
37977 this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
37981 beforeInvalidDrop : function(e, id){
37982 // this scrolls the original position back into view
37983 var sm = this.tree.getSelectionModel();
37984 sm.clearSelections();
37985 sm.select(this.dragData.node);
37990 * Ext JS Library 1.1.1
37991 * Copyright(c) 2006-2007, Ext JS, LLC.
37993 * Originally Released Under LGPL - original licence link has changed is not relivant.
37996 * <script type="text/javascript">
37999 * @class Roo.tree.TreeEditor
38000 * @extends Roo.Editor
38001 * Provides editor functionality for inline tree node editing. Any valid {@link Roo.form.Field} can be used
38002 * as the editor field.
38004 * @param {Object} config (used to be the tree panel.)
38005 * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
38007 * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
38008 * @cfg {Roo.form.TextField} field [required] The field configuration
38012 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
38015 if (oldconfig) { // old style..
38016 field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
38019 tree = config.tree;
38020 config.field = config.field || {};
38021 config.field.xtype = 'TextField';
38022 field = Roo.factory(config.field, Roo.form);
38024 config = config || {};
38029 * @event beforenodeedit
38030 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
38031 * false from the handler of this event.
38032 * @param {Editor} this
38033 * @param {Roo.tree.Node} node
38035 "beforenodeedit" : true
38039 Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
38043 tree.on('beforeclick', this.beforeNodeClick, this);
38044 tree.getTreeEl().on('mousedown', this.hide, this);
38045 this.on('complete', this.updateNode, this);
38046 this.on('beforestartedit', this.fitToTree, this);
38047 this.on('startedit', this.bindScroll, this, {delay:10});
38048 this.on('specialkey', this.onSpecialKey, this);
38051 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
38053 * @cfg {String} alignment
38054 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
38060 * @cfg {Boolean} hideEl
38061 * True to hide the bound element while the editor is displayed (defaults to false)
38065 * @cfg {String} cls
38066 * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
38068 cls: "x-small-editor x-tree-editor",
38070 * @cfg {Boolean} shim
38071 * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
38077 * @cfg {Number} maxWidth
38078 * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed
38079 * the containing tree element's size, it will be automatically limited for you to the container width, taking
38080 * scroll and client offsets into account prior to each edit.
38087 fitToTree : function(ed, el){
38088 var td = this.tree.getTreeEl().dom, nd = el.dom;
38089 if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible
38090 td.scrollLeft = nd.offsetLeft;
38094 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
38095 this.setSize(w, '');
38097 return this.fireEvent('beforenodeedit', this, this.editNode);
38102 triggerEdit : function(node){
38103 this.completeEdit();
38104 this.editNode = node;
38105 this.startEdit(node.ui.textNode, node.text);
38109 bindScroll : function(){
38110 this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
38114 beforeNodeClick : function(node, e){
38115 var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
38116 this.lastClick = new Date();
38117 if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
38119 this.triggerEdit(node);
38126 updateNode : function(ed, value){
38127 this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
38128 this.editNode.setText(value);
38132 onHide : function(){
38133 Roo.tree.TreeEditor.superclass.onHide.call(this);
38135 this.editNode.ui.focus();
38140 onSpecialKey : function(field, e){
38141 var k = e.getKey();
38145 }else if(k == e.ENTER && !e.hasModifier()){
38147 this.completeEdit();
38150 });//<Script type="text/javascript">
38153 * Ext JS Library 1.1.1
38154 * Copyright(c) 2006-2007, Ext JS, LLC.
38156 * Originally Released Under LGPL - original licence link has changed is not relivant.
38159 * <script type="text/javascript">
38163 * Not documented??? - probably should be...
38166 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
38167 //focus: Roo.emptyFn, // prevent odd scrolling behavior
38169 renderElements : function(n, a, targetNode, bulkRender){
38170 //consel.log("renderElements?");
38171 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
38173 var t = n.getOwnerTree();
38174 var tid = Pman.Tab.Document_TypesTree.tree.el.id;
38176 var cols = t.columns;
38177 var bw = t.borderWidth;
38179 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
38180 var cb = typeof a.checked == "boolean";
38181 var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
38182 var colcls = 'x-t-' + tid + '-c0';
38184 '<li class="x-tree-node">',
38187 '<div class="x-tree-node-el ', a.cls,'">',
38189 '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
38192 '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
38193 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon " />',
38194 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
38195 (a.icon ? ' x-tree-node-inline-icon' : ''),
38196 (a.iconCls ? ' '+a.iconCls : ''),
38197 '" unselectable="on" />',
38198 (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' +
38199 (a.checked ? 'checked="checked" />' : ' />')) : ''),
38201 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
38202 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
38203 '<span unselectable="on" qtip="' + tx + '">',
38207 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
38208 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
38210 for(var i = 1, len = cols.length; i < len; i++){
38212 colcls = 'x-t-' + tid + '-c' +i;
38213 tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
38214 buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
38215 '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
38221 '<div class="x-clear"></div></div>',
38222 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
38225 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
38226 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
38227 n.nextSibling.ui.getEl(), buf.join(""));
38229 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
38231 var el = this.wrap.firstChild;
38233 this.elNode = el.firstChild;
38234 this.ranchor = el.childNodes[1];
38235 this.ctNode = this.wrap.childNodes[1];
38236 var cs = el.firstChild.childNodes;
38237 this.indentNode = cs[0];
38238 this.ecNode = cs[1];
38239 this.iconNode = cs[2];
38242 this.checkbox = cs[3];
38245 this.anchor = cs[index];
38247 this.textNode = cs[index].firstChild;
38249 //el.on("click", this.onClick, this);
38250 //el.on("dblclick", this.onDblClick, this);
38253 // console.log(this);
38255 initEvents : function(){
38256 Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
38259 var a = this.ranchor;
38261 var el = Roo.get(a);
38263 if(Roo.isOpera){ // opera render bug ignores the CSS
38264 el.setStyle("text-decoration", "none");
38267 el.on("click", this.onClick, this);
38268 el.on("dblclick", this.onDblClick, this);
38269 el.on("contextmenu", this.onContextMenu, this);
38273 /*onSelectedChange : function(state){
38276 this.addClass("x-tree-selected");
38279 this.removeClass("x-tree-selected");
38282 addClass : function(cls){
38284 Roo.fly(this.elRow).addClass(cls);
38290 removeClass : function(cls){
38292 Roo.fly(this.elRow).removeClass(cls);
38298 });//<Script type="text/javascript">
38302 * Ext JS Library 1.1.1
38303 * Copyright(c) 2006-2007, Ext JS, LLC.
38305 * Originally Released Under LGPL - original licence link has changed is not relivant.
38308 * <script type="text/javascript">
38313 * @class Roo.tree.ColumnTree
38314 * @extends Roo.tree.TreePanel
38315 * @cfg {Object} columns Including width, header, renderer, cls, dataIndex
38316 * @cfg {int} borderWidth compined right/left border allowance
38318 * @param {String/HTMLElement/Element} el The container element
38319 * @param {Object} config
38321 Roo.tree.ColumnTree = function(el, config)
38323 Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
38327 * Fire this event on a container when it resizes
38328 * @param {int} w Width
38329 * @param {int} h Height
38333 this.on('resize', this.onResize, this);
38336 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
38340 borderWidth: Roo.isBorderBox ? 0 : 2,
38343 render : function(){
38344 // add the header.....
38346 Roo.tree.ColumnTree.superclass.render.apply(this);
38348 this.el.addClass('x-column-tree');
38350 this.headers = this.el.createChild(
38351 {cls:'x-tree-headers'},this.innerCt.dom);
38353 var cols = this.columns, c;
38354 var totalWidth = 0;
38356 var len = cols.length;
38357 for(var i = 0; i < len; i++){
38359 totalWidth += c.width;
38360 this.headEls.push(this.headers.createChild({
38361 cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
38363 cls:'x-tree-hd-text',
38366 style:'width:'+(c.width-this.borderWidth)+'px;'
38369 this.headers.createChild({cls:'x-clear'});
38370 // prevent floats from wrapping when clipped
38371 this.headers.setWidth(totalWidth);
38372 //this.innerCt.setWidth(totalWidth);
38373 this.innerCt.setStyle({ overflow: 'auto' });
38374 this.onResize(this.width, this.height);
38378 onResize : function(w,h)
38383 this.innerCt.setWidth(this.width);
38384 this.innerCt.setHeight(this.height-20);
38387 var cols = this.columns, c;
38388 var totalWidth = 0;
38390 var len = cols.length;
38391 for(var i = 0; i < len; i++){
38393 if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
38394 // it's the expander..
38395 expEl = this.headEls[i];
38398 totalWidth += c.width;
38402 expEl.setWidth( ((w - totalWidth)-this.borderWidth - 20));
38404 this.headers.setWidth(w-20);
38413 * Ext JS Library 1.1.1
38414 * Copyright(c) 2006-2007, Ext JS, LLC.
38416 * Originally Released Under LGPL - original licence link has changed is not relivant.
38419 * <script type="text/javascript">
38423 * @class Roo.menu.Menu
38424 * @extends Roo.util.Observable
38425 * @children Roo.menu.Item Roo.menu.Separator Roo.menu.TextItem
38426 * A menu object. This is the container to which you add all other menu items. Menu can also serve a as a base class
38427 * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
38429 * Creates a new Menu
38430 * @param {Object} config Configuration options
38432 Roo.menu.Menu = function(config){
38434 Roo.menu.Menu.superclass.constructor.call(this, config);
38436 this.id = this.id || Roo.id();
38439 * @event beforeshow
38440 * Fires before this menu is displayed
38441 * @param {Roo.menu.Menu} this
38445 * @event beforehide
38446 * Fires before this menu is hidden
38447 * @param {Roo.menu.Menu} this
38452 * Fires after this menu is displayed
38453 * @param {Roo.menu.Menu} this
38458 * Fires after this menu is hidden
38459 * @param {Roo.menu.Menu} this
38464 * Fires when this menu is clicked (or when the enter key is pressed while it is active)
38465 * @param {Roo.menu.Menu} this
38466 * @param {Roo.menu.Item} menuItem The menu item that was clicked
38467 * @param {Roo.EventObject} e
38472 * Fires when the mouse is hovering over this menu
38473 * @param {Roo.menu.Menu} this
38474 * @param {Roo.EventObject} e
38475 * @param {Roo.menu.Item} menuItem The menu item that was clicked
38480 * Fires when the mouse exits this menu
38481 * @param {Roo.menu.Menu} this
38482 * @param {Roo.EventObject} e
38483 * @param {Roo.menu.Item} menuItem The menu item that was clicked
38488 * Fires when a menu item contained in this menu is clicked
38489 * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
38490 * @param {Roo.EventObject} e
38494 if (this.registerMenu) {
38495 Roo.menu.MenuMgr.register(this);
38498 var mis = this.items;
38499 this.items = new Roo.util.MixedCollection();
38501 this.add.apply(this, mis);
38505 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
38507 * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
38511 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
38512 * for bottom-right shadow (defaults to "sides")
38516 * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
38517 * this menu (defaults to "tl-tr?")
38519 subMenuAlign : "tl-tr?",
38521 * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
38522 * relative to its element of origin (defaults to "tl-bl?")
38524 defaultAlign : "tl-bl?",
38526 * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
38528 allowOtherMenus : false,
38530 * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
38532 registerMenu : true,
38537 render : function(){
38541 var el = this.el = new Roo.Layer({
38543 shadow:this.shadow,
38545 parentEl: this.parentEl || document.body,
38549 this.keyNav = new Roo.menu.MenuNav(this);
38552 el.addClass("x-menu-plain");
38555 el.addClass(this.cls);
38557 // generic focus element
38558 this.focusEl = el.createChild({
38559 tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
38561 var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
38562 //disabling touch- as it's causing issues ..
38563 //ul.on(Roo.isTouch ? 'touchstart' : 'click' , this.onClick, this);
38564 ul.on('click' , this.onClick, this);
38567 ul.on("mouseover", this.onMouseOver, this);
38568 ul.on("mouseout", this.onMouseOut, this);
38569 this.items.each(function(item){
38574 var li = document.createElement("li");
38575 li.className = "x-menu-list-item";
38576 ul.dom.appendChild(li);
38577 item.render(li, this);
38584 autoWidth : function(){
38585 var el = this.el, ul = this.ul;
38589 var w = this.width;
38592 }else if(Roo.isIE){
38593 el.setWidth(this.minWidth);
38594 var t = el.dom.offsetWidth; // force recalc
38595 el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
38600 delayAutoWidth : function(){
38603 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
38605 this.awTask.delay(20);
38610 findTargetItem : function(e){
38611 var t = e.getTarget(".x-menu-list-item", this.ul, true);
38612 if(t && t.menuItemId){
38613 return this.items.get(t.menuItemId);
38618 onClick : function(e){
38619 Roo.log("menu.onClick");
38620 var t = this.findTargetItem(e);
38625 if (Roo.isTouch && e.type == 'touchstart' && t.menu && !t.disabled) {
38626 if(t == this.activeItem && t.shouldDeactivate(e)){
38627 this.activeItem.deactivate();
38628 delete this.activeItem;
38632 this.setActiveItem(t, true);
38640 this.fireEvent("click", this, t, e);
38644 setActiveItem : function(item, autoExpand){
38645 if(item != this.activeItem){
38646 if(this.activeItem){
38647 this.activeItem.deactivate();
38649 this.activeItem = item;
38650 item.activate(autoExpand);
38651 }else if(autoExpand){
38657 tryActivate : function(start, step){
38658 var items = this.items;
38659 for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
38660 var item = items.get(i);
38661 if(!item.disabled && item.canActivate){
38662 this.setActiveItem(item, false);
38670 onMouseOver : function(e){
38672 if(t = this.findTargetItem(e)){
38673 if(t.canActivate && !t.disabled){
38674 this.setActiveItem(t, true);
38677 this.fireEvent("mouseover", this, e, t);
38681 onMouseOut : function(e){
38683 if(t = this.findTargetItem(e)){
38684 if(t == this.activeItem && t.shouldDeactivate(e)){
38685 this.activeItem.deactivate();
38686 delete this.activeItem;
38689 this.fireEvent("mouseout", this, e, t);
38693 * Read-only. Returns true if the menu is currently displayed, else false.
38696 isVisible : function(){
38697 return this.el && !this.hidden;
38701 * Displays this menu relative to another element
38702 * @param {String/HTMLElement/Roo.Element} element The element to align to
38703 * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
38704 * the element (defaults to this.defaultAlign)
38705 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
38707 show : function(el, pos, parentMenu){
38708 this.parentMenu = parentMenu;
38712 this.fireEvent("beforeshow", this);
38713 this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
38717 * Displays this menu at a specific xy position
38718 * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
38719 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
38721 showAt : function(xy, parentMenu, /* private: */_e){
38722 this.parentMenu = parentMenu;
38727 this.fireEvent("beforeshow", this);
38728 xy = this.el.adjustForConstraints(xy);
38732 this.hidden = false;
38734 this.fireEvent("show", this);
38737 focus : function(){
38739 this.doFocus.defer(50, this);
38743 doFocus : function(){
38745 this.focusEl.focus();
38750 * Hides this menu and optionally all parent menus
38751 * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
38753 hide : function(deep){
38754 if(this.el && this.isVisible()){
38755 this.fireEvent("beforehide", this);
38756 if(this.activeItem){
38757 this.activeItem.deactivate();
38758 this.activeItem = null;
38761 this.hidden = true;
38762 this.fireEvent("hide", this);
38764 if(deep === true && this.parentMenu){
38765 this.parentMenu.hide(true);
38770 * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
38771 * Any of the following are valid:
38773 * <li>Any menu item object based on {@link Roo.menu.Item}</li>
38774 * <li>An HTMLElement object which will be converted to a menu item</li>
38775 * <li>A menu item config object that will be created as a new menu item</li>
38776 * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
38777 * it will be converted into a {@link Roo.menu.TextItem} and added</li>
38782 var menu = new Roo.menu.Menu();
38784 // Create a menu item to add by reference
38785 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
38787 // Add a bunch of items at once using different methods.
38788 // Only the last item added will be returned.
38789 var item = menu.add(
38790 menuItem, // add existing item by ref
38791 'Dynamic Item', // new TextItem
38792 '-', // new separator
38793 { text: 'Config Item' } // new item by config
38796 * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
38797 * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
38800 var a = arguments, l = a.length, item;
38801 for(var i = 0; i < l; i++){
38803 if ((typeof(el) == "object") && el.xtype && el.xns) {
38804 el = Roo.factory(el, Roo.menu);
38807 if(el.render){ // some kind of Item
38808 item = this.addItem(el);
38809 }else if(typeof el == "string"){ // string
38810 if(el == "separator" || el == "-"){
38811 item = this.addSeparator();
38813 item = this.addText(el);
38815 }else if(el.tagName || el.el){ // element
38816 item = this.addElement(el);
38817 }else if(typeof el == "object"){ // must be menu item config?
38818 item = this.addMenuItem(el);
38825 * Returns this menu's underlying {@link Roo.Element} object
38826 * @return {Roo.Element} The element
38828 getEl : function(){
38836 * Adds a separator bar to the menu
38837 * @return {Roo.menu.Item} The menu item that was added
38839 addSeparator : function(){
38840 return this.addItem(new Roo.menu.Separator());
38844 * Adds an {@link Roo.Element} object to the menu
38845 * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
38846 * @return {Roo.menu.Item} The menu item that was added
38848 addElement : function(el){
38849 return this.addItem(new Roo.menu.BaseItem(el));
38853 * Adds an existing object based on {@link Roo.menu.Item} to the menu
38854 * @param {Roo.menu.Item} item The menu item to add
38855 * @return {Roo.menu.Item} The menu item that was added
38857 addItem : function(item){
38858 this.items.add(item);
38860 var li = document.createElement("li");
38861 li.className = "x-menu-list-item";
38862 this.ul.dom.appendChild(li);
38863 item.render(li, this);
38864 this.delayAutoWidth();
38870 * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
38871 * @param {Object} config A MenuItem config object
38872 * @return {Roo.menu.Item} The menu item that was added
38874 addMenuItem : function(config){
38875 if(!(config instanceof Roo.menu.Item)){
38876 if(typeof config.checked == "boolean"){ // must be check menu item config?
38877 config = new Roo.menu.CheckItem(config);
38879 config = new Roo.menu.Item(config);
38882 return this.addItem(config);
38886 * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
38887 * @param {String} text The text to display in the menu item
38888 * @return {Roo.menu.Item} The menu item that was added
38890 addText : function(text){
38891 return this.addItem(new Roo.menu.TextItem({ text : text }));
38895 * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
38896 * @param {Number} index The index in the menu's list of current items where the new item should be inserted
38897 * @param {Roo.menu.Item} item The menu item to add
38898 * @return {Roo.menu.Item} The menu item that was added
38900 insert : function(index, item){
38901 this.items.insert(index, item);
38903 var li = document.createElement("li");
38904 li.className = "x-menu-list-item";
38905 this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
38906 item.render(li, this);
38907 this.delayAutoWidth();
38913 * Removes an {@link Roo.menu.Item} from the menu and destroys the object
38914 * @param {Roo.menu.Item} item The menu item to remove
38916 remove : function(item){
38917 this.items.removeKey(item.id);
38922 * Removes and destroys all items in the menu
38924 removeAll : function(){
38926 while(f = this.items.first()){
38932 // MenuNav is a private utility class used internally by the Menu
38933 Roo.menu.MenuNav = function(menu){
38934 Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
38935 this.scope = this.menu = menu;
38938 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
38939 doRelay : function(e, h){
38940 var k = e.getKey();
38941 if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
38942 this.menu.tryActivate(0, 1);
38945 return h.call(this.scope || this, e, this.menu);
38948 up : function(e, m){
38949 if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
38950 m.tryActivate(m.items.length-1, -1);
38954 down : function(e, m){
38955 if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
38956 m.tryActivate(0, 1);
38960 right : function(e, m){
38962 m.activeItem.expandMenu(true);
38966 left : function(e, m){
38968 if(m.parentMenu && m.parentMenu.activeItem){
38969 m.parentMenu.activeItem.activate();
38973 enter : function(e, m){
38975 e.stopPropagation();
38976 m.activeItem.onClick(e);
38977 m.fireEvent("click", this, m.activeItem);
38983 * Ext JS Library 1.1.1
38984 * Copyright(c) 2006-2007, Ext JS, LLC.
38986 * Originally Released Under LGPL - original licence link has changed is not relivant.
38989 * <script type="text/javascript">
38993 * @class Roo.menu.MenuMgr
38994 * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
38997 Roo.menu.MenuMgr = function(){
38998 var menus, active, groups = {}, attached = false, lastShow = new Date();
39000 // private - called when first menu is created
39003 active = new Roo.util.MixedCollection();
39004 Roo.get(document).addKeyListener(27, function(){
39005 if(active.length > 0){
39012 function hideAll(){
39013 if(active && active.length > 0){
39014 var c = active.clone();
39015 c.each(function(m){
39022 function onHide(m){
39024 if(active.length < 1){
39025 Roo.get(document).un("mousedown", onMouseDown);
39031 function onShow(m){
39032 var last = active.last();
39033 lastShow = new Date();
39036 Roo.get(document).on("mousedown", onMouseDown);
39040 m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
39041 m.parentMenu.activeChild = m;
39042 }else if(last && last.isVisible()){
39043 m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
39048 function onBeforeHide(m){
39050 m.activeChild.hide();
39052 if(m.autoHideTimer){
39053 clearTimeout(m.autoHideTimer);
39054 delete m.autoHideTimer;
39059 function onBeforeShow(m){
39060 var pm = m.parentMenu;
39061 if(!pm && !m.allowOtherMenus){
39063 }else if(pm && pm.activeChild && active != m){
39064 pm.activeChild.hide();
39069 function onMouseDown(e){
39070 if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
39076 function onBeforeCheck(mi, state){
39078 var g = groups[mi.group];
39079 for(var i = 0, l = g.length; i < l; i++){
39081 g[i].setChecked(false);
39090 * Hides all menus that are currently visible
39092 hideAll : function(){
39097 register : function(menu){
39101 menus[menu.id] = menu;
39102 menu.on("beforehide", onBeforeHide);
39103 menu.on("hide", onHide);
39104 menu.on("beforeshow", onBeforeShow);
39105 menu.on("show", onShow);
39106 var g = menu.group;
39107 if(g && menu.events["checkchange"]){
39111 groups[g].push(menu);
39112 menu.on("checkchange", onCheck);
39117 * Returns a {@link Roo.menu.Menu} object
39118 * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
39119 * be used to generate and return a new Menu instance.
39121 get : function(menu){
39122 if(typeof menu == "string"){ // menu id
39123 return menus[menu];
39124 }else if(menu.events){ // menu instance
39126 }else if(typeof menu.length == 'number'){ // array of menu items?
39127 return new Roo.menu.Menu({items:menu});
39128 }else{ // otherwise, must be a config
39129 return new Roo.menu.Menu(menu);
39134 unregister : function(menu){
39135 delete menus[menu.id];
39136 menu.un("beforehide", onBeforeHide);
39137 menu.un("hide", onHide);
39138 menu.un("beforeshow", onBeforeShow);
39139 menu.un("show", onShow);
39140 var g = menu.group;
39141 if(g && menu.events["checkchange"]){
39142 groups[g].remove(menu);
39143 menu.un("checkchange", onCheck);
39148 registerCheckable : function(menuItem){
39149 var g = menuItem.group;
39154 groups[g].push(menuItem);
39155 menuItem.on("beforecheckchange", onBeforeCheck);
39160 unregisterCheckable : function(menuItem){
39161 var g = menuItem.group;
39163 groups[g].remove(menuItem);
39164 menuItem.un("beforecheckchange", onBeforeCheck);
39170 * Ext JS Library 1.1.1
39171 * Copyright(c) 2006-2007, Ext JS, LLC.
39173 * Originally Released Under LGPL - original licence link has changed is not relivant.
39176 * <script type="text/javascript">
39181 * @class Roo.menu.BaseItem
39182 * @extends Roo.Component
39184 * The base class for all items that render into menus. BaseItem provides default rendering, activated state
39185 * management and base configuration options shared by all menu components.
39187 * Creates a new BaseItem
39188 * @param {Object} config Configuration options
39190 Roo.menu.BaseItem = function(config){
39191 Roo.menu.BaseItem.superclass.constructor.call(this, config);
39196 * Fires when this item is clicked
39197 * @param {Roo.menu.BaseItem} this
39198 * @param {Roo.EventObject} e
39203 * Fires when this item is activated
39204 * @param {Roo.menu.BaseItem} this
39208 * @event deactivate
39209 * Fires when this item is deactivated
39210 * @param {Roo.menu.BaseItem} this
39216 this.on("click", this.handler, this.scope, true);
39220 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
39222 * @cfg {Function} handler
39223 * A function that will handle the click event of this menu item (defaults to undefined)
39226 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
39228 canActivate : false,
39231 * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
39236 * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
39238 activeClass : "x-menu-item-active",
39240 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
39242 hideOnClick : true,
39244 * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
39249 ctype: "Roo.menu.BaseItem",
39252 actionMode : "container",
39255 render : function(container, parentMenu){
39256 this.parentMenu = parentMenu;
39257 Roo.menu.BaseItem.superclass.render.call(this, container);
39258 this.container.menuItemId = this.id;
39262 onRender : function(container, position){
39263 this.el = Roo.get(this.el);
39264 container.dom.appendChild(this.el.dom);
39268 onClick : function(e){
39269 if(!this.disabled && this.fireEvent("click", this, e) !== false
39270 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
39271 this.handleClick(e);
39278 activate : function(){
39282 var li = this.container;
39283 li.addClass(this.activeClass);
39284 this.region = li.getRegion().adjust(2, 2, -2, -2);
39285 this.fireEvent("activate", this);
39290 deactivate : function(){
39291 this.container.removeClass(this.activeClass);
39292 this.fireEvent("deactivate", this);
39296 shouldDeactivate : function(e){
39297 return !this.region || !this.region.contains(e.getPoint());
39301 handleClick : function(e){
39302 if(this.hideOnClick){
39303 this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
39308 expandMenu : function(autoActivate){
39313 hideMenu : function(){
39318 * Ext JS Library 1.1.1
39319 * Copyright(c) 2006-2007, Ext JS, LLC.
39321 * Originally Released Under LGPL - original licence link has changed is not relivant.
39324 * <script type="text/javascript">
39328 * @class Roo.menu.Adapter
39329 * @extends Roo.menu.BaseItem
39331 * 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.
39332 * It provides basic rendering, activation management and enable/disable logic required to work in menus.
39334 * Creates a new Adapter
39335 * @param {Object} config Configuration options
39337 Roo.menu.Adapter = function(component, config){
39338 Roo.menu.Adapter.superclass.constructor.call(this, config);
39339 this.component = component;
39341 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
39343 canActivate : true,
39346 onRender : function(container, position){
39347 this.component.render(container);
39348 this.el = this.component.getEl();
39352 activate : function(){
39356 this.component.focus();
39357 this.fireEvent("activate", this);
39362 deactivate : function(){
39363 this.fireEvent("deactivate", this);
39367 disable : function(){
39368 this.component.disable();
39369 Roo.menu.Adapter.superclass.disable.call(this);
39373 enable : function(){
39374 this.component.enable();
39375 Roo.menu.Adapter.superclass.enable.call(this);
39379 * Ext JS Library 1.1.1
39380 * Copyright(c) 2006-2007, Ext JS, LLC.
39382 * Originally Released Under LGPL - original licence link has changed is not relivant.
39385 * <script type="text/javascript">
39389 * @class Roo.menu.TextItem
39390 * @extends Roo.menu.BaseItem
39391 * Adds a static text string to a menu, usually used as either a heading or group separator.
39392 * Note: old style constructor with text is still supported.
39395 * Creates a new TextItem
39396 * @param {Object} cfg Configuration
39398 Roo.menu.TextItem = function(cfg){
39399 if (typeof(cfg) == 'string') {
39402 Roo.apply(this,cfg);
39405 Roo.menu.TextItem.superclass.constructor.call(this);
39408 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
39410 * @cfg {String} text Text to show on item.
39415 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
39417 hideOnClick : false,
39419 * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
39421 itemCls : "x-menu-text",
39424 onRender : function(){
39425 var s = document.createElement("span");
39426 s.className = this.itemCls;
39427 s.innerHTML = this.text;
39429 Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
39433 * Ext JS Library 1.1.1
39434 * Copyright(c) 2006-2007, Ext JS, LLC.
39436 * Originally Released Under LGPL - original licence link has changed is not relivant.
39439 * <script type="text/javascript">
39443 * @class Roo.menu.Separator
39444 * @extends Roo.menu.BaseItem
39445 * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
39446 * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
39448 * @param {Object} config Configuration options
39450 Roo.menu.Separator = function(config){
39451 Roo.menu.Separator.superclass.constructor.call(this, config);
39454 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
39456 * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
39458 itemCls : "x-menu-sep",
39460 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
39462 hideOnClick : false,
39465 onRender : function(li){
39466 var s = document.createElement("span");
39467 s.className = this.itemCls;
39468 s.innerHTML = " ";
39470 li.addClass("x-menu-sep-li");
39471 Roo.menu.Separator.superclass.onRender.apply(this, arguments);
39475 * Ext JS Library 1.1.1
39476 * Copyright(c) 2006-2007, Ext JS, LLC.
39478 * Originally Released Under LGPL - original licence link has changed is not relivant.
39481 * <script type="text/javascript">
39484 * @class Roo.menu.Item
39485 * @extends Roo.menu.BaseItem
39486 * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
39487 * display items. Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
39488 * activation and click handling.
39490 * Creates a new Item
39491 * @param {Object} config Configuration options
39493 Roo.menu.Item = function(config){
39494 Roo.menu.Item.superclass.constructor.call(this, config);
39496 this.menu = Roo.menu.MenuMgr.get(this.menu);
39499 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
39501 * @cfg {Roo.menu.Menu} menu
39505 * @cfg {String} text
39506 * The text to show on the menu item.
39510 * @cfg {String} HTML to render in menu
39511 * The text to show on the menu item (HTML version).
39515 * @cfg {String} icon
39516 * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
39520 * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
39522 itemCls : "x-menu-item",
39524 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
39526 canActivate : true,
39528 * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
39531 // doc'd in BaseItem
39535 ctype: "Roo.menu.Item",
39538 onRender : function(container, position){
39539 var el = document.createElement("a");
39540 el.hideFocus = true;
39541 el.unselectable = "on";
39542 el.href = this.href || "#";
39543 if(this.hrefTarget){
39544 el.target = this.hrefTarget;
39546 el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : "");
39548 var html = this.html.length ? this.html : String.format('{0}',this.text);
39550 el.innerHTML = String.format(
39551 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
39552 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
39554 Roo.menu.Item.superclass.onRender.call(this, container, position);
39558 * Sets the text to display in this menu item
39559 * @param {String} text The text to display
39560 * @param {Boolean} isHTML true to indicate text is pure html.
39562 setText : function(text, isHTML){
39570 var html = this.html.length ? this.html : String.format('{0}',this.text);
39572 this.el.update(String.format(
39573 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
39574 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
39575 this.parentMenu.autoWidth();
39580 handleClick : function(e){
39581 if(!this.href){ // if no link defined, stop the event automatically
39584 Roo.menu.Item.superclass.handleClick.apply(this, arguments);
39588 activate : function(autoExpand){
39589 if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
39599 shouldDeactivate : function(e){
39600 if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
39601 if(this.menu && this.menu.isVisible()){
39602 return !this.menu.getEl().getRegion().contains(e.getPoint());
39610 deactivate : function(){
39611 Roo.menu.Item.superclass.deactivate.apply(this, arguments);
39616 expandMenu : function(autoActivate){
39617 if(!this.disabled && this.menu){
39618 clearTimeout(this.hideTimer);
39619 delete this.hideTimer;
39620 if(!this.menu.isVisible() && !this.showTimer){
39621 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
39622 }else if (this.menu.isVisible() && autoActivate){
39623 this.menu.tryActivate(0, 1);
39629 deferExpand : function(autoActivate){
39630 delete this.showTimer;
39631 this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
39633 this.menu.tryActivate(0, 1);
39638 hideMenu : function(){
39639 clearTimeout(this.showTimer);
39640 delete this.showTimer;
39641 if(!this.hideTimer && this.menu && this.menu.isVisible()){
39642 this.hideTimer = this.deferHide.defer(this.hideDelay, this);
39647 deferHide : function(){
39648 delete this.hideTimer;
39653 * Ext JS Library 1.1.1
39654 * Copyright(c) 2006-2007, Ext JS, LLC.
39656 * Originally Released Under LGPL - original licence link has changed is not relivant.
39659 * <script type="text/javascript">
39663 * @class Roo.menu.CheckItem
39664 * @extends Roo.menu.Item
39665 * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
39667 * Creates a new CheckItem
39668 * @param {Object} config Configuration options
39670 Roo.menu.CheckItem = function(config){
39671 Roo.menu.CheckItem.superclass.constructor.call(this, config);
39674 * @event beforecheckchange
39675 * Fires before the checked value is set, providing an opportunity to cancel if needed
39676 * @param {Roo.menu.CheckItem} this
39677 * @param {Boolean} checked The new checked value that will be set
39679 "beforecheckchange" : true,
39681 * @event checkchange
39682 * Fires after the checked value has been set
39683 * @param {Roo.menu.CheckItem} this
39684 * @param {Boolean} checked The checked value that was set
39686 "checkchange" : true
39688 if(this.checkHandler){
39689 this.on('checkchange', this.checkHandler, this.scope);
39692 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
39694 * @cfg {String} group
39695 * All check items with the same group name will automatically be grouped into a single-select
39696 * radio button group (defaults to '')
39699 * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
39701 itemCls : "x-menu-item x-menu-check-item",
39703 * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
39705 groupClass : "x-menu-group-item",
39708 * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false). Note that
39709 * if this checkbox is part of a radio group (group = true) only the last item in the group that is
39710 * initialized with checked = true will be rendered as checked.
39715 ctype: "Roo.menu.CheckItem",
39718 onRender : function(c){
39719 Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
39721 this.el.addClass(this.groupClass);
39723 Roo.menu.MenuMgr.registerCheckable(this);
39725 this.checked = false;
39726 this.setChecked(true, true);
39731 destroy : function(){
39733 Roo.menu.MenuMgr.unregisterCheckable(this);
39735 Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
39739 * Set the checked state of this item
39740 * @param {Boolean} checked The new checked value
39741 * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
39743 setChecked : function(state, suppressEvent){
39744 if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
39745 if(this.container){
39746 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
39748 this.checked = state;
39749 if(suppressEvent !== true){
39750 this.fireEvent("checkchange", this, state);
39756 handleClick : function(e){
39757 if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
39758 this.setChecked(!this.checked);
39760 Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
39764 * Ext JS Library 1.1.1
39765 * Copyright(c) 2006-2007, Ext JS, LLC.
39767 * Originally Released Under LGPL - original licence link has changed is not relivant.
39770 * <script type="text/javascript">
39774 * @class Roo.menu.DateItem
39775 * @extends Roo.menu.Adapter
39776 * A menu item that wraps the {@link Roo.DatPicker} component.
39778 * Creates a new DateItem
39779 * @param {Object} config Configuration options
39781 Roo.menu.DateItem = function(config){
39782 Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
39783 /** The Roo.DatePicker object @type Roo.DatePicker */
39784 this.picker = this.component;
39785 this.addEvents({select: true});
39787 this.picker.on("render", function(picker){
39788 picker.getEl().swallowEvent("click");
39789 picker.container.addClass("x-menu-date-item");
39792 this.picker.on("select", this.onSelect, this);
39795 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
39797 onSelect : function(picker, date){
39798 this.fireEvent("select", this, date, picker);
39799 Roo.menu.DateItem.superclass.handleClick.call(this);
39803 * Ext JS Library 1.1.1
39804 * Copyright(c) 2006-2007, Ext JS, LLC.
39806 * Originally Released Under LGPL - original licence link has changed is not relivant.
39809 * <script type="text/javascript">
39813 * @class Roo.menu.ColorItem
39814 * @extends Roo.menu.Adapter
39815 * A menu item that wraps the {@link Roo.ColorPalette} component.
39817 * Creates a new ColorItem
39818 * @param {Object} config Configuration options
39820 Roo.menu.ColorItem = function(config){
39821 Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
39822 /** The Roo.ColorPalette object @type Roo.ColorPalette */
39823 this.palette = this.component;
39824 this.relayEvents(this.palette, ["select"]);
39825 if(this.selectHandler){
39826 this.on('select', this.selectHandler, this.scope);
39829 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
39831 * Ext JS Library 1.1.1
39832 * Copyright(c) 2006-2007, Ext JS, LLC.
39834 * Originally Released Under LGPL - original licence link has changed is not relivant.
39837 * <script type="text/javascript">
39842 * @class Roo.menu.DateMenu
39843 * @extends Roo.menu.Menu
39844 * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
39846 * Creates a new DateMenu
39847 * @param {Object} config Configuration options
39849 Roo.menu.DateMenu = function(config){
39850 Roo.menu.DateMenu.superclass.constructor.call(this, config);
39852 var di = new Roo.menu.DateItem(config);
39855 * The {@link Roo.DatePicker} instance for this DateMenu
39858 this.picker = di.picker;
39861 * @param {DatePicker} picker
39862 * @param {Date} date
39864 this.relayEvents(di, ["select"]);
39865 this.on('beforeshow', function(){
39867 this.picker.hideMonthPicker(false);
39871 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
39875 * Ext JS Library 1.1.1
39876 * Copyright(c) 2006-2007, Ext JS, LLC.
39878 * Originally Released Under LGPL - original licence link has changed is not relivant.
39881 * <script type="text/javascript">
39886 * @class Roo.menu.ColorMenu
39887 * @extends Roo.menu.Menu
39888 * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
39890 * Creates a new ColorMenu
39891 * @param {Object} config Configuration options
39893 Roo.menu.ColorMenu = function(config){
39894 Roo.menu.ColorMenu.superclass.constructor.call(this, config);
39896 var ci = new Roo.menu.ColorItem(config);
39899 * The {@link Roo.ColorPalette} instance for this ColorMenu
39900 * @type ColorPalette
39902 this.palette = ci.palette;
39905 * @param {ColorPalette} palette
39906 * @param {String} color
39908 this.relayEvents(ci, ["select"]);
39910 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
39912 * Ext JS Library 1.1.1
39913 * Copyright(c) 2006-2007, Ext JS, LLC.
39915 * Originally Released Under LGPL - original licence link has changed is not relivant.
39918 * <script type="text/javascript">
39922 * @class Roo.form.TextItem
39923 * @extends Roo.BoxComponent
39924 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
39926 * Creates a new TextItem
39927 * @param {Object} config Configuration options
39929 Roo.form.TextItem = function(config){
39930 Roo.form.TextItem.superclass.constructor.call(this, config);
39933 Roo.extend(Roo.form.TextItem, Roo.BoxComponent, {
39936 * @cfg {String} tag the tag for this item (default div)
39940 * @cfg {String} html the content for this item
39944 getAutoCreate : function()
39957 onRender : function(ct, position)
39959 Roo.form.TextItem.superclass.onRender.call(this, ct, position);
39962 var cfg = this.getAutoCreate();
39964 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
39966 if (!cfg.name.length) {
39969 this.el = ct.createChild(cfg, position);
39974 * @param {String} html update the Contents of the element.
39976 setHTML : function(html)
39978 this.fieldEl.dom.innerHTML = html;
39983 * Ext JS Library 1.1.1
39984 * Copyright(c) 2006-2007, Ext JS, LLC.
39986 * Originally Released Under LGPL - original licence link has changed is not relivant.
39989 * <script type="text/javascript">
39993 * @class Roo.form.Field
39994 * @extends Roo.BoxComponent
39995 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
39997 * Creates a new Field
39998 * @param {Object} config Configuration options
40000 Roo.form.Field = function(config){
40001 Roo.form.Field.superclass.constructor.call(this, config);
40004 Roo.extend(Roo.form.Field, Roo.BoxComponent, {
40006 * @cfg {String} fieldLabel Label to use when rendering a form.
40009 * @cfg {String} qtip Mouse over tip
40013 * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
40015 invalidClass : "x-form-invalid",
40017 * @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")
40019 invalidText : "The value in this field is invalid",
40021 * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
40023 focusClass : "x-form-focus",
40025 * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
40026 automatic validation (defaults to "keyup").
40028 validationEvent : "keyup",
40030 * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
40032 validateOnBlur : true,
40034 * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
40036 validationDelay : 250,
40038 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
40039 * {tag: "input", type: "text", size: "20", autocomplete: "off"})
40041 defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
40043 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
40045 fieldClass : "x-form-field",
40047 * @cfg {String} msgTarget The location where error text should display. Should be one of the following values (defaults to 'qtip'):
40050 ----------- ----------------------------------------------------------------------
40051 qtip Display a quick tip when the user hovers over the field
40052 title Display a default browser title attribute popup
40053 under Add a block div beneath the field containing the error text
40054 side Add an error icon to the right of the field with a popup on hover
40055 [element id] Add the error text directly to the innerHTML of the specified element
40058 msgTarget : 'qtip',
40060 * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
40065 * @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.
40070 * @cfg {Boolean} disabled True to disable the field (defaults to false).
40075 * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
40077 inputType : undefined,
40080 * @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).
40082 tabIndex : undefined,
40085 isFormField : true,
40090 * @property {Roo.Element} fieldEl
40091 * Element Containing the rendered Field (with label etc.)
40094 * @cfg {Mixed} value A value to initialize this field with.
40099 * @cfg {String} name The field's HTML name attribute.
40102 * @cfg {String} cls A CSS class to apply to the field's underlying element.
40105 loadedValue : false,
40109 initComponent : function(){
40110 Roo.form.Field.superclass.initComponent.call(this);
40114 * Fires when this field receives input focus.
40115 * @param {Roo.form.Field} this
40120 * Fires when this field loses input focus.
40121 * @param {Roo.form.Field} this
40125 * @event specialkey
40126 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
40127 * {@link Roo.EventObject#getKey} to determine which key was pressed.
40128 * @param {Roo.form.Field} this
40129 * @param {Roo.EventObject} e The event object
40134 * Fires just before the field blurs if the field value has changed.
40135 * @param {Roo.form.Field} this
40136 * @param {Mixed} newValue The new value
40137 * @param {Mixed} oldValue The original value
40142 * Fires after the field has been marked as invalid.
40143 * @param {Roo.form.Field} this
40144 * @param {String} msg The validation message
40149 * Fires after the field has been validated with no errors.
40150 * @param {Roo.form.Field} this
40155 * Fires after the key up
40156 * @param {Roo.form.Field} this
40157 * @param {Roo.EventObject} e The event Object
40164 * Returns the name attribute of the field if available
40165 * @return {String} name The field name
40167 getName: function(){
40168 return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
40172 onRender : function(ct, position){
40173 Roo.form.Field.superclass.onRender.call(this, ct, position);
40175 var cfg = this.getAutoCreate();
40177 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
40179 if (!cfg.name.length) {
40182 if(this.inputType){
40183 cfg.type = this.inputType;
40185 this.el = ct.createChild(cfg, position);
40187 var type = this.el.dom.type;
40189 if(type == 'password'){
40192 this.el.addClass('x-form-'+type);
40195 this.el.dom.readOnly = true;
40197 if(this.tabIndex !== undefined){
40198 this.el.dom.setAttribute('tabIndex', this.tabIndex);
40201 this.el.addClass([this.fieldClass, this.cls]);
40206 * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
40207 * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
40208 * @return {Roo.form.Field} this
40210 applyTo : function(target){
40211 this.allowDomMove = false;
40212 this.el = Roo.get(target);
40213 this.render(this.el.dom.parentNode);
40218 initValue : function(){
40219 if(this.value !== undefined){
40220 this.setValue(this.value);
40221 }else if(this.el.dom.value.length > 0){
40222 this.setValue(this.el.dom.value);
40227 * Returns true if this field has been changed since it was originally loaded and is not disabled.
40228 * DEPRICATED - it never worked well - use hasChanged/resetHasChanged.
40230 isDirty : function() {
40231 if(this.disabled) {
40234 return String(this.getValue()) !== String(this.originalValue);
40238 * stores the current value in loadedValue
40240 resetHasChanged : function()
40242 this.loadedValue = String(this.getValue());
40245 * checks the current value against the 'loaded' value.
40246 * Note - will return false if 'resetHasChanged' has not been called first.
40248 hasChanged : function()
40250 if(this.disabled || this.readOnly) {
40253 return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
40259 afterRender : function(){
40260 Roo.form.Field.superclass.afterRender.call(this);
40265 fireKey : function(e){
40266 //Roo.log('field ' + e.getKey());
40267 if(e.isNavKeyPress()){
40268 this.fireEvent("specialkey", this, e);
40273 * Resets the current field value to the originally loaded value and clears any validation messages
40275 reset : function(){
40276 this.setValue(this.resetValue);
40277 this.originalValue = this.getValue();
40278 this.clearInvalid();
40282 initEvents : function(){
40283 // safari killled keypress - so keydown is now used..
40284 this.el.on("keydown" , this.fireKey, this);
40285 this.el.on("focus", this.onFocus, this);
40286 this.el.on("blur", this.onBlur, this);
40287 this.el.relayEvent('keyup', this);
40289 // reference to original value for reset
40290 this.originalValue = this.getValue();
40291 this.resetValue = this.getValue();
40295 onFocus : function(){
40296 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
40297 this.el.addClass(this.focusClass);
40299 if(!this.hasFocus){
40300 this.hasFocus = true;
40301 this.startValue = this.getValue();
40302 this.fireEvent("focus", this);
40306 beforeBlur : Roo.emptyFn,
40309 onBlur : function(){
40311 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
40312 this.el.removeClass(this.focusClass);
40314 this.hasFocus = false;
40315 if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
40318 var v = this.getValue();
40319 if(String(v) !== String(this.startValue)){
40320 this.fireEvent('change', this, v, this.startValue);
40322 this.fireEvent("blur", this);
40326 * Returns whether or not the field value is currently valid
40327 * @param {Boolean} preventMark True to disable marking the field invalid
40328 * @return {Boolean} True if the value is valid, else false
40330 isValid : function(preventMark){
40334 var restore = this.preventMark;
40335 this.preventMark = preventMark === true;
40336 var v = this.validateValue(this.processValue(this.getRawValue()));
40337 this.preventMark = restore;
40342 * Validates the field value
40343 * @return {Boolean} True if the value is valid, else false
40345 validate : function(){
40346 if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
40347 this.clearInvalid();
40353 processValue : function(value){
40358 // Subclasses should provide the validation implementation by overriding this
40359 validateValue : function(value){
40364 * Mark this field as invalid
40365 * @param {String} msg The validation message
40367 markInvalid : function(msg){
40368 if(!this.rendered || this.preventMark){ // not rendered
40372 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
40374 obj.el.addClass(this.invalidClass);
40375 msg = msg || this.invalidText;
40376 switch(this.msgTarget){
40378 obj.el.dom.qtip = msg;
40379 obj.el.dom.qclass = 'x-form-invalid-tip';
40380 if(Roo.QuickTips){ // fix for floating editors interacting with DND
40381 Roo.QuickTips.enable();
40385 this.el.dom.title = msg;
40389 var elp = this.el.findParent('.x-form-element', 5, true);
40390 this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
40391 this.errorEl.setWidth(elp.getWidth(true)-20);
40393 this.errorEl.update(msg);
40394 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
40397 if(!this.errorIcon){
40398 var elp = this.el.findParent('.x-form-element', 5, true);
40399 this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
40401 this.alignErrorIcon();
40402 this.errorIcon.dom.qtip = msg;
40403 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
40404 this.errorIcon.show();
40405 this.on('resize', this.alignErrorIcon, this);
40408 var t = Roo.getDom(this.msgTarget);
40410 t.style.display = this.msgDisplay;
40413 this.fireEvent('invalid', this, msg);
40417 alignErrorIcon : function(){
40418 this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
40422 * Clear any invalid styles/messages for this field
40424 clearInvalid : function(){
40425 if(!this.rendered || this.preventMark){ // not rendered
40428 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
40430 obj.el.removeClass(this.invalidClass);
40431 switch(this.msgTarget){
40433 obj.el.dom.qtip = '';
40436 this.el.dom.title = '';
40440 Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
40444 if(this.errorIcon){
40445 this.errorIcon.dom.qtip = '';
40446 this.errorIcon.hide();
40447 this.un('resize', this.alignErrorIcon, this);
40451 var t = Roo.getDom(this.msgTarget);
40453 t.style.display = 'none';
40456 this.fireEvent('valid', this);
40460 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
40461 * @return {Mixed} value The field value
40463 getRawValue : function(){
40464 var v = this.el.getValue();
40470 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
40471 * @return {Mixed} value The field value
40473 getValue : function(){
40474 var v = this.el.getValue();
40480 * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
40481 * @param {Mixed} value The value to set
40483 setRawValue : function(v){
40484 return this.el.dom.value = (v === null || v === undefined ? '' : v);
40488 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
40489 * @param {Mixed} value The value to set
40491 setValue : function(v){
40494 this.el.dom.value = (v === null || v === undefined ? '' : v);
40499 adjustSize : function(w, h){
40500 var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
40501 s.width = this.adjustWidth(this.el.dom.tagName, s.width);
40505 adjustWidth : function(tag, w){
40506 tag = tag.toLowerCase();
40507 if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
40508 if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
40509 if(tag == 'input'){
40512 if(tag == 'textarea'){
40515 }else if(Roo.isOpera){
40516 if(tag == 'input'){
40519 if(tag == 'textarea'){
40529 // anything other than normal should be considered experimental
40530 Roo.form.Field.msgFx = {
40532 show: function(msgEl, f){
40533 msgEl.setDisplayed('block');
40536 hide : function(msgEl, f){
40537 msgEl.setDisplayed(false).update('');
40542 show: function(msgEl, f){
40543 msgEl.slideIn('t', {stopFx:true});
40546 hide : function(msgEl, f){
40547 msgEl.slideOut('t', {stopFx:true,useDisplay:true});
40552 show: function(msgEl, f){
40553 msgEl.fixDisplay();
40554 msgEl.alignTo(f.el, 'tl-tr');
40555 msgEl.slideIn('l', {stopFx:true});
40558 hide : function(msgEl, f){
40559 msgEl.slideOut('l', {stopFx:true,useDisplay:true});
40564 * Ext JS Library 1.1.1
40565 * Copyright(c) 2006-2007, Ext JS, LLC.
40567 * Originally Released Under LGPL - original licence link has changed is not relivant.
40570 * <script type="text/javascript">
40575 * @class Roo.form.TextField
40576 * @extends Roo.form.Field
40577 * Basic text field. Can be used as a direct replacement for traditional text inputs, or as the base
40578 * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
40580 * Creates a new TextField
40581 * @param {Object} config Configuration options
40583 Roo.form.TextField = function(config){
40584 Roo.form.TextField.superclass.constructor.call(this, config);
40588 * Fires when the autosize function is triggered. The field may or may not have actually changed size
40589 * according to the default logic, but this event provides a hook for the developer to apply additional
40590 * logic at runtime to resize the field if needed.
40591 * @param {Roo.form.Field} this This text field
40592 * @param {Number} width The new field width
40598 Roo.extend(Roo.form.TextField, Roo.form.Field, {
40600 * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
40604 * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
40608 * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
40612 * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
40616 * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
40620 * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
40622 disableKeyFilter : false,
40624 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
40628 * @cfg {Number} minLength Minimum input field length required (defaults to 0)
40632 * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
40634 maxLength : Number.MAX_VALUE,
40636 * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
40638 minLengthText : "The minimum length for this field is {0}",
40640 * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
40642 maxLengthText : "The maximum length for this field is {0}",
40644 * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
40646 selectOnFocus : false,
40648 * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space
40650 allowLeadingSpace : false,
40652 * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
40654 blankText : "This field is required",
40656 * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
40657 * If available, this function will be called only after the basic validators all return true, and will be passed the
40658 * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
40662 * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
40663 * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
40664 * current field value. If the test fails, the field will be marked invalid using {@link #regexText}.
40668 * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
40672 * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
40678 initEvents : function()
40680 if (this.emptyText) {
40681 this.el.attr('placeholder', this.emptyText);
40684 Roo.form.TextField.superclass.initEvents.call(this);
40685 if(this.validationEvent == 'keyup'){
40686 this.validationTask = new Roo.util.DelayedTask(this.validate, this);
40687 this.el.on('keyup', this.filterValidation, this);
40689 else if(this.validationEvent !== false){
40690 this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
40693 if(this.selectOnFocus){
40694 this.on("focus", this.preFocus, this);
40696 if (!this.allowLeadingSpace) {
40697 this.on('blur', this.cleanLeadingSpace, this);
40700 if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
40701 this.el.on("keypress", this.filterKeys, this);
40704 this.el.on("keyup", this.onKeyUp, this, {buffer:50});
40705 this.el.on("click", this.autoSize, this);
40707 if(this.el.is('input[type=password]') && Roo.isSafari){
40708 this.el.on('keydown', this.SafariOnKeyDown, this);
40712 processValue : function(value){
40713 if(this.stripCharsRe){
40714 var newValue = value.replace(this.stripCharsRe, '');
40715 if(newValue !== value){
40716 this.setRawValue(newValue);
40723 filterValidation : function(e){
40724 if(!e.isNavKeyPress()){
40725 this.validationTask.delay(this.validationDelay);
40730 onKeyUp : function(e){
40731 if(!e.isNavKeyPress()){
40735 // private - clean the leading white space
40736 cleanLeadingSpace : function(e)
40738 if ( this.inputType == 'file') {
40742 this.setValue((this.getValue() + '').replace(/^\s+/,''));
40745 * Resets the current field value to the originally-loaded value and clears any validation messages.
40748 reset : function(){
40749 Roo.form.TextField.superclass.reset.call(this);
40753 preFocus : function(){
40755 if(this.selectOnFocus){
40756 this.el.dom.select();
40762 filterKeys : function(e){
40763 var k = e.getKey();
40764 if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
40767 var c = e.getCharCode(), cc = String.fromCharCode(c);
40768 if(Roo.isIE && (e.isSpecialKey() || !cc)){
40771 if(!this.maskRe.test(cc)){
40776 setValue : function(v){
40778 Roo.form.TextField.superclass.setValue.apply(this, arguments);
40784 * Validates a value according to the field's validation rules and marks the field as invalid
40785 * if the validation fails
40786 * @param {Mixed} value The value to validate
40787 * @return {Boolean} True if the value is valid, else false
40789 validateValue : function(value){
40790 if(value.length < 1) { // if it's blank
40791 if(this.allowBlank){
40792 this.clearInvalid();
40795 this.markInvalid(this.blankText);
40799 if(value.length < this.minLength){
40800 this.markInvalid(String.format(this.minLengthText, this.minLength));
40803 if(value.length > this.maxLength){
40804 this.markInvalid(String.format(this.maxLengthText, this.maxLength));
40808 var vt = Roo.form.VTypes;
40809 if(!vt[this.vtype](value, this)){
40810 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
40814 if(typeof this.validator == "function"){
40815 var msg = this.validator(value);
40817 this.markInvalid(msg);
40821 if(this.regex && !this.regex.test(value)){
40822 this.markInvalid(this.regexText);
40829 * Selects text in this field
40830 * @param {Number} start (optional) The index where the selection should start (defaults to 0)
40831 * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
40833 selectText : function(start, end){
40834 var v = this.getRawValue();
40836 start = start === undefined ? 0 : start;
40837 end = end === undefined ? v.length : end;
40838 var d = this.el.dom;
40839 if(d.setSelectionRange){
40840 d.setSelectionRange(start, end);
40841 }else if(d.createTextRange){
40842 var range = d.createTextRange();
40843 range.moveStart("character", start);
40844 range.moveEnd("character", v.length-end);
40851 * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
40852 * This only takes effect if grow = true, and fires the autosize event.
40854 autoSize : function(){
40855 if(!this.grow || !this.rendered){
40859 this.metrics = Roo.util.TextMetrics.createInstance(this.el);
40862 var v = el.dom.value;
40863 var d = document.createElement('div');
40864 d.appendChild(document.createTextNode(v));
40868 var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
40869 this.el.setWidth(w);
40870 this.fireEvent("autosize", this, w);
40874 SafariOnKeyDown : function(event)
40876 // this is a workaround for a password hang bug on chrome/ webkit.
40878 var isSelectAll = false;
40880 if(this.el.dom.selectionEnd > 0){
40881 isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
40883 if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
40884 event.preventDefault();
40889 if(isSelectAll && event.getCharCode() > 31){ // backspace and delete key
40891 event.preventDefault();
40892 // this is very hacky as keydown always get's upper case.
40894 var cc = String.fromCharCode(event.getCharCode());
40897 this.setValue( event.shiftKey ? cc : cc.toLowerCase());
40905 * Ext JS Library 1.1.1
40906 * Copyright(c) 2006-2007, Ext JS, LLC.
40908 * Originally Released Under LGPL - original licence link has changed is not relivant.
40911 * <script type="text/javascript">
40915 * @class Roo.form.Hidden
40916 * @extends Roo.form.TextField
40917 * Simple Hidden element used on forms
40919 * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
40922 * Creates a new Hidden form element.
40923 * @param {Object} config Configuration options
40928 // easy hidden field...
40929 Roo.form.Hidden = function(config){
40930 Roo.form.Hidden.superclass.constructor.call(this, config);
40933 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
40935 inputType: 'hidden',
40938 labelSeparator: '',
40940 itemCls : 'x-form-item-display-none'
40948 * Ext JS Library 1.1.1
40949 * Copyright(c) 2006-2007, Ext JS, LLC.
40951 * Originally Released Under LGPL - original licence link has changed is not relivant.
40954 * <script type="text/javascript">
40958 * @class Roo.form.TriggerField
40959 * @extends Roo.form.TextField
40960 * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
40961 * The trigger has no default action, so you must assign a function to implement the trigger click handler by
40962 * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
40963 * for which you can provide a custom implementation. For example:
40965 var trigger = new Roo.form.TriggerField();
40966 trigger.onTriggerClick = myTriggerFn;
40967 trigger.applyTo('my-field');
40970 * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
40971 * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
40972 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
40973 * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
40975 * Create a new TriggerField.
40976 * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
40977 * to the base TextField)
40979 Roo.form.TriggerField = function(config){
40980 this.mimicing = false;
40981 Roo.form.TriggerField.superclass.constructor.call(this, config);
40984 Roo.extend(Roo.form.TriggerField, Roo.form.TextField, {
40986 * @cfg {String} triggerClass A CSS class to apply to the trigger
40989 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
40990 * {tag: "input", type: "text", size: "16", autocomplete: "off"})
40992 defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
40994 * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
40998 /** @cfg {Boolean} grow @hide */
40999 /** @cfg {Number} growMin @hide */
41000 /** @cfg {Number} growMax @hide */
41006 autoSize: Roo.emptyFn,
41010 deferHeight : true,
41013 actionMode : 'wrap',
41015 onResize : function(w, h){
41016 Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
41017 if(typeof w == 'number'){
41018 var x = w - this.trigger.getWidth();
41019 this.el.setWidth(this.adjustWidth('input', x));
41020 this.trigger.setStyle('left', x+'px');
41025 adjustSize : Roo.BoxComponent.prototype.adjustSize,
41028 getResizeEl : function(){
41033 getPositionEl : function(){
41038 alignErrorIcon : function(){
41039 this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
41043 onRender : function(ct, position){
41044 Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
41045 this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
41046 this.trigger = this.wrap.createChild(this.triggerConfig ||
41047 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
41048 if(this.hideTrigger){
41049 this.trigger.setDisplayed(false);
41051 this.initTrigger();
41053 this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
41058 initTrigger : function(){
41059 this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
41060 this.trigger.addClassOnOver('x-form-trigger-over');
41061 this.trigger.addClassOnClick('x-form-trigger-click');
41065 onDestroy : function(){
41067 this.trigger.removeAllListeners();
41068 this.trigger.remove();
41071 this.wrap.remove();
41073 Roo.form.TriggerField.superclass.onDestroy.call(this);
41077 onFocus : function(){
41078 Roo.form.TriggerField.superclass.onFocus.call(this);
41079 if(!this.mimicing){
41080 this.wrap.addClass('x-trigger-wrap-focus');
41081 this.mimicing = true;
41082 Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
41083 if(this.monitorTab){
41084 this.el.on("keydown", this.checkTab, this);
41090 checkTab : function(e){
41091 if(e.getKey() == e.TAB){
41092 this.triggerBlur();
41097 onBlur : function(){
41102 mimicBlur : function(e, t){
41103 if(!this.wrap.contains(t) && this.validateBlur()){
41104 this.triggerBlur();
41109 triggerBlur : function(){
41110 this.mimicing = false;
41111 Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
41112 if(this.monitorTab){
41113 this.el.un("keydown", this.checkTab, this);
41115 this.wrap.removeClass('x-trigger-wrap-focus');
41116 Roo.form.TriggerField.superclass.onBlur.call(this);
41120 // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
41121 validateBlur : function(e, t){
41126 onDisable : function(){
41127 Roo.form.TriggerField.superclass.onDisable.call(this);
41129 this.wrap.addClass('x-item-disabled');
41134 onEnable : function(){
41135 Roo.form.TriggerField.superclass.onEnable.call(this);
41137 this.wrap.removeClass('x-item-disabled');
41142 onShow : function(){
41143 var ae = this.getActionEl();
41146 ae.dom.style.display = '';
41147 ae.dom.style.visibility = 'visible';
41153 onHide : function(){
41154 var ae = this.getActionEl();
41155 ae.dom.style.display = 'none';
41159 * The function that should handle the trigger's click event. This method does nothing by default until overridden
41160 * by an implementing function.
41162 * @param {EventObject} e
41164 onTriggerClick : Roo.emptyFn
41167 // TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
41168 // to be extended by an implementing class. For an example of implementing this class, see the custom
41169 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
41170 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
41171 initComponent : function(){
41172 Roo.form.TwinTriggerField.superclass.initComponent.call(this);
41174 this.triggerConfig = {
41175 tag:'span', cls:'x-form-twin-triggers', cn:[
41176 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
41177 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
41181 getTrigger : function(index){
41182 return this.triggers[index];
41185 initTrigger : function(){
41186 var ts = this.trigger.select('.x-form-trigger', true);
41187 this.wrap.setStyle('overflow', 'hidden');
41188 var triggerField = this;
41189 ts.each(function(t, all, index){
41190 t.hide = function(){
41191 var w = triggerField.wrap.getWidth();
41192 this.dom.style.display = 'none';
41193 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
41195 t.show = function(){
41196 var w = triggerField.wrap.getWidth();
41197 this.dom.style.display = '';
41198 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
41200 var triggerIndex = 'Trigger'+(index+1);
41202 if(this['hide'+triggerIndex]){
41203 t.dom.style.display = 'none';
41205 t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
41206 t.addClassOnOver('x-form-trigger-over');
41207 t.addClassOnClick('x-form-trigger-click');
41209 this.triggers = ts.elements;
41212 onTrigger1Click : Roo.emptyFn,
41213 onTrigger2Click : Roo.emptyFn
41216 * Ext JS Library 1.1.1
41217 * Copyright(c) 2006-2007, Ext JS, LLC.
41219 * Originally Released Under LGPL - original licence link has changed is not relivant.
41222 * <script type="text/javascript">
41226 * @class Roo.form.TextArea
41227 * @extends Roo.form.TextField
41228 * Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
41229 * support for auto-sizing.
41231 * Creates a new TextArea
41232 * @param {Object} config Configuration options
41234 Roo.form.TextArea = function(config){
41235 Roo.form.TextArea.superclass.constructor.call(this, config);
41236 // these are provided exchanges for backwards compat
41237 // minHeight/maxHeight were replaced by growMin/growMax to be
41238 // compatible with TextField growing config values
41239 if(this.minHeight !== undefined){
41240 this.growMin = this.minHeight;
41242 if(this.maxHeight !== undefined){
41243 this.growMax = this.maxHeight;
41247 Roo.extend(Roo.form.TextArea, Roo.form.TextField, {
41249 * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
41253 * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
41257 * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
41258 * in the field (equivalent to setting overflow: hidden, defaults to false)
41260 preventScrollbars: false,
41262 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
41263 * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
41267 onRender : function(ct, position){
41269 this.defaultAutoCreate = {
41271 style:"width:300px;height:60px;",
41272 autocomplete: "new-password"
41275 Roo.form.TextArea.superclass.onRender.call(this, ct, position);
41277 this.textSizeEl = Roo.DomHelper.append(document.body, {
41278 tag: "pre", cls: "x-form-grow-sizer"
41280 if(this.preventScrollbars){
41281 this.el.setStyle("overflow", "hidden");
41283 this.el.setHeight(this.growMin);
41287 onDestroy : function(){
41288 if(this.textSizeEl){
41289 this.textSizeEl.parentNode.removeChild(this.textSizeEl);
41291 Roo.form.TextArea.superclass.onDestroy.call(this);
41295 onKeyUp : function(e){
41296 if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
41302 * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
41303 * This only takes effect if grow = true, and fires the autosize event if the height changes.
41305 autoSize : function(){
41306 if(!this.grow || !this.textSizeEl){
41310 var v = el.dom.value;
41311 var ts = this.textSizeEl;
41314 ts.appendChild(document.createTextNode(v));
41317 Roo.fly(ts).setWidth(this.el.getWidth());
41319 v = "  ";
41322 v = v.replace(/\n/g, '<p> </p>');
41324 v += " \n ";
41327 var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
41328 if(h != this.lastHeight){
41329 this.lastHeight = h;
41330 this.el.setHeight(h);
41331 this.fireEvent("autosize", this, h);
41336 * Ext JS Library 1.1.1
41337 * Copyright(c) 2006-2007, Ext JS, LLC.
41339 * Originally Released Under LGPL - original licence link has changed is not relivant.
41342 * <script type="text/javascript">
41347 * @class Roo.form.NumberField
41348 * @extends Roo.form.TextField
41349 * Numeric text field that provides automatic keystroke filtering and numeric validation.
41351 * Creates a new NumberField
41352 * @param {Object} config Configuration options
41354 Roo.form.NumberField = function(config){
41355 Roo.form.NumberField.superclass.constructor.call(this, config);
41358 Roo.extend(Roo.form.NumberField, Roo.form.TextField, {
41360 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
41362 fieldClass: "x-form-field x-form-num-field",
41364 * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
41366 allowDecimals : true,
41368 * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
41370 decimalSeparator : ".",
41372 * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
41374 decimalPrecision : 2,
41376 * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
41378 allowNegative : true,
41380 * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
41382 minValue : Number.NEGATIVE_INFINITY,
41384 * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
41386 maxValue : Number.MAX_VALUE,
41388 * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
41390 minText : "The minimum value for this field is {0}",
41392 * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
41394 maxText : "The maximum value for this field is {0}",
41396 * @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
41397 * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
41399 nanText : "{0} is not a valid number",
41402 initEvents : function(){
41403 Roo.form.NumberField.superclass.initEvents.call(this);
41404 var allowed = "0123456789";
41405 if(this.allowDecimals){
41406 allowed += this.decimalSeparator;
41408 if(this.allowNegative){
41411 this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
41412 var keyPress = function(e){
41413 var k = e.getKey();
41414 if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
41417 var c = e.getCharCode();
41418 if(allowed.indexOf(String.fromCharCode(c)) === -1){
41422 this.el.on("keypress", keyPress, this);
41426 validateValue : function(value){
41427 if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
41430 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
41433 var num = this.parseValue(value);
41435 this.markInvalid(String.format(this.nanText, value));
41438 if(num < this.minValue){
41439 this.markInvalid(String.format(this.minText, this.minValue));
41442 if(num > this.maxValue){
41443 this.markInvalid(String.format(this.maxText, this.maxValue));
41449 getValue : function(){
41450 return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
41454 parseValue : function(value){
41455 value = parseFloat(String(value).replace(this.decimalSeparator, "."));
41456 return isNaN(value) ? '' : value;
41460 fixPrecision : function(value){
41461 var nan = isNaN(value);
41462 if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
41463 return nan ? '' : value;
41465 return parseFloat(value).toFixed(this.decimalPrecision);
41468 setValue : function(v){
41469 v = this.fixPrecision(v);
41470 Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
41474 decimalPrecisionFcn : function(v){
41475 return Math.floor(v);
41478 beforeBlur : function(){
41479 var v = this.parseValue(this.getRawValue());
41486 * Ext JS Library 1.1.1
41487 * Copyright(c) 2006-2007, Ext JS, LLC.
41489 * Originally Released Under LGPL - original licence link has changed is not relivant.
41492 * <script type="text/javascript">
41496 * @class Roo.form.DateField
41497 * @extends Roo.form.TriggerField
41498 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
41500 * Create a new DateField
41501 * @param {Object} config
41503 Roo.form.DateField = function(config)
41505 Roo.form.DateField.superclass.constructor.call(this, config);
41511 * Fires when a date is selected
41512 * @param {Roo.form.DateField} combo This combo box
41513 * @param {Date} date The date selected
41520 if(typeof this.minValue == "string") {
41521 this.minValue = this.parseDate(this.minValue);
41523 if(typeof this.maxValue == "string") {
41524 this.maxValue = this.parseDate(this.maxValue);
41526 this.ddMatch = null;
41527 if(this.disabledDates){
41528 var dd = this.disabledDates;
41530 for(var i = 0; i < dd.length; i++){
41532 if(i != dd.length-1) {
41536 this.ddMatch = new RegExp(re + ")");
41540 Roo.extend(Roo.form.DateField, Roo.form.TriggerField, {
41542 * @cfg {String} format
41543 * The default date format string which can be overriden for localization support. The format must be
41544 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
41548 * @cfg {String} altFormats
41549 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
41550 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
41552 altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
41554 * @cfg {Array} disabledDays
41555 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
41557 disabledDays : null,
41559 * @cfg {String} disabledDaysText
41560 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
41562 disabledDaysText : "Disabled",
41564 * @cfg {Array} disabledDates
41565 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
41566 * expression so they are very powerful. Some examples:
41568 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
41569 * <li>["03/08", "09/16"] would disable those days for every year</li>
41570 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
41571 * <li>["03/../2006"] would disable every day in March 2006</li>
41572 * <li>["^03"] would disable every day in every March</li>
41574 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
41575 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
41577 disabledDates : null,
41579 * @cfg {String} disabledDatesText
41580 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
41582 disabledDatesText : "Disabled",
41586 * @cfg {Date/String} zeroValue
41587 * if the date is less that this number, then the field is rendered as empty
41590 zeroValue : '1800-01-01',
41594 * @cfg {Date/String} minValue
41595 * The minimum allowed date. Can be either a Javascript date object or a string date in a
41596 * valid format (defaults to null).
41600 * @cfg {Date/String} maxValue
41601 * The maximum allowed date. Can be either a Javascript date object or a string date in a
41602 * valid format (defaults to null).
41606 * @cfg {String} minText
41607 * The error text to display when the date in the cell is before minValue (defaults to
41608 * 'The date in this field must be after {minValue}').
41610 minText : "The date in this field must be equal to or after {0}",
41612 * @cfg {String} maxText
41613 * The error text to display when the date in the cell is after maxValue (defaults to
41614 * 'The date in this field must be before {maxValue}').
41616 maxText : "The date in this field must be equal to or before {0}",
41618 * @cfg {String} invalidText
41619 * The error text to display when the date in the field is invalid (defaults to
41620 * '{value} is not a valid date - it must be in the format {format}').
41622 invalidText : "{0} is not a valid date - it must be in the format {1}",
41624 * @cfg {String} triggerClass
41625 * An additional CSS class used to style the trigger button. The trigger will always get the
41626 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
41627 * which displays a calendar icon).
41629 triggerClass : 'x-form-date-trigger',
41633 * @cfg {Boolean} useIso
41634 * if enabled, then the date field will use a hidden field to store the
41635 * real value as iso formated date. default (false)
41639 * @cfg {String/Object} autoCreate
41640 * A DomHelper element spec, or true for a default element spec (defaults to
41641 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
41644 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
41647 hiddenField: false,
41649 onRender : function(ct, position)
41651 Roo.form.DateField.superclass.onRender.call(this, ct, position);
41653 //this.el.dom.removeAttribute('name');
41654 Roo.log("Changing name?");
41655 this.el.dom.setAttribute('name', this.name + '____hidden___' );
41656 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
41658 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
41659 // prevent input submission
41660 this.hiddenName = this.name;
41667 validateValue : function(value)
41669 value = this.formatDate(value);
41670 if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
41671 Roo.log('super failed');
41674 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
41677 var svalue = value;
41678 value = this.parseDate(value);
41680 Roo.log('parse date failed' + svalue);
41681 this.markInvalid(String.format(this.invalidText, svalue, this.format));
41684 var time = value.getTime();
41685 if(this.minValue && time < this.minValue.getTime()){
41686 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
41689 if(this.maxValue && time > this.maxValue.getTime()){
41690 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
41693 if(this.disabledDays){
41694 var day = value.getDay();
41695 for(var i = 0; i < this.disabledDays.length; i++) {
41696 if(day === this.disabledDays[i]){
41697 this.markInvalid(this.disabledDaysText);
41702 var fvalue = this.formatDate(value);
41703 if(this.ddMatch && this.ddMatch.test(fvalue)){
41704 this.markInvalid(String.format(this.disabledDatesText, fvalue));
41711 // Provides logic to override the default TriggerField.validateBlur which just returns true
41712 validateBlur : function(){
41713 return !this.menu || !this.menu.isVisible();
41716 getName: function()
41718 // returns hidden if it's set..
41719 if (!this.rendered) {return ''};
41720 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
41725 * Returns the current date value of the date field.
41726 * @return {Date} The date value
41728 getValue : function(){
41730 return this.hiddenField ?
41731 this.hiddenField.value :
41732 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
41736 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
41737 * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
41738 * (the default format used is "m/d/y").
41741 //All of these calls set the same date value (May 4, 2006)
41743 //Pass a date object:
41744 var dt = new Date('5/4/06');
41745 dateField.setValue(dt);
41747 //Pass a date string (default format):
41748 dateField.setValue('5/4/06');
41750 //Pass a date string (custom format):
41751 dateField.format = 'Y-m-d';
41752 dateField.setValue('2006-5-4');
41754 * @param {String/Date} date The date or valid date string
41756 setValue : function(date){
41757 if (this.hiddenField) {
41758 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
41760 Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
41761 // make sure the value field is always stored as a date..
41762 this.value = this.parseDate(date);
41768 parseDate : function(value){
41770 if (value instanceof Date) {
41771 if (value < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
41778 if(!value || value instanceof Date){
41781 var v = Date.parseDate(value, this.format);
41782 if (!v && this.useIso) {
41783 v = Date.parseDate(value, 'Y-m-d');
41785 if(!v && this.altFormats){
41786 if(!this.altFormatsArray){
41787 this.altFormatsArray = this.altFormats.split("|");
41789 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
41790 v = Date.parseDate(value, this.altFormatsArray[i]);
41793 if (v < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
41800 formatDate : function(date, fmt){
41801 return (!date || !(date instanceof Date)) ?
41802 date : date.dateFormat(fmt || this.format);
41807 select: function(m, d){
41810 this.fireEvent('select', this, d);
41812 show : function(){ // retain focus styling
41816 this.focus.defer(10, this);
41817 var ml = this.menuListeners;
41818 this.menu.un("select", ml.select, this);
41819 this.menu.un("show", ml.show, this);
41820 this.menu.un("hide", ml.hide, this);
41825 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
41826 onTriggerClick : function(){
41830 if(this.menu == null){
41831 this.menu = new Roo.menu.DateMenu();
41833 Roo.apply(this.menu.picker, {
41834 showClear: this.allowBlank,
41835 minDate : this.minValue,
41836 maxDate : this.maxValue,
41837 disabledDatesRE : this.ddMatch,
41838 disabledDatesText : this.disabledDatesText,
41839 disabledDays : this.disabledDays,
41840 disabledDaysText : this.disabledDaysText,
41841 format : this.useIso ? 'Y-m-d' : this.format,
41842 minText : String.format(this.minText, this.formatDate(this.minValue)),
41843 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
41845 this.menu.on(Roo.apply({}, this.menuListeners, {
41848 this.menu.picker.setValue(this.getValue() || new Date());
41849 this.menu.show(this.el, "tl-bl?");
41852 beforeBlur : function(){
41853 var v = this.parseDate(this.getRawValue());
41863 isDirty : function() {
41864 if(this.disabled) {
41868 if(typeof(this.startValue) === 'undefined'){
41872 return String(this.getValue()) !== String(this.startValue);
41876 cleanLeadingSpace : function(e)
41883 * Ext JS Library 1.1.1
41884 * Copyright(c) 2006-2007, Ext JS, LLC.
41886 * Originally Released Under LGPL - original licence link has changed is not relivant.
41889 * <script type="text/javascript">
41893 * @class Roo.form.MonthField
41894 * @extends Roo.form.TriggerField
41895 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
41897 * Create a new MonthField
41898 * @param {Object} config
41900 Roo.form.MonthField = function(config){
41902 Roo.form.MonthField.superclass.constructor.call(this, config);
41908 * Fires when a date is selected
41909 * @param {Roo.form.MonthFieeld} combo This combo box
41910 * @param {Date} date The date selected
41917 if(typeof this.minValue == "string") {
41918 this.minValue = this.parseDate(this.minValue);
41920 if(typeof this.maxValue == "string") {
41921 this.maxValue = this.parseDate(this.maxValue);
41923 this.ddMatch = null;
41924 if(this.disabledDates){
41925 var dd = this.disabledDates;
41927 for(var i = 0; i < dd.length; i++){
41929 if(i != dd.length-1) {
41933 this.ddMatch = new RegExp(re + ")");
41937 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField, {
41939 * @cfg {String} format
41940 * The default date format string which can be overriden for localization support. The format must be
41941 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
41945 * @cfg {String} altFormats
41946 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
41947 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
41949 altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
41951 * @cfg {Array} disabledDays
41952 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
41954 disabledDays : [0,1,2,3,4,5,6],
41956 * @cfg {String} disabledDaysText
41957 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
41959 disabledDaysText : "Disabled",
41961 * @cfg {Array} disabledDates
41962 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
41963 * expression so they are very powerful. Some examples:
41965 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
41966 * <li>["03/08", "09/16"] would disable those days for every year</li>
41967 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
41968 * <li>["03/../2006"] would disable every day in March 2006</li>
41969 * <li>["^03"] would disable every day in every March</li>
41971 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
41972 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
41974 disabledDates : null,
41976 * @cfg {String} disabledDatesText
41977 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
41979 disabledDatesText : "Disabled",
41981 * @cfg {Date/String} minValue
41982 * The minimum allowed date. Can be either a Javascript date object or a string date in a
41983 * valid format (defaults to null).
41987 * @cfg {Date/String} maxValue
41988 * The maximum allowed date. Can be either a Javascript date object or a string date in a
41989 * valid format (defaults to null).
41993 * @cfg {String} minText
41994 * The error text to display when the date in the cell is before minValue (defaults to
41995 * 'The date in this field must be after {minValue}').
41997 minText : "The date in this field must be equal to or after {0}",
41999 * @cfg {String} maxTextf
42000 * The error text to display when the date in the cell is after maxValue (defaults to
42001 * 'The date in this field must be before {maxValue}').
42003 maxText : "The date in this field must be equal to or before {0}",
42005 * @cfg {String} invalidText
42006 * The error text to display when the date in the field is invalid (defaults to
42007 * '{value} is not a valid date - it must be in the format {format}').
42009 invalidText : "{0} is not a valid date - it must be in the format {1}",
42011 * @cfg {String} triggerClass
42012 * An additional CSS class used to style the trigger button. The trigger will always get the
42013 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
42014 * which displays a calendar icon).
42016 triggerClass : 'x-form-date-trigger',
42020 * @cfg {Boolean} useIso
42021 * if enabled, then the date field will use a hidden field to store the
42022 * real value as iso formated date. default (true)
42026 * @cfg {String/Object} autoCreate
42027 * A DomHelper element spec, or true for a default element spec (defaults to
42028 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
42031 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
42034 hiddenField: false,
42036 hideMonthPicker : false,
42038 onRender : function(ct, position)
42040 Roo.form.MonthField.superclass.onRender.call(this, ct, position);
42042 this.el.dom.removeAttribute('name');
42043 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
42045 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
42046 // prevent input submission
42047 this.hiddenName = this.name;
42054 validateValue : function(value)
42056 value = this.formatDate(value);
42057 if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
42060 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
42063 var svalue = value;
42064 value = this.parseDate(value);
42066 this.markInvalid(String.format(this.invalidText, svalue, this.format));
42069 var time = value.getTime();
42070 if(this.minValue && time < this.minValue.getTime()){
42071 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
42074 if(this.maxValue && time > this.maxValue.getTime()){
42075 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
42078 /*if(this.disabledDays){
42079 var day = value.getDay();
42080 for(var i = 0; i < this.disabledDays.length; i++) {
42081 if(day === this.disabledDays[i]){
42082 this.markInvalid(this.disabledDaysText);
42088 var fvalue = this.formatDate(value);
42089 /*if(this.ddMatch && this.ddMatch.test(fvalue)){
42090 this.markInvalid(String.format(this.disabledDatesText, fvalue));
42098 // Provides logic to override the default TriggerField.validateBlur which just returns true
42099 validateBlur : function(){
42100 return !this.menu || !this.menu.isVisible();
42104 * Returns the current date value of the date field.
42105 * @return {Date} The date value
42107 getValue : function(){
42111 return this.hiddenField ?
42112 this.hiddenField.value :
42113 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
42117 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
42118 * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
42119 * (the default format used is "m/d/y").
42122 //All of these calls set the same date value (May 4, 2006)
42124 //Pass a date object:
42125 var dt = new Date('5/4/06');
42126 monthField.setValue(dt);
42128 //Pass a date string (default format):
42129 monthField.setValue('5/4/06');
42131 //Pass a date string (custom format):
42132 monthField.format = 'Y-m-d';
42133 monthField.setValue('2006-5-4');
42135 * @param {String/Date} date The date or valid date string
42137 setValue : function(date){
42138 Roo.log('month setValue' + date);
42139 // can only be first of month..
42141 var val = this.parseDate(date);
42143 if (this.hiddenField) {
42144 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
42146 Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
42147 this.value = this.parseDate(date);
42151 parseDate : function(value){
42152 if(!value || value instanceof Date){
42153 value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
42156 var v = Date.parseDate(value, this.format);
42157 if (!v && this.useIso) {
42158 v = Date.parseDate(value, 'Y-m-d');
42162 v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
42166 if(!v && this.altFormats){
42167 if(!this.altFormatsArray){
42168 this.altFormatsArray = this.altFormats.split("|");
42170 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
42171 v = Date.parseDate(value, this.altFormatsArray[i]);
42178 formatDate : function(date, fmt){
42179 return (!date || !(date instanceof Date)) ?
42180 date : date.dateFormat(fmt || this.format);
42185 select: function(m, d){
42187 this.fireEvent('select', this, d);
42189 show : function(){ // retain focus styling
42193 this.focus.defer(10, this);
42194 var ml = this.menuListeners;
42195 this.menu.un("select", ml.select, this);
42196 this.menu.un("show", ml.show, this);
42197 this.menu.un("hide", ml.hide, this);
42201 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
42202 onTriggerClick : function(){
42206 if(this.menu == null){
42207 this.menu = new Roo.menu.DateMenu();
42211 Roo.apply(this.menu.picker, {
42213 showClear: this.allowBlank,
42214 minDate : this.minValue,
42215 maxDate : this.maxValue,
42216 disabledDatesRE : this.ddMatch,
42217 disabledDatesText : this.disabledDatesText,
42219 format : this.useIso ? 'Y-m-d' : this.format,
42220 minText : String.format(this.minText, this.formatDate(this.minValue)),
42221 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
42224 this.menu.on(Roo.apply({}, this.menuListeners, {
42232 // hide month picker get's called when we called by 'before hide';
42234 var ignorehide = true;
42235 p.hideMonthPicker = function(disableAnim){
42239 if(this.monthPicker){
42240 Roo.log("hideMonthPicker called");
42241 if(disableAnim === true){
42242 this.monthPicker.hide();
42244 this.monthPicker.slideOut('t', {duration:.2});
42245 p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
42246 p.fireEvent("select", this, this.value);
42252 Roo.log('picker set value');
42253 Roo.log(this.getValue());
42254 p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
42255 m.show(this.el, 'tl-bl?');
42256 ignorehide = false;
42257 // this will trigger hideMonthPicker..
42260 // hidden the day picker
42261 Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
42267 p.showMonthPicker.defer(100, p);
42273 beforeBlur : function(){
42274 var v = this.parseDate(this.getRawValue());
42280 /** @cfg {Boolean} grow @hide */
42281 /** @cfg {Number} growMin @hide */
42282 /** @cfg {Number} growMax @hide */
42289 * Ext JS Library 1.1.1
42290 * Copyright(c) 2006-2007, Ext JS, LLC.
42292 * Originally Released Under LGPL - original licence link has changed is not relivant.
42295 * <script type="text/javascript">
42300 * @class Roo.form.ComboBox
42301 * @extends Roo.form.TriggerField
42302 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
42304 * Create a new ComboBox.
42305 * @param {Object} config Configuration options
42307 Roo.form.ComboBox = function(config){
42308 Roo.form.ComboBox.superclass.constructor.call(this, config);
42312 * Fires when the dropdown list is expanded
42313 * @param {Roo.form.ComboBox} combo This combo box
42318 * Fires when the dropdown list is collapsed
42319 * @param {Roo.form.ComboBox} combo This combo box
42323 * @event beforeselect
42324 * Fires before a list item is selected. Return false to cancel the selection.
42325 * @param {Roo.form.ComboBox} combo This combo box
42326 * @param {Roo.data.Record} record The data record returned from the underlying store
42327 * @param {Number} index The index of the selected item in the dropdown list
42329 'beforeselect' : true,
42332 * Fires when a list item is selected
42333 * @param {Roo.form.ComboBox} combo This combo box
42334 * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
42335 * @param {Number} index The index of the selected item in the dropdown list
42339 * @event beforequery
42340 * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
42341 * The event object passed has these properties:
42342 * @param {Roo.form.ComboBox} combo This combo box
42343 * @param {String} query The query
42344 * @param {Boolean} forceAll true to force "all" query
42345 * @param {Boolean} cancel true to cancel the query
42346 * @param {Object} e The query event object
42348 'beforequery': true,
42351 * Fires when the 'add' icon is pressed (add a listener to enable add button)
42352 * @param {Roo.form.ComboBox} combo This combo box
42357 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
42358 * @param {Roo.form.ComboBox} combo This combo box
42359 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
42365 if(this.transform){
42366 this.allowDomMove = false;
42367 var s = Roo.getDom(this.transform);
42368 if(!this.hiddenName){
42369 this.hiddenName = s.name;
42372 this.mode = 'local';
42373 var d = [], opts = s.options;
42374 for(var i = 0, len = opts.length;i < len; i++){
42376 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
42378 this.value = value;
42380 d.push([value, o.text]);
42382 this.store = new Roo.data.SimpleStore({
42384 fields: ['value', 'text'],
42387 this.valueField = 'value';
42388 this.displayField = 'text';
42390 s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
42391 if(!this.lazyRender){
42392 this.target = true;
42393 this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
42394 s.parentNode.removeChild(s); // remove it
42395 this.render(this.el.parentNode);
42397 s.parentNode.removeChild(s); // remove it
42402 this.store = Roo.factory(this.store, Roo.data);
42405 this.selectedIndex = -1;
42406 if(this.mode == 'local'){
42407 if(config.queryDelay === undefined){
42408 this.queryDelay = 10;
42410 if(config.minChars === undefined){
42416 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
42418 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
42421 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
42422 * rendering into an Roo.Editor, defaults to false)
42425 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
42426 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
42429 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
42432 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
42433 * the dropdown list (defaults to undefined, with no header element)
42437 * @cfg {String/Roo.Template} tpl The template to use to render the output
42441 defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
42443 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
42445 listWidth: undefined,
42447 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
42448 * mode = 'remote' or 'text' if mode = 'local')
42450 displayField: undefined,
42452 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
42453 * mode = 'remote' or 'value' if mode = 'local').
42454 * Note: use of a valueField requires the user make a selection
42455 * in order for a value to be mapped.
42457 valueField: undefined,
42461 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
42462 * field's data value (defaults to the underlying DOM element's name)
42464 hiddenName: undefined,
42466 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
42470 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
42472 selectedClass: 'x-combo-selected',
42474 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
42475 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
42476 * which displays a downward arrow icon).
42478 triggerClass : 'x-form-arrow-trigger',
42480 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
42484 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
42485 * anchor positions (defaults to 'tl-bl')
42487 listAlign: 'tl-bl?',
42489 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
42493 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
42494 * query specified by the allQuery config option (defaults to 'query')
42496 triggerAction: 'query',
42498 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
42499 * (defaults to 4, does not apply if editable = false)
42503 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
42504 * delay (typeAheadDelay) if it matches a known value (defaults to false)
42508 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
42509 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
42513 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
42514 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
42518 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
42519 * when editable = true (defaults to false)
42521 selectOnFocus:false,
42523 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
42525 queryParam: 'query',
42527 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
42528 * when mode = 'remote' (defaults to 'Loading...')
42530 loadingText: 'Loading...',
42532 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
42536 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
42540 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
42541 * traditional select (defaults to true)
42545 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
42549 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
42553 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
42554 * listWidth has a higher value)
42558 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
42559 * allow the user to set arbitrary text into the field (defaults to false)
42561 forceSelection:false,
42563 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
42564 * if typeAhead = true (defaults to 250)
42566 typeAheadDelay : 250,
42568 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
42569 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
42571 valueNotFoundText : undefined,
42573 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
42575 blockFocus : false,
42578 * @cfg {Boolean} disableClear Disable showing of clear button.
42580 disableClear : false,
42582 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
42584 alwaysQuery : false,
42590 // element that contains real text value.. (when hidden is used..)
42593 onRender : function(ct, position)
42595 Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
42597 if(this.hiddenName){
42598 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
42600 this.hiddenField.value =
42601 this.hiddenValue !== undefined ? this.hiddenValue :
42602 this.value !== undefined ? this.value : '';
42604 // prevent input submission
42605 this.el.dom.removeAttribute('name');
42611 this.el.dom.setAttribute('autocomplete', 'off');
42614 var cls = 'x-combo-list';
42616 this.list = new Roo.Layer({
42617 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
42620 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
42621 this.list.setWidth(lw);
42622 this.list.swallowEvent('mousewheel');
42623 this.assetHeight = 0;
42626 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
42627 this.assetHeight += this.header.getHeight();
42630 this.innerList = this.list.createChild({cls:cls+'-inner'});
42631 this.innerList.on('mouseover', this.onViewOver, this);
42632 this.innerList.on('mousemove', this.onViewMove, this);
42633 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
42635 if(this.allowBlank && !this.pageSize && !this.disableClear){
42636 this.footer = this.list.createChild({cls:cls+'-ft'});
42637 this.pageTb = new Roo.Toolbar(this.footer);
42641 this.footer = this.list.createChild({cls:cls+'-ft'});
42642 this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
42643 {pageSize: this.pageSize});
42647 if (this.pageTb && this.allowBlank && !this.disableClear) {
42649 this.pageTb.add(new Roo.Toolbar.Fill(), {
42650 cls: 'x-btn-icon x-btn-clear',
42652 handler: function()
42655 _this.clearValue();
42656 _this.onSelect(false, -1);
42661 this.assetHeight += this.footer.getHeight();
42666 this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
42669 this.view = new Roo.View(this.innerList, this.tpl, {
42672 selectedClass: this.selectedClass
42675 this.view.on('click', this.onViewClick, this);
42677 this.store.on('beforeload', this.onBeforeLoad, this);
42678 this.store.on('load', this.onLoad, this);
42679 this.store.on('loadexception', this.onLoadException, this);
42681 if(this.resizable){
42682 this.resizer = new Roo.Resizable(this.list, {
42683 pinned:true, handles:'se'
42685 this.resizer.on('resize', function(r, w, h){
42686 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
42687 this.listWidth = w;
42688 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
42689 this.restrictHeight();
42691 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
42693 if(!this.editable){
42694 this.editable = true;
42695 this.setEditable(false);
42699 if (typeof(this.events.add.listeners) != 'undefined') {
42701 this.addicon = this.wrap.createChild(
42702 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });
42704 this.addicon.on('click', function(e) {
42705 this.fireEvent('add', this);
42708 if (typeof(this.events.edit.listeners) != 'undefined') {
42710 this.editicon = this.wrap.createChild(
42711 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });
42712 if (this.addicon) {
42713 this.editicon.setStyle('margin-left', '40px');
42715 this.editicon.on('click', function(e) {
42717 // we fire even if inothing is selected..
42718 this.fireEvent('edit', this, this.lastData );
42728 initEvents : function(){
42729 Roo.form.ComboBox.superclass.initEvents.call(this);
42731 this.keyNav = new Roo.KeyNav(this.el, {
42732 "up" : function(e){
42733 this.inKeyMode = true;
42737 "down" : function(e){
42738 if(!this.isExpanded()){
42739 this.onTriggerClick();
42741 this.inKeyMode = true;
42746 "enter" : function(e){
42747 this.onViewClick();
42751 "esc" : function(e){
42755 "tab" : function(e){
42756 this.onViewClick(false);
42757 this.fireEvent("specialkey", this, e);
42763 doRelay : function(foo, bar, hname){
42764 if(hname == 'down' || this.scope.isExpanded()){
42765 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
42772 this.queryDelay = Math.max(this.queryDelay || 10,
42773 this.mode == 'local' ? 10 : 250);
42774 this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
42775 if(this.typeAhead){
42776 this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
42778 if(this.editable !== false){
42779 this.el.on("keyup", this.onKeyUp, this);
42781 if(this.forceSelection){
42782 this.on('blur', this.doForce, this);
42786 onDestroy : function(){
42788 this.view.setStore(null);
42789 this.view.el.removeAllListeners();
42790 this.view.el.remove();
42791 this.view.purgeListeners();
42794 this.list.destroy();
42797 this.store.un('beforeload', this.onBeforeLoad, this);
42798 this.store.un('load', this.onLoad, this);
42799 this.store.un('loadexception', this.onLoadException, this);
42801 Roo.form.ComboBox.superclass.onDestroy.call(this);
42805 fireKey : function(e){
42806 if(e.isNavKeyPress() && !this.list.isVisible()){
42807 this.fireEvent("specialkey", this, e);
42812 onResize: function(w, h){
42813 Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
42815 if(typeof w != 'number'){
42816 // we do not handle it!?!?
42819 var tw = this.trigger.getWidth();
42820 tw += this.addicon ? this.addicon.getWidth() : 0;
42821 tw += this.editicon ? this.editicon.getWidth() : 0;
42823 this.el.setWidth( this.adjustWidth('input', x));
42825 this.trigger.setStyle('left', x+'px');
42827 if(this.list && this.listWidth === undefined){
42828 var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
42829 this.list.setWidth(lw);
42830 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
42838 * Allow or prevent the user from directly editing the field text. If false is passed,
42839 * the user will only be able to select from the items defined in the dropdown list. This method
42840 * is the runtime equivalent of setting the 'editable' config option at config time.
42841 * @param {Boolean} value True to allow the user to directly edit the field text
42843 setEditable : function(value){
42844 if(value == this.editable){
42847 this.editable = value;
42849 this.el.dom.setAttribute('readOnly', true);
42850 this.el.on('mousedown', this.onTriggerClick, this);
42851 this.el.addClass('x-combo-noedit');
42853 this.el.dom.setAttribute('readOnly', false);
42854 this.el.un('mousedown', this.onTriggerClick, this);
42855 this.el.removeClass('x-combo-noedit');
42860 onBeforeLoad : function(){
42861 if(!this.hasFocus){
42864 this.innerList.update(this.loadingText ?
42865 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
42866 this.restrictHeight();
42867 this.selectedIndex = -1;
42871 onLoad : function(){
42872 if(!this.hasFocus){
42875 if(this.store.getCount() > 0){
42877 this.restrictHeight();
42878 if(this.lastQuery == this.allQuery){
42880 this.el.dom.select();
42882 if(!this.selectByValue(this.value, true)){
42883 this.select(0, true);
42887 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
42888 this.taTask.delay(this.typeAheadDelay);
42892 this.onEmptyResults();
42897 onLoadException : function()
42900 Roo.log(this.store.reader.jsonData);
42901 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
42902 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
42908 onTypeAhead : function(){
42909 if(this.store.getCount() > 0){
42910 var r = this.store.getAt(0);
42911 var newValue = r.data[this.displayField];
42912 var len = newValue.length;
42913 var selStart = this.getRawValue().length;
42914 if(selStart != len){
42915 this.setRawValue(newValue);
42916 this.selectText(selStart, newValue.length);
42922 onSelect : function(record, index){
42923 if(this.fireEvent('beforeselect', this, record, index) !== false){
42924 this.setFromData(index > -1 ? record.data : false);
42926 this.fireEvent('select', this, record, index);
42931 * Returns the currently selected field value or empty string if no value is set.
42932 * @return {String} value The selected value
42934 getValue : function(){
42935 if(this.valueField){
42936 return typeof this.value != 'undefined' ? this.value : '';
42938 return Roo.form.ComboBox.superclass.getValue.call(this);
42942 * Clears any text/value currently set in the field
42944 clearValue : function(){
42945 if(this.hiddenField){
42946 this.hiddenField.value = '';
42949 this.setRawValue('');
42950 this.lastSelectionText = '';
42955 * Sets the specified value into the field. If the value finds a match, the corresponding record text
42956 * will be displayed in the field. If the value does not match the data value of an existing item,
42957 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
42958 * Otherwise the field will be blank (although the value will still be set).
42959 * @param {String} value The value to match
42961 setValue : function(v){
42963 if(this.valueField){
42964 var r = this.findRecord(this.valueField, v);
42966 text = r.data[this.displayField];
42967 }else if(this.valueNotFoundText !== undefined){
42968 text = this.valueNotFoundText;
42971 this.lastSelectionText = text;
42972 if(this.hiddenField){
42973 this.hiddenField.value = v;
42975 Roo.form.ComboBox.superclass.setValue.call(this, text);
42979 * @property {Object} the last set data for the element
42984 * Sets the value of the field based on a object which is related to the record format for the store.
42985 * @param {Object} value the value to set as. or false on reset?
42987 setFromData : function(o){
42988 var dv = ''; // display value
42989 var vv = ''; // value value..
42991 if (this.displayField) {
42992 dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
42994 // this is an error condition!!!
42995 Roo.log('no displayField value set for '+ (this.name ? this.name : this.id));
42998 if(this.valueField){
42999 vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
43001 if(this.hiddenField){
43002 this.hiddenField.value = vv;
43004 this.lastSelectionText = dv;
43005 Roo.form.ComboBox.superclass.setValue.call(this, dv);
43009 // no hidden field.. - we store the value in 'value', but still display
43010 // display field!!!!
43011 this.lastSelectionText = dv;
43012 Roo.form.ComboBox.superclass.setValue.call(this, dv);
43018 reset : function(){
43019 // overridden so that last data is reset..
43020 this.setValue(this.resetValue);
43021 this.originalValue = this.getValue();
43022 this.clearInvalid();
43023 this.lastData = false;
43025 this.view.clearSelections();
43029 findRecord : function(prop, value){
43031 if(this.store.getCount() > 0){
43032 this.store.each(function(r){
43033 if(r.data[prop] == value){
43043 getName: function()
43045 // returns hidden if it's set..
43046 if (!this.rendered) {return ''};
43047 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
43051 onViewMove : function(e, t){
43052 this.inKeyMode = false;
43056 onViewOver : function(e, t){
43057 if(this.inKeyMode){ // prevent key nav and mouse over conflicts
43060 var item = this.view.findItemFromChild(t);
43062 var index = this.view.indexOf(item);
43063 this.select(index, false);
43068 onViewClick : function(doFocus)
43070 var index = this.view.getSelectedIndexes()[0];
43071 var r = this.store.getAt(index);
43073 this.onSelect(r, index);
43075 if(doFocus !== false && !this.blockFocus){
43081 restrictHeight : function(){
43082 this.innerList.dom.style.height = '';
43083 var inner = this.innerList.dom;
43084 var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
43085 this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
43086 this.list.beginUpdate();
43087 this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
43088 this.list.alignTo(this.el, this.listAlign);
43089 this.list.endUpdate();
43093 onEmptyResults : function(){
43098 * Returns true if the dropdown list is expanded, else false.
43100 isExpanded : function(){
43101 return this.list.isVisible();
43105 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
43106 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
43107 * @param {String} value The data value of the item to select
43108 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
43109 * selected item if it is not currently in view (defaults to true)
43110 * @return {Boolean} True if the value matched an item in the list, else false
43112 selectByValue : function(v, scrollIntoView){
43113 if(v !== undefined && v !== null){
43114 var r = this.findRecord(this.valueField || this.displayField, v);
43116 this.select(this.store.indexOf(r), scrollIntoView);
43124 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
43125 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
43126 * @param {Number} index The zero-based index of the list item to select
43127 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
43128 * selected item if it is not currently in view (defaults to true)
43130 select : function(index, scrollIntoView){
43131 this.selectedIndex = index;
43132 this.view.select(index);
43133 if(scrollIntoView !== false){
43134 var el = this.view.getNode(index);
43136 this.innerList.scrollChildIntoView(el, false);
43142 selectNext : function(){
43143 var ct = this.store.getCount();
43145 if(this.selectedIndex == -1){
43147 }else if(this.selectedIndex < ct-1){
43148 this.select(this.selectedIndex+1);
43154 selectPrev : function(){
43155 var ct = this.store.getCount();
43157 if(this.selectedIndex == -1){
43159 }else if(this.selectedIndex != 0){
43160 this.select(this.selectedIndex-1);
43166 onKeyUp : function(e){
43167 if(this.editable !== false && !e.isSpecialKey()){
43168 this.lastKey = e.getKey();
43169 this.dqTask.delay(this.queryDelay);
43174 validateBlur : function(){
43175 return !this.list || !this.list.isVisible();
43179 initQuery : function(){
43180 this.doQuery(this.getRawValue());
43184 doForce : function(){
43185 if(this.el.dom.value.length > 0){
43186 this.el.dom.value =
43187 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
43193 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
43194 * query allowing the query action to be canceled if needed.
43195 * @param {String} query The SQL query to execute
43196 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
43197 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
43198 * saved in the current store (defaults to false)
43200 doQuery : function(q, forceAll){
43201 if(q === undefined || q === null){
43206 forceAll: forceAll,
43210 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
43214 forceAll = qe.forceAll;
43215 if(forceAll === true || (q.length >= this.minChars)){
43216 if(this.lastQuery != q || this.alwaysQuery){
43217 this.lastQuery = q;
43218 if(this.mode == 'local'){
43219 this.selectedIndex = -1;
43221 this.store.clearFilter();
43223 this.store.filter(this.displayField, q);
43227 this.store.baseParams[this.queryParam] = q;
43229 params: this.getParams(q)
43234 this.selectedIndex = -1;
43241 getParams : function(q){
43243 //p[this.queryParam] = q;
43246 p.limit = this.pageSize;
43252 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
43254 collapse : function(){
43255 if(!this.isExpanded()){
43259 Roo.get(document).un('mousedown', this.collapseIf, this);
43260 Roo.get(document).un('mousewheel', this.collapseIf, this);
43261 if (!this.editable) {
43262 Roo.get(document).un('keydown', this.listKeyPress, this);
43264 this.fireEvent('collapse', this);
43268 collapseIf : function(e){
43269 if(!e.within(this.wrap) && !e.within(this.list)){
43275 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
43277 expand : function(){
43278 if(this.isExpanded() || !this.hasFocus){
43281 this.list.alignTo(this.el, this.listAlign);
43283 Roo.get(document).on('mousedown', this.collapseIf, this);
43284 Roo.get(document).on('mousewheel', this.collapseIf, this);
43285 if (!this.editable) {
43286 Roo.get(document).on('keydown', this.listKeyPress, this);
43289 this.fireEvent('expand', this);
43293 // Implements the default empty TriggerField.onTriggerClick function
43294 onTriggerClick : function(){
43298 if(this.isExpanded()){
43300 if (!this.blockFocus) {
43305 this.hasFocus = true;
43306 if(this.triggerAction == 'all') {
43307 this.doQuery(this.allQuery, true);
43309 this.doQuery(this.getRawValue());
43311 if (!this.blockFocus) {
43316 listKeyPress : function(e)
43318 //Roo.log('listkeypress');
43319 // scroll to first matching element based on key pres..
43320 if (e.isSpecialKey()) {
43323 var k = String.fromCharCode(e.getKey()).toUpperCase();
43326 var csel = this.view.getSelectedNodes();
43327 var cselitem = false;
43329 var ix = this.view.indexOf(csel[0]);
43330 cselitem = this.store.getAt(ix);
43331 if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
43337 this.store.each(function(v) {
43339 // start at existing selection.
43340 if (cselitem.id == v.id) {
43346 if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
43347 match = this.store.indexOf(v);
43352 if (match === false) {
43353 return true; // no more action?
43356 this.view.select(match);
43357 var sn = Roo.get(this.view.getSelectedNodes()[0]);
43358 sn.scrollIntoView(sn.dom.parentNode, false);
43362 * @cfg {Boolean} grow
43366 * @cfg {Number} growMin
43370 * @cfg {Number} growMax
43378 * Copyright(c) 2010-2012, Roo J Solutions Limited
43385 * @class Roo.form.ComboBoxArray
43386 * @extends Roo.form.TextField
43387 * A facebook style adder... for lists of email / people / countries etc...
43388 * pick multiple items from a combo box, and shows each one.
43390 * Fred [x] Brian [x] [Pick another |v]
43393 * For this to work: it needs various extra information
43394 * - normal combo problay has
43396 * + displayField, valueField
43398 * For our purpose...
43401 * If we change from 'extends' to wrapping...
43408 * Create a new ComboBoxArray.
43409 * @param {Object} config Configuration options
43413 Roo.form.ComboBoxArray = function(config)
43417 * @event beforeremove
43418 * Fires before remove the value from the list
43419 * @param {Roo.form.ComboBoxArray} _self This combo box array
43420 * @param {Roo.form.ComboBoxArray.Item} item removed item
43422 'beforeremove' : true,
43425 * Fires when remove the value from the list
43426 * @param {Roo.form.ComboBoxArray} _self This combo box array
43427 * @param {Roo.form.ComboBoxArray.Item} item removed item
43434 Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
43436 this.items = new Roo.util.MixedCollection(false);
43438 // construct the child combo...
43448 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
43451 * @cfg {Roo.form.ComboBox} combo [required] The combo box that is wrapped
43456 // behavies liek a hiddne field
43457 inputType: 'hidden',
43459 * @cfg {Number} width The width of the box that displays the selected element
43466 * @cfg {String} name The name of the visable items on this form (eg. titles not ids)
43470 * @cfg {String} hiddenName The hidden name of the field, often contains an comma seperated list of names
43472 hiddenName : false,
43474 * @cfg {String} seperator The value seperator normally ','
43478 // private the array of items that are displayed..
43480 // private - the hidden field el.
43482 // private - the filed el..
43485 //validateValue : function() { return true; }, // all values are ok!
43486 //onAddClick: function() { },
43488 onRender : function(ct, position)
43491 // create the standard hidden element
43492 //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
43495 // give fake names to child combo;
43496 this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
43497 this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
43499 this.combo = Roo.factory(this.combo, Roo.form);
43500 this.combo.onRender(ct, position);
43501 if (typeof(this.combo.width) != 'undefined') {
43502 this.combo.onResize(this.combo.width,0);
43505 this.combo.initEvents();
43507 // assigned so form know we need to do this..
43508 this.store = this.combo.store;
43509 this.valueField = this.combo.valueField;
43510 this.displayField = this.combo.displayField ;
43513 this.combo.wrap.addClass('x-cbarray-grp');
43515 var cbwrap = this.combo.wrap.createChild(
43516 {tag: 'div', cls: 'x-cbarray-cb'},
43521 this.hiddenEl = this.combo.wrap.createChild({
43522 tag: 'input', type:'hidden' , name: this.hiddenName, value : ''
43524 this.el = this.combo.wrap.createChild({
43525 tag: 'input', type:'hidden' , name: this.name, value : ''
43527 // this.el.dom.removeAttribute("name");
43530 this.outerWrap = this.combo.wrap;
43531 this.wrap = cbwrap;
43533 this.outerWrap.setWidth(this.width);
43534 this.outerWrap.dom.removeChild(this.el.dom);
43536 this.wrap.dom.appendChild(this.el.dom);
43537 this.outerWrap.dom.removeChild(this.combo.trigger.dom);
43538 this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
43540 this.combo.trigger.setStyle('position','relative');
43541 this.combo.trigger.setStyle('left', '0px');
43542 this.combo.trigger.setStyle('top', '2px');
43544 this.combo.el.setStyle('vertical-align', 'text-bottom');
43546 //this.trigger.setStyle('vertical-align', 'top');
43548 // this should use the code from combo really... on('add' ....)
43552 this.adder = this.outerWrap.createChild(
43553 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});
43555 this.adder.on('click', function(e) {
43556 _t.fireEvent('adderclick', this, e);
43560 //this.adder.on('click', this.onAddClick, _t);
43563 this.combo.on('select', function(cb, rec, ix) {
43564 this.addItem(rec.data);
43567 cb.el.dom.value = '';
43568 //cb.lastData = rec.data;
43577 getName: function()
43579 // returns hidden if it's set..
43580 if (!this.rendered) {return ''};
43581 return this.hiddenName ? this.hiddenName : this.name;
43586 onResize: function(w, h){
43589 // not sure if this is needed..
43590 //this.combo.onResize(w,h);
43592 if(typeof w != 'number'){
43593 // we do not handle it!?!?
43596 var tw = this.combo.trigger.getWidth();
43597 tw += this.addicon ? this.addicon.getWidth() : 0;
43598 tw += this.editicon ? this.editicon.getWidth() : 0;
43600 this.combo.el.setWidth( this.combo.adjustWidth('input', x));
43602 this.combo.trigger.setStyle('left', '0px');
43604 if(this.list && this.listWidth === undefined){
43605 var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
43606 this.list.setWidth(lw);
43607 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
43614 addItem: function(rec)
43616 var valueField = this.combo.valueField;
43617 var displayField = this.combo.displayField;
43619 if (this.items.indexOfKey(rec[valueField]) > -1) {
43620 //console.log("GOT " + rec.data.id);
43624 var x = new Roo.form.ComboBoxArray.Item({
43625 //id : rec[this.idField],
43627 displayField : displayField ,
43628 tipField : displayField ,
43632 this.items.add(rec[valueField],x);
43633 // add it before the element..
43634 this.updateHiddenEl();
43635 x.render(this.outerWrap, this.wrap.dom);
43636 // add the image handler..
43639 updateHiddenEl : function()
43642 if (!this.hiddenEl) {
43646 var idField = this.combo.valueField;
43648 this.items.each(function(f) {
43649 ar.push(f.data[idField]);
43651 this.hiddenEl.dom.value = ar.join(this.seperator);
43657 this.items.clear();
43659 Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
43663 this.el.dom.value = '';
43664 if (this.hiddenEl) {
43665 this.hiddenEl.dom.value = '';
43669 getValue: function()
43671 return this.hiddenEl ? this.hiddenEl.dom.value : '';
43673 setValue: function(v) // not a valid action - must use addItems..
43678 if (this.store.isLocal && (typeof(v) == 'string')) {
43679 // then we can use the store to find the values..
43680 // comma seperated at present.. this needs to allow JSON based encoding..
43681 this.hiddenEl.value = v;
43683 Roo.each(v.split(this.seperator), function(k) {
43684 Roo.log("CHECK " + this.valueField + ',' + k);
43685 var li = this.store.query(this.valueField, k);
43690 add[this.valueField] = k;
43691 add[this.displayField] = li.item(0).data[this.displayField];
43697 if (typeof(v) == 'object' ) {
43698 // then let's assume it's an array of objects..
43699 Roo.each(v, function(l) {
43701 if (typeof(l) == 'string') {
43703 add[this.valueField] = l;
43704 add[this.displayField] = l
43713 setFromData: function(v)
43715 // this recieves an object, if setValues is called.
43717 this.el.dom.value = v[this.displayField];
43718 this.hiddenEl.dom.value = v[this.valueField];
43719 if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
43722 var kv = v[this.valueField];
43723 var dv = v[this.displayField];
43724 kv = typeof(kv) != 'string' ? '' : kv;
43725 dv = typeof(dv) != 'string' ? '' : dv;
43728 var keys = kv.split(this.seperator);
43729 var display = dv.split(this.seperator);
43730 for (var i = 0 ; i < keys.length; i++) {
43732 add[this.valueField] = keys[i];
43733 add[this.displayField] = display[i];
43741 * Validates the combox array value
43742 * @return {Boolean} True if the value is valid, else false
43744 validate : function(){
43745 if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
43746 this.clearInvalid();
43752 validateValue : function(value){
43753 return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
43761 isDirty : function() {
43762 if(this.disabled) {
43767 var d = Roo.decode(String(this.originalValue));
43769 return String(this.getValue()) !== String(this.originalValue);
43772 var originalValue = [];
43774 for (var i = 0; i < d.length; i++){
43775 originalValue.push(d[i][this.valueField]);
43778 return String(this.getValue()) !== String(originalValue.join(this.seperator));
43787 * @class Roo.form.ComboBoxArray.Item
43788 * @extends Roo.BoxComponent
43789 * A selected item in the list
43790 * Fred [x] Brian [x] [Pick another |v]
43793 * Create a new item.
43794 * @param {Object} config Configuration options
43797 Roo.form.ComboBoxArray.Item = function(config) {
43798 config.id = Roo.id();
43799 Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
43802 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
43805 displayField : false,
43809 defaultAutoCreate : {
43811 cls: 'x-cbarray-item',
43818 src : Roo.BLANK_IMAGE_URL ,
43826 onRender : function(ct, position)
43828 Roo.form.Field.superclass.onRender.call(this, ct, position);
43831 var cfg = this.getAutoCreate();
43832 this.el = ct.createChild(cfg, position);
43835 this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
43837 this.el.child('div').dom.innerHTML = this.cb.renderer ?
43838 this.cb.renderer(this.data) :
43839 String.format('{0}',this.data[this.displayField]);
43842 this.el.child('div').dom.setAttribute('qtip',
43843 String.format('{0}',this.data[this.tipField])
43846 this.el.child('img').on('click', this.remove, this);
43850 remove : function()
43852 if(this.cb.disabled){
43856 if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
43857 this.cb.items.remove(this);
43858 this.el.child('img').un('click', this.remove, this);
43860 this.cb.updateHiddenEl();
43862 this.cb.fireEvent('remove', this.cb, this);
43867 * RooJS Library 1.1.1
43868 * Copyright(c) 2008-2011 Alan Knowles
43875 * @class Roo.form.ComboNested
43876 * @extends Roo.form.ComboBox
43877 * A combobox for that allows selection of nested items in a list,
43892 * Create a new ComboNested
43893 * @param {Object} config Configuration options
43895 Roo.form.ComboNested = function(config){
43896 Roo.form.ComboCheck.superclass.constructor.call(this, config);
43897 // should verify some data...
43899 // hiddenName = required..
43900 // displayField = required
43901 // valudField == required
43902 var req= [ 'hiddenName', 'displayField', 'valueField' ];
43904 Roo.each(req, function(e) {
43905 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
43906 throw "Roo.form.ComboNested : missing value for: " + e;
43913 Roo.extend(Roo.form.ComboNested, Roo.form.ComboBox, {
43916 * @config {Number} max Number of columns to show
43921 list : null, // the outermost div..
43922 innerLists : null, // the
43926 loadingChildren : false,
43928 onRender : function(ct, position)
43930 Roo.form.ComboBox.superclass.onRender.call(this, ct, position); // skip parent call - got to above..
43932 if(this.hiddenName){
43933 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
43935 this.hiddenField.value =
43936 this.hiddenValue !== undefined ? this.hiddenValue :
43937 this.value !== undefined ? this.value : '';
43939 // prevent input submission
43940 this.el.dom.removeAttribute('name');
43946 this.el.dom.setAttribute('autocomplete', 'off');
43949 var cls = 'x-combo-list';
43951 this.list = new Roo.Layer({
43952 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
43955 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
43956 this.list.setWidth(lw);
43957 this.list.swallowEvent('mousewheel');
43958 this.assetHeight = 0;
43961 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
43962 this.assetHeight += this.header.getHeight();
43964 this.innerLists = [];
43967 for (var i =0 ; i < this.maxColumns; i++) {
43968 this.onRenderList( cls, i);
43971 // always needs footer, as we are going to have an 'OK' button.
43972 this.footer = this.list.createChild({cls:cls+'-ft'});
43973 this.pageTb = new Roo.Toolbar(this.footer);
43978 handler: function()
43984 if ( this.allowBlank && !this.disableClear) {
43986 this.pageTb.add(new Roo.Toolbar.Fill(), {
43987 cls: 'x-btn-icon x-btn-clear',
43989 handler: function()
43992 _this.clearValue();
43993 _this.onSelect(false, -1);
43998 this.assetHeight += this.footer.getHeight();
44002 onRenderList : function ( cls, i)
44005 var lw = Math.floor(
44006 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
44009 this.list.setWidth(lw); // default to '1'
44011 var il = this.innerLists[i] = this.list.createChild({cls:cls+'-inner'});
44012 //il.on('mouseover', this.onViewOver, this, { list: i });
44013 //il.on('mousemove', this.onViewMove, this, { list: i });
44015 il.setStyle({ 'overflow-x' : 'hidden'});
44018 this.tpl = new Roo.Template({
44019 html : '<div class="'+cls+'-item '+cls+'-item-{cn:this.isEmpty}">{' + this.displayField + '}</div>',
44020 isEmpty: function (value, allValues) {
44022 var dl = typeof(value.data) != 'undefined' ? value.data.length : value.length; ///json is a nested response..
44023 return dl ? 'has-children' : 'no-children'
44028 var store = this.store;
44030 store = new Roo.data.SimpleStore({
44031 //fields : this.store.reader.meta.fields,
44032 reader : this.store.reader,
44036 this.stores[i] = store;
44038 var view = this.views[i] = new Roo.View(
44044 selectedClass: this.selectedClass
44047 view.getEl().setWidth(lw);
44048 view.getEl().setStyle({
44049 position: i < 1 ? 'relative' : 'absolute',
44051 left: (i * lw ) + 'px',
44052 display : i > 0 ? 'none' : 'block'
44054 view.on('selectionchange', this.onSelectChange.createDelegate(this, {list : i }, true));
44055 view.on('dblclick', this.onDoubleClick.createDelegate(this, {list : i }, true));
44056 //view.on('click', this.onViewClick, this, { list : i });
44058 store.on('beforeload', this.onBeforeLoad, this);
44059 store.on('load', this.onLoad, this, { list : i});
44060 store.on('loadexception', this.onLoadException, this);
44062 // hide the other vies..
44068 restrictHeight : function()
44071 Roo.each(this.innerLists, function(il,i) {
44072 var el = this.views[i].getEl();
44073 el.dom.style.height = '';
44074 var inner = el.dom;
44075 var h = Math.max(il.clientHeight, il.offsetHeight, il.scrollHeight);
44076 // only adjust heights on other ones..
44077 mh = Math.max(h, mh);
44080 el.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
44081 il.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
44088 this.list.beginUpdate();
44089 this.list.setHeight(mh+this.list.getFrameWidth('tb')+this.assetHeight);
44090 this.list.alignTo(this.el, this.listAlign);
44091 this.list.endUpdate();
44096 // -- store handlers..
44098 onBeforeLoad : function()
44100 if(!this.hasFocus){
44103 this.innerLists[0].update(this.loadingText ?
44104 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
44105 this.restrictHeight();
44106 this.selectedIndex = -1;
44109 onLoad : function(a,b,c,d)
44111 if (!this.loadingChildren) {
44112 // then we are loading the top level. - hide the children
44113 for (var i = 1;i < this.views.length; i++) {
44114 this.views[i].getEl().setStyle({ display : 'none' });
44116 var lw = Math.floor(
44117 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
44120 this.list.setWidth(lw); // default to '1'
44124 if(!this.hasFocus){
44128 if(this.store.getCount() > 0) {
44130 this.restrictHeight();
44132 this.onEmptyResults();
44135 if (!this.loadingChildren) {
44136 this.selectActive();
44139 this.stores[1].loadData([]);
44140 this.stores[2].loadData([]);
44149 onLoadException : function()
44152 Roo.log(this.store.reader.jsonData);
44153 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
44154 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
44159 // no cleaning of leading spaces on blur here.
44160 cleanLeadingSpace : function(e) { },
44163 onSelectChange : function (view, sels, opts )
44165 var ix = view.getSelectedIndexes();
44167 if (opts.list > this.maxColumns - 2) {
44168 if (view.store.getCount()< 1) {
44169 this.views[opts.list ].getEl().setStyle({ display : 'none' });
44173 // used to clear ?? but if we are loading unselected
44174 this.setFromData(view.store.getAt(ix[0]).data);
44183 // this get's fired when trigger opens..
44184 // this.setFromData({});
44185 var str = this.stores[opts.list+1];
44186 str.data.clear(); // removeall wihtout the fire events..
44190 var rec = view.store.getAt(ix[0]);
44192 this.setFromData(rec.data);
44193 this.fireEvent('select', this, rec, ix[0]);
44195 var lw = Math.floor(
44197 (this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')
44198 ) / this.maxColumns
44200 this.loadingChildren = true;
44201 this.stores[opts.list+1].loadDataFromChildren( rec );
44202 this.loadingChildren = false;
44203 var dl = this.stores[opts.list+1]. getTotalCount();
44205 this.views[opts.list+1].getEl().setHeight( this.innerLists[0].getHeight());
44207 this.views[opts.list+1].getEl().setStyle({ display : dl ? 'block' : 'none' });
44208 for (var i = opts.list+2; i < this.views.length;i++) {
44209 this.views[i].getEl().setStyle({ display : 'none' });
44212 this.innerLists[opts.list+1].setHeight( this.innerLists[0].getHeight());
44213 this.list.setWidth(lw * (opts.list + (dl ? 2 : 1)));
44215 if (this.isLoading) {
44216 // this.selectActive(opts.list);
44224 onDoubleClick : function()
44226 this.collapse(); //??
44234 recordToStack : function(store, prop, value, stack)
44236 var cstore = new Roo.data.SimpleStore({
44237 //fields : this.store.reader.meta.fields, // we need array reader.. for
44238 reader : this.store.reader,
44242 var record = false;
44244 if(store.getCount() < 1){
44247 store.each(function(r){
44248 if(r.data[prop] == value){
44253 if (r.data.cn && r.data.cn.length) {
44254 cstore.loadDataFromChildren( r);
44255 var cret = _this.recordToStack(cstore, prop, value, stack);
44256 if (cret !== false) {
44265 if (record == false) {
44268 stack.unshift(srec);
44273 * find the stack of stores that match our value.
44278 selectActive : function ()
44280 // if store is not loaded, then we will need to wait for that to happen first.
44282 this.recordToStack(this.store, this.valueField, this.getValue(), stack);
44283 for (var i = 0; i < stack.length; i++ ) {
44284 this.views[i].select(stack[i].store.indexOf(stack[i]), false, false );
44296 * Ext JS Library 1.1.1
44297 * Copyright(c) 2006-2007, Ext JS, LLC.
44299 * Originally Released Under LGPL - original licence link has changed is not relivant.
44302 * <script type="text/javascript">
44305 * @class Roo.form.Checkbox
44306 * @extends Roo.form.Field
44307 * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
44309 * Creates a new Checkbox
44310 * @param {Object} config Configuration options
44312 Roo.form.Checkbox = function(config){
44313 Roo.form.Checkbox.superclass.constructor.call(this, config);
44317 * Fires when the checkbox is checked or unchecked.
44318 * @param {Roo.form.Checkbox} this This checkbox
44319 * @param {Boolean} checked The new checked value
44325 Roo.extend(Roo.form.Checkbox, Roo.form.Field, {
44327 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
44329 focusClass : undefined,
44331 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
44333 fieldClass: "x-form-field",
44335 * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
44339 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
44340 * {tag: "input", type: "checkbox", autocomplete: "off"})
44342 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
44344 * @cfg {String} boxLabel The text that appears beside the checkbox
44348 * @cfg {String} inputValue The value that should go into the generated input element's value attribute
44352 * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
44354 valueOff: '0', // value when not checked..
44356 actionMode : 'viewEl',
44359 itemCls : 'x-menu-check-item x-form-item',
44360 groupClass : 'x-menu-group-item',
44361 inputType : 'hidden',
44364 inSetChecked: false, // check that we are not calling self...
44366 inputElement: false, // real input element?
44367 basedOn: false, // ????
44369 isFormField: true, // not sure where this is needed!!!!
44371 onResize : function(){
44372 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
44373 if(!this.boxLabel){
44374 this.el.alignTo(this.wrap, 'c-c');
44378 initEvents : function(){
44379 Roo.form.Checkbox.superclass.initEvents.call(this);
44380 this.el.on("click", this.onClick, this);
44381 this.el.on("change", this.onClick, this);
44385 getResizeEl : function(){
44389 getPositionEl : function(){
44394 onRender : function(ct, position){
44395 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
44397 if(this.inputValue !== undefined){
44398 this.el.dom.value = this.inputValue;
44401 //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
44402 this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
44403 var viewEl = this.wrap.createChild({
44404 tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
44405 this.viewEl = viewEl;
44406 this.wrap.on('click', this.onClick, this);
44408 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
44409 this.el.on('propertychange', this.setFromHidden, this); //ie
44414 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
44415 // viewEl.on('click', this.onClick, this);
44417 //if(this.checked){
44418 this.setChecked(this.checked);
44420 //this.checked = this.el.dom;
44426 initValue : Roo.emptyFn,
44429 * Returns the checked state of the checkbox.
44430 * @return {Boolean} True if checked, else false
44432 getValue : function(){
44434 return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
44436 return this.valueOff;
44441 onClick : function(){
44442 if (this.disabled) {
44445 this.setChecked(!this.checked);
44447 //if(this.el.dom.checked != this.checked){
44448 // this.setValue(this.el.dom.checked);
44453 * Sets the checked state of the checkbox.
44454 * On is always based on a string comparison between inputValue and the param.
44455 * @param {Boolean/String} value - the value to set
44456 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
44458 setValue : function(v,suppressEvent){
44461 //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
44462 //if(this.el && this.el.dom){
44463 // this.el.dom.checked = this.checked;
44464 // this.el.dom.defaultChecked = this.checked;
44466 this.setChecked(String(v) === String(this.inputValue), suppressEvent);
44467 //this.fireEvent("check", this, this.checked);
44470 setChecked : function(state,suppressEvent)
44472 if (this.inSetChecked) {
44473 this.checked = state;
44479 this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
44481 this.checked = state;
44482 if(suppressEvent !== true){
44483 this.fireEvent('check', this, state);
44485 this.inSetChecked = true;
44486 this.el.dom.value = state ? this.inputValue : this.valueOff;
44487 this.inSetChecked = false;
44490 // handle setting of hidden value by some other method!!?!?
44491 setFromHidden: function()
44496 //console.log("SET FROM HIDDEN");
44497 //alert('setFrom hidden');
44498 this.setValue(this.el.dom.value);
44501 onDestroy : function()
44504 Roo.get(this.viewEl).remove();
44507 Roo.form.Checkbox.superclass.onDestroy.call(this);
44510 setBoxLabel : function(str)
44512 this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
44517 * Ext JS Library 1.1.1
44518 * Copyright(c) 2006-2007, Ext JS, LLC.
44520 * Originally Released Under LGPL - original licence link has changed is not relivant.
44523 * <script type="text/javascript">
44527 * @class Roo.form.Radio
44528 * @extends Roo.form.Checkbox
44529 * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
44530 * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
44532 * Creates a new Radio
44533 * @param {Object} config Configuration options
44535 Roo.form.Radio = function(){
44536 Roo.form.Radio.superclass.constructor.apply(this, arguments);
44538 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
44539 inputType: 'radio',
44542 * If this radio is part of a group, it will return the selected value
44545 getGroupValue : function(){
44546 return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
44550 onRender : function(ct, position){
44551 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
44553 if(this.inputValue !== undefined){
44554 this.el.dom.value = this.inputValue;
44557 this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
44558 //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
44559 //var viewEl = this.wrap.createChild({
44560 // tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
44561 //this.viewEl = viewEl;
44562 //this.wrap.on('click', this.onClick, this);
44564 //this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
44565 //this.el.on('propertychange', this.setFromHidden, this); //ie
44570 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
44571 // viewEl.on('click', this.onClick, this);
44574 this.el.dom.checked = 'checked' ;
44580 });Roo.rtf = {}; // namespace
44581 Roo.rtf.Hex = function(hex)
44585 Roo.rtf.Paragraph = function(opts)
44587 this.content = []; ///??? is that used?
44588 };Roo.rtf.Span = function(opts)
44590 this.value = opts.value;
44593 Roo.rtf.Group = function(parent)
44595 // we dont want to acutally store parent - it will make debug a nightmare..
44603 Roo.rtf.Group.prototype = {
44607 addContent : function(node) {
44608 // could set styles...
44609 this.content.push(node);
44611 addChild : function(cn)
44615 // only for images really...
44616 toDataURL : function()
44618 var mimetype = false;
44620 case this.content.filter(function(a) { return a.value == 'pngblip' } ).length > 0:
44621 mimetype = "image/png";
44623 case this.content.filter(function(a) { return a.value == 'jpegblip' } ).length > 0:
44624 mimetype = "image/jpeg";
44627 return 'about:blank'; // ?? error?
44631 var hexstring = this.content[this.content.length-1].value;
44633 return 'data:' + mimetype + ';base64,' + btoa(hexstring.match(/\w{2}/g).map(function(a) {
44634 return String.fromCharCode(parseInt(a, 16));
44639 // this looks like it's normally the {rtf{ .... }}
44640 Roo.rtf.Document = function()
44642 // we dont want to acutally store parent - it will make debug a nightmare..
44648 Roo.extend(Roo.rtf.Document, Roo.rtf.Group, {
44649 addChild : function(cn)
44653 case 'rtlch': // most content seems to be inside this??
44656 this.rtlch.push(cn);
44659 this[cn.type] = cn;
44664 getElementsByType : function(type)
44667 this._getElementsByType(type, ret, this.cn, 'rtf');
44670 _getElementsByType : function (type, ret, search_array, path)
44672 search_array.forEach(function(n,i) {
44673 if (n.type == type) {
44674 n.path = path + '/' + n.type + ':' + i;
44677 if (n.cn.length > 0) {
44678 this._getElementsByType(type, ret, n.cn, path + '/' + n.type+':'+i);
44685 Roo.rtf.Ctrl = function(opts)
44687 this.value = opts.value;
44688 this.param = opts.param;
44693 * based on this https://github.com/iarna/rtf-parser
44694 * it's really only designed to extract pict from pasted RTF
44698 * var images = new Roo.rtf.Parser().parse(a_string).filter(function(g) { return g.type == 'pict'; });
44707 Roo.rtf.Parser = function(text) {
44708 //super({objectMode: true})
44710 this.parserState = this.parseText;
44712 // these are for interpeter...
44714 ///this.parserState = this.parseTop
44715 this.groupStack = [];
44716 this.hexStore = [];
44719 this.groups = []; // where we put the return.
44721 for (var ii = 0; ii < text.length; ++ii) {
44724 if (text[ii] === '\n') {
44730 this.parserState(text[ii]);
44736 Roo.rtf.Parser.prototype = {
44737 text : '', // string being parsed..
44739 controlWordParam : '',
44743 groupStack : false,
44748 row : 1, // reportin?
44752 push : function (el)
44754 var m = 'cmd'+ el.type;
44755 if (typeof(this[m]) == 'undefined') {
44756 Roo.log('invalid cmd:' + el.type);
44762 flushHexStore : function()
44764 if (this.hexStore.length < 1) {
44767 var hexstr = this.hexStore.map(
44772 this.group.addContent( new Roo.rtf.Hex( hexstr ));
44775 this.hexStore.splice(0)
44779 cmdgroupstart : function()
44781 this.flushHexStore();
44783 this.groupStack.push(this.group);
44786 if (this.doc === false) {
44787 this.group = this.doc = new Roo.rtf.Document();
44791 this.group = new Roo.rtf.Group(this.group);
44793 cmdignorable : function()
44795 this.flushHexStore();
44796 this.group.ignorable = true;
44798 cmdendparagraph : function()
44800 this.flushHexStore();
44801 this.group.addContent(new Roo.rtf.Paragraph());
44803 cmdgroupend : function ()
44805 this.flushHexStore();
44806 var endingGroup = this.group;
44809 this.group = this.groupStack.pop();
44811 this.group.addChild(endingGroup);
44816 var doc = this.group || this.doc;
44817 //if (endingGroup instanceof FontTable) {
44818 // doc.fonts = endingGroup.table
44819 //} else if (endingGroup instanceof ColorTable) {
44820 // doc.colors = endingGroup.table
44821 //} else if (endingGroup !== this.doc && !endingGroup.get('ignorable')) {
44822 if (endingGroup.ignorable === false) {
44824 this.groups.push(endingGroup);
44825 // Roo.log( endingGroup );
44827 //Roo.each(endingGroup.content, function(item)) {
44828 // doc.addContent(item);
44830 //process.emit('debug', 'GROUP END', endingGroup.type, endingGroup.get('ignorable'))
44833 cmdtext : function (cmd)
44835 this.flushHexStore();
44836 if (!this.group) { // an RTF fragment, missing the {\rtf1 header
44837 //this.group = this.doc
44839 this.group.addContent(new Roo.rtf.Span(cmd));
44841 cmdcontrolword : function (cmd)
44843 this.flushHexStore();
44844 if (!this.group.type) {
44845 this.group.type = cmd.value;
44848 this.group.addContent(new Roo.rtf.Ctrl(cmd));
44849 // we actually don't care about ctrl words...
44852 var method = 'ctrl$' + cmd.value.replace(/-(.)/g, (_, char) => char.toUpperCase())
44853 if (this[method]) {
44854 this[method](cmd.param)
44856 if (!this.group.get('ignorable')) process.emit('debug', method, cmd.param)
44860 cmdhexchar : function(cmd) {
44861 this.hexStore.push(cmd);
44863 cmderror : function(cmd) {
44864 throw new Exception (cmd.value);
44869 if (this.text !== '\u0000') this.emitText()
44875 parseText : function(c)
44878 this.parserState = this.parseEscapes;
44879 } else if (c === '{') {
44880 this.emitStartGroup();
44881 } else if (c === '}') {
44882 this.emitEndGroup();
44883 } else if (c === '\x0A' || c === '\x0D') {
44884 // cr/lf are noise chars
44890 parseEscapes: function (c)
44892 if (c === '\\' || c === '{' || c === '}') {
44894 this.parserState = this.parseText;
44896 this.parserState = this.parseControlSymbol;
44897 this.parseControlSymbol(c);
44900 parseControlSymbol: function(c)
44903 this.text += '\u00a0'; // nbsp
44904 this.parserState = this.parseText
44905 } else if (c === '-') {
44906 this.text += '\u00ad'; // soft hyphen
44907 } else if (c === '_') {
44908 this.text += '\u2011'; // non-breaking hyphen
44909 } else if (c === '*') {
44910 this.emitIgnorable();
44911 this.parserState = this.parseText;
44912 } else if (c === "'") {
44913 this.parserState = this.parseHexChar;
44914 } else if (c === '|') { // formula cacter
44915 this.emitFormula();
44916 this.parserState = this.parseText;
44917 } else if (c === ':') { // subentry in an index entry
44918 this.emitIndexSubEntry();
44919 this.parserState = this.parseText;
44920 } else if (c === '\x0a') {
44921 this.emitEndParagraph();
44922 this.parserState = this.parseText;
44923 } else if (c === '\x0d') {
44924 this.emitEndParagraph();
44925 this.parserState = this.parseText;
44927 this.parserState = this.parseControlWord;
44928 this.parseControlWord(c);
44931 parseHexChar: function (c)
44933 if (/^[A-Fa-f0-9]$/.test(c)) {
44935 if (this.hexChar.length >= 2) {
44936 this.emitHexChar();
44937 this.parserState = this.parseText;
44941 this.emitError("Invalid character \"" + c + "\" in hex literal.");
44942 this.parserState = this.parseText;
44945 parseControlWord : function(c)
44948 this.emitControlWord();
44949 this.parserState = this.parseText;
44950 } else if (/^[-\d]$/.test(c)) {
44951 this.parserState = this.parseControlWordParam;
44952 this.controlWordParam += c;
44953 } else if (/^[A-Za-z]$/.test(c)) {
44954 this.controlWord += c;
44956 this.emitControlWord();
44957 this.parserState = this.parseText;
44961 parseControlWordParam : function (c) {
44962 if (/^\d$/.test(c)) {
44963 this.controlWordParam += c;
44964 } else if (c === ' ') {
44965 this.emitControlWord();
44966 this.parserState = this.parseText;
44968 this.emitControlWord();
44969 this.parserState = this.parseText;
44977 emitText : function () {
44978 if (this.text === '') {
44990 emitControlWord : function ()
44993 if (this.controlWord === '') {
44994 this.emitError('empty control word');
44997 type: 'controlword',
44998 value: this.controlWord,
44999 param: this.controlWordParam !== '' && Number(this.controlWordParam),
45005 this.controlWord = '';
45006 this.controlWordParam = '';
45008 emitStartGroup : function ()
45012 type: 'groupstart',
45018 emitEndGroup : function ()
45028 emitIgnorable : function ()
45038 emitHexChar : function ()
45043 value: this.hexChar,
45050 emitError : function (message)
45058 char: this.cpos //,
45059 //stack: new Error().stack
45062 emitEndParagraph : function () {
45065 type: 'endparagraph',
45073 Roo.htmleditor = {};
45076 * @class Roo.htmleditor.Filter
45077 * Base Class for filtering htmleditor stuff. - do not use this directly - extend it.
45078 * @cfg {DomElement} node The node to iterate and filter
45079 * @cfg {boolean|String|Array} tag Tags to replace
45081 * Create a new Filter.
45082 * @param {Object} config Configuration options
45087 Roo.htmleditor.Filter = function(cfg) {
45088 Roo.apply(this.cfg);
45089 // this does not actually call walk as it's really just a abstract class
45093 Roo.htmleditor.Filter.prototype = {
45099 // overrride to do replace comments.
45100 replaceComment : false,
45102 // overrride to do replace or do stuff with tags..
45103 replaceTag : false,
45105 walk : function(dom)
45107 Roo.each( Array.from(dom.childNodes), function( e ) {
45110 case e.nodeType == 8 && typeof(this.replaceComment) != 'undefined': // comment
45111 this.replaceComment(e);
45114 case e.nodeType != 1: //not a node.
45117 case this.tag === true: // everything
45118 case typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1: // array and it matches.
45119 case typeof(this.tag) == 'string' && this.tag == e.tagName: // array and it matches.
45120 if (this.replaceTag && false === this.replaceTag(e)) {
45123 if (e.hasChildNodes()) {
45128 default: // tags .. that do not match.
45129 if (e.hasChildNodes()) {
45140 * @class Roo.htmleditor.FilterAttributes
45141 * clean attributes and styles including http:// etc.. in attribute
45143 * Run a new Attribute Filter
45144 * @param {Object} config Configuration options
45146 Roo.htmleditor.FilterAttributes = function(cfg)
45148 Roo.apply(this, cfg);
45149 this.attrib_black = this.attrib_black || [];
45150 this.attrib_white = this.attrib_white || [];
45152 this.attrib_clean = this.attrib_clean || [];
45153 this.style_white = this.style_white || [];
45154 this.style_black = this.style_black || [];
45155 this.walk(cfg.node);
45158 Roo.extend(Roo.htmleditor.FilterAttributes, Roo.htmleditor.Filter,
45160 tag: true, // all tags
45162 attrib_black : false, // array
45163 attrib_clean : false,
45164 attrib_white : false,
45166 style_white : false,
45167 style_black : false,
45170 replaceTag : function(node)
45172 if (!node.attributes || !node.attributes.length) {
45176 for (var i = node.attributes.length-1; i > -1 ; i--) {
45177 var a = node.attributes[i];
45179 if (this.attrib_white.length && this.attrib_white.indexOf(a.name.toLowerCase()) < 0) {
45180 node.removeAttribute(a.name);
45186 if (a.name.toLowerCase().substr(0,2)=='on') {
45187 node.removeAttribute(a.name);
45192 if (this.attrib_black.indexOf(a.name.toLowerCase()) > -1) {
45193 node.removeAttribute(a.name);
45196 if (this.attrib_clean.indexOf(a.name.toLowerCase()) > -1) {
45197 this.cleanAttr(node,a.name,a.value); // fixme..
45200 if (a.name == 'style') {
45201 this.cleanStyle(node,a.name,a.value);
45204 /// clean up MS crap..
45205 // tecnically this should be a list of valid class'es..
45208 if (a.name == 'class') {
45209 if (a.value.match(/^Mso/)) {
45210 node.removeAttribute('class');
45213 if (a.value.match(/^body$/)) {
45214 node.removeAttribute('class');
45224 return true; // clean children
45227 cleanAttr: function(node, n,v)
45230 if (v.match(/^\./) || v.match(/^\//)) {
45233 if (v.match(/^(http|https):\/\//)
45234 || v.match(/^mailto:/)
45235 || v.match(/^ftp:/)
45236 || v.match(/^data:/)
45240 if (v.match(/^#/)) {
45243 if (v.match(/^\{/)) { // allow template editing.
45246 // Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
45247 node.removeAttribute(n);
45250 cleanStyle : function(node, n,v)
45252 if (v.match(/expression/)) { //XSS?? should we even bother..
45253 node.removeAttribute(n);
45257 var parts = v.split(/;/);
45260 Roo.each(parts, function(p) {
45261 p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
45265 var l = p.split(':').shift().replace(/\s+/g,'');
45266 l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
45268 if ( this.style_black.length && (this.style_black.indexOf(l) > -1 || this.style_black.indexOf(l.toLowerCase()) > -1)) {
45272 // only allow 'c whitelisted system attributes'
45273 if ( this.style_white.length && style_white.indexOf(l) < 0 && style_white.indexOf(l.toLowerCase()) < 0 ) {
45281 if (clean.length) {
45282 node.setAttribute(n, clean.join(';'));
45284 node.removeAttribute(n);
45293 * @class Roo.htmleditor.FilterBlack
45294 * remove blacklisted elements.
45296 * Run a new Blacklisted Filter
45297 * @param {Object} config Configuration options
45300 Roo.htmleditor.FilterBlack = function(cfg)
45302 Roo.apply(this, cfg);
45303 this.walk(cfg.node);
45306 Roo.extend(Roo.htmleditor.FilterBlack, Roo.htmleditor.Filter,
45308 tag : true, // all elements.
45310 replace : function(n)
45312 n.parentNode.removeChild(n);
45316 * @class Roo.htmleditor.FilterComment
45319 * Run a new Comments Filter
45320 * @param {Object} config Configuration options
45322 Roo.htmleditor.FilterComment = function(cfg)
45324 this.walk(cfg.node);
45327 Roo.extend(Roo.htmleditor.FilterComment, Roo.htmleditor.Filter,
45330 replaceComment : function(n)
45332 n.parentNode.removeChild(n);
45335 * @class Roo.htmleditor.FilterKeepChildren
45336 * remove tags but keep children
45338 * Run a new Keep Children Filter
45339 * @param {Object} config Configuration options
45342 Roo.htmleditor.FilterKeepChildren = function(cfg)
45344 Roo.apply(this, cfg);
45345 if (this.tag === false) {
45346 return; // dont walk.. (you can use this to use this just to do a child removal on a single tag )
45348 this.walk(cfg.node);
45351 Roo.extend(Roo.htmleditor.FilterKeepChildren, Roo.htmleditor.FilterBlack,
45355 replaceTag : function(node)
45357 // walk children...
45359 var ar = Array.from(node.childNodes);
45361 for (var i = 0; i < ar.length; i++) {
45362 if (ar[i].nodeType == 1) {
45364 (typeof(this.tag) == 'object' && this.tag.indexOf(ar[i].tagName) > -1)
45365 || // array and it matches
45366 (typeof(this.tag) == 'string' && this.tag == ar[i].tagName)
45368 this.replaceTag(ar[i]); // child is blacklisted as well...
45373 ar = Array.from(node.childNodes);
45374 for (var i = 0; i < ar.length; i++) {
45376 node.removeChild(ar[i]);
45377 // what if we need to walk these???
45378 node.parentNode.insertBefore(ar[i], node);
45379 if (this.tag !== false) {
45384 node.parentNode.removeChild(node);
45385 return false; // don't walk children
45390 * @class Roo.htmleditor.FilterParagraph
45391 * paragraphs cause a nightmare for shared content - this filter is designed to be called ? at various points when editing
45392 * like on 'push' to remove the <p> tags and replace them with line breaks.
45394 * Run a new Paragraph Filter
45395 * @param {Object} config Configuration options
45398 Roo.htmleditor.FilterParagraph = function(cfg)
45400 // no need to apply config.
45401 this.walk(cfg.node);
45404 Roo.extend(Roo.htmleditor.FilterParagraph, Roo.htmleditor.Filter,
45411 replaceTag : function(node)
45414 if (node.childNodes.length == 1 &&
45415 node.childNodes[0].nodeType == 3 &&
45416 node.childNodes[0].textContent.trim().length < 1
45418 // remove and replace with '<BR>';
45419 node.parentNode.replaceChild(node.ownerDocument.createElement('BR'),node);
45420 return false; // no need to walk..
45422 var ar = Array.from(node.childNodes);
45423 for (var i = 0; i < ar.length; i++) {
45424 node.removeChild(ar[i]);
45425 // what if we need to walk these???
45426 node.parentNode.insertBefore(ar[i], node);
45428 // now what about this?
45432 node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
45433 node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
45434 node.parentNode.removeChild(node);
45441 * @class Roo.htmleditor.FilterSpan
45442 * filter span's with no attributes out..
45444 * Run a new Span Filter
45445 * @param {Object} config Configuration options
45448 Roo.htmleditor.FilterSpan = function(cfg)
45450 // no need to apply config.
45451 this.walk(cfg.node);
45454 Roo.extend(Roo.htmleditor.FilterSpan, Roo.htmleditor.FilterKeepChildren,
45460 replaceTag : function(node)
45462 if (node.attributes && node.attributes.length > 0) {
45463 return true; // walk if there are any.
45465 Roo.htmleditor.FilterKeepChildren.prototype.replaceTag.call(this, node);
45471 * @class Roo.htmleditor.FilterTableWidth
45472 try and remove table width data - as that frequently messes up other stuff.
45474 * was cleanTableWidths.
45476 * Quite often pasting from word etc.. results in tables with column and widths.
45477 * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
45480 * Run a new Table Filter
45481 * @param {Object} config Configuration options
45484 Roo.htmleditor.FilterTableWidth = function(cfg)
45486 // no need to apply config.
45487 this.tag = ['TABLE', 'TD', 'TR', 'TH', 'THEAD', 'TBODY' ];
45488 this.walk(cfg.node);
45491 Roo.extend(Roo.htmleditor.FilterTableWidth, Roo.htmleditor.Filter,
45496 replaceTag: function(node) {
45500 if (node.hasAttribute('width')) {
45501 node.removeAttribute('width');
45505 if (node.hasAttribute("style")) {
45508 var styles = node.getAttribute("style").split(";");
45510 Roo.each(styles, function(s) {
45511 if (!s.match(/:/)) {
45514 var kv = s.split(":");
45515 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
45518 // what ever is left... we allow.
45521 node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
45522 if (!nstyle.length) {
45523 node.removeAttribute('style');
45527 return true; // continue doing children..
45530 * @class Roo.htmleditor.FilterWord
45531 * try and clean up all the mess that Word generates.
45533 * This is the 'nice version' - see 'Heavy' that white lists a very short list of elements, and multi-filters
45536 * Run a new Span Filter
45537 * @param {Object} config Configuration options
45540 Roo.htmleditor.FilterWord = function(cfg)
45542 // no need to apply config.
45543 this.walk(cfg.node);
45546 Roo.extend(Roo.htmleditor.FilterWord, Roo.htmleditor.Filter,
45552 * Clean up MS wordisms...
45554 replaceTag : function(node)
45557 // no idea what this does - span with text, replaceds with just text.
45559 node.nodeName == 'SPAN' &&
45560 !node.hasAttributes() &&
45561 node.childNodes.length == 1 &&
45562 node.firstChild.nodeName == "#text"
45564 var textNode = node.firstChild;
45565 node.removeChild(textNode);
45566 if (node.getAttribute('lang') != 'zh-CN') { // do not space pad on chinese characters..
45567 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
45569 node.parentNode.insertBefore(textNode, node);
45570 if (node.getAttribute('lang') != 'zh-CN') { // do not space pad on chinese characters..
45571 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
45574 node.parentNode.removeChild(node);
45575 return false; // dont do chidren - we have remove our node - so no need to do chdhilren?
45580 if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
45581 node.parentNode.removeChild(node);
45582 return false; // dont do chidlren
45584 //Roo.log(node.tagName);
45585 // remove - but keep children..
45586 if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
45587 //Roo.log('-- removed');
45588 while (node.childNodes.length) {
45589 var cn = node.childNodes[0];
45590 node.removeChild(cn);
45591 node.parentNode.insertBefore(cn, node);
45592 // move node to parent - and clean it..
45593 this.replaceTag(cn);
45595 node.parentNode.removeChild(node);
45596 /// no need to iterate chidlren = it's got none..
45597 //this.iterateChildren(node, this.cleanWord);
45598 return false; // no need to iterate children.
45601 if (node.className.length) {
45603 var cn = node.className.split(/\W+/);
45605 Roo.each(cn, function(cls) {
45606 if (cls.match(/Mso[a-zA-Z]+/)) {
45611 node.className = cna.length ? cna.join(' ') : '';
45613 node.removeAttribute("class");
45617 if (node.hasAttribute("lang")) {
45618 node.removeAttribute("lang");
45621 if (node.hasAttribute("style")) {
45623 var styles = node.getAttribute("style").split(";");
45625 Roo.each(styles, function(s) {
45626 if (!s.match(/:/)) {
45629 var kv = s.split(":");
45630 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
45633 // what ever is left... we allow.
45636 node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
45637 if (!nstyle.length) {
45638 node.removeAttribute('style');
45641 return true; // do children
45648 * @class Roo.htmleditor.FilterStyleToTag
45649 * part of the word stuff... - certain 'styles' should be converted to tags.
45651 * font-weight: bold -> bold
45652 * ?? super / subscrit etc..
45655 * Run a new style to tag filter.
45656 * @param {Object} config Configuration options
45658 Roo.htmleditor.FilterStyleToTag = function(cfg)
45662 B : [ 'fontWeight' , 'bold'],
45663 I : [ 'fontStyle' , 'italic'],
45664 //pre : [ 'font-style' , 'italic'],
45665 // h1.. h6 ?? font-size?
45666 SUP : [ 'verticalAlign' , 'super' ],
45667 SUB : [ 'verticalAlign' , 'sub' ]
45672 Roo.apply(this, cfg);
45675 this.walk(cfg.node);
45682 Roo.extend(Roo.htmleditor.FilterStyleToTag, Roo.htmleditor.Filter,
45684 tag: true, // all tags
45689 replaceTag : function(node)
45693 if (node.getAttribute("style") === null) {
45697 for (var k in this.tags) {
45698 if (node.style[this.tags[k][0]] == this.tags[k][1]) {
45700 node.style.removeProperty(this.tags[k][0]);
45703 if (!inject.length) {
45706 var cn = Array.from(node.childNodes);
45708 Roo.each(inject, function(t) {
45709 var nc = node.ownerDocument.createelement(t);
45710 nn.appendChild(nc);
45713 for(var i = 0;i < cn.length;cn++) {
45714 node.removeChild(cn[i]);
45715 nn.appendChild(cn[i]);
45717 return true /// iterate thru
45721 * @class Roo.htmleditor.FilterLongBr
45722 * BR/BR/BR - keep a maximum of 2...
45724 * Run a new Long BR Filter
45725 * @param {Object} config Configuration options
45728 Roo.htmleditor.FilterLongBr = function(cfg)
45730 // no need to apply config.
45731 this.walk(cfg.node);
45734 Roo.extend(Roo.htmleditor.FilterLongBr, Roo.htmleditor.Filter,
45741 replaceTag : function(node)
45744 var ps = node.nextSibling;
45745 while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
45746 ps = ps.nextSibling;
45749 if (!ps && [ 'TD', 'TH', 'LI', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(node.parentNode.tagName) > -1) {
45750 node.parentNode.removeChild(node); // remove last BR inside one fo these tags
45754 if (!ps || ps.nodeType != 1) {
45758 if (!ps || ps.tagName != 'BR') {
45767 if (!node.previousSibling) {
45770 var ps = node.previousSibling;
45772 while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
45773 ps = ps.previousSibling;
45775 if (!ps || ps.nodeType != 1) {
45778 // if header or BR before.. then it's a candidate for removal.. - as we only want '2' of these..
45779 if (!ps || [ 'BR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(ps.tagName) < 0) {
45783 node.parentNode.removeChild(node); // remove me...
45785 return false; // no need to do children
45791 * @class Roo.htmleditor.Tidy
45793 * @cfg {Roo.HtmlEditorCore} core the editor.
45795 * Create a new Filter.
45796 * @param {Object} config Configuration options
45800 Roo.htmleditor.Tidy = function(cfg) {
45801 Roo.apply(this, cfg);
45803 this.core.doc.body.innerHTML = this.tidy(this.core.doc.body, '');
45807 Roo.htmleditor.Tidy.toString = function(node)
45809 return Roo.htmleditor.Tidy.prototype.tidy(node, '');
45812 Roo.htmleditor.Tidy.prototype = {
45815 wrap : function(s) {
45816 return s.replace(/\n/g, " ").replace(/(?![^\n]{1,80}$)([^\n]{1,80})\s/g, '$1\n');
45820 tidy : function(node, indent) {
45822 if (node.nodeType == 3) {
45826 return indent === false ? node.nodeValue : this.wrap(node.nodeValue.trim()).split("\n").join("\n" + indent);
45831 if (node.nodeType != 1) {
45837 if (node.tagName == 'BODY') {
45839 return this.cn(node, '');
45842 // Prints the node tagName, such as <A>, <IMG>, etc
45843 var ret = "<" + node.tagName + this.attr(node) ;
45845 // elements with no children..
45846 if (['IMG', 'BR', 'HR', 'INPUT'].indexOf(node.tagName) > -1) {
45852 var cindent = indent === false ? '' : (indent + ' ');
45853 // tags where we will not pad the children.. (inline text tags etc..)
45854 if (['PRE', 'TEXTAREA', 'TD', 'A', 'SPAN', 'B', 'I', 'S'].indexOf(node.tagName) > -1) { // or code?
45860 var cn = this.cn(node, cindent );
45862 return ret + cn + '</' + node.tagName + '>';
45865 cn: function(node, indent)
45869 var ar = Array.from(node.childNodes);
45870 for (var i = 0 ; i < ar.length ; i++) {
45874 if (indent !== false // indent==false preservies everything
45876 && ar[i].nodeType == 3
45877 && ar[i].nodeValue.length > 0
45878 && ar[i].nodeValue.match(/^\s+/)
45880 if (ret.length && ret[ret.length-1] == "\n" + indent) {
45881 ret.pop(); // remove line break from last?
45884 ret.push(" "); // add a space if i'm a text item with a space at the front, as tidy will strip spaces.
45886 if (indent !== false
45887 && ar[i].nodeType == 1 // element - and indent is not set...
45889 ret.push("\n" + indent);
45892 ret.push(this.tidy(ar[i], indent));
45893 // text + trailing indent
45894 if (indent !== false
45895 && ar[i].nodeType == 3
45896 && ar[i].nodeValue.length > 0
45897 && ar[i].nodeValue.match(/\s+$/)
45899 ret.push("\n" + indent);
45906 // what if all text?
45909 return ret.join('');
45914 attr : function(node)
45917 for(i = 0; i < node.attributes.length;i++) {
45919 // skip empty values?
45920 if (!node.attributes.item(i).value.length) {
45923 attr.push( node.attributes.item(i).name + '="' +
45924 Roo.util.Format.htmlEncode(node.attributes.item(i).value) + '"'
45927 return attr.length ? (' ' + attr.join(' ') ) : '';
45935 * @class Roo.htmleditor.KeyEnter
45936 * Handle Enter press..
45937 * @cfg {Roo.HtmlEditorCore} core the editor.
45939 * Create a new Filter.
45940 * @param {Object} config Configuration options
45945 Roo.htmleditor.KeyEnter = function(cfg) {
45946 Roo.apply(this, cfg);
45947 // this does not actually call walk as it's really just a abstract class
45949 Roo.get(this.core.doc.body).on('keypress', this.keypress, this);
45953 Roo.htmleditor.KeyEnter.prototype = {
45957 keypress : function(e) {
45958 if (e.charCode != 13) {
45961 e.preventDefault();
45962 // https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
45963 var doc = this.core.doc;
45965 var docFragment = doc.createDocumentFragment();
45968 var newEle = doc.createTextNode('\n');
45969 docFragment.appendChild(newEle);
45972 var range = this.core.win.getSelection().getRangeAt(0);
45973 var n = range.commonAncestorContainer ;
45974 while (n && n.nodeType != 1) {
45978 if (n && n.tagName == 'UL') {
45979 li = doc.createElement('LI');
45983 if (n && n.tagName == 'LI') {
45984 li = doc.createElement('LI');
45985 if (n.nextSibling) {
45986 n.parentNode.insertBefore(li, n.firstSibling);
45989 n.parentNode.appendChild(li);
45993 range = doc.createRange();
45994 range.setStartAfter(li);
45995 range.collapse(true);
45997 //make the cursor there
45998 var sel = this.core.win.getSelection();
45999 sel.removeAllRanges();
46000 sel.addRange(range);
46005 //add the br, or p, or something else
46006 newEle = doc.createElement('br');
46007 docFragment.appendChild(newEle);
46009 //make the br replace selection
46011 range.deleteContents();
46013 range.insertNode(docFragment);
46015 //create a new range
46016 range = doc.createRange();
46017 range.setStartAfter(newEle);
46018 range.collapse(true);
46020 //make the cursor there
46021 var sel = this.core.win.getSelection();
46022 sel.removeAllRanges();
46023 sel.addRange(range);
46031 * @class Roo.htmleditor.Block
46032 * Base class for html editor blocks - do not use it directly .. extend it..
46033 * @cfg {DomElement} node The node to apply stuff to.
46034 * @cfg {String} friendly_name the name that appears in the context bar about this block
46035 * @cfg {Object} Context menu - see Roo.form.HtmlEditor.ToolbarContext
46038 * Create a new Filter.
46039 * @param {Object} config Configuration options
46042 Roo.htmleditor.Block = function(cfg)
46044 // do nothing .. should not be called really.
46047 Roo.htmleditor.Block.factory = function(node)
46050 var id = Roo.get(node).id;
46051 if (typeof(Roo.htmleditor.Block.cache[id]) != 'undefined') {
46052 Roo.htmleditor.Block.cache[id].readElement();
46053 return Roo.htmleditor.Block.cache[id];
46056 var cls = Roo.htmleditor['Block' + Roo.get(node).attr('data-block')];
46057 if (typeof(cls) == 'undefined') {
46058 Roo.log("OOps missing block : " + 'Block' + Roo.get(node).attr('data-block'));
46061 Roo.htmleditor.Block.cache[id] = new cls({ node: node });
46062 return Roo.htmleditor.Block.cache[id]; /// should trigger update element
46064 // question goes here... do we need to clear out this cache sometimes?
46065 // or show we make it relivant to the htmleditor.
46066 Roo.htmleditor.Block.cache = {};
46068 Roo.htmleditor.Block.prototype = {
46072 // used by context menu
46073 friendly_name : 'Image with caption',
46077 * Update a node with values from this object
46078 * @param {DomElement} node
46080 updateElement : function(node)
46082 Roo.DomHelper.update(node === undefined ? this.node : node, this.toObject());
46085 * convert to plain HTML for calling insertAtCursor..
46087 toHTML : function()
46089 return Roo.DomHelper.markup(this.toObject());
46092 * used by readEleemnt to extract data from a node
46093 * may need improving as it's pretty basic
46095 * @param {DomElement} node
46096 * @param {String} tag - tag to find, eg. IMG ?? might be better to use DomQuery ?
46097 * @param {String} attribute (use html - for contents, or style for using next param as style)
46098 * @param {String} style the style property - eg. text-align
46100 getVal : function(node, tag, attr, style)
46103 if (tag !== true && n.tagName != tag.toUpperCase()) {
46104 // in theory we could do figure[3] << 3rd figure? or some more complex search..?
46105 // but kiss for now.
46106 n = node.getElementsByTagName(tag).item(0);
46108 if (attr == 'html') {
46109 return n.innerHTML;
46111 if (attr == 'style') {
46112 return Roo.get(n).getStyle(style);
46115 return Roo.get(n).attr(attr);
46119 * create a DomHelper friendly object - for use with
46120 * Roo.DomHelper.markup / overwrite / etc..
46123 toObject : function()
46128 * Read a node that has a 'data-block' property - and extract the values from it.
46129 * @param {DomElement} node - the node
46131 readElement : function(node)
46142 * @class Roo.htmleditor.BlockFigure
46143 * Block that has an image and a figcaption
46144 * @cfg {String} image_src the url for the image
46145 * @cfg {String} align (left|right) alignment for the block default left
46146 * @cfg {String} text_align (left|right) alignment for the text caption default left.
46147 * @cfg {String} caption the text to appear below (and in the alt tag)
46148 * @cfg {String|number} image_width the width of the image number or %?
46149 * @cfg {String|number} image_height the height of the image number or %?
46152 * Create a new Filter.
46153 * @param {Object} config Configuration options
46156 Roo.htmleditor.BlockFigure = function(cfg)
46159 this.readElement(cfg.node);
46160 this.updateElement(cfg.node);
46162 Roo.apply(this, cfg);
46164 Roo.extend(Roo.htmleditor.BlockFigure, Roo.htmleditor.Block, {
46172 text_align: 'left',
46177 // used by context menu
46178 friendly_name : 'Image with caption',
46180 context : { // ?? static really
46193 opts : [[ "left"],[ "right"]],
46198 title: "Caption Align",
46199 opts : [ [ "left"],[ "right"],[ "center"]],
46210 * create a DomHelper friendly object - for use with
46211 * Roo.DomHelper.markup / overwrite / etc..
46213 toObject : function()
46215 var d = document.createElement('div');
46216 d.innerHTML = this.caption;
46220 'data-block' : 'Figure',
46221 contenteditable : 'false',
46224 float : this.align ,
46225 width : this.width,
46226 margin: this.margin
46231 src : this.image_src,
46232 alt : d.innerText.replace(/\n/g, " "), // removeHTML..
46239 contenteditable : true,
46241 'text-align': this.text_align
46243 html : this.caption
46250 readElement : function(node)
46252 this.image_src = this.getVal(node, 'img', 'src');
46253 this.align = this.getVal(node, 'figure', 'style', 'float');
46254 this.caption = this.getVal(node, 'figcaption', 'html');
46255 this.text_align = this.getVal(node, 'figcaption', 'style','text-align');
46256 this.width = this.getVal(node, 'figure', 'style', 'width');
46257 this.margin = this.getVal(node, 'figure', 'style', 'margin');
46270 //<script type="text/javascript">
46273 * Based Ext JS Library 1.1.1
46274 * Copyright(c) 2006-2007, Ext JS, LLC.
46280 * @class Roo.HtmlEditorCore
46281 * @extends Roo.Component
46282 * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
46284 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
46287 Roo.HtmlEditorCore = function(config){
46290 Roo.HtmlEditorCore.superclass.constructor.call(this, config);
46295 * @event initialize
46296 * Fires when the editor is fully initialized (including the iframe)
46297 * @param {Roo.HtmlEditorCore} this
46302 * Fires when the editor is first receives the focus. Any insertion must wait
46303 * until after this event.
46304 * @param {Roo.HtmlEditorCore} this
46308 * @event beforesync
46309 * Fires before the textarea is updated with content from the editor iframe. Return false
46310 * to cancel the sync.
46311 * @param {Roo.HtmlEditorCore} this
46312 * @param {String} html
46316 * @event beforepush
46317 * Fires before the iframe editor is updated with content from the textarea. Return false
46318 * to cancel the push.
46319 * @param {Roo.HtmlEditorCore} this
46320 * @param {String} html
46325 * Fires when the textarea is updated with content from the editor iframe.
46326 * @param {Roo.HtmlEditorCore} this
46327 * @param {String} html
46332 * Fires when the iframe editor is updated with content from the textarea.
46333 * @param {Roo.HtmlEditorCore} this
46334 * @param {String} html
46339 * @event editorevent
46340 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
46341 * @param {Roo.HtmlEditorCore} this
46347 // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
46349 // defaults : white / black...
46350 this.applyBlacklists();
46357 Roo.extend(Roo.HtmlEditorCore, Roo.Component, {
46361 * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field
46367 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
46372 * @cfg {Number} height (in pixels)
46376 * @cfg {Number} width (in pixels)
46381 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
46384 stylesheets: false,
46387 * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
46389 allowComments: false,
46393 // private properties
46394 validationEvent : false,
46396 initialized : false,
46398 sourceEditMode : false,
46399 onFocus : Roo.emptyFn,
46401 hideMode:'offsets',
46405 // blacklist + whitelisted elements..
46412 * Protected method that will not generally be called directly. It
46413 * is called when the editor initializes the iframe with HTML contents. Override this method if you
46414 * want to change the initialization markup of the iframe (e.g. to add stylesheets).
46416 getDocMarkup : function(){
46420 // inherit styels from page...??
46421 if (this.stylesheets === false) {
46423 Roo.get(document.head).select('style').each(function(node) {
46424 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
46427 Roo.get(document.head).select('link').each(function(node) {
46428 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
46431 } else if (!this.stylesheets.length) {
46433 st = '<style type="text/css">' +
46434 'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
46437 for (var i in this.stylesheets) {
46438 if (typeof(this.stylesheets[i]) != 'string') {
46441 st += '<link rel="stylesheet" href="' + this.stylesheets[i] +'" type="text/css">';
46446 st += '<style type="text/css">' +
46447 'IMG { cursor: pointer } ' +
46450 var cls = 'roo-htmleditor-body';
46452 if(this.bodyCls.length){
46453 cls += ' ' + this.bodyCls;
46456 return '<html><head>' + st +
46457 //<style type="text/css">' +
46458 //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
46460 ' </head><body contenteditable="true" data-enable-grammerly="true" class="' + cls + '"></body></html>';
46464 onRender : function(ct, position)
46467 //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
46468 this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
46471 this.el.dom.style.border = '0 none';
46472 this.el.dom.setAttribute('tabIndex', -1);
46473 this.el.addClass('x-hidden hide');
46477 if(Roo.isIE){ // fix IE 1px bogus margin
46478 this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
46482 this.frameId = Roo.id();
46486 var iframe = this.owner.wrap.createChild({
46488 cls: 'form-control', // bootstrap..
46490 name: this.frameId,
46491 frameBorder : 'no',
46492 'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL : "javascript:false"
46497 this.iframe = iframe.dom;
46499 this.assignDocWin();
46501 this.doc.designMode = 'on';
46504 this.doc.write(this.getDocMarkup());
46508 var task = { // must defer to wait for browser to be ready
46510 //console.log("run task?" + this.doc.readyState);
46511 this.assignDocWin();
46512 if(this.doc.body || this.doc.readyState == 'complete'){
46514 this.doc.designMode="on";
46518 Roo.TaskMgr.stop(task);
46519 this.initEditor.defer(10, this);
46526 Roo.TaskMgr.start(task);
46531 onResize : function(w, h)
46533 Roo.log('resize: ' +w + ',' + h );
46534 //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
46538 if(typeof w == 'number'){
46540 this.iframe.style.width = w + 'px';
46542 if(typeof h == 'number'){
46544 this.iframe.style.height = h + 'px';
46546 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
46553 * Toggles the editor between standard and source edit mode.
46554 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
46556 toggleSourceEdit : function(sourceEditMode){
46558 this.sourceEditMode = sourceEditMode === true;
46560 if(this.sourceEditMode){
46562 Roo.get(this.iframe).addClass(['x-hidden','hide', 'd-none']); //FIXME - what's the BS styles for these
46565 Roo.get(this.iframe).removeClass(['x-hidden','hide', 'd-none']);
46566 //this.iframe.className = '';
46569 //this.setSize(this.owner.wrap.getSize());
46570 //this.fireEvent('editmodechange', this, this.sourceEditMode);
46577 * Protected method that will not generally be called directly. If you need/want
46578 * custom HTML cleanup, this is the method you should override.
46579 * @param {String} html The HTML to be cleaned
46580 * return {String} The cleaned HTML
46582 cleanHtml : function(html){
46583 html = String(html);
46584 if(html.length > 5){
46585 if(Roo.isSafari){ // strip safari nonsense
46586 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
46589 if(html == ' '){
46596 * HTML Editor -> Textarea
46597 * Protected method that will not generally be called directly. Syncs the contents
46598 * of the editor iframe with the textarea.
46600 syncValue : function()
46602 Roo.log("HtmlEditorCore:syncValue (EDITOR->TEXT)");
46603 if(this.initialized){
46604 var bd = (this.doc.body || this.doc.documentElement);
46605 //this.cleanUpPaste(); -- this is done else where and causes havoc..
46607 // not sure if this is really the place for this
46608 // the blocks are synced occasionaly - since we currently dont add listeners on the blocks
46609 // this has to update attributes that get duped.. like alt and caption..
46612 //Roo.each(Roo.get(this.doc.body).query('*[data-block]'), function(e) {
46613 // Roo.htmleditor.Block.factory(e);
46617 var div = document.createElement('div');
46618 div.innerHTML = bd.innerHTML;
46619 // remove content editable. (blocks)
46622 new Roo.htmleditor.FilterAttributes({node : div, attrib_black: [ 'contenteditable' ] });
46624 var html = div.innerHTML;
46626 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
46627 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
46629 html = '<div style="'+m[0]+'">' + html + '</div>';
46632 html = this.cleanHtml(html);
46633 // fix up the special chars.. normaly like back quotes in word...
46634 // however we do not want to do this with chinese..
46635 html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
46637 var cc = match.charCodeAt();
46639 // Get the character value, handling surrogate pairs
46640 if (match.length == 2) {
46641 // It's a surrogate pair, calculate the Unicode code point
46642 var high = match.charCodeAt(0) - 0xD800;
46643 var low = match.charCodeAt(1) - 0xDC00;
46644 cc = (high * 0x400) + low + 0x10000;
46646 (cc >= 0x4E00 && cc < 0xA000 ) ||
46647 (cc >= 0x3400 && cc < 0x4E00 ) ||
46648 (cc >= 0xf900 && cc < 0xfb00 )
46653 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
46654 return "&#" + cc + ";";
46661 if(this.owner.fireEvent('beforesync', this, html) !== false){
46662 this.el.dom.value = html;
46663 this.owner.fireEvent('sync', this, html);
46669 * TEXTAREA -> EDITABLE
46670 * Protected method that will not generally be called directly. Pushes the value of the textarea
46671 * into the iframe editor.
46673 pushValue : function()
46675 Roo.log("HtmlEditorCore:pushValue (TEXT->EDITOR)");
46676 if(this.initialized){
46677 var v = this.el.dom.value.trim();
46680 if(this.owner.fireEvent('beforepush', this, v) !== false){
46681 var d = (this.doc.body || this.doc.documentElement);
46684 this.el.dom.value = d.innerHTML;
46685 this.owner.fireEvent('push', this, v);
46688 Roo.each(Roo.get(this.doc.body).query('*[data-block]'), function(e) {
46690 Roo.htmleditor.Block.factory(e);
46693 var lc = this.doc.body.lastChild;
46694 if (lc && lc.nodeType == 1 && lc.getAttribute("contenteditable") == "false") {
46695 // add an extra line at the end.
46696 this.doc.body.appendChild(this.doc.createElement('br'));
46704 deferFocus : function(){
46705 this.focus.defer(10, this);
46709 focus : function(){
46710 if(this.win && !this.sourceEditMode){
46717 assignDocWin: function()
46719 var iframe = this.iframe;
46722 this.doc = iframe.contentWindow.document;
46723 this.win = iframe.contentWindow;
46725 // if (!Roo.get(this.frameId)) {
46728 // this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
46729 // this.win = Roo.get(this.frameId).dom.contentWindow;
46731 if (!Roo.get(this.frameId) && !iframe.contentDocument) {
46735 this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
46736 this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
46741 initEditor : function(){
46742 //console.log("INIT EDITOR");
46743 this.assignDocWin();
46747 this.doc.designMode="on";
46749 this.doc.write(this.getDocMarkup());
46752 var dbody = (this.doc.body || this.doc.documentElement);
46753 //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
46754 // this copies styles from the containing element into thsi one..
46755 // not sure why we need all of this..
46756 //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
46758 //var ss = this.el.getStyles( 'background-image', 'background-repeat');
46759 //ss['background-attachment'] = 'fixed'; // w3c
46760 dbody.bgProperties = 'fixed'; // ie
46761 //Roo.DomHelper.applyStyles(dbody, ss);
46762 Roo.EventManager.on(this.doc, {
46763 //'mousedown': this.onEditorEvent,
46764 'mouseup': this.onEditorEvent,
46765 'dblclick': this.onEditorEvent,
46766 'click': this.onEditorEvent,
46767 'keyup': this.onEditorEvent,
46772 Roo.EventManager.on(this.doc, {
46773 'paste': this.onPasteEvent,
46777 Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
46779 if(Roo.isIE || Roo.isSafari || Roo.isOpera){
46780 Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
46782 this.initialized = true;
46785 // initialize special key events - enter
46786 new Roo.htmleditor.KeyEnter({core : this});
46790 this.owner.fireEvent('initialize', this);
46794 onPasteEvent : function(e,v)
46796 // I think we better assume paste is going to be a dirty load of rubish from word..
46798 // even pasting into a 'email version' of this widget will have to clean up that mess.
46799 var cd = (e.browserEvent.clipboardData || window.clipboardData);
46801 // check what type of paste - if it's an image, then handle it differently.
46802 if (cd.files.length > 0) {
46804 var urlAPI = (window.createObjectURL && window) ||
46805 (window.URL && URL.revokeObjectURL && URL) ||
46806 (window.webkitURL && webkitURL);
46808 var url = urlAPI.createObjectURL( cd.files[0]);
46809 this.insertAtCursor('<img src=" + url + ">');
46813 var html = cd.getData('text/html'); // clipboard event
46814 var parser = new Roo.rtf.Parser(cd.getData('text/rtf'));
46815 var images = parser.doc.getElementsByType('pict');
46819 images = images.filter(function(g) { return !g.path.match(/^rtf\/(head|pgdsctbl|listtable)/); }) // ignore headers
46820 .map(function(g) { return g.toDataURL(); });
46823 html = this.cleanWordChars(html);
46825 var d = (new DOMParser().parseFromString(html, 'text/html')).body;
46827 if (images.length > 0) {
46828 Roo.each(d.getElementsByTagName('img'), function(img, i) {
46829 img.setAttribute('src', images[i]);
46834 new Roo.htmleditor.FilterStyleToTag({ node : d });
46835 new Roo.htmleditor.FilterAttributes({
46837 attrib_white : ['href', 'src', 'name', 'align'],
46838 attrib_clean : ['href', 'src' ]
46840 new Roo.htmleditor.FilterBlack({ node : d, tag : this.black});
46841 // should be fonts..
46842 new Roo.htmleditor.FilterKeepChildren({node : d, tag : [ 'FONT' ]} );
46843 new Roo.htmleditor.FilterParagraph({ node : d });
46844 new Roo.htmleditor.FilterSpan({ node : d });
46845 new Roo.htmleditor.FilterLongBr({ node : d });
46849 this.insertAtCursor(d.innerHTML);
46851 e.preventDefault();
46853 // default behaveiour should be our local cleanup paste? (optional?)
46854 // for simple editor - we want to hammer the paste and get rid of everything... - so over-rideable..
46855 //this.owner.fireEvent('paste', e, v);
46858 onDestroy : function(){
46864 //for (var i =0; i < this.toolbars.length;i++) {
46865 // // fixme - ask toolbars for heights?
46866 // this.toolbars[i].onDestroy();
46869 //this.wrap.dom.innerHTML = '';
46870 //this.wrap.remove();
46875 onFirstFocus : function(){
46877 this.assignDocWin();
46880 this.activated = true;
46883 if(Roo.isGecko){ // prevent silly gecko errors
46885 var s = this.win.getSelection();
46886 if(!s.focusNode || s.focusNode.nodeType != 3){
46887 var r = s.getRangeAt(0);
46888 r.selectNodeContents((this.doc.body || this.doc.documentElement));
46893 this.execCmd('useCSS', true);
46894 this.execCmd('styleWithCSS', false);
46897 this.owner.fireEvent('activate', this);
46901 adjustFont: function(btn){
46902 var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
46903 //if(Roo.isSafari){ // safari
46906 var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
46907 if(Roo.isSafari){ // safari
46908 var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
46909 v = (v < 10) ? 10 : v;
46910 v = (v > 48) ? 48 : v;
46911 v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
46916 v = Math.max(1, v+adjust);
46918 this.execCmd('FontSize', v );
46921 onEditorEvent : function(e)
46923 this.owner.fireEvent('editorevent', this, e);
46924 // this.updateToolbar();
46925 this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
46928 insertTag : function(tg)
46930 // could be a bit smarter... -> wrap the current selected tRoo..
46931 if (tg.toLowerCase() == 'span' ||
46932 tg.toLowerCase() == 'code' ||
46933 tg.toLowerCase() == 'sup' ||
46934 tg.toLowerCase() == 'sub'
46937 range = this.createRange(this.getSelection());
46938 var wrappingNode = this.doc.createElement(tg.toLowerCase());
46939 wrappingNode.appendChild(range.extractContents());
46940 range.insertNode(wrappingNode);
46947 this.execCmd("formatblock", tg);
46951 insertText : function(txt)
46955 var range = this.createRange();
46956 range.deleteContents();
46957 //alert(Sender.getAttribute('label'));
46959 range.insertNode(this.doc.createTextNode(txt));
46965 * Executes a Midas editor command on the editor document and performs necessary focus and
46966 * toolbar updates. <b>This should only be called after the editor is initialized.</b>
46967 * @param {String} cmd The Midas command
46968 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
46970 relayCmd : function(cmd, value){
46972 this.execCmd(cmd, value);
46973 this.owner.fireEvent('editorevent', this);
46974 //this.updateToolbar();
46975 this.owner.deferFocus();
46979 * Executes a Midas editor command directly on the editor document.
46980 * For visual commands, you should use {@link #relayCmd} instead.
46981 * <b>This should only be called after the editor is initialized.</b>
46982 * @param {String} cmd The Midas command
46983 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
46985 execCmd : function(cmd, value){
46986 this.doc.execCommand(cmd, false, value === undefined ? null : value);
46993 * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
46995 * @param {String} text | dom node..
46997 insertAtCursor : function(text)
47000 if(!this.activated){
47004 if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
47008 // from jquery ui (MIT licenced)
47010 var win = this.win;
47012 if (win.getSelection && win.getSelection().getRangeAt) {
47014 // delete the existing?
47016 this.createRange(this.getSelection()).deleteContents();
47017 range = win.getSelection().getRangeAt(0);
47018 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
47019 range.insertNode(node);
47020 } else if (win.document.selection && win.document.selection.createRange) {
47021 // no firefox support
47022 var txt = typeof(text) == 'string' ? text : text.outerHTML;
47023 win.document.selection.createRange().pasteHTML(txt);
47025 // no firefox support
47026 var txt = typeof(text) == 'string' ? text : text.outerHTML;
47027 this.execCmd('InsertHTML', txt);
47036 mozKeyPress : function(e){
47038 var c = e.getCharCode(), cmd;
47041 c = String.fromCharCode(c).toLowerCase();
47055 // this.cleanUpPaste.defer(100, this);
47063 e.preventDefault();
47071 fixKeys : function(){ // load time branching for fastest keydown performance
47073 return function(e){
47074 var k = e.getKey(), r;
47077 r = this.doc.selection.createRange();
47080 r.pasteHTML('    ');
47087 r = this.doc.selection.createRange();
47089 var target = r.parentElement();
47090 if(!target || target.tagName.toLowerCase() != 'li'){
47092 r.pasteHTML('<br/>');
47098 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
47099 // this.cleanUpPaste.defer(100, this);
47105 }else if(Roo.isOpera){
47106 return function(e){
47107 var k = e.getKey();
47111 this.execCmd('InsertHTML','    ');
47114 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
47115 // this.cleanUpPaste.defer(100, this);
47120 }else if(Roo.isSafari){
47121 return function(e){
47122 var k = e.getKey();
47126 this.execCmd('InsertText','\t');
47130 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
47131 // this.cleanUpPaste.defer(100, this);
47139 getAllAncestors: function()
47141 var p = this.getSelectedNode();
47144 a.push(p); // push blank onto stack..
47145 p = this.getParentElement();
47149 while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
47153 a.push(this.doc.body);
47157 lastSelNode : false,
47160 getSelection : function()
47162 this.assignDocWin();
47163 return Roo.isIE ? this.doc.selection : this.win.getSelection();
47166 * Select a dom node
47167 * @param {DomElement} node the node to select
47169 selectNode : function(node)
47172 var nodeRange = node.ownerDocument.createRange();
47174 nodeRange.selectNode(node);
47176 nodeRange.selectNodeContents(node);
47178 //nodeRange.collapse(true);
47179 var s = this.win.getSelection();
47180 s.removeAllRanges();
47181 s.addRange(nodeRange);
47184 getSelectedNode: function()
47186 // this may only work on Gecko!!!
47188 // should we cache this!!!!
47193 var range = this.createRange(this.getSelection()).cloneRange();
47196 var parent = range.parentElement();
47198 var testRange = range.duplicate();
47199 testRange.moveToElementText(parent);
47200 if (testRange.inRange(range)) {
47203 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
47206 parent = parent.parentElement;
47211 // is ancestor a text element.
47212 var ac = range.commonAncestorContainer;
47213 if (ac.nodeType == 3) {
47214 ac = ac.parentNode;
47217 var ar = ac.childNodes;
47220 var other_nodes = [];
47221 var has_other_nodes = false;
47222 for (var i=0;i<ar.length;i++) {
47223 if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ?
47226 // fullly contained node.
47228 if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
47233 // probably selected..
47234 if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
47235 other_nodes.push(ar[i]);
47239 if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0)) {
47244 has_other_nodes = true;
47246 if (!nodes.length && other_nodes.length) {
47247 nodes= other_nodes;
47249 if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
47255 createRange: function(sel)
47257 // this has strange effects when using with
47258 // top toolbar - not sure if it's a great idea.
47259 //this.editor.contentWindow.focus();
47260 if (typeof sel != "undefined") {
47262 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
47264 return this.doc.createRange();
47267 return this.doc.createRange();
47270 getParentElement: function()
47273 this.assignDocWin();
47274 var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
47276 var range = this.createRange(sel);
47279 var p = range.commonAncestorContainer;
47280 while (p.nodeType == 3) { // text node
47291 * Range intersection.. the hard stuff...
47295 * [ -- selected range --- ]
47299 * if end is before start or hits it. fail.
47300 * if start is after end or hits it fail.
47302 * if either hits (but other is outside. - then it's not
47308 // @see http://www.thismuchiknow.co.uk/?p=64.
47309 rangeIntersectsNode : function(range, node)
47311 var nodeRange = node.ownerDocument.createRange();
47313 nodeRange.selectNode(node);
47315 nodeRange.selectNodeContents(node);
47318 var rangeStartRange = range.cloneRange();
47319 rangeStartRange.collapse(true);
47321 var rangeEndRange = range.cloneRange();
47322 rangeEndRange.collapse(false);
47324 var nodeStartRange = nodeRange.cloneRange();
47325 nodeStartRange.collapse(true);
47327 var nodeEndRange = nodeRange.cloneRange();
47328 nodeEndRange.collapse(false);
47330 return rangeStartRange.compareBoundaryPoints(
47331 Range.START_TO_START, nodeEndRange) == -1 &&
47332 rangeEndRange.compareBoundaryPoints(
47333 Range.START_TO_START, nodeStartRange) == 1;
47337 rangeCompareNode : function(range, node)
47339 var nodeRange = node.ownerDocument.createRange();
47341 nodeRange.selectNode(node);
47343 nodeRange.selectNodeContents(node);
47347 range.collapse(true);
47349 nodeRange.collapse(true);
47351 var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
47352 var ee = range.compareBoundaryPoints( Range.END_TO_END, nodeRange);
47354 //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
47356 var nodeIsBefore = ss == 1;
47357 var nodeIsAfter = ee == -1;
47359 if (nodeIsBefore && nodeIsAfter) {
47362 if (!nodeIsBefore && nodeIsAfter) {
47363 return 1; //right trailed.
47366 if (nodeIsBefore && !nodeIsAfter) {
47367 return 2; // left trailed.
47373 cleanWordChars : function(input) {// change the chars to hex code
47376 [ 8211, "–" ],
47377 [ 8212, "—" ],
47385 var output = input;
47386 Roo.each(swapCodes, function(sw) {
47387 var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
47389 output = output.replace(swapper, sw[1]);
47399 cleanUpChild : function (node)
47402 new Roo.htmleditor.FilterComment({node : node});
47403 new Roo.htmleditor.FilterAttributes({
47405 attrib_black : this.ablack,
47406 attrib_clean : this.aclean,
47407 style_white : this.cwhite,
47408 style_black : this.cblack
47410 new Roo.htmleditor.FilterBlack({ node : node, tag : this.black});
47411 new Roo.htmleditor.FilterKeepChildren({node : node, tag : this.tag_remove} );
47417 * Clean up MS wordisms...
47418 * @deprecated - use filter directly
47420 cleanWord : function(node)
47422 new Roo.htmleditor.FilterWord({ node : node ? node : this.doc.body });
47429 * @deprecated - use filters
47431 cleanTableWidths : function(node)
47433 new Roo.htmleditor.FilterTableWidth({ node : node ? node : this.doc.body});
47440 applyBlacklists : function()
47442 var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white : [];
47443 var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black : [];
47445 this.aclean = typeof(this.owner.aclean) != 'undefined' && this.owner.aclean ? this.owner.aclean : Roo.HtmlEditorCore.aclean;
47446 this.ablack = typeof(this.owner.ablack) != 'undefined' && this.owner.ablack ? this.owner.ablack : Roo.HtmlEditorCore.ablack;
47447 this.tag_remove = typeof(this.owner.tag_remove) != 'undefined' && this.owner.tag_remove ? this.owner.tag_remove : Roo.HtmlEditorCore.tag_remove;
47451 Roo.each(Roo.HtmlEditorCore.white, function(tag) {
47452 if (b.indexOf(tag) > -1) {
47455 this.white.push(tag);
47459 Roo.each(w, function(tag) {
47460 if (b.indexOf(tag) > -1) {
47463 if (this.white.indexOf(tag) > -1) {
47466 this.white.push(tag);
47471 Roo.each(Roo.HtmlEditorCore.black, function(tag) {
47472 if (w.indexOf(tag) > -1) {
47475 this.black.push(tag);
47479 Roo.each(b, function(tag) {
47480 if (w.indexOf(tag) > -1) {
47483 if (this.black.indexOf(tag) > -1) {
47486 this.black.push(tag);
47491 w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite : [];
47492 b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack : [];
47496 Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
47497 if (b.indexOf(tag) > -1) {
47500 this.cwhite.push(tag);
47504 Roo.each(w, function(tag) {
47505 if (b.indexOf(tag) > -1) {
47508 if (this.cwhite.indexOf(tag) > -1) {
47511 this.cwhite.push(tag);
47516 Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
47517 if (w.indexOf(tag) > -1) {
47520 this.cblack.push(tag);
47524 Roo.each(b, function(tag) {
47525 if (w.indexOf(tag) > -1) {
47528 if (this.cblack.indexOf(tag) > -1) {
47531 this.cblack.push(tag);
47536 setStylesheets : function(stylesheets)
47538 if(typeof(stylesheets) == 'string'){
47539 Roo.get(this.iframe.contentDocument.head).createChild({
47541 rel : 'stylesheet',
47550 Roo.each(stylesheets, function(s) {
47555 Roo.get(_this.iframe.contentDocument.head).createChild({
47557 rel : 'stylesheet',
47566 removeStylesheets : function()
47570 Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
47575 setStyle : function(style)
47577 Roo.get(this.iframe.contentDocument.head).createChild({
47586 // hide stuff that is not compatible
47600 * @event specialkey
47604 * @cfg {String} fieldClass @hide
47607 * @cfg {String} focusClass @hide
47610 * @cfg {String} autoCreate @hide
47613 * @cfg {String} inputType @hide
47616 * @cfg {String} invalidClass @hide
47619 * @cfg {String} invalidText @hide
47622 * @cfg {String} msgFx @hide
47625 * @cfg {String} validateOnBlur @hide
47629 Roo.HtmlEditorCore.white = [
47630 'AREA', 'BR', 'IMG', 'INPUT', 'HR', 'WBR',
47632 'ADDRESS', 'BLOCKQUOTE', 'CENTER', 'DD', 'DIR', 'DIV',
47633 'DL', 'DT', 'H1', 'H2', 'H3', 'H4',
47634 'H5', 'H6', 'HR', 'ISINDEX', 'LISTING', 'MARQUEE',
47635 'MENU', 'MULTICOL', 'OL', 'P', 'PLAINTEXT', 'PRE',
47636 'TABLE', 'UL', 'XMP',
47638 'CAPTION', 'COL', 'COLGROUP', 'TBODY', 'TD', 'TFOOT', 'TH',
47641 'DIR', 'MENU', 'OL', 'UL', 'DL',
47647 Roo.HtmlEditorCore.black = [
47648 // 'embed', 'object', // enable - backend responsiblity to clean thiese
47650 'BASE', 'BASEFONT', 'BGSOUND', 'BLINK', 'BODY',
47651 'FRAME', 'FRAMESET', 'HEAD', 'HTML', 'ILAYER',
47652 'IFRAME', 'LAYER', 'LINK', 'META', 'OBJECT',
47653 'SCRIPT', 'STYLE' ,'TITLE', 'XML',
47654 //'FONT' // CLEAN LATER..
47655 'COLGROUP', 'COL' // messy tables.
47658 Roo.HtmlEditorCore.clean = [ // ?? needed???
47659 'SCRIPT', 'STYLE', 'TITLE', 'XML'
47661 Roo.HtmlEditorCore.tag_remove = [
47666 Roo.HtmlEditorCore.ablack = [
47670 Roo.HtmlEditorCore.aclean = [
47671 'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc'
47675 Roo.HtmlEditorCore.pwhite= [
47676 'http', 'https', 'mailto'
47679 // white listed style attributes.
47680 Roo.HtmlEditorCore.cwhite= [
47681 // 'text-align', /// default is to allow most things..
47687 // black listed style attributes.
47688 Roo.HtmlEditorCore.cblack= [
47689 // 'font-size' -- this can be set by the project
47695 //<script type="text/javascript">
47698 * Ext JS Library 1.1.1
47699 * Copyright(c) 2006-2007, Ext JS, LLC.
47705 Roo.form.HtmlEditor = function(config){
47709 Roo.form.HtmlEditor.superclass.constructor.call(this, config);
47711 if (!this.toolbars) {
47712 this.toolbars = [];
47714 this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
47720 * @class Roo.form.HtmlEditor
47721 * @extends Roo.form.Field
47722 * Provides a lightweight HTML Editor component.
47724 * This has been tested on Fireforx / Chrome.. IE may not be so great..
47726 * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
47727 * supported by this editor.</b><br/><br/>
47728 * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
47729 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
47731 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
47733 * @cfg {Boolean} clearUp
47737 * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
47742 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
47747 * @cfg {Number} height (in pixels)
47751 * @cfg {Number} width (in pixels)
47756 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets - this is usally a good idea rootURL + '/roojs1/css/undoreset.css', .
47759 stylesheets: false,
47763 * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
47768 * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
47774 * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
47779 * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
47784 * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
47786 allowComments: false,
47788 * @cfg {string} bodyCls- default '' default classes to add to body of editable area - usually undoreset is a good start..
47797 // private properties
47798 validationEvent : false,
47800 initialized : false,
47803 onFocus : Roo.emptyFn,
47805 hideMode:'offsets',
47807 actionMode : 'container', // defaults to hiding it...
47809 defaultAutoCreate : { // modified by initCompnoent..
47811 style:"width:500px;height:300px;",
47812 autocomplete: "new-password"
47816 initComponent : function(){
47819 * @event initialize
47820 * Fires when the editor is fully initialized (including the iframe)
47821 * @param {HtmlEditor} this
47826 * Fires when the editor is first receives the focus. Any insertion must wait
47827 * until after this event.
47828 * @param {HtmlEditor} this
47832 * @event beforesync
47833 * Fires before the textarea is updated with content from the editor iframe. Return false
47834 * to cancel the sync.
47835 * @param {HtmlEditor} this
47836 * @param {String} html
47840 * @event beforepush
47841 * Fires before the iframe editor is updated with content from the textarea. Return false
47842 * to cancel the push.
47843 * @param {HtmlEditor} this
47844 * @param {String} html
47849 * Fires when the textarea is updated with content from the editor iframe.
47850 * @param {HtmlEditor} this
47851 * @param {String} html
47856 * Fires when the iframe editor is updated with content from the textarea.
47857 * @param {HtmlEditor} this
47858 * @param {String} html
47862 * @event editmodechange
47863 * Fires when the editor switches edit modes
47864 * @param {HtmlEditor} this
47865 * @param {Boolean} sourceEdit True if source edit, false if standard editing.
47867 editmodechange: true,
47869 * @event editorevent
47870 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
47871 * @param {HtmlEditor} this
47875 * @event firstfocus
47876 * Fires when on first focus - needed by toolbars..
47877 * @param {HtmlEditor} this
47882 * Auto save the htmlEditor value as a file into Events
47883 * @param {HtmlEditor} this
47887 * @event savedpreview
47888 * preview the saved version of htmlEditor
47889 * @param {HtmlEditor} this
47891 savedpreview: true,
47894 * @event stylesheetsclick
47895 * Fires when press the Sytlesheets button
47896 * @param {Roo.HtmlEditorCore} this
47898 stylesheetsclick: true,
47901 * Fires when press user pastes into the editor
47902 * @param {Roo.HtmlEditorCore} this
47906 this.defaultAutoCreate = {
47908 style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
47909 autocomplete: "new-password"
47914 * Protected method that will not generally be called directly. It
47915 * is called when the editor creates its toolbar. Override this method if you need to
47916 * add custom toolbar buttons.
47917 * @param {HtmlEditor} editor
47919 createToolbar : function(editor){
47920 Roo.log("create toolbars");
47921 if (!editor.toolbars || !editor.toolbars.length) {
47922 editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
47925 for (var i =0 ; i < editor.toolbars.length;i++) {
47926 editor.toolbars[i] = Roo.factory(
47927 typeof(editor.toolbars[i]) == 'string' ?
47928 { xtype: editor.toolbars[i]} : editor.toolbars[i],
47929 Roo.form.HtmlEditor);
47930 editor.toolbars[i].init(editor);
47938 onRender : function(ct, position)
47941 Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
47943 this.wrap = this.el.wrap({
47944 cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
47947 this.editorcore.onRender(ct, position);
47949 if (this.resizable) {
47950 this.resizeEl = new Roo.Resizable(this.wrap, {
47954 minHeight : this.height,
47955 height: this.height,
47956 handles : this.resizable,
47959 resize : function(r, w, h) {
47960 _t.onResize(w,h); // -something
47966 this.createToolbar(this);
47970 this.setSize(this.wrap.getSize());
47972 if (this.resizeEl) {
47973 this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
47974 // should trigger onReize..
47977 this.keyNav = new Roo.KeyNav(this.el, {
47979 "tab" : function(e){
47980 e.preventDefault();
47982 var value = this.getValue();
47984 var start = this.el.dom.selectionStart;
47985 var end = this.el.dom.selectionEnd;
47989 this.setValue(value.substring(0, start) + "\t" + value.substring(end));
47990 this.el.dom.setSelectionRange(end + 1, end + 1);
47994 var f = value.substring(0, start).split("\t");
47996 if(f.pop().length != 0){
48000 this.setValue(f.join("\t") + value.substring(end));
48001 this.el.dom.setSelectionRange(start - 1, start - 1);
48005 "home" : function(e){
48006 e.preventDefault();
48008 var curr = this.el.dom.selectionStart;
48009 var lines = this.getValue().split("\n");
48016 this.el.dom.setSelectionRange(0, 0);
48022 for (var i = 0; i < lines.length;i++) {
48023 pos += lines[i].length;
48033 pos -= lines[i].length;
48039 this.el.dom.setSelectionRange(pos, pos);
48043 this.el.dom.selectionStart = pos;
48044 this.el.dom.selectionEnd = curr;
48047 "end" : function(e){
48048 e.preventDefault();
48050 var curr = this.el.dom.selectionStart;
48051 var lines = this.getValue().split("\n");
48058 this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
48064 for (var i = 0; i < lines.length;i++) {
48066 pos += lines[i].length;
48080 this.el.dom.setSelectionRange(pos, pos);
48084 this.el.dom.selectionStart = curr;
48085 this.el.dom.selectionEnd = pos;
48090 doRelay : function(foo, bar, hname){
48091 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
48097 // if(this.autosave && this.w){
48098 // this.autoSaveFn = setInterval(this.autosave, 1000);
48103 onResize : function(w, h)
48105 Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
48110 if(typeof w == 'number'){
48111 var aw = w - this.wrap.getFrameWidth('lr');
48112 this.el.setWidth(this.adjustWidth('textarea', aw));
48115 if(typeof h == 'number'){
48117 for (var i =0; i < this.toolbars.length;i++) {
48118 // fixme - ask toolbars for heights?
48119 tbh += this.toolbars[i].tb.el.getHeight();
48120 if (this.toolbars[i].footer) {
48121 tbh += this.toolbars[i].footer.el.getHeight();
48128 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
48129 ah -= 5; // knock a few pixes off for look..
48131 this.el.setHeight(this.adjustWidth('textarea', ah));
48135 Roo.log('onResize:' + [w,h,ew,eh].join(',') );
48136 this.editorcore.onResize(ew,eh);
48141 * Toggles the editor between standard and source edit mode.
48142 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
48144 toggleSourceEdit : function(sourceEditMode)
48146 this.editorcore.toggleSourceEdit(sourceEditMode);
48148 if(this.editorcore.sourceEditMode){
48149 Roo.log('editor - showing textarea');
48152 // Roo.log(this.syncValue());
48153 this.editorcore.syncValue();
48154 this.el.removeClass('x-hidden');
48155 this.el.dom.removeAttribute('tabIndex');
48157 this.el.dom.scrollTop = 0;
48160 for (var i = 0; i < this.toolbars.length; i++) {
48161 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
48162 this.toolbars[i].tb.hide();
48163 this.toolbars[i].footer.hide();
48168 Roo.log('editor - hiding textarea');
48170 // Roo.log(this.pushValue());
48171 this.editorcore.pushValue();
48173 this.el.addClass('x-hidden');
48174 this.el.dom.setAttribute('tabIndex', -1);
48176 for (var i = 0; i < this.toolbars.length; i++) {
48177 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
48178 this.toolbars[i].tb.show();
48179 this.toolbars[i].footer.show();
48183 //this.deferFocus();
48186 this.setSize(this.wrap.getSize());
48187 this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
48189 this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
48192 // private (for BoxComponent)
48193 adjustSize : Roo.BoxComponent.prototype.adjustSize,
48195 // private (for BoxComponent)
48196 getResizeEl : function(){
48200 // private (for BoxComponent)
48201 getPositionEl : function(){
48206 initEvents : function(){
48207 this.originalValue = this.getValue();
48211 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
48214 markInvalid : Roo.emptyFn,
48216 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
48219 clearInvalid : Roo.emptyFn,
48221 setValue : function(v){
48222 Roo.form.HtmlEditor.superclass.setValue.call(this, v);
48223 this.editorcore.pushValue();
48228 deferFocus : function(){
48229 this.focus.defer(10, this);
48233 focus : function(){
48234 this.editorcore.focus();
48240 onDestroy : function(){
48246 for (var i =0; i < this.toolbars.length;i++) {
48247 // fixme - ask toolbars for heights?
48248 this.toolbars[i].onDestroy();
48251 this.wrap.dom.innerHTML = '';
48252 this.wrap.remove();
48257 onFirstFocus : function(){
48258 //Roo.log("onFirstFocus");
48259 this.editorcore.onFirstFocus();
48260 for (var i =0; i < this.toolbars.length;i++) {
48261 this.toolbars[i].onFirstFocus();
48267 syncValue : function()
48269 this.editorcore.syncValue();
48272 pushValue : function()
48274 this.editorcore.pushValue();
48277 setStylesheets : function(stylesheets)
48279 this.editorcore.setStylesheets(stylesheets);
48282 removeStylesheets : function()
48284 this.editorcore.removeStylesheets();
48288 // hide stuff that is not compatible
48302 * @event specialkey
48306 * @cfg {String} fieldClass @hide
48309 * @cfg {String} focusClass @hide
48312 * @cfg {String} autoCreate @hide
48315 * @cfg {String} inputType @hide
48318 * @cfg {String} invalidClass @hide
48321 * @cfg {String} invalidText @hide
48324 * @cfg {String} msgFx @hide
48327 * @cfg {String} validateOnBlur @hide
48331 // <script type="text/javascript">
48334 * Ext JS Library 1.1.1
48335 * Copyright(c) 2006-2007, Ext JS, LLC.
48341 * @class Roo.form.HtmlEditorToolbar1
48346 new Roo.form.HtmlEditor({
48349 new Roo.form.HtmlEditorToolbar1({
48350 disable : { fonts: 1 , format: 1, ..., ... , ...],
48356 * @cfg {Object} disable List of elements to disable..
48357 * @cfg {Array} btns List of additional buttons.
48361 * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
48364 Roo.form.HtmlEditor.ToolbarStandard = function(config)
48367 Roo.apply(this, config);
48369 // default disabled, based on 'good practice'..
48370 this.disable = this.disable || {};
48371 Roo.applyIf(this.disable, {
48374 specialElements : true
48378 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
48379 // dont call parent... till later.
48382 Roo.apply(Roo.form.HtmlEditor.ToolbarStandard.prototype, {
48389 editorcore : false,
48391 * @cfg {Object} disable List of toolbar elements to disable
48398 * @cfg {String} createLinkText The default text for the create link prompt
48400 createLinkText : 'Please enter the URL for the link:',
48402 * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
48404 defaultLinkValue : 'http:/'+'/',
48408 * @cfg {Array} fontFamilies An array of available font families
48426 // "á" , ?? a acute?
48431 "°" // , // degrees
48433 // "é" , // e ecute
48434 // "ú" , // u ecute?
48437 specialElements : [
48439 text: "Insert Table",
48442 ihtml : '<table><tr><td>Cell</td></tr></table>'
48446 text: "Insert Image",
48449 ihtml : '<img src="about:blank"/>'
48458 "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password",
48459 "input:submit", "input:button", "select", "textarea", "label" ],
48462 ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"],
48464 ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
48473 * @cfg {String} defaultFont default font to use.
48475 defaultFont: 'tahoma',
48477 fontSelect : false,
48480 formatCombo : false,
48482 init : function(editor)
48484 this.editor = editor;
48485 this.editorcore = editor.editorcore ? editor.editorcore : editor;
48486 var editorcore = this.editorcore;
48490 var fid = editorcore.frameId;
48492 function btn(id, toggle, handler){
48493 var xid = fid + '-'+ id ;
48497 cls : 'x-btn-icon x-edit-'+id,
48498 enableToggle:toggle !== false,
48499 scope: _t, // was editor...
48500 handler:handler||_t.relayBtnCmd,
48501 clickEvent:'mousedown',
48502 tooltip: etb.buttonTips[id] || undefined, ///tips ???
48509 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
48511 // stop form submits
48512 tb.el.on('click', function(e){
48513 e.preventDefault(); // what does this do?
48516 if(!this.disable.font) { // && !Roo.isSafari){
48517 /* why no safari for fonts
48518 editor.fontSelect = tb.el.createChild({
48521 cls:'x-font-select',
48522 html: this.createFontOptions()
48525 editor.fontSelect.on('change', function(){
48526 var font = editor.fontSelect.dom.value;
48527 editor.relayCmd('fontname', font);
48528 editor.deferFocus();
48532 editor.fontSelect.dom,
48538 if(!this.disable.formats){
48539 this.formatCombo = new Roo.form.ComboBox({
48540 store: new Roo.data.SimpleStore({
48543 data : this.formats // from states.js
48547 //autoCreate : {tag: "div", size: "20"},
48548 displayField:'tag',
48552 triggerAction: 'all',
48553 emptyText:'Add tag',
48554 selectOnFocus:true,
48557 'select': function(c, r, i) {
48558 editorcore.insertTag(r.get('tag'));
48564 tb.addField(this.formatCombo);
48568 if(!this.disable.format){
48573 btn('strikethrough')
48576 if(!this.disable.fontSize){
48581 btn('increasefontsize', false, editorcore.adjustFont),
48582 btn('decreasefontsize', false, editorcore.adjustFont)
48587 if(!this.disable.colors){
48590 id:editorcore.frameId +'-forecolor',
48591 cls:'x-btn-icon x-edit-forecolor',
48592 clickEvent:'mousedown',
48593 tooltip: this.buttonTips['forecolor'] || undefined,
48595 menu : new Roo.menu.ColorMenu({
48596 allowReselect: true,
48597 focus: Roo.emptyFn,
48600 selectHandler: function(cp, color){
48601 editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
48602 editor.deferFocus();
48605 clickEvent:'mousedown'
48608 id:editorcore.frameId +'backcolor',
48609 cls:'x-btn-icon x-edit-backcolor',
48610 clickEvent:'mousedown',
48611 tooltip: this.buttonTips['backcolor'] || undefined,
48613 menu : new Roo.menu.ColorMenu({
48614 focus: Roo.emptyFn,
48617 allowReselect: true,
48618 selectHandler: function(cp, color){
48620 editorcore.execCmd('useCSS', false);
48621 editorcore.execCmd('hilitecolor', color);
48622 editorcore.execCmd('useCSS', true);
48623 editor.deferFocus();
48625 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor',
48626 Roo.isSafari || Roo.isIE ? '#'+color : color);
48627 editor.deferFocus();
48631 clickEvent:'mousedown'
48636 // now add all the items...
48639 if(!this.disable.alignments){
48642 btn('justifyleft'),
48643 btn('justifycenter'),
48644 btn('justifyright')
48648 //if(!Roo.isSafari){
48649 if(!this.disable.links){
48652 btn('createlink', false, this.createLink) /// MOVE TO HERE?!!?!?!?!
48656 if(!this.disable.lists){
48659 btn('insertorderedlist'),
48660 btn('insertunorderedlist')
48663 if(!this.disable.sourceEdit){
48666 btn('sourceedit', true, function(btn){
48667 this.toggleSourceEdit(btn.pressed);
48674 // special menu.. - needs to be tidied up..
48675 if (!this.disable.special) {
48678 cls: 'x-edit-none',
48684 for (var i =0; i < this.specialChars.length; i++) {
48685 smenu.menu.items.push({
48687 html: this.specialChars[i],
48688 handler: function(a,b) {
48689 editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
48690 //editor.insertAtCursor(a.html);
48704 if (!this.disable.cleanStyles) {
48706 cls: 'x-btn-icon x-btn-clear',
48712 for (var i =0; i < this.cleanStyles.length; i++) {
48713 cmenu.menu.items.push({
48714 actiontype : this.cleanStyles[i],
48715 html: 'Remove ' + this.cleanStyles[i],
48716 handler: function(a,b) {
48719 var c = Roo.get(editorcore.doc.body);
48720 c.select('[style]').each(function(s) {
48721 s.dom.style.removeProperty(a.actiontype);
48723 editorcore.syncValue();
48728 cmenu.menu.items.push({
48729 actiontype : 'tablewidths',
48730 html: 'Remove Table Widths',
48731 handler: function(a,b) {
48732 editorcore.cleanTableWidths();
48733 editorcore.syncValue();
48737 cmenu.menu.items.push({
48738 actiontype : 'word',
48739 html: 'Remove MS Word Formating',
48740 handler: function(a,b) {
48741 editorcore.cleanWord();
48742 editorcore.syncValue();
48747 cmenu.menu.items.push({
48748 actiontype : 'all',
48749 html: 'Remove All Styles',
48750 handler: function(a,b) {
48752 var c = Roo.get(editorcore.doc.body);
48753 c.select('[style]').each(function(s) {
48754 s.dom.removeAttribute('style');
48756 editorcore.syncValue();
48761 cmenu.menu.items.push({
48762 actiontype : 'all',
48763 html: 'Remove All CSS Classes',
48764 handler: function(a,b) {
48766 var c = Roo.get(editorcore.doc.body);
48767 c.select('[class]').each(function(s) {
48768 s.dom.removeAttribute('class');
48770 editorcore.cleanWord();
48771 editorcore.syncValue();
48776 cmenu.menu.items.push({
48777 actiontype : 'tidy',
48778 html: 'Tidy HTML Source',
48779 handler: function(a,b) {
48780 new Roo.htmleditor.Tidy(editorcore.doc.body);
48781 editorcore.syncValue();
48790 if (!this.disable.specialElements) {
48793 cls: 'x-edit-none',
48798 for (var i =0; i < this.specialElements.length; i++) {
48799 semenu.menu.items.push(
48801 handler: function(a,b) {
48802 editor.insertAtCursor(this.ihtml);
48804 }, this.specialElements[i])
48816 for(var i =0; i< this.btns.length;i++) {
48817 var b = Roo.factory(this.btns[i],this.btns[i].xns || Roo.form);
48818 b.cls = 'x-edit-none';
48820 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
48821 b.cls += ' x-init-enable';
48824 b.scope = editorcore;
48832 // disable everything...
48834 this.tb.items.each(function(item){
48837 item.id != editorcore.frameId+ '-sourceedit' &&
48838 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
48844 this.rendered = true;
48846 // the all the btns;
48847 editor.on('editorevent', this.updateToolbar, this);
48848 // other toolbars need to implement this..
48849 //editor.on('editmodechange', this.updateToolbar, this);
48853 relayBtnCmd : function(btn) {
48854 this.editorcore.relayCmd(btn.cmd);
48856 // private used internally
48857 createLink : function(){
48858 Roo.log("create link?");
48859 var url = prompt(this.createLinkText, this.defaultLinkValue);
48860 if(url && url != 'http:/'+'/'){
48861 this.editorcore.relayCmd('createlink', url);
48867 * Protected method that will not generally be called directly. It triggers
48868 * a toolbar update by reading the markup state of the current selection in the editor.
48870 updateToolbar: function(){
48872 if(!this.editorcore.activated){
48873 this.editor.onFirstFocus();
48877 var btns = this.tb.items.map,
48878 doc = this.editorcore.doc,
48879 frameId = this.editorcore.frameId;
48881 if(!this.disable.font && !Roo.isSafari){
48883 var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
48884 if(name != this.fontSelect.dom.value){
48885 this.fontSelect.dom.value = name;
48889 if(!this.disable.format){
48890 btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
48891 btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
48892 btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
48893 btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
48895 if(!this.disable.alignments){
48896 btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
48897 btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
48898 btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
48900 if(!Roo.isSafari && !this.disable.lists){
48901 btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
48902 btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
48905 var ans = this.editorcore.getAllAncestors();
48906 if (this.formatCombo) {
48909 var store = this.formatCombo.store;
48910 this.formatCombo.setValue("");
48911 for (var i =0; i < ans.length;i++) {
48912 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
48914 this.formatCombo.setValue(ans[i].tagName.toLowerCase());
48922 // hides menus... - so this cant be on a menu...
48923 Roo.menu.MenuMgr.hideAll();
48925 //this.editorsyncValue();
48929 createFontOptions : function(){
48930 var buf = [], fs = this.fontFamilies, ff, lc;
48934 for(var i = 0, len = fs.length; i< len; i++){
48936 lc = ff.toLowerCase();
48938 '<option value="',lc,'" style="font-family:',ff,';"',
48939 (this.defaultFont == lc ? ' selected="true">' : '>'),
48944 return buf.join('');
48947 toggleSourceEdit : function(sourceEditMode){
48949 Roo.log("toolbar toogle");
48950 if(sourceEditMode === undefined){
48951 sourceEditMode = !this.sourceEditMode;
48953 this.sourceEditMode = sourceEditMode === true;
48954 var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
48955 // just toggle the button?
48956 if(btn.pressed !== this.sourceEditMode){
48957 btn.toggle(this.sourceEditMode);
48961 if(sourceEditMode){
48962 Roo.log("disabling buttons");
48963 this.tb.items.each(function(item){
48964 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
48970 Roo.log("enabling buttons");
48971 if(this.editorcore.initialized){
48972 this.tb.items.each(function(item){
48978 Roo.log("calling toggole on editor");
48979 // tell the editor that it's been pressed..
48980 this.editor.toggleSourceEdit(sourceEditMode);
48984 * Object collection of toolbar tooltips for the buttons in the editor. The key
48985 * is the command id associated with that button and the value is a valid QuickTips object.
48990 title: 'Bold (Ctrl+B)',
48991 text: 'Make the selected text bold.',
48992 cls: 'x-html-editor-tip'
48995 title: 'Italic (Ctrl+I)',
48996 text: 'Make the selected text italic.',
48997 cls: 'x-html-editor-tip'
49005 title: 'Bold (Ctrl+B)',
49006 text: 'Make the selected text bold.',
49007 cls: 'x-html-editor-tip'
49010 title: 'Italic (Ctrl+I)',
49011 text: 'Make the selected text italic.',
49012 cls: 'x-html-editor-tip'
49015 title: 'Underline (Ctrl+U)',
49016 text: 'Underline the selected text.',
49017 cls: 'x-html-editor-tip'
49020 title: 'Strikethrough',
49021 text: 'Strikethrough the selected text.',
49022 cls: 'x-html-editor-tip'
49024 increasefontsize : {
49025 title: 'Grow Text',
49026 text: 'Increase the font size.',
49027 cls: 'x-html-editor-tip'
49029 decreasefontsize : {
49030 title: 'Shrink Text',
49031 text: 'Decrease the font size.',
49032 cls: 'x-html-editor-tip'
49035 title: 'Text Highlight Color',
49036 text: 'Change the background color of the selected text.',
49037 cls: 'x-html-editor-tip'
49040 title: 'Font Color',
49041 text: 'Change the color of the selected text.',
49042 cls: 'x-html-editor-tip'
49045 title: 'Align Text Left',
49046 text: 'Align text to the left.',
49047 cls: 'x-html-editor-tip'
49050 title: 'Center Text',
49051 text: 'Center text in the editor.',
49052 cls: 'x-html-editor-tip'
49055 title: 'Align Text Right',
49056 text: 'Align text to the right.',
49057 cls: 'x-html-editor-tip'
49059 insertunorderedlist : {
49060 title: 'Bullet List',
49061 text: 'Start a bulleted list.',
49062 cls: 'x-html-editor-tip'
49064 insertorderedlist : {
49065 title: 'Numbered List',
49066 text: 'Start a numbered list.',
49067 cls: 'x-html-editor-tip'
49070 title: 'Hyperlink',
49071 text: 'Make the selected text a hyperlink.',
49072 cls: 'x-html-editor-tip'
49075 title: 'Source Edit',
49076 text: 'Switch to source editing mode.',
49077 cls: 'x-html-editor-tip'
49081 onDestroy : function(){
49084 this.tb.items.each(function(item){
49086 item.menu.removeAll();
49088 item.menu.el.destroy();
49096 onFirstFocus: function() {
49097 this.tb.items.each(function(item){
49106 // <script type="text/javascript">
49109 * Ext JS Library 1.1.1
49110 * Copyright(c) 2006-2007, Ext JS, LLC.
49117 * @class Roo.form.HtmlEditor.ToolbarContext
49122 new Roo.form.HtmlEditor({
49125 { xtype: 'ToolbarStandard', styles : {} }
49126 { xtype: 'ToolbarContext', disable : {} }
49132 * @config : {Object} disable List of elements to disable.. (not done yet.)
49133 * @config : {Object} styles Map of styles available.
49137 Roo.form.HtmlEditor.ToolbarContext = function(config)
49140 Roo.apply(this, config);
49141 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
49142 // dont call parent... till later.
49143 this.styles = this.styles || {};
49148 Roo.form.HtmlEditor.ToolbarContext.types = {
49163 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
49189 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
49260 name : 'selectoptions',
49266 // should we really allow this??
49267 // should this just be
49284 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
49285 Roo.form.HtmlEditor.ToolbarContext.stores = false;
49287 Roo.form.HtmlEditor.ToolbarContext.options = {
49289 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
49290 [ 'Courier New', 'Courier New'],
49291 [ 'Tahoma', 'Tahoma'],
49292 [ 'Times New Roman,serif', 'Times'],
49293 [ 'Verdana','Verdana' ]
49297 // fixme - these need to be configurable..
49300 //Roo.form.HtmlEditor.ToolbarContext.types
49303 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype, {
49310 editorcore : false,
49312 * @cfg {Object} disable List of toolbar elements to disable
49317 * @cfg {Object} styles List of styles
49318 * eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] }
49320 * These must be defined in the page, so they get rendered correctly..
49331 init : function(editor)
49333 this.editor = editor;
49334 this.editorcore = editor.editorcore ? editor.editorcore : editor;
49335 var editorcore = this.editorcore;
49337 var fid = editorcore.frameId;
49339 function btn(id, toggle, handler){
49340 var xid = fid + '-'+ id ;
49344 cls : 'x-btn-icon x-edit-'+id,
49345 enableToggle:toggle !== false,
49346 scope: editorcore, // was editor...
49347 handler:handler||editorcore.relayBtnCmd,
49348 clickEvent:'mousedown',
49349 tooltip: etb.buttonTips[id] || undefined, ///tips ???
49353 // create a new element.
49354 var wdiv = editor.wrap.createChild({
49356 }, editor.wrap.dom.firstChild.nextSibling, true);
49358 // can we do this more than once??
49360 // stop form submits
49363 // disable everything...
49364 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
49365 this.toolbars = {};
49367 for (var i in ty) {
49369 this.toolbars[i] = this.buildToolbar(ty[i],i);
49371 this.tb = this.toolbars.BODY;
49373 this.buildFooter();
49374 this.footer.show();
49375 editor.on('hide', function( ) { this.footer.hide() }, this);
49376 editor.on('show', function( ) { this.footer.show() }, this);
49379 this.rendered = true;
49381 // the all the btns;
49382 editor.on('editorevent', this.updateToolbar, this);
49383 // other toolbars need to implement this..
49384 //editor.on('editmodechange', this.updateToolbar, this);
49390 * Protected method that will not generally be called directly. It triggers
49391 * a toolbar update by reading the markup state of the current selection in the editor.
49393 * Note you can force an update by calling on('editorevent', scope, false)
49395 updateToolbar: function(editor ,ev, sel)
49399 ev.stopEvent(); // se if we can stop this looping with mutiple events.
49403 // capture mouse up - this is handy for selecting images..
49404 // perhaps should go somewhere else...
49405 if(!this.editorcore.activated){
49406 this.editor.onFirstFocus();
49409 Roo.log(ev ? ev.target : 'NOTARGET');
49412 // http://developer.yahoo.com/yui/docs/simple-editor.js.html
49413 // selectNode - might want to handle IE?
49418 (ev.type == 'mouseup' || ev.type == 'click' ) &&
49419 ev.target && ev.target != 'BODY' ) { // && ev.target.tagName == 'IMG') {
49420 // they have click on an image...
49421 // let's see if we can change the selection...
49424 // this triggers looping?
49425 //this.editorcore.selectNode(sel);
49430 //var updateFooter = sel ? false : true;
49433 var ans = this.editorcore.getAllAncestors();
49436 var ty = Roo.form.HtmlEditor.ToolbarContext.types;
49439 sel = ans.length ? (ans[0] ? ans[0] : ans[1]) : this.editorcore.doc.body;
49440 sel = sel ? sel : this.editorcore.doc.body;
49441 sel = sel.tagName.length ? sel : this.editorcore.doc.body;
49445 var tn = sel.tagName.toUpperCase();
49446 var lastSel = this.tb.selectedNode;
49447 this.tb.selectedNode = sel;
49448 var left_label = tn;
49450 // ok see if we are editing a block?
49451 var sel_el = Roo.get(sel);
49453 // you are not actually selecting the block.
49454 if (sel && sel.hasAttribute('data-block')) {
49456 } else if (sel && !sel.hasAttribute('contenteditable')) {
49457 db = sel_el.findParent('[data-block]');
49458 var cepar = sel_el.findParent('[contenteditable=true]');
49459 if (db && cepar && cepar.tagName != 'BODY') {
49460 db = false; // we are inside an editable block.. = not sure how we are going to handle nested blocks!?
49466 //if (db && !sel.hasAttribute('contenteditable') && sel.getAttribute('contenteditable') != 'true' ) {
49468 block = Roo.htmleditor.Block.factory(db);
49470 tn = 'BLOCK.' + db.getAttribute('data-block');
49472 //this.editorcore.selectNode(db);
49473 if (typeof(this.toolbars[tn]) == 'undefined') {
49474 this.toolbars[tn] = this.buildToolbar( false ,tn ,block.friendly_name, block);
49476 this.toolbars[tn].selectedNode = db;
49477 left_label = block.friendly_name;
49478 ans = this.editorcore.getAllAncestors();
49486 if (this.tb.name == tn && lastSel == this.tb.selectedNode && ev !== false) {
49487 return; // no change?
49493 ///console.log("show: " + tn);
49494 this.tb = typeof(this.toolbars[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
49498 this.tb.items.first().el.innerHTML = left_label + ': ';
49501 // update attributes
49504 this.tb.fields.each(function(e) {
49505 e.setValue(block[e.name]);
49509 } else if (this.tb.fields && this.tb.selectedNode) {
49510 this.tb.fields.each( function(e) {
49512 e.setValue(this.tb.selectedNode.style[e.stylename]);
49515 e.setValue(this.tb.selectedNode.getAttribute(e.attrname));
49517 this.updateToolbarStyles(this.tb.selectedNode);
49522 Roo.menu.MenuMgr.hideAll();
49527 // update the footer
49529 this.updateFooter(ans);
49533 updateToolbarStyles : function(sel)
49535 var hasStyles = false;
49536 for(var i in this.styles) {
49542 if (hasStyles && this.tb.hasStyles) {
49543 var st = this.tb.fields.item(0);
49545 st.store.removeAll();
49546 var cn = sel.className.split(/\s+/);
49549 if (this.styles['*']) {
49551 Roo.each(this.styles['*'], function(v) {
49552 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
49555 if (this.styles[tn]) {
49556 Roo.each(this.styles[tn], function(v) {
49557 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
49561 st.store.loadData(avs);
49568 updateFooter : function(ans)
49571 if (ans === false) {
49572 this.footDisp.dom.innerHTML = '';
49576 this.footerEls = ans.reverse();
49577 Roo.each(this.footerEls, function(a,i) {
49578 if (!a) { return; }
49579 html += html.length ? ' > ' : '';
49581 html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
49586 var sz = this.footDisp.up('td').getSize();
49587 this.footDisp.dom.style.width = (sz.width -10) + 'px';
49588 this.footDisp.dom.style.marginLeft = '5px';
49590 this.footDisp.dom.style.overflow = 'hidden';
49592 this.footDisp.dom.innerHTML = html;
49599 onDestroy : function(){
49602 this.tb.items.each(function(item){
49604 item.menu.removeAll();
49606 item.menu.el.destroy();
49614 onFirstFocus: function() {
49615 // need to do this for all the toolbars..
49616 this.tb.items.each(function(item){
49620 buildToolbar: function(tlist, nm, friendly_name, block)
49622 var editor = this.editor;
49623 var editorcore = this.editorcore;
49624 // create a new element.
49625 var wdiv = editor.wrap.createChild({
49627 }, editor.wrap.dom.firstChild.nextSibling, true);
49630 var tb = new Roo.Toolbar(wdiv);
49632 if (tlist === false && block) {
49633 tlist = block.contextMenu(this);
49636 tb.hasStyles = false;
49639 tb.add((typeof(friendly_name) == 'undefined' ? nm : friendly_name) + ": ");
49641 var styles = Array.from(this.styles);
49645 if (styles && styles.length) {
49646 tb.hasStyles = true;
49647 // this needs a multi-select checkbox...
49648 tb.addField( new Roo.form.ComboBox({
49649 store: new Roo.data.SimpleStore({
49651 fields: ['val', 'selected'],
49654 name : '-roo-edit-className',
49655 attrname : 'className',
49656 displayField: 'val',
49660 triggerAction: 'all',
49661 emptyText:'Select Style',
49662 selectOnFocus:true,
49665 'select': function(c, r, i) {
49666 // initial support only for on class per el..
49667 tb.selectedNode.className = r ? r.get('val') : '';
49668 editorcore.syncValue();
49675 var tbc = Roo.form.HtmlEditor.ToolbarContext;
49678 for (var i = 0; i < tlist.length; i++) {
49680 // newer versions will use xtype cfg to create menus.
49681 if (typeof(tlist[i].xtype) != 'undefined') {
49683 tb[typeof(tlist[i].name)== 'undefined' ? 'add' : 'addField'](Roo.factory(tlist[i]));
49689 var item = tlist[i];
49690 tb.add(item.title + ": ");
49693 //optname == used so you can configure the options available..
49694 var opts = item.opts ? item.opts : false;
49695 if (item.optname) { // use the b
49696 opts = Roo.form.HtmlEditor.ToolbarContext.options[item.optname];
49701 // opts == pulldown..
49702 tb.addField( new Roo.form.ComboBox({
49703 store: typeof(tbc.stores[i]) != 'undefined' ? Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
49705 fields: ['val', 'display'],
49708 name : '-roo-edit-' + tlist[i].name,
49710 attrname : tlist[i].name,
49711 stylename : item.style ? item.style : false,
49713 displayField: item.displayField ? item.displayField : 'val',
49714 valueField : 'val',
49716 mode: typeof(tbc.stores[tlist[i].name]) != 'undefined' ? 'remote' : 'local',
49718 triggerAction: 'all',
49719 emptyText:'Select',
49720 selectOnFocus:true,
49721 width: item.width ? item.width : 130,
49723 'select': function(c, r, i) {
49724 if (tb.selectedNode.hasAttribute('data-block')) {
49725 var b = Roo.htmleditor.Block.factory(tb.selectedNode);
49726 b[c.attrname] = r.get('val');
49727 b.updateElement(tb.selectedNode);
49728 editorcore.syncValue();
49733 tb.selectedNode.style[c.stylename] = r.get('val');
49734 editorcore.syncValue();
49738 tb.selectedNode.removeAttribute(c.attrname);
49739 editorcore.syncValue();
49742 tb.selectedNode.setAttribute(c.attrname, r.get('val'));
49743 editorcore.syncValue();
49752 tb.addField( new Roo.form.TextField({
49755 //allowBlank:false,
49761 tb.addField( new Roo.form.TextField({
49762 name: '-roo-edit-' + tlist[i].name,
49763 attrname : tlist[i].name,
49769 'change' : function(f, nv, ov) {
49771 if (tb.selectedNode.hasAttribute('data-block')) {
49772 var b = Roo.htmleditor.Block.factory(tb.selectedNode);
49773 b[f.attrname] = nv;
49774 b.updateElement(tb.selectedNode);
49775 editorcore.syncValue();
49779 tb.selectedNode.setAttribute(f.attrname, nv);
49780 editorcore.syncValue();
49793 text: 'Stylesheets',
49796 click : function ()
49798 _this.editor.fireEvent('stylesheetsclick', _this.editor);
49806 text: 'Remove Block or Formating', // remove the tag, and puts the children outside...
49809 click : function ()
49811 var sn = tb.selectedNode;
49813 sn = Roo.htmleditor.Block.factory(tb.selectedNode).removalNode();
49819 var stn = sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
49820 if (sn.hasAttribute('data-block')) {
49821 stn = sn.nextSibling || sn.previousSibling || sn.parentNode;
49822 sn.parentNode.removeChild(sn);
49824 } else if (sn && sn.tagName != 'BODY') {
49825 // remove and keep parents.
49826 a = new Roo.htmleditor.FilterKeepChildren({tag : false});
49831 var range = editorcore.createRange();
49833 range.setStart(stn,0);
49834 range.setEnd(stn,0);
49835 var selection = editorcore.getSelection();
49836 selection.removeAllRanges();
49837 selection.addRange(range);
49840 //_this.updateToolbar(null, null, pn);
49841 _this.updateToolbar(null, null, null);
49842 _this.updateFooter(false);
49853 tb.el.on('click', function(e){
49854 e.preventDefault(); // what does this do?
49856 tb.el.setVisibilityMode( Roo.Element.DISPLAY);
49859 // dont need to disable them... as they will get hidden
49864 buildFooter : function()
49867 var fel = this.editor.wrap.createChild();
49868 this.footer = new Roo.Toolbar(fel);
49869 // toolbar has scrolly on left / right?
49870 var footDisp= new Roo.Toolbar.Fill();
49876 handler : function() {
49877 _t.footDisp.scrollTo('left',0,true)
49881 this.footer.add( footDisp );
49886 handler : function() {
49888 _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
49892 var fel = Roo.get(footDisp.el);
49893 fel.addClass('x-editor-context');
49894 this.footDispWrap = fel;
49895 this.footDispWrap.overflow = 'hidden';
49897 this.footDisp = fel.createChild();
49898 this.footDispWrap.on('click', this.onContextClick, this)
49902 // when the footer contect changes
49903 onContextClick : function (ev,dom)
49905 ev.preventDefault();
49906 var cn = dom.className;
49908 if (!cn.match(/x-ed-loc-/)) {
49911 var n = cn.split('-').pop();
49912 var ans = this.footerEls;
49916 var range = this.editorcore.createRange();
49918 range.selectNodeContents(sel);
49919 //range.selectNode(sel);
49922 var selection = this.editorcore.getSelection();
49923 selection.removeAllRanges();
49924 selection.addRange(range);
49928 this.updateToolbar(null, null, sel);
49945 * Ext JS Library 1.1.1
49946 * Copyright(c) 2006-2007, Ext JS, LLC.
49948 * Originally Released Under LGPL - original licence link has changed is not relivant.
49951 * <script type="text/javascript">
49955 * @class Roo.form.BasicForm
49956 * @extends Roo.util.Observable
49957 * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
49959 * @param {String/HTMLElement/Roo.Element} el The form element or its id
49960 * @param {Object} config Configuration options
49962 Roo.form.BasicForm = function(el, config){
49963 this.allItems = [];
49964 this.childForms = [];
49965 Roo.apply(this, config);
49967 * The Roo.form.Field items in this form.
49968 * @type MixedCollection
49972 this.items = new Roo.util.MixedCollection(false, function(o){
49973 return o.id || (o.id = Roo.id());
49977 * @event beforeaction
49978 * Fires before any action is performed. Return false to cancel the action.
49979 * @param {Form} this
49980 * @param {Action} action The action to be performed
49982 beforeaction: true,
49984 * @event actionfailed
49985 * Fires when an action fails.
49986 * @param {Form} this
49987 * @param {Action} action The action that failed
49989 actionfailed : true,
49991 * @event actioncomplete
49992 * Fires when an action is completed.
49993 * @param {Form} this
49994 * @param {Action} action The action that completed
49996 actioncomplete : true
50001 Roo.form.BasicForm.superclass.constructor.call(this);
50003 Roo.form.BasicForm.popover.apply();
50006 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
50008 * @cfg {String} method
50009 * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
50012 * @cfg {DataReader} reader
50013 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
50014 * This is optional as there is built-in support for processing JSON.
50017 * @cfg {DataReader} errorReader
50018 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
50019 * This is completely optional as there is built-in support for processing JSON.
50022 * @cfg {String} url
50023 * The URL to use for form actions if one isn't supplied in the action options.
50026 * @cfg {Boolean} fileUpload
50027 * Set to true if this form is a file upload.
50031 * @cfg {Object} baseParams
50032 * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
50037 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
50042 activeAction : null,
50045 * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
50046 * or setValues() data instead of when the form was first created.
50048 trackResetOnLoad : false,
50052 * childForms - used for multi-tab forms
50055 childForms : false,
50058 * allItems - full list of fields.
50064 * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
50065 * element by passing it or its id or mask the form itself by passing in true.
50068 waitMsgTarget : false,
50073 disableMask : false,
50076 * @cfg {Boolean} errorMask (true|false) default false
50081 * @cfg {Number} maskOffset Default 100
50086 initEl : function(el){
50087 this.el = Roo.get(el);
50088 this.id = this.el.id || Roo.id();
50089 this.el.on('submit', this.onSubmit, this);
50090 this.el.addClass('x-form');
50094 onSubmit : function(e){
50099 * Returns true if client-side validation on the form is successful.
50102 isValid : function(){
50104 var target = false;
50105 this.items.each(function(f){
50112 if(!target && f.el.isVisible(true)){
50117 if(this.errorMask && !valid){
50118 Roo.form.BasicForm.popover.mask(this, target);
50124 * Returns array of invalid form fields.
50128 invalidFields : function()
50131 this.items.each(function(f){
50144 * DEPRICATED Returns true if any fields in this form have changed since their original load.
50147 isDirty : function(){
50149 this.items.each(function(f){
50159 * Returns true if any fields in this form have changed since their original load. (New version)
50163 hasChanged : function()
50166 this.items.each(function(f){
50167 if(f.hasChanged()){
50176 * Resets all hasChanged to 'false' -
50177 * The old 'isDirty' used 'original value..' however this breaks reset() and a few other things.
50178 * So hasChanged storage is only to be used for this purpose
50181 resetHasChanged : function()
50183 this.items.each(function(f){
50184 f.resetHasChanged();
50191 * Performs a predefined action (submit or load) or custom actions you define on this form.
50192 * @param {String} actionName The name of the action type
50193 * @param {Object} options (optional) The options to pass to the action. All of the config options listed
50194 * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
50195 * accept other config options):
50197 Property Type Description
50198 ---------------- --------------- ----------------------------------------------------------------------------------
50199 url String The url for the action (defaults to the form's url)
50200 method String The form method to use (defaults to the form's method, or POST if not defined)
50201 params String/Object The params to pass (defaults to the form's baseParams, or none if not defined)
50202 clientValidation Boolean Applies to submit only. Pass true to call form.isValid() prior to posting to
50203 validate the form on the client (defaults to false)
50205 * @return {BasicForm} this
50207 doAction : function(action, options){
50208 if(typeof action == 'string'){
50209 action = new Roo.form.Action.ACTION_TYPES[action](this, options);
50211 if(this.fireEvent('beforeaction', this, action) !== false){
50212 this.beforeAction(action);
50213 action.run.defer(100, action);
50219 * Shortcut to do a submit action.
50220 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
50221 * @return {BasicForm} this
50223 submit : function(options){
50224 this.doAction('submit', options);
50229 * Shortcut to do a load action.
50230 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
50231 * @return {BasicForm} this
50233 load : function(options){
50234 this.doAction('load', options);
50239 * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
50240 * @param {Record} record The record to edit
50241 * @return {BasicForm} this
50243 updateRecord : function(record){
50244 record.beginEdit();
50245 var fs = record.fields;
50246 fs.each(function(f){
50247 var field = this.findField(f.name);
50249 record.set(f.name, field.getValue());
50257 * Loads an Roo.data.Record into this form.
50258 * @param {Record} record The record to load
50259 * @return {BasicForm} this
50261 loadRecord : function(record){
50262 this.setValues(record.data);
50267 beforeAction : function(action){
50268 var o = action.options;
50270 if(!this.disableMask) {
50271 if(this.waitMsgTarget === true){
50272 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
50273 }else if(this.waitMsgTarget){
50274 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
50275 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
50277 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
50285 afterAction : function(action, success){
50286 this.activeAction = null;
50287 var o = action.options;
50289 if(!this.disableMask) {
50290 if(this.waitMsgTarget === true){
50292 }else if(this.waitMsgTarget){
50293 this.waitMsgTarget.unmask();
50295 Roo.MessageBox.updateProgress(1);
50296 Roo.MessageBox.hide();
50304 Roo.callback(o.success, o.scope, [this, action]);
50305 this.fireEvent('actioncomplete', this, action);
50309 // failure condition..
50310 // we have a scenario where updates need confirming.
50311 // eg. if a locking scenario exists..
50312 // we look for { errors : { needs_confirm : true }} in the response.
50314 (typeof(action.result) != 'undefined') &&
50315 (typeof(action.result.errors) != 'undefined') &&
50316 (typeof(action.result.errors.needs_confirm) != 'undefined')
50319 Roo.MessageBox.confirm(
50320 "Change requires confirmation",
50321 action.result.errorMsg,
50326 _t.doAction('submit', { params : { _submit_confirmed : 1 } } );
50336 Roo.callback(o.failure, o.scope, [this, action]);
50337 // show an error message if no failed handler is set..
50338 if (!this.hasListener('actionfailed')) {
50339 Roo.MessageBox.alert("Error",
50340 (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
50341 action.result.errorMsg :
50342 "Saving Failed, please check your entries or try again"
50346 this.fireEvent('actionfailed', this, action);
50352 * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
50353 * @param {String} id The value to search for
50356 findField : function(id){
50357 var field = this.items.get(id);
50359 this.items.each(function(f){
50360 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
50366 return field || null;
50370 * Add a secondary form to this one,
50371 * Used to provide tabbed forms. One form is primary, with hidden values
50372 * which mirror the elements from the other forms.
50374 * @param {Roo.form.Form} form to add.
50377 addForm : function(form)
50380 if (this.childForms.indexOf(form) > -1) {
50384 this.childForms.push(form);
50386 Roo.each(form.allItems, function (fe) {
50388 n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
50389 if (this.findField(n)) { // already added..
50392 var add = new Roo.form.Hidden({
50395 add.render(this.el);
50402 * Mark fields in this form invalid in bulk.
50403 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
50404 * @return {BasicForm} this
50406 markInvalid : function(errors){
50407 if(errors instanceof Array){
50408 for(var i = 0, len = errors.length; i < len; i++){
50409 var fieldError = errors[i];
50410 var f = this.findField(fieldError.id);
50412 f.markInvalid(fieldError.msg);
50418 if(typeof errors[id] != 'function' && (field = this.findField(id))){
50419 field.markInvalid(errors[id]);
50423 Roo.each(this.childForms || [], function (f) {
50424 f.markInvalid(errors);
50431 * Set values for fields in this form in bulk.
50432 * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
50433 * @return {BasicForm} this
50435 setValues : function(values){
50436 if(values instanceof Array){ // array of objects
50437 for(var i = 0, len = values.length; i < len; i++){
50439 var f = this.findField(v.id);
50441 f.setValue(v.value);
50442 if(this.trackResetOnLoad){
50443 f.originalValue = f.getValue();
50447 }else{ // object hash
50450 if(typeof values[id] != 'function' && (field = this.findField(id))){
50452 if (field.setFromData &&
50453 field.valueField &&
50454 field.displayField &&
50455 // combos' with local stores can
50456 // be queried via setValue()
50457 // to set their value..
50458 (field.store && !field.store.isLocal)
50462 sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
50463 sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
50464 field.setFromData(sd);
50467 field.setValue(values[id]);
50471 if(this.trackResetOnLoad){
50472 field.originalValue = field.getValue();
50477 this.resetHasChanged();
50480 Roo.each(this.childForms || [], function (f) {
50481 f.setValues(values);
50482 f.resetHasChanged();
50489 * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
50490 * they are returned as an array.
50491 * @param {Boolean} asString
50494 getValues : function(asString)
50496 if (this.childForms) {
50497 // copy values from the child forms
50498 Roo.each(this.childForms, function (f) {
50499 this.setValues(f.getFieldValues()); // get the full set of data, as we might be copying comboboxes from external into this one.
50504 if (typeof(FormData) != 'undefined' && asString !== true) {
50505 // this relies on a 'recent' version of chrome apparently...
50507 var fd = (new FormData(this.el.dom)).entries();
50509 var ent = fd.next();
50510 while (!ent.done) {
50511 ret[ent.value[0]] = ent.value[1]; // not sure how this will handle duplicates..
50522 var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
50523 if(asString === true){
50526 return Roo.urlDecode(fs);
50530 * Returns the fields in this form as an object with key/value pairs.
50531 * This differs from getValues as it calls getValue on each child item, rather than using dom data.
50534 getFieldValues : function(with_hidden)
50536 if (this.childForms) {
50537 // copy values from the child forms
50538 // should this call getFieldValues - probably not as we do not currently copy
50539 // hidden fields when we generate..
50540 Roo.each(this.childForms, function (f) {
50541 this.setValues(f.getFieldValues());
50546 this.items.each(function(f){
50549 return; // skip read only values.
50552 if (!f.getName()) {
50555 var v = f.getValue();
50556 if (f.inputType =='radio') {
50557 if (typeof(ret[f.getName()]) == 'undefined') {
50558 ret[f.getName()] = ''; // empty..
50561 if (!f.el.dom.checked) {
50565 v = f.el.dom.value;
50569 // not sure if this supported any more..
50570 if ((typeof(v) == 'object') && f.getRawValue) {
50571 v = f.getRawValue() ; // dates..
50573 // combo boxes where name != hiddenName...
50574 if (f.name != f.getName()) {
50575 ret[f.name] = f.getRawValue();
50577 ret[f.getName()] = v;
50584 * Clears all invalid messages in this form.
50585 * @return {BasicForm} this
50587 clearInvalid : function(){
50588 this.items.each(function(f){
50592 Roo.each(this.childForms || [], function (f) {
50601 * Resets this form.
50602 * @return {BasicForm} this
50604 reset : function(){
50605 this.items.each(function(f){
50609 Roo.each(this.childForms || [], function (f) {
50612 this.resetHasChanged();
50618 * Add Roo.form components to this form.
50619 * @param {Field} field1
50620 * @param {Field} field2 (optional)
50621 * @param {Field} etc (optional)
50622 * @return {BasicForm} this
50625 this.items.addAll(Array.prototype.slice.call(arguments, 0));
50631 * Removes a field from the items collection (does NOT remove its markup).
50632 * @param {Field} field
50633 * @return {BasicForm} this
50635 remove : function(field){
50636 this.items.remove(field);
50641 * Looks at the fields in this form, checks them for an id attribute,
50642 * and calls applyTo on the existing dom element with that id.
50643 * @return {BasicForm} this
50645 render : function(){
50646 this.items.each(function(f){
50647 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
50655 * Calls {@link Ext#apply} for all fields in this form with the passed object.
50656 * @param {Object} values
50657 * @return {BasicForm} this
50659 applyToFields : function(o){
50660 this.items.each(function(f){
50667 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
50668 * @param {Object} values
50669 * @return {BasicForm} this
50671 applyIfToFields : function(o){
50672 this.items.each(function(f){
50680 Roo.BasicForm = Roo.form.BasicForm;
50682 Roo.apply(Roo.form.BasicForm, {
50696 intervalID : false,
50702 if(this.isApplied){
50707 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
50708 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
50709 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
50710 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
50713 this.maskEl.top.enableDisplayMode("block");
50714 this.maskEl.left.enableDisplayMode("block");
50715 this.maskEl.bottom.enableDisplayMode("block");
50716 this.maskEl.right.enableDisplayMode("block");
50718 Roo.get(document.body).on('click', function(){
50722 Roo.get(document.body).on('touchstart', function(){
50726 this.isApplied = true
50729 mask : function(form, target)
50733 this.target = target;
50735 if(!this.form.errorMask || !target.el){
50739 var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.x-layout-active-content', 100, true) || Roo.get(document.body);
50741 var ot = this.target.el.calcOffsetsTo(scrollable);
50743 var scrollTo = ot[1] - this.form.maskOffset;
50745 scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
50747 scrollable.scrollTo('top', scrollTo);
50749 var el = this.target.wrap || this.target.el;
50751 var box = el.getBox();
50753 this.maskEl.top.setStyle('position', 'absolute');
50754 this.maskEl.top.setStyle('z-index', 10000);
50755 this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
50756 this.maskEl.top.setLeft(0);
50757 this.maskEl.top.setTop(0);
50758 this.maskEl.top.show();
50760 this.maskEl.left.setStyle('position', 'absolute');
50761 this.maskEl.left.setStyle('z-index', 10000);
50762 this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
50763 this.maskEl.left.setLeft(0);
50764 this.maskEl.left.setTop(box.y - this.padding);
50765 this.maskEl.left.show();
50767 this.maskEl.bottom.setStyle('position', 'absolute');
50768 this.maskEl.bottom.setStyle('z-index', 10000);
50769 this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
50770 this.maskEl.bottom.setLeft(0);
50771 this.maskEl.bottom.setTop(box.bottom + this.padding);
50772 this.maskEl.bottom.show();
50774 this.maskEl.right.setStyle('position', 'absolute');
50775 this.maskEl.right.setStyle('z-index', 10000);
50776 this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
50777 this.maskEl.right.setLeft(box.right + this.padding);
50778 this.maskEl.right.setTop(box.y - this.padding);
50779 this.maskEl.right.show();
50781 this.intervalID = window.setInterval(function() {
50782 Roo.form.BasicForm.popover.unmask();
50785 window.onwheel = function(){ return false;};
50787 (function(){ this.isMasked = true; }).defer(500, this);
50791 unmask : function()
50793 if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
50797 this.maskEl.top.setStyle('position', 'absolute');
50798 this.maskEl.top.setSize(0, 0).setXY([0, 0]);
50799 this.maskEl.top.hide();
50801 this.maskEl.left.setStyle('position', 'absolute');
50802 this.maskEl.left.setSize(0, 0).setXY([0, 0]);
50803 this.maskEl.left.hide();
50805 this.maskEl.bottom.setStyle('position', 'absolute');
50806 this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
50807 this.maskEl.bottom.hide();
50809 this.maskEl.right.setStyle('position', 'absolute');
50810 this.maskEl.right.setSize(0, 0).setXY([0, 0]);
50811 this.maskEl.right.hide();
50813 window.onwheel = function(){ return true;};
50815 if(this.intervalID){
50816 window.clearInterval(this.intervalID);
50817 this.intervalID = false;
50820 this.isMasked = false;
50828 * Ext JS Library 1.1.1
50829 * Copyright(c) 2006-2007, Ext JS, LLC.
50831 * Originally Released Under LGPL - original licence link has changed is not relivant.
50834 * <script type="text/javascript">
50838 * @class Roo.form.Form
50839 * @extends Roo.form.BasicForm
50840 * @children Roo.form.Column Roo.form.FieldSet Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
50841 * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
50843 * @param {Object} config Configuration options
50845 Roo.form.Form = function(config){
50847 if (config.items) {
50848 xitems = config.items;
50849 delete config.items;
50853 Roo.form.Form.superclass.constructor.call(this, null, config);
50854 this.url = this.url || this.action;
50856 this.root = new Roo.form.Layout(Roo.applyIf({
50860 this.active = this.root;
50862 * Array of all the buttons that have been added to this form via {@link addButton}
50866 this.allItems = [];
50869 * @event clientvalidation
50870 * If the monitorValid config option is true, this event fires repetitively to notify of valid state
50871 * @param {Form} this
50872 * @param {Boolean} valid true if the form has passed client-side validation
50874 clientvalidation: true,
50877 * Fires when the form is rendered
50878 * @param {Roo.form.Form} form
50883 if (this.progressUrl) {
50884 // push a hidden field onto the list of fields..
50888 name : 'UPLOAD_IDENTIFIER'
50893 Roo.each(xitems, this.addxtype, this);
50897 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
50899 * @cfg {Roo.Button} buttons[] buttons at bottom of form
50903 * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
50906 * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
50909 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
50911 buttonAlign:'center',
50914 * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
50919 * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
50920 * This property cascades to child containers if not set.
50925 * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
50926 * fires a looping event with that state. This is required to bind buttons to the valid
50927 * state using the config value formBind:true on the button.
50929 monitorValid : false,
50932 * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
50937 * @cfg {String} progressUrl - Url to return progress data
50940 progressUrl : false,
50942 * @cfg {boolean|FormData} formData - true to use new 'FormData' post, or set to a new FormData({dom form}) Object, if
50943 * sending a formdata with extra parameters - eg uploaded elements.
50949 * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
50950 * fields are added and the column is closed. If no fields are passed the column remains open
50951 * until end() is called.
50952 * @param {Object} config The config to pass to the column
50953 * @param {Field} field1 (optional)
50954 * @param {Field} field2 (optional)
50955 * @param {Field} etc (optional)
50956 * @return Column The column container object
50958 column : function(c){
50959 var col = new Roo.form.Column(c);
50961 if(arguments.length > 1){ // duplicate code required because of Opera
50962 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
50969 * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
50970 * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
50971 * until end() is called.
50972 * @param {Object} config The config to pass to the fieldset
50973 * @param {Field} field1 (optional)
50974 * @param {Field} field2 (optional)
50975 * @param {Field} etc (optional)
50976 * @return FieldSet The fieldset container object
50978 fieldset : function(c){
50979 var fs = new Roo.form.FieldSet(c);
50981 if(arguments.length > 1){ // duplicate code required because of Opera
50982 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
50989 * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
50990 * fields are added and the container is closed. If no fields are passed the container remains open
50991 * until end() is called.
50992 * @param {Object} config The config to pass to the Layout
50993 * @param {Field} field1 (optional)
50994 * @param {Field} field2 (optional)
50995 * @param {Field} etc (optional)
50996 * @return Layout The container object
50998 container : function(c){
50999 var l = new Roo.form.Layout(c);
51001 if(arguments.length > 1){ // duplicate code required because of Opera
51002 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
51009 * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
51010 * @param {Object} container A Roo.form.Layout or subclass of Layout
51011 * @return {Form} this
51013 start : function(c){
51014 // cascade label info
51015 Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
51016 this.active.stack.push(c);
51017 c.ownerCt = this.active;
51023 * Closes the current open container
51024 * @return {Form} this
51027 if(this.active == this.root){
51030 this.active = this.active.ownerCt;
51035 * Add Roo.form components to the current open container (e.g. column, fieldset, etc.). Fields added via this method
51036 * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
51037 * as the label of the field.
51038 * @param {Field} field1
51039 * @param {Field} field2 (optional)
51040 * @param {Field} etc. (optional)
51041 * @return {Form} this
51044 this.active.stack.push.apply(this.active.stack, arguments);
51045 this.allItems.push.apply(this.allItems,arguments);
51047 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
51048 if(a[i].isFormField){
51053 Roo.form.Form.superclass.add.apply(this, r);
51063 * Find any element that has been added to a form, using it's ID or name
51064 * This can include framesets, columns etc. along with regular fields..
51065 * @param {String} id - id or name to find.
51067 * @return {Element} e - or false if nothing found.
51069 findbyId : function(id)
51075 Roo.each(this.allItems, function(f){
51076 if (f.id == id || f.name == id ){
51087 * Render this form into the passed container. This should only be called once!
51088 * @param {String/HTMLElement/Element} container The element this component should be rendered into
51089 * @return {Form} this
51091 render : function(ct)
51097 var o = this.autoCreate || {
51099 method : this.method || 'POST',
51100 id : this.id || Roo.id()
51102 this.initEl(ct.createChild(o));
51104 this.root.render(this.el);
51108 this.items.each(function(f){
51109 f.render('x-form-el-'+f.id);
51112 if(this.buttons.length > 0){
51113 // tables are required to maintain order and for correct IE layout
51114 var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
51115 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
51116 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
51118 var tr = tb.getElementsByTagName('tr')[0];
51119 for(var i = 0, len = this.buttons.length; i < len; i++) {
51120 var b = this.buttons[i];
51121 var td = document.createElement('td');
51122 td.className = 'x-form-btn-td';
51123 b.render(tr.appendChild(td));
51126 if(this.monitorValid){ // initialize after render
51127 this.startMonitoring();
51129 this.fireEvent('rendered', this);
51134 * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
51135 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
51136 * object or a valid Roo.DomHelper element config
51137 * @param {Function} handler The function called when the button is clicked
51138 * @param {Object} scope (optional) The scope of the handler function
51139 * @return {Roo.Button}
51141 addButton : function(config, handler, scope){
51145 minWidth: this.minButtonWidth,
51148 if(typeof config == "string"){
51151 Roo.apply(bc, config);
51153 var btn = new Roo.Button(null, bc);
51154 this.buttons.push(btn);
51159 * Adds a series of form elements (using the xtype property as the factory method.
51160 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
51161 * @param {Object} config
51164 addxtype : function()
51166 var ar = Array.prototype.slice.call(arguments, 0);
51168 for(var i = 0; i < ar.length; i++) {
51170 continue; // skip -- if this happends something invalid got sent, we
51171 // should ignore it, as basically that interface element will not show up
51172 // and that should be pretty obvious!!
51175 if (Roo.form[ar[i].xtype]) {
51177 var fe = Roo.factory(ar[i], Roo.form);
51183 fe.store.form = this;
51188 this.allItems.push(fe);
51189 if (fe.items && fe.addxtype) {
51190 fe.addxtype.apply(fe, fe.items);
51200 // console.log('adding ' + ar[i].xtype);
51202 if (ar[i].xtype == 'Button') {
51203 //console.log('adding button');
51204 //console.log(ar[i]);
51205 this.addButton(ar[i]);
51206 this.allItems.push(fe);
51210 if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
51211 alert('end is not supported on xtype any more, use items');
51213 // //console.log('adding end');
51221 * Starts monitoring of the valid state of this form. Usually this is done by passing the config
51222 * option "monitorValid"
51224 startMonitoring : function(){
51227 Roo.TaskMgr.start({
51228 run : this.bindHandler,
51229 interval : this.monitorPoll || 200,
51236 * Stops monitoring of the valid state of this form
51238 stopMonitoring : function(){
51239 this.bound = false;
51243 bindHandler : function(){
51245 return false; // stops binding
51248 this.items.each(function(f){
51249 if(!f.isValid(true)){
51254 for(var i = 0, len = this.buttons.length; i < len; i++){
51255 var btn = this.buttons[i];
51256 if(btn.formBind === true && btn.disabled === valid){
51257 btn.setDisabled(!valid);
51260 this.fireEvent('clientvalidation', this, valid);
51274 Roo.Form = Roo.form.Form;
51277 * Ext JS Library 1.1.1
51278 * Copyright(c) 2006-2007, Ext JS, LLC.
51280 * Originally Released Under LGPL - original licence link has changed is not relivant.
51283 * <script type="text/javascript">
51286 // as we use this in bootstrap.
51287 Roo.namespace('Roo.form');
51289 * @class Roo.form.Action
51290 * Internal Class used to handle form actions
51292 * @param {Roo.form.BasicForm} el The form element or its id
51293 * @param {Object} config Configuration options
51298 // define the action interface
51299 Roo.form.Action = function(form, options){
51301 this.options = options || {};
51304 * Client Validation Failed
51307 Roo.form.Action.CLIENT_INVALID = 'client';
51309 * Server Validation Failed
51312 Roo.form.Action.SERVER_INVALID = 'server';
51314 * Connect to Server Failed
51317 Roo.form.Action.CONNECT_FAILURE = 'connect';
51319 * Reading Data from Server Failed
51322 Roo.form.Action.LOAD_FAILURE = 'load';
51324 Roo.form.Action.prototype = {
51326 failureType : undefined,
51327 response : undefined,
51328 result : undefined,
51330 // interface method
51331 run : function(options){
51335 // interface method
51336 success : function(response){
51340 // interface method
51341 handleResponse : function(response){
51345 // default connection failure
51346 failure : function(response){
51348 this.response = response;
51349 this.failureType = Roo.form.Action.CONNECT_FAILURE;
51350 this.form.afterAction(this, false);
51353 processResponse : function(response){
51354 this.response = response;
51355 if(!response.responseText){
51358 this.result = this.handleResponse(response);
51359 return this.result;
51362 // utility functions used internally
51363 getUrl : function(appendParams){
51364 var url = this.options.url || this.form.url || this.form.el.dom.action;
51366 var p = this.getParams();
51368 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
51374 getMethod : function(){
51375 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
51378 getParams : function(){
51379 var bp = this.form.baseParams;
51380 var p = this.options.params;
51382 if(typeof p == "object"){
51383 p = Roo.urlEncode(Roo.applyIf(p, bp));
51384 }else if(typeof p == 'string' && bp){
51385 p += '&' + Roo.urlEncode(bp);
51388 p = Roo.urlEncode(bp);
51393 createCallback : function(){
51395 success: this.success,
51396 failure: this.failure,
51398 timeout: (this.form.timeout*1000),
51399 upload: this.form.fileUpload ? this.success : undefined
51404 Roo.form.Action.Submit = function(form, options){
51405 Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
51408 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
51411 haveProgress : false,
51412 uploadComplete : false,
51414 // uploadProgress indicator.
51415 uploadProgress : function()
51417 if (!this.form.progressUrl) {
51421 if (!this.haveProgress) {
51422 Roo.MessageBox.progress("Uploading", "Uploading");
51424 if (this.uploadComplete) {
51425 Roo.MessageBox.hide();
51429 this.haveProgress = true;
51431 var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
51433 var c = new Roo.data.Connection();
51435 url : this.form.progressUrl,
51440 success : function(req){
51441 //console.log(data);
51445 rdata = Roo.decode(req.responseText)
51447 Roo.log("Invalid data from server..");
51451 if (!rdata || !rdata.success) {
51453 Roo.MessageBox.alert(Roo.encode(rdata));
51456 var data = rdata.data;
51458 if (this.uploadComplete) {
51459 Roo.MessageBox.hide();
51464 Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
51465 Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
51468 this.uploadProgress.defer(2000,this);
51471 failure: function(data) {
51472 Roo.log('progress url failed ');
51483 // run get Values on the form, so it syncs any secondary forms.
51484 this.form.getValues();
51486 var o = this.options;
51487 var method = this.getMethod();
51488 var isPost = method == 'POST';
51489 if(o.clientValidation === false || this.form.isValid()){
51491 if (this.form.progressUrl) {
51492 this.form.findField('UPLOAD_IDENTIFIER').setValue(
51493 (new Date() * 1) + '' + Math.random());
51498 Roo.Ajax.request(Roo.apply(this.createCallback(), {
51499 form:this.form.el.dom,
51500 url:this.getUrl(!isPost),
51502 params:isPost ? this.getParams() : null,
51503 isUpload: this.form.fileUpload,
51504 formData : this.form.formData
51507 this.uploadProgress();
51509 }else if (o.clientValidation !== false){ // client validation failed
51510 this.failureType = Roo.form.Action.CLIENT_INVALID;
51511 this.form.afterAction(this, false);
51515 success : function(response)
51517 this.uploadComplete= true;
51518 if (this.haveProgress) {
51519 Roo.MessageBox.hide();
51523 var result = this.processResponse(response);
51524 if(result === true || result.success){
51525 this.form.afterAction(this, true);
51529 this.form.markInvalid(result.errors);
51530 this.failureType = Roo.form.Action.SERVER_INVALID;
51532 this.form.afterAction(this, false);
51534 failure : function(response)
51536 this.uploadComplete= true;
51537 if (this.haveProgress) {
51538 Roo.MessageBox.hide();
51541 this.response = response;
51542 this.failureType = Roo.form.Action.CONNECT_FAILURE;
51543 this.form.afterAction(this, false);
51546 handleResponse : function(response){
51547 if(this.form.errorReader){
51548 var rs = this.form.errorReader.read(response);
51551 for(var i = 0, len = rs.records.length; i < len; i++) {
51552 var r = rs.records[i];
51553 errors[i] = r.data;
51556 if(errors.length < 1){
51560 success : rs.success,
51566 ret = Roo.decode(response.responseText);
51570 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
51580 Roo.form.Action.Load = function(form, options){
51581 Roo.form.Action.Load.superclass.constructor.call(this, form, options);
51582 this.reader = this.form.reader;
51585 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
51590 Roo.Ajax.request(Roo.apply(
51591 this.createCallback(), {
51592 method:this.getMethod(),
51593 url:this.getUrl(false),
51594 params:this.getParams()
51598 success : function(response){
51600 var result = this.processResponse(response);
51601 if(result === true || !result.success || !result.data){
51602 this.failureType = Roo.form.Action.LOAD_FAILURE;
51603 this.form.afterAction(this, false);
51606 this.form.clearInvalid();
51607 this.form.setValues(result.data);
51608 this.form.afterAction(this, true);
51611 handleResponse : function(response){
51612 if(this.form.reader){
51613 var rs = this.form.reader.read(response);
51614 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
51616 success : rs.success,
51620 return Roo.decode(response.responseText);
51624 Roo.form.Action.ACTION_TYPES = {
51625 'load' : Roo.form.Action.Load,
51626 'submit' : Roo.form.Action.Submit
51629 * Ext JS Library 1.1.1
51630 * Copyright(c) 2006-2007, Ext JS, LLC.
51632 * Originally Released Under LGPL - original licence link has changed is not relivant.
51635 * <script type="text/javascript">
51639 * @class Roo.form.Layout
51640 * @extends Roo.Component
51641 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
51642 * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
51644 * @param {Object} config Configuration options
51646 Roo.form.Layout = function(config){
51648 if (config.items) {
51649 xitems = config.items;
51650 delete config.items;
51652 Roo.form.Layout.superclass.constructor.call(this, config);
51654 Roo.each(xitems, this.addxtype, this);
51658 Roo.extend(Roo.form.Layout, Roo.Component, {
51660 * @cfg {String/Object} autoCreate
51661 * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
51664 * @cfg {String/Object/Function} style
51665 * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
51666 * a function which returns such a specification.
51669 * @cfg {String} labelAlign
51670 * Valid values are "left," "top" and "right" (defaults to "left")
51673 * @cfg {Number} labelWidth
51674 * Fixed width in pixels of all field labels (defaults to undefined)
51677 * @cfg {Boolean} clear
51678 * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
51682 * @cfg {String} labelSeparator
51683 * The separator to use after field labels (defaults to ':')
51685 labelSeparator : ':',
51687 * @cfg {Boolean} hideLabels
51688 * True to suppress the display of field labels in this layout (defaults to false)
51690 hideLabels : false,
51693 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
51698 onRender : function(ct, position){
51699 if(this.el){ // from markup
51700 this.el = Roo.get(this.el);
51701 }else { // generate
51702 var cfg = this.getAutoCreate();
51703 this.el = ct.createChild(cfg, position);
51706 this.el.applyStyles(this.style);
51708 if(this.labelAlign){
51709 this.el.addClass('x-form-label-'+this.labelAlign);
51711 if(this.hideLabels){
51712 this.labelStyle = "display:none";
51713 this.elementStyle = "padding-left:0;";
51715 if(typeof this.labelWidth == 'number'){
51716 this.labelStyle = "width:"+this.labelWidth+"px;";
51717 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
51719 if(this.labelAlign == 'top'){
51720 this.labelStyle = "width:auto;";
51721 this.elementStyle = "padding-left:0;";
51724 var stack = this.stack;
51725 var slen = stack.length;
51727 if(!this.fieldTpl){
51728 var t = new Roo.Template(
51729 '<div class="x-form-item {5}">',
51730 '<label for="{0}" style="{2}">{1}{4}</label>',
51731 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
51733 '</div><div class="x-form-clear-left"></div>'
51735 t.disableFormats = true;
51737 Roo.form.Layout.prototype.fieldTpl = t;
51739 for(var i = 0; i < slen; i++) {
51740 if(stack[i].isFormField){
51741 this.renderField(stack[i]);
51743 this.renderComponent(stack[i]);
51748 this.el.createChild({cls:'x-form-clear'});
51753 renderField : function(f){
51754 f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
51757 f.labelStyle||this.labelStyle||'', //2
51758 this.elementStyle||'', //3
51759 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
51760 f.itemCls||this.itemCls||'' //5
51761 ], true).getPrevSibling());
51765 renderComponent : function(c){
51766 c.render(c.isLayout ? this.el : this.el.createChild());
51769 * Adds a object form elements (using the xtype property as the factory method.)
51770 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column
51771 * @param {Object} config
51773 addxtype : function(o)
51775 // create the lement.
51776 o.form = this.form;
51777 var fe = Roo.factory(o, Roo.form);
51778 this.form.allItems.push(fe);
51779 this.stack.push(fe);
51781 if (fe.isFormField) {
51782 this.form.items.add(fe);
51790 * @class Roo.form.Column
51791 * @extends Roo.form.Layout
51792 * @children Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
51793 * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
51795 * @param {Object} config Configuration options
51797 Roo.form.Column = function(config){
51798 Roo.form.Column.superclass.constructor.call(this, config);
51801 Roo.extend(Roo.form.Column, Roo.form.Layout, {
51803 * @cfg {Number/String} width
51804 * The fixed width of the column in pixels or CSS value (defaults to "auto")
51807 * @cfg {String/Object} autoCreate
51808 * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
51812 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
51815 onRender : function(ct, position){
51816 Roo.form.Column.superclass.onRender.call(this, ct, position);
51818 this.el.setWidth(this.width);
51825 * @class Roo.form.Row
51826 * @extends Roo.form.Layout
51827 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
51828 * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
51830 * @param {Object} config Configuration options
51834 Roo.form.Row = function(config){
51835 Roo.form.Row.superclass.constructor.call(this, config);
51838 Roo.extend(Roo.form.Row, Roo.form.Layout, {
51840 * @cfg {Number/String} width
51841 * The fixed width of the column in pixels or CSS value (defaults to "auto")
51844 * @cfg {Number/String} height
51845 * The fixed height of the column in pixels or CSS value (defaults to "auto")
51847 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
51851 onRender : function(ct, position){
51852 //console.log('row render');
51854 var t = new Roo.Template(
51855 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
51856 '<label for="{0}" style="{2}">{1}{4}</label>',
51857 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
51861 t.disableFormats = true;
51863 Roo.form.Layout.prototype.rowTpl = t;
51865 this.fieldTpl = this.rowTpl;
51867 //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
51868 var labelWidth = 100;
51870 if ((this.labelAlign != 'top')) {
51871 if (typeof this.labelWidth == 'number') {
51872 labelWidth = this.labelWidth
51874 this.padWidth = 20 + labelWidth;
51878 Roo.form.Column.superclass.onRender.call(this, ct, position);
51880 this.el.setWidth(this.width);
51883 this.el.setHeight(this.height);
51888 renderField : function(f){
51889 f.fieldEl = this.fieldTpl.append(this.el, [
51890 f.id, f.fieldLabel,
51891 f.labelStyle||this.labelStyle||'',
51892 this.elementStyle||'',
51893 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
51894 f.itemCls||this.itemCls||'',
51895 f.width ? f.width + this.padWidth : 160 + this.padWidth
51902 * @class Roo.form.FieldSet
51903 * @extends Roo.form.Layout
51904 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
51905 * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
51907 * @param {Object} config Configuration options
51909 Roo.form.FieldSet = function(config){
51910 Roo.form.FieldSet.superclass.constructor.call(this, config);
51913 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
51915 * @cfg {String} legend
51916 * The text to display as the legend for the FieldSet (defaults to '')
51919 * @cfg {String/Object} autoCreate
51920 * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
51924 defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
51927 onRender : function(ct, position){
51928 Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
51930 this.setLegend(this.legend);
51935 setLegend : function(text){
51937 this.el.child('legend').update(text);
51942 * Ext JS Library 1.1.1
51943 * Copyright(c) 2006-2007, Ext JS, LLC.
51945 * Originally Released Under LGPL - original licence link has changed is not relivant.
51948 * <script type="text/javascript">
51951 * @class Roo.form.VTypes
51952 * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
51955 Roo.form.VTypes = function(){
51956 // closure these in so they are only created once.
51957 var alpha = /^[a-zA-Z_]+$/;
51958 var alphanum = /^[a-zA-Z0-9_]+$/;
51959 var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
51960 var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
51962 // All these messages and functions are configurable
51965 * The function used to validate email addresses
51966 * @param {String} value The email address
51968 'email' : function(v){
51969 return email.test(v);
51972 * The error text to display when the email validation function returns false
51975 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
51977 * The keystroke filter mask to be applied on email input
51980 'emailMask' : /[a-z0-9_\.\-@]/i,
51983 * The function used to validate URLs
51984 * @param {String} value The URL
51986 'url' : function(v){
51987 return url.test(v);
51990 * The error text to display when the url validation function returns false
51993 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
51996 * The function used to validate alpha values
51997 * @param {String} value The value
51999 'alpha' : function(v){
52000 return alpha.test(v);
52003 * The error text to display when the alpha validation function returns false
52006 'alphaText' : 'This field should only contain letters and _',
52008 * The keystroke filter mask to be applied on alpha input
52011 'alphaMask' : /[a-z_]/i,
52014 * The function used to validate alphanumeric values
52015 * @param {String} value The value
52017 'alphanum' : function(v){
52018 return alphanum.test(v);
52021 * The error text to display when the alphanumeric validation function returns false
52024 'alphanumText' : 'This field should only contain letters, numbers and _',
52026 * The keystroke filter mask to be applied on alphanumeric input
52029 'alphanumMask' : /[a-z0-9_]/i
52031 }();//<script type="text/javascript">
52034 * @class Roo.form.FCKeditor
52035 * @extends Roo.form.TextArea
52036 * Wrapper around the FCKEditor http://www.fckeditor.net
52038 * Creates a new FCKeditor
52039 * @param {Object} config Configuration options
52041 Roo.form.FCKeditor = function(config){
52042 Roo.form.FCKeditor.superclass.constructor.call(this, config);
52045 * @event editorinit
52046 * Fired when the editor is initialized - you can add extra handlers here..
52047 * @param {FCKeditor} this
52048 * @param {Object} the FCK object.
52055 Roo.form.FCKeditor.editors = { };
52056 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
52058 //defaultAutoCreate : {
52059 // tag : "textarea",style : "width:100px;height:60px;" ,autocomplete : "off"
52063 * @cfg {Object} fck options - see fck manual for details.
52068 * @cfg {Object} fck toolbar set (Basic or Default)
52070 toolbarSet : 'Basic',
52072 * @cfg {Object} fck BasePath
52074 basePath : '/fckeditor/',
52082 onRender : function(ct, position)
52085 this.defaultAutoCreate = {
52087 style:"width:300px;height:60px;",
52088 autocomplete: "new-password"
52091 Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
52094 this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
52095 if(this.preventScrollbars){
52096 this.el.setStyle("overflow", "hidden");
52098 this.el.setHeight(this.growMin);
52101 //console.log('onrender' + this.getId() );
52102 Roo.form.FCKeditor.editors[this.getId()] = this;
52105 this.replaceTextarea() ;
52109 getEditor : function() {
52110 return this.fckEditor;
52113 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
52114 * @param {Mixed} value The value to set
52118 setValue : function(value)
52120 //console.log('setValue: ' + value);
52122 if(typeof(value) == 'undefined') { // not sure why this is happending...
52125 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
52127 //if(!this.el || !this.getEditor()) {
52128 // this.value = value;
52129 //this.setValue.defer(100,this,[value]);
52133 if(!this.getEditor()) {
52137 this.getEditor().SetData(value);
52144 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
52145 * @return {Mixed} value The field value
52147 getValue : function()
52150 if (this.frame && this.frame.dom.style.display == 'none') {
52151 return Roo.form.FCKeditor.superclass.getValue.call(this);
52154 if(!this.el || !this.getEditor()) {
52156 // this.getValue.defer(100,this);
52161 var value=this.getEditor().GetData();
52162 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
52163 return Roo.form.FCKeditor.superclass.getValue.call(this);
52169 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
52170 * @return {Mixed} value The field value
52172 getRawValue : function()
52174 if (this.frame && this.frame.dom.style.display == 'none') {
52175 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
52178 if(!this.el || !this.getEditor()) {
52179 //this.getRawValue.defer(100,this);
52186 var value=this.getEditor().GetData();
52187 Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
52188 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
52192 setSize : function(w,h) {
52196 //if (this.frame && this.frame.dom.style.display == 'none') {
52197 // Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
52200 //if(!this.el || !this.getEditor()) {
52201 // this.setSize.defer(100,this, [w,h]);
52207 Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
52209 this.frame.dom.setAttribute('width', w);
52210 this.frame.dom.setAttribute('height', h);
52211 this.frame.setSize(w,h);
52215 toggleSourceEdit : function(value) {
52219 this.el.dom.style.display = value ? '' : 'none';
52220 this.frame.dom.style.display = value ? 'none' : '';
52225 focus: function(tag)
52227 if (this.frame.dom.style.display == 'none') {
52228 return Roo.form.FCKeditor.superclass.focus.call(this);
52230 if(!this.el || !this.getEditor()) {
52231 this.focus.defer(100,this, [tag]);
52238 var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
52239 this.getEditor().Focus();
52241 if (!this.getEditor().Selection.GetSelection()) {
52242 this.focus.defer(100,this, [tag]);
52247 var r = this.getEditor().EditorDocument.createRange();
52248 r.setStart(tgs[0],0);
52249 r.setEnd(tgs[0],0);
52250 this.getEditor().Selection.GetSelection().removeAllRanges();
52251 this.getEditor().Selection.GetSelection().addRange(r);
52252 this.getEditor().Focus();
52259 replaceTextarea : function()
52261 if ( document.getElementById( this.getId() + '___Frame' ) ) {
52264 //if ( !this.checkBrowser || this._isCompatibleBrowser() )
52266 // We must check the elements firstly using the Id and then the name.
52267 var oTextarea = document.getElementById( this.getId() );
52269 var colElementsByName = document.getElementsByName( this.getId() ) ;
52271 oTextarea.style.display = 'none' ;
52273 if ( oTextarea.tabIndex ) {
52274 this.TabIndex = oTextarea.tabIndex ;
52277 this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
52278 this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
52279 this.frame = Roo.get(this.getId() + '___Frame')
52282 _getConfigHtml : function()
52286 for ( var o in this.fckconfig ) {
52287 sConfig += sConfig.length > 0 ? '&' : '';
52288 sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
52291 return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
52295 _getIFrameHtml : function()
52297 var sFile = 'fckeditor.html' ;
52298 /* no idea what this is about..
52301 if ( (/fcksource=true/i).test( window.top.location.search ) )
52302 sFile = 'fckeditor.original.html' ;
52307 var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
52308 sLink += this.toolbarSet ? ( '&Toolbar=' + this.toolbarSet) : '';
52311 var html = '<iframe id="' + this.getId() +
52312 '___Frame" src="' + sLink +
52313 '" width="' + this.width +
52314 '" height="' + this.height + '"' +
52315 (this.tabIndex ? ' tabindex="' + this.tabIndex + '"' :'' ) +
52316 ' frameborder="0" scrolling="no"></iframe>' ;
52321 _insertHtmlBefore : function( html, element )
52323 if ( element.insertAdjacentHTML ) {
52325 element.insertAdjacentHTML( 'beforeBegin', html ) ;
52327 var oRange = document.createRange() ;
52328 oRange.setStartBefore( element ) ;
52329 var oFragment = oRange.createContextualFragment( html );
52330 element.parentNode.insertBefore( oFragment, element ) ;
52343 //Roo.reg('fckeditor', Roo.form.FCKeditor);
52345 function FCKeditor_OnComplete(editorInstance){
52346 var f = Roo.form.FCKeditor.editors[editorInstance.Name];
52347 f.fckEditor = editorInstance;
52348 //console.log("loaded");
52349 f.fireEvent('editorinit', f, editorInstance);
52369 //<script type="text/javascript">
52371 * @class Roo.form.GridField
52372 * @extends Roo.form.Field
52373 * Embed a grid (or editable grid into a form)
52376 * This embeds a grid in a form, the value of the field should be the json encoded array of rows
52378 * xgrid.store = Roo.data.Store
52379 * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
52380 * xgrid.store.reader = Roo.data.JsonReader
52384 * Creates a new GridField
52385 * @param {Object} config Configuration options
52387 Roo.form.GridField = function(config){
52388 Roo.form.GridField.superclass.constructor.call(this, config);
52392 Roo.extend(Roo.form.GridField, Roo.form.Field, {
52394 * @cfg {Number} width - used to restrict width of grid..
52398 * @cfg {Number} height - used to restrict height of grid..
52402 * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
52408 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
52409 * {tag: "input", type: "checkbox", autocomplete: "off"})
52411 // defaultAutoCreate : { tag: 'div' },
52412 defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
52414 * @cfg {String} addTitle Text to include for adding a title.
52418 onResize : function(){
52419 Roo.form.Field.superclass.onResize.apply(this, arguments);
52422 initEvents : function(){
52423 // Roo.form.Checkbox.superclass.initEvents.call(this);
52424 // has no events...
52429 getResizeEl : function(){
52433 getPositionEl : function(){
52438 onRender : function(ct, position){
52440 this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
52441 var style = this.style;
52444 Roo.form.GridField.superclass.onRender.call(this, ct, position);
52445 this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
52446 this.viewEl = this.wrap.createChild({ tag: 'div' });
52448 this.viewEl.applyStyles(style);
52451 this.viewEl.setWidth(this.width);
52454 this.viewEl.setHeight(this.height);
52456 //if(this.inputValue !== undefined){
52457 //this.setValue(this.value);
52460 this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
52463 this.grid.render();
52464 this.grid.getDataSource().on('remove', this.refreshValue, this);
52465 this.grid.getDataSource().on('update', this.refreshValue, this);
52466 this.grid.on('afteredit', this.refreshValue, this);
52472 * Sets the value of the item.
52473 * @param {String} either an object or a string..
52475 setValue : function(v){
52477 v = v || []; // empty set..
52478 // this does not seem smart - it really only affects memoryproxy grids..
52479 if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
52480 var ds = this.grid.getDataSource();
52481 // assumes a json reader..
52483 data[ds.reader.meta.root ] = typeof(v) == 'string' ? Roo.decode(v) : v;
52484 ds.loadData( data);
52486 // clear selection so it does not get stale.
52487 if (this.grid.sm) {
52488 this.grid.sm.clearSelections();
52491 Roo.form.GridField.superclass.setValue.call(this, v);
52492 this.refreshValue();
52493 // should load data in the grid really....
52497 refreshValue: function() {
52499 this.grid.getDataSource().each(function(r) {
52502 this.el.dom.value = Roo.encode(val);
52510 * Ext JS Library 1.1.1
52511 * Copyright(c) 2006-2007, Ext JS, LLC.
52513 * Originally Released Under LGPL - original licence link has changed is not relivant.
52516 * <script type="text/javascript">
52519 * @class Roo.form.DisplayField
52520 * @extends Roo.form.Field
52521 * A generic Field to display non-editable data.
52522 * @cfg {Boolean} closable (true|false) default false
52524 * Creates a new Display Field item.
52525 * @param {Object} config Configuration options
52527 Roo.form.DisplayField = function(config){
52528 Roo.form.DisplayField.superclass.constructor.call(this, config);
52533 * Fires after the click the close btn
52534 * @param {Roo.form.DisplayField} this
52540 Roo.extend(Roo.form.DisplayField, Roo.form.TextField, {
52541 inputType: 'hidden',
52547 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
52549 focusClass : undefined,
52551 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
52553 fieldClass: 'x-form-field',
52556 * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
52558 valueRenderer: undefined,
52562 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
52563 * {tag: "input", type: "checkbox", autocomplete: "off"})
52566 // defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
52570 onResize : function(){
52571 Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
52575 initEvents : function(){
52576 // Roo.form.Checkbox.superclass.initEvents.call(this);
52577 // has no events...
52580 this.closeEl.on('click', this.onClose, this);
52586 getResizeEl : function(){
52590 getPositionEl : function(){
52595 onRender : function(ct, position){
52597 Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
52598 //if(this.inputValue !== undefined){
52599 this.wrap = this.el.wrap();
52601 this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
52604 this.closeEl = this.wrap.createChild({ tag: 'div', cls: 'x-dlg-close'});
52607 if (this.bodyStyle) {
52608 this.viewEl.applyStyles(this.bodyStyle);
52610 //this.viewEl.setStyle('padding', '2px');
52612 this.setValue(this.value);
52617 initValue : Roo.emptyFn,
52622 onClick : function(){
52627 * Sets the checked state of the checkbox.
52628 * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
52630 setValue : function(v){
52632 var html = this.valueRenderer ? this.valueRenderer(v) : String.format('{0}', v);
52633 // this might be called before we have a dom element..
52634 if (!this.viewEl) {
52637 this.viewEl.dom.innerHTML = html;
52638 Roo.form.DisplayField.superclass.setValue.call(this, v);
52642 onClose : function(e)
52644 e.preventDefault();
52646 this.fireEvent('close', this);
52655 * @class Roo.form.DayPicker
52656 * @extends Roo.form.Field
52657 * A Day picker show [M] [T] [W] ....
52659 * Creates a new Day Picker
52660 * @param {Object} config Configuration options
52662 Roo.form.DayPicker= function(config){
52663 Roo.form.DayPicker.superclass.constructor.call(this, config);
52667 Roo.extend(Roo.form.DayPicker, Roo.form.Field, {
52669 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
52671 focusClass : undefined,
52673 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
52675 fieldClass: "x-form-field",
52678 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
52679 * {tag: "input", type: "checkbox", autocomplete: "off"})
52681 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
52684 actionMode : 'viewEl',
52688 inputType : 'hidden',
52691 inputElement: false, // real input element?
52692 basedOn: false, // ????
52694 isFormField: true, // not sure where this is needed!!!!
52696 onResize : function(){
52697 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
52698 if(!this.boxLabel){
52699 this.el.alignTo(this.wrap, 'c-c');
52703 initEvents : function(){
52704 Roo.form.Checkbox.superclass.initEvents.call(this);
52705 this.el.on("click", this.onClick, this);
52706 this.el.on("change", this.onClick, this);
52710 getResizeEl : function(){
52714 getPositionEl : function(){
52720 onRender : function(ct, position){
52721 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
52723 this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
52725 var r1 = '<table><tr>';
52726 var r2 = '<tr class="x-form-daypick-icons">';
52727 for (var i=0; i < 7; i++) {
52728 r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
52729 r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL +'"></td>';
52732 var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
52733 viewEl.select('img').on('click', this.onClick, this);
52734 this.viewEl = viewEl;
52737 // this will not work on Chrome!!!
52738 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
52739 this.el.on('propertychange', this.setFromHidden, this); //ie
52747 initValue : Roo.emptyFn,
52750 * Returns the checked state of the checkbox.
52751 * @return {Boolean} True if checked, else false
52753 getValue : function(){
52754 return this.el.dom.value;
52759 onClick : function(e){
52760 //this.setChecked(!this.checked);
52761 Roo.get(e.target).toggleClass('x-menu-item-checked');
52762 this.refreshValue();
52763 //if(this.el.dom.checked != this.checked){
52764 // this.setValue(this.el.dom.checked);
52769 refreshValue : function()
52772 this.viewEl.select('img',true).each(function(e,i,n) {
52773 val += e.is(".x-menu-item-checked") ? String(n) : '';
52775 this.setValue(val, true);
52779 * Sets the checked state of the checkbox.
52780 * On is always based on a string comparison between inputValue and the param.
52781 * @param {Boolean/String} value - the value to set
52782 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
52784 setValue : function(v,suppressEvent){
52785 if (!this.el.dom) {
52788 var old = this.el.dom.value ;
52789 this.el.dom.value = v;
52790 if (suppressEvent) {
52794 // update display..
52795 this.viewEl.select('img',true).each(function(e,i,n) {
52797 var on = e.is(".x-menu-item-checked");
52798 var newv = v.indexOf(String(n)) > -1;
52800 e.toggleClass('x-menu-item-checked');
52806 this.fireEvent('change', this, v, old);
52811 // handle setting of hidden value by some other method!!?!?
52812 setFromHidden: function()
52817 //console.log("SET FROM HIDDEN");
52818 //alert('setFrom hidden');
52819 this.setValue(this.el.dom.value);
52822 onDestroy : function()
52825 Roo.get(this.viewEl).remove();
52828 Roo.form.DayPicker.superclass.onDestroy.call(this);
52832 * RooJS Library 1.1.1
52833 * Copyright(c) 2008-2011 Alan Knowles
52840 * @class Roo.form.ComboCheck
52841 * @extends Roo.form.ComboBox
52842 * A combobox for multiple select items.
52844 * FIXME - could do with a reset button..
52847 * Create a new ComboCheck
52848 * @param {Object} config Configuration options
52850 Roo.form.ComboCheck = function(config){
52851 Roo.form.ComboCheck.superclass.constructor.call(this, config);
52852 // should verify some data...
52854 // hiddenName = required..
52855 // displayField = required
52856 // valudField == required
52857 var req= [ 'hiddenName', 'displayField', 'valueField' ];
52859 Roo.each(req, function(e) {
52860 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
52861 throw "Roo.form.ComboCheck : missing value for: " + e;
52868 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
52873 selectedClass: 'x-menu-item-checked',
52876 onRender : function(ct, position){
52882 var cls = 'x-combo-list';
52885 this.tpl = new Roo.Template({
52886 html : '<div class="'+cls+'-item x-menu-check-item">' +
52887 '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' +
52888 '<span>{' + this.displayField + '}</span>' +
52895 Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
52896 this.view.singleSelect = false;
52897 this.view.multiSelect = true;
52898 this.view.toggleSelect = true;
52899 this.pageTb.add(new Roo.Toolbar.Fill(), {
52902 handler: function()
52909 onViewOver : function(e, t){
52915 onViewClick : function(doFocus,index){
52919 select: function () {
52920 //Roo.log("SELECT CALLED");
52923 selectByValue : function(xv, scrollIntoView){
52924 var ar = this.getValueArray();
52927 Roo.each(ar, function(v) {
52928 if(v === undefined || v === null){
52931 var r = this.findRecord(this.valueField, v);
52933 sels.push(this.store.indexOf(r))
52937 this.view.select(sels);
52943 onSelect : function(record, index){
52944 // Roo.log("onselect Called");
52945 // this is only called by the clear button now..
52946 this.view.clearSelections();
52947 this.setValue('[]');
52948 if (this.value != this.valueBefore) {
52949 this.fireEvent('change', this, this.value, this.valueBefore);
52950 this.valueBefore = this.value;
52953 getValueArray : function()
52958 //Roo.log(this.value);
52959 if (typeof(this.value) == 'undefined') {
52962 var ar = Roo.decode(this.value);
52963 return ar instanceof Array ? ar : []; //?? valid?
52966 Roo.log(e + "\nRoo.form.ComboCheck:getValueArray invalid data:" + this.getValue());
52971 expand : function ()
52974 Roo.form.ComboCheck.superclass.expand.call(this);
52975 this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
52976 //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
52981 collapse : function(){
52982 Roo.form.ComboCheck.superclass.collapse.call(this);
52983 var sl = this.view.getSelectedIndexes();
52984 var st = this.store;
52988 Roo.each(sl, function(i) {
52990 nv.push(r.get(this.valueField));
52992 this.setValue(Roo.encode(nv));
52993 if (this.value != this.valueBefore) {
52995 this.fireEvent('change', this, this.value, this.valueBefore);
52996 this.valueBefore = this.value;
53001 setValue : function(v){
53005 var vals = this.getValueArray();
53007 Roo.each(vals, function(k) {
53008 var r = this.findRecord(this.valueField, k);
53010 tv.push(r.data[this.displayField]);
53011 }else if(this.valueNotFoundText !== undefined){
53012 tv.push( this.valueNotFoundText );
53017 Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
53018 this.hiddenField.value = v;
53024 * Ext JS Library 1.1.1
53025 * Copyright(c) 2006-2007, Ext JS, LLC.
53027 * Originally Released Under LGPL - original licence link has changed is not relivant.
53030 * <script type="text/javascript">
53034 * @class Roo.form.Signature
53035 * @extends Roo.form.Field
53039 * @param {Object} config Configuration options
53042 Roo.form.Signature = function(config){
53043 Roo.form.Signature.superclass.constructor.call(this, config);
53045 this.addEvents({// not in used??
53048 * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
53049 * @param {Roo.form.Signature} combo This combo box
53054 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
53055 * @param {Roo.form.ComboBox} combo This combo box
53056 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
53062 Roo.extend(Roo.form.Signature, Roo.form.Field, {
53064 * @cfg {Object} labels Label to use when rendering a form.
53068 * confirm : "Confirm"
53073 confirm : "Confirm"
53076 * @cfg {Number} width The signature panel width (defaults to 300)
53080 * @cfg {Number} height The signature panel height (defaults to 100)
53084 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
53086 allowBlank : false,
53089 // {Object} signPanel The signature SVG panel element (defaults to {})
53091 // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
53092 isMouseDown : false,
53093 // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
53094 isConfirmed : false,
53095 // {String} signatureTmp SVG mapping string (defaults to empty string)
53099 defaultAutoCreate : { // modified by initCompnoent..
53105 onRender : function(ct, position){
53107 Roo.form.Signature.superclass.onRender.call(this, ct, position);
53109 this.wrap = this.el.wrap({
53110 cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
53113 this.createToolbar(this);
53114 this.signPanel = this.wrap.createChild({
53116 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
53120 this.svgID = Roo.id();
53121 this.svgEl = this.signPanel.createChild({
53122 xmlns : 'http://www.w3.org/2000/svg',
53124 id : this.svgID + "-svg",
53126 height: this.height,
53127 viewBox: '0 0 '+this.width+' '+this.height,
53131 id: this.svgID + "-svg-r",
53133 height: this.height,
53138 id: this.svgID + "-svg-l",
53140 y1: (this.height*0.8), // start set the line in 80% of height
53141 x2: this.width, // end
53142 y2: (this.height*0.8), // end set the line in 80% of height
53144 'stroke-width': "1",
53145 'stroke-dasharray': "3",
53146 'shape-rendering': "crispEdges",
53147 'pointer-events': "none"
53151 id: this.svgID + "-svg-p",
53153 'stroke-width': "3",
53155 'pointer-events': 'none'
53160 this.svgBox = this.svgEl.dom.getScreenCTM();
53162 createSVG : function(){
53163 var svg = this.signPanel;
53164 var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
53167 r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
53168 r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
53169 r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
53170 r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
53171 r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
53172 r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
53173 r.addEventListener('touchend', function(e) { return t.up(e); }, false);
53176 isTouchEvent : function(e){
53177 return e.type.match(/^touch/);
53179 getCoords : function (e) {
53180 var pt = this.svgEl.dom.createSVGPoint();
53183 if (this.isTouchEvent(e)) {
53184 pt.x = e.targetTouches[0].clientX;
53185 pt.y = e.targetTouches[0].clientY;
53187 var a = this.svgEl.dom.getScreenCTM();
53188 var b = a.inverse();
53189 var mx = pt.matrixTransform(b);
53190 return mx.x + ',' + mx.y;
53192 //mouse event headler
53193 down : function (e) {
53194 this.signatureTmp += 'M' + this.getCoords(e) + ' ';
53195 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
53197 this.isMouseDown = true;
53199 e.preventDefault();
53201 move : function (e) {
53202 if (this.isMouseDown) {
53203 this.signatureTmp += 'L' + this.getCoords(e) + ' ';
53204 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
53207 e.preventDefault();
53209 up : function (e) {
53210 this.isMouseDown = false;
53211 var sp = this.signatureTmp.split(' ');
53214 if(!sp[sp.length-2].match(/^L/)){
53218 this.signatureTmp = sp.join(" ");
53221 if(this.getValue() != this.signatureTmp){
53222 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
53223 this.isConfirmed = false;
53225 e.preventDefault();
53229 * Protected method that will not generally be called directly. It
53230 * is called when the editor creates its toolbar. Override this method if you need to
53231 * add custom toolbar buttons.
53232 * @param {HtmlEditor} editor
53234 createToolbar : function(editor){
53235 function btn(id, toggle, handler){
53236 var xid = fid + '-'+ id ;
53240 cls : 'x-btn-icon x-edit-'+id,
53241 enableToggle:toggle !== false,
53242 scope: editor, // was editor...
53243 handler:handler||editor.relayBtnCmd,
53244 clickEvent:'mousedown',
53245 tooltip: etb.buttonTips[id] || undefined, ///tips ???
53251 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
53255 cls : ' x-signature-btn x-signature-'+id,
53256 scope: editor, // was editor...
53257 handler: this.reset,
53258 clickEvent:'mousedown',
53259 text: this.labels.clear
53266 cls : ' x-signature-btn x-signature-'+id,
53267 scope: editor, // was editor...
53268 handler: this.confirmHandler,
53269 clickEvent:'mousedown',
53270 text: this.labels.confirm
53277 * when user is clicked confirm then show this image.....
53279 * @return {String} Image Data URI
53281 getImageDataURI : function(){
53282 var svg = this.svgEl.dom.parentNode.innerHTML;
53283 var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
53288 * @return {Boolean} this.isConfirmed
53290 getConfirmed : function(){
53291 return this.isConfirmed;
53295 * @return {Number} this.width
53297 getWidth : function(){
53302 * @return {Number} this.height
53304 getHeight : function(){
53305 return this.height;
53308 getSignature : function(){
53309 return this.signatureTmp;
53312 reset : function(){
53313 this.signatureTmp = '';
53314 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
53315 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
53316 this.isConfirmed = false;
53317 Roo.form.Signature.superclass.reset.call(this);
53319 setSignature : function(s){
53320 this.signatureTmp = s;
53321 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
53322 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
53324 this.isConfirmed = false;
53325 Roo.form.Signature.superclass.reset.call(this);
53328 // Roo.log(this.signPanel.dom.contentWindow.up())
53331 setConfirmed : function(){
53335 // Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
53338 confirmHandler : function(){
53339 if(!this.getSignature()){
53343 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
53344 this.setValue(this.getSignature());
53345 this.isConfirmed = true;
53347 this.fireEvent('confirm', this);
53350 // Subclasses should provide the validation implementation by overriding this
53351 validateValue : function(value){
53352 if(this.allowBlank){
53356 if(this.isConfirmed){
53363 * Ext JS Library 1.1.1
53364 * Copyright(c) 2006-2007, Ext JS, LLC.
53366 * Originally Released Under LGPL - original licence link has changed is not relivant.
53369 * <script type="text/javascript">
53374 * @class Roo.form.ComboBox
53375 * @extends Roo.form.TriggerField
53376 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
53378 * Create a new ComboBox.
53379 * @param {Object} config Configuration options
53381 Roo.form.Select = function(config){
53382 Roo.form.Select.superclass.constructor.call(this, config);
53386 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
53388 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
53391 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
53392 * rendering into an Roo.Editor, defaults to false)
53395 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
53396 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
53399 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
53402 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
53403 * the dropdown list (defaults to undefined, with no header element)
53407 * @cfg {String/Roo.Template} tpl The template to use to render the output
53411 defaultAutoCreate : {tag: "select" },
53413 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
53415 listWidth: undefined,
53417 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
53418 * mode = 'remote' or 'text' if mode = 'local')
53420 displayField: undefined,
53422 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
53423 * mode = 'remote' or 'value' if mode = 'local').
53424 * Note: use of a valueField requires the user make a selection
53425 * in order for a value to be mapped.
53427 valueField: undefined,
53431 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
53432 * field's data value (defaults to the underlying DOM element's name)
53434 hiddenName: undefined,
53436 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
53440 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
53442 selectedClass: 'x-combo-selected',
53444 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
53445 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
53446 * which displays a downward arrow icon).
53448 triggerClass : 'x-form-arrow-trigger',
53450 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
53454 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
53455 * anchor positions (defaults to 'tl-bl')
53457 listAlign: 'tl-bl?',
53459 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
53463 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
53464 * query specified by the allQuery config option (defaults to 'query')
53466 triggerAction: 'query',
53468 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
53469 * (defaults to 4, does not apply if editable = false)
53473 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
53474 * delay (typeAheadDelay) if it matches a known value (defaults to false)
53478 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
53479 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
53483 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
53484 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
53488 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
53489 * when editable = true (defaults to false)
53491 selectOnFocus:false,
53493 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
53495 queryParam: 'query',
53497 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
53498 * when mode = 'remote' (defaults to 'Loading...')
53500 loadingText: 'Loading...',
53502 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
53506 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
53510 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
53511 * traditional select (defaults to true)
53515 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
53519 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
53523 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
53524 * listWidth has a higher value)
53528 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
53529 * allow the user to set arbitrary text into the field (defaults to false)
53531 forceSelection:false,
53533 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
53534 * if typeAhead = true (defaults to 250)
53536 typeAheadDelay : 250,
53538 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
53539 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
53541 valueNotFoundText : undefined,
53544 * @cfg {String} defaultValue The value displayed after loading the store.
53549 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
53551 blockFocus : false,
53554 * @cfg {Boolean} disableClear Disable showing of clear button.
53556 disableClear : false,
53558 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
53560 alwaysQuery : false,
53566 // element that contains real text value.. (when hidden is used..)
53569 onRender : function(ct, position){
53570 Roo.form.Field.prototype.onRender.call(this, ct, position);
53573 this.store.on('beforeload', this.onBeforeLoad, this);
53574 this.store.on('load', this.onLoad, this);
53575 this.store.on('loadexception', this.onLoadException, this);
53576 this.store.load({});
53584 initEvents : function(){
53585 //Roo.form.ComboBox.superclass.initEvents.call(this);
53589 onDestroy : function(){
53592 this.store.un('beforeload', this.onBeforeLoad, this);
53593 this.store.un('load', this.onLoad, this);
53594 this.store.un('loadexception', this.onLoadException, this);
53596 //Roo.form.ComboBox.superclass.onDestroy.call(this);
53600 fireKey : function(e){
53601 if(e.isNavKeyPress() && !this.list.isVisible()){
53602 this.fireEvent("specialkey", this, e);
53607 onResize: function(w, h){
53615 * Allow or prevent the user from directly editing the field text. If false is passed,
53616 * the user will only be able to select from the items defined in the dropdown list. This method
53617 * is the runtime equivalent of setting the 'editable' config option at config time.
53618 * @param {Boolean} value True to allow the user to directly edit the field text
53620 setEditable : function(value){
53625 onBeforeLoad : function(){
53627 Roo.log("Select before load");
53630 this.innerList.update(this.loadingText ?
53631 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
53632 //this.restrictHeight();
53633 this.selectedIndex = -1;
53637 onLoad : function(){
53640 var dom = this.el.dom;
53641 dom.innerHTML = '';
53642 var od = dom.ownerDocument;
53644 if (this.emptyText) {
53645 var op = od.createElement('option');
53646 op.setAttribute('value', '');
53647 op.innerHTML = String.format('{0}', this.emptyText);
53648 dom.appendChild(op);
53650 if(this.store.getCount() > 0){
53652 var vf = this.valueField;
53653 var df = this.displayField;
53654 this.store.data.each(function(r) {
53655 // which colmsn to use... testing - cdoe / title..
53656 var op = od.createElement('option');
53657 op.setAttribute('value', r.data[vf]);
53658 op.innerHTML = String.format('{0}', r.data[df]);
53659 dom.appendChild(op);
53661 if (typeof(this.defaultValue != 'undefined')) {
53662 this.setValue(this.defaultValue);
53667 //this.onEmptyResults();
53672 onLoadException : function()
53674 dom.innerHTML = '';
53676 Roo.log("Select on load exception");
53680 Roo.log(this.store.reader.jsonData);
53681 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
53682 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
53688 onTypeAhead : function(){
53693 onSelect : function(record, index){
53694 Roo.log('on select?');
53696 if(this.fireEvent('beforeselect', this, record, index) !== false){
53697 this.setFromData(index > -1 ? record.data : false);
53699 this.fireEvent('select', this, record, index);
53704 * Returns the currently selected field value or empty string if no value is set.
53705 * @return {String} value The selected value
53707 getValue : function(){
53708 var dom = this.el.dom;
53709 this.value = dom.options[dom.selectedIndex].value;
53715 * Clears any text/value currently set in the field
53717 clearValue : function(){
53719 this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
53724 * Sets the specified value into the field. If the value finds a match, the corresponding record text
53725 * will be displayed in the field. If the value does not match the data value of an existing item,
53726 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
53727 * Otherwise the field will be blank (although the value will still be set).
53728 * @param {String} value The value to match
53730 setValue : function(v){
53731 var d = this.el.dom;
53732 for (var i =0; i < d.options.length;i++) {
53733 if (v == d.options[i].value) {
53734 d.selectedIndex = i;
53742 * @property {Object} the last set data for the element
53747 * Sets the value of the field based on a object which is related to the record format for the store.
53748 * @param {Object} value the value to set as. or false on reset?
53750 setFromData : function(o){
53751 Roo.log('setfrom data?');
53757 reset : function(){
53761 findRecord : function(prop, value){
53766 if(this.store.getCount() > 0){
53767 this.store.each(function(r){
53768 if(r.data[prop] == value){
53778 getName: function()
53780 // returns hidden if it's set..
53781 if (!this.rendered) {return ''};
53782 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
53790 onEmptyResults : function(){
53791 Roo.log('empty results');
53796 * Returns true if the dropdown list is expanded, else false.
53798 isExpanded : function(){
53803 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
53804 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
53805 * @param {String} value The data value of the item to select
53806 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
53807 * selected item if it is not currently in view (defaults to true)
53808 * @return {Boolean} True if the value matched an item in the list, else false
53810 selectByValue : function(v, scrollIntoView){
53811 Roo.log('select By Value');
53814 if(v !== undefined && v !== null){
53815 var r = this.findRecord(this.valueField || this.displayField, v);
53817 this.select(this.store.indexOf(r), scrollIntoView);
53825 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
53826 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
53827 * @param {Number} index The zero-based index of the list item to select
53828 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
53829 * selected item if it is not currently in view (defaults to true)
53831 select : function(index, scrollIntoView){
53832 Roo.log('select ');
53835 this.selectedIndex = index;
53836 this.view.select(index);
53837 if(scrollIntoView !== false){
53838 var el = this.view.getNode(index);
53840 this.innerList.scrollChildIntoView(el, false);
53848 validateBlur : function(){
53855 initQuery : function(){
53856 this.doQuery(this.getRawValue());
53860 doForce : function(){
53861 if(this.el.dom.value.length > 0){
53862 this.el.dom.value =
53863 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
53869 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
53870 * query allowing the query action to be canceled if needed.
53871 * @param {String} query The SQL query to execute
53872 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
53873 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
53874 * saved in the current store (defaults to false)
53876 doQuery : function(q, forceAll){
53878 Roo.log('doQuery?');
53879 if(q === undefined || q === null){
53884 forceAll: forceAll,
53888 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
53892 forceAll = qe.forceAll;
53893 if(forceAll === true || (q.length >= this.minChars)){
53894 if(this.lastQuery != q || this.alwaysQuery){
53895 this.lastQuery = q;
53896 if(this.mode == 'local'){
53897 this.selectedIndex = -1;
53899 this.store.clearFilter();
53901 this.store.filter(this.displayField, q);
53905 this.store.baseParams[this.queryParam] = q;
53907 params: this.getParams(q)
53912 this.selectedIndex = -1;
53919 getParams : function(q){
53921 //p[this.queryParam] = q;
53924 p.limit = this.pageSize;
53930 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
53932 collapse : function(){
53937 collapseIf : function(e){
53942 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
53944 expand : function(){
53952 * @cfg {Boolean} grow
53956 * @cfg {Number} growMin
53960 * @cfg {Number} growMax
53968 setWidth : function()
53972 getResizeEl : function(){
53975 });//<script type="text/javasscript">
53979 * @class Roo.DDView
53980 * A DnD enabled version of Roo.View.
53981 * @param {Element/String} container The Element in which to create the View.
53982 * @param {String} tpl The template string used to create the markup for each element of the View
53983 * @param {Object} config The configuration properties. These include all the config options of
53984 * {@link Roo.View} plus some specific to this class.<br>
53986 * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
53987 * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
53989 * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
53990 .x-view-drag-insert-above {
53991 border-top:1px dotted #3366cc;
53993 .x-view-drag-insert-below {
53994 border-bottom:1px dotted #3366cc;
54000 Roo.DDView = function(container, tpl, config) {
54001 Roo.DDView.superclass.constructor.apply(this, arguments);
54002 this.getEl().setStyle("outline", "0px none");
54003 this.getEl().unselectable();
54004 if (this.dragGroup) {
54005 this.setDraggable(this.dragGroup.split(","));
54007 if (this.dropGroup) {
54008 this.setDroppable(this.dropGroup.split(","));
54010 if (this.deletable) {
54011 this.setDeletable();
54013 this.isDirtyFlag = false;
54019 Roo.extend(Roo.DDView, Roo.View, {
54020 /** @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
54021 /** @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
54022 /** @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
54023 /** @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
54027 reset: Roo.emptyFn,
54029 clearInvalid: Roo.form.Field.prototype.clearInvalid,
54031 validate: function() {
54035 destroy: function() {
54036 this.purgeListeners();
54037 this.getEl.removeAllListeners();
54038 this.getEl().remove();
54039 if (this.dragZone) {
54040 if (this.dragZone.destroy) {
54041 this.dragZone.destroy();
54044 if (this.dropZone) {
54045 if (this.dropZone.destroy) {
54046 this.dropZone.destroy();
54051 /** Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
54052 getName: function() {
54056 /** Loads the View from a JSON string representing the Records to put into the Store. */
54057 setValue: function(v) {
54059 throw "DDView.setValue(). DDView must be constructed with a valid Store";
54062 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
54063 this.store.proxy = new Roo.data.MemoryProxy(data);
54067 /** @return {String} a parenthesised list of the ids of the Records in the View. */
54068 getValue: function() {
54070 this.store.each(function(rec) {
54071 result += rec.id + ',';
54073 return result.substr(0, result.length - 1) + ')';
54076 getIds: function() {
54077 var i = 0, result = new Array(this.store.getCount());
54078 this.store.each(function(rec) {
54079 result[i++] = rec.id;
54084 isDirty: function() {
54085 return this.isDirtyFlag;
54089 * Part of the Roo.dd.DropZone interface. If no target node is found, the
54090 * whole Element becomes the target, and this causes the drop gesture to append.
54092 getTargetFromEvent : function(e) {
54093 var target = e.getTarget();
54094 while ((target !== null) && (target.parentNode != this.el.dom)) {
54095 target = target.parentNode;
54098 target = this.el.dom.lastChild || this.el.dom;
54104 * Create the drag data which consists of an object which has the property "ddel" as
54105 * the drag proxy element.
54107 getDragData : function(e) {
54108 var target = this.findItemFromChild(e.getTarget());
54110 this.handleSelection(e);
54111 var selNodes = this.getSelectedNodes();
54114 copy: this.copy || (this.allowCopy && e.ctrlKey),
54118 var selectedIndices = this.getSelectedIndexes();
54119 for (var i = 0; i < selectedIndices.length; i++) {
54120 dragData.records.push(this.store.getAt(selectedIndices[i]));
54122 if (selNodes.length == 1) {
54123 dragData.ddel = target.cloneNode(true); // the div element
54125 var div = document.createElement('div'); // create the multi element drag "ghost"
54126 div.className = 'multi-proxy';
54127 for (var i = 0, len = selNodes.length; i < len; i++) {
54128 div.appendChild(selNodes[i].cloneNode(true));
54130 dragData.ddel = div;
54132 //console.log(dragData)
54133 //console.log(dragData.ddel.innerHTML)
54136 //console.log('nodragData')
54140 /** Specify to which ddGroup items in this DDView may be dragged. */
54141 setDraggable: function(ddGroup) {
54142 if (ddGroup instanceof Array) {
54143 Roo.each(ddGroup, this.setDraggable, this);
54146 if (this.dragZone) {
54147 this.dragZone.addToGroup(ddGroup);
54149 this.dragZone = new Roo.dd.DragZone(this.getEl(), {
54150 containerScroll: true,
54154 // Draggability implies selection. DragZone's mousedown selects the element.
54155 if (!this.multiSelect) { this.singleSelect = true; }
54157 // Wire the DragZone's handlers up to methods in *this*
54158 this.dragZone.getDragData = this.getDragData.createDelegate(this);
54162 /** Specify from which ddGroup this DDView accepts drops. */
54163 setDroppable: function(ddGroup) {
54164 if (ddGroup instanceof Array) {
54165 Roo.each(ddGroup, this.setDroppable, this);
54168 if (this.dropZone) {
54169 this.dropZone.addToGroup(ddGroup);
54171 this.dropZone = new Roo.dd.DropZone(this.getEl(), {
54172 containerScroll: true,
54176 // Wire the DropZone's handlers up to methods in *this*
54177 this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
54178 this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
54179 this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
54180 this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
54181 this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
54185 /** Decide whether to drop above or below a View node. */
54186 getDropPoint : function(e, n, dd){
54187 if (n == this.el.dom) { return "above"; }
54188 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
54189 var c = t + (b - t) / 2;
54190 var y = Roo.lib.Event.getPageY(e);
54198 onNodeEnter : function(n, dd, e, data){
54202 onNodeOver : function(n, dd, e, data){
54203 var pt = this.getDropPoint(e, n, dd);
54204 // set the insert point style on the target node
54205 var dragElClass = this.dropNotAllowed;
54208 if (pt == "above"){
54209 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
54210 targetElClass = "x-view-drag-insert-above";
54212 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
54213 targetElClass = "x-view-drag-insert-below";
54215 if (this.lastInsertClass != targetElClass){
54216 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
54217 this.lastInsertClass = targetElClass;
54220 return dragElClass;
54223 onNodeOut : function(n, dd, e, data){
54224 this.removeDropIndicators(n);
54227 onNodeDrop : function(n, dd, e, data){
54228 if (this.fireEvent("drop", this, n, dd, e, data) === false) {
54231 var pt = this.getDropPoint(e, n, dd);
54232 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
54233 if (pt == "below") { insertAt++; }
54234 for (var i = 0; i < data.records.length; i++) {
54235 var r = data.records[i];
54236 var dup = this.store.getById(r.id);
54237 if (dup && (dd != this.dragZone)) {
54238 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
54241 this.store.insert(insertAt++, r.copy());
54243 data.source.isDirtyFlag = true;
54245 this.store.insert(insertAt++, r);
54247 this.isDirtyFlag = true;
54250 this.dragZone.cachedTarget = null;
54254 removeDropIndicators : function(n){
54256 Roo.fly(n).removeClass([
54257 "x-view-drag-insert-above",
54258 "x-view-drag-insert-below"]);
54259 this.lastInsertClass = "_noclass";
54264 * Utility method. Add a delete option to the DDView's context menu.
54265 * @param {String} imageUrl The URL of the "delete" icon image.
54267 setDeletable: function(imageUrl) {
54268 if (!this.singleSelect && !this.multiSelect) {
54269 this.singleSelect = true;
54271 var c = this.getContextMenu();
54272 this.contextMenu.on("itemclick", function(item) {
54275 this.remove(this.getSelectedIndexes());
54279 this.contextMenu.add({
54286 /** Return the context menu for this DDView. */
54287 getContextMenu: function() {
54288 if (!this.contextMenu) {
54289 // Create the View's context menu
54290 this.contextMenu = new Roo.menu.Menu({
54291 id: this.id + "-contextmenu"
54293 this.el.on("contextmenu", this.showContextMenu, this);
54295 return this.contextMenu;
54298 disableContextMenu: function() {
54299 if (this.contextMenu) {
54300 this.el.un("contextmenu", this.showContextMenu, this);
54304 showContextMenu: function(e, item) {
54305 item = this.findItemFromChild(e.getTarget());
54308 this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
54309 this.contextMenu.showAt(e.getXY());
54314 * Remove {@link Roo.data.Record}s at the specified indices.
54315 * @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
54317 remove: function(selectedIndices) {
54318 selectedIndices = [].concat(selectedIndices);
54319 for (var i = 0; i < selectedIndices.length; i++) {
54320 var rec = this.store.getAt(selectedIndices[i]);
54321 this.store.remove(rec);
54326 * Double click fires the event, but also, if this is draggable, and there is only one other
54327 * related DropZone, it transfers the selected node.
54329 onDblClick : function(e){
54330 var item = this.findItemFromChild(e.getTarget());
54332 if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
54335 if (this.dragGroup) {
54336 var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
54337 while (targets.indexOf(this.dropZone) > -1) {
54338 targets.remove(this.dropZone);
54340 if (targets.length == 1) {
54341 this.dragZone.cachedTarget = null;
54342 var el = Roo.get(targets[0].getEl());
54343 var box = el.getBox(true);
54344 targets[0].onNodeDrop(el.dom, {
54346 xy: [box.x, box.y + box.height - 1]
54347 }, null, this.getDragData(e));
54353 handleSelection: function(e) {
54354 this.dragZone.cachedTarget = null;
54355 var item = this.findItemFromChild(e.getTarget());
54357 this.clearSelections(true);
54360 if (item && (this.multiSelect || this.singleSelect)){
54361 if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
54362 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
54363 }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
54364 this.unselect(item);
54366 this.select(item, this.multiSelect && e.ctrlKey);
54367 this.lastSelection = item;
54372 onItemClick : function(item, index, e){
54373 if(this.fireEvent("beforeclick", this, index, item, e) === false){
54379 unselect : function(nodeInfo, suppressEvent){
54380 var node = this.getNode(nodeInfo);
54381 if(node && this.isSelected(node)){
54382 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
54383 Roo.fly(node).removeClass(this.selectedClass);
54384 this.selections.remove(node);
54385 if(!suppressEvent){
54386 this.fireEvent("selectionchange", this, this.selections);
54394 * Ext JS Library 1.1.1
54395 * Copyright(c) 2006-2007, Ext JS, LLC.
54397 * Originally Released Under LGPL - original licence link has changed is not relivant.
54400 * <script type="text/javascript">
54404 * @class Roo.LayoutManager
54405 * @extends Roo.util.Observable
54406 * Base class for layout managers.
54408 Roo.LayoutManager = function(container, config){
54409 Roo.LayoutManager.superclass.constructor.call(this);
54410 this.el = Roo.get(container);
54411 // ie scrollbar fix
54412 if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
54413 document.body.scroll = "no";
54414 }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
54415 this.el.position('relative');
54417 this.id = this.el.id;
54418 this.el.addClass("x-layout-container");
54419 /** false to disable window resize monitoring @type Boolean */
54420 this.monitorWindowResize = true;
54425 * Fires when a layout is performed.
54426 * @param {Roo.LayoutManager} this
54430 * @event regionresized
54431 * Fires when the user resizes a region.
54432 * @param {Roo.LayoutRegion} region The resized region
54433 * @param {Number} newSize The new size (width for east/west, height for north/south)
54435 "regionresized" : true,
54437 * @event regioncollapsed
54438 * Fires when a region is collapsed.
54439 * @param {Roo.LayoutRegion} region The collapsed region
54441 "regioncollapsed" : true,
54443 * @event regionexpanded
54444 * Fires when a region is expanded.
54445 * @param {Roo.LayoutRegion} region The expanded region
54447 "regionexpanded" : true
54449 this.updating = false;
54450 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
54453 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
54455 * Returns true if this layout is currently being updated
54456 * @return {Boolean}
54458 isUpdating : function(){
54459 return this.updating;
54463 * Suspend the LayoutManager from doing auto-layouts while
54464 * making multiple add or remove calls
54466 beginUpdate : function(){
54467 this.updating = true;
54471 * Restore auto-layouts and optionally disable the manager from performing a layout
54472 * @param {Boolean} noLayout true to disable a layout update
54474 endUpdate : function(noLayout){
54475 this.updating = false;
54481 layout: function(){
54485 onRegionResized : function(region, newSize){
54486 this.fireEvent("regionresized", region, newSize);
54490 onRegionCollapsed : function(region){
54491 this.fireEvent("regioncollapsed", region);
54494 onRegionExpanded : function(region){
54495 this.fireEvent("regionexpanded", region);
54499 * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
54500 * performs box-model adjustments.
54501 * @return {Object} The size as an object {width: (the width), height: (the height)}
54503 getViewSize : function(){
54505 if(this.el.dom != document.body){
54506 size = this.el.getSize();
54508 size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
54510 size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
54511 size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
54516 * Returns the Element this layout is bound to.
54517 * @return {Roo.Element}
54519 getEl : function(){
54524 * Returns the specified region.
54525 * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
54526 * @return {Roo.LayoutRegion}
54528 getRegion : function(target){
54529 return this.regions[target.toLowerCase()];
54532 onWindowResize : function(){
54533 if(this.monitorWindowResize){
54539 * Ext JS Library 1.1.1
54540 * Copyright(c) 2006-2007, Ext JS, LLC.
54542 * Originally Released Under LGPL - original licence link has changed is not relivant.
54545 * <script type="text/javascript">
54548 * @class Roo.BorderLayout
54549 * @extends Roo.LayoutManager
54550 * @children Roo.ContentPanel
54551 * This class represents a common layout manager used in desktop applications. For screenshots and more details,
54552 * please see: <br><br>
54553 * <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>
54554 * <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>
54557 var layout = new Roo.BorderLayout(document.body, {
54591 preferredTabWidth: 150
54596 var CP = Roo.ContentPanel;
54598 layout.beginUpdate();
54599 layout.add("north", new CP("north", "North"));
54600 layout.add("south", new CP("south", {title: "South", closable: true}));
54601 layout.add("west", new CP("west", {title: "West"}));
54602 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
54603 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
54604 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
54605 layout.getRegion("center").showPanel("center1");
54606 layout.endUpdate();
54609 <b>The container the layout is rendered into can be either the body element or any other element.
54610 If it is not the body element, the container needs to either be an absolute positioned element,
54611 or you will need to add "position:relative" to the css of the container. You will also need to specify
54612 the container size if it is not the body element.</b>
54615 * Create a new BorderLayout
54616 * @param {String/HTMLElement/Element} container The container this layout is bound to
54617 * @param {Object} config Configuration options
54619 Roo.BorderLayout = function(container, config){
54620 config = config || {};
54621 Roo.BorderLayout.superclass.constructor.call(this, container, config);
54622 this.factory = config.factory || Roo.BorderLayout.RegionFactory;
54623 for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
54624 var target = this.factory.validRegions[i];
54625 if(config[target]){
54626 this.addRegion(target, config[target]);
54631 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
54634 * @cfg {Roo.LayoutRegion} east
54637 * @cfg {Roo.LayoutRegion} west
54640 * @cfg {Roo.LayoutRegion} north
54643 * @cfg {Roo.LayoutRegion} south
54646 * @cfg {Roo.LayoutRegion} center
54649 * Creates and adds a new region if it doesn't already exist.
54650 * @param {String} target The target region key (north, south, east, west or center).
54651 * @param {Object} config The regions config object
54652 * @return {BorderLayoutRegion} The new region
54654 addRegion : function(target, config){
54655 if(!this.regions[target]){
54656 var r = this.factory.create(target, this, config);
54657 this.bindRegion(target, r);
54659 return this.regions[target];
54663 bindRegion : function(name, r){
54664 this.regions[name] = r;
54665 r.on("visibilitychange", this.layout, this);
54666 r.on("paneladded", this.layout, this);
54667 r.on("panelremoved", this.layout, this);
54668 r.on("invalidated", this.layout, this);
54669 r.on("resized", this.onRegionResized, this);
54670 r.on("collapsed", this.onRegionCollapsed, this);
54671 r.on("expanded", this.onRegionExpanded, this);
54675 * Performs a layout update.
54677 layout : function(){
54678 if(this.updating) {
54681 var size = this.getViewSize();
54682 var w = size.width;
54683 var h = size.height;
54688 //var x = 0, y = 0;
54690 var rs = this.regions;
54691 var north = rs["north"];
54692 var south = rs["south"];
54693 var west = rs["west"];
54694 var east = rs["east"];
54695 var center = rs["center"];
54696 //if(this.hideOnLayout){ // not supported anymore
54697 //c.el.setStyle("display", "none");
54699 if(north && north.isVisible()){
54700 var b = north.getBox();
54701 var m = north.getMargins();
54702 b.width = w - (m.left+m.right);
54705 centerY = b.height + b.y + m.bottom;
54706 centerH -= centerY;
54707 north.updateBox(this.safeBox(b));
54709 if(south && south.isVisible()){
54710 var b = south.getBox();
54711 var m = south.getMargins();
54712 b.width = w - (m.left+m.right);
54714 var totalHeight = (b.height + m.top + m.bottom);
54715 b.y = h - totalHeight + m.top;
54716 centerH -= totalHeight;
54717 south.updateBox(this.safeBox(b));
54719 if(west && west.isVisible()){
54720 var b = west.getBox();
54721 var m = west.getMargins();
54722 b.height = centerH - (m.top+m.bottom);
54724 b.y = centerY + m.top;
54725 var totalWidth = (b.width + m.left + m.right);
54726 centerX += totalWidth;
54727 centerW -= totalWidth;
54728 west.updateBox(this.safeBox(b));
54730 if(east && east.isVisible()){
54731 var b = east.getBox();
54732 var m = east.getMargins();
54733 b.height = centerH - (m.top+m.bottom);
54734 var totalWidth = (b.width + m.left + m.right);
54735 b.x = w - totalWidth + m.left;
54736 b.y = centerY + m.top;
54737 centerW -= totalWidth;
54738 east.updateBox(this.safeBox(b));
54741 var m = center.getMargins();
54743 x: centerX + m.left,
54744 y: centerY + m.top,
54745 width: centerW - (m.left+m.right),
54746 height: centerH - (m.top+m.bottom)
54748 //if(this.hideOnLayout){
54749 //center.el.setStyle("display", "block");
54751 center.updateBox(this.safeBox(centerBox));
54754 this.fireEvent("layout", this);
54758 safeBox : function(box){
54759 box.width = Math.max(0, box.width);
54760 box.height = Math.max(0, box.height);
54765 * Adds a ContentPanel (or subclass) to this layout.
54766 * @param {String} target The target region key (north, south, east, west or center).
54767 * @param {Roo.ContentPanel} panel The panel to add
54768 * @return {Roo.ContentPanel} The added panel
54770 add : function(target, panel){
54772 target = target.toLowerCase();
54773 return this.regions[target].add(panel);
54777 * Remove a ContentPanel (or subclass) to this layout.
54778 * @param {String} target The target region key (north, south, east, west or center).
54779 * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
54780 * @return {Roo.ContentPanel} The removed panel
54782 remove : function(target, panel){
54783 target = target.toLowerCase();
54784 return this.regions[target].remove(panel);
54788 * Searches all regions for a panel with the specified id
54789 * @param {String} panelId
54790 * @return {Roo.ContentPanel} The panel or null if it wasn't found
54792 findPanel : function(panelId){
54793 var rs = this.regions;
54794 for(var target in rs){
54795 if(typeof rs[target] != "function"){
54796 var p = rs[target].getPanel(panelId);
54806 * Searches all regions for a panel with the specified id and activates (shows) it.
54807 * @param {String/ContentPanel} panelId The panels id or the panel itself
54808 * @return {Roo.ContentPanel} The shown panel or null
54810 showPanel : function(panelId) {
54811 var rs = this.regions;
54812 for(var target in rs){
54813 var r = rs[target];
54814 if(typeof r != "function"){
54815 if(r.hasPanel(panelId)){
54816 return r.showPanel(panelId);
54824 * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
54825 * @param {Roo.state.Provider} provider (optional) An alternate state provider
54827 restoreState : function(provider){
54829 provider = Roo.state.Manager;
54831 var sm = new Roo.LayoutStateManager();
54832 sm.init(this, provider);
54836 * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object. This config
54837 * object should contain properties for each region to add ContentPanels to, and each property's value should be
54838 * a valid ContentPanel config object. Example:
54840 // Create the main layout
54841 var layout = new Roo.BorderLayout('main-ct', {
54852 // Create and add multiple ContentPanels at once via configs
54855 id: 'source-files',
54857 title:'Ext Source Files',
54870 * @param {Object} regions An object containing ContentPanel configs by region name
54872 batchAdd : function(regions){
54873 this.beginUpdate();
54874 for(var rname in regions){
54875 var lr = this.regions[rname];
54877 this.addTypedPanels(lr, regions[rname]);
54884 addTypedPanels : function(lr, ps){
54885 if(typeof ps == 'string'){
54886 lr.add(new Roo.ContentPanel(ps));
54888 else if(ps instanceof Array){
54889 for(var i =0, len = ps.length; i < len; i++){
54890 this.addTypedPanels(lr, ps[i]);
54893 else if(!ps.events){ // raw config?
54895 delete ps.el; // prevent conflict
54896 lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
54898 else { // panel object assumed!
54903 * Adds a xtype elements to the layout.
54907 xtype : 'ContentPanel',
54914 xtype : 'NestedLayoutPanel',
54920 items : [ ... list of content panels or nested layout panels.. ]
54924 * @param {Object} cfg Xtype definition of item to add.
54926 addxtype : function(cfg)
54928 // basically accepts a pannel...
54929 // can accept a layout region..!?!?
54930 //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
54932 if (!cfg.xtype.match(/Panel$/)) {
54937 if (typeof(cfg.region) == 'undefined') {
54938 Roo.log("Failed to add Panel, region was not set");
54942 var region = cfg.region;
54948 xitems = cfg.items;
54955 case 'ContentPanel': // ContentPanel (el, cfg)
54956 case 'ScrollPanel': // ContentPanel (el, cfg)
54958 if(cfg.autoCreate) {
54959 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
54961 var el = this.el.createChild();
54962 ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
54965 this.add(region, ret);
54969 case 'TreePanel': // our new panel!
54970 cfg.el = this.el.createChild();
54971 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
54972 this.add(region, ret);
54975 case 'NestedLayoutPanel':
54976 // create a new Layout (which is a Border Layout...
54977 var el = this.el.createChild();
54978 var clayout = cfg.layout;
54980 clayout.items = clayout.items || [];
54981 // replace this exitems with the clayout ones..
54982 xitems = clayout.items;
54985 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
54986 cfg.background = false;
54988 var layout = new Roo.BorderLayout(el, clayout);
54990 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
54991 //console.log('adding nested layout panel ' + cfg.toSource());
54992 this.add(region, ret);
54993 nb = {}; /// find first...
54998 // needs grid and region
55000 //var el = this.getRegion(region).el.createChild();
55001 var el = this.el.createChild();
55002 // create the grid first...
55004 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
55006 if (region == 'center' && this.active ) {
55007 cfg.background = false;
55009 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
55011 this.add(region, ret);
55012 if (cfg.background) {
55013 ret.on('activate', function(gp) {
55014 if (!gp.grid.rendered) {
55029 if (typeof(Roo[cfg.xtype]) != 'undefined') {
55031 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
55032 this.add(region, ret);
55035 alert("Can not add '" + cfg.xtype + "' to BorderLayout");
55039 // GridPanel (grid, cfg)
55042 this.beginUpdate();
55046 Roo.each(xitems, function(i) {
55047 region = nb && i.region ? i.region : false;
55049 var add = ret.addxtype(i);
55052 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
55053 if (!i.background) {
55054 abn[region] = nb[region] ;
55061 // make the last non-background panel active..
55062 //if (nb) { Roo.log(abn); }
55065 for(var r in abn) {
55066 region = this.getRegion(r);
55068 // tried using nb[r], but it does not work..
55070 region.showPanel(abn[r]);
55081 * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
55082 * the beginUpdate and endUpdate calls internally. The key to this method is the <b>panels</b> property that can be
55083 * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
55084 * during creation. The following code is equivalent to the constructor-based example at the beginning of this class:
55087 var CP = Roo.ContentPanel;
55089 var layout = Roo.BorderLayout.create({
55093 panels: [new CP("north", "North")]
55102 panels: [new CP("west", {title: "West"})]
55111 panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
55120 panels: [new CP("south", {title: "South", closable: true})]
55127 preferredTabWidth: 150,
55129 new CP("center1", {title: "Close Me", closable: true}),
55130 new CP("center2", {title: "Center Panel", closable: false})
55135 layout.getRegion("center").showPanel("center1");
55140 Roo.BorderLayout.create = function(config, targetEl){
55141 var layout = new Roo.BorderLayout(targetEl || document.body, config);
55142 layout.beginUpdate();
55143 var regions = Roo.BorderLayout.RegionFactory.validRegions;
55144 for(var j = 0, jlen = regions.length; j < jlen; j++){
55145 var lr = regions[j];
55146 if(layout.regions[lr] && config[lr].panels){
55147 var r = layout.regions[lr];
55148 var ps = config[lr].panels;
55149 layout.addTypedPanels(r, ps);
55152 layout.endUpdate();
55157 Roo.BorderLayout.RegionFactory = {
55159 validRegions : ["north","south","east","west","center"],
55162 create : function(target, mgr, config){
55163 target = target.toLowerCase();
55164 if(config.lightweight || config.basic){
55165 return new Roo.BasicLayoutRegion(mgr, config, target);
55169 return new Roo.NorthLayoutRegion(mgr, config);
55171 return new Roo.SouthLayoutRegion(mgr, config);
55173 return new Roo.EastLayoutRegion(mgr, config);
55175 return new Roo.WestLayoutRegion(mgr, config);
55177 return new Roo.CenterLayoutRegion(mgr, config);
55179 throw 'Layout region "'+target+'" not supported.';
55183 * Ext JS Library 1.1.1
55184 * Copyright(c) 2006-2007, Ext JS, LLC.
55186 * Originally Released Under LGPL - original licence link has changed is not relivant.
55189 * <script type="text/javascript">
55193 * @class Roo.BasicLayoutRegion
55194 * @extends Roo.util.Observable
55195 * This class represents a lightweight region in a layout manager. This region does not move dom nodes
55196 * and does not have a titlebar, tabs or any other features. All it does is size and position
55197 * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
55199 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
55201 this.position = pos;
55204 * @scope Roo.BasicLayoutRegion
55208 * @event beforeremove
55209 * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
55210 * @param {Roo.LayoutRegion} this
55211 * @param {Roo.ContentPanel} panel The panel
55212 * @param {Object} e The cancel event object
55214 "beforeremove" : true,
55216 * @event invalidated
55217 * Fires when the layout for this region is changed.
55218 * @param {Roo.LayoutRegion} this
55220 "invalidated" : true,
55222 * @event visibilitychange
55223 * Fires when this region is shown or hidden
55224 * @param {Roo.LayoutRegion} this
55225 * @param {Boolean} visibility true or false
55227 "visibilitychange" : true,
55229 * @event paneladded
55230 * Fires when a panel is added.
55231 * @param {Roo.LayoutRegion} this
55232 * @param {Roo.ContentPanel} panel The panel
55234 "paneladded" : true,
55236 * @event panelremoved
55237 * Fires when a panel is removed.
55238 * @param {Roo.LayoutRegion} this
55239 * @param {Roo.ContentPanel} panel The panel
55241 "panelremoved" : true,
55243 * @event beforecollapse
55244 * Fires when this region before collapse.
55245 * @param {Roo.LayoutRegion} this
55247 "beforecollapse" : true,
55250 * Fires when this region is collapsed.
55251 * @param {Roo.LayoutRegion} this
55253 "collapsed" : true,
55256 * Fires when this region is expanded.
55257 * @param {Roo.LayoutRegion} this
55262 * Fires when this region is slid into view.
55263 * @param {Roo.LayoutRegion} this
55265 "slideshow" : true,
55268 * Fires when this region slides out of view.
55269 * @param {Roo.LayoutRegion} this
55271 "slidehide" : true,
55273 * @event panelactivated
55274 * Fires when a panel is activated.
55275 * @param {Roo.LayoutRegion} this
55276 * @param {Roo.ContentPanel} panel The activated panel
55278 "panelactivated" : true,
55281 * Fires when the user resizes this region.
55282 * @param {Roo.LayoutRegion} this
55283 * @param {Number} newSize The new size (width for east/west, height for north/south)
55287 /** A collection of panels in this region. @type Roo.util.MixedCollection */
55288 this.panels = new Roo.util.MixedCollection();
55289 this.panels.getKey = this.getPanelId.createDelegate(this);
55291 this.activePanel = null;
55292 // ensure listeners are added...
55294 if (config.listeners || config.events) {
55295 Roo.BasicLayoutRegion.superclass.constructor.call(this, {
55296 listeners : config.listeners || {},
55297 events : config.events || {}
55301 if(skipConfig !== true){
55302 this.applyConfig(config);
55306 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
55307 getPanelId : function(p){
55311 applyConfig : function(config){
55312 this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
55313 this.config = config;
55318 * Resizes the region to the specified size. For vertical regions (west, east) this adjusts
55319 * the width, for horizontal (north, south) the height.
55320 * @param {Number} newSize The new width or height
55322 resizeTo : function(newSize){
55323 var el = this.el ? this.el :
55324 (this.activePanel ? this.activePanel.getEl() : null);
55326 switch(this.position){
55329 el.setWidth(newSize);
55330 this.fireEvent("resized", this, newSize);
55334 el.setHeight(newSize);
55335 this.fireEvent("resized", this, newSize);
55341 getBox : function(){
55342 return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
55345 getMargins : function(){
55346 return this.margins;
55349 updateBox : function(box){
55351 var el = this.activePanel.getEl();
55352 el.dom.style.left = box.x + "px";
55353 el.dom.style.top = box.y + "px";
55354 this.activePanel.setSize(box.width, box.height);
55358 * Returns the container element for this region.
55359 * @return {Roo.Element}
55361 getEl : function(){
55362 return this.activePanel;
55366 * Returns true if this region is currently visible.
55367 * @return {Boolean}
55369 isVisible : function(){
55370 return this.activePanel ? true : false;
55373 setActivePanel : function(panel){
55374 panel = this.getPanel(panel);
55375 if(this.activePanel && this.activePanel != panel){
55376 this.activePanel.setActiveState(false);
55377 this.activePanel.getEl().setLeftTop(-10000,-10000);
55379 this.activePanel = panel;
55380 panel.setActiveState(true);
55382 panel.setSize(this.box.width, this.box.height);
55384 this.fireEvent("panelactivated", this, panel);
55385 this.fireEvent("invalidated");
55389 * Show the specified panel.
55390 * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
55391 * @return {Roo.ContentPanel} The shown panel or null
55393 showPanel : function(panel){
55394 if(panel = this.getPanel(panel)){
55395 this.setActivePanel(panel);
55401 * Get the active panel for this region.
55402 * @return {Roo.ContentPanel} The active panel or null
55404 getActivePanel : function(){
55405 return this.activePanel;
55409 * Add the passed ContentPanel(s)
55410 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
55411 * @return {Roo.ContentPanel} The panel added (if only one was added)
55413 add : function(panel){
55414 if(arguments.length > 1){
55415 for(var i = 0, len = arguments.length; i < len; i++) {
55416 this.add(arguments[i]);
55420 if(this.hasPanel(panel)){
55421 this.showPanel(panel);
55424 var el = panel.getEl();
55425 if(el.dom.parentNode != this.mgr.el.dom){
55426 this.mgr.el.dom.appendChild(el.dom);
55428 if(panel.setRegion){
55429 panel.setRegion(this);
55431 this.panels.add(panel);
55432 el.setStyle("position", "absolute");
55433 if(!panel.background){
55434 this.setActivePanel(panel);
55435 if(this.config.initialSize && this.panels.getCount()==1){
55436 this.resizeTo(this.config.initialSize);
55439 this.fireEvent("paneladded", this, panel);
55444 * Returns true if the panel is in this region.
55445 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
55446 * @return {Boolean}
55448 hasPanel : function(panel){
55449 if(typeof panel == "object"){ // must be panel obj
55450 panel = panel.getId();
55452 return this.getPanel(panel) ? true : false;
55456 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
55457 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
55458 * @param {Boolean} preservePanel Overrides the config preservePanel option
55459 * @return {Roo.ContentPanel} The panel that was removed
55461 remove : function(panel, preservePanel){
55462 panel = this.getPanel(panel);
55467 this.fireEvent("beforeremove", this, panel, e);
55468 if(e.cancel === true){
55471 var panelId = panel.getId();
55472 this.panels.removeKey(panelId);
55477 * Returns the panel specified or null if it's not in this region.
55478 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
55479 * @return {Roo.ContentPanel}
55481 getPanel : function(id){
55482 if(typeof id == "object"){ // must be panel obj
55485 return this.panels.get(id);
55489 * Returns this regions position (north/south/east/west/center).
55492 getPosition: function(){
55493 return this.position;
55497 * Ext JS Library 1.1.1
55498 * Copyright(c) 2006-2007, Ext JS, LLC.
55500 * Originally Released Under LGPL - original licence link has changed is not relivant.
55503 * <script type="text/javascript">
55507 * @class Roo.LayoutRegion
55508 * @extends Roo.BasicLayoutRegion
55509 * This class represents a region in a layout manager.
55510 * @cfg {Boolean} collapsible False to disable collapsing (defaults to true)
55511 * @cfg {Boolean} collapsed True to set the initial display to collapsed (defaults to false)
55512 * @cfg {Boolean} floatable False to disable floating (defaults to true)
55513 * @cfg {Object} margins Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
55514 * @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})
55515 * @cfg {String} tabPosition (top|bottom) "top" or "bottom" (defaults to "bottom")
55516 * @cfg {String} collapsedTitle Optional string message to display in the collapsed block of a north or south region
55517 * @cfg {Boolean} alwaysShowTabs True to always display tabs even when there is only 1 panel (defaults to false)
55518 * @cfg {Boolean} autoScroll True to enable overflow scrolling (defaults to false)
55519 * @cfg {Boolean} titlebar True to display a title bar (defaults to true)
55520 * @cfg {String} title The title for the region (overrides panel titles)
55521 * @cfg {Boolean} animate True to animate expand/collapse (defaults to false)
55522 * @cfg {Boolean} autoHide False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
55523 * @cfg {Boolean} preservePanels True to preserve removed panels so they can be readded later (defaults to false)
55524 * @cfg {Boolean} closeOnTab True to place the close icon on the tabs instead of the region titlebar (defaults to false)
55525 * @cfg {Boolean} hideTabs True to hide the tab strip (defaults to false)
55526 * @cfg {Boolean} resizeTabs True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
55527 * the space available, similar to FireFox 1.5 tabs (defaults to false)
55528 * @cfg {Number} minTabWidth The minimum tab width (defaults to 40)
55529 * @cfg {Number} preferredTabWidth The preferred tab width (defaults to 150)
55530 * @cfg {Boolean} showPin True to show a pin button
55531 * @cfg {Boolean} hidden True to start the region hidden (defaults to false)
55532 * @cfg {Boolean} hideWhenEmpty True to hide the region when it has no panels
55533 * @cfg {Boolean} disableTabTips True to disable tab tooltips
55534 * @cfg {Number} width For East/West panels
55535 * @cfg {Number} height For North/South panels
55536 * @cfg {Boolean} split To show the splitter
55537 * @cfg {Boolean} toolbar xtype configuration for a toolbar - shows on right of tabbar
55539 Roo.LayoutRegion = function(mgr, config, pos){
55540 Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
55541 var dh = Roo.DomHelper;
55542 /** This region's container element
55543 * @type Roo.Element */
55544 this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
55545 /** This region's title element
55546 * @type Roo.Element */
55548 this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
55549 {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: " "},
55550 {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
55552 this.titleEl.enableDisplayMode();
55553 /** This region's title text element
55554 * @type HTMLElement */
55555 this.titleTextEl = this.titleEl.dom.firstChild;
55556 this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
55557 this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
55558 this.closeBtn.enableDisplayMode();
55559 this.closeBtn.on("click", this.closeClicked, this);
55560 this.closeBtn.hide();
55562 this.createBody(config);
55563 this.visible = true;
55564 this.collapsed = false;
55566 if(config.hideWhenEmpty){
55568 this.on("paneladded", this.validateVisibility, this);
55569 this.on("panelremoved", this.validateVisibility, this);
55571 this.applyConfig(config);
55574 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
55576 createBody : function(){
55577 /** This region's body element
55578 * @type Roo.Element */
55579 this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
55582 applyConfig : function(c){
55583 if(c.collapsible && this.position != "center" && !this.collapsedEl){
55584 var dh = Roo.DomHelper;
55585 if(c.titlebar !== false){
55586 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
55587 this.collapseBtn.on("click", this.collapse, this);
55588 this.collapseBtn.enableDisplayMode();
55590 if(c.showPin === true || this.showPin){
55591 this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
55592 this.stickBtn.enableDisplayMode();
55593 this.stickBtn.on("click", this.expand, this);
55594 this.stickBtn.hide();
55597 /** This region's collapsed element
55598 * @type Roo.Element */
55599 this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
55600 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
55602 if(c.floatable !== false){
55603 this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
55604 this.collapsedEl.on("click", this.collapseClick, this);
55607 if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
55608 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
55609 id: "message", unselectable: "on", style:{"float":"left"}});
55610 this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
55612 this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
55613 this.expandBtn.on("click", this.expand, this);
55615 if(this.collapseBtn){
55616 this.collapseBtn.setVisible(c.collapsible == true);
55618 this.cmargins = c.cmargins || this.cmargins ||
55619 (this.position == "west" || this.position == "east" ?
55620 {top: 0, left: 2, right:2, bottom: 0} :
55621 {top: 2, left: 0, right:0, bottom: 2});
55622 this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
55623 this.bottomTabs = c.tabPosition != "top";
55624 this.autoScroll = c.autoScroll || false;
55625 if(this.autoScroll){
55626 this.bodyEl.setStyle("overflow", "auto");
55628 this.bodyEl.setStyle("overflow", "hidden");
55630 //if(c.titlebar !== false){
55631 if((!c.titlebar && !c.title) || c.titlebar === false){
55632 this.titleEl.hide();
55634 this.titleEl.show();
55636 this.titleTextEl.innerHTML = c.title;
55640 this.duration = c.duration || .30;
55641 this.slideDuration = c.slideDuration || .45;
55644 this.collapse(true);
55651 * Returns true if this region is currently visible.
55652 * @return {Boolean}
55654 isVisible : function(){
55655 return this.visible;
55659 * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
55660 * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&#160;")
55662 setCollapsedTitle : function(title){
55663 title = title || " ";
55664 if(this.collapsedTitleTextEl){
55665 this.collapsedTitleTextEl.innerHTML = title;
55669 getBox : function(){
55671 if(!this.collapsed){
55672 b = this.el.getBox(false, true);
55674 b = this.collapsedEl.getBox(false, true);
55679 getMargins : function(){
55680 return this.collapsed ? this.cmargins : this.margins;
55683 highlight : function(){
55684 this.el.addClass("x-layout-panel-dragover");
55687 unhighlight : function(){
55688 this.el.removeClass("x-layout-panel-dragover");
55691 updateBox : function(box){
55693 if(!this.collapsed){
55694 this.el.dom.style.left = box.x + "px";
55695 this.el.dom.style.top = box.y + "px";
55696 this.updateBody(box.width, box.height);
55698 this.collapsedEl.dom.style.left = box.x + "px";
55699 this.collapsedEl.dom.style.top = box.y + "px";
55700 this.collapsedEl.setSize(box.width, box.height);
55703 this.tabs.autoSizeTabs();
55707 updateBody : function(w, h){
55709 this.el.setWidth(w);
55710 w -= this.el.getBorderWidth("rl");
55711 if(this.config.adjustments){
55712 w += this.config.adjustments[0];
55716 this.el.setHeight(h);
55717 h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
55718 h -= this.el.getBorderWidth("tb");
55719 if(this.config.adjustments){
55720 h += this.config.adjustments[1];
55722 this.bodyEl.setHeight(h);
55724 h = this.tabs.syncHeight(h);
55727 if(this.panelSize){
55728 w = w !== null ? w : this.panelSize.width;
55729 h = h !== null ? h : this.panelSize.height;
55731 if(this.activePanel){
55732 var el = this.activePanel.getEl();
55733 w = w !== null ? w : el.getWidth();
55734 h = h !== null ? h : el.getHeight();
55735 this.panelSize = {width: w, height: h};
55736 this.activePanel.setSize(w, h);
55738 if(Roo.isIE && this.tabs){
55739 this.tabs.el.repaint();
55744 * Returns the container element for this region.
55745 * @return {Roo.Element}
55747 getEl : function(){
55752 * Hides this region.
55755 if(!this.collapsed){
55756 this.el.dom.style.left = "-2000px";
55759 this.collapsedEl.dom.style.left = "-2000px";
55760 this.collapsedEl.hide();
55762 this.visible = false;
55763 this.fireEvent("visibilitychange", this, false);
55767 * Shows this region if it was previously hidden.
55770 if(!this.collapsed){
55773 this.collapsedEl.show();
55775 this.visible = true;
55776 this.fireEvent("visibilitychange", this, true);
55779 closeClicked : function(){
55780 if(this.activePanel){
55781 this.remove(this.activePanel);
55785 collapseClick : function(e){
55787 e.stopPropagation();
55790 e.stopPropagation();
55796 * Collapses this region.
55797 * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
55799 collapse : function(skipAnim, skipCheck){
55800 if(this.collapsed) {
55804 if(skipCheck || this.fireEvent("beforecollapse", this) != false){
55806 this.collapsed = true;
55808 this.split.el.hide();
55810 if(this.config.animate && skipAnim !== true){
55811 this.fireEvent("invalidated", this);
55812 this.animateCollapse();
55814 this.el.setLocation(-20000,-20000);
55816 this.collapsedEl.show();
55817 this.fireEvent("collapsed", this);
55818 this.fireEvent("invalidated", this);
55824 animateCollapse : function(){
55829 * Expands this region if it was previously collapsed.
55830 * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
55831 * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
55833 expand : function(e, skipAnim){
55835 e.stopPropagation();
55837 if(!this.collapsed || this.el.hasActiveFx()) {
55841 this.afterSlideIn();
55844 this.collapsed = false;
55845 if(this.config.animate && skipAnim !== true){
55846 this.animateExpand();
55850 this.split.el.show();
55852 this.collapsedEl.setLocation(-2000,-2000);
55853 this.collapsedEl.hide();
55854 this.fireEvent("invalidated", this);
55855 this.fireEvent("expanded", this);
55859 animateExpand : function(){
55863 initTabs : function()
55865 this.bodyEl.setStyle("overflow", "hidden");
55866 var ts = new Roo.TabPanel(
55869 tabPosition: this.bottomTabs ? 'bottom' : 'top',
55870 disableTooltips: this.config.disableTabTips,
55871 toolbar : this.config.toolbar
55874 if(this.config.hideTabs){
55875 ts.stripWrap.setDisplayed(false);
55878 ts.resizeTabs = this.config.resizeTabs === true;
55879 ts.minTabWidth = this.config.minTabWidth || 40;
55880 ts.maxTabWidth = this.config.maxTabWidth || 250;
55881 ts.preferredTabWidth = this.config.preferredTabWidth || 150;
55882 ts.monitorResize = false;
55883 ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
55884 ts.bodyEl.addClass('x-layout-tabs-body');
55885 this.panels.each(this.initPanelAsTab, this);
55888 initPanelAsTab : function(panel){
55889 var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
55890 this.config.closeOnTab && panel.isClosable());
55891 if(panel.tabTip !== undefined){
55892 ti.setTooltip(panel.tabTip);
55894 ti.on("activate", function(){
55895 this.setActivePanel(panel);
55897 if(this.config.closeOnTab){
55898 ti.on("beforeclose", function(t, e){
55900 this.remove(panel);
55906 updatePanelTitle : function(panel, title){
55907 if(this.activePanel == panel){
55908 this.updateTitle(title);
55911 var ti = this.tabs.getTab(panel.getEl().id);
55913 if(panel.tabTip !== undefined){
55914 ti.setTooltip(panel.tabTip);
55919 updateTitle : function(title){
55920 if(this.titleTextEl && !this.config.title){
55921 this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : " ");
55925 setActivePanel : function(panel){
55926 panel = this.getPanel(panel);
55927 if(this.activePanel && this.activePanel != panel){
55928 this.activePanel.setActiveState(false);
55930 this.activePanel = panel;
55931 panel.setActiveState(true);
55932 if(this.panelSize){
55933 panel.setSize(this.panelSize.width, this.panelSize.height);
55936 this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
55938 this.updateTitle(panel.getTitle());
55940 this.fireEvent("invalidated", this);
55942 this.fireEvent("panelactivated", this, panel);
55946 * Shows the specified panel.
55947 * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
55948 * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
55950 showPanel : function(panel)
55952 panel = this.getPanel(panel);
55955 var tab = this.tabs.getTab(panel.getEl().id);
55956 if(tab.isHidden()){
55957 this.tabs.unhideTab(tab.id);
55961 this.setActivePanel(panel);
55968 * Get the active panel for this region.
55969 * @return {Roo.ContentPanel} The active panel or null
55971 getActivePanel : function(){
55972 return this.activePanel;
55975 validateVisibility : function(){
55976 if(this.panels.getCount() < 1){
55977 this.updateTitle(" ");
55978 this.closeBtn.hide();
55981 if(!this.isVisible()){
55988 * Adds the passed ContentPanel(s) to this region.
55989 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
55990 * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
55992 add : function(panel){
55993 if(arguments.length > 1){
55994 for(var i = 0, len = arguments.length; i < len; i++) {
55995 this.add(arguments[i]);
55999 if(this.hasPanel(panel)){
56000 this.showPanel(panel);
56003 panel.setRegion(this);
56004 this.panels.add(panel);
56005 if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
56006 this.bodyEl.dom.appendChild(panel.getEl().dom);
56007 if(panel.background !== true){
56008 this.setActivePanel(panel);
56010 this.fireEvent("paneladded", this, panel);
56016 this.initPanelAsTab(panel);
56018 if(panel.background !== true){
56019 this.tabs.activate(panel.getEl().id);
56021 this.fireEvent("paneladded", this, panel);
56026 * Hides the tab for the specified panel.
56027 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
56029 hidePanel : function(panel){
56030 if(this.tabs && (panel = this.getPanel(panel))){
56031 this.tabs.hideTab(panel.getEl().id);
56036 * Unhides the tab for a previously hidden panel.
56037 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
56039 unhidePanel : function(panel){
56040 if(this.tabs && (panel = this.getPanel(panel))){
56041 this.tabs.unhideTab(panel.getEl().id);
56045 clearPanels : function(){
56046 while(this.panels.getCount() > 0){
56047 this.remove(this.panels.first());
56052 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
56053 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
56054 * @param {Boolean} preservePanel Overrides the config preservePanel option
56055 * @return {Roo.ContentPanel} The panel that was removed
56057 remove : function(panel, preservePanel){
56058 panel = this.getPanel(panel);
56063 this.fireEvent("beforeremove", this, panel, e);
56064 if(e.cancel === true){
56067 preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
56068 var panelId = panel.getId();
56069 this.panels.removeKey(panelId);
56071 document.body.appendChild(panel.getEl().dom);
56074 this.tabs.removeTab(panel.getEl().id);
56075 }else if (!preservePanel){
56076 this.bodyEl.dom.removeChild(panel.getEl().dom);
56078 if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
56079 var p = this.panels.first();
56080 var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
56081 tempEl.appendChild(p.getEl().dom);
56082 this.bodyEl.update("");
56083 this.bodyEl.dom.appendChild(p.getEl().dom);
56085 this.updateTitle(p.getTitle());
56087 this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
56088 this.setActivePanel(p);
56090 panel.setRegion(null);
56091 if(this.activePanel == panel){
56092 this.activePanel = null;
56094 if(this.config.autoDestroy !== false && preservePanel !== true){
56095 try{panel.destroy();}catch(e){}
56097 this.fireEvent("panelremoved", this, panel);
56102 * Returns the TabPanel component used by this region
56103 * @return {Roo.TabPanel}
56105 getTabs : function(){
56109 createTool : function(parentEl, className){
56110 var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
56111 children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: " "}]}, true);
56112 btn.addClassOnOver("x-layout-tools-button-over");
56117 * Ext JS Library 1.1.1
56118 * Copyright(c) 2006-2007, Ext JS, LLC.
56120 * Originally Released Under LGPL - original licence link has changed is not relivant.
56123 * <script type="text/javascript">
56129 * @class Roo.SplitLayoutRegion
56130 * @extends Roo.LayoutRegion
56131 * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
56133 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
56134 this.cursor = cursor;
56135 Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
56138 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
56139 splitTip : "Drag to resize.",
56140 collapsibleSplitTip : "Drag to resize. Double click to hide.",
56141 useSplitTips : false,
56143 applyConfig : function(config){
56144 Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
56147 var splitEl = Roo.DomHelper.append(this.mgr.el.dom,
56148 {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: " "});
56149 /** The SplitBar for this region
56150 * @type Roo.SplitBar */
56151 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
56152 this.split.on("moved", this.onSplitMove, this);
56153 this.split.useShim = config.useShim === true;
56154 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
56155 if(this.useSplitTips){
56156 this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
56158 if(config.collapsible){
56159 this.split.el.on("dblclick", this.collapse, this);
56162 if(typeof config.minSize != "undefined"){
56163 this.split.minSize = config.minSize;
56165 if(typeof config.maxSize != "undefined"){
56166 this.split.maxSize = config.maxSize;
56168 if(config.hideWhenEmpty || config.hidden || config.collapsed){
56169 this.hideSplitter();
56174 getHMaxSize : function(){
56175 var cmax = this.config.maxSize || 10000;
56176 var center = this.mgr.getRegion("center");
56177 return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
56180 getVMaxSize : function(){
56181 var cmax = this.config.maxSize || 10000;
56182 var center = this.mgr.getRegion("center");
56183 return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
56186 onSplitMove : function(split, newSize){
56187 this.fireEvent("resized", this, newSize);
56191 * Returns the {@link Roo.SplitBar} for this region.
56192 * @return {Roo.SplitBar}
56194 getSplitBar : function(){
56199 this.hideSplitter();
56200 Roo.SplitLayoutRegion.superclass.hide.call(this);
56203 hideSplitter : function(){
56205 this.split.el.setLocation(-2000,-2000);
56206 this.split.el.hide();
56212 this.split.el.show();
56214 Roo.SplitLayoutRegion.superclass.show.call(this);
56217 beforeSlide: function(){
56218 if(Roo.isGecko){// firefox overflow auto bug workaround
56219 this.bodyEl.clip();
56221 this.tabs.bodyEl.clip();
56223 if(this.activePanel){
56224 this.activePanel.getEl().clip();
56226 if(this.activePanel.beforeSlide){
56227 this.activePanel.beforeSlide();
56233 afterSlide : function(){
56234 if(Roo.isGecko){// firefox overflow auto bug workaround
56235 this.bodyEl.unclip();
56237 this.tabs.bodyEl.unclip();
56239 if(this.activePanel){
56240 this.activePanel.getEl().unclip();
56241 if(this.activePanel.afterSlide){
56242 this.activePanel.afterSlide();
56248 initAutoHide : function(){
56249 if(this.autoHide !== false){
56250 if(!this.autoHideHd){
56251 var st = new Roo.util.DelayedTask(this.slideIn, this);
56252 this.autoHideHd = {
56253 "mouseout": function(e){
56254 if(!e.within(this.el, true)){
56258 "mouseover" : function(e){
56264 this.el.on(this.autoHideHd);
56268 clearAutoHide : function(){
56269 if(this.autoHide !== false){
56270 this.el.un("mouseout", this.autoHideHd.mouseout);
56271 this.el.un("mouseover", this.autoHideHd.mouseover);
56275 clearMonitor : function(){
56276 Roo.get(document).un("click", this.slideInIf, this);
56279 // these names are backwards but not changed for compat
56280 slideOut : function(){
56281 if(this.isSlid || this.el.hasActiveFx()){
56284 this.isSlid = true;
56285 if(this.collapseBtn){
56286 this.collapseBtn.hide();
56288 this.closeBtnState = this.closeBtn.getStyle('display');
56289 this.closeBtn.hide();
56291 this.stickBtn.show();
56294 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
56295 this.beforeSlide();
56296 this.el.setStyle("z-index", 10001);
56297 this.el.slideIn(this.getSlideAnchor(), {
56298 callback: function(){
56300 this.initAutoHide();
56301 Roo.get(document).on("click", this.slideInIf, this);
56302 this.fireEvent("slideshow", this);
56309 afterSlideIn : function(){
56310 this.clearAutoHide();
56311 this.isSlid = false;
56312 this.clearMonitor();
56313 this.el.setStyle("z-index", "");
56314 if(this.collapseBtn){
56315 this.collapseBtn.show();
56317 this.closeBtn.setStyle('display', this.closeBtnState);
56319 this.stickBtn.hide();
56321 this.fireEvent("slidehide", this);
56324 slideIn : function(cb){
56325 if(!this.isSlid || this.el.hasActiveFx()){
56329 this.isSlid = false;
56330 this.beforeSlide();
56331 this.el.slideOut(this.getSlideAnchor(), {
56332 callback: function(){
56333 this.el.setLeftTop(-10000, -10000);
56335 this.afterSlideIn();
56343 slideInIf : function(e){
56344 if(!e.within(this.el)){
56349 animateCollapse : function(){
56350 this.beforeSlide();
56351 this.el.setStyle("z-index", 20000);
56352 var anchor = this.getSlideAnchor();
56353 this.el.slideOut(anchor, {
56354 callback : function(){
56355 this.el.setStyle("z-index", "");
56356 this.collapsedEl.slideIn(anchor, {duration:.3});
56358 this.el.setLocation(-10000,-10000);
56360 this.fireEvent("collapsed", this);
56367 animateExpand : function(){
56368 this.beforeSlide();
56369 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
56370 this.el.setStyle("z-index", 20000);
56371 this.collapsedEl.hide({
56374 this.el.slideIn(this.getSlideAnchor(), {
56375 callback : function(){
56376 this.el.setStyle("z-index", "");
56379 this.split.el.show();
56381 this.fireEvent("invalidated", this);
56382 this.fireEvent("expanded", this);
56410 getAnchor : function(){
56411 return this.anchors[this.position];
56414 getCollapseAnchor : function(){
56415 return this.canchors[this.position];
56418 getSlideAnchor : function(){
56419 return this.sanchors[this.position];
56422 getAlignAdj : function(){
56423 var cm = this.cmargins;
56424 switch(this.position){
56440 getExpandAdj : function(){
56441 var c = this.collapsedEl, cm = this.cmargins;
56442 switch(this.position){
56444 return [-(cm.right+c.getWidth()+cm.left), 0];
56447 return [cm.right+c.getWidth()+cm.left, 0];
56450 return [0, -(cm.top+cm.bottom+c.getHeight())];
56453 return [0, cm.top+cm.bottom+c.getHeight()];
56459 * Ext JS Library 1.1.1
56460 * Copyright(c) 2006-2007, Ext JS, LLC.
56462 * Originally Released Under LGPL - original licence link has changed is not relivant.
56465 * <script type="text/javascript">
56468 * These classes are private internal classes
56470 Roo.CenterLayoutRegion = function(mgr, config){
56471 Roo.LayoutRegion.call(this, mgr, config, "center");
56472 this.visible = true;
56473 this.minWidth = config.minWidth || 20;
56474 this.minHeight = config.minHeight || 20;
56477 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
56479 // center panel can't be hidden
56483 // center panel can't be hidden
56486 getMinWidth: function(){
56487 return this.minWidth;
56490 getMinHeight: function(){
56491 return this.minHeight;
56496 Roo.NorthLayoutRegion = function(mgr, config){
56497 Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
56499 this.split.placement = Roo.SplitBar.TOP;
56500 this.split.orientation = Roo.SplitBar.VERTICAL;
56501 this.split.el.addClass("x-layout-split-v");
56503 var size = config.initialSize || config.height;
56504 if(typeof size != "undefined"){
56505 this.el.setHeight(size);
56508 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
56509 orientation: Roo.SplitBar.VERTICAL,
56510 getBox : function(){
56511 if(this.collapsed){
56512 return this.collapsedEl.getBox();
56514 var box = this.el.getBox();
56516 box.height += this.split.el.getHeight();
56521 updateBox : function(box){
56522 if(this.split && !this.collapsed){
56523 box.height -= this.split.el.getHeight();
56524 this.split.el.setLeft(box.x);
56525 this.split.el.setTop(box.y+box.height);
56526 this.split.el.setWidth(box.width);
56528 if(this.collapsed){
56529 this.updateBody(box.width, null);
56531 Roo.LayoutRegion.prototype.updateBox.call(this, box);
56535 Roo.SouthLayoutRegion = function(mgr, config){
56536 Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
56538 this.split.placement = Roo.SplitBar.BOTTOM;
56539 this.split.orientation = Roo.SplitBar.VERTICAL;
56540 this.split.el.addClass("x-layout-split-v");
56542 var size = config.initialSize || config.height;
56543 if(typeof size != "undefined"){
56544 this.el.setHeight(size);
56547 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
56548 orientation: Roo.SplitBar.VERTICAL,
56549 getBox : function(){
56550 if(this.collapsed){
56551 return this.collapsedEl.getBox();
56553 var box = this.el.getBox();
56555 var sh = this.split.el.getHeight();
56562 updateBox : function(box){
56563 if(this.split && !this.collapsed){
56564 var sh = this.split.el.getHeight();
56567 this.split.el.setLeft(box.x);
56568 this.split.el.setTop(box.y-sh);
56569 this.split.el.setWidth(box.width);
56571 if(this.collapsed){
56572 this.updateBody(box.width, null);
56574 Roo.LayoutRegion.prototype.updateBox.call(this, box);
56578 Roo.EastLayoutRegion = function(mgr, config){
56579 Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
56581 this.split.placement = Roo.SplitBar.RIGHT;
56582 this.split.orientation = Roo.SplitBar.HORIZONTAL;
56583 this.split.el.addClass("x-layout-split-h");
56585 var size = config.initialSize || config.width;
56586 if(typeof size != "undefined"){
56587 this.el.setWidth(size);
56590 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
56591 orientation: Roo.SplitBar.HORIZONTAL,
56592 getBox : function(){
56593 if(this.collapsed){
56594 return this.collapsedEl.getBox();
56596 var box = this.el.getBox();
56598 var sw = this.split.el.getWidth();
56605 updateBox : function(box){
56606 if(this.split && !this.collapsed){
56607 var sw = this.split.el.getWidth();
56609 this.split.el.setLeft(box.x);
56610 this.split.el.setTop(box.y);
56611 this.split.el.setHeight(box.height);
56614 if(this.collapsed){
56615 this.updateBody(null, box.height);
56617 Roo.LayoutRegion.prototype.updateBox.call(this, box);
56621 Roo.WestLayoutRegion = function(mgr, config){
56622 Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
56624 this.split.placement = Roo.SplitBar.LEFT;
56625 this.split.orientation = Roo.SplitBar.HORIZONTAL;
56626 this.split.el.addClass("x-layout-split-h");
56628 var size = config.initialSize || config.width;
56629 if(typeof size != "undefined"){
56630 this.el.setWidth(size);
56633 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
56634 orientation: Roo.SplitBar.HORIZONTAL,
56635 getBox : function(){
56636 if(this.collapsed){
56637 return this.collapsedEl.getBox();
56639 var box = this.el.getBox();
56641 box.width += this.split.el.getWidth();
56646 updateBox : function(box){
56647 if(this.split && !this.collapsed){
56648 var sw = this.split.el.getWidth();
56650 this.split.el.setLeft(box.x+box.width);
56651 this.split.el.setTop(box.y);
56652 this.split.el.setHeight(box.height);
56654 if(this.collapsed){
56655 this.updateBody(null, box.height);
56657 Roo.LayoutRegion.prototype.updateBox.call(this, box);
56662 * Ext JS Library 1.1.1
56663 * Copyright(c) 2006-2007, Ext JS, LLC.
56665 * Originally Released Under LGPL - original licence link has changed is not relivant.
56668 * <script type="text/javascript">
56673 * Private internal class for reading and applying state
56675 Roo.LayoutStateManager = function(layout){
56676 // default empty state
56685 Roo.LayoutStateManager.prototype = {
56686 init : function(layout, provider){
56687 this.provider = provider;
56688 var state = provider.get(layout.id+"-layout-state");
56690 var wasUpdating = layout.isUpdating();
56692 layout.beginUpdate();
56694 for(var key in state){
56695 if(typeof state[key] != "function"){
56696 var rstate = state[key];
56697 var r = layout.getRegion(key);
56700 r.resizeTo(rstate.size);
56702 if(rstate.collapsed == true){
56705 r.expand(null, true);
56711 layout.endUpdate();
56713 this.state = state;
56715 this.layout = layout;
56716 layout.on("regionresized", this.onRegionResized, this);
56717 layout.on("regioncollapsed", this.onRegionCollapsed, this);
56718 layout.on("regionexpanded", this.onRegionExpanded, this);
56721 storeState : function(){
56722 this.provider.set(this.layout.id+"-layout-state", this.state);
56725 onRegionResized : function(region, newSize){
56726 this.state[region.getPosition()].size = newSize;
56730 onRegionCollapsed : function(region){
56731 this.state[region.getPosition()].collapsed = true;
56735 onRegionExpanded : function(region){
56736 this.state[region.getPosition()].collapsed = false;
56741 * Ext JS Library 1.1.1
56742 * Copyright(c) 2006-2007, Ext JS, LLC.
56744 * Originally Released Under LGPL - original licence link has changed is not relivant.
56747 * <script type="text/javascript">
56750 * @class Roo.ContentPanel
56751 * @extends Roo.util.Observable
56752 * @children Roo.form.Form Roo.JsonView Roo.View
56753 * @parent Roo.BorderLayout Roo.LayoutDialog builder
56754 * A basic ContentPanel element.
56755 * @cfg {Boolean} fitToFrame True for this panel to adjust its size to fit when the region resizes (defaults to false)
56756 * @cfg {Boolean} fitContainer When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container (defaults to false)
56757 * @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
56758 * @cfg {Boolean} closable True if the panel can be closed/removed
56759 * @cfg {Boolean} background True if the panel should not be activated when it is added (defaults to false)
56760 * @cfg {String|HTMLElement|Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
56761 * @cfg {Roo.Toolbar} toolbar A toolbar for this panel
56762 * @cfg {Boolean} autoScroll True to scroll overflow in this panel (use with {@link #fitToFrame})
56763 * @cfg {String} title The title for this panel
56764 * @cfg {Array} adjustments Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
56765 * @cfg {String} url Calls {@link #setUrl} with this value
56766 * @cfg {String} region (center|north|south|east|west) [required] which region to put this panel on (when used with xtype constructors)
56767 * @cfg {String|Object} params When used with {@link #url}, calls {@link #setUrl} with this value
56768 * @cfg {Boolean} loadOnce When used with {@link #url}, calls {@link #setUrl} with this value
56769 * @cfg {String} content Raw content to fill content panel with (uses setContent on construction.)
56770 * @cfg {String} style Extra style to add to the content panel
56771 * @cfg {Roo.menu.Menu} menu popup menu
56774 * Create a new ContentPanel.
56775 * @param {String/HTMLElement/Roo.Element} el The container element for this panel
56776 * @param {String/Object} config A string to set only the title or a config object
56777 * @param {String} content (optional) Set the HTML content for this panel
56778 * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
56780 Roo.ContentPanel = function(el, config, content){
56784 if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
56788 if (config && config.parentLayout) {
56789 el = config.parentLayout.el.createChild();
56792 if(el.autoCreate){ // xtype is available if this is called from factory
56796 this.el = Roo.get(el);
56797 if(!this.el && config && config.autoCreate){
56798 if(typeof config.autoCreate == "object"){
56799 if(!config.autoCreate.id){
56800 config.autoCreate.id = config.id||el;
56802 this.el = Roo.DomHelper.append(document.body,
56803 config.autoCreate, true);
56805 this.el = Roo.DomHelper.append(document.body,
56806 {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
56811 this.closable = false;
56812 this.loaded = false;
56813 this.active = false;
56814 if(typeof config == "string"){
56815 this.title = config;
56817 Roo.apply(this, config);
56820 if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
56821 this.wrapEl = this.el.wrap();
56822 this.toolbar.container = this.el.insertSibling(false, 'before');
56823 this.toolbar = new Roo.Toolbar(this.toolbar);
56826 // xtype created footer. - not sure if will work as we normally have to render first..
56827 if (this.footer && !this.footer.el && this.footer.xtype) {
56828 if (!this.wrapEl) {
56829 this.wrapEl = this.el.wrap();
56832 this.footer.container = this.wrapEl.createChild();
56834 this.footer = Roo.factory(this.footer, Roo);
56839 this.resizeEl = Roo.get(this.resizeEl, true);
56841 this.resizeEl = this.el;
56843 // handle view.xtype
56851 * Fires when this panel is activated.
56852 * @param {Roo.ContentPanel} this
56856 * @event deactivate
56857 * Fires when this panel is activated.
56858 * @param {Roo.ContentPanel} this
56860 "deactivate" : true,
56864 * Fires when this panel is resized if fitToFrame is true.
56865 * @param {Roo.ContentPanel} this
56866 * @param {Number} width The width after any component adjustments
56867 * @param {Number} height The height after any component adjustments
56873 * Fires when this tab is created
56874 * @param {Roo.ContentPanel} this
56884 if(this.autoScroll){
56885 this.resizeEl.setStyle("overflow", "auto");
56887 // fix randome scrolling
56888 this.el.on('scroll', function() {
56889 Roo.log('fix random scolling');
56890 this.scrollTo('top',0);
56893 content = content || this.content;
56895 this.setContent(content);
56897 if(config && config.url){
56898 this.setUrl(this.url, this.params, this.loadOnce);
56903 Roo.ContentPanel.superclass.constructor.call(this);
56905 if (this.view && typeof(this.view.xtype) != 'undefined') {
56906 this.view.el = this.el.appendChild(document.createElement("div"));
56907 this.view = Roo.factory(this.view);
56908 this.view.render && this.view.render(false, '');
56912 this.fireEvent('render', this);
56915 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
56917 setRegion : function(region){
56918 this.region = region;
56920 this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
56922 this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
56927 * Returns the toolbar for this Panel if one was configured.
56928 * @return {Roo.Toolbar}
56930 getToolbar : function(){
56931 return this.toolbar;
56934 setActiveState : function(active){
56935 this.active = active;
56937 this.fireEvent("deactivate", this);
56939 this.fireEvent("activate", this);
56943 * Updates this panel's element
56944 * @param {String} content The new content
56945 * @param {Boolean} loadScripts (optional) true to look for and process scripts
56947 setContent : function(content, loadScripts){
56948 this.el.update(content, loadScripts);
56951 ignoreResize : function(w, h){
56952 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
56955 this.lastSize = {width: w, height: h};
56960 * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
56961 * @return {Roo.UpdateManager} The UpdateManager
56963 getUpdateManager : function(){
56964 return this.el.getUpdateManager();
56967 * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
56968 * @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:
56971 url: "your-url.php",
56972 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
56973 callback: yourFunction,
56974 scope: yourObject, //(optional scope)
56977 text: "Loading...",
56982 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
56983 * 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.
56984 * @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}
56985 * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
56986 * @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.
56987 * @return {Roo.ContentPanel} this
56990 var um = this.el.getUpdateManager();
56991 um.update.apply(um, arguments);
56997 * 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.
56998 * @param {String/Function} url The URL to load the content from or a function to call to get the URL
56999 * @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)
57000 * @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)
57001 * @return {Roo.UpdateManager} The UpdateManager
57003 setUrl : function(url, params, loadOnce){
57004 if(this.refreshDelegate){
57005 this.removeListener("activate", this.refreshDelegate);
57007 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
57008 this.on("activate", this.refreshDelegate);
57009 return this.el.getUpdateManager();
57012 _handleRefresh : function(url, params, loadOnce){
57013 if(!loadOnce || !this.loaded){
57014 var updater = this.el.getUpdateManager();
57015 updater.update(url, params, this._setLoaded.createDelegate(this));
57019 _setLoaded : function(){
57020 this.loaded = true;
57024 * Returns this panel's id
57027 getId : function(){
57032 * Returns this panel's element - used by regiosn to add.
57033 * @return {Roo.Element}
57035 getEl : function(){
57036 return this.wrapEl || this.el;
57039 adjustForComponents : function(width, height)
57041 //Roo.log('adjustForComponents ');
57042 if(this.resizeEl != this.el){
57043 width -= this.el.getFrameWidth('lr');
57044 height -= this.el.getFrameWidth('tb');
57047 var te = this.toolbar.getEl();
57048 height -= te.getHeight();
57049 te.setWidth(width);
57052 var te = this.footer.getEl();
57053 //Roo.log("footer:" + te.getHeight());
57055 height -= te.getHeight();
57056 te.setWidth(width);
57060 if(this.adjustments){
57061 width += this.adjustments[0];
57062 height += this.adjustments[1];
57064 return {"width": width, "height": height};
57067 setSize : function(width, height){
57068 if(this.fitToFrame && !this.ignoreResize(width, height)){
57069 if(this.fitContainer && this.resizeEl != this.el){
57070 this.el.setSize(width, height);
57072 var size = this.adjustForComponents(width, height);
57073 this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
57074 this.fireEvent('resize', this, size.width, size.height);
57079 * Returns this panel's title
57082 getTitle : function(){
57087 * Set this panel's title
57088 * @param {String} title
57090 setTitle : function(title){
57091 this.title = title;
57093 this.region.updatePanelTitle(this, title);
57098 * Returns true is this panel was configured to be closable
57099 * @return {Boolean}
57101 isClosable : function(){
57102 return this.closable;
57105 beforeSlide : function(){
57107 this.resizeEl.clip();
57110 afterSlide : function(){
57112 this.resizeEl.unclip();
57116 * Force a content refresh from the URL specified in the {@link #setUrl} method.
57117 * Will fail silently if the {@link #setUrl} method has not been called.
57118 * This does not activate the panel, just updates its content.
57120 refresh : function(){
57121 if(this.refreshDelegate){
57122 this.loaded = false;
57123 this.refreshDelegate();
57128 * Destroys this panel
57130 destroy : function(){
57131 this.el.removeAllListeners();
57132 var tempEl = document.createElement("span");
57133 tempEl.appendChild(this.el.dom);
57134 tempEl.innerHTML = "";
57140 * form - if the content panel contains a form - this is a reference to it.
57141 * @type {Roo.form.Form}
57145 * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
57146 * This contains a reference to it.
57152 * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
57162 * @param {Object} cfg Xtype definition of item to add.
57165 addxtype : function(cfg) {
57167 if (cfg.xtype.match(/^Form$/)) {
57170 //if (this.footer) {
57171 // el = this.footer.container.insertSibling(false, 'before');
57173 el = this.el.createChild();
57176 this.form = new Roo.form.Form(cfg);
57179 if ( this.form.allItems.length) {
57180 this.form.render(el.dom);
57184 // should only have one of theses..
57185 if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
57186 // views.. should not be just added - used named prop 'view''
57188 cfg.el = this.el.appendChild(document.createElement("div"));
57191 var ret = new Roo.factory(cfg);
57193 ret.render && ret.render(false, ''); // render blank..
57202 * @class Roo.GridPanel
57203 * @extends Roo.ContentPanel
57204 * @parent Roo.BorderLayout Roo.LayoutDialog builder
57206 * Create a new GridPanel.
57207 * @cfg {Roo.grid.Grid} grid The grid for this panel
57209 Roo.GridPanel = function(grid, config){
57211 // universal ctor...
57212 if (typeof(grid.grid) != 'undefined') {
57214 grid = config.grid;
57216 this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
57217 {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
57219 this.wrapper.dom.appendChild(grid.getGridEl().dom);
57221 Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
57224 this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
57226 // xtype created footer. - not sure if will work as we normally have to render first..
57227 if (this.footer && !this.footer.el && this.footer.xtype) {
57229 this.footer.container = this.grid.getView().getFooterPanel(true);
57230 this.footer.dataSource = this.grid.dataSource;
57231 this.footer = Roo.factory(this.footer, Roo);
57235 grid.monitorWindowResize = false; // turn off autosizing
57236 grid.autoHeight = false;
57237 grid.autoWidth = false;
57239 this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
57242 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
57243 getId : function(){
57244 return this.grid.id;
57248 * Returns the grid for this panel
57249 * @return {Roo.grid.Grid}
57251 getGrid : function(){
57255 setSize : function(width, height){
57256 if(!this.ignoreResize(width, height)){
57257 var grid = this.grid;
57258 var size = this.adjustForComponents(width, height);
57259 grid.getGridEl().setSize(size.width, size.height);
57264 beforeSlide : function(){
57265 this.grid.getView().scroller.clip();
57268 afterSlide : function(){
57269 this.grid.getView().scroller.unclip();
57272 destroy : function(){
57273 this.grid.destroy();
57275 Roo.GridPanel.superclass.destroy.call(this);
57281 * @class Roo.NestedLayoutPanel
57282 * @extends Roo.ContentPanel
57283 * @parent Roo.BorderLayout Roo.LayoutDialog builder
57284 * @cfg Roo.BorderLayout} layout [required] The layout for this panel
57288 * Create a new NestedLayoutPanel.
57291 * @param {Roo.BorderLayout} layout [required] The layout for this panel
57292 * @param {String/Object} config A string to set only the title or a config object
57294 Roo.NestedLayoutPanel = function(layout, config)
57296 // construct with only one argument..
57297 /* FIXME - implement nicer consturctors
57298 if (layout.layout) {
57300 layout = config.layout;
57301 delete config.layout;
57303 if (layout.xtype && !layout.getEl) {
57304 // then layout needs constructing..
57305 layout = Roo.factory(layout, Roo);
57310 Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
57312 layout.monitorWindowResize = false; // turn off autosizing
57313 this.layout = layout;
57314 this.layout.getEl().addClass("x-layout-nested-layout");
57321 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
57323 setSize : function(width, height){
57324 if(!this.ignoreResize(width, height)){
57325 var size = this.adjustForComponents(width, height);
57326 var el = this.layout.getEl();
57327 el.setSize(size.width, size.height);
57328 var touch = el.dom.offsetWidth;
57329 this.layout.layout();
57330 // ie requires a double layout on the first pass
57331 if(Roo.isIE && !this.initialized){
57332 this.initialized = true;
57333 this.layout.layout();
57338 // activate all subpanels if not currently active..
57340 setActiveState : function(active){
57341 this.active = active;
57343 this.fireEvent("deactivate", this);
57347 this.fireEvent("activate", this);
57348 // not sure if this should happen before or after..
57349 if (!this.layout) {
57350 return; // should not happen..
57353 for (var r in this.layout.regions) {
57354 reg = this.layout.getRegion(r);
57355 if (reg.getActivePanel()) {
57356 //reg.showPanel(reg.getActivePanel()); // force it to activate..
57357 reg.setActivePanel(reg.getActivePanel());
57360 if (!reg.panels.length) {
57363 reg.showPanel(reg.getPanel(0));
57372 * Returns the nested BorderLayout for this panel
57373 * @return {Roo.BorderLayout}
57375 getLayout : function(){
57376 return this.layout;
57380 * Adds a xtype elements to the layout of the nested panel
57384 xtype : 'ContentPanel',
57391 xtype : 'NestedLayoutPanel',
57397 items : [ ... list of content panels or nested layout panels.. ]
57401 * @param {Object} cfg Xtype definition of item to add.
57403 addxtype : function(cfg) {
57404 return this.layout.addxtype(cfg);
57409 Roo.ScrollPanel = function(el, config, content){
57410 config = config || {};
57411 config.fitToFrame = true;
57412 Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
57414 this.el.dom.style.overflow = "hidden";
57415 var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
57416 this.el.removeClass("x-layout-inactive-content");
57417 this.el.on("mousewheel", this.onWheel, this);
57419 var up = wrap.createChild({cls: "x-scroller-up", html: " "}, this.el.dom);
57420 var down = wrap.createChild({cls: "x-scroller-down", html: " "});
57421 up.unselectable(); down.unselectable();
57422 up.on("click", this.scrollUp, this);
57423 down.on("click", this.scrollDown, this);
57424 up.addClassOnOver("x-scroller-btn-over");
57425 down.addClassOnOver("x-scroller-btn-over");
57426 up.addClassOnClick("x-scroller-btn-click");
57427 down.addClassOnClick("x-scroller-btn-click");
57428 this.adjustments = [0, -(up.getHeight() + down.getHeight())];
57430 this.resizeEl = this.el;
57431 this.el = wrap; this.up = up; this.down = down;
57434 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
57436 wheelIncrement : 5,
57437 scrollUp : function(){
57438 this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
57441 scrollDown : function(){
57442 this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
57445 afterScroll : function(){
57446 var el = this.resizeEl;
57447 var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
57448 this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
57449 this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
57452 setSize : function(){
57453 Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
57454 this.afterScroll();
57457 onWheel : function(e){
57458 var d = e.getWheelDelta();
57459 this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
57460 this.afterScroll();
57464 setContent : function(content, loadScripts){
57465 this.resizeEl.update(content, loadScripts);
57473 * @class Roo.TreePanel
57474 * @extends Roo.ContentPanel
57475 * @parent Roo.BorderLayout Roo.LayoutDialog builder
57476 * Treepanel component
57479 * Create a new TreePanel. - defaults to fit/scoll contents.
57480 * @param {String/Object} config A string to set only the panel's title, or a config object
57482 Roo.TreePanel = function(config){
57483 var el = config.el;
57484 var tree = config.tree;
57485 delete config.tree;
57486 delete config.el; // hopefull!
57488 // wrapper for IE7 strict & safari scroll issue
57490 var treeEl = el.createChild();
57491 config.resizeEl = treeEl;
57495 Roo.TreePanel.superclass.constructor.call(this, el, config);
57498 this.tree = new Roo.tree.TreePanel(treeEl , tree);
57499 //console.log(tree);
57500 this.on('activate', function()
57502 if (this.tree.rendered) {
57505 //console.log('render tree');
57506 this.tree.render();
57508 // this should not be needed.. - it's actually the 'el' that resizes?
57509 // actuall it breaks the containerScroll - dragging nodes auto scroll at top
57511 //this.on('resize', function (cp, w, h) {
57512 // this.tree.innerCt.setWidth(w);
57513 // this.tree.innerCt.setHeight(h);
57514 // //this.tree.innerCt.setStyle('overflow-y', 'auto');
57521 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {
57525 * @cfg {Roo.tree.TreePanel} tree [required] The tree TreePanel, with config etc.
57543 * Ext JS Library 1.1.1
57544 * Copyright(c) 2006-2007, Ext JS, LLC.
57546 * Originally Released Under LGPL - original licence link has changed is not relivant.
57549 * <script type="text/javascript">
57554 * @class Roo.ReaderLayout
57555 * @extends Roo.BorderLayout
57556 * This is a pre-built layout that represents a classic, 5-pane application. It consists of a header, a primary
57557 * center region containing two nested regions (a top one for a list view and one for item preview below),
57558 * and regions on either side that can be used for navigation, application commands, informational displays, etc.
57559 * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
57560 * expedites the setup of the overall layout and regions for this common application style.
57563 var reader = new Roo.ReaderLayout();
57564 var CP = Roo.ContentPanel; // shortcut for adding
57566 reader.beginUpdate();
57567 reader.add("north", new CP("north", "North"));
57568 reader.add("west", new CP("west", {title: "West"}));
57569 reader.add("east", new CP("east", {title: "East"}));
57571 reader.regions.listView.add(new CP("listView", "List"));
57572 reader.regions.preview.add(new CP("preview", "Preview"));
57573 reader.endUpdate();
57576 * Create a new ReaderLayout
57577 * @param {Object} config Configuration options
57578 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
57579 * document.body if omitted)
57581 Roo.ReaderLayout = function(config, renderTo){
57582 var c = config || {size:{}};
57583 Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
57584 north: c.north !== false ? Roo.apply({
57588 }, c.north) : false,
57589 west: c.west !== false ? Roo.apply({
57597 margins:{left:5,right:0,bottom:5,top:5},
57598 cmargins:{left:5,right:5,bottom:5,top:5}
57599 }, c.west) : false,
57600 east: c.east !== false ? Roo.apply({
57608 margins:{left:0,right:5,bottom:5,top:5},
57609 cmargins:{left:5,right:5,bottom:5,top:5}
57610 }, c.east) : false,
57611 center: Roo.apply({
57612 tabPosition: 'top',
57616 margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
57620 this.el.addClass('x-reader');
57622 this.beginUpdate();
57624 var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
57625 south: c.preview !== false ? Roo.apply({
57632 cmargins:{top:5,left:0, right:0, bottom:0}
57633 }, c.preview) : false,
57634 center: Roo.apply({
57640 this.add('center', new Roo.NestedLayoutPanel(inner,
57641 Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
57645 this.regions.preview = inner.getRegion('south');
57646 this.regions.listView = inner.getRegion('center');
57649 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
57651 * Ext JS Library 1.1.1
57652 * Copyright(c) 2006-2007, Ext JS, LLC.
57654 * Originally Released Under LGPL - original licence link has changed is not relivant.
57657 * <script type="text/javascript">
57661 * @class Roo.grid.Grid
57662 * @extends Roo.util.Observable
57663 * This class represents the primary interface of a component based grid control.
57664 * <br><br>Usage:<pre><code>
57665 var grid = new Roo.grid.Grid("my-container-id", {
57668 selModel: mySelectionModel,
57669 autoSizeColumns: true,
57670 monitorWindowResize: false,
57671 trackMouseOver: true
57676 * <b>Common Problems:</b><br/>
57677 * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
57678 * element will correct this<br/>
57679 * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
57680 * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
57681 * are unpredictable.<br/>
57682 * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
57683 * grid to calculate dimensions/offsets.<br/>
57685 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
57686 * The container MUST have some type of size defined for the grid to fill. The container will be
57687 * automatically set to position relative if it isn't already.
57688 * @param {Object} config A config object that sets properties on this grid.
57690 Roo.grid.Grid = function(container, config){
57691 // initialize the container
57692 this.container = Roo.get(container);
57693 this.container.update("");
57694 this.container.setStyle("overflow", "hidden");
57695 this.container.addClass('x-grid-container');
57697 this.id = this.container.id;
57699 Roo.apply(this, config);
57700 // check and correct shorthanded configs
57702 this.dataSource = this.ds;
57706 this.colModel = this.cm;
57710 this.selModel = this.sm;
57714 if (this.selModel) {
57715 this.selModel = Roo.factory(this.selModel, Roo.grid);
57716 this.sm = this.selModel;
57717 this.sm.xmodule = this.xmodule || false;
57719 if (typeof(this.colModel.config) == 'undefined') {
57720 this.colModel = new Roo.grid.ColumnModel(this.colModel);
57721 this.cm = this.colModel;
57722 this.cm.xmodule = this.xmodule || false;
57724 if (this.dataSource) {
57725 this.dataSource= Roo.factory(this.dataSource, Roo.data);
57726 this.ds = this.dataSource;
57727 this.ds.xmodule = this.xmodule || false;
57734 this.container.setWidth(this.width);
57738 this.container.setHeight(this.height);
57745 * The raw click event for the entire grid.
57746 * @param {Roo.EventObject} e
57751 * The raw dblclick event for the entire grid.
57752 * @param {Roo.EventObject} e
57756 * @event contextmenu
57757 * The raw contextmenu event for the entire grid.
57758 * @param {Roo.EventObject} e
57760 "contextmenu" : true,
57763 * The raw mousedown event for the entire grid.
57764 * @param {Roo.EventObject} e
57766 "mousedown" : true,
57769 * The raw mouseup event for the entire grid.
57770 * @param {Roo.EventObject} e
57775 * The raw mouseover event for the entire grid.
57776 * @param {Roo.EventObject} e
57778 "mouseover" : true,
57781 * The raw mouseout event for the entire grid.
57782 * @param {Roo.EventObject} e
57787 * The raw keypress event for the entire grid.
57788 * @param {Roo.EventObject} e
57793 * The raw keydown event for the entire grid.
57794 * @param {Roo.EventObject} e
57802 * Fires when a cell is clicked
57803 * @param {Grid} this
57804 * @param {Number} rowIndex
57805 * @param {Number} columnIndex
57806 * @param {Roo.EventObject} e
57808 "cellclick" : true,
57810 * @event celldblclick
57811 * Fires when a cell is double clicked
57812 * @param {Grid} this
57813 * @param {Number} rowIndex
57814 * @param {Number} columnIndex
57815 * @param {Roo.EventObject} e
57817 "celldblclick" : true,
57820 * Fires when a row is clicked
57821 * @param {Grid} this
57822 * @param {Number} rowIndex
57823 * @param {Roo.EventObject} e
57827 * @event rowdblclick
57828 * Fires when a row is double clicked
57829 * @param {Grid} this
57830 * @param {Number} rowIndex
57831 * @param {Roo.EventObject} e
57833 "rowdblclick" : true,
57835 * @event headerclick
57836 * Fires when a header is clicked
57837 * @param {Grid} this
57838 * @param {Number} columnIndex
57839 * @param {Roo.EventObject} e
57841 "headerclick" : true,
57843 * @event headerdblclick
57844 * Fires when a header cell is double clicked
57845 * @param {Grid} this
57846 * @param {Number} columnIndex
57847 * @param {Roo.EventObject} e
57849 "headerdblclick" : true,
57851 * @event rowcontextmenu
57852 * Fires when a row is right clicked
57853 * @param {Grid} this
57854 * @param {Number} rowIndex
57855 * @param {Roo.EventObject} e
57857 "rowcontextmenu" : true,
57859 * @event cellcontextmenu
57860 * Fires when a cell is right clicked
57861 * @param {Grid} this
57862 * @param {Number} rowIndex
57863 * @param {Number} cellIndex
57864 * @param {Roo.EventObject} e
57866 "cellcontextmenu" : true,
57868 * @event headercontextmenu
57869 * Fires when a header is right clicked
57870 * @param {Grid} this
57871 * @param {Number} columnIndex
57872 * @param {Roo.EventObject} e
57874 "headercontextmenu" : true,
57876 * @event bodyscroll
57877 * Fires when the body element is scrolled
57878 * @param {Number} scrollLeft
57879 * @param {Number} scrollTop
57881 "bodyscroll" : true,
57883 * @event columnresize
57884 * Fires when the user resizes a column
57885 * @param {Number} columnIndex
57886 * @param {Number} newSize
57888 "columnresize" : true,
57890 * @event columnmove
57891 * Fires when the user moves a column
57892 * @param {Number} oldIndex
57893 * @param {Number} newIndex
57895 "columnmove" : true,
57898 * Fires when row(s) start being dragged
57899 * @param {Grid} this
57900 * @param {Roo.GridDD} dd The drag drop object
57901 * @param {event} e The raw browser event
57903 "startdrag" : true,
57906 * Fires when a drag operation is complete
57907 * @param {Grid} this
57908 * @param {Roo.GridDD} dd The drag drop object
57909 * @param {event} e The raw browser event
57914 * Fires when dragged row(s) are dropped on a valid DD target
57915 * @param {Grid} this
57916 * @param {Roo.GridDD} dd The drag drop object
57917 * @param {String} targetId The target drag drop object
57918 * @param {event} e The raw browser event
57923 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
57924 * @param {Grid} this
57925 * @param {Roo.GridDD} dd The drag drop object
57926 * @param {String} targetId The target drag drop object
57927 * @param {event} e The raw browser event
57932 * Fires when the dragged row(s) first cross another DD target while being dragged
57933 * @param {Grid} this
57934 * @param {Roo.GridDD} dd The drag drop object
57935 * @param {String} targetId The target drag drop object
57936 * @param {event} e The raw browser event
57938 "dragenter" : true,
57941 * Fires when the dragged row(s) leave another DD target while being dragged
57942 * @param {Grid} this
57943 * @param {Roo.GridDD} dd The drag drop object
57944 * @param {String} targetId The target drag drop object
57945 * @param {event} e The raw browser event
57950 * Fires when a row is rendered, so you can change add a style to it.
57951 * @param {GridView} gridview The grid view
57952 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
57958 * Fires when the grid is rendered
57959 * @param {Grid} grid
57964 Roo.grid.Grid.superclass.constructor.call(this);
57966 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
57969 * @cfg {Roo.grid.AbstractSelectionModel} sm The selection Model (default = Roo.grid.RowSelectionModel)
57972 * @cfg {Roo.grid.GridView} view The view that renders the grid (default = Roo.grid.GridView)
57975 * @cfg {Roo.grid.ColumnModel} cm[] The columns of the grid
57978 * @cfg {Roo.grid.Store} ds The data store for the grid
57981 * @cfg {Roo.Toolbar} toolbar a toolbar for buttons etc.
57984 * @cfg {String} ddGroup - drag drop group.
57987 * @cfg {String} dragGroup - drag group (?? not sure if needed.)
57991 * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
57993 minColumnWidth : 25,
57996 * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
57997 * <b>on initial render.</b> It is more efficient to explicitly size the columns
57998 * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option. Default is false.
58000 autoSizeColumns : false,
58003 * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
58005 autoSizeHeaders : true,
58008 * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
58010 monitorWindowResize : true,
58013 * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
58014 * rows measured to get a columns size. Default is 0 (all rows).
58016 maxRowsToMeasure : 0,
58019 * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
58021 trackMouseOver : true,
58024 * @cfg {Boolean} enableDrag True to enable drag of rows. Default is false. (double check if this is needed?)
58027 * @cfg {Boolean} enableDrop True to enable drop of elements. Default is false. (double check if this is needed?)
58031 * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
58033 enableDragDrop : false,
58036 * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
58038 enableColumnMove : true,
58041 * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
58043 enableColumnHide : true,
58046 * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
58048 enableRowHeightSync : false,
58051 * @cfg {Boolean} stripeRows True to stripe the rows. Default is true.
58056 * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
58058 autoHeight : false,
58061 * @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.
58063 autoExpandColumn : false,
58066 * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
58069 autoExpandMin : 50,
58072 * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
58074 autoExpandMax : 1000,
58077 * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
58082 * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
58086 * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
58090 * @cfg {boolean} sortColMenu Sort the column order menu when it shows (usefull for long lists..) default false
58092 sortColMenu : false,
58098 * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
58099 * of a fixed width. Default is false.
58102 * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
58107 * @cfg {String} ddText Configures the text is the drag proxy (defaults to "%0 selected row(s)").
58108 * %0 is replaced with the number of selected rows.
58110 ddText : "{0} selected row{1}",
58114 * Called once after all setup has been completed and the grid is ready to be rendered.
58115 * @return {Roo.grid.Grid} this
58117 render : function()
58119 var c = this.container;
58120 // try to detect autoHeight/width mode
58121 if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
58122 this.autoHeight = true;
58124 var view = this.getView();
58127 c.on("click", this.onClick, this);
58128 c.on("dblclick", this.onDblClick, this);
58129 c.on("contextmenu", this.onContextMenu, this);
58130 c.on("keydown", this.onKeyDown, this);
58132 c.on("touchstart", this.onTouchStart, this);
58135 this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
58137 this.getSelectionModel().init(this);
58142 this.loadMask = new Roo.LoadMask(this.container,
58143 Roo.apply({store:this.dataSource}, this.loadMask));
58147 if (this.toolbar && this.toolbar.xtype) {
58148 this.toolbar.container = this.getView().getHeaderPanel(true);
58149 this.toolbar = new Roo.Toolbar(this.toolbar);
58151 if (this.footer && this.footer.xtype) {
58152 this.footer.dataSource = this.getDataSource();
58153 this.footer.container = this.getView().getFooterPanel(true);
58154 this.footer = Roo.factory(this.footer, Roo);
58156 if (this.dropTarget && this.dropTarget.xtype) {
58157 delete this.dropTarget.xtype;
58158 this.dropTarget = new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
58162 this.rendered = true;
58163 this.fireEvent('render', this);
58168 * Reconfigures the grid to use a different Store and Column Model.
58169 * The View will be bound to the new objects and refreshed.
58170 * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
58171 * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
58173 reconfigure : function(dataSource, colModel){
58175 this.loadMask.destroy();
58176 this.loadMask = new Roo.LoadMask(this.container,
58177 Roo.apply({store:dataSource}, this.loadMask));
58179 this.view.bind(dataSource, colModel);
58180 this.dataSource = dataSource;
58181 this.colModel = colModel;
58182 this.view.refresh(true);
58186 * Add's a column, default at the end..
58188 * @param {int} position to add (default end)
58189 * @param {Array} of objects of column configuration see {@link Roo.grid.ColumnModel}
58191 addColumns : function(pos, ar)
58194 for (var i =0;i< ar.length;i++) {
58196 cfg.id = typeof(cfg.id) == 'undefined' ? Roo.id() : cfg.id; // don't normally use this..
58197 this.cm.lookup[cfg.id] = cfg;
58201 if (typeof(pos) == 'undefined' || pos >= this.cm.config.length) {
58202 pos = this.cm.config.length; //this.cm.config.push(cfg);
58204 pos = Math.max(0,pos);
58207 this.cm.config.splice.apply(this.cm.config, ar);
58211 this.view.generateRules(this.cm);
58212 this.view.refresh(true);
58220 onKeyDown : function(e){
58221 this.fireEvent("keydown", e);
58225 * Destroy this grid.
58226 * @param {Boolean} removeEl True to remove the element
58228 destroy : function(removeEl, keepListeners){
58230 this.loadMask.destroy();
58232 var c = this.container;
58233 c.removeAllListeners();
58234 this.view.destroy();
58235 this.colModel.purgeListeners();
58236 if(!keepListeners){
58237 this.purgeListeners();
58240 if(removeEl === true){
58246 processEvent : function(name, e){
58247 // does this fire select???
58248 //Roo.log('grid:processEvent ' + name);
58250 if (name != 'touchstart' ) {
58251 this.fireEvent(name, e);
58254 var t = e.getTarget();
58256 var header = v.findHeaderIndex(t);
58257 if(header !== false){
58258 var ename = name == 'touchstart' ? 'click' : name;
58260 this.fireEvent("header" + ename, this, header, e);
58262 var row = v.findRowIndex(t);
58263 var cell = v.findCellIndex(t);
58264 if (name == 'touchstart') {
58265 // first touch is always a click.
58266 // hopefull this happens after selection is updated.?
58269 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
58270 var cs = this.selModel.getSelectedCell();
58271 if (row == cs[0] && cell == cs[1]){
58275 if (typeof(this.selModel.getSelections) != 'undefined') {
58276 var cs = this.selModel.getSelections();
58277 var ds = this.dataSource;
58278 if (cs.length == 1 && ds.getAt(row) == cs[0]){
58289 this.fireEvent("row" + name, this, row, e);
58290 if(cell !== false){
58291 this.fireEvent("cell" + name, this, row, cell, e);
58298 onClick : function(e){
58299 this.processEvent("click", e);
58302 onTouchStart : function(e){
58303 this.processEvent("touchstart", e);
58307 onContextMenu : function(e, t){
58308 this.processEvent("contextmenu", e);
58312 onDblClick : function(e){
58313 this.processEvent("dblclick", e);
58317 walkCells : function(row, col, step, fn, scope){
58318 var cm = this.colModel, clen = cm.getColumnCount();
58319 var ds = this.dataSource, rlen = ds.getCount(), first = true;
58331 if(fn.call(scope || this, row, col, cm) === true){
58349 if(fn.call(scope || this, row, col, cm) === true){
58361 getSelections : function(){
58362 return this.selModel.getSelections();
58366 * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
58367 * but if manual update is required this method will initiate it.
58369 autoSize : function(){
58371 this.view.layout();
58372 if(this.view.adjustForScroll){
58373 this.view.adjustForScroll();
58379 * Returns the grid's underlying element.
58380 * @return {Element} The element
58382 getGridEl : function(){
58383 return this.container;
58386 // private for compatibility, overridden by editor grid
58387 stopEditing : function(){},
58390 * Returns the grid's SelectionModel.
58391 * @return {SelectionModel}
58393 getSelectionModel : function(){
58394 if(!this.selModel){
58395 this.selModel = new Roo.grid.RowSelectionModel();
58397 return this.selModel;
58401 * Returns the grid's DataSource.
58402 * @return {DataSource}
58404 getDataSource : function(){
58405 return this.dataSource;
58409 * Returns the grid's ColumnModel.
58410 * @return {ColumnModel}
58412 getColumnModel : function(){
58413 return this.colModel;
58417 * Returns the grid's GridView object.
58418 * @return {GridView}
58420 getView : function(){
58422 this.view = new Roo.grid.GridView(this.viewConfig);
58423 this.relayEvents(this.view, [
58424 "beforerowremoved", "beforerowsinserted",
58425 "beforerefresh", "rowremoved",
58426 "rowsinserted", "rowupdated" ,"refresh"
58432 * Called to get grid's drag proxy text, by default returns this.ddText.
58433 * Override this to put something different in the dragged text.
58436 getDragDropText : function(){
58437 var count = this.selModel.getCount();
58438 return String.format(this.ddText, count, count == 1 ? '' : 's');
58443 * Ext JS Library 1.1.1
58444 * Copyright(c) 2006-2007, Ext JS, LLC.
58446 * Originally Released Under LGPL - original licence link has changed is not relivant.
58449 * <script type="text/javascript">
58452 * @class Roo.grid.AbstractGridView
58453 * @extends Roo.util.Observable
58455 * Abstract base class for grid Views
58458 Roo.grid.AbstractGridView = function(){
58462 "beforerowremoved" : true,
58463 "beforerowsinserted" : true,
58464 "beforerefresh" : true,
58465 "rowremoved" : true,
58466 "rowsinserted" : true,
58467 "rowupdated" : true,
58470 Roo.grid.AbstractGridView.superclass.constructor.call(this);
58473 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
58474 rowClass : "x-grid-row",
58475 cellClass : "x-grid-cell",
58476 tdClass : "x-grid-td",
58477 hdClass : "x-grid-hd",
58478 splitClass : "x-grid-hd-split",
58480 init: function(grid){
58482 var cid = this.grid.getGridEl().id;
58483 this.colSelector = "#" + cid + " ." + this.cellClass + "-";
58484 this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
58485 this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
58486 this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
58489 getColumnRenderers : function(){
58490 var renderers = [];
58491 var cm = this.grid.colModel;
58492 var colCount = cm.getColumnCount();
58493 for(var i = 0; i < colCount; i++){
58494 renderers[i] = cm.getRenderer(i);
58499 getColumnIds : function(){
58501 var cm = this.grid.colModel;
58502 var colCount = cm.getColumnCount();
58503 for(var i = 0; i < colCount; i++){
58504 ids[i] = cm.getColumnId(i);
58509 getDataIndexes : function(){
58510 if(!this.indexMap){
58511 this.indexMap = this.buildIndexMap();
58513 return this.indexMap.colToData;
58516 getColumnIndexByDataIndex : function(dataIndex){
58517 if(!this.indexMap){
58518 this.indexMap = this.buildIndexMap();
58520 return this.indexMap.dataToCol[dataIndex];
58524 * Set a css style for a column dynamically.
58525 * @param {Number} colIndex The index of the column
58526 * @param {String} name The css property name
58527 * @param {String} value The css value
58529 setCSSStyle : function(colIndex, name, value){
58530 var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
58531 Roo.util.CSS.updateRule(selector, name, value);
58534 generateRules : function(cm){
58535 var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
58536 Roo.util.CSS.removeStyleSheet(rulesId);
58537 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
58538 var cid = cm.getColumnId(i);
58539 ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
58540 this.tdSelector, cid, " {\n}\n",
58541 this.hdSelector, cid, " {\n}\n",
58542 this.splitSelector, cid, " {\n}\n");
58544 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
58548 * Ext JS Library 1.1.1
58549 * Copyright(c) 2006-2007, Ext JS, LLC.
58551 * Originally Released Under LGPL - original licence link has changed is not relivant.
58554 * <script type="text/javascript">
58558 // This is a support class used internally by the Grid components
58559 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
58561 this.view = grid.getView();
58562 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
58563 Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
58565 this.setHandleElId(Roo.id(hd));
58566 this.setOuterHandleElId(Roo.id(hd2));
58568 this.scroll = false;
58570 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
58572 getDragData : function(e){
58573 var t = Roo.lib.Event.getTarget(e);
58574 var h = this.view.findHeaderCell(t);
58576 return {ddel: h.firstChild, header:h};
58581 onInitDrag : function(e){
58582 this.view.headersDisabled = true;
58583 var clone = this.dragData.ddel.cloneNode(true);
58584 clone.id = Roo.id();
58585 clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
58586 this.proxy.update(clone);
58590 afterValidDrop : function(){
58592 setTimeout(function(){
58593 v.headersDisabled = false;
58597 afterInvalidDrop : function(){
58599 setTimeout(function(){
58600 v.headersDisabled = false;
58606 * Ext JS Library 1.1.1
58607 * Copyright(c) 2006-2007, Ext JS, LLC.
58609 * Originally Released Under LGPL - original licence link has changed is not relivant.
58612 * <script type="text/javascript">
58615 // This is a support class used internally by the Grid components
58616 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
58618 this.view = grid.getView();
58619 // split the proxies so they don't interfere with mouse events
58620 this.proxyTop = Roo.DomHelper.append(document.body, {
58621 cls:"col-move-top", html:" "
58623 this.proxyBottom = Roo.DomHelper.append(document.body, {
58624 cls:"col-move-bottom", html:" "
58626 this.proxyTop.hide = this.proxyBottom.hide = function(){
58627 this.setLeftTop(-100,-100);
58628 this.setStyle("visibility", "hidden");
58630 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
58631 // temporarily disabled
58632 //Roo.dd.ScrollManager.register(this.view.scroller.dom);
58633 Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
58635 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
58636 proxyOffsets : [-4, -9],
58637 fly: Roo.Element.fly,
58639 getTargetFromEvent : function(e){
58640 var t = Roo.lib.Event.getTarget(e);
58641 var cindex = this.view.findCellIndex(t);
58642 if(cindex !== false){
58643 return this.view.getHeaderCell(cindex);
58648 nextVisible : function(h){
58649 var v = this.view, cm = this.grid.colModel;
58652 if(!cm.isHidden(v.getCellIndex(h))){
58660 prevVisible : function(h){
58661 var v = this.view, cm = this.grid.colModel;
58664 if(!cm.isHidden(v.getCellIndex(h))){
58672 positionIndicator : function(h, n, e){
58673 var x = Roo.lib.Event.getPageX(e);
58674 var r = Roo.lib.Dom.getRegion(n.firstChild);
58675 var px, pt, py = r.top + this.proxyOffsets[1];
58676 if((r.right - x) <= (r.right-r.left)/2){
58677 px = r.right+this.view.borderWidth;
58683 var oldIndex = this.view.getCellIndex(h);
58684 var newIndex = this.view.getCellIndex(n);
58686 if(this.grid.colModel.isFixed(newIndex)){
58690 var locked = this.grid.colModel.isLocked(newIndex);
58695 if(oldIndex < newIndex){
58698 if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
58701 px += this.proxyOffsets[0];
58702 this.proxyTop.setLeftTop(px, py);
58703 this.proxyTop.show();
58704 if(!this.bottomOffset){
58705 this.bottomOffset = this.view.mainHd.getHeight();
58707 this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
58708 this.proxyBottom.show();
58712 onNodeEnter : function(n, dd, e, data){
58713 if(data.header != n){
58714 this.positionIndicator(data.header, n, e);
58718 onNodeOver : function(n, dd, e, data){
58719 var result = false;
58720 if(data.header != n){
58721 result = this.positionIndicator(data.header, n, e);
58724 this.proxyTop.hide();
58725 this.proxyBottom.hide();
58727 return result ? this.dropAllowed : this.dropNotAllowed;
58730 onNodeOut : function(n, dd, e, data){
58731 this.proxyTop.hide();
58732 this.proxyBottom.hide();
58735 onNodeDrop : function(n, dd, e, data){
58736 var h = data.header;
58738 var cm = this.grid.colModel;
58739 var x = Roo.lib.Event.getPageX(e);
58740 var r = Roo.lib.Dom.getRegion(n.firstChild);
58741 var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
58742 var oldIndex = this.view.getCellIndex(h);
58743 var newIndex = this.view.getCellIndex(n);
58744 var locked = cm.isLocked(newIndex);
58748 if(oldIndex < newIndex){
58751 if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
58754 cm.setLocked(oldIndex, locked, true);
58755 cm.moveColumn(oldIndex, newIndex);
58756 this.grid.fireEvent("columnmove", oldIndex, newIndex);
58764 * Ext JS Library 1.1.1
58765 * Copyright(c) 2006-2007, Ext JS, LLC.
58767 * Originally Released Under LGPL - original licence link has changed is not relivant.
58770 * <script type="text/javascript">
58774 * @class Roo.grid.GridView
58775 * @extends Roo.util.Observable
58778 * @param {Object} config
58780 Roo.grid.GridView = function(config){
58781 Roo.grid.GridView.superclass.constructor.call(this);
58784 Roo.apply(this, config);
58787 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
58789 unselectable : 'unselectable="on"',
58790 unselectableCls : 'x-unselectable',
58793 rowClass : "x-grid-row",
58795 cellClass : "x-grid-col",
58797 tdClass : "x-grid-td",
58799 hdClass : "x-grid-hd",
58801 splitClass : "x-grid-split",
58803 sortClasses : ["sort-asc", "sort-desc"],
58805 enableMoveAnim : false,
58809 dh : Roo.DomHelper,
58811 fly : Roo.Element.fly,
58813 css : Roo.util.CSS,
58819 scrollIncrement : 22,
58821 cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
58823 findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
58825 bind : function(ds, cm){
58827 this.ds.un("load", this.onLoad, this);
58828 this.ds.un("datachanged", this.onDataChange, this);
58829 this.ds.un("add", this.onAdd, this);
58830 this.ds.un("remove", this.onRemove, this);
58831 this.ds.un("update", this.onUpdate, this);
58832 this.ds.un("clear", this.onClear, this);
58835 ds.on("load", this.onLoad, this);
58836 ds.on("datachanged", this.onDataChange, this);
58837 ds.on("add", this.onAdd, this);
58838 ds.on("remove", this.onRemove, this);
58839 ds.on("update", this.onUpdate, this);
58840 ds.on("clear", this.onClear, this);
58845 this.cm.un("widthchange", this.onColWidthChange, this);
58846 this.cm.un("headerchange", this.onHeaderChange, this);
58847 this.cm.un("hiddenchange", this.onHiddenChange, this);
58848 this.cm.un("columnmoved", this.onColumnMove, this);
58849 this.cm.un("columnlockchange", this.onColumnLock, this);
58852 this.generateRules(cm);
58853 cm.on("widthchange", this.onColWidthChange, this);
58854 cm.on("headerchange", this.onHeaderChange, this);
58855 cm.on("hiddenchange", this.onHiddenChange, this);
58856 cm.on("columnmoved", this.onColumnMove, this);
58857 cm.on("columnlockchange", this.onColumnLock, this);
58862 init: function(grid){
58863 Roo.grid.GridView.superclass.init.call(this, grid);
58865 this.bind(grid.dataSource, grid.colModel);
58867 grid.on("headerclick", this.handleHeaderClick, this);
58869 if(grid.trackMouseOver){
58870 grid.on("mouseover", this.onRowOver, this);
58871 grid.on("mouseout", this.onRowOut, this);
58873 grid.cancelTextSelection = function(){};
58874 this.gridId = grid.id;
58876 var tpls = this.templates || {};
58879 tpls.master = new Roo.Template(
58880 '<div class="x-grid" hidefocus="true">',
58881 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
58882 '<div class="x-grid-topbar"></div>',
58883 '<div class="x-grid-scroller"><div></div></div>',
58884 '<div class="x-grid-locked">',
58885 '<div class="x-grid-header">{lockedHeader}</div>',
58886 '<div class="x-grid-body">{lockedBody}</div>',
58888 '<div class="x-grid-viewport">',
58889 '<div class="x-grid-header">{header}</div>',
58890 '<div class="x-grid-body">{body}</div>',
58892 '<div class="x-grid-bottombar"></div>',
58894 '<div class="x-grid-resize-proxy"> </div>',
58897 tpls.master.disableformats = true;
58901 tpls.header = new Roo.Template(
58902 '<table border="0" cellspacing="0" cellpadding="0">',
58903 '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
58906 tpls.header.disableformats = true;
58908 tpls.header.compile();
58911 tpls.hcell = new Roo.Template(
58912 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
58913 '<div class="x-grid-hd-text ' + this.unselectableCls + '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
58916 tpls.hcell.disableFormats = true;
58918 tpls.hcell.compile();
58921 tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
58922 this.unselectableCls + '" ' + this.unselectable +'> </div>');
58923 tpls.hsplit.disableFormats = true;
58925 tpls.hsplit.compile();
58928 tpls.body = new Roo.Template(
58929 '<table border="0" cellspacing="0" cellpadding="0">',
58930 "<tbody>{rows}</tbody>",
58933 tpls.body.disableFormats = true;
58935 tpls.body.compile();
58938 tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
58939 tpls.row.disableFormats = true;
58941 tpls.row.compile();
58944 tpls.cell = new Roo.Template(
58945 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
58946 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
58947 this.unselectableCls + '" ' + this.unselectable +'" {attr}>{value}</div></div>',
58950 tpls.cell.disableFormats = true;
58952 tpls.cell.compile();
58954 this.templates = tpls;
58957 // remap these for backwards compat
58958 onColWidthChange : function(){
58959 this.updateColumns.apply(this, arguments);
58961 onHeaderChange : function(){
58962 this.updateHeaders.apply(this, arguments);
58964 onHiddenChange : function(){
58965 this.handleHiddenChange.apply(this, arguments);
58967 onColumnMove : function(){
58968 this.handleColumnMove.apply(this, arguments);
58970 onColumnLock : function(){
58971 this.handleLockChange.apply(this, arguments);
58974 onDataChange : function(){
58976 this.updateHeaderSortState();
58979 onClear : function(){
58983 onUpdate : function(ds, record){
58984 this.refreshRow(record);
58987 refreshRow : function(record){
58988 var ds = this.ds, index;
58989 if(typeof record == 'number'){
58991 record = ds.getAt(index);
58993 index = ds.indexOf(record);
58995 this.insertRows(ds, index, index, true);
58996 this.onRemove(ds, record, index+1, true);
58997 this.syncRowHeights(index, index);
58999 this.fireEvent("rowupdated", this, index, record);
59002 onAdd : function(ds, records, index){
59003 this.insertRows(ds, index, index + (records.length-1));
59006 onRemove : function(ds, record, index, isUpdate){
59007 if(isUpdate !== true){
59008 this.fireEvent("beforerowremoved", this, index, record);
59010 var bt = this.getBodyTable(), lt = this.getLockedTable();
59011 if(bt.rows[index]){
59012 bt.firstChild.removeChild(bt.rows[index]);
59014 if(lt.rows[index]){
59015 lt.firstChild.removeChild(lt.rows[index]);
59017 if(isUpdate !== true){
59018 this.stripeRows(index);
59019 this.syncRowHeights(index, index);
59021 this.fireEvent("rowremoved", this, index, record);
59025 onLoad : function(){
59026 this.scrollToTop();
59030 * Scrolls the grid to the top
59032 scrollToTop : function(){
59034 this.scroller.dom.scrollTop = 0;
59040 * Gets a panel in the header of the grid that can be used for toolbars etc.
59041 * After modifying the contents of this panel a call to grid.autoSize() may be
59042 * required to register any changes in size.
59043 * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
59044 * @return Roo.Element
59046 getHeaderPanel : function(doShow){
59048 this.headerPanel.show();
59050 return this.headerPanel;
59054 * Gets a panel in the footer of the grid that can be used for toolbars etc.
59055 * After modifying the contents of this panel a call to grid.autoSize() may be
59056 * required to register any changes in size.
59057 * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
59058 * @return Roo.Element
59060 getFooterPanel : function(doShow){
59062 this.footerPanel.show();
59064 return this.footerPanel;
59067 initElements : function(){
59068 var E = Roo.Element;
59069 var el = this.grid.getGridEl().dom.firstChild;
59070 var cs = el.childNodes;
59072 this.el = new E(el);
59074 this.focusEl = new E(el.firstChild);
59075 this.focusEl.swallowEvent("click", true);
59077 this.headerPanel = new E(cs[1]);
59078 this.headerPanel.enableDisplayMode("block");
59080 this.scroller = new E(cs[2]);
59081 this.scrollSizer = new E(this.scroller.dom.firstChild);
59083 this.lockedWrap = new E(cs[3]);
59084 this.lockedHd = new E(this.lockedWrap.dom.firstChild);
59085 this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
59087 this.mainWrap = new E(cs[4]);
59088 this.mainHd = new E(this.mainWrap.dom.firstChild);
59089 this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
59091 this.footerPanel = new E(cs[5]);
59092 this.footerPanel.enableDisplayMode("block");
59094 this.resizeProxy = new E(cs[6]);
59096 this.headerSelector = String.format(
59097 '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
59098 this.lockedHd.id, this.mainHd.id
59101 this.splitterSelector = String.format(
59102 '#{0} div.x-grid-split, #{1} div.x-grid-split',
59103 this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
59106 idToCssName : function(s)
59108 return s.replace(/[^a-z0-9]+/ig, '-');
59111 getHeaderCell : function(index){
59112 return Roo.DomQuery.select(this.headerSelector)[index];
59115 getHeaderCellMeasure : function(index){
59116 return this.getHeaderCell(index).firstChild;
59119 getHeaderCellText : function(index){
59120 return this.getHeaderCell(index).firstChild.firstChild;
59123 getLockedTable : function(){
59124 return this.lockedBody.dom.firstChild;
59127 getBodyTable : function(){
59128 return this.mainBody.dom.firstChild;
59131 getLockedRow : function(index){
59132 return this.getLockedTable().rows[index];
59135 getRow : function(index){
59136 return this.getBodyTable().rows[index];
59139 getRowComposite : function(index){
59141 this.rowEl = new Roo.CompositeElementLite();
59143 var els = [], lrow, mrow;
59144 if(lrow = this.getLockedRow(index)){
59147 if(mrow = this.getRow(index)){
59150 this.rowEl.elements = els;
59154 * Gets the 'td' of the cell
59156 * @param {Integer} rowIndex row to select
59157 * @param {Integer} colIndex column to select
59161 getCell : function(rowIndex, colIndex){
59162 var locked = this.cm.getLockedCount();
59164 if(colIndex < locked){
59165 source = this.lockedBody.dom.firstChild;
59167 source = this.mainBody.dom.firstChild;
59168 colIndex -= locked;
59170 return source.rows[rowIndex].childNodes[colIndex];
59173 getCellText : function(rowIndex, colIndex){
59174 return this.getCell(rowIndex, colIndex).firstChild.firstChild;
59177 getCellBox : function(cell){
59178 var b = this.fly(cell).getBox();
59179 if(Roo.isOpera){ // opera fails to report the Y
59180 b.y = cell.offsetTop + this.mainBody.getY();
59185 getCellIndex : function(cell){
59186 var id = String(cell.className).match(this.cellRE);
59188 return parseInt(id[1], 10);
59193 findHeaderIndex : function(n){
59194 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
59195 return r ? this.getCellIndex(r) : false;
59198 findHeaderCell : function(n){
59199 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
59200 return r ? r : false;
59203 findRowIndex : function(n){
59207 var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
59208 return r ? r.rowIndex : false;
59211 findCellIndex : function(node){
59212 var stop = this.el.dom;
59213 while(node && node != stop){
59214 if(this.findRE.test(node.className)){
59215 return this.getCellIndex(node);
59217 node = node.parentNode;
59222 getColumnId : function(index){
59223 return this.cm.getColumnId(index);
59226 getSplitters : function()
59228 if(this.splitterSelector){
59229 return Roo.DomQuery.select(this.splitterSelector);
59235 getSplitter : function(index){
59236 return this.getSplitters()[index];
59239 onRowOver : function(e, t){
59241 if((row = this.findRowIndex(t)) !== false){
59242 this.getRowComposite(row).addClass("x-grid-row-over");
59246 onRowOut : function(e, t){
59248 if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
59249 this.getRowComposite(row).removeClass("x-grid-row-over");
59253 renderHeaders : function(){
59255 var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
59256 var cb = [], lb = [], sb = [], lsb = [], p = {};
59257 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
59258 p.cellId = "x-grid-hd-0-" + i;
59259 p.splitId = "x-grid-csplit-0-" + i;
59260 p.id = cm.getColumnId(i);
59261 p.value = cm.getColumnHeader(i) || "";
59262 p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</) ? '' : p.value || "";
59263 p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
59264 if(!cm.isLocked(i)){
59265 cb[cb.length] = ct.apply(p);
59266 sb[sb.length] = st.apply(p);
59268 lb[lb.length] = ct.apply(p);
59269 lsb[lsb.length] = st.apply(p);
59272 return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
59273 ht.apply({cells: cb.join(""), splits:sb.join("")})];
59276 updateHeaders : function(){
59277 var html = this.renderHeaders();
59278 this.lockedHd.update(html[0]);
59279 this.mainHd.update(html[1]);
59283 * Focuses the specified row.
59284 * @param {Number} row The row index
59286 focusRow : function(row)
59288 //Roo.log('GridView.focusRow');
59289 var x = this.scroller.dom.scrollLeft;
59290 this.focusCell(row, 0, false);
59291 this.scroller.dom.scrollLeft = x;
59295 * Focuses the specified cell.
59296 * @param {Number} row The row index
59297 * @param {Number} col The column index
59298 * @param {Boolean} hscroll false to disable horizontal scrolling
59300 focusCell : function(row, col, hscroll)
59302 //Roo.log('GridView.focusCell');
59303 var el = this.ensureVisible(row, col, hscroll);
59304 this.focusEl.alignTo(el, "tl-tl");
59306 this.focusEl.focus();
59308 this.focusEl.focus.defer(1, this.focusEl);
59313 * Scrolls the specified cell into view
59314 * @param {Number} row The row index
59315 * @param {Number} col The column index
59316 * @param {Boolean} hscroll false to disable horizontal scrolling
59318 ensureVisible : function(row, col, hscroll)
59320 //Roo.log('GridView.ensureVisible,' + row + ',' + col);
59321 //return null; //disable for testing.
59322 if(typeof row != "number"){
59323 row = row.rowIndex;
59325 if(row < 0 && row >= this.ds.getCount()){
59328 col = (col !== undefined ? col : 0);
59329 var cm = this.grid.colModel;
59330 while(cm.isHidden(col)){
59334 var el = this.getCell(row, col);
59338 var c = this.scroller.dom;
59340 var ctop = parseInt(el.offsetTop, 10);
59341 var cleft = parseInt(el.offsetLeft, 10);
59342 var cbot = ctop + el.offsetHeight;
59343 var cright = cleft + el.offsetWidth;
59345 var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
59346 var stop = parseInt(c.scrollTop, 10);
59347 var sleft = parseInt(c.scrollLeft, 10);
59348 var sbot = stop + ch;
59349 var sright = sleft + c.clientWidth;
59351 Roo.log('GridView.ensureVisible:' +
59353 ' c.clientHeight:' + c.clientHeight +
59354 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
59362 c.scrollTop = ctop;
59363 //Roo.log("set scrolltop to ctop DISABLE?");
59364 }else if(cbot > sbot){
59365 //Roo.log("set scrolltop to cbot-ch");
59366 c.scrollTop = cbot-ch;
59369 if(hscroll !== false){
59371 c.scrollLeft = cleft;
59372 }else if(cright > sright){
59373 c.scrollLeft = cright-c.clientWidth;
59380 updateColumns : function(){
59381 this.grid.stopEditing();
59382 var cm = this.grid.colModel, colIds = this.getColumnIds();
59383 //var totalWidth = cm.getTotalWidth();
59385 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
59386 //if(cm.isHidden(i)) continue;
59387 var w = cm.getColumnWidth(i);
59388 this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
59389 this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
59391 this.updateSplitters();
59394 generateRules : function(cm){
59395 var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
59396 Roo.util.CSS.removeStyleSheet(rulesId);
59397 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
59398 var cid = cm.getColumnId(i);
59400 if(cm.config[i].align){
59401 align = 'text-align:'+cm.config[i].align+';';
59404 if(cm.isHidden(i)){
59405 hidden = 'display:none;';
59407 var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
59409 this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
59410 this.hdSelector, cid, " {\n", align, width, "}\n",
59411 this.tdSelector, cid, " {\n",hidden,"\n}\n",
59412 this.splitSelector, cid, " {\n", hidden , "\n}\n");
59414 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
59417 updateSplitters : function(){
59418 var cm = this.cm, s = this.getSplitters();
59419 if(s){ // splitters not created yet
59420 var pos = 0, locked = true;
59421 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
59422 if(cm.isHidden(i)) {
59425 var w = cm.getColumnWidth(i); // make sure it's a number
59426 if(!cm.isLocked(i) && locked){
59431 s[i].style.left = (pos-this.splitOffset) + "px";
59436 handleHiddenChange : function(colModel, colIndex, hidden){
59438 this.hideColumn(colIndex);
59440 this.unhideColumn(colIndex);
59444 hideColumn : function(colIndex){
59445 var cid = this.getColumnId(colIndex);
59446 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
59447 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
59449 this.updateHeaders();
59451 this.updateSplitters();
59455 unhideColumn : function(colIndex){
59456 var cid = this.getColumnId(colIndex);
59457 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
59458 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
59461 this.updateHeaders();
59463 this.updateSplitters();
59467 insertRows : function(dm, firstRow, lastRow, isUpdate){
59468 if(firstRow == 0 && lastRow == dm.getCount()-1){
59472 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
59474 var s = this.getScrollState();
59475 var markup = this.renderRows(firstRow, lastRow);
59476 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
59477 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
59478 this.restoreScroll(s);
59480 this.fireEvent("rowsinserted", this, firstRow, lastRow);
59481 this.syncRowHeights(firstRow, lastRow);
59482 this.stripeRows(firstRow);
59488 bufferRows : function(markup, target, index){
59489 var before = null, trows = target.rows, tbody = target.tBodies[0];
59490 if(index < trows.length){
59491 before = trows[index];
59493 var b = document.createElement("div");
59494 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
59495 var rows = b.firstChild.rows;
59496 for(var i = 0, len = rows.length; i < len; i++){
59498 tbody.insertBefore(rows[0], before);
59500 tbody.appendChild(rows[0]);
59507 deleteRows : function(dm, firstRow, lastRow){
59508 if(dm.getRowCount()<1){
59509 this.fireEvent("beforerefresh", this);
59510 this.mainBody.update("");
59511 this.lockedBody.update("");
59512 this.fireEvent("refresh", this);
59514 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
59515 var bt = this.getBodyTable();
59516 var tbody = bt.firstChild;
59517 var rows = bt.rows;
59518 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
59519 tbody.removeChild(rows[firstRow]);
59521 this.stripeRows(firstRow);
59522 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
59526 updateRows : function(dataSource, firstRow, lastRow){
59527 var s = this.getScrollState();
59529 this.restoreScroll(s);
59532 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
59536 this.updateHeaderSortState();
59539 getScrollState : function(){
59541 var sb = this.scroller.dom;
59542 return {left: sb.scrollLeft, top: sb.scrollTop};
59545 stripeRows : function(startRow){
59546 if(!this.grid.stripeRows || this.ds.getCount() < 1){
59549 startRow = startRow || 0;
59550 var rows = this.getBodyTable().rows;
59551 var lrows = this.getLockedTable().rows;
59552 var cls = ' x-grid-row-alt ';
59553 for(var i = startRow, len = rows.length; i < len; i++){
59554 var row = rows[i], lrow = lrows[i];
59555 var isAlt = ((i+1) % 2 == 0);
59556 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
59557 if(isAlt == hasAlt){
59561 row.className += " x-grid-row-alt";
59563 row.className = row.className.replace("x-grid-row-alt", "");
59566 lrow.className = row.className;
59571 restoreScroll : function(state){
59572 //Roo.log('GridView.restoreScroll');
59573 var sb = this.scroller.dom;
59574 sb.scrollLeft = state.left;
59575 sb.scrollTop = state.top;
59579 syncScroll : function(){
59580 //Roo.log('GridView.syncScroll');
59581 var sb = this.scroller.dom;
59582 var sh = this.mainHd.dom;
59583 var bs = this.mainBody.dom;
59584 var lv = this.lockedBody.dom;
59585 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
59586 lv.scrollTop = bs.scrollTop = sb.scrollTop;
59589 handleScroll : function(e){
59591 var sb = this.scroller.dom;
59592 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
59596 handleWheel : function(e){
59597 var d = e.getWheelDelta();
59598 this.scroller.dom.scrollTop -= d*22;
59599 // set this here to prevent jumpy scrolling on large tables
59600 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
59604 renderRows : function(startRow, endRow){
59605 // pull in all the crap needed to render rows
59606 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
59607 var colCount = cm.getColumnCount();
59609 if(ds.getCount() < 1){
59613 // build a map for all the columns
59615 for(var i = 0; i < colCount; i++){
59616 var name = cm.getDataIndex(i);
59618 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
59619 renderer : cm.getRenderer(i),
59620 id : cm.getColumnId(i),
59621 locked : cm.isLocked(i),
59622 has_editor : cm.isCellEditable(i)
59626 startRow = startRow || 0;
59627 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
59629 // records to render
59630 var rs = ds.getRange(startRow, endRow);
59632 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
59635 // As much as I hate to duplicate code, this was branched because FireFox really hates
59636 // [].join("") on strings. The performance difference was substantial enough to
59637 // branch this function
59638 doRender : Roo.isGecko ?
59639 function(cs, rs, ds, startRow, colCount, stripe){
59640 var ts = this.templates, ct = ts.cell, rt = ts.row;
59642 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
59644 var hasListener = this.grid.hasListener('rowclass');
59646 for(var j = 0, len = rs.length; j < len; j++){
59647 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
59648 for(var i = 0; i < colCount; i++){
59650 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
59652 p.css = p.attr = "";
59653 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
59654 if(p.value == undefined || p.value === "") {
59655 p.value = " ";
59658 p.css += ' x-grid-editable-cell';
59660 if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
59661 p.css += ' x-grid-dirty-cell';
59663 var markup = ct.apply(p);
59671 if(stripe && ((rowIndex+1) % 2 == 0)){
59672 alt.push("x-grid-row-alt")
59675 alt.push( " x-grid-dirty-row");
59678 if(this.getRowClass){
59679 alt.push(this.getRowClass(r, rowIndex));
59685 rowIndex : rowIndex,
59688 this.grid.fireEvent('rowclass', this, rowcfg);
59689 alt.push(rowcfg.rowClass);
59691 rp.alt = alt.join(" ");
59692 lbuf+= rt.apply(rp);
59694 buf+= rt.apply(rp);
59696 return [lbuf, buf];
59698 function(cs, rs, ds, startRow, colCount, stripe){
59699 var ts = this.templates, ct = ts.cell, rt = ts.row;
59701 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
59702 var hasListener = this.grid.hasListener('rowclass');
59705 for(var j = 0, len = rs.length; j < len; j++){
59706 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
59707 for(var i = 0; i < colCount; i++){
59709 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
59711 p.css = p.attr = "";
59712 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
59713 if(p.value == undefined || p.value === "") {
59714 p.value = " ";
59718 p.css += ' x-grid-editable-cell';
59720 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
59721 p.css += ' x-grid-dirty-cell'
59724 var markup = ct.apply(p);
59726 cb[cb.length] = markup;
59728 lcb[lcb.length] = markup;
59732 if(stripe && ((rowIndex+1) % 2 == 0)){
59733 alt.push( "x-grid-row-alt");
59736 alt.push(" x-grid-dirty-row");
59739 if(this.getRowClass){
59740 alt.push( this.getRowClass(r, rowIndex));
59746 rowIndex : rowIndex,
59749 this.grid.fireEvent('rowclass', this, rowcfg);
59750 alt.push(rowcfg.rowClass);
59753 rp.alt = alt.join(" ");
59754 rp.cells = lcb.join("");
59755 lbuf[lbuf.length] = rt.apply(rp);
59756 rp.cells = cb.join("");
59757 buf[buf.length] = rt.apply(rp);
59759 return [lbuf.join(""), buf.join("")];
59762 renderBody : function(){
59763 var markup = this.renderRows();
59764 var bt = this.templates.body;
59765 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
59769 * Refreshes the grid
59770 * @param {Boolean} headersToo
59772 refresh : function(headersToo){
59773 this.fireEvent("beforerefresh", this);
59774 this.grid.stopEditing();
59775 var result = this.renderBody();
59776 this.lockedBody.update(result[0]);
59777 this.mainBody.update(result[1]);
59778 if(headersToo === true){
59779 this.updateHeaders();
59780 this.updateColumns();
59781 this.updateSplitters();
59782 this.updateHeaderSortState();
59784 this.syncRowHeights();
59786 this.fireEvent("refresh", this);
59789 handleColumnMove : function(cm, oldIndex, newIndex){
59790 this.indexMap = null;
59791 var s = this.getScrollState();
59792 this.refresh(true);
59793 this.restoreScroll(s);
59794 this.afterMove(newIndex);
59797 afterMove : function(colIndex){
59798 if(this.enableMoveAnim && Roo.enableFx){
59799 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
59801 // if multisort - fix sortOrder, and reload..
59802 if (this.grid.dataSource.multiSort) {
59803 // the we can call sort again..
59804 var dm = this.grid.dataSource;
59805 var cm = this.grid.colModel;
59807 for(var i = 0; i < cm.config.length; i++ ) {
59809 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
59810 continue; // dont' bother, it's not in sort list or being set.
59813 so.push(cm.config[i].dataIndex);
59816 dm.load(dm.lastOptions);
59823 updateCell : function(dm, rowIndex, dataIndex){
59824 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
59825 if(typeof colIndex == "undefined"){ // not present in grid
59828 var cm = this.grid.colModel;
59829 var cell = this.getCell(rowIndex, colIndex);
59830 var cellText = this.getCellText(rowIndex, colIndex);
59833 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
59834 id : cm.getColumnId(colIndex),
59835 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
59837 var renderer = cm.getRenderer(colIndex);
59838 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
59839 if(typeof val == "undefined" || val === "") {
59842 cellText.innerHTML = val;
59843 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
59844 this.syncRowHeights(rowIndex, rowIndex);
59847 calcColumnWidth : function(colIndex, maxRowsToMeasure){
59849 if(this.grid.autoSizeHeaders){
59850 var h = this.getHeaderCellMeasure(colIndex);
59851 maxWidth = Math.max(maxWidth, h.scrollWidth);
59854 if(this.cm.isLocked(colIndex)){
59855 tb = this.getLockedTable();
59858 tb = this.getBodyTable();
59859 index = colIndex - this.cm.getLockedCount();
59862 var rows = tb.rows;
59863 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
59864 for(var i = 0; i < stopIndex; i++){
59865 var cell = rows[i].childNodes[index].firstChild;
59866 maxWidth = Math.max(maxWidth, cell.scrollWidth);
59869 return maxWidth + /*margin for error in IE*/ 5;
59872 * Autofit a column to its content.
59873 * @param {Number} colIndex
59874 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
59876 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
59877 if(this.cm.isHidden(colIndex)){
59878 return; // can't calc a hidden column
59881 var cid = this.cm.getColumnId(colIndex);
59882 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
59883 if(this.grid.autoSizeHeaders){
59884 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
59887 var newWidth = this.calcColumnWidth(colIndex);
59888 this.cm.setColumnWidth(colIndex,
59889 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
59890 if(!suppressEvent){
59891 this.grid.fireEvent("columnresize", colIndex, newWidth);
59896 * Autofits all columns to their content and then expands to fit any extra space in the grid
59898 autoSizeColumns : function(){
59899 var cm = this.grid.colModel;
59900 var colCount = cm.getColumnCount();
59901 for(var i = 0; i < colCount; i++){
59902 this.autoSizeColumn(i, true, true);
59904 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
59907 this.updateColumns();
59913 * Autofits all columns to the grid's width proportionate with their current size
59914 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
59916 fitColumns : function(reserveScrollSpace){
59917 var cm = this.grid.colModel;
59918 var colCount = cm.getColumnCount();
59922 for (i = 0; i < colCount; i++){
59923 if(!cm.isHidden(i) && !cm.isFixed(i)){
59924 w = cm.getColumnWidth(i);
59930 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
59931 if(reserveScrollSpace){
59934 var frac = (avail - cm.getTotalWidth())/width;
59935 while (cols.length){
59938 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
59940 this.updateColumns();
59944 onRowSelect : function(rowIndex){
59945 var row = this.getRowComposite(rowIndex);
59946 row.addClass("x-grid-row-selected");
59949 onRowDeselect : function(rowIndex){
59950 var row = this.getRowComposite(rowIndex);
59951 row.removeClass("x-grid-row-selected");
59954 onCellSelect : function(row, col){
59955 var cell = this.getCell(row, col);
59957 Roo.fly(cell).addClass("x-grid-cell-selected");
59961 onCellDeselect : function(row, col){
59962 var cell = this.getCell(row, col);
59964 Roo.fly(cell).removeClass("x-grid-cell-selected");
59968 updateHeaderSortState : function(){
59970 // sort state can be single { field: xxx, direction : yyy}
59971 // or { xxx=>ASC , yyy : DESC ..... }
59974 if (!this.ds.multiSort) {
59975 var state = this.ds.getSortState();
59979 mstate[state.field] = state.direction;
59980 // FIXME... - this is not used here.. but might be elsewhere..
59981 this.sortState = state;
59984 mstate = this.ds.sortToggle;
59986 //remove existing sort classes..
59988 var sc = this.sortClasses;
59989 var hds = this.el.select(this.headerSelector).removeClass(sc);
59991 for(var f in mstate) {
59993 var sortColumn = this.cm.findColumnIndex(f);
59995 if(sortColumn != -1){
59996 var sortDir = mstate[f];
59997 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
60006 handleHeaderClick : function(g, index,e){
60008 Roo.log("header click");
60011 // touch events on header are handled by context
60012 this.handleHdCtx(g,index,e);
60017 if(this.headersDisabled){
60020 var dm = g.dataSource, cm = g.colModel;
60021 if(!cm.isSortable(index)){
60026 if (dm.multiSort) {
60027 // update the sortOrder
60029 for(var i = 0; i < cm.config.length; i++ ) {
60031 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
60032 continue; // dont' bother, it's not in sort list or being set.
60035 so.push(cm.config[i].dataIndex);
60041 dm.sort(cm.getDataIndex(index));
60045 destroy : function(){
60047 this.colMenu.removeAll();
60048 Roo.menu.MenuMgr.unregister(this.colMenu);
60049 this.colMenu.getEl().remove();
60050 delete this.colMenu;
60053 this.hmenu.removeAll();
60054 Roo.menu.MenuMgr.unregister(this.hmenu);
60055 this.hmenu.getEl().remove();
60058 if(this.grid.enableColumnMove){
60059 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
60061 for(var dd in dds){
60062 if(!dds[dd].config.isTarget && dds[dd].dragElId){
60063 var elid = dds[dd].dragElId;
60065 Roo.get(elid).remove();
60066 } else if(dds[dd].config.isTarget){
60067 dds[dd].proxyTop.remove();
60068 dds[dd].proxyBottom.remove();
60071 if(Roo.dd.DDM.locationCache[dd]){
60072 delete Roo.dd.DDM.locationCache[dd];
60075 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
60078 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
60079 this.bind(null, null);
60080 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
60083 handleLockChange : function(){
60084 this.refresh(true);
60087 onDenyColumnLock : function(){
60091 onDenyColumnHide : function(){
60095 handleHdMenuClick : function(item){
60096 var index = this.hdCtxIndex;
60097 var cm = this.cm, ds = this.ds;
60100 ds.sort(cm.getDataIndex(index), "ASC");
60103 ds.sort(cm.getDataIndex(index), "DESC");
60106 var lc = cm.getLockedCount();
60107 if(cm.getColumnCount(true) <= lc+1){
60108 this.onDenyColumnLock();
60112 cm.setLocked(index, true, true);
60113 cm.moveColumn(index, lc);
60114 this.grid.fireEvent("columnmove", index, lc);
60116 cm.setLocked(index, true);
60120 var lc = cm.getLockedCount();
60121 if((lc-1) != index){
60122 cm.setLocked(index, false, true);
60123 cm.moveColumn(index, lc-1);
60124 this.grid.fireEvent("columnmove", index, lc-1);
60126 cm.setLocked(index, false);
60129 case 'wider': // used to expand cols on touch..
60131 var cw = cm.getColumnWidth(index);
60132 cw += (item.id == 'wider' ? 1 : -1) * 50;
60133 cw = Math.max(0, cw);
60134 cw = Math.min(cw,4000);
60135 cm.setColumnWidth(index, cw);
60139 index = cm.getIndexById(item.id.substr(4));
60141 if(item.checked && cm.getColumnCount(true) <= 1){
60142 this.onDenyColumnHide();
60145 cm.setHidden(index, item.checked);
60151 beforeColMenuShow : function(){
60152 var cm = this.cm, colCount = cm.getColumnCount();
60153 this.colMenu.removeAll();
60156 for(var i = 0; i < colCount; i++){
60158 id: "col-"+cm.getColumnId(i),
60159 text: cm.getColumnHeader(i),
60160 checked: !cm.isHidden(i),
60165 if (this.grid.sortColMenu) {
60166 items.sort(function(a,b) {
60167 if (a.text == b.text) {
60170 return a.text.toUpperCase() > b.text.toUpperCase() ? 1 : -1;
60174 for(var i = 0; i < colCount; i++){
60175 this.colMenu.add(new Roo.menu.CheckItem(items[i]));
60179 handleHdCtx : function(g, index, e){
60181 var hd = this.getHeaderCell(index);
60182 this.hdCtxIndex = index;
60183 var ms = this.hmenu.items, cm = this.cm;
60184 ms.get("asc").setDisabled(!cm.isSortable(index));
60185 ms.get("desc").setDisabled(!cm.isSortable(index));
60186 if(this.grid.enableColLock !== false){
60187 ms.get("lock").setDisabled(cm.isLocked(index));
60188 ms.get("unlock").setDisabled(!cm.isLocked(index));
60190 this.hmenu.show(hd, "tl-bl");
60193 handleHdOver : function(e){
60194 var hd = this.findHeaderCell(e.getTarget());
60195 if(hd && !this.headersDisabled){
60196 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
60197 this.fly(hd).addClass("x-grid-hd-over");
60202 handleHdOut : function(e){
60203 var hd = this.findHeaderCell(e.getTarget());
60205 this.fly(hd).removeClass("x-grid-hd-over");
60209 handleSplitDblClick : function(e, t){
60210 var i = this.getCellIndex(t);
60211 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
60212 this.autoSizeColumn(i, true);
60217 render : function(){
60220 var colCount = cm.getColumnCount();
60222 if(this.grid.monitorWindowResize === true){
60223 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
60225 var header = this.renderHeaders();
60226 var body = this.templates.body.apply({rows:""});
60227 var html = this.templates.master.apply({
60230 lockedHeader: header[0],
60234 //this.updateColumns();
60236 this.grid.getGridEl().dom.innerHTML = html;
60238 this.initElements();
60240 // a kludge to fix the random scolling effect in webkit
60241 this.el.on("scroll", function() {
60242 this.el.dom.scrollTop=0; // hopefully not recursive..
60245 this.scroller.on("scroll", this.handleScroll, this);
60246 this.lockedBody.on("mousewheel", this.handleWheel, this);
60247 this.mainBody.on("mousewheel", this.handleWheel, this);
60249 this.mainHd.on("mouseover", this.handleHdOver, this);
60250 this.mainHd.on("mouseout", this.handleHdOut, this);
60251 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
60252 {delegate: "."+this.splitClass});
60254 this.lockedHd.on("mouseover", this.handleHdOver, this);
60255 this.lockedHd.on("mouseout", this.handleHdOut, this);
60256 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
60257 {delegate: "."+this.splitClass});
60259 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
60260 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
60263 this.updateSplitters();
60265 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
60266 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
60267 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
60270 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
60271 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
60273 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
60274 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
60276 if(this.grid.enableColLock !== false){
60277 this.hmenu.add('-',
60278 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
60279 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
60283 this.hmenu.add('-',
60284 {id:"wider", text: this.columnsWiderText},
60285 {id:"narrow", text: this.columnsNarrowText }
60291 if(this.grid.enableColumnHide !== false){
60293 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
60294 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
60295 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
60297 this.hmenu.add('-',
60298 {id:"columns", text: this.columnsText, menu: this.colMenu}
60301 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
60303 this.grid.on("headercontextmenu", this.handleHdCtx, this);
60306 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
60307 this.dd = new Roo.grid.GridDragZone(this.grid, {
60308 ddGroup : this.grid.ddGroup || 'GridDD'
60314 for(var i = 0; i < colCount; i++){
60315 if(cm.isHidden(i)){
60316 this.hideColumn(i);
60318 if(cm.config[i].align){
60319 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
60320 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
60324 this.updateHeaderSortState();
60326 this.beforeInitialResize();
60329 // two part rendering gives faster view to the user
60330 this.renderPhase2.defer(1, this);
60333 renderPhase2 : function(){
60334 // render the rows now
60336 if(this.grid.autoSizeColumns){
60337 this.autoSizeColumns();
60341 beforeInitialResize : function(){
60345 onColumnSplitterMoved : function(i, w){
60346 this.userResized = true;
60347 var cm = this.grid.colModel;
60348 cm.setColumnWidth(i, w, true);
60349 var cid = cm.getColumnId(i);
60350 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
60351 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
60352 this.updateSplitters();
60354 this.grid.fireEvent("columnresize", i, w);
60357 syncRowHeights : function(startIndex, endIndex){
60358 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
60359 startIndex = startIndex || 0;
60360 var mrows = this.getBodyTable().rows;
60361 var lrows = this.getLockedTable().rows;
60362 var len = mrows.length-1;
60363 endIndex = Math.min(endIndex || len, len);
60364 for(var i = startIndex; i <= endIndex; i++){
60365 var m = mrows[i], l = lrows[i];
60366 var h = Math.max(m.offsetHeight, l.offsetHeight);
60367 m.style.height = l.style.height = h + "px";
60372 layout : function(initialRender, is2ndPass)
60375 var auto = g.autoHeight;
60376 var scrollOffset = 16;
60377 var c = g.getGridEl(), cm = this.cm,
60378 expandCol = g.autoExpandColumn,
60380 //c.beginMeasure();
60382 if(!c.dom.offsetWidth){ // display:none?
60384 this.lockedWrap.show();
60385 this.mainWrap.show();
60390 var hasLock = this.cm.isLocked(0);
60392 var tbh = this.headerPanel.getHeight();
60393 var bbh = this.footerPanel.getHeight();
60396 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
60397 var newHeight = ch + c.getBorderWidth("tb");
60399 newHeight = Math.min(g.maxHeight, newHeight);
60401 c.setHeight(newHeight);
60405 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
60408 var s = this.scroller;
60410 var csize = c.getSize(true);
60412 this.el.setSize(csize.width, csize.height);
60414 this.headerPanel.setWidth(csize.width);
60415 this.footerPanel.setWidth(csize.width);
60417 var hdHeight = this.mainHd.getHeight();
60418 var vw = csize.width;
60419 var vh = csize.height - (tbh + bbh);
60423 var bt = this.getBodyTable();
60425 if(cm.getLockedCount() == cm.config.length){
60426 bt = this.getLockedTable();
60429 var ltWidth = hasLock ?
60430 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
60432 var scrollHeight = bt.offsetHeight;
60433 var scrollWidth = ltWidth + bt.offsetWidth;
60434 var vscroll = false, hscroll = false;
60436 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
60438 var lw = this.lockedWrap, mw = this.mainWrap;
60439 var lb = this.lockedBody, mb = this.mainBody;
60441 setTimeout(function(){
60442 var t = s.dom.offsetTop;
60443 var w = s.dom.clientWidth,
60444 h = s.dom.clientHeight;
60447 lw.setSize(ltWidth, h);
60449 mw.setLeftTop(ltWidth, t);
60450 mw.setSize(w-ltWidth, h);
60452 lb.setHeight(h-hdHeight);
60453 mb.setHeight(h-hdHeight);
60455 if(is2ndPass !== true && !gv.userResized && expandCol){
60456 // high speed resize without full column calculation
60458 var ci = cm.getIndexById(expandCol);
60460 ci = cm.findColumnIndex(expandCol);
60462 ci = Math.max(0, ci); // make sure it's got at least the first col.
60463 var expandId = cm.getColumnId(ci);
60464 var tw = cm.getTotalWidth(false);
60465 var currentWidth = cm.getColumnWidth(ci);
60466 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
60467 if(currentWidth != cw){
60468 cm.setColumnWidth(ci, cw, true);
60469 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
60470 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
60471 gv.updateSplitters();
60472 gv.layout(false, true);
60484 onWindowResize : function(){
60485 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
60491 appendFooter : function(parentEl){
60495 sortAscText : "Sort Ascending",
60496 sortDescText : "Sort Descending",
60497 lockText : "Lock Column",
60498 unlockText : "Unlock Column",
60499 columnsText : "Columns",
60501 columnsWiderText : "Wider",
60502 columnsNarrowText : "Thinner"
60506 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
60507 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
60508 this.proxy.el.addClass('x-grid3-col-dd');
60511 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
60512 handleMouseDown : function(e){
60516 callHandleMouseDown : function(e){
60517 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
60522 * Ext JS Library 1.1.1
60523 * Copyright(c) 2006-2007, Ext JS, LLC.
60525 * Originally Released Under LGPL - original licence link has changed is not relivant.
60528 * <script type="text/javascript">
60531 * @extends Roo.dd.DDProxy
60532 * @class Roo.grid.SplitDragZone
60533 * Support for Column Header resizing
60535 * @param {Object} config
60538 // This is a support class used internally by the Grid components
60539 Roo.grid.SplitDragZone = function(grid, hd, hd2){
60541 this.view = grid.getView();
60542 this.proxy = this.view.resizeProxy;
60543 Roo.grid.SplitDragZone.superclass.constructor.call(
60546 "gridSplitters" + this.grid.getGridEl().id, // SGROUP
60548 dragElId : Roo.id(this.proxy.dom),
60553 this.setHandleElId(Roo.id(hd));
60554 if (hd2 !== false) {
60555 this.setOuterHandleElId(Roo.id(hd2));
60558 this.scroll = false;
60560 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
60561 fly: Roo.Element.fly,
60563 b4StartDrag : function(x, y){
60564 this.view.headersDisabled = true;
60565 var h = this.view.mainWrap ? this.view.mainWrap.getHeight() : (
60566 this.view.headEl.getHeight() + this.view.bodyEl.getHeight()
60568 this.proxy.setHeight(h);
60570 // for old system colWidth really stored the actual width?
60571 // in bootstrap we tried using xs/ms/etc.. to do % sizing?
60572 // which in reality did not work.. - it worked only for fixed sizes
60573 // for resizable we need to use actual sizes.
60574 var w = this.cm.getColumnWidth(this.cellIndex);
60575 if (!this.view.mainWrap) {
60577 w = this.view.getHeaderIndex(this.cellIndex).getWidth();
60582 // this was w-this.grid.minColumnWidth;
60583 // doesnt really make sense? - w = thie curren width or the rendered one?
60584 var minw = Math.max(w-this.grid.minColumnWidth, 0);
60585 this.resetConstraints();
60586 this.setXConstraint(minw, 1000);
60587 this.setYConstraint(0, 0);
60588 this.minX = x - minw;
60589 this.maxX = x + 1000;
60591 if (!this.view.mainWrap) { // this is Bootstrap code..
60592 this.getDragEl().style.display='block';
60595 Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
60599 handleMouseDown : function(e){
60600 ev = Roo.EventObject.setEvent(e);
60601 var t = this.fly(ev.getTarget());
60602 if(t.hasClass("x-grid-split")){
60603 this.cellIndex = this.view.getCellIndex(t.dom);
60604 this.split = t.dom;
60605 this.cm = this.grid.colModel;
60606 if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
60607 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
60612 endDrag : function(e){
60613 this.view.headersDisabled = false;
60614 var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
60615 var diff = endX - this.startPos;
60617 var w = this.cm.getColumnWidth(this.cellIndex);
60618 if (!this.view.mainWrap) {
60621 this.view.onColumnSplitterMoved(this.cellIndex, w+diff);
60624 autoOffset : function(){
60625 this.setDelta(0,0);
60629 * Ext JS Library 1.1.1
60630 * Copyright(c) 2006-2007, Ext JS, LLC.
60632 * Originally Released Under LGPL - original licence link has changed is not relivant.
60635 * <script type="text/javascript">
60639 // This is a support class used internally by the Grid components
60640 Roo.grid.GridDragZone = function(grid, config){
60641 this.view = grid.getView();
60642 Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
60643 if(this.view.lockedBody){
60644 this.setHandleElId(Roo.id(this.view.mainBody.dom));
60645 this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
60647 this.scroll = false;
60649 this.ddel = document.createElement('div');
60650 this.ddel.className = 'x-grid-dd-wrap';
60653 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
60654 ddGroup : "GridDD",
60656 getDragData : function(e){
60657 var t = Roo.lib.Event.getTarget(e);
60658 var rowIndex = this.view.findRowIndex(t);
60659 var sm = this.grid.selModel;
60661 //Roo.log(rowIndex);
60663 if (sm.getSelectedCell) {
60664 // cell selection..
60665 if (!sm.getSelectedCell()) {
60668 if (rowIndex != sm.getSelectedCell()[0]) {
60673 if (sm.getSelections && sm.getSelections().length < 1) {
60678 // before it used to all dragging of unseleted... - now we dont do that.
60679 if(rowIndex !== false){
60684 //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
60686 //if(!sm.isSelected(rowIndex) || e.hasModifier()){
60689 if (e.hasModifier()){
60690 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
60693 Roo.log("getDragData");
60698 rowIndex: rowIndex,
60699 selections: sm.getSelections ? sm.getSelections() : (
60700 sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : [])
60707 onInitDrag : function(e){
60708 var data = this.dragData;
60709 this.ddel.innerHTML = this.grid.getDragDropText();
60710 this.proxy.update(this.ddel);
60711 // fire start drag?
60714 afterRepair : function(){
60715 this.dragging = false;
60718 getRepairXY : function(e, data){
60722 onEndDrag : function(data, e){
60726 onValidDrop : function(dd, e, id){
60731 beforeInvalidDrop : function(e, id){
60736 * Ext JS Library 1.1.1
60737 * Copyright(c) 2006-2007, Ext JS, LLC.
60739 * Originally Released Under LGPL - original licence link has changed is not relivant.
60742 * <script type="text/javascript">
60747 * @class Roo.grid.ColumnModel
60748 * @extends Roo.util.Observable
60749 * This is the default implementation of a ColumnModel used by the Grid. It defines
60750 * the columns in the grid.
60753 var colModel = new Roo.grid.ColumnModel([
60754 {header: "Ticker", width: 60, sortable: true, locked: true},
60755 {header: "Company Name", width: 150, sortable: true},
60756 {header: "Market Cap.", width: 100, sortable: true},
60757 {header: "$ Sales", width: 100, sortable: true, renderer: money},
60758 {header: "Employees", width: 100, sortable: true, resizable: false}
60763 * The config options listed for this class are options which may appear in each
60764 * individual column definition.
60765 * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
60767 * @param {Object} config An Array of column config objects. See this class's
60768 * config objects for details.
60770 Roo.grid.ColumnModel = function(config){
60772 * The config passed into the constructor
60774 this.config = []; //config;
60777 // if no id, create one
60778 // if the column does not have a dataIndex mapping,
60779 // map it to the order it is in the config
60780 for(var i = 0, len = config.length; i < len; i++){
60781 this.addColumn(config[i]);
60786 * The width of columns which have no width specified (defaults to 100)
60789 this.defaultWidth = 100;
60792 * Default sortable of columns which have no sortable specified (defaults to false)
60795 this.defaultSortable = false;
60799 * @event widthchange
60800 * Fires when the width of a column changes.
60801 * @param {ColumnModel} this
60802 * @param {Number} columnIndex The column index
60803 * @param {Number} newWidth The new width
60805 "widthchange": true,
60807 * @event headerchange
60808 * Fires when the text of a header changes.
60809 * @param {ColumnModel} this
60810 * @param {Number} columnIndex The column index
60811 * @param {Number} newText The new header text
60813 "headerchange": true,
60815 * @event hiddenchange
60816 * Fires when a column is hidden or "unhidden".
60817 * @param {ColumnModel} this
60818 * @param {Number} columnIndex The column index
60819 * @param {Boolean} hidden true if hidden, false otherwise
60821 "hiddenchange": true,
60823 * @event columnmoved
60824 * Fires when a column is moved.
60825 * @param {ColumnModel} this
60826 * @param {Number} oldIndex
60827 * @param {Number} newIndex
60829 "columnmoved" : true,
60831 * @event columlockchange
60832 * Fires when a column's locked state is changed
60833 * @param {ColumnModel} this
60834 * @param {Number} colIndex
60835 * @param {Boolean} locked true if locked
60837 "columnlockchange" : true
60839 Roo.grid.ColumnModel.superclass.constructor.call(this);
60841 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
60843 * @cfg {String} header The header text to display in the Grid view.
60846 * @cfg {String} xsHeader Header at Bootsrap Extra Small width (default for all)
60849 * @cfg {String} smHeader Header at Bootsrap Small width
60852 * @cfg {String} mdHeader Header at Bootsrap Medium width
60855 * @cfg {String} lgHeader Header at Bootsrap Large width
60858 * @cfg {String} xlHeader Header at Bootsrap extra Large width
60861 * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
60862 * {@link Roo.data.Record} definition from which to draw the column's value. If not
60863 * specified, the column's index is used as an index into the Record's data Array.
60866 * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
60867 * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
60870 * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
60871 * Defaults to the value of the {@link #defaultSortable} property.
60872 * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
60875 * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid. Defaults to false.
60878 * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed. Defaults to false.
60881 * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
60884 * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
60887 * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
60888 * given the cell's data value. See {@link #setRenderer}. If not specified, the
60889 * default renderer returns the escaped data value. If an object is returned (bootstrap only)
60890 * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
60893 * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor
60896 * @cfg {String} align (Optional) Set the CSS text-align property of the column. Defaults to undefined.
60899 * @cfg {String} valign (Optional) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc). Defaults to undefined.
60902 * @cfg {String} cursor (Optional)
60905 * @cfg {String} tooltip (Optional)
60908 * @cfg {Number} xs (Optional) can be '0' for hidden at this size (number less than 12)
60911 * @cfg {Number} sm (Optional) can be '0' for hidden at this size (number less than 12)
60914 * @cfg {Number} md (Optional) can be '0' for hidden at this size (number less than 12)
60917 * @cfg {Number} lg (Optional) can be '0' for hidden at this size (number less than 12)
60920 * @cfg {Number} xl (Optional) can be '0' for hidden at this size (number less than 12)
60923 * Returns the id of the column at the specified index.
60924 * @param {Number} index The column index
60925 * @return {String} the id
60927 getColumnId : function(index){
60928 return this.config[index].id;
60932 * Returns the column for a specified id.
60933 * @param {String} id The column id
60934 * @return {Object} the column
60936 getColumnById : function(id){
60937 return this.lookup[id];
60942 * Returns the column Object for a specified dataIndex.
60943 * @param {String} dataIndex The column dataIndex
60944 * @return {Object|Boolean} the column or false if not found
60946 getColumnByDataIndex: function(dataIndex){
60947 var index = this.findColumnIndex(dataIndex);
60948 return index > -1 ? this.config[index] : false;
60952 * Returns the index for a specified column id.
60953 * @param {String} id The column id
60954 * @return {Number} the index, or -1 if not found
60956 getIndexById : function(id){
60957 for(var i = 0, len = this.config.length; i < len; i++){
60958 if(this.config[i].id == id){
60966 * Returns the index for a specified column dataIndex.
60967 * @param {String} dataIndex The column dataIndex
60968 * @return {Number} the index, or -1 if not found
60971 findColumnIndex : function(dataIndex){
60972 for(var i = 0, len = this.config.length; i < len; i++){
60973 if(this.config[i].dataIndex == dataIndex){
60981 moveColumn : function(oldIndex, newIndex){
60982 var c = this.config[oldIndex];
60983 this.config.splice(oldIndex, 1);
60984 this.config.splice(newIndex, 0, c);
60985 this.dataMap = null;
60986 this.fireEvent("columnmoved", this, oldIndex, newIndex);
60989 isLocked : function(colIndex){
60990 return this.config[colIndex].locked === true;
60993 setLocked : function(colIndex, value, suppressEvent){
60994 if(this.isLocked(colIndex) == value){
60997 this.config[colIndex].locked = value;
60998 if(!suppressEvent){
60999 this.fireEvent("columnlockchange", this, colIndex, value);
61003 getTotalLockedWidth : function(){
61004 var totalWidth = 0;
61005 for(var i = 0; i < this.config.length; i++){
61006 if(this.isLocked(i) && !this.isHidden(i)){
61007 this.totalWidth += this.getColumnWidth(i);
61013 getLockedCount : function(){
61014 for(var i = 0, len = this.config.length; i < len; i++){
61015 if(!this.isLocked(i)){
61020 return this.config.length;
61024 * Returns the number of columns.
61027 getColumnCount : function(visibleOnly){
61028 if(visibleOnly === true){
61030 for(var i = 0, len = this.config.length; i < len; i++){
61031 if(!this.isHidden(i)){
61037 return this.config.length;
61041 * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
61042 * @param {Function} fn
61043 * @param {Object} scope (optional)
61044 * @return {Array} result
61046 getColumnsBy : function(fn, scope){
61048 for(var i = 0, len = this.config.length; i < len; i++){
61049 var c = this.config[i];
61050 if(fn.call(scope||this, c, i) === true){
61058 * Returns true if the specified column is sortable.
61059 * @param {Number} col The column index
61060 * @return {Boolean}
61062 isSortable : function(col){
61063 if(typeof this.config[col].sortable == "undefined"){
61064 return this.defaultSortable;
61066 return this.config[col].sortable;
61070 * Returns the rendering (formatting) function defined for the column.
61071 * @param {Number} col The column index.
61072 * @return {Function} The function used to render the cell. See {@link #setRenderer}.
61074 getRenderer : function(col){
61075 if(!this.config[col].renderer){
61076 return Roo.grid.ColumnModel.defaultRenderer;
61078 return this.config[col].renderer;
61082 * Sets the rendering (formatting) function for a column.
61083 * @param {Number} col The column index
61084 * @param {Function} fn The function to use to process the cell's raw data
61085 * to return HTML markup for the grid view. The render function is called with
61086 * the following parameters:<ul>
61087 * <li>Data value.</li>
61088 * <li>Cell metadata. An object in which you may set the following attributes:<ul>
61089 * <li>css A CSS style string to apply to the table cell.</li>
61090 * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
61091 * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
61092 * <li>Row index</li>
61093 * <li>Column index</li>
61094 * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
61096 setRenderer : function(col, fn){
61097 this.config[col].renderer = fn;
61101 * Returns the width for the specified column.
61102 * @param {Number} col The column index
61103 * @param (optional) {String} gridSize bootstrap width size.
61106 getColumnWidth : function(col, gridSize)
61108 var cfg = this.config[col];
61110 if (typeof(gridSize) == 'undefined') {
61111 return cfg.width * 1 || this.defaultWidth;
61113 if (gridSize === false) { // if we set it..
61114 return cfg.width || false;
61116 var sizes = ['xl', 'lg', 'md', 'sm', 'xs'];
61118 for(var i = sizes.indexOf(gridSize); i < sizes.length; i++) {
61119 if (typeof(cfg[ sizes[i] ] ) == 'undefined') {
61122 return cfg[ sizes[i] ];
61129 * Sets the width for a column.
61130 * @param {Number} col The column index
61131 * @param {Number} width The new width
61133 setColumnWidth : function(col, width, suppressEvent){
61134 this.config[col].width = width;
61135 this.totalWidth = null;
61136 if(!suppressEvent){
61137 this.fireEvent("widthchange", this, col, width);
61142 * Returns the total width of all columns.
61143 * @param {Boolean} includeHidden True to include hidden column widths
61146 getTotalWidth : function(includeHidden){
61147 if(!this.totalWidth){
61148 this.totalWidth = 0;
61149 for(var i = 0, len = this.config.length; i < len; i++){
61150 if(includeHidden || !this.isHidden(i)){
61151 this.totalWidth += this.getColumnWidth(i);
61155 return this.totalWidth;
61159 * Returns the header for the specified column.
61160 * @param {Number} col The column index
61163 getColumnHeader : function(col){
61164 return this.config[col].header;
61168 * Sets the header for a column.
61169 * @param {Number} col The column index
61170 * @param {String} header The new header
61172 setColumnHeader : function(col, header){
61173 this.config[col].header = header;
61174 this.fireEvent("headerchange", this, col, header);
61178 * Returns the tooltip for the specified column.
61179 * @param {Number} col The column index
61182 getColumnTooltip : function(col){
61183 return this.config[col].tooltip;
61186 * Sets the tooltip for a column.
61187 * @param {Number} col The column index
61188 * @param {String} tooltip The new tooltip
61190 setColumnTooltip : function(col, tooltip){
61191 this.config[col].tooltip = tooltip;
61195 * Returns the dataIndex for the specified column.
61196 * @param {Number} col The column index
61199 getDataIndex : function(col){
61200 return this.config[col].dataIndex;
61204 * Sets the dataIndex for a column.
61205 * @param {Number} col The column index
61206 * @param {Number} dataIndex The new dataIndex
61208 setDataIndex : function(col, dataIndex){
61209 this.config[col].dataIndex = dataIndex;
61215 * Returns true if the cell is editable.
61216 * @param {Number} colIndex The column index
61217 * @param {Number} rowIndex The row index - this is nto actually used..?
61218 * @return {Boolean}
61220 isCellEditable : function(colIndex, rowIndex){
61221 return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
61225 * Returns the editor defined for the cell/column.
61226 * return false or null to disable editing.
61227 * @param {Number} colIndex The column index
61228 * @param {Number} rowIndex The row index
61231 getCellEditor : function(colIndex, rowIndex){
61232 return this.config[colIndex].editor;
61236 * Sets if a column is editable.
61237 * @param {Number} col The column index
61238 * @param {Boolean} editable True if the column is editable
61240 setEditable : function(col, editable){
61241 this.config[col].editable = editable;
61246 * Returns true if the column is hidden.
61247 * @param {Number} colIndex The column index
61248 * @return {Boolean}
61250 isHidden : function(colIndex){
61251 return this.config[colIndex].hidden;
61256 * Returns true if the column width cannot be changed
61258 isFixed : function(colIndex){
61259 return this.config[colIndex].fixed;
61263 * Returns true if the column can be resized
61264 * @return {Boolean}
61266 isResizable : function(colIndex){
61267 return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
61270 * Sets if a column is hidden.
61271 * @param {Number} colIndex The column index
61272 * @param {Boolean} hidden True if the column is hidden
61274 setHidden : function(colIndex, hidden){
61275 this.config[colIndex].hidden = hidden;
61276 this.totalWidth = null;
61277 this.fireEvent("hiddenchange", this, colIndex, hidden);
61281 * Sets the editor for a column.
61282 * @param {Number} col The column index
61283 * @param {Object} editor The editor object
61285 setEditor : function(col, editor){
61286 this.config[col].editor = editor;
61289 * Add a column (experimental...) - defaults to adding to the end..
61290 * @param {Object} config
61292 addColumn : function(c)
61295 var i = this.config.length;
61296 this.config[i] = c;
61298 if(typeof c.dataIndex == "undefined"){
61301 if(typeof c.renderer == "string"){
61302 c.renderer = Roo.util.Format[c.renderer];
61304 if(typeof c.id == "undefined"){
61307 if(c.editor && c.editor.xtype){
61308 c.editor = Roo.factory(c.editor, Roo.grid);
61310 if(c.editor && c.editor.isFormField){
61311 c.editor = new Roo.grid.GridEditor(c.editor);
61313 this.lookup[c.id] = c;
61318 Roo.grid.ColumnModel.defaultRenderer = function(value)
61320 if(typeof value == "object") {
61323 if(typeof value == "string" && value.length < 1){
61327 return String.format("{0}", value);
61330 // Alias for backwards compatibility
61331 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
61334 * Ext JS Library 1.1.1
61335 * Copyright(c) 2006-2007, Ext JS, LLC.
61337 * Originally Released Under LGPL - original licence link has changed is not relivant.
61340 * <script type="text/javascript">
61344 * @class Roo.grid.AbstractSelectionModel
61345 * @extends Roo.util.Observable
61347 * Abstract base class for grid SelectionModels. It provides the interface that should be
61348 * implemented by descendant classes. This class should not be directly instantiated.
61351 Roo.grid.AbstractSelectionModel = function(){
61352 this.locked = false;
61353 Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
61356 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable, {
61357 /** @ignore Called by the grid automatically. Do not call directly. */
61358 init : function(grid){
61364 * Locks the selections.
61367 this.locked = true;
61371 * Unlocks the selections.
61373 unlock : function(){
61374 this.locked = false;
61378 * Returns true if the selections are locked.
61379 * @return {Boolean}
61381 isLocked : function(){
61382 return this.locked;
61386 * Ext JS Library 1.1.1
61387 * Copyright(c) 2006-2007, Ext JS, LLC.
61389 * Originally Released Under LGPL - original licence link has changed is not relivant.
61392 * <script type="text/javascript">
61395 * @extends Roo.grid.AbstractSelectionModel
61396 * @class Roo.grid.RowSelectionModel
61397 * The default SelectionModel used by {@link Roo.grid.Grid}.
61398 * It supports multiple selections and keyboard selection/navigation.
61400 * @param {Object} config
61402 Roo.grid.RowSelectionModel = function(config){
61403 Roo.apply(this, config);
61404 this.selections = new Roo.util.MixedCollection(false, function(o){
61409 this.lastActive = false;
61413 * @event selectionchange
61414 * Fires when the selection changes
61415 * @param {SelectionModel} this
61417 "selectionchange" : true,
61419 * @event afterselectionchange
61420 * Fires after the selection changes (eg. by key press or clicking)
61421 * @param {SelectionModel} this
61423 "afterselectionchange" : true,
61425 * @event beforerowselect
61426 * Fires when a row is selected being selected, return false to cancel.
61427 * @param {SelectionModel} this
61428 * @param {Number} rowIndex The selected index
61429 * @param {Boolean} keepExisting False if other selections will be cleared
61431 "beforerowselect" : true,
61434 * Fires when a row is selected.
61435 * @param {SelectionModel} this
61436 * @param {Number} rowIndex The selected index
61437 * @param {Roo.data.Record} r The record
61439 "rowselect" : true,
61441 * @event rowdeselect
61442 * Fires when a row is deselected.
61443 * @param {SelectionModel} this
61444 * @param {Number} rowIndex The selected index
61446 "rowdeselect" : true
61448 Roo.grid.RowSelectionModel.superclass.constructor.call(this);
61449 this.locked = false;
61452 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel, {
61454 * @cfg {Boolean} singleSelect
61455 * True to allow selection of only one row at a time (defaults to false)
61457 singleSelect : false,
61460 initEvents : function(){
61462 if(!this.grid.enableDragDrop && !this.grid.enableDrag){
61463 this.grid.on("mousedown", this.handleMouseDown, this);
61464 }else{ // allow click to work like normal
61465 this.grid.on("rowclick", this.handleDragableRowClick, this);
61467 // bootstrap does not have a view..
61468 var view = this.grid.view ? this.grid.view : this.grid;
61469 this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
61470 "up" : function(e){
61472 this.selectPrevious(e.shiftKey);
61473 }else if(this.last !== false && this.lastActive !== false){
61474 var last = this.last;
61475 this.selectRange(this.last, this.lastActive-1);
61476 view.focusRow(this.lastActive);
61477 if(last !== false){
61481 this.selectFirstRow();
61483 this.fireEvent("afterselectionchange", this);
61485 "down" : function(e){
61487 this.selectNext(e.shiftKey);
61488 }else if(this.last !== false && this.lastActive !== false){
61489 var last = this.last;
61490 this.selectRange(this.last, this.lastActive+1);
61491 view.focusRow(this.lastActive);
61492 if(last !== false){
61496 this.selectFirstRow();
61498 this.fireEvent("afterselectionchange", this);
61504 view.on("refresh", this.onRefresh, this);
61505 view.on("rowupdated", this.onRowUpdated, this);
61506 view.on("rowremoved", this.onRemove, this);
61510 onRefresh : function(){
61511 var ds = this.grid.ds, i, v = this.grid.view;
61512 var s = this.selections;
61513 s.each(function(r){
61514 if((i = ds.indexOfId(r.id)) != -1){
61516 s.add(ds.getAt(i)); // updating the selection relate data
61524 onRemove : function(v, index, r){
61525 this.selections.remove(r);
61529 onRowUpdated : function(v, index, r){
61530 if(this.isSelected(r)){
61531 v.onRowSelect(index);
61537 * @param {Array} records The records to select
61538 * @param {Boolean} keepExisting (optional) True to keep existing selections
61540 selectRecords : function(records, keepExisting){
61542 this.clearSelections();
61544 var ds = this.grid.ds;
61545 for(var i = 0, len = records.length; i < len; i++){
61546 this.selectRow(ds.indexOf(records[i]), true);
61551 * Gets the number of selected rows.
61554 getCount : function(){
61555 return this.selections.length;
61559 * Selects the first row in the grid.
61561 selectFirstRow : function(){
61566 * Select the last row.
61567 * @param {Boolean} keepExisting (optional) True to keep existing selections
61569 selectLastRow : function(keepExisting){
61570 this.selectRow(this.grid.ds.getCount() - 1, keepExisting);
61574 * Selects the row immediately following the last selected row.
61575 * @param {Boolean} keepExisting (optional) True to keep existing selections
61577 selectNext : function(keepExisting){
61578 if(this.last !== false && (this.last+1) < this.grid.ds.getCount()){
61579 this.selectRow(this.last+1, keepExisting);
61580 var view = this.grid.view ? this.grid.view : this.grid;
61581 view.focusRow(this.last);
61586 * Selects the row that precedes the last selected row.
61587 * @param {Boolean} keepExisting (optional) True to keep existing selections
61589 selectPrevious : function(keepExisting){
61591 this.selectRow(this.last-1, keepExisting);
61592 var view = this.grid.view ? this.grid.view : this.grid;
61593 view.focusRow(this.last);
61598 * Returns the selected records
61599 * @return {Array} Array of selected records
61601 getSelections : function(){
61602 return [].concat(this.selections.items);
61606 * Returns the first selected record.
61609 getSelected : function(){
61610 return this.selections.itemAt(0);
61615 * Clears all selections.
61617 clearSelections : function(fast){
61622 var ds = this.grid.ds;
61623 var s = this.selections;
61624 s.each(function(r){
61625 this.deselectRow(ds.indexOfId(r.id));
61629 this.selections.clear();
61636 * Selects all rows.
61638 selectAll : function(){
61642 this.selections.clear();
61643 for(var i = 0, len = this.grid.ds.getCount(); i < len; i++){
61644 this.selectRow(i, true);
61649 * Returns True if there is a selection.
61650 * @return {Boolean}
61652 hasSelection : function(){
61653 return this.selections.length > 0;
61657 * Returns True if the specified row is selected.
61658 * @param {Number/Record} record The record or index of the record to check
61659 * @return {Boolean}
61661 isSelected : function(index){
61662 var r = typeof index == "number" ? this.grid.ds.getAt(index) : index;
61663 return (r && this.selections.key(r.id) ? true : false);
61667 * Returns True if the specified record id is selected.
61668 * @param {String} id The id of record to check
61669 * @return {Boolean}
61671 isIdSelected : function(id){
61672 return (this.selections.key(id) ? true : false);
61676 handleMouseDown : function(e, t)
61678 var view = this.grid.view ? this.grid.view : this.grid;
61680 if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
61683 if(e.shiftKey && this.last !== false){
61684 var last = this.last;
61685 this.selectRange(last, rowIndex, e.ctrlKey);
61686 this.last = last; // reset the last
61687 view.focusRow(rowIndex);
61689 var isSelected = this.isSelected(rowIndex);
61690 if(e.button !== 0 && isSelected){
61691 view.focusRow(rowIndex);
61692 }else if(e.ctrlKey && isSelected){
61693 this.deselectRow(rowIndex);
61694 }else if(!isSelected){
61695 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
61696 view.focusRow(rowIndex);
61699 this.fireEvent("afterselectionchange", this);
61702 handleDragableRowClick : function(grid, rowIndex, e)
61704 if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
61705 this.selectRow(rowIndex, false);
61706 var view = this.grid.view ? this.grid.view : this.grid;
61707 view.focusRow(rowIndex);
61708 this.fireEvent("afterselectionchange", this);
61713 * Selects multiple rows.
61714 * @param {Array} rows Array of the indexes of the row to select
61715 * @param {Boolean} keepExisting (optional) True to keep existing selections
61717 selectRows : function(rows, keepExisting){
61719 this.clearSelections();
61721 for(var i = 0, len = rows.length; i < len; i++){
61722 this.selectRow(rows[i], true);
61727 * Selects a range of rows. All rows in between startRow and endRow are also selected.
61728 * @param {Number} startRow The index of the first row in the range
61729 * @param {Number} endRow The index of the last row in the range
61730 * @param {Boolean} keepExisting (optional) True to retain existing selections
61732 selectRange : function(startRow, endRow, keepExisting){
61737 this.clearSelections();
61739 if(startRow <= endRow){
61740 for(var i = startRow; i <= endRow; i++){
61741 this.selectRow(i, true);
61744 for(var i = startRow; i >= endRow; i--){
61745 this.selectRow(i, true);
61751 * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
61752 * @param {Number} startRow The index of the first row in the range
61753 * @param {Number} endRow The index of the last row in the range
61755 deselectRange : function(startRow, endRow, preventViewNotify){
61759 for(var i = startRow; i <= endRow; i++){
61760 this.deselectRow(i, preventViewNotify);
61766 * @param {Number} row The index of the row to select
61767 * @param {Boolean} keepExisting (optional) True to keep existing selections
61769 selectRow : function(index, keepExisting, preventViewNotify){
61770 if(this.locked || (index < 0 || index >= this.grid.ds.getCount())) {
61773 if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
61774 if(!keepExisting || this.singleSelect){
61775 this.clearSelections();
61777 var r = this.grid.ds.getAt(index);
61778 this.selections.add(r);
61779 this.last = this.lastActive = index;
61780 if(!preventViewNotify){
61781 var view = this.grid.view ? this.grid.view : this.grid;
61782 view.onRowSelect(index);
61784 this.fireEvent("rowselect", this, index, r);
61785 this.fireEvent("selectionchange", this);
61791 * @param {Number} row The index of the row to deselect
61793 deselectRow : function(index, preventViewNotify){
61797 if(this.last == index){
61800 if(this.lastActive == index){
61801 this.lastActive = false;
61803 var r = this.grid.ds.getAt(index);
61804 this.selections.remove(r);
61805 if(!preventViewNotify){
61806 var view = this.grid.view ? this.grid.view : this.grid;
61807 view.onRowDeselect(index);
61809 this.fireEvent("rowdeselect", this, index);
61810 this.fireEvent("selectionchange", this);
61814 restoreLast : function(){
61816 this.last = this._last;
61821 acceptsNav : function(row, col, cm){
61822 return !cm.isHidden(col) && cm.isCellEditable(col, row);
61826 onEditorKey : function(field, e){
61827 var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
61832 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
61834 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
61836 }else if(k == e.ENTER && !e.ctrlKey){
61840 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
61842 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
61844 }else if(k == e.ESC){
61848 g.startEditing(newCell[0], newCell[1]);
61853 * Ext JS Library 1.1.1
61854 * Copyright(c) 2006-2007, Ext JS, LLC.
61856 * Originally Released Under LGPL - original licence link has changed is not relivant.
61859 * <script type="text/javascript">
61862 * @class Roo.grid.CellSelectionModel
61863 * @extends Roo.grid.AbstractSelectionModel
61864 * This class provides the basic implementation for cell selection in a grid.
61866 * @param {Object} config The object containing the configuration of this model.
61867 * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
61869 Roo.grid.CellSelectionModel = function(config){
61870 Roo.apply(this, config);
61872 this.selection = null;
61876 * @event beforerowselect
61877 * Fires before a cell is selected.
61878 * @param {SelectionModel} this
61879 * @param {Number} rowIndex The selected row index
61880 * @param {Number} colIndex The selected cell index
61882 "beforecellselect" : true,
61884 * @event cellselect
61885 * Fires when a cell is selected.
61886 * @param {SelectionModel} this
61887 * @param {Number} rowIndex The selected row index
61888 * @param {Number} colIndex The selected cell index
61890 "cellselect" : true,
61892 * @event selectionchange
61893 * Fires when the active selection changes.
61894 * @param {SelectionModel} this
61895 * @param {Object} selection null for no selection or an object (o) with two properties
61897 <li>o.record: the record object for the row the selection is in</li>
61898 <li>o.cell: An array of [rowIndex, columnIndex]</li>
61901 "selectionchange" : true,
61904 * Fires when the tab (or enter) was pressed on the last editable cell
61905 * You can use this to trigger add new row.
61906 * @param {SelectionModel} this
61910 * @event beforeeditnext
61911 * Fires before the next editable sell is made active
61912 * You can use this to skip to another cell or fire the tabend
61913 * if you set cell to false
61914 * @param {Object} eventdata object : { cell : [ row, col ] }
61916 "beforeeditnext" : true
61918 Roo.grid.CellSelectionModel.superclass.constructor.call(this);
61921 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel, {
61923 enter_is_tab: false,
61926 initEvents : function(){
61927 this.grid.on("mousedown", this.handleMouseDown, this);
61928 this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
61929 var view = this.grid.view;
61930 view.on("refresh", this.onViewChange, this);
61931 view.on("rowupdated", this.onRowUpdated, this);
61932 view.on("beforerowremoved", this.clearSelections, this);
61933 view.on("beforerowsinserted", this.clearSelections, this);
61934 if(this.grid.isEditor){
61935 this.grid.on("beforeedit", this.beforeEdit, this);
61940 beforeEdit : function(e){
61941 this.select(e.row, e.column, false, true, e.record);
61945 onRowUpdated : function(v, index, r){
61946 if(this.selection && this.selection.record == r){
61947 v.onCellSelect(index, this.selection.cell[1]);
61952 onViewChange : function(){
61953 this.clearSelections(true);
61957 * Returns the currently selected cell,.
61958 * @return {Array} The selected cell (row, column) or null if none selected.
61960 getSelectedCell : function(){
61961 return this.selection ? this.selection.cell : null;
61965 * Clears all selections.
61966 * @param {Boolean} true to prevent the gridview from being notified about the change.
61968 clearSelections : function(preventNotify){
61969 var s = this.selection;
61971 if(preventNotify !== true){
61972 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
61974 this.selection = null;
61975 this.fireEvent("selectionchange", this, null);
61980 * Returns true if there is a selection.
61981 * @return {Boolean}
61983 hasSelection : function(){
61984 return this.selection ? true : false;
61988 handleMouseDown : function(e, t){
61989 var v = this.grid.getView();
61990 if(this.isLocked()){
61993 var row = v.findRowIndex(t);
61994 var cell = v.findCellIndex(t);
61995 if(row !== false && cell !== false){
61996 this.select(row, cell);
62002 * @param {Number} rowIndex
62003 * @param {Number} collIndex
62005 select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
62006 if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
62007 this.clearSelections();
62008 r = r || this.grid.dataSource.getAt(rowIndex);
62011 cell : [rowIndex, colIndex]
62013 if(!preventViewNotify){
62014 var v = this.grid.getView();
62015 v.onCellSelect(rowIndex, colIndex);
62016 if(preventFocus !== true){
62017 v.focusCell(rowIndex, colIndex);
62020 this.fireEvent("cellselect", this, rowIndex, colIndex);
62021 this.fireEvent("selectionchange", this, this.selection);
62026 isSelectable : function(rowIndex, colIndex, cm){
62027 return !cm.isHidden(colIndex);
62031 handleKeyDown : function(e){
62032 //Roo.log('Cell Sel Model handleKeyDown');
62033 if(!e.isNavKeyPress()){
62036 var g = this.grid, s = this.selection;
62039 var cell = g.walkCells(0, 0, 1, this.isSelectable, this);
62041 this.select(cell[0], cell[1]);
62046 var walk = function(row, col, step){
62047 return g.walkCells(row, col, step, sm.isSelectable, sm);
62049 var k = e.getKey(), r = s.cell[0], c = s.cell[1];
62056 // handled by onEditorKey
62057 if (g.isEditor && g.editing) {
62061 newCell = walk(r, c-1, -1);
62063 newCell = walk(r, c+1, 1);
62068 newCell = walk(r+1, c, 1);
62072 newCell = walk(r-1, c, -1);
62076 newCell = walk(r, c+1, 1);
62080 newCell = walk(r, c-1, -1);
62085 if(g.isEditor && !g.editing){
62086 g.startEditing(r, c);
62095 this.select(newCell[0], newCell[1]);
62101 acceptsNav : function(row, col, cm){
62102 return !cm.isHidden(col) && cm.isCellEditable(col, row);
62106 * @param {Number} field (not used) - as it's normally used as a listener
62107 * @param {Number} e - event - fake it by using
62109 * var e = Roo.EventObjectImpl.prototype;
62110 * e.keyCode = e.TAB
62114 onEditorKey : function(field, e){
62116 var k = e.getKey(),
62119 ed = g.activeEditor,
62121 ///Roo.log('onEditorKey' + k);
62124 if (this.enter_is_tab && k == e.ENTER) {
62130 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
62132 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
62138 } else if(k == e.ENTER && !e.ctrlKey){
62141 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
62143 } else if(k == e.ESC){
62148 var ecall = { cell : newCell, forward : forward };
62149 this.fireEvent('beforeeditnext', ecall );
62150 newCell = ecall.cell;
62151 forward = ecall.forward;
62155 //Roo.log('next cell after edit');
62156 g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
62157 } else if (forward) {
62158 // tabbed past last
62159 this.fireEvent.defer(100, this, ['tabend',this]);
62164 * Ext JS Library 1.1.1
62165 * Copyright(c) 2006-2007, Ext JS, LLC.
62167 * Originally Released Under LGPL - original licence link has changed is not relivant.
62170 * <script type="text/javascript">
62174 * @class Roo.grid.EditorGrid
62175 * @extends Roo.grid.Grid
62176 * Class for creating and editable grid.
62177 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
62178 * The container MUST have some type of size defined for the grid to fill. The container will be
62179 * automatically set to position relative if it isn't already.
62180 * @param {Object} dataSource The data model to bind to
62181 * @param {Object} colModel The column model with info about this grid's columns
62183 Roo.grid.EditorGrid = function(container, config){
62184 Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
62185 this.getGridEl().addClass("xedit-grid");
62187 if(!this.selModel){
62188 this.selModel = new Roo.grid.CellSelectionModel();
62191 this.activeEditor = null;
62195 * @event beforeedit
62196 * Fires before cell editing is triggered. The edit event object has the following properties <br />
62197 * <ul style="padding:5px;padding-left:16px;">
62198 * <li>grid - This grid</li>
62199 * <li>record - The record being edited</li>
62200 * <li>field - The field name being edited</li>
62201 * <li>value - The value for the field being edited.</li>
62202 * <li>row - The grid row index</li>
62203 * <li>column - The grid column index</li>
62204 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
62206 * @param {Object} e An edit event (see above for description)
62208 "beforeedit" : true,
62211 * Fires after a cell is edited. <br />
62212 * <ul style="padding:5px;padding-left:16px;">
62213 * <li>grid - This grid</li>
62214 * <li>record - The record being edited</li>
62215 * <li>field - The field name being edited</li>
62216 * <li>value - The value being set</li>
62217 * <li>originalValue - The original value for the field, before the edit.</li>
62218 * <li>row - The grid row index</li>
62219 * <li>column - The grid column index</li>
62221 * @param {Object} e An edit event (see above for description)
62223 "afteredit" : true,
62225 * @event validateedit
62226 * Fires after a cell is edited, but before the value is set in the record.
62227 * You can use this to modify the value being set in the field, Return false
62228 * to cancel the change. The edit event object has the following properties <br />
62229 * <ul style="padding:5px;padding-left:16px;">
62230 * <li>editor - This editor</li>
62231 * <li>grid - This grid</li>
62232 * <li>record - The record being edited</li>
62233 * <li>field - The field name being edited</li>
62234 * <li>value - The value being set</li>
62235 * <li>originalValue - The original value for the field, before the edit.</li>
62236 * <li>row - The grid row index</li>
62237 * <li>column - The grid column index</li>
62238 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
62240 * @param {Object} e An edit event (see above for description)
62242 "validateedit" : true
62244 this.on("bodyscroll", this.stopEditing, this);
62245 this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick, this);
62248 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
62250 * @cfg {Number} clicksToEdit
62251 * The number of clicks on a cell required to display the cell's editor (defaults to 2)
62258 trackMouseOver: false, // causes very odd FF errors
62260 onCellDblClick : function(g, row, col){
62261 this.startEditing(row, col);
62264 onEditComplete : function(ed, value, startValue){
62265 this.editing = false;
62266 this.activeEditor = null;
62267 ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
62269 var field = this.colModel.getDataIndex(ed.col);
62274 originalValue: startValue,
62281 var cell = Roo.get(this.view.getCell(ed.row,ed.col));
62284 if(String(value) !== String(startValue)){
62286 if(this.fireEvent("validateedit", e) !== false && !e.cancel){
62287 r.set(field, e.value);
62288 // if we are dealing with a combo box..
62289 // then we also set the 'name' colum to be the displayField
62290 if (ed.field.displayField && ed.field.name) {
62291 r.set(ed.field.name, ed.field.el.dom.value);
62294 delete e.cancel; //?? why!!!
62295 this.fireEvent("afteredit", e);
62298 this.fireEvent("afteredit", e); // always fire it!
62300 this.view.focusCell(ed.row, ed.col);
62304 * Starts editing the specified for the specified row/column
62305 * @param {Number} rowIndex
62306 * @param {Number} colIndex
62308 startEditing : function(row, col){
62309 this.stopEditing();
62310 if(this.colModel.isCellEditable(col, row)){
62311 this.view.ensureVisible(row, col, true);
62313 var r = this.dataSource.getAt(row);
62314 var field = this.colModel.getDataIndex(col);
62315 var cell = Roo.get(this.view.getCell(row,col));
62320 value: r.data[field],
62325 if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
62326 this.editing = true;
62327 var ed = this.colModel.getCellEditor(col, row);
62333 ed.render(ed.parentEl || document.body);
62339 (function(){ // complex but required for focus issues in safari, ie and opera
62343 ed.on("complete", this.onEditComplete, this, {single: true});
62344 ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
62345 this.activeEditor = ed;
62346 var v = r.data[field];
62347 ed.startEdit(this.view.getCell(row, col), v);
62348 // combo's with 'displayField and name set
62349 if (ed.field.displayField && ed.field.name) {
62350 ed.field.el.dom.value = r.data[ed.field.name];
62354 }).defer(50, this);
62360 * Stops any active editing
62362 stopEditing : function(){
62363 if(this.activeEditor){
62364 this.activeEditor.completeEdit();
62366 this.activeEditor = null;
62370 * Called to get grid's drag proxy text, by default returns this.ddText.
62373 getDragDropText : function(){
62374 var count = this.selModel.getSelectedCell() ? 1 : 0;
62375 return String.format(this.ddText, count, count == 1 ? '' : 's');
62380 * Ext JS Library 1.1.1
62381 * Copyright(c) 2006-2007, Ext JS, LLC.
62383 * Originally Released Under LGPL - original licence link has changed is not relivant.
62386 * <script type="text/javascript">
62389 // private - not really -- you end up using it !
62390 // This is a support class used internally by the Grid components
62393 * @class Roo.grid.GridEditor
62394 * @extends Roo.Editor
62395 * Class for creating and editable grid elements.
62396 * @param {Object} config any settings (must include field)
62398 Roo.grid.GridEditor = function(field, config){
62399 if (!config && field.field) {
62401 field = Roo.factory(config.field, Roo.form);
62403 Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
62404 field.monitorTab = false;
62407 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
62410 * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
62413 alignment: "tl-tl",
62416 cls: "x-small-editor x-grid-editor",
62421 * Ext JS Library 1.1.1
62422 * Copyright(c) 2006-2007, Ext JS, LLC.
62424 * Originally Released Under LGPL - original licence link has changed is not relivant.
62427 * <script type="text/javascript">
62432 Roo.grid.PropertyRecord = Roo.data.Record.create([
62433 {name:'name',type:'string'}, 'value'
62437 Roo.grid.PropertyStore = function(grid, source){
62439 this.store = new Roo.data.Store({
62440 recordType : Roo.grid.PropertyRecord
62442 this.store.on('update', this.onUpdate, this);
62444 this.setSource(source);
62446 Roo.grid.PropertyStore.superclass.constructor.call(this);
62451 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
62452 setSource : function(o){
62454 this.store.removeAll();
62457 if(this.isEditableValue(o[k])){
62458 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
62461 this.store.loadRecords({records: data}, {}, true);
62464 onUpdate : function(ds, record, type){
62465 if(type == Roo.data.Record.EDIT){
62466 var v = record.data['value'];
62467 var oldValue = record.modified['value'];
62468 if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
62469 this.source[record.id] = v;
62471 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
62478 getProperty : function(row){
62479 return this.store.getAt(row);
62482 isEditableValue: function(val){
62483 if(val && val instanceof Date){
62485 }else if(typeof val == 'object' || typeof val == 'function'){
62491 setValue : function(prop, value){
62492 this.source[prop] = value;
62493 this.store.getById(prop).set('value', value);
62496 getSource : function(){
62497 return this.source;
62501 Roo.grid.PropertyColumnModel = function(grid, store){
62504 g.PropertyColumnModel.superclass.constructor.call(this, [
62505 {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
62506 {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
62508 this.store = store;
62509 this.bselect = Roo.DomHelper.append(document.body, {
62510 tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
62511 {tag: 'option', value: 'true', html: 'true'},
62512 {tag: 'option', value: 'false', html: 'false'}
62515 Roo.id(this.bselect);
62518 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
62519 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
62520 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
62521 'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
62522 'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
62524 this.renderCellDelegate = this.renderCell.createDelegate(this);
62525 this.renderPropDelegate = this.renderProp.createDelegate(this);
62528 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
62532 valueText : 'Value',
62534 dateFormat : 'm/j/Y',
62537 renderDate : function(dateVal){
62538 return dateVal.dateFormat(this.dateFormat);
62541 renderBool : function(bVal){
62542 return bVal ? 'true' : 'false';
62545 isCellEditable : function(colIndex, rowIndex){
62546 return colIndex == 1;
62549 getRenderer : function(col){
62551 this.renderCellDelegate : this.renderPropDelegate;
62554 renderProp : function(v){
62555 return this.getPropertyName(v);
62558 renderCell : function(val){
62560 if(val instanceof Date){
62561 rv = this.renderDate(val);
62562 }else if(typeof val == 'boolean'){
62563 rv = this.renderBool(val);
62565 return Roo.util.Format.htmlEncode(rv);
62568 getPropertyName : function(name){
62569 var pn = this.grid.propertyNames;
62570 return pn && pn[name] ? pn[name] : name;
62573 getCellEditor : function(colIndex, rowIndex){
62574 var p = this.store.getProperty(rowIndex);
62575 var n = p.data['name'], val = p.data['value'];
62577 if(typeof(this.grid.customEditors[n]) == 'string'){
62578 return this.editors[this.grid.customEditors[n]];
62580 if(typeof(this.grid.customEditors[n]) != 'undefined'){
62581 return this.grid.customEditors[n];
62583 if(val instanceof Date){
62584 return this.editors['date'];
62585 }else if(typeof val == 'number'){
62586 return this.editors['number'];
62587 }else if(typeof val == 'boolean'){
62588 return this.editors['boolean'];
62590 return this.editors['string'];
62596 * @class Roo.grid.PropertyGrid
62597 * @extends Roo.grid.EditorGrid
62598 * This class represents the interface of a component based property grid control.
62599 * <br><br>Usage:<pre><code>
62600 var grid = new Roo.grid.PropertyGrid("my-container-id", {
62608 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
62609 * The container MUST have some type of size defined for the grid to fill. The container will be
62610 * automatically set to position relative if it isn't already.
62611 * @param {Object} config A config object that sets properties on this grid.
62613 Roo.grid.PropertyGrid = function(container, config){
62614 config = config || {};
62615 var store = new Roo.grid.PropertyStore(this);
62616 this.store = store;
62617 var cm = new Roo.grid.PropertyColumnModel(this, store);
62618 store.store.sort('name', 'ASC');
62619 Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
62622 enableColLock:false,
62623 enableColumnMove:false,
62625 trackMouseOver: false,
62628 this.getGridEl().addClass('x-props-grid');
62629 this.lastEditRow = null;
62630 this.on('columnresize', this.onColumnResize, this);
62633 * @event beforepropertychange
62634 * Fires before a property changes (return false to stop?)
62635 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
62636 * @param {String} id Record Id
62637 * @param {String} newval New Value
62638 * @param {String} oldval Old Value
62640 "beforepropertychange": true,
62642 * @event propertychange
62643 * Fires after a property changes
62644 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
62645 * @param {String} id Record Id
62646 * @param {String} newval New Value
62647 * @param {String} oldval Old Value
62649 "propertychange": true
62651 this.customEditors = this.customEditors || {};
62653 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
62656 * @cfg {Object} customEditors map of colnames=> custom editors.
62657 * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
62658 * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
62659 * false disables editing of the field.
62663 * @cfg {Object} propertyNames map of property Names to their displayed value
62666 render : function(){
62667 Roo.grid.PropertyGrid.superclass.render.call(this);
62668 this.autoSize.defer(100, this);
62671 autoSize : function(){
62672 Roo.grid.PropertyGrid.superclass.autoSize.call(this);
62674 this.view.fitColumns();
62678 onColumnResize : function(){
62679 this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
62683 * Sets the data for the Grid
62684 * accepts a Key => Value object of all the elements avaiable.
62685 * @param {Object} data to appear in grid.
62687 setSource : function(source){
62688 this.store.setSource(source);
62692 * Gets all the data from the grid.
62693 * @return {Object} data data stored in grid
62695 getSource : function(){
62696 return this.store.getSource();
62705 * @class Roo.grid.Calendar
62706 * @extends Roo.grid.Grid
62707 * This class extends the Grid to provide a calendar widget
62708 * <br><br>Usage:<pre><code>
62709 var grid = new Roo.grid.Calendar("my-container-id", {
62712 selModel: mySelectionModel,
62713 autoSizeColumns: true,
62714 monitorWindowResize: false,
62715 trackMouseOver: true
62716 eventstore : real data store..
62722 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
62723 * The container MUST have some type of size defined for the grid to fill. The container will be
62724 * automatically set to position relative if it isn't already.
62725 * @param {Object} config A config object that sets properties on this grid.
62727 Roo.grid.Calendar = function(container, config){
62728 // initialize the container
62729 this.container = Roo.get(container);
62730 this.container.update("");
62731 this.container.setStyle("overflow", "hidden");
62732 this.container.addClass('x-grid-container');
62734 this.id = this.container.id;
62736 Roo.apply(this, config);
62737 // check and correct shorthanded configs
62741 for (var r = 0;r < 6;r++) {
62744 for (var c =0;c < 7;c++) {
62748 if (this.eventStore) {
62749 this.eventStore= Roo.factory(this.eventStore, Roo.data);
62750 this.eventStore.on('load',this.onLoad, this);
62751 this.eventStore.on('beforeload',this.clearEvents, this);
62755 this.dataSource = new Roo.data.Store({
62756 proxy: new Roo.data.MemoryProxy(rows),
62757 reader: new Roo.data.ArrayReader({}, [
62758 'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
62761 this.dataSource.load();
62762 this.ds = this.dataSource;
62763 this.ds.xmodule = this.xmodule || false;
62766 var cellRender = function(v,x,r)
62768 return String.format(
62769 '<div class="fc-day fc-widget-content"><div>' +
62770 '<div class="fc-event-container"></div>' +
62771 '<div class="fc-day-number">{0}</div>'+
62773 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
62774 '</div></div>', v);
62779 this.colModel = new Roo.grid.ColumnModel( [
62781 xtype: 'ColumnModel',
62783 dataIndex : 'weekday0',
62785 renderer : cellRender
62788 xtype: 'ColumnModel',
62790 dataIndex : 'weekday1',
62792 renderer : cellRender
62795 xtype: 'ColumnModel',
62797 dataIndex : 'weekday2',
62798 header : 'Tuesday',
62799 renderer : cellRender
62802 xtype: 'ColumnModel',
62804 dataIndex : 'weekday3',
62805 header : 'Wednesday',
62806 renderer : cellRender
62809 xtype: 'ColumnModel',
62811 dataIndex : 'weekday4',
62812 header : 'Thursday',
62813 renderer : cellRender
62816 xtype: 'ColumnModel',
62818 dataIndex : 'weekday5',
62820 renderer : cellRender
62823 xtype: 'ColumnModel',
62825 dataIndex : 'weekday6',
62826 header : 'Saturday',
62827 renderer : cellRender
62830 this.cm = this.colModel;
62831 this.cm.xmodule = this.xmodule || false;
62835 //this.selModel = new Roo.grid.CellSelectionModel();
62836 //this.sm = this.selModel;
62837 //this.selModel.init(this);
62841 this.container.setWidth(this.width);
62845 this.container.setHeight(this.height);
62852 * The raw click event for the entire grid.
62853 * @param {Roo.EventObject} e
62858 * The raw dblclick event for the entire grid.
62859 * @param {Roo.EventObject} e
62863 * @event contextmenu
62864 * The raw contextmenu event for the entire grid.
62865 * @param {Roo.EventObject} e
62867 "contextmenu" : true,
62870 * The raw mousedown event for the entire grid.
62871 * @param {Roo.EventObject} e
62873 "mousedown" : true,
62876 * The raw mouseup event for the entire grid.
62877 * @param {Roo.EventObject} e
62882 * The raw mouseover event for the entire grid.
62883 * @param {Roo.EventObject} e
62885 "mouseover" : true,
62888 * The raw mouseout event for the entire grid.
62889 * @param {Roo.EventObject} e
62894 * The raw keypress event for the entire grid.
62895 * @param {Roo.EventObject} e
62900 * The raw keydown event for the entire grid.
62901 * @param {Roo.EventObject} e
62909 * Fires when a cell is clicked
62910 * @param {Grid} this
62911 * @param {Number} rowIndex
62912 * @param {Number} columnIndex
62913 * @param {Roo.EventObject} e
62915 "cellclick" : true,
62917 * @event celldblclick
62918 * Fires when a cell is double clicked
62919 * @param {Grid} this
62920 * @param {Number} rowIndex
62921 * @param {Number} columnIndex
62922 * @param {Roo.EventObject} e
62924 "celldblclick" : true,
62927 * Fires when a row is clicked
62928 * @param {Grid} this
62929 * @param {Number} rowIndex
62930 * @param {Roo.EventObject} e
62934 * @event rowdblclick
62935 * Fires when a row is double clicked
62936 * @param {Grid} this
62937 * @param {Number} rowIndex
62938 * @param {Roo.EventObject} e
62940 "rowdblclick" : true,
62942 * @event headerclick
62943 * Fires when a header is clicked
62944 * @param {Grid} this
62945 * @param {Number} columnIndex
62946 * @param {Roo.EventObject} e
62948 "headerclick" : true,
62950 * @event headerdblclick
62951 * Fires when a header cell is double clicked
62952 * @param {Grid} this
62953 * @param {Number} columnIndex
62954 * @param {Roo.EventObject} e
62956 "headerdblclick" : true,
62958 * @event rowcontextmenu
62959 * Fires when a row is right clicked
62960 * @param {Grid} this
62961 * @param {Number} rowIndex
62962 * @param {Roo.EventObject} e
62964 "rowcontextmenu" : true,
62966 * @event cellcontextmenu
62967 * Fires when a cell is right clicked
62968 * @param {Grid} this
62969 * @param {Number} rowIndex
62970 * @param {Number} cellIndex
62971 * @param {Roo.EventObject} e
62973 "cellcontextmenu" : true,
62975 * @event headercontextmenu
62976 * Fires when a header is right clicked
62977 * @param {Grid} this
62978 * @param {Number} columnIndex
62979 * @param {Roo.EventObject} e
62981 "headercontextmenu" : true,
62983 * @event bodyscroll
62984 * Fires when the body element is scrolled
62985 * @param {Number} scrollLeft
62986 * @param {Number} scrollTop
62988 "bodyscroll" : true,
62990 * @event columnresize
62991 * Fires when the user resizes a column
62992 * @param {Number} columnIndex
62993 * @param {Number} newSize
62995 "columnresize" : true,
62997 * @event columnmove
62998 * Fires when the user moves a column
62999 * @param {Number} oldIndex
63000 * @param {Number} newIndex
63002 "columnmove" : true,
63005 * Fires when row(s) start being dragged
63006 * @param {Grid} this
63007 * @param {Roo.GridDD} dd The drag drop object
63008 * @param {event} e The raw browser event
63010 "startdrag" : true,
63013 * Fires when a drag operation is complete
63014 * @param {Grid} this
63015 * @param {Roo.GridDD} dd The drag drop object
63016 * @param {event} e The raw browser event
63021 * Fires when dragged row(s) are dropped on a valid DD target
63022 * @param {Grid} this
63023 * @param {Roo.GridDD} dd The drag drop object
63024 * @param {String} targetId The target drag drop object
63025 * @param {event} e The raw browser event
63030 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
63031 * @param {Grid} this
63032 * @param {Roo.GridDD} dd The drag drop object
63033 * @param {String} targetId The target drag drop object
63034 * @param {event} e The raw browser event
63039 * Fires when the dragged row(s) first cross another DD target while being dragged
63040 * @param {Grid} this
63041 * @param {Roo.GridDD} dd The drag drop object
63042 * @param {String} targetId The target drag drop object
63043 * @param {event} e The raw browser event
63045 "dragenter" : true,
63048 * Fires when the dragged row(s) leave another DD target while being dragged
63049 * @param {Grid} this
63050 * @param {Roo.GridDD} dd The drag drop object
63051 * @param {String} targetId The target drag drop object
63052 * @param {event} e The raw browser event
63057 * Fires when a row is rendered, so you can change add a style to it.
63058 * @param {GridView} gridview The grid view
63059 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
63065 * Fires when the grid is rendered
63066 * @param {Grid} grid
63071 * Fires when a date is selected
63072 * @param {DatePicker} this
63073 * @param {Date} date The selected date
63077 * @event monthchange
63078 * Fires when the displayed month changes
63079 * @param {DatePicker} this
63080 * @param {Date} date The selected month
63082 'monthchange': true,
63084 * @event evententer
63085 * Fires when mouse over an event
63086 * @param {Calendar} this
63087 * @param {event} Event
63089 'evententer': true,
63091 * @event eventleave
63092 * Fires when the mouse leaves an
63093 * @param {Calendar} this
63096 'eventleave': true,
63098 * @event eventclick
63099 * Fires when the mouse click an
63100 * @param {Calendar} this
63103 'eventclick': true,
63105 * @event eventrender
63106 * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
63107 * @param {Calendar} this
63108 * @param {data} data to be modified
63110 'eventrender': true
63114 Roo.grid.Grid.superclass.constructor.call(this);
63115 this.on('render', function() {
63116 this.view.el.addClass('x-grid-cal');
63118 (function() { this.setDate(new Date()); }).defer(100,this); //default today..
63122 if (!Roo.grid.Calendar.style) {
63123 Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
63126 '.x-grid-cal .x-grid-col' : {
63127 height: 'auto !important',
63128 'vertical-align': 'top'
63130 '.x-grid-cal .fc-event-hori' : {
63141 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
63143 * @cfg {Store} eventStore The store that loads events.
63148 activeDate : false,
63151 monitorWindowResize : false,
63154 resizeColumns : function() {
63155 var col = (this.view.el.getWidth() / 7) - 3;
63156 // loop through cols, and setWidth
63157 for(var i =0 ; i < 7 ; i++){
63158 this.cm.setColumnWidth(i, col);
63161 setDate :function(date) {
63163 Roo.log('setDate?');
63165 this.resizeColumns();
63166 var vd = this.activeDate;
63167 this.activeDate = date;
63168 // if(vd && this.el){
63169 // var t = date.getTime();
63170 // if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
63171 // Roo.log('using add remove');
63173 // this.fireEvent('monthchange', this, date);
63175 // this.cells.removeClass("fc-state-highlight");
63176 // this.cells.each(function(c){
63177 // if(c.dateValue == t){
63178 // c.addClass("fc-state-highlight");
63179 // setTimeout(function(){
63180 // try{c.dom.firstChild.focus();}catch(e){}
63190 var days = date.getDaysInMonth();
63192 var firstOfMonth = date.getFirstDateOfMonth();
63193 var startingPos = firstOfMonth.getDay()-this.startDay;
63195 if(startingPos < this.startDay){
63199 var pm = date.add(Date.MONTH, -1);
63200 var prevStart = pm.getDaysInMonth()-startingPos;
63204 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
63206 this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
63207 //this.cells.addClassOnOver('fc-state-hover');
63209 var cells = this.cells.elements;
63210 var textEls = this.textNodes;
63212 //Roo.each(cells, function(cell){
63213 // cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
63216 days += startingPos;
63218 // convert everything to numbers so it's fast
63219 var day = 86400000;
63220 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
63223 //Roo.log(prevStart);
63225 var today = new Date().clearTime().getTime();
63226 var sel = date.clearTime().getTime();
63227 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
63228 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
63229 var ddMatch = this.disabledDatesRE;
63230 var ddText = this.disabledDatesText;
63231 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
63232 var ddaysText = this.disabledDaysText;
63233 var format = this.format;
63235 var setCellClass = function(cal, cell){
63237 //Roo.log('set Cell Class');
63239 var t = d.getTime();
63244 cell.dateValue = t;
63246 cell.className += " fc-today";
63247 cell.className += " fc-state-highlight";
63248 cell.title = cal.todayText;
63251 // disable highlight in other month..
63252 cell.className += " fc-state-highlight";
63257 //cell.className = " fc-state-disabled";
63258 cell.title = cal.minText;
63262 //cell.className = " fc-state-disabled";
63263 cell.title = cal.maxText;
63267 if(ddays.indexOf(d.getDay()) != -1){
63268 // cell.title = ddaysText;
63269 // cell.className = " fc-state-disabled";
63272 if(ddMatch && format){
63273 var fvalue = d.dateFormat(format);
63274 if(ddMatch.test(fvalue)){
63275 cell.title = ddText.replace("%0", fvalue);
63276 cell.className = " fc-state-disabled";
63280 if (!cell.initialClassName) {
63281 cell.initialClassName = cell.dom.className;
63284 cell.dom.className = cell.initialClassName + ' ' + cell.className;
63289 for(; i < startingPos; i++) {
63290 cells[i].dayName = (++prevStart);
63291 Roo.log(textEls[i]);
63292 d.setDate(d.getDate()+1);
63294 //cells[i].className = "fc-past fc-other-month";
63295 setCellClass(this, cells[i]);
63300 for(; i < days; i++){
63301 intDay = i - startingPos + 1;
63302 cells[i].dayName = (intDay);
63303 d.setDate(d.getDate()+1);
63305 cells[i].className = ''; // "x-date-active";
63306 setCellClass(this, cells[i]);
63310 for(; i < 42; i++) {
63311 //textEls[i].innerHTML = (++extraDays);
63313 d.setDate(d.getDate()+1);
63314 cells[i].dayName = (++extraDays);
63315 cells[i].className = "fc-future fc-other-month";
63316 setCellClass(this, cells[i]);
63319 //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
63321 var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
63323 // this will cause all the cells to mis
63326 for (var r = 0;r < 6;r++) {
63327 for (var c =0;c < 7;c++) {
63328 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
63332 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
63333 for(i=0;i<cells.length;i++) {
63335 this.cells.elements[i].dayName = cells[i].dayName ;
63336 this.cells.elements[i].className = cells[i].className;
63337 this.cells.elements[i].initialClassName = cells[i].initialClassName ;
63338 this.cells.elements[i].title = cells[i].title ;
63339 this.cells.elements[i].dateValue = cells[i].dateValue ;
63345 //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
63346 //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
63348 ////if(totalRows != 6){
63349 //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
63350 // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
63353 this.fireEvent('monthchange', this, date);
63358 * Returns the grid's SelectionModel.
63359 * @return {SelectionModel}
63361 getSelectionModel : function(){
63362 if(!this.selModel){
63363 this.selModel = new Roo.grid.CellSelectionModel();
63365 return this.selModel;
63369 this.eventStore.load()
63375 findCell : function(dt) {
63376 dt = dt.clearTime().getTime();
63378 this.cells.each(function(c){
63379 //Roo.log("check " +c.dateValue + '?=' + dt);
63380 if(c.dateValue == dt){
63390 findCells : function(rec) {
63391 var s = rec.data.start_dt.clone().clearTime().getTime();
63393 var e= rec.data.end_dt.clone().clearTime().getTime();
63396 this.cells.each(function(c){
63397 ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
63399 if(c.dateValue > e){
63402 if(c.dateValue < s){
63411 findBestRow: function(cells)
63415 for (var i =0 ; i < cells.length;i++) {
63416 ret = Math.max(cells[i].rows || 0,ret);
63423 addItem : function(rec)
63425 // look for vertical location slot in
63426 var cells = this.findCells(rec);
63428 rec.row = this.findBestRow(cells);
63430 // work out the location.
63434 for(var i =0; i < cells.length; i++) {
63442 if (crow.start.getY() == cells[i].getY()) {
63444 crow.end = cells[i];
63460 for (var i = 0; i < cells.length;i++) {
63461 cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
63468 clearEvents: function() {
63470 if (!this.eventStore.getCount()) {
63473 // reset number of rows in cells.
63474 Roo.each(this.cells.elements, function(c){
63478 this.eventStore.each(function(e) {
63479 this.clearEvent(e);
63484 clearEvent : function(ev)
63487 Roo.each(ev.els, function(el) {
63488 el.un('mouseenter' ,this.onEventEnter, this);
63489 el.un('mouseleave' ,this.onEventLeave, this);
63497 renderEvent : function(ev,ctr) {
63499 ctr = this.view.el.select('.fc-event-container',true).first();
63503 this.clearEvent(ev);
63509 var cells = ev.cells;
63510 var rows = ev.rows;
63511 this.fireEvent('eventrender', this, ev);
63513 for(var i =0; i < rows.length; i++) {
63517 cls += ' fc-event-start';
63519 if ((i+1) == rows.length) {
63520 cls += ' fc-event-end';
63523 //Roo.log(ev.data);
63524 // how many rows should it span..
63525 var cg = this.eventTmpl.append(ctr,Roo.apply({
63528 }, ev.data) , true);
63531 cg.on('mouseenter' ,this.onEventEnter, this, ev);
63532 cg.on('mouseleave' ,this.onEventLeave, this, ev);
63533 cg.on('click', this.onEventClick, this, ev);
63537 var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
63538 var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
63541 cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);
63542 cg.setWidth(ebox.right - sbox.x -2);
63546 renderEvents: function()
63548 // first make sure there is enough space..
63550 if (!this.eventTmpl) {
63551 this.eventTmpl = new Roo.Template(
63552 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}" style="position: absolute" unselectable="on">' +
63553 '<div class="fc-event-inner">' +
63554 '<span class="fc-event-time">{time}</span>' +
63555 '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
63557 '<div class="ui-resizable-heandle ui-resizable-e"> </div>' +
63565 this.cells.each(function(c) {
63566 //Roo.log(c.select('.fc-day-content div',true).first());
63567 c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
63570 var ctr = this.view.el.select('.fc-event-container',true).first();
63573 this.eventStore.each(function(ev){
63575 this.renderEvent(ev);
63579 this.view.layout();
63583 onEventEnter: function (e, el,event,d) {
63584 this.fireEvent('evententer', this, el, event);
63587 onEventLeave: function (e, el,event,d) {
63588 this.fireEvent('eventleave', this, el, event);
63591 onEventClick: function (e, el,event,d) {
63592 this.fireEvent('eventclick', this, el, event);
63595 onMonthChange: function () {
63599 onLoad: function () {
63601 //Roo.log('calendar onload');
63603 if(this.eventStore.getCount() > 0){
63607 this.eventStore.each(function(d){
63612 if (typeof(add.end_dt) == 'undefined') {
63613 Roo.log("Missing End time in calendar data: ");
63617 if (typeof(add.start_dt) == 'undefined') {
63618 Roo.log("Missing Start time in calendar data: ");
63622 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
63623 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
63624 add.id = add.id || d.id;
63625 add.title = add.title || '??';
63633 this.renderEvents();
63643 render : function ()
63647 if (!this.view.el.hasClass('course-timesheet')) {
63648 this.view.el.addClass('course-timesheet');
63650 if (this.tsStyle) {
63655 Roo.log(_this.grid.view.el.getWidth());
63658 this.tsStyle = Roo.util.CSS.createStyleSheet({
63659 '.course-timesheet .x-grid-row' : {
63662 '.x-grid-row td' : {
63663 'vertical-align' : 0
63665 '.course-edit-link' : {
63667 'text-overflow' : 'ellipsis',
63668 'overflow' : 'hidden',
63669 'white-space' : 'nowrap',
63670 'cursor' : 'pointer'
63675 '.de-act-sup-link' : {
63676 'color' : 'purple',
63677 'text-decoration' : 'line-through'
63681 'text-decoration' : 'line-through'
63683 '.course-timesheet .course-highlight' : {
63684 'border-top-style': 'dashed !important',
63685 'border-bottom-bottom': 'dashed !important'
63687 '.course-timesheet .course-item' : {
63688 'font-family' : 'tahoma, arial, helvetica',
63689 'font-size' : '11px',
63690 'overflow' : 'hidden',
63691 'padding-left' : '10px',
63692 'padding-right' : '10px',
63693 'padding-top' : '10px'
63701 monitorWindowResize : false,
63702 cellrenderer : function(v,x,r)
63707 xtype: 'CellSelectionModel',
63714 beforeload : function (_self, options)
63716 options.params = options.params || {};
63717 options.params._month = _this.monthField.getValue();
63718 options.params.limit = 9999;
63719 options.params['sort'] = 'when_dt';
63720 options.params['dir'] = 'ASC';
63721 this.proxy.loadResponse = this.loadResponse;
63723 //this.addColumns();
63725 load : function (_self, records, options)
63727 _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
63728 // if you click on the translation.. you can edit it...
63729 var el = Roo.get(this);
63730 var id = el.dom.getAttribute('data-id');
63731 var d = el.dom.getAttribute('data-date');
63732 var t = el.dom.getAttribute('data-time');
63733 //var id = this.child('span').dom.textContent;
63736 Pman.Dialog.CourseCalendar.show({
63740 productitem_active : id ? 1 : 0
63742 _this.grid.ds.load({});
63747 _this.panel.fireEvent('resize', [ '', '' ]);
63750 loadResponse : function(o, success, response){
63751 // this is overridden on before load..
63753 Roo.log("our code?");
63754 //Roo.log(success);
63755 //Roo.log(response)
63756 delete this.activeRequest;
63758 this.fireEvent("loadexception", this, o, response);
63759 o.request.callback.call(o.request.scope, null, o.request.arg, false);
63764 result = o.reader.read(response);
63766 Roo.log("load exception?");
63767 this.fireEvent("loadexception", this, o, response, e);
63768 o.request.callback.call(o.request.scope, null, o.request.arg, false);
63771 Roo.log("ready...");
63772 // loop through result.records;
63773 // and set this.tdate[date] = [] << array of records..
63775 Roo.each(result.records, function(r){
63777 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
63778 _this.tdata[r.data.when_dt.format('j')] = [];
63780 _this.tdata[r.data.when_dt.format('j')].push(r.data);
63783 //Roo.log(_this.tdata);
63785 result.records = [];
63786 result.totalRecords = 6;
63788 // let's generate some duumy records for the rows.
63789 //var st = _this.dateField.getValue();
63791 // work out monday..
63792 //st = st.add(Date.DAY, -1 * st.format('w'));
63794 var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
63796 var firstOfMonth = date.getFirstDayOfMonth();
63797 var days = date.getDaysInMonth();
63799 var firstAdded = false;
63800 for (var i = 0; i < result.totalRecords ; i++) {
63801 //var d= st.add(Date.DAY, i);
63804 for(var w = 0 ; w < 7 ; w++){
63805 if(!firstAdded && firstOfMonth != w){
63812 var dd = (d > 0 && d < 10) ? "0"+d : d;
63813 row['weekday'+w] = String.format(
63814 '<span style="font-size: 16px;"><b>{0}</b></span>'+
63815 '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
63817 date.format('Y-m-')+dd
63820 if(typeof(_this.tdata[d]) != 'undefined'){
63821 Roo.each(_this.tdata[d], function(r){
63825 var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
63826 if(r.parent_id*1>0){
63827 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
63830 if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
63831 deactive = 'de-act-link';
63834 row['weekday'+w] += String.format(
63835 '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
63837 r.product_id_name, //1
63838 r.when_dt.format('h:ia'), //2
63848 // only do this if something added..
63850 result.records.push(_this.grid.dataSource.reader.newRow(row));
63854 // push it twice. (second one with an hour..
63858 this.fireEvent("load", this, o, o.request.arg);
63859 o.request.callback.call(o.request.scope, result, o.request.arg, true);
63861 sortInfo : {field: 'when_dt', direction : 'ASC' },
63863 xtype: 'HttpProxy',
63866 url : baseURL + '/Roo/Shop_course.php'
63869 xtype: 'JsonReader',
63886 'name': 'parent_id',
63890 'name': 'product_id',
63894 'name': 'productitem_id',
63912 click : function (_self, e)
63914 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
63915 sd.setMonth(sd.getMonth()-1);
63916 _this.monthField.setValue(sd.format('Y-m-d'));
63917 _this.grid.ds.load({});
63923 xtype: 'Separator',
63927 xtype: 'MonthField',
63930 render : function (_self)
63932 _this.monthField = _self;
63933 // _this.monthField.set today
63935 select : function (combo, date)
63937 _this.grid.ds.load({});
63940 value : (function() { return new Date(); })()
63943 xtype: 'Separator',
63949 text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
63959 click : function (_self, e)
63961 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
63962 sd.setMonth(sd.getMonth()+1);
63963 _this.monthField.setValue(sd.format('Y-m-d'));
63964 _this.grid.ds.load({});
63977 * Ext JS Library 1.1.1
63978 * Copyright(c) 2006-2007, Ext JS, LLC.
63980 * Originally Released Under LGPL - original licence link has changed is not relivant.
63983 * <script type="text/javascript">
63987 * @class Roo.LoadMask
63988 * A simple utility class for generically masking elements while loading data. If the element being masked has
63989 * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
63990 * process and the mask element will be cached for reuse. For all other elements, this mask will replace the
63991 * element's UpdateManager load indicator and will be destroyed after the initial load.
63993 * Create a new LoadMask
63994 * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
63995 * @param {Object} config The config object
63997 Roo.LoadMask = function(el, config){
63998 this.el = Roo.get(el);
63999 Roo.apply(this, config);
64001 this.store.on('beforeload', this.onBeforeLoad, this);
64002 this.store.on('load', this.onLoad, this);
64003 this.store.on('loadexception', this.onLoadException, this);
64004 this.removeMask = false;
64006 var um = this.el.getUpdateManager();
64007 um.showLoadIndicator = false; // disable the default indicator
64008 um.on('beforeupdate', this.onBeforeLoad, this);
64009 um.on('update', this.onLoad, this);
64010 um.on('failure', this.onLoad, this);
64011 this.removeMask = true;
64015 Roo.LoadMask.prototype = {
64017 * @cfg {Boolean} removeMask
64018 * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
64019 * False to persist the mask element reference for multiple uses (e.g., for paged data widgets). Defaults to false.
64021 removeMask : false,
64023 * @cfg {String} msg
64024 * The text to display in a centered loading message box (defaults to 'Loading...')
64026 msg : 'Loading...',
64028 * @cfg {String} msgCls
64029 * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
64031 msgCls : 'x-mask-loading',
64034 * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
64040 * Disables the mask to prevent it from being displayed
64042 disable : function(){
64043 this.disabled = true;
64047 * Enables the mask so that it can be displayed
64049 enable : function(){
64050 this.disabled = false;
64053 onLoadException : function()
64055 Roo.log(arguments);
64057 if (typeof(arguments[3]) != 'undefined') {
64058 Roo.MessageBox.alert("Error loading",arguments[3]);
64062 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
64063 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
64070 (function() { this.el.unmask(this.removeMask); }).defer(50, this);
64073 onLoad : function()
64075 (function() { this.el.unmask(this.removeMask); }).defer(50, this);
64079 onBeforeLoad : function(){
64080 if(!this.disabled){
64081 (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
64086 destroy : function(){
64088 this.store.un('beforeload', this.onBeforeLoad, this);
64089 this.store.un('load', this.onLoad, this);
64090 this.store.un('loadexception', this.onLoadException, this);
64092 var um = this.el.getUpdateManager();
64093 um.un('beforeupdate', this.onBeforeLoad, this);
64094 um.un('update', this.onLoad, this);
64095 um.un('failure', this.onLoad, this);
64100 * Ext JS Library 1.1.1
64101 * Copyright(c) 2006-2007, Ext JS, LLC.
64103 * Originally Released Under LGPL - original licence link has changed is not relivant.
64106 * <script type="text/javascript">
64111 * @class Roo.XTemplate
64112 * @extends Roo.Template
64113 * Provides a template that can have nested templates for loops or conditionals. The syntax is:
64115 var t = new Roo.XTemplate(
64116 '<select name="{name}">',
64117 '<tpl for="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
64121 // then append, applying the master template values
64124 * Supported features:
64129 {a_variable} - output encoded.
64130 {a_variable.format:("Y-m-d")} - call a method on the variable
64131 {a_variable:raw} - unencoded output
64132 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
64133 {a_variable:this.method_on_template(...)} - call a method on the template object.
64138 <tpl for="a_variable or condition.."></tpl>
64139 <tpl if="a_variable or condition"></tpl>
64140 <tpl exec="some javascript"></tpl>
64141 <tpl name="named_template"></tpl> (experimental)
64143 <tpl for="."></tpl> - just iterate the property..
64144 <tpl for=".."></tpl> - iterates with the parent (probably the template)
64148 Roo.XTemplate = function()
64150 Roo.XTemplate.superclass.constructor.apply(this, arguments);
64157 Roo.extend(Roo.XTemplate, Roo.Template, {
64160 * The various sub templates
64165 * basic tag replacing syntax
64168 * // you can fake an object call by doing this
64172 re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
64175 * compile the template
64177 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
64180 compile: function()
64184 s = ['<tpl>', s, '</tpl>'].join('');
64186 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
64187 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
64188 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
64189 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
64190 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
64195 while(true == !!(m = s.match(re))){
64196 var forMatch = m[0].match(nameRe),
64197 ifMatch = m[0].match(ifRe),
64198 execMatch = m[0].match(execRe),
64199 namedMatch = m[0].match(namedRe),
64204 name = forMatch && forMatch[1] ? forMatch[1] : '';
64207 // if - puts fn into test..
64208 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
64210 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
64215 // exec - calls a function... returns empty if true is returned.
64216 exp = execMatch && execMatch[1] ? execMatch[1] : null;
64218 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
64226 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
64227 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
64228 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
64231 var uid = namedMatch ? namedMatch[1] : id;
64235 id: namedMatch ? namedMatch[1] : id,
64242 s = s.replace(m[0], '');
64244 s = s.replace(m[0], '{xtpl'+ id + '}');
64249 for(var i = tpls.length-1; i >= 0; --i){
64250 this.compileTpl(tpls[i]);
64251 this.tpls[tpls[i].id] = tpls[i];
64253 this.master = tpls[tpls.length-1];
64257 * same as applyTemplate, except it's done to one of the subTemplates
64258 * when using named templates, you can do:
64260 * var str = pl.applySubTemplate('your-name', values);
64263 * @param {Number} id of the template
64264 * @param {Object} values to apply to template
64265 * @param {Object} parent (normaly the instance of this object)
64267 applySubTemplate : function(id, values, parent)
64271 var t = this.tpls[id];
64275 if(t.test && !t.test.call(this, values, parent)){
64279 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
64280 Roo.log(e.toString());
64286 if(t.exec && t.exec.call(this, values, parent)){
64290 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
64291 Roo.log(e.toString());
64296 var vs = t.target ? t.target.call(this, values, parent) : values;
64297 parent = t.target ? values : parent;
64298 if(t.target && vs instanceof Array){
64300 for(var i = 0, len = vs.length; i < len; i++){
64301 buf[buf.length] = t.compiled.call(this, vs[i], parent);
64303 return buf.join('');
64305 return t.compiled.call(this, vs, parent);
64307 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
64308 Roo.log(e.toString());
64309 Roo.log(t.compiled);
64314 compileTpl : function(tpl)
64316 var fm = Roo.util.Format;
64317 var useF = this.disableFormats !== true;
64318 var sep = Roo.isGecko ? "+" : ",";
64319 var undef = function(str) {
64320 Roo.log("Property not found :" + str);
64324 var fn = function(m, name, format, args)
64326 //Roo.log(arguments);
64327 args = args ? args.replace(/\\'/g,"'") : args;
64328 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
64329 if (typeof(format) == 'undefined') {
64330 format= 'htmlEncode';
64332 if (format == 'raw' ) {
64336 if(name.substr(0, 4) == 'xtpl'){
64337 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
64340 // build an array of options to determine if value is undefined..
64342 // basically get 'xxxx.yyyy' then do
64343 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
64344 // (function () { Roo.log("Property not found"); return ''; })() :
64349 Roo.each(name.split('.'), function(st) {
64350 lookfor += (lookfor.length ? '.': '') + st;
64351 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
64354 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
64357 if(format && useF){
64359 args = args ? ',' + args : "";
64361 if(format.substr(0, 5) != "this."){
64362 format = "fm." + format + '(';
64364 format = 'this.call("'+ format.substr(5) + '", ';
64368 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
64372 // called with xxyx.yuu:(test,test)
64374 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
64376 // raw.. - :raw modifier..
64377 return "'"+ sep + udef_st + name + ")"+sep+"'";
64381 // branched to use + in gecko and [].join() in others
64383 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
64384 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
64387 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
64388 body.push(tpl.body.replace(/(\r\n|\n)/g,
64389 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
64390 body.push("'].join('');};};");
64391 body = body.join('');
64394 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
64396 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
64402 applyTemplate : function(values){
64403 return this.master.compiled.call(this, values, {});
64404 //var s = this.subs;
64407 apply : function(){
64408 return this.applyTemplate.apply(this, arguments);
64413 Roo.XTemplate.from = function(el){
64414 el = Roo.getDom(el);
64415 return new Roo.XTemplate(el.value || el.innerHTML);