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 * Make the first letter of a string uppercase
961 * @return {String} The new string.
963 String.prototype.toUpperCaseFirst = function () {
964 return this.charAt(0).toUpperCase() + this.slice(1);
969 * Ext JS Library 1.1.1
970 * Copyright(c) 2006-2007, Ext JS, LLC.
972 * Originally Released Under LGPL - original licence link has changed is not relivant.
975 * <script type="text/javascript">
981 Roo.applyIf(Number.prototype, {
983 * Checks whether or not the current number is within a desired range. If the number is already within the
984 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
985 * exceeded. Note that this method returns the constrained value but does not change the current number.
986 * @param {Number} min The minimum number in the range
987 * @param {Number} max The maximum number in the range
988 * @return {Number} The constrained value if outside the range, otherwise the current value
990 constrain : function(min, max){
991 return Math.min(Math.max(this, min), max);
995 * Ext JS Library 1.1.1
996 * Copyright(c) 2006-2007, Ext JS, LLC.
998 * Originally Released Under LGPL - original licence link has changed is not relivant.
1001 * <script type="text/javascript">
1006 Roo.applyIf(Array.prototype, {
1009 * Checks whether or not the specified object exists in the array.
1010 * @param {Object} o The object to check for
1011 * @return {Number} The index of o in the array (or -1 if it is not found)
1013 indexOf : function(o){
1014 for (var i = 0, len = this.length; i < len; i++){
1015 if(this[i] == o) { return i; }
1021 * Removes the specified object from the array. If the object is not found nothing happens.
1022 * @param {Object} o The object to remove
1024 remove : function(o){
1025 var index = this.indexOf(o);
1027 this.splice(index, 1);
1031 * Map (JS 1.6 compatibility)
1032 * @param {Function} function to call
1034 map : function(fun )
1036 var len = this.length >>> 0;
1037 if (typeof fun != "function") {
1038 throw new TypeError();
1040 var res = new Array(len);
1041 var thisp = arguments[1];
1042 for (var i = 0; i < len; i++)
1045 res[i] = fun.call(thisp, this[i], i, this);
1053 * @param {Array} o The array to compare to
1054 * @returns {Boolean} true if the same
1056 equals : function(b)
1058 // https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript
1065 if (this.length !== b.length) {
1069 // sort?? a.sort().equals(b.sort());
1071 for (var i = 0; i < this.length; ++i) {
1072 if (this[i] !== b[i]) {
1084 Roo.applyIf(Array, {
1088 * @param {Array} o Or Array like object (eg. nodelist)
1095 for (var i =0; i < o.length; i++) {
1104 * Ext JS Library 1.1.1
1105 * Copyright(c) 2006-2007, Ext JS, LLC.
1107 * Originally Released Under LGPL - original licence link has changed is not relivant.
1110 * <script type="text/javascript">
1116 * The date parsing and format syntax is a subset of
1117 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
1118 * supported will provide results equivalent to their PHP versions.
1120 * Following is the list of all currently supported formats:
1123 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
1125 Format Output Description
1126 ------ ---------- --------------------------------------------------------------
1127 d 10 Day of the month, 2 digits with leading zeros
1128 D Wed A textual representation of a day, three letters
1129 j 10 Day of the month without leading zeros
1130 l Wednesday A full textual representation of the day of the week
1131 S th English ordinal day of month suffix, 2 chars (use with j)
1132 w 3 Numeric representation of the day of the week
1133 z 9 The julian date, or day of the year (0-365)
1134 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
1135 F January A full textual representation of the month
1136 m 01 Numeric representation of a month, with leading zeros
1137 M Jan Month name abbreviation, three letters
1138 n 1 Numeric representation of a month, without leading zeros
1139 t 31 Number of days in the given month
1140 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
1141 Y 2007 A full numeric representation of a year, 4 digits
1142 y 07 A two digit representation of a year
1143 a pm Lowercase Ante meridiem and Post meridiem
1144 A PM Uppercase Ante meridiem and Post meridiem
1145 g 3 12-hour format of an hour without leading zeros
1146 G 15 24-hour format of an hour without leading zeros
1147 h 03 12-hour format of an hour with leading zeros
1148 H 15 24-hour format of an hour with leading zeros
1149 i 05 Minutes with leading zeros
1150 s 01 Seconds, with leading zeros
1151 O -0600 Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
1152 P -06:00 Difference to Greenwich time (GMT) with colon between hours and minutes
1153 T CST Timezone setting of the machine running the code
1154 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
1157 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
1159 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
1160 document.write(dt.format('Y-m-d')); //2007-01-10
1161 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
1162 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
1165 * Here are some standard date/time patterns that you might find helpful. They
1166 * are not part of the source of Date.js, but to use them you can simply copy this
1167 * block of code into any script that is included after Date.js and they will also become
1168 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
1171 ISO8601Long:"Y-m-d H:i:s",
1172 ISO8601Short:"Y-m-d",
1174 LongDate: "l, F d, Y",
1175 FullDateTime: "l, F d, Y g:i:s A",
1178 LongTime: "g:i:s A",
1179 SortableDateTime: "Y-m-d\\TH:i:s",
1180 UniversalSortableDateTime: "Y-m-d H:i:sO",
1187 var dt = new Date();
1188 document.write(dt.format(Date.patterns.ShortDate));
1193 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
1194 * They generate precompiled functions from date formats instead of parsing and
1195 * processing the pattern every time you format a date. These functions are available
1196 * on every Date object (any javascript function).
1198 * The original article and download are here:
1199 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
1206 Returns the number of milliseconds between this date and date
1207 @param {Date} date (optional) Defaults to now
1208 @return {Number} The diff in milliseconds
1209 @member Date getElapsed
1211 Date.prototype.getElapsed = function(date) {
1212 return Math.abs((date || new Date()).getTime()-this.getTime());
1214 // was in date file..
1218 Date.parseFunctions = {count:0};
1220 Date.parseRegexes = [];
1222 Date.formatFunctions = {count:0};
1225 Date.prototype.dateFormat = function(format) {
1226 if (Date.formatFunctions[format] == null) {
1227 Date.createNewFormat(format);
1229 var func = Date.formatFunctions[format];
1230 return this[func]();
1235 * Formats a date given the supplied format string
1236 * @param {String} format The format string
1237 * @return {String} The formatted date
1240 Date.prototype.format = Date.prototype.dateFormat;
1243 Date.createNewFormat = function(format) {
1244 var funcName = "format" + Date.formatFunctions.count++;
1245 Date.formatFunctions[format] = funcName;
1246 var code = "Date.prototype." + funcName + " = function(){return ";
1247 var special = false;
1249 for (var i = 0; i < format.length; ++i) {
1250 ch = format.charAt(i);
1251 if (!special && ch == "\\") {
1256 code += "'" + String.escape(ch) + "' + ";
1259 code += Date.getFormatCode(ch);
1262 /** eval:var:zzzzzzzzzzzzz */
1263 eval(code.substring(0, code.length - 3) + ";}");
1267 Date.getFormatCode = function(character) {
1268 switch (character) {
1270 return "String.leftPad(this.getDate(), 2, '0') + ";
1272 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1274 return "this.getDate() + ";
1276 return "Date.dayNames[this.getDay()] + ";
1278 return "this.getSuffix() + ";
1280 return "this.getDay() + ";
1282 return "this.getDayOfYear() + ";
1284 return "this.getWeekOfYear() + ";
1286 return "Date.monthNames[this.getMonth()] + ";
1288 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1290 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1292 return "(this.getMonth() + 1) + ";
1294 return "this.getDaysInMonth() + ";
1296 return "(this.isLeapYear() ? 1 : 0) + ";
1298 return "this.getFullYear() + ";
1300 return "('' + this.getFullYear()).substring(2, 4) + ";
1302 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1304 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1306 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1308 return "this.getHours() + ";
1310 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1312 return "String.leftPad(this.getHours(), 2, '0') + ";
1314 return "String.leftPad(this.getMinutes(), 2, '0') + ";
1316 return "String.leftPad(this.getSeconds(), 2, '0') + ";
1318 return "this.getGMTOffset() + ";
1320 return "this.getGMTColonOffset() + ";
1322 return "this.getTimezone() + ";
1324 return "(this.getTimezoneOffset() * -60) + ";
1326 return "'" + String.escape(character) + "' + ";
1331 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1332 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
1333 * the date format that is not specified will default to the current date value for that part. Time parts can also
1334 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
1335 * string or the parse operation will fail.
1338 //dt = Fri May 25 2007 (current date)
1339 var dt = new Date();
1341 //dt = Thu May 25 2006 (today's month/day in 2006)
1342 dt = Date.parseDate("2006", "Y");
1344 //dt = Sun Jan 15 2006 (all date parts specified)
1345 dt = Date.parseDate("2006-1-15", "Y-m-d");
1347 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1348 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1350 * @param {String} input The unparsed date as a string
1351 * @param {String} format The format the date is in
1352 * @return {Date} The parsed date
1355 Date.parseDate = function(input, format) {
1356 if (Date.parseFunctions[format] == null) {
1357 Date.createParser(format);
1359 var func = Date.parseFunctions[format];
1360 return Date[func](input);
1366 Date.createParser = function(format) {
1367 var funcName = "parse" + Date.parseFunctions.count++;
1368 var regexNum = Date.parseRegexes.length;
1369 var currentGroup = 1;
1370 Date.parseFunctions[format] = funcName;
1372 var code = "Date." + funcName + " = function(input){\n"
1373 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1374 + "var d = new Date();\n"
1375 + "y = d.getFullYear();\n"
1376 + "m = d.getMonth();\n"
1377 + "d = d.getDate();\n"
1378 + "if (typeof(input) !== 'string') { input = input.toString(); }\n"
1379 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1380 + "if (results && results.length > 0) {";
1383 var special = false;
1385 for (var i = 0; i < format.length; ++i) {
1386 ch = format.charAt(i);
1387 if (!special && ch == "\\") {
1392 regex += String.escape(ch);
1395 var obj = Date.formatCodeToRegex(ch, currentGroup);
1396 currentGroup += obj.g;
1398 if (obj.g && obj.c) {
1404 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1405 + "{v = new Date(y, m, d, h, i, s); v.setFullYear(y);}\n"
1406 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1407 + "{v = new Date(y, m, d, h, i); v.setFullYear(y);}\n"
1408 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1409 + "{v = new Date(y, m, d, h); v.setFullYear(y);}\n"
1410 + "else if (y >= 0 && m >= 0 && d > 0)\n"
1411 + "{v = new Date(y, m, d); v.setFullYear(y);}\n"
1412 + "else if (y >= 0 && m >= 0)\n"
1413 + "{v = new Date(y, m); v.setFullYear(y);}\n"
1414 + "else if (y >= 0)\n"
1415 + "{v = new Date(y); v.setFullYear(y);}\n"
1416 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1417 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1418 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1421 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1422 /** eval:var:zzzzzzzzzzzzz */
1427 Date.formatCodeToRegex = function(character, currentGroup) {
1428 switch (character) {
1432 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1435 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1436 s:"(\\d{1,2})"}; // day of month without leading zeroes
1439 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1440 s:"(\\d{2})"}; // day of month with leading zeroes
1444 s:"(?:" + Date.dayNames.join("|") + ")"};
1448 s:"(?:st|nd|rd|th)"};
1463 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1464 s:"(" + Date.monthNames.join("|") + ")"};
1467 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1468 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1471 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1472 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1475 c:"m = Math.max(0,parseInt(results[" + currentGroup + "], 10) - 1);\n",
1476 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1487 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1491 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1492 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1496 c:"if (results[" + currentGroup + "] == 'am') {\n"
1497 + "if (h == 12) { h = 0; }\n"
1498 + "} else { if (h < 12) { h += 12; }}",
1502 c:"if (results[" + currentGroup + "] == 'AM') {\n"
1503 + "if (h == 12) { h = 0; }\n"
1504 + "} else { if (h < 12) { h += 12; }}",
1509 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1510 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
1514 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1515 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
1518 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1522 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1527 "o = results[", currentGroup, "];\n",
1528 "var sn = o.substring(0,1);\n", // get + / - sign
1529 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1530 "var mn = o.substring(3,5) % 60;\n", // get minutes
1531 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1532 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1534 s:"([+\-]\\d{2,4})"};
1540 "o = results[", currentGroup, "];\n",
1541 "var sn = o.substring(0,1);\n",
1542 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
1543 "var mn = o.substring(4,6) % 60;\n",
1544 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
1545 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1551 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1554 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1555 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1556 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1560 s:String.escape(character)};
1565 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1566 * @return {String} The abbreviated timezone name (e.g. 'CST')
1568 Date.prototype.getTimezone = function() {
1569 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1573 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1574 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1576 Date.prototype.getGMTOffset = function() {
1577 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1578 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1579 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1583 * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
1584 * @return {String} 2-characters representing hours and 2-characters representing minutes
1585 * seperated by a colon and prefixed with + or - (e.g. '-06:00')
1587 Date.prototype.getGMTColonOffset = function() {
1588 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1589 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1591 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
1595 * Get the numeric day number of the year, adjusted for leap year.
1596 * @return {Number} 0 through 364 (365 in leap years)
1598 Date.prototype.getDayOfYear = function() {
1600 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1601 for (var i = 0; i < this.getMonth(); ++i) {
1602 num += Date.daysInMonth[i];
1604 return num + this.getDate() - 1;
1608 * Get the string representation of the numeric week number of the year
1609 * (equivalent to the format specifier 'W').
1610 * @return {String} '00' through '52'
1612 Date.prototype.getWeekOfYear = function() {
1613 // Skip to Thursday of this week
1614 var now = this.getDayOfYear() + (4 - this.getDay());
1615 // Find the first Thursday of the year
1616 var jan1 = new Date(this.getFullYear(), 0, 1);
1617 var then = (7 - jan1.getDay() + 4);
1618 return String.leftPad(((now - then) / 7) + 1, 2, "0");
1622 * Whether or not the current date is in a leap year.
1623 * @return {Boolean} True if the current date is in a leap year, else false
1625 Date.prototype.isLeapYear = function() {
1626 var year = this.getFullYear();
1627 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1631 * Get the first day of the current month, adjusted for leap year. The returned value
1632 * is the numeric day index within the week (0-6) which can be used in conjunction with
1633 * the {@link #monthNames} array to retrieve the textual day name.
1636 var dt = new Date('1/10/2007');
1637 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1639 * @return {Number} The day number (0-6)
1641 Date.prototype.getFirstDayOfMonth = function() {
1642 var day = (this.getDay() - (this.getDate() - 1)) % 7;
1643 return (day < 0) ? (day + 7) : day;
1647 * Get the last day of the current month, adjusted for leap year. The returned value
1648 * is the numeric day index within the week (0-6) which can be used in conjunction with
1649 * the {@link #monthNames} array to retrieve the textual day name.
1652 var dt = new Date('1/10/2007');
1653 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1655 * @return {Number} The day number (0-6)
1657 Date.prototype.getLastDayOfMonth = function() {
1658 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1659 return (day < 0) ? (day + 7) : day;
1664 * Get the first date of this date's month
1667 Date.prototype.getFirstDateOfMonth = function() {
1668 return new Date(this.getFullYear(), this.getMonth(), 1);
1672 * Get the last date of this date's month
1675 Date.prototype.getLastDateOfMonth = function() {
1676 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1679 * Get the number of days in the current month, adjusted for leap year.
1680 * @return {Number} The number of days in the month
1682 Date.prototype.getDaysInMonth = function() {
1683 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1684 return Date.daysInMonth[this.getMonth()];
1688 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1689 * @return {String} 'st, 'nd', 'rd' or 'th'
1691 Date.prototype.getSuffix = function() {
1692 switch (this.getDate()) {
1709 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1712 * An array of textual month names.
1713 * Override these values for international dates, for example...
1714 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1733 * An array of textual day names.
1734 * Override these values for international dates, for example...
1735 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1751 Date.monthNumbers = {
1766 * Creates and returns a new Date instance with the exact same date value as the called instance.
1767 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1768 * variable will also be changed. When the intention is to create a new variable that will not
1769 * modify the original instance, you should create a clone.
1771 * Example of correctly cloning a date:
1774 var orig = new Date('10/1/2006');
1777 document.write(orig); //returns 'Thu Oct 05 2006'!
1780 var orig = new Date('10/1/2006');
1781 var copy = orig.clone();
1783 document.write(orig); //returns 'Thu Oct 01 2006'
1785 * @return {Date} The new Date instance
1787 Date.prototype.clone = function() {
1788 return new Date(this.getTime());
1792 * Clears any time information from this date
1793 @param {Boolean} clone true to create a clone of this date, clear the time and return it
1794 @return {Date} this or the clone
1796 Date.prototype.clearTime = function(clone){
1798 return this.clone().clearTime();
1803 this.setMilliseconds(0);
1808 // safari setMonth is broken -- check that this is only donw once...
1809 if(Roo.isSafari && typeof(Date.brokenSetMonth) == 'undefined'){
1810 Date.brokenSetMonth = Date.prototype.setMonth;
1811 Date.prototype.setMonth = function(num){
1813 var n = Math.ceil(-num);
1814 var back_year = Math.ceil(n/12);
1815 var month = (n % 12) ? 12 - n % 12 : 0 ;
1816 this.setFullYear(this.getFullYear() - back_year);
1817 return Date.brokenSetMonth.call(this, month);
1819 return Date.brokenSetMonth.apply(this, arguments);
1824 /** Date interval constant
1828 /** Date interval constant
1832 /** Date interval constant
1836 /** Date interval constant
1840 /** Date interval constant
1844 /** Date interval constant
1848 /** Date interval constant
1854 * Provides a convenient method of performing basic date arithmetic. This method
1855 * does not modify the Date instance being called - it creates and returns
1856 * a new Date instance containing the resulting date value.
1861 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1862 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1864 //Negative values will subtract correctly:
1865 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1866 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1868 //You can even chain several calls together in one line!
1869 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1870 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1873 * @param {String} interval A valid date interval enum value
1874 * @param {Number} value The amount to add to the current date
1875 * @return {Date} The new Date instance
1877 Date.prototype.add = function(interval, value){
1878 var d = this.clone();
1879 if (!interval || value === 0) { return d; }
1880 switch(interval.toLowerCase()){
1882 d.setMilliseconds(this.getMilliseconds() + value);
1885 d.setSeconds(this.getSeconds() + value);
1888 d.setMinutes(this.getMinutes() + value);
1891 d.setHours(this.getHours() + value);
1894 d.setDate(this.getDate() + value);
1897 var day = this.getDate();
1899 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1902 d.setMonth(this.getMonth() + value);
1905 d.setFullYear(this.getFullYear() + value);
1911 * @class Roo.lib.Dom
1915 * Dom utils (from YIU afaik)
1921 * Get the view width
1922 * @param {Boolean} full True will get the full document, otherwise it's the view width
1923 * @return {Number} The width
1926 getViewWidth : function(full) {
1927 return full ? this.getDocumentWidth() : this.getViewportWidth();
1930 * Get the view height
1931 * @param {Boolean} full True will get the full document, otherwise it's the view height
1932 * @return {Number} The height
1934 getViewHeight : function(full) {
1935 return full ? this.getDocumentHeight() : this.getViewportHeight();
1938 * Get the Full Document height
1939 * @return {Number} The height
1941 getDocumentHeight: function() {
1942 var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1943 return Math.max(scrollHeight, this.getViewportHeight());
1946 * Get the Full Document width
1947 * @return {Number} The width
1949 getDocumentWidth: function() {
1950 var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1951 return Math.max(scrollWidth, this.getViewportWidth());
1954 * Get the Window Viewport height
1955 * @return {Number} The height
1957 getViewportHeight: function() {
1958 var height = self.innerHeight;
1959 var mode = document.compatMode;
1961 if ((mode || Roo.isIE) && !Roo.isOpera) {
1962 height = (mode == "CSS1Compat") ?
1963 document.documentElement.clientHeight :
1964 document.body.clientHeight;
1970 * Get the Window Viewport width
1971 * @return {Number} The width
1973 getViewportWidth: function() {
1974 var width = self.innerWidth;
1975 var mode = document.compatMode;
1977 if (mode || Roo.isIE) {
1978 width = (mode == "CSS1Compat") ?
1979 document.documentElement.clientWidth :
1980 document.body.clientWidth;
1985 isAncestor : function(p, c) {
1992 if (p.contains && !Roo.isSafari) {
1993 return p.contains(c);
1994 } else if (p.compareDocumentPosition) {
1995 return !!(p.compareDocumentPosition(c) & 16);
1997 var parent = c.parentNode;
2002 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
2005 parent = parent.parentNode;
2011 getRegion : function(el) {
2012 return Roo.lib.Region.getRegion(el);
2015 getY : function(el) {
2016 return this.getXY(el)[1];
2019 getX : function(el) {
2020 return this.getXY(el)[0];
2023 getXY : function(el) {
2024 var p, pe, b, scroll, bd = document.body;
2025 el = Roo.getDom(el);
2026 var fly = Roo.lib.AnimBase.fly;
2027 if (el.getBoundingClientRect) {
2028 b = el.getBoundingClientRect();
2029 scroll = fly(document).getScroll();
2030 return [b.left + scroll.left, b.top + scroll.top];
2036 var hasAbsolute = fly(el).getStyle("position") == "absolute";
2043 if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
2050 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
2051 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
2058 if (p != el && pe.getStyle('overflow') != 'visible') {
2066 if (Roo.isSafari && hasAbsolute) {
2071 if (Roo.isGecko && !hasAbsolute) {
2073 x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
2074 y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
2078 while (p && p != bd) {
2079 if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
2091 setXY : function(el, xy) {
2092 el = Roo.fly(el, '_setXY');
2094 var pts = el.translatePoints(xy);
2095 if (xy[0] !== false) {
2096 el.dom.style.left = pts.left + "px";
2098 if (xy[1] !== false) {
2099 el.dom.style.top = pts.top + "px";
2103 setX : function(el, x) {
2104 this.setXY(el, [x, false]);
2107 setY : function(el, y) {
2108 this.setXY(el, [false, y]);
2112 * Portions of this file are based on pieces of Yahoo User Interface Library
2113 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2114 * YUI licensed under the BSD License:
2115 * http://developer.yahoo.net/yui/license.txt
2116 * <script type="text/javascript">
2120 Roo.lib.Event = function() {
2121 var loadComplete = false;
2123 var unloadListeners = [];
2125 var onAvailStack = [];
2127 var lastError = null;
2140 startInterval: function() {
2141 if (!this._interval) {
2143 var callback = function() {
2144 self._tryPreloadAttach();
2146 this._interval = setInterval(callback, this.POLL_INTERVAL);
2151 onAvailable: function(p_id, p_fn, p_obj, p_override) {
2152 onAvailStack.push({ id: p_id,
2155 override: p_override,
2156 checkReady: false });
2158 retryCount = this.POLL_RETRYS;
2159 this.startInterval();
2163 addListener: function(el, eventName, fn) {
2164 el = Roo.getDom(el);
2169 if ("unload" == eventName) {
2170 unloadListeners[unloadListeners.length] =
2171 [el, eventName, fn];
2175 var wrappedFn = function(e) {
2176 return fn(Roo.lib.Event.getEvent(e));
2179 var li = [el, eventName, fn, wrappedFn];
2181 var index = listeners.length;
2182 listeners[index] = li;
2184 this.doAdd(el, eventName, wrappedFn, false);
2190 removeListener: function(el, eventName, fn) {
2193 el = Roo.getDom(el);
2196 return this.purgeElement(el, false, eventName);
2200 if ("unload" == eventName) {
2202 for (i = 0,len = unloadListeners.length; i < len; i++) {
2203 var li = unloadListeners[i];
2206 li[1] == eventName &&
2208 unloadListeners.splice(i, 1);
2216 var cacheItem = null;
2219 var index = arguments[3];
2221 if ("undefined" == typeof index) {
2222 index = this._getCacheIndex(el, eventName, fn);
2226 cacheItem = listeners[index];
2229 if (!el || !cacheItem) {
2233 this.doRemove(el, eventName, cacheItem[this.WFN], false);
2235 delete listeners[index][this.WFN];
2236 delete listeners[index][this.FN];
2237 listeners.splice(index, 1);
2244 getTarget: function(ev, resolveTextNode) {
2245 ev = ev.browserEvent || ev;
2246 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2247 var t = ev.target || ev.srcElement;
2248 return this.resolveTextNode(t);
2252 resolveTextNode: function(node) {
2253 if (Roo.isSafari && node && 3 == node.nodeType) {
2254 return node.parentNode;
2261 getPageX: function(ev) {
2262 ev = ev.browserEvent || ev;
2263 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2265 if (!x && 0 !== x) {
2266 x = ev.clientX || 0;
2269 x += this.getScroll()[1];
2277 getPageY: function(ev) {
2278 ev = ev.browserEvent || ev;
2279 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2281 if (!y && 0 !== y) {
2282 y = ev.clientY || 0;
2285 y += this.getScroll()[0];
2294 getXY: function(ev) {
2295 ev = ev.browserEvent || ev;
2296 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2297 return [this.getPageX(ev), this.getPageY(ev)];
2301 getRelatedTarget: function(ev) {
2302 ev = ev.browserEvent || ev;
2303 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2304 var t = ev.relatedTarget;
2306 if (ev.type == "mouseout") {
2308 } else if (ev.type == "mouseover") {
2313 return this.resolveTextNode(t);
2317 getTime: function(ev) {
2318 ev = ev.browserEvent || ev;
2319 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2321 var t = new Date().getTime();
2325 this.lastError = ex;
2334 stopEvent: function(ev) {
2335 this.stopPropagation(ev);
2336 this.preventDefault(ev);
2340 stopPropagation: function(ev) {
2341 ev = ev.browserEvent || ev;
2342 if (ev.stopPropagation) {
2343 ev.stopPropagation();
2345 ev.cancelBubble = true;
2350 preventDefault: function(ev) {
2351 ev = ev.browserEvent || ev;
2352 if(ev.preventDefault) {
2353 ev.preventDefault();
2355 ev.returnValue = false;
2360 getEvent: function(e) {
2361 var ev = e || window.event;
2363 var c = this.getEvent.caller;
2365 ev = c.arguments[0];
2366 if (ev && Event == ev.constructor) {
2376 getCharCode: function(ev) {
2377 ev = ev.browserEvent || ev;
2378 return ev.charCode || ev.keyCode || 0;
2382 _getCacheIndex: function(el, eventName, fn) {
2383 for (var i = 0,len = listeners.length; i < len; ++i) {
2384 var li = listeners[i];
2386 li[this.FN] == fn &&
2387 li[this.EL] == el &&
2388 li[this.TYPE] == eventName) {
2400 getEl: function(id) {
2401 return document.getElementById(id);
2405 clearCache: function() {
2409 _load: function(e) {
2410 loadComplete = true;
2411 var EU = Roo.lib.Event;
2415 EU.doRemove(window, "load", EU._load);
2420 _tryPreloadAttach: function() {
2429 var tryAgain = !loadComplete;
2431 tryAgain = (retryCount > 0);
2436 for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2437 var item = onAvailStack[i];
2439 var el = this.getEl(item.id);
2442 if (!item.checkReady ||
2445 (document && document.body)) {
2448 if (item.override) {
2449 if (item.override === true) {
2452 scope = item.override;
2455 item.fn.call(scope, item.obj);
2456 onAvailStack[i] = null;
2459 notAvail.push(item);
2464 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2468 this.startInterval();
2470 clearInterval(this._interval);
2471 this._interval = null;
2474 this.locked = false;
2481 purgeElement: function(el, recurse, eventName) {
2482 var elListeners = this.getListeners(el, eventName);
2484 for (var i = 0,len = elListeners.length; i < len; ++i) {
2485 var l = elListeners[i];
2486 this.removeListener(el, l.type, l.fn);
2490 if (recurse && el && el.childNodes) {
2491 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2492 this.purgeElement(el.childNodes[i], recurse, eventName);
2498 getListeners: function(el, eventName) {
2499 var results = [], searchLists;
2501 searchLists = [listeners, unloadListeners];
2502 } else if (eventName == "unload") {
2503 searchLists = [unloadListeners];
2505 searchLists = [listeners];
2508 for (var j = 0; j < searchLists.length; ++j) {
2509 var searchList = searchLists[j];
2510 if (searchList && searchList.length > 0) {
2511 for (var i = 0,len = searchList.length; i < len; ++i) {
2512 var l = searchList[i];
2513 if (l && l[this.EL] === el &&
2514 (!eventName || eventName === l[this.TYPE])) {
2519 adjust: l[this.ADJ_SCOPE],
2527 return (results.length) ? results : null;
2531 _unload: function(e) {
2533 var EU = Roo.lib.Event, i, j, l, len, index;
2535 for (i = 0,len = unloadListeners.length; i < len; ++i) {
2536 l = unloadListeners[i];
2539 if (l[EU.ADJ_SCOPE]) {
2540 if (l[EU.ADJ_SCOPE] === true) {
2543 scope = l[EU.ADJ_SCOPE];
2546 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2547 unloadListeners[i] = null;
2553 unloadListeners = null;
2555 if (listeners && listeners.length > 0) {
2556 j = listeners.length;
2559 l = listeners[index];
2561 EU.removeListener(l[EU.EL], l[EU.TYPE],
2571 EU.doRemove(window, "unload", EU._unload);
2576 getScroll: function() {
2577 var dd = document.documentElement, db = document.body;
2578 if (dd && (dd.scrollTop || dd.scrollLeft)) {
2579 return [dd.scrollTop, dd.scrollLeft];
2581 return [db.scrollTop, db.scrollLeft];
2588 doAdd: function () {
2589 if (window.addEventListener) {
2590 return function(el, eventName, fn, capture) {
2591 el.addEventListener(eventName, fn, (capture));
2593 } else if (window.attachEvent) {
2594 return function(el, eventName, fn, capture) {
2595 el.attachEvent("on" + eventName, fn);
2604 doRemove: function() {
2605 if (window.removeEventListener) {
2606 return function (el, eventName, fn, capture) {
2607 el.removeEventListener(eventName, fn, (capture));
2609 } else if (window.detachEvent) {
2610 return function (el, eventName, fn) {
2611 el.detachEvent("on" + eventName, fn);
2623 var E = Roo.lib.Event;
2624 E.on = E.addListener;
2625 E.un = E.removeListener;
2627 if (document && document.body) {
2630 E.doAdd(window, "load", E._load);
2632 E.doAdd(window, "unload", E._unload);
2633 E._tryPreloadAttach();
2640 * @class Roo.lib.Ajax
2642 * provide a simple Ajax request utility functions
2644 * Portions of this file are based on pieces of Yahoo User Interface Library
2645 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2646 * YUI licensed under the BSD License:
2647 * http://developer.yahoo.net/yui/license.txt
2648 * <script type="text/javascript">
2656 request : function(method, uri, cb, data, options) {
2658 var hs = options.headers;
2661 if(hs.hasOwnProperty(h)){
2662 this.initHeader(h, hs[h], false);
2666 if(options.xmlData){
2667 this.initHeader('Content-Type', 'text/xml', false);
2669 data = options.xmlData;
2673 return this.asyncRequest(method, uri, cb, data);
2679 * @param {DomForm} form element
2680 * @return {String} urlencode form output.
2682 serializeForm : function(form) {
2683 if(typeof form == 'string') {
2684 form = (document.getElementById(form) || document.forms[form]);
2687 var el, name, val, disabled, data = '', hasSubmit = false;
2688 for (var i = 0; i < form.elements.length; i++) {
2689 el = form.elements[i];
2690 disabled = form.elements[i].disabled;
2691 name = form.elements[i].name;
2692 val = form.elements[i].value;
2694 if (!disabled && name){
2698 case 'select-multiple':
2699 for (var j = 0; j < el.options.length; j++) {
2700 if (el.options[j].selected) {
2702 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2705 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2713 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2726 if(hasSubmit == false) {
2727 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2732 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2737 data = data.substr(0, data.length - 1);
2745 useDefaultHeader:true,
2747 defaultPostHeader:'application/x-www-form-urlencoded',
2749 useDefaultXhrHeader:true,
2751 defaultXhrHeader:'XMLHttpRequest',
2753 hasDefaultHeaders:true,
2765 setProgId:function(id)
2767 this.activeX.unshift(id);
2770 setDefaultPostHeader:function(b)
2772 this.useDefaultHeader = b;
2775 setDefaultXhrHeader:function(b)
2777 this.useDefaultXhrHeader = b;
2780 setPollingInterval:function(i)
2782 if (typeof i == 'number' && isFinite(i)) {
2783 this.pollInterval = i;
2787 createXhrObject:function(transactionId)
2793 http = new XMLHttpRequest();
2795 obj = { conn:http, tId:transactionId };
2799 for (var i = 0; i < this.activeX.length; ++i) {
2803 http = new ActiveXObject(this.activeX[i]);
2805 obj = { conn:http, tId:transactionId };
2818 getConnectionObject:function()
2821 var tId = this.transactionId;
2825 o = this.createXhrObject(tId);
2827 this.transactionId++;
2838 asyncRequest:function(method, uri, callback, postData)
2840 var o = this.getConnectionObject();
2846 o.conn.open(method, uri, true);
2848 if (this.useDefaultXhrHeader) {
2849 if (!this.defaultHeaders['X-Requested-With']) {
2850 this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2854 if(postData && this.useDefaultHeader){
2855 this.initHeader('Content-Type', this.defaultPostHeader);
2858 if (this.hasDefaultHeaders || this.hasHeaders) {
2862 this.handleReadyState(o, callback);
2863 o.conn.send(postData || null);
2869 handleReadyState:function(o, callback)
2873 if (callback && callback.timeout) {
2875 this.timeout[o.tId] = window.setTimeout(function() {
2876 oConn.abort(o, callback, true);
2877 }, callback.timeout);
2880 this.poll[o.tId] = window.setInterval(
2882 if (o.conn && o.conn.readyState == 4) {
2883 window.clearInterval(oConn.poll[o.tId]);
2884 delete oConn.poll[o.tId];
2886 if(callback && callback.timeout) {
2887 window.clearTimeout(oConn.timeout[o.tId]);
2888 delete oConn.timeout[o.tId];
2891 oConn.handleTransactionResponse(o, callback);
2894 , this.pollInterval);
2897 handleTransactionResponse:function(o, callback, isAbort)
2901 this.releaseObject(o);
2905 var httpStatus, responseObject;
2909 if (o.conn.status !== undefined && o.conn.status != 0) {
2910 httpStatus = o.conn.status;
2922 if (httpStatus >= 200 && httpStatus < 300) {
2923 responseObject = this.createResponseObject(o, callback.argument);
2924 if (callback.success) {
2925 if (!callback.scope) {
2926 callback.success(responseObject);
2931 callback.success.apply(callback.scope, [responseObject]);
2936 switch (httpStatus) {
2944 responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2945 if (callback.failure) {
2946 if (!callback.scope) {
2947 callback.failure(responseObject);
2950 callback.failure.apply(callback.scope, [responseObject]);
2955 responseObject = this.createResponseObject(o, callback.argument);
2956 if (callback.failure) {
2957 if (!callback.scope) {
2958 callback.failure(responseObject);
2961 callback.failure.apply(callback.scope, [responseObject]);
2967 this.releaseObject(o);
2968 responseObject = null;
2971 createResponseObject:function(o, callbackArg)
2978 var headerStr = o.conn.getAllResponseHeaders();
2979 var header = headerStr.split('\n');
2980 for (var i = 0; i < header.length; i++) {
2981 var delimitPos = header[i].indexOf(':');
2982 if (delimitPos != -1) {
2983 headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2991 obj.status = o.conn.status;
2992 obj.statusText = o.conn.statusText;
2993 obj.getResponseHeader = headerObj;
2994 obj.getAllResponseHeaders = headerStr;
2995 obj.responseText = o.conn.responseText;
2996 obj.responseXML = o.conn.responseXML;
2998 if (typeof callbackArg !== undefined) {
2999 obj.argument = callbackArg;
3005 createExceptionObject:function(tId, callbackArg, isAbort)
3008 var COMM_ERROR = 'communication failure';
3009 var ABORT_CODE = -1;
3010 var ABORT_ERROR = 'transaction aborted';
3016 obj.status = ABORT_CODE;
3017 obj.statusText = ABORT_ERROR;
3020 obj.status = COMM_CODE;
3021 obj.statusText = COMM_ERROR;
3025 obj.argument = callbackArg;
3031 initHeader:function(label, value, isDefault)
3033 var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
3035 if (headerObj[label] === undefined) {
3036 headerObj[label] = value;
3041 headerObj[label] = value + "," + headerObj[label];
3045 this.hasDefaultHeaders = true;
3048 this.hasHeaders = true;
3053 setHeader:function(o)
3055 if (this.hasDefaultHeaders) {
3056 for (var prop in this.defaultHeaders) {
3057 if (this.defaultHeaders.hasOwnProperty(prop)) {
3058 o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
3063 if (this.hasHeaders) {
3064 for (var prop in this.headers) {
3065 if (this.headers.hasOwnProperty(prop)) {
3066 o.conn.setRequestHeader(prop, this.headers[prop]);
3070 this.hasHeaders = false;
3074 resetDefaultHeaders:function() {
3075 delete this.defaultHeaders;
3076 this.defaultHeaders = {};
3077 this.hasDefaultHeaders = false;
3080 abort:function(o, callback, isTimeout)
3082 if(this.isCallInProgress(o)) {
3084 window.clearInterval(this.poll[o.tId]);
3085 delete this.poll[o.tId];
3087 delete this.timeout[o.tId];
3090 this.handleTransactionResponse(o, callback, true);
3100 isCallInProgress:function(o)
3103 return o.conn.readyState != 4 && o.conn.readyState != 0;
3112 releaseObject:function(o)
3121 'MSXML2.XMLHTTP.3.0',
3129 * Portions of this file are based on pieces of Yahoo User Interface Library
3130 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3131 * YUI licensed under the BSD License:
3132 * http://developer.yahoo.net/yui/license.txt
3133 * <script type="text/javascript">
3137 Roo.lib.Region = function(t, r, b, l) {
3147 Roo.lib.Region.prototype = {
3148 contains : function(region) {
3149 return ( region.left >= this.left &&
3150 region.right <= this.right &&
3151 region.top >= this.top &&
3152 region.bottom <= this.bottom );
3156 getArea : function() {
3157 return ( (this.bottom - this.top) * (this.right - this.left) );
3160 intersect : function(region) {
3161 var t = Math.max(this.top, region.top);
3162 var r = Math.min(this.right, region.right);
3163 var b = Math.min(this.bottom, region.bottom);
3164 var l = Math.max(this.left, region.left);
3166 if (b >= t && r >= l) {
3167 return new Roo.lib.Region(t, r, b, l);
3172 union : function(region) {
3173 var t = Math.min(this.top, region.top);
3174 var r = Math.max(this.right, region.right);
3175 var b = Math.max(this.bottom, region.bottom);
3176 var l = Math.min(this.left, region.left);
3178 return new Roo.lib.Region(t, r, b, l);
3181 adjust : function(t, l, b, r) {
3190 Roo.lib.Region.getRegion = function(el) {
3191 var p = Roo.lib.Dom.getXY(el);
3194 var r = p[0] + el.offsetWidth;
3195 var b = p[1] + el.offsetHeight;
3198 return new Roo.lib.Region(t, r, b, l);
3201 * Portions of this file are based on pieces of Yahoo User Interface Library
3202 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3203 * YUI licensed under the BSD License:
3204 * http://developer.yahoo.net/yui/license.txt
3205 * <script type="text/javascript">
3208 //@@dep Roo.lib.Region
3211 Roo.lib.Point = function(x, y) {
3212 if (x instanceof Array) {
3216 this.x = this.right = this.left = this[0] = x;
3217 this.y = this.top = this.bottom = this[1] = y;
3220 Roo.lib.Point.prototype = new Roo.lib.Region();
3222 * Portions of this file are based on pieces of Yahoo User Interface Library
3223 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3224 * YUI licensed under the BSD License:
3225 * http://developer.yahoo.net/yui/license.txt
3226 * <script type="text/javascript">
3233 scroll : function(el, args, duration, easing, cb, scope) {
3234 this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
3237 motion : function(el, args, duration, easing, cb, scope) {
3238 this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
3241 color : function(el, args, duration, easing, cb, scope) {
3242 this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
3245 run : function(el, args, duration, easing, cb, scope, type) {
3246 type = type || Roo.lib.AnimBase;
3247 if (typeof easing == "string") {
3248 easing = Roo.lib.Easing[easing];
3250 var anim = new type(el, args, duration, easing);
3251 anim.animateX(function() {
3252 Roo.callback(cb, scope);
3258 * Portions of this file are based on pieces of Yahoo User Interface Library
3259 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3260 * YUI licensed under the BSD License:
3261 * http://developer.yahoo.net/yui/license.txt
3262 * <script type="text/javascript">
3270 if (!libFlyweight) {
3271 libFlyweight = new Roo.Element.Flyweight();
3273 libFlyweight.dom = el;
3274 return libFlyweight;
3277 // since this uses fly! - it cant be in DOM (which does not have fly yet..)
3281 Roo.lib.AnimBase = function(el, attributes, duration, method) {
3283 this.init(el, attributes, duration, method);
3287 Roo.lib.AnimBase.fly = fly;
3291 Roo.lib.AnimBase.prototype = {
3293 toString: function() {
3294 var el = this.getEl();
3295 var id = el.id || el.tagName;
3296 return ("Anim " + id);
3300 noNegatives: /width|height|opacity|padding/i,
3301 offsetAttribute: /^((width|height)|(top|left))$/,
3302 defaultUnit: /width|height|top$|bottom$|left$|right$/i,
3303 offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3307 doMethod: function(attr, start, end) {
3308 return this.method(this.currentFrame, start, end - start, this.totalFrames);
3312 setAttribute: function(attr, val, unit) {
3313 if (this.patterns.noNegatives.test(attr)) {
3314 val = (val > 0) ? val : 0;
3317 Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3321 getAttribute: function(attr) {
3322 var el = this.getEl();
3323 var val = fly(el).getStyle(attr);
3325 if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3326 return parseFloat(val);
3329 var a = this.patterns.offsetAttribute.exec(attr) || [];
3330 var pos = !!( a[3] );
3331 var box = !!( a[2] );
3334 if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3335 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3344 getDefaultUnit: function(attr) {
3345 if (this.patterns.defaultUnit.test(attr)) {
3352 animateX : function(callback, scope) {
3353 var f = function() {
3354 this.onComplete.removeListener(f);
3355 if (typeof callback == "function") {
3356 callback.call(scope || this, this);
3359 this.onComplete.addListener(f, this);
3364 setRuntimeAttribute: function(attr) {
3367 var attributes = this.attributes;
3369 this.runtimeAttributes[attr] = {};
3371 var isset = function(prop) {
3372 return (typeof prop !== 'undefined');
3375 if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3379 start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3382 if (isset(attributes[attr]['to'])) {
3383 end = attributes[attr]['to'];
3384 } else if (isset(attributes[attr]['by'])) {
3385 if (start.constructor == Array) {
3387 for (var i = 0, len = start.length; i < len; ++i) {
3388 end[i] = start[i] + attributes[attr]['by'][i];
3391 end = start + attributes[attr]['by'];
3395 this.runtimeAttributes[attr].start = start;
3396 this.runtimeAttributes[attr].end = end;
3399 this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3403 init: function(el, attributes, duration, method) {
3405 var isAnimated = false;
3408 var startTime = null;
3411 var actualFrames = 0;
3414 el = Roo.getDom(el);
3417 this.attributes = attributes || {};
3420 this.duration = duration || 1;
3423 this.method = method || Roo.lib.Easing.easeNone;
3426 this.useSeconds = true;
3429 this.currentFrame = 0;
3432 this.totalFrames = Roo.lib.AnimMgr.fps;
3435 this.getEl = function() {
3440 this.isAnimated = function() {
3445 this.getStartTime = function() {
3449 this.runtimeAttributes = {};
3452 this.animate = function() {
3453 if (this.isAnimated()) {
3457 this.currentFrame = 0;
3459 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3461 Roo.lib.AnimMgr.registerElement(this);
3465 this.stop = function(finish) {
3467 this.currentFrame = this.totalFrames;
3468 this._onTween.fire();
3470 Roo.lib.AnimMgr.stop(this);
3473 var onStart = function() {
3474 this.onStart.fire();
3476 this.runtimeAttributes = {};
3477 for (var attr in this.attributes) {
3478 this.setRuntimeAttribute(attr);
3483 startTime = new Date();
3487 var onTween = function() {
3489 duration: new Date() - this.getStartTime(),
3490 currentFrame: this.currentFrame
3493 data.toString = function() {
3495 'duration: ' + data.duration +
3496 ', currentFrame: ' + data.currentFrame
3500 this.onTween.fire(data);
3502 var runtimeAttributes = this.runtimeAttributes;
3504 for (var attr in runtimeAttributes) {
3505 this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3511 var onComplete = function() {
3512 var actual_duration = (new Date() - startTime) / 1000 ;
3515 duration: actual_duration,
3516 frames: actualFrames,
3517 fps: actualFrames / actual_duration
3520 data.toString = function() {
3522 'duration: ' + data.duration +
3523 ', frames: ' + data.frames +
3524 ', fps: ' + data.fps
3530 this.onComplete.fire(data);
3534 this._onStart = new Roo.util.Event(this);
3535 this.onStart = new Roo.util.Event(this);
3536 this.onTween = new Roo.util.Event(this);
3537 this._onTween = new Roo.util.Event(this);
3538 this.onComplete = new Roo.util.Event(this);
3539 this._onComplete = new Roo.util.Event(this);
3540 this._onStart.addListener(onStart);
3541 this._onTween.addListener(onTween);
3542 this._onComplete.addListener(onComplete);
3547 * Portions of this file are based on pieces of Yahoo User Interface Library
3548 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3549 * YUI licensed under the BSD License:
3550 * http://developer.yahoo.net/yui/license.txt
3551 * <script type="text/javascript">
3555 Roo.lib.AnimMgr = new function() {
3572 this.registerElement = function(tween) {
3573 queue[queue.length] = tween;
3575 tween._onStart.fire();
3580 this.unRegister = function(tween, index) {
3581 tween._onComplete.fire();
3582 index = index || getIndex(tween);
3584 queue.splice(index, 1);
3588 if (tweenCount <= 0) {
3594 this.start = function() {
3595 if (thread === null) {
3596 thread = setInterval(this.run, this.delay);
3601 this.stop = function(tween) {
3603 clearInterval(thread);
3605 for (var i = 0, len = queue.length; i < len; ++i) {
3606 if (queue[0].isAnimated()) {
3607 this.unRegister(queue[0], 0);
3616 this.unRegister(tween);
3621 this.run = function() {
3622 for (var i = 0, len = queue.length; i < len; ++i) {
3623 var tween = queue[i];
3624 if (!tween || !tween.isAnimated()) {
3628 if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3630 tween.currentFrame += 1;
3632 if (tween.useSeconds) {
3633 correctFrame(tween);
3635 tween._onTween.fire();
3638 Roo.lib.AnimMgr.stop(tween, i);
3643 var getIndex = function(anim) {
3644 for (var i = 0, len = queue.length; i < len; ++i) {
3645 if (queue[i] == anim) {
3653 var correctFrame = function(tween) {
3654 var frames = tween.totalFrames;
3655 var frame = tween.currentFrame;
3656 var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3657 var elapsed = (new Date() - tween.getStartTime());
3660 if (elapsed < tween.duration * 1000) {
3661 tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3663 tweak = frames - (frame + 1);
3665 if (tweak > 0 && isFinite(tweak)) {
3666 if (tween.currentFrame + tweak >= frames) {
3667 tweak = frames - (frame + 1);
3670 tween.currentFrame += tweak;
3676 * Portions of this file are based on pieces of Yahoo User Interface Library
3677 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3678 * YUI licensed under the BSD License:
3679 * http://developer.yahoo.net/yui/license.txt
3680 * <script type="text/javascript">
3683 Roo.lib.Bezier = new function() {
3685 this.getPosition = function(points, t) {
3686 var n = points.length;
3689 for (var i = 0; i < n; ++i) {
3690 tmp[i] = [points[i][0], points[i][1]];
3693 for (var j = 1; j < n; ++j) {
3694 for (i = 0; i < n - j; ++i) {
3695 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3696 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3700 return [ tmp[0][0], tmp[0][1] ];
3706 * @class Roo.lib.Color
3708 * An abstract Color implementation. Concrete Color implementations should use
3709 * an instance of this function as their prototype, and implement the getRGB and
3710 * getHSL functions. getRGB should return an object representing the RGB
3711 * components of this Color, with the red, green, and blue components in the
3712 * range [0,255] and the alpha component in the range [0,100]. getHSL should
3713 * return an object representing the HSL components of this Color, with the hue
3714 * component in the range [0,360), the saturation and lightness components in
3715 * the range [0,100], and the alpha component in the range [0,1].
3720 * Functions for Color handling and processing.
3722 * http://www.safalra.com/web-design/javascript/Color-handling-and-processing/
3724 * The author of this program, Safalra (Stephen Morley), irrevocably releases all
3725 * rights to this program, with the intention of it becoming part of the public
3726 * domain. Because this program is released into the public domain, it comes with
3727 * no warranty either expressed or implied, to the extent permitted by law.
3729 * For more free and public domain JavaScript code by the same author, visit:
3730 * http://www.safalra.com/web-design/javascript/
3733 Roo.lib.Color = function() { }
3736 Roo.apply(Roo.lib.Color.prototype, {
3744 * @return {Object} an object representing the RGBA components of this Color. The red,
3745 * green, and blue components are converted to integers in the range [0,255].
3746 * The alpha is a value in the range [0,1].
3748 getIntegerRGB : function(){
3750 // get the RGB components of this Color
3751 var rgb = this.getRGB();
3753 // return the integer components
3755 'r' : Math.round(rgb.r),
3756 'g' : Math.round(rgb.g),
3757 'b' : Math.round(rgb.b),
3765 * @return {Object} an object representing the RGBA components of this Color. The red,
3766 * green, and blue components are converted to numbers in the range [0,100].
3767 * The alpha is a value in the range [0,1].
3769 getPercentageRGB : function(){
3771 // get the RGB components of this Color
3772 var rgb = this.getRGB();
3774 // return the percentage components
3776 'r' : 100 * rgb.r / 255,
3777 'g' : 100 * rgb.g / 255,
3778 'b' : 100 * rgb.b / 255,
3785 * getCSSHexadecimalRGB
3786 * @return {String} a string representing this Color as a CSS hexadecimal RGB Color
3787 * value - that is, a string of the form #RRGGBB where each of RR, GG, and BB
3788 * are two-digit hexadecimal numbers.
3790 getCSSHexadecimalRGB : function()
3793 // get the integer RGB components
3794 var rgb = this.getIntegerRGB();
3796 // determine the hexadecimal equivalents
3797 var r16 = rgb.r.toString(16);
3798 var g16 = rgb.g.toString(16);
3799 var b16 = rgb.b.toString(16);
3801 // return the CSS RGB Color value
3803 + (r16.length == 2 ? r16 : '0' + r16)
3804 + (g16.length == 2 ? g16 : '0' + g16)
3805 + (b16.length == 2 ? b16 : '0' + b16);
3811 * @return {String} a string representing this Color as a CSS integer RGB Color
3812 * value - that is, a string of the form rgb(r,g,b) where each of r, g, and b
3813 * are integers in the range [0,255].
3815 getCSSIntegerRGB : function(){
3817 // get the integer RGB components
3818 var rgb = this.getIntegerRGB();
3820 // return the CSS RGB Color value
3821 return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
3827 * @return {String} Returns a string representing this Color as a CSS integer RGBA Color
3828 * value - that is, a string of the form rgba(r,g,b,a) where each of r, g, and
3829 * b are integers in the range [0,255] and a is in the range [0,1].
3831 getCSSIntegerRGBA : function(){
3833 // get the integer RGB components
3834 var rgb = this.getIntegerRGB();
3836 // return the CSS integer RGBA Color value
3837 return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgb.a + ')';
3842 * getCSSPercentageRGB
3843 * @return {String} a string representing this Color as a CSS percentage RGB Color
3844 * value - that is, a string of the form rgb(r%,g%,b%) where each of r, g, and
3845 * b are in the range [0,100].
3847 getCSSPercentageRGB : function(){
3849 // get the percentage RGB components
3850 var rgb = this.getPercentageRGB();
3852 // return the CSS RGB Color value
3853 return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%)';
3858 * getCSSPercentageRGBA
3859 * @return {String} a string representing this Color as a CSS percentage RGBA Color
3860 * value - that is, a string of the form rgba(r%,g%,b%,a) where each of r, g,
3861 * and b are in the range [0,100] and a is in the range [0,1].
3863 getCSSPercentageRGBA : function(){
3865 // get the percentage RGB components
3866 var rgb = this.getPercentageRGB();
3868 // return the CSS percentage RGBA Color value
3869 return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%,' + rgb.a + ')';
3875 * @return {String} a string representing this Color as a CSS HSL Color value - that
3876 * is, a string of the form hsl(h,s%,l%) where h is in the range [0,100] and
3877 * s and l are in the range [0,100].
3879 getCSSHSL : function(){
3881 // get the HSL components
3882 var hsl = this.getHSL();
3884 // return the CSS HSL Color value
3885 return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%)';
3891 * @return {String} a string representing this Color as a CSS HSLA Color value - that
3892 * is, a string of the form hsla(h,s%,l%,a) where h is in the range [0,100],
3893 * s and l are in the range [0,100], and a is in the range [0,1].
3895 getCSSHSLA : function(){
3897 // get the HSL components
3898 var hsl = this.getHSL();
3900 // return the CSS HSL Color value
3901 return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%,' + hsl.a + ')';
3906 * Sets the Color of the specified node to this Color. This functions sets
3907 * the CSS 'color' property for the node. The parameter is:
3909 * @param {DomElement} node - the node whose Color should be set
3911 setNodeColor : function(node){
3913 // set the Color of the node
3914 node.style.color = this.getCSSHexadecimalRGB();
3919 * Sets the background Color of the specified node to this Color. This
3920 * functions sets the CSS 'background-color' property for the node. The
3923 * @param {DomElement} node - the node whose background Color should be set
3925 setNodeBackgroundColor : function(node){
3927 // set the background Color of the node
3928 node.style.backgroundColor = this.getCSSHexadecimalRGB();
3931 // convert between formats..
3934 var r = this.getIntegerRGB();
3935 return new Roo.lib.RGBColor(r.r,r.g,r.b,r.a);
3940 var hsl = this.getHSL();
3941 // return the CSS HSL Color value
3942 return new Roo.lib.HSLColor(hsl.h, hsl.s, hsl.l , hsl.a );
3948 var rgb = this.toRGB();
3949 var hsv = rgb.getHSV();
3950 // return the CSS HSL Color value
3951 return new Roo.lib.HSVColor(hsv.h, hsv.s, hsv.v , hsv.a );
3955 // modify v = 0 ... 1 (eg. 0.5)
3956 saturate : function(v)
3958 var rgb = this.toRGB();
3959 var hsv = rgb.getHSV();
3960 return new Roo.lib.HSVColor(hsv.h, hsv.s * v, hsv.v , hsv.a );
3968 * @return {Object} the RGB and alpha components of this Color as an object with r,
3969 * g, b, and a properties. r, g, and b are in the range [0,255] and a is in
3974 // return the RGB components
3986 * @return {Object} the HSV and alpha components of this Color as an object with h,
3987 * s, v, and a properties. h is in the range [0,360), s and v are in the range
3988 * [0,100], and a is in the range [0,1].
3993 // calculate the HSV components if necessary
3994 if (this.hsv == null) {
3995 this.calculateHSV();
3998 // return the HSV components
4010 * @return {Object} the HSL and alpha components of this Color as an object with h,
4011 * s, l, and a properties. h is in the range [0,360), s and l are in the range
4012 * [0,100], and a is in the range [0,1].
4014 getHSL : function(){
4017 // calculate the HSV components if necessary
4018 if (this.hsl == null) { this.calculateHSL(); }
4020 // return the HSL components
4035 * @class Roo.lib.RGBColor
4036 * @extends Roo.lib.Color
4037 * Creates a Color specified in the RGB Color space, with an optional alpha
4038 * component. The parameters are:
4042 * @param {Number} r - the red component, clipped to the range [0,255]
4043 * @param {Number} g - the green component, clipped to the range [0,255]
4044 * @param {Number} b - the blue component, clipped to the range [0,255]
4045 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4046 * optional and defaults to 1
4048 Roo.lib.RGBColor = function (r, g, b, a){
4050 // store the alpha component after clipping it if necessary
4051 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4053 // store the RGB components after clipping them if necessary
4056 'r' : Math.max(0, Math.min(255, r)),
4057 'g' : Math.max(0, Math.min(255, g)),
4058 'b' : Math.max(0, Math.min(255, b))
4061 // initialise the HSV and HSL components to null
4065 * //private returns the HSV or HSL hue component of this RGBColor. The hue is in the
4066 * range [0,360). The parameters are:
4068 * maximum - the maximum of the RGB component values
4069 * range - the range of the RGB component values
4074 // this does an 'exteds'
4075 Roo.extend(Roo.lib.RGBColor, Roo.lib.Color, {
4078 getHue : function(maximum, range)
4082 // check whether the range is zero
4085 // set the hue to zero (any hue is acceptable as the Color is grey)
4090 // determine which of the components has the highest value and set the hue
4093 // red has the highest value
4095 var hue = (rgb.g - rgb.b) / range * 60;
4096 if (hue < 0) { hue += 360; }
4099 // green has the highest value
4101 var hue = (rgb.b - rgb.r) / range * 60 + 120;
4104 // blue has the highest value
4106 var hue = (rgb.r - rgb.g) / range * 60 + 240;
4118 /* //private Calculates and stores the HSV components of this RGBColor so that they can
4119 * be returned be the getHSV function.
4121 calculateHSV : function(){
4123 // get the maximum and range of the RGB component values
4124 var maximum = Math.max(rgb.r, rgb.g, rgb.b);
4125 var range = maximum - Math.min(rgb.r, rgb.g, rgb.b);
4127 // store the HSV components
4130 'h' : this.getHue(maximum, range),
4131 's' : (maximum == 0 ? 0 : 100 * range / maximum),
4132 'v' : maximum / 2.55
4137 /* //private Calculates and stores the HSL components of this RGBColor so that they can
4138 * be returned be the getHSL function.
4140 calculateHSL : function(){
4142 // get the maximum and range of the RGB component values
4143 var maximum = Math.max(rgb.r, rgb.g, rgb.b);
4144 var range = maximum - Math.min(rgb.r, rgb.g, rgb.b);
4146 // determine the lightness in the range [0,1]
4147 var l = maximum / 255 - range / 510;
4149 // store the HSL components
4152 'h' : this.getHue(maximum, range),
4153 's' : (range == 0 ? 0 : range / 2.55 / (l < 0.5 ? l * 2 : 2 - l * 2)),
4162 * @class Roo.lib.HSVColor
4163 * @extends Roo.lib.Color
4164 * Creates a Color specified in the HSV Color space, with an optional alpha
4165 * component. The parameters are:
4168 * @param {Number} h - the hue component, wrapped to the range [0,360)
4169 * @param {Number} s - the saturation component, clipped to the range [0,100]
4170 * @param {Number} v - the value component, clipped to the range [0,100]
4171 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4172 * optional and defaults to 1
4174 Roo.lib.HSVColor = function (h, s, v, a){
4176 // store the alpha component after clipping it if necessary
4177 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4179 // store the HSV components after clipping or wrapping them if necessary
4182 'h' : (h % 360 + 360) % 360,
4183 's' : Math.max(0, Math.min(100, s)),
4184 'v' : Math.max(0, Math.min(100, v))
4187 // initialise the RGB and HSL components to null
4192 Roo.extend(Roo.lib.HSVColor, Roo.lib.Color, {
4193 /* Calculates and stores the RGB components of this HSVColor so that they can
4194 * be returned be the getRGB function.
4196 calculateRGB: function ()
4199 // check whether the saturation is zero
4202 // set the Color to the appropriate shade of grey
4209 // set some temporary values
4210 var f = hsv.h / 60 - Math.floor(hsv.h / 60);
4211 var p = hsv.v * (1 - hsv.s / 100);
4212 var q = hsv.v * (1 - hsv.s / 100 * f);
4213 var t = hsv.v * (1 - hsv.s / 100 * (1 - f));
4215 // set the RGB Color components to their temporary values
4216 switch (Math.floor(hsv.h / 60)){
4217 case 0: var r = hsv.v; var g = t; var b = p; break;
4218 case 1: var r = q; var g = hsv.v; var b = p; break;
4219 case 2: var r = p; var g = hsv.v; var b = t; break;
4220 case 3: var r = p; var g = q; var b = hsv.v; break;
4221 case 4: var r = t; var g = p; var b = hsv.v; break;
4222 case 5: var r = hsv.v; var g = p; var b = q; break;
4227 // store the RGB components
4237 /* Calculates and stores the HSL components of this HSVColor so that they can
4238 * be returned be the getHSL function.
4240 calculateHSL : function (){
4243 // determine the lightness in the range [0,100]
4244 var l = (2 - hsv.s / 100) * hsv.v / 2;
4246 // store the HSL components
4250 's' : hsv.s * hsv.v / (l < 50 ? l * 2 : 200 - l * 2),
4254 // correct a division-by-zero error
4255 if (isNaN(hsl.s)) { hsl.s = 0; }
4264 * @class Roo.lib.HSLColor
4265 * @extends Roo.lib.Color
4268 * Creates a Color specified in the HSL Color space, with an optional alpha
4269 * component. The parameters are:
4271 * @param {Number} h - the hue component, wrapped to the range [0,360)
4272 * @param {Number} s - the saturation component, clipped to the range [0,100]
4273 * @param {Number} l - the lightness component, clipped to the range [0,100]
4274 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4275 * optional and defaults to 1
4278 Roo.lib.HSLColor = function(h, s, l, a){
4280 // store the alpha component after clipping it if necessary
4281 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4283 // store the HSL components after clipping or wrapping them if necessary
4286 'h' : (h % 360 + 360) % 360,
4287 's' : Math.max(0, Math.min(100, s)),
4288 'l' : Math.max(0, Math.min(100, l))
4291 // initialise the RGB and HSV components to null
4294 Roo.extend(Roo.lib.HSLColor, Roo.lib.Color, {
4296 /* Calculates and stores the RGB components of this HSLColor so that they can
4297 * be returned be the getRGB function.
4299 calculateRGB: function (){
4301 // check whether the saturation is zero
4302 if (this.hsl.s == 0){
4304 // store the RGB components representing the appropriate shade of grey
4307 'r' : this.hsl.l * 2.55,
4308 'g' : this.hsl.l * 2.55,
4309 'b' : this.hsl.l * 2.55
4314 // set some temporary values
4315 var p = this.hsl.l < 50
4316 ? this.hsl.l * (1 + hsl.s / 100)
4317 : this.hsl.l + hsl.s - hsl.l * hsl.s / 100;
4318 var q = 2 * hsl.l - p;
4320 // initialise the RGB components
4323 'r' : (h + 120) / 60 % 6,
4325 'b' : (h + 240) / 60 % 6
4328 // loop over the RGB components
4329 for (var key in this.rgb){
4331 // ensure that the property is not inherited from the root object
4332 if (this.rgb.hasOwnProperty(key)){
4334 // set the component to its value in the range [0,100]
4335 if (this.rgb[key] < 1){
4336 this.rgb[key] = q + (p - q) * this.rgb[key];
4337 }else if (this.rgb[key] < 3){
4339 }else if (this.rgb[key] < 4){
4340 this.rgb[key] = q + (p - q) * (4 - this.rgb[key]);
4345 // set the component to its value in the range [0,255]
4346 this.rgb[key] *= 2.55;
4356 /* Calculates and stores the HSV components of this HSLColor so that they can
4357 * be returned be the getHSL function.
4359 calculateHSV : function(){
4361 // set a temporary value
4362 var t = this.hsl.s * (this.hsl.l < 50 ? this.hsl.l : 100 - this.hsl.l) / 100;
4364 // store the HSV components
4368 's' : 200 * t / (this.hsl.l + t),
4369 'v' : t + this.hsl.l
4372 // correct a division-by-zero error
4373 if (isNaN(this.hsv.s)) { this.hsv.s = 0; }
4380 * Portions of this file are based on pieces of Yahoo User Interface Library
4381 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4382 * YUI licensed under the BSD License:
4383 * http://developer.yahoo.net/yui/license.txt
4384 * <script type="text/javascript">
4389 Roo.lib.ColorAnim = function(el, attributes, duration, method) {
4390 Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
4393 Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
4395 var fly = Roo.lib.AnimBase.fly;
4397 var superclass = Y.ColorAnim.superclass;
4398 var proto = Y.ColorAnim.prototype;
4400 proto.toString = function() {
4401 var el = this.getEl();
4402 var id = el.id || el.tagName;
4403 return ("ColorAnim " + id);
4406 proto.patterns.color = /color$/i;
4407 proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
4408 proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
4409 proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
4410 proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
4413 proto.parseColor = function(s) {
4414 if (s.length == 3) {
4418 var c = this.patterns.hex.exec(s);
4419 if (c && c.length == 4) {
4420 return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
4423 c = this.patterns.rgb.exec(s);
4424 if (c && c.length == 4) {
4425 return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
4428 c = this.patterns.hex3.exec(s);
4429 if (c && c.length == 4) {
4430 return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
4435 // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
4436 proto.getAttribute = function(attr) {
4437 var el = this.getEl();
4438 if (this.patterns.color.test(attr)) {
4439 var val = fly(el).getStyle(attr);
4441 if (this.patterns.transparent.test(val)) {
4442 var parent = el.parentNode;
4443 val = fly(parent).getStyle(attr);
4445 while (parent && this.patterns.transparent.test(val)) {
4446 parent = parent.parentNode;
4447 val = fly(parent).getStyle(attr);
4448 if (parent.tagName.toUpperCase() == 'HTML') {
4454 val = superclass.getAttribute.call(this, attr);
4459 proto.getAttribute = function(attr) {
4460 var el = this.getEl();
4461 if (this.patterns.color.test(attr)) {
4462 var val = fly(el).getStyle(attr);
4464 if (this.patterns.transparent.test(val)) {
4465 var parent = el.parentNode;
4466 val = fly(parent).getStyle(attr);
4468 while (parent && this.patterns.transparent.test(val)) {
4469 parent = parent.parentNode;
4470 val = fly(parent).getStyle(attr);
4471 if (parent.tagName.toUpperCase() == 'HTML') {
4477 val = superclass.getAttribute.call(this, attr);
4483 proto.doMethod = function(attr, start, end) {
4486 if (this.patterns.color.test(attr)) {
4488 for (var i = 0, len = start.length; i < len; ++i) {
4489 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
4492 val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
4495 val = superclass.doMethod.call(this, attr, start, end);
4501 proto.setRuntimeAttribute = function(attr) {
4502 superclass.setRuntimeAttribute.call(this, attr);
4504 if (this.patterns.color.test(attr)) {
4505 var attributes = this.attributes;
4506 var start = this.parseColor(this.runtimeAttributes[attr].start);
4507 var end = this.parseColor(this.runtimeAttributes[attr].end);
4509 if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
4510 end = this.parseColor(attributes[attr].by);
4512 for (var i = 0, len = start.length; i < len; ++i) {
4513 end[i] = start[i] + end[i];
4517 this.runtimeAttributes[attr].start = start;
4518 this.runtimeAttributes[attr].end = end;
4524 * Portions of this file are based on pieces of Yahoo User Interface Library
4525 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4526 * YUI licensed under the BSD License:
4527 * http://developer.yahoo.net/yui/license.txt
4528 * <script type="text/javascript">
4534 easeNone: function (t, b, c, d) {
4535 return c * t / d + b;
4539 easeIn: function (t, b, c, d) {
4540 return c * (t /= d) * t + b;
4544 easeOut: function (t, b, c, d) {
4545 return -c * (t /= d) * (t - 2) + b;
4549 easeBoth: function (t, b, c, d) {
4550 if ((t /= d / 2) < 1) {
4551 return c / 2 * t * t + b;
4554 return -c / 2 * ((--t) * (t - 2) - 1) + b;
4558 easeInStrong: function (t, b, c, d) {
4559 return c * (t /= d) * t * t * t + b;
4563 easeOutStrong: function (t, b, c, d) {
4564 return -c * ((t = t / d - 1) * t * t * t - 1) + b;
4568 easeBothStrong: function (t, b, c, d) {
4569 if ((t /= d / 2) < 1) {
4570 return c / 2 * t * t * t * t + b;
4573 return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
4578 elasticIn: function (t, b, c, d, a, p) {
4582 if ((t /= d) == 1) {
4589 if (!a || a < Math.abs(c)) {
4594 var s = p / (2 * Math.PI) * Math.asin(c / a);
4597 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4601 elasticOut: function (t, b, c, d, a, p) {
4605 if ((t /= d) == 1) {
4612 if (!a || a < Math.abs(c)) {
4617 var s = p / (2 * Math.PI) * Math.asin(c / a);
4620 return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
4624 elasticBoth: function (t, b, c, d, a, p) {
4629 if ((t /= d / 2) == 2) {
4637 if (!a || a < Math.abs(c)) {
4642 var s = p / (2 * Math.PI) * Math.asin(c / a);
4646 return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
4647 Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4649 return a * Math.pow(2, -10 * (t -= 1)) *
4650 Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
4655 backIn: function (t, b, c, d, s) {
4656 if (typeof s == 'undefined') {
4659 return c * (t /= d) * t * ((s + 1) * t - s) + b;
4663 backOut: function (t, b, c, d, s) {
4664 if (typeof s == 'undefined') {
4667 return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
4671 backBoth: function (t, b, c, d, s) {
4672 if (typeof s == 'undefined') {
4676 if ((t /= d / 2 ) < 1) {
4677 return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
4679 return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
4683 bounceIn: function (t, b, c, d) {
4684 return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
4688 bounceOut: function (t, b, c, d) {
4689 if ((t /= d) < (1 / 2.75)) {
4690 return c * (7.5625 * t * t) + b;
4691 } else if (t < (2 / 2.75)) {
4692 return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
4693 } else if (t < (2.5 / 2.75)) {
4694 return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
4696 return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
4700 bounceBoth: function (t, b, c, d) {
4702 return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
4704 return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
4707 * Portions of this file are based on pieces of Yahoo User Interface Library
4708 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4709 * YUI licensed under the BSD License:
4710 * http://developer.yahoo.net/yui/license.txt
4711 * <script type="text/javascript">
4715 Roo.lib.Motion = function(el, attributes, duration, method) {
4717 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
4721 Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
4725 var superclass = Y.Motion.superclass;
4726 var proto = Y.Motion.prototype;
4728 proto.toString = function() {
4729 var el = this.getEl();
4730 var id = el.id || el.tagName;
4731 return ("Motion " + id);
4734 proto.patterns.points = /^points$/i;
4736 proto.setAttribute = function(attr, val, unit) {
4737 if (this.patterns.points.test(attr)) {
4738 unit = unit || 'px';
4739 superclass.setAttribute.call(this, 'left', val[0], unit);
4740 superclass.setAttribute.call(this, 'top', val[1], unit);
4742 superclass.setAttribute.call(this, attr, val, unit);
4746 proto.getAttribute = function(attr) {
4747 if (this.patterns.points.test(attr)) {
4749 superclass.getAttribute.call(this, 'left'),
4750 superclass.getAttribute.call(this, 'top')
4753 val = superclass.getAttribute.call(this, attr);
4759 proto.doMethod = function(attr, start, end) {
4762 if (this.patterns.points.test(attr)) {
4763 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
4764 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
4766 val = superclass.doMethod.call(this, attr, start, end);
4771 proto.setRuntimeAttribute = function(attr) {
4772 if (this.patterns.points.test(attr)) {
4773 var el = this.getEl();
4774 var attributes = this.attributes;
4776 var control = attributes['points']['control'] || [];
4780 if (control.length > 0 && !(control[0] instanceof Array)) {
4781 control = [control];
4784 for (i = 0,len = control.length; i < len; ++i) {
4785 tmp[i] = control[i];
4790 Roo.fly(el).position();
4792 if (isset(attributes['points']['from'])) {
4793 Roo.lib.Dom.setXY(el, attributes['points']['from']);
4796 Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
4799 start = this.getAttribute('points');
4802 if (isset(attributes['points']['to'])) {
4803 end = translateValues.call(this, attributes['points']['to'], start);
4805 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4806 for (i = 0,len = control.length; i < len; ++i) {
4807 control[i] = translateValues.call(this, control[i], start);
4811 } else if (isset(attributes['points']['by'])) {
4812 end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
4814 for (i = 0,len = control.length; i < len; ++i) {
4815 control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
4819 this.runtimeAttributes[attr] = [start];
4821 if (control.length > 0) {
4822 this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
4825 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
4828 superclass.setRuntimeAttribute.call(this, attr);
4832 var translateValues = function(val, start) {
4833 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4834 val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
4839 var isset = function(prop) {
4840 return (typeof prop !== 'undefined');
4844 * Portions of this file are based on pieces of Yahoo User Interface Library
4845 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4846 * YUI licensed under the BSD License:
4847 * http://developer.yahoo.net/yui/license.txt
4848 * <script type="text/javascript">
4852 Roo.lib.Scroll = function(el, attributes, duration, method) {
4854 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
4858 Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
4862 var superclass = Y.Scroll.superclass;
4863 var proto = Y.Scroll.prototype;
4865 proto.toString = function() {
4866 var el = this.getEl();
4867 var id = el.id || el.tagName;
4868 return ("Scroll " + id);
4871 proto.doMethod = function(attr, start, end) {
4874 if (attr == 'scroll') {
4876 this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
4877 this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
4881 val = superclass.doMethod.call(this, attr, start, end);
4886 proto.getAttribute = function(attr) {
4888 var el = this.getEl();
4890 if (attr == 'scroll') {
4891 val = [ el.scrollLeft, el.scrollTop ];
4893 val = superclass.getAttribute.call(this, attr);
4899 proto.setAttribute = function(attr, val, unit) {
4900 var el = this.getEl();
4902 if (attr == 'scroll') {
4903 el.scrollLeft = val[0];
4904 el.scrollTop = val[1];
4906 superclass.setAttribute.call(this, attr, val, unit);
4911 * Originally based of this code... - refactored for Roo...
4912 * https://github.com/aaalsaleh/undo-manager
4915 * @author Abdulrahman Alsaleh
4916 * @copyright 2015 Abdulrahman Alsaleh
4917 * @license MIT License (c)
4919 * Hackily modifyed by alan@roojs.com
4924 * TOTALLY UNTESTED...
4926 * Documentation to be done....
4931 * @class Roo.lib.UndoManager
4932 * An undo manager implementation in JavaScript. It follows the W3C UndoManager and DOM Transaction
4933 * Draft and the undocumented and disabled Mozilla Firefox's UndoManager implementation.
4939 editor.undoManager = new Roo.lib.UndoManager(1000, editor);
4943 * For more information see this blog post with examples:
4944 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
4945 - Create Elements using DOM, HTML fragments and Templates</a>.
4947 * @param {Number} limit how far back to go ... use 1000?
4948 * @param {Object} scope usually use document..
4951 Roo.lib.UndoManager = function (limit, undoScopeHost)
4955 this.scope = undoScopeHost;
4956 this.fireEvent = typeof CustomEvent != 'undefined' && undoScopeHost && undoScopeHost.dispatchEvent;
4957 if (this.fireEvent) {
4964 Roo.lib.UndoManager.prototype = {
4975 * To push and execute a transaction, the method undoManager.transact
4976 * must be called by passing a transaction object as the first argument, and a merge
4977 * flag as the second argument. A transaction object has the following properties:
4981 undoManager.transact({
4983 execute: function() { ... },
4984 undo: function() { ... },
4985 // redo same as execute
4986 redo: function() { this.execute(); }
4989 // merge transaction
4990 undoManager.transact({
4992 execute: function() { ... }, // this will be run...
4993 undo: function() { ... }, // what to do when undo is run.
4994 // redo same as execute
4995 redo: function() { this.execute(); }
5000 * @param {Object} transaction The transaction to add to the stack.
5001 * @return {String} The HTML fragment
5005 transact : function (transaction, merge)
5007 if (arguments.length < 2) {
5008 throw new TypeError('Not enough arguments to UndoManager.transact.');
5011 transaction.execute();
5013 this.stack.splice(0, this.position);
5014 if (merge && this.length) {
5015 this.stack[0].push(transaction);
5017 this.stack.unshift([transaction]);
5022 if (this.limit && this.stack.length > this.limit) {
5023 this.length = this.stack.length = this.limit;
5025 this.length = this.stack.length;
5028 if (this.fireEvent) {
5029 this.scope.dispatchEvent(
5030 new CustomEvent('DOMTransaction', {
5032 transactions: this.stack[0].slice()
5040 //Roo.log("transaction: pos:" + this.position + " len: " + this.length + " slen:" + this.stack.length);
5047 //Roo.log("undo: pos:" + this.position + " len: " + this.length + " slen:" + this.stack.length);
5049 if (this.position < this.length) {
5050 for (var i = this.stack[this.position].length - 1; i >= 0; i--) {
5051 this.stack[this.position][i].undo();
5055 if (this.fireEvent) {
5056 this.scope.dispatchEvent(
5057 new CustomEvent('undo', {
5059 transactions: this.stack[this.position - 1].slice()
5071 if (this.position > 0) {
5072 for (var i = 0, n = this.stack[this.position - 1].length; i < n; i++) {
5073 this.stack[this.position - 1][i].redo();
5077 if (this.fireEvent) {
5078 this.scope.dispatchEvent(
5079 new CustomEvent('redo', {
5081 transactions: this.stack[this.position].slice()
5091 item : function (index)
5093 if (index >= 0 && index < this.length) {
5094 return this.stack[index].slice();
5099 clearUndo : function () {
5100 this.stack.length = this.length = this.position;
5103 clearRedo : function () {
5104 this.stack.splice(0, this.position);
5106 this.length = this.stack.length;
5109 * Reset the undo - probaly done on load to clear all history.
5116 this.current_html = this.scope.innerHTML;
5117 if (this.timer !== false) {
5118 clearTimeout(this.timer);
5130 // this will handle the undo/redo on the element.?
5131 bindEvents : function()
5133 var el = this.scope;
5134 el.undoManager = this;
5137 this.scope.addEventListener('keydown', function(e) {
5138 if ((e.ctrlKey || e.metaKey) && e.keyCode === 90) {
5140 el.undoManager.redo(); // Ctrl/Command + Shift + Z
5142 el.undoManager.undo(); // Ctrl/Command + Z
5149 this.scope.addEventListener('keyup', function(e) {
5150 if ((e.ctrlKey || e.metaKey) && e.keyCode === 90) {
5159 el.addEventListener('input', function(e) {
5160 if(el.innerHTML == t.current_html) {
5163 // only record events every second.
5164 if (t.timer !== false) {
5165 clearTimeout(t.timer);
5168 t.timer = setTimeout(function() { t.merge = false; }, 1000);
5170 t.addEvent(t.merge);
5171 t.merge = true; // ignore changes happening every second..
5175 * Manually add an event.
5176 * Normall called without arguements - and it will just get added to the stack.
5180 addEvent : function(merge)
5182 //Roo.log("undomanager +" + (merge ? 'Y':'n'));
5183 // not sure if this should clear the timer
5184 merge = typeof(merge) == 'undefined' ? false : merge;
5186 this.scope.undoManager.transact({
5188 oldHTML: this.current_html,
5189 newHTML: this.scope.innerHTML,
5190 // nothing to execute (content already changed when input is fired)
5191 execute: function() { },
5193 this.scope.innerHTML = this.current_html = this.oldHTML;
5196 this.scope.innerHTML = this.current_html = this.newHTML;
5198 }, false); //merge);
5202 this.current_html = this.scope.innerHTML;
5212 * @class Roo.lib.Range
5214 * This is a toolkit, normally used to copy features into a Dom Range element
5215 * Roo.lib.Range.wrap(x);
5220 Roo.lib.Range = function() { };
5223 * Wrap a Dom Range object, to give it new features...
5225 * @param {Range} the range to wrap
5227 Roo.lib.Range.wrap = function(r) {
5228 return Roo.apply(r, Roo.lib.Range.prototype);
5231 * find a parent node eg. LI / OL
5232 * @param {string|Array} node name or array of nodenames
5233 * @return {DomElement|false}
5235 Roo.apply(Roo.lib.Range.prototype,
5238 closest : function(str)
5240 if (typeof(str) != 'string') {
5241 // assume it's a array.
5242 for(var i = 0;i < str.length;i++) {
5243 var r = this.closest(str[i]);
5251 str = str.toLowerCase();
5252 var n = this.commonAncestorContainer; // might not be a node
5253 while (n.nodeType != 1) {
5257 if (n.nodeName.toLowerCase() == str ) {
5260 if (n.nodeName.toLowerCase() == 'body') {
5264 return n.closest(str) || false;
5267 cloneRange : function()
5269 return Roo.lib.Range.wrap(Range.prototype.cloneRange.call(this));
5272 * @class Roo.lib.Selection
5274 * This is a toolkit, normally used to copy features into a Dom Selection element
5275 * Roo.lib.Selection.wrap(x);
5280 Roo.lib.Selection = function() { };
5283 * Wrap a Dom Range object, to give it new features...
5285 * @param {Range} the range to wrap
5287 Roo.lib.Selection.wrap = function(r, doc) {
5288 Roo.apply(r, Roo.lib.Selection.prototype);
5289 r.ownerDocument = doc; // usefull so we dont have to keep referening to it.
5293 * find a parent node eg. LI / OL
5294 * @param {string|Array} node name or array of nodenames
5295 * @return {DomElement|false}
5297 Roo.apply(Roo.lib.Selection.prototype,
5300 * the owner document
5302 ownerDocument : false,
5304 getRangeAt : function(n)
5306 return Roo.lib.Range.wrap(Selection.prototype.getRangeAt.call(this,n));
5310 * insert node at selection
5311 * @param {DomElement|string} node
5312 * @param {string} cursor (after|in|none) where to place the cursor after inserting.
5314 insertNode: function(node, cursor)
5316 if (typeof(node) == 'string') {
5317 node = this.ownerDocument.createElement(node);
5318 if (cursor == 'in') {
5319 node.innerHTML = ' ';
5323 var range = this.getRangeAt(0);
5325 if (this.type != 'Caret') {
5326 range.deleteContents();
5328 var sn = node.childNodes[0]; // select the contents.
5332 range.insertNode(node);
5333 if (cursor == 'after') {
5334 node.insertAdjacentHTML('afterend', ' ');
5335 sn = node.nextSibling;
5338 if (cursor == 'none') {
5342 this.cursorText(sn);
5345 cursorText : function(n)
5348 //var range = this.getRangeAt(0);
5349 range = Roo.lib.Range.wrap(new Range());
5350 //range.selectNode(n);
5352 var ix = Array.from(n.parentNode.childNodes).indexOf(n);
5353 range.setStart(n.parentNode,ix);
5354 range.setEnd(n.parentNode,ix+1);
5355 //range.collapse(false);
5357 this.removeAllRanges();
5358 this.addRange(range);
5360 Roo.log([n, range, this,this.baseOffset,this.extentOffset, this.type]);
5362 cursorAfter : function(n)
5364 if (!n.nextSibling || n.nextSibling.nodeValue != ' ') {
5365 n.insertAdjacentHTML('afterend', ' ');
5367 this.cursorText (n.nextSibling);
5373 * Ext JS Library 1.1.1
5374 * Copyright(c) 2006-2007, Ext JS, LLC.
5376 * Originally Released Under LGPL - original licence link has changed is not relivant.
5379 * <script type="text/javascript">
5383 // nasty IE9 hack - what a pile of crap that is..
5385 if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
5386 Range.prototype.createContextualFragment = function (html) {
5387 var doc = window.document;
5388 var container = doc.createElement("div");
5389 container.innerHTML = html;
5390 var frag = doc.createDocumentFragment(), n;
5391 while ((n = container.firstChild)) {
5392 frag.appendChild(n);
5399 * @class Roo.DomHelper
5400 * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
5401 * 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>.
5404 Roo.DomHelper = function(){
5405 var tempTableEl = null;
5406 var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
5407 var tableRe = /^table|tbody|tr|td$/i;
5409 // build as innerHTML where available
5411 var createHtml = function(o){
5412 if(typeof o == 'string'){
5421 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") { continue; }
5422 if(attr == "style"){
5424 if(typeof s == "function"){
5427 if(typeof s == "string"){
5428 b += ' style="' + s + '"';
5429 }else if(typeof s == "object"){
5432 if(typeof s[key] != "function"){
5433 b += key + ":" + s[key] + ";";
5440 b += ' class="' + o["cls"] + '"';
5441 }else if(attr == "htmlFor"){
5442 b += ' for="' + o["htmlFor"] + '"';
5444 b += " " + attr + '="' + o[attr] + '"';
5448 if(emptyTags.test(o.tag)){
5452 var cn = o.children || o.cn;
5454 //http://bugs.kde.org/show_bug.cgi?id=71506
5455 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
5456 for(var i = 0, len = cn.length; i < len; i++) {
5457 b += createHtml(cn[i], b);
5460 b += createHtml(cn, b);
5466 b += "</" + o.tag + ">";
5473 var createDom = function(o, parentNode){
5475 // defininition craeted..
5477 if (o.ns && o.ns != 'html') {
5479 if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
5480 xmlns[o.ns] = o.xmlns;
5483 if (typeof(xmlns[o.ns]) == 'undefined') {
5484 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
5490 if (typeof(o) == 'string') {
5491 return parentNode.appendChild(document.createTextNode(o));
5493 o.tag = o.tag || div;
5494 if (o.ns && Roo.isIE) {
5496 o.tag = o.ns + ':' + o.tag;
5499 var el = ns ? document.createElementNS( ns, o.tag||'div') : document.createElement(o.tag||'div');
5500 var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
5503 if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" ||
5504 attr == "style" || typeof o[attr] == "function") { continue; }
5506 if(attr=="cls" && Roo.isIE){
5507 el.className = o["cls"];
5509 if(useSet) { el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);}
5515 Roo.DomHelper.applyStyles(el, o.style);
5516 var cn = o.children || o.cn;
5518 //http://bugs.kde.org/show_bug.cgi?id=71506
5519 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
5520 for(var i = 0, len = cn.length; i < len; i++) {
5521 createDom(cn[i], el);
5528 el.innerHTML = o.html;
5531 parentNode.appendChild(el);
5536 var ieTable = function(depth, s, h, e){
5537 tempTableEl.innerHTML = [s, h, e].join('');
5538 var i = -1, el = tempTableEl;
5539 while(++i < depth && el.firstChild){
5545 // kill repeat to save bytes
5549 tbe = '</tbody>'+te,
5555 * Nasty code for IE's broken table implementation
5557 var insertIntoTable = function(tag, where, el, html){
5559 tempTableEl = document.createElement('div');
5564 if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
5567 if(where == 'beforebegin'){
5571 before = el.nextSibling;
5574 node = ieTable(4, trs, html, tre);
5576 else if(tag == 'tr'){
5577 if(where == 'beforebegin'){
5580 node = ieTable(3, tbs, html, tbe);
5581 } else if(where == 'afterend'){
5582 before = el.nextSibling;
5584 node = ieTable(3, tbs, html, tbe);
5585 } else{ // INTO a TR
5586 if(where == 'afterbegin'){
5587 before = el.firstChild;
5589 node = ieTable(4, trs, html, tre);
5591 } else if(tag == 'tbody'){
5592 if(where == 'beforebegin'){
5595 node = ieTable(2, ts, html, te);
5596 } else if(where == 'afterend'){
5597 before = el.nextSibling;
5599 node = ieTable(2, ts, html, te);
5601 if(where == 'afterbegin'){
5602 before = el.firstChild;
5604 node = ieTable(3, tbs, html, tbe);
5607 if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
5610 if(where == 'afterbegin'){
5611 before = el.firstChild;
5613 node = ieTable(2, ts, html, te);
5615 el.insertBefore(node, before);
5619 // this is a bit like the react update code...
5622 var updateNode = function(from, to)
5624 // should we handle non-standard elements?
5625 Roo.log(["UpdateNode" , from, to]);
5626 if (from.nodeType != to.nodeType) {
5627 Roo.log(["ReplaceChild - mismatch notType" , to, from ]);
5628 from.parentNode.replaceChild(to, from);
5631 if (from.nodeType == 3) {
5632 // assume it's text?!
5633 if (from.data == to.data) {
5636 from.data = to.data;
5639 if (!from.parentNode) {
5640 // not sure why this is happening?
5643 // assume 'to' doesnt have '1/3 nodetypes!
5644 // not sure why, by from, parent node might not exist?
5645 if (from.nodeType !=1 || from.tagName != to.tagName) {
5646 Roo.log(["ReplaceChild" , from, to ]);
5648 from.parentNode.replaceChild(to, from);
5651 // compare attributes
5652 var ar = Array.from(from.attributes);
5653 for(var i = 0; i< ar.length;i++) {
5654 if (to.hasAttribute(ar[i].name)) {
5657 if (ar[i].name == 'id') { // always keep ids?
5660 //if (ar[i].name == 'style') {
5661 // throw "style removed?";
5663 Roo.log("removeAttribute" + ar[i].name);
5664 from.removeAttribute(ar[i].name);
5667 for(var i = 0; i< ar.length;i++) {
5668 if (from.getAttribute(ar[i].name) == to.getAttribute(ar[i].name)) {
5669 Roo.log("skipAttribute " + ar[i].name + '=' + to.getAttribute(ar[i].name));
5672 Roo.log("updateAttribute " + ar[i].name + '=>' + to.getAttribute(ar[i].name));
5673 from.setAttribute(ar[i].name, to.getAttribute(ar[i].name));
5676 var far = Array.from(from.childNodes);
5677 var tar = Array.from(to.childNodes);
5678 // if the lengths are different.. then it's probably a editable content change, rather than
5679 // a change of the block definition..
5681 // this did notwork , as our rebuilt nodes did not include ID's so did not match at all.
5682 /*if (from.innerHTML == to.innerHTML) {
5685 if (far.length != tar.length) {
5686 from.innerHTML = to.innerHTML;
5691 for(var i = 0; i < Math.max(tar.length, far.length); i++) {
5692 if (i >= far.length) {
5693 from.appendChild(tar[i]);
5694 Roo.log(["add", tar[i]]);
5696 } else if ( i >= tar.length) {
5697 from.removeChild(far[i]);
5698 Roo.log(["remove", far[i]]);
5701 updateNode(far[i], tar[i]);
5713 /** True to force the use of DOM instead of html fragments @type Boolean */
5717 * Returns the markup for the passed Element(s) config
5718 * @param {Object} o The Dom object spec (and children)
5721 markup : function(o){
5722 return createHtml(o);
5726 * Applies a style specification to an element
5727 * @param {String/HTMLElement} el The element to apply styles to
5728 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
5729 * a function which returns such a specification.
5731 applyStyles : function(el, styles){
5734 if(typeof styles == "string"){
5735 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
5737 while ((matches = re.exec(styles)) != null){
5738 el.setStyle(matches[1], matches[2]);
5740 }else if (typeof styles == "object"){
5741 for (var style in styles){
5742 el.setStyle(style, styles[style]);
5744 }else if (typeof styles == "function"){
5745 Roo.DomHelper.applyStyles(el, styles.call());
5751 * Inserts an HTML fragment into the Dom
5752 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
5753 * @param {HTMLElement} el The context element
5754 * @param {String} html The HTML fragmenet
5755 * @return {HTMLElement} The new node
5757 insertHtml : function(where, el, html){
5758 where = where.toLowerCase();
5759 if(el.insertAdjacentHTML){
5760 if(tableRe.test(el.tagName)){
5762 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
5768 el.insertAdjacentHTML('BeforeBegin', html);
5769 return el.previousSibling;
5771 el.insertAdjacentHTML('AfterBegin', html);
5772 return el.firstChild;
5774 el.insertAdjacentHTML('BeforeEnd', html);
5775 return el.lastChild;
5777 el.insertAdjacentHTML('AfterEnd', html);
5778 return el.nextSibling;
5780 throw 'Illegal insertion point -> "' + where + '"';
5782 var range = el.ownerDocument.createRange();
5786 range.setStartBefore(el);
5787 frag = range.createContextualFragment(html);
5788 el.parentNode.insertBefore(frag, el);
5789 return el.previousSibling;
5792 range.setStartBefore(el.firstChild);
5793 frag = range.createContextualFragment(html);
5794 el.insertBefore(frag, el.firstChild);
5795 return el.firstChild;
5797 el.innerHTML = html;
5798 return el.firstChild;
5802 range.setStartAfter(el.lastChild);
5803 frag = range.createContextualFragment(html);
5804 el.appendChild(frag);
5805 return el.lastChild;
5807 el.innerHTML = html;
5808 return el.lastChild;
5811 range.setStartAfter(el);
5812 frag = range.createContextualFragment(html);
5813 el.parentNode.insertBefore(frag, el.nextSibling);
5814 return el.nextSibling;
5816 throw 'Illegal insertion point -> "' + where + '"';
5820 * Creates new Dom element(s) and inserts them before el
5821 * @param {String/HTMLElement/Element} el The context element
5822 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5823 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5824 * @return {HTMLElement/Roo.Element} The new node
5826 insertBefore : function(el, o, returnElement){
5827 return this.doInsert(el, o, returnElement, "beforeBegin");
5831 * Creates new Dom element(s) and inserts them after el
5832 * @param {String/HTMLElement/Element} el The context element
5833 * @param {Object} o The Dom object spec (and children)
5834 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5835 * @return {HTMLElement/Roo.Element} The new node
5837 insertAfter : function(el, o, returnElement){
5838 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
5842 * Creates new Dom element(s) and inserts them as the first child of el
5843 * @param {String/HTMLElement/Element} el The context element
5844 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5845 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5846 * @return {HTMLElement/Roo.Element} The new node
5848 insertFirst : function(el, o, returnElement){
5849 return this.doInsert(el, o, returnElement, "afterBegin");
5853 doInsert : function(el, o, returnElement, pos, sibling){
5854 el = Roo.getDom(el);
5856 if(this.useDom || o.ns){
5857 newNode = createDom(o, null);
5858 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
5860 var html = createHtml(o);
5861 newNode = this.insertHtml(pos, el, html);
5863 return returnElement ? Roo.get(newNode, true) : newNode;
5867 * Creates new Dom element(s) and appends them to el
5868 * @param {String/HTMLElement/Element} el The context element
5869 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5870 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5871 * @return {HTMLElement/Roo.Element} The new node
5873 append : function(el, o, returnElement){
5874 el = Roo.getDom(el);
5876 if(this.useDom || o.ns){
5877 newNode = createDom(o, null);
5878 el.appendChild(newNode);
5880 var html = createHtml(o);
5881 newNode = this.insertHtml("beforeEnd", el, html);
5883 return returnElement ? Roo.get(newNode, true) : newNode;
5887 * Creates new Dom element(s) and overwrites the contents of el with them
5888 * @param {String/HTMLElement/Element} el The context element
5889 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5890 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5891 * @return {HTMLElement/Roo.Element} The new node
5893 overwrite : function(el, o, returnElement)
5895 el = Roo.getDom(el);
5898 while (el.childNodes.length) {
5899 el.removeChild(el.firstChild);
5903 el.innerHTML = createHtml(o);
5906 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5910 * Creates a new Roo.DomHelper.Template from the Dom object spec
5911 * @param {Object} o The Dom object spec (and children)
5912 * @return {Roo.DomHelper.Template} The new template
5914 createTemplate : function(o){
5915 var html = createHtml(o);
5916 return new Roo.Template(html);
5919 * Updates the first element with the spec from the o (replacing if necessary)
5920 * This iterates through the children, and updates attributes / children etc..
5921 * @param {String/HTMLElement/Element} el The context element
5922 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5925 update : function(el, o)
5927 updateNode(Roo.getDom(el), createDom(o));
5936 * Ext JS Library 1.1.1
5937 * Copyright(c) 2006-2007, Ext JS, LLC.
5939 * Originally Released Under LGPL - original licence link has changed is not relivant.
5942 * <script type="text/javascript">
5946 * @class Roo.Template
5947 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
5948 * For a list of available format functions, see {@link Roo.util.Format}.<br />
5951 var t = new Roo.Template({
5952 html : '<div name="{id}">' +
5953 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
5955 myformat: function (value, allValues) {
5956 return 'XX' + value;
5959 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
5961 * For more information see this blog post with examples:
5962 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
5963 - Create Elements using DOM, HTML fragments and Templates</a>.
5965 * @param {Object} cfg - Configuration object.
5967 Roo.Template = function(cfg){
5969 if(cfg instanceof Array){
5971 }else if(arguments.length > 1){
5972 cfg = Array.prototype.join.call(arguments, "");
5976 if (typeof(cfg) == 'object') {
5987 Roo.Template.prototype = {
5990 * @cfg {Function} onLoad Called after the template has been loaded and complied (usually from a remove source)
5996 * @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..
5997 * it should be fixed so that template is observable...
6001 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
6009 * Returns an HTML fragment of this template with the specified values applied.
6010 * @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'})
6011 * @return {String} The HTML fragment
6016 applyTemplate : function(values){
6017 //Roo.log(["applyTemplate", values]);
6021 return this.compiled(values);
6023 var useF = this.disableFormats !== true;
6024 var fm = Roo.util.Format, tpl = this;
6025 var fn = function(m, name, format, args){
6027 if(format.substr(0, 5) == "this."){
6028 return tpl.call(format.substr(5), values[name], values);
6031 // quoted values are required for strings in compiled templates,
6032 // but for non compiled we need to strip them
6033 // quoted reversed for jsmin
6034 var re = /^\s*['"](.*)["']\s*$/;
6035 args = args.split(',');
6036 for(var i = 0, len = args.length; i < len; i++){
6037 args[i] = args[i].replace(re, "$1");
6039 args = [values[name]].concat(args);
6041 args = [values[name]];
6043 return fm[format].apply(fm, args);
6046 return values[name] !== undefined ? values[name] : "";
6049 return this.html.replace(this.re, fn);
6067 this.loading = true;
6068 this.compiled = false;
6070 var cx = new Roo.data.Connection();
6074 success : function (response) {
6078 _t.set(response.responseText,true);
6084 failure : function(response) {
6085 Roo.log("Template failed to load from " + _t.url);
6092 * Sets the HTML used as the template and optionally compiles it.
6093 * @param {String} html
6094 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
6095 * @return {Roo.Template} this
6097 set : function(html, compile){
6099 this.compiled = false;
6107 * True to disable format functions (defaults to false)
6110 disableFormats : false,
6113 * The regular expression used to match template variables
6117 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
6120 * Compiles the template into an internal function, eliminating the RegEx overhead.
6121 * @return {Roo.Template} this
6123 compile : function(){
6124 var fm = Roo.util.Format;
6125 var useF = this.disableFormats !== true;
6126 var sep = Roo.isGecko ? "+" : ",";
6127 var fn = function(m, name, format, args){
6129 args = args ? ',' + args : "";
6130 if(format.substr(0, 5) != "this."){
6131 format = "fm." + format + '(';
6133 format = 'this.call("'+ format.substr(5) + '", ';
6137 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
6139 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
6142 // branched to use + in gecko and [].join() in others
6144 body = "this.compiled = function(values){ return '" +
6145 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
6148 body = ["this.compiled = function(values){ return ['"];
6149 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
6150 body.push("'].join('');};");
6151 body = body.join('');
6161 // private function used to call members
6162 call : function(fnName, value, allValues){
6163 return this[fnName](value, allValues);
6167 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
6168 * @param {String/HTMLElement/Roo.Element} el The context element
6169 * @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'})
6170 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6171 * @return {HTMLElement/Roo.Element} The new node or Element
6173 insertFirst: function(el, values, returnElement){
6174 return this.doInsert('afterBegin', el, values, returnElement);
6178 * Applies the supplied values to the template and inserts the new node(s) before el.
6179 * @param {String/HTMLElement/Roo.Element} el The context element
6180 * @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'})
6181 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6182 * @return {HTMLElement/Roo.Element} The new node or Element
6184 insertBefore: function(el, values, returnElement){
6185 return this.doInsert('beforeBegin', el, values, returnElement);
6189 * Applies the supplied values to the template and inserts the new node(s) after el.
6190 * @param {String/HTMLElement/Roo.Element} el The context element
6191 * @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'})
6192 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6193 * @return {HTMLElement/Roo.Element} The new node or Element
6195 insertAfter : function(el, values, returnElement){
6196 return this.doInsert('afterEnd', el, values, returnElement);
6200 * Applies the supplied values to the template and appends the new node(s) to el.
6201 * @param {String/HTMLElement/Roo.Element} el The context element
6202 * @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'})
6203 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6204 * @return {HTMLElement/Roo.Element} The new node or Element
6206 append : function(el, values, returnElement){
6207 return this.doInsert('beforeEnd', el, values, returnElement);
6210 doInsert : function(where, el, values, returnEl){
6211 el = Roo.getDom(el);
6212 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
6213 return returnEl ? Roo.get(newNode, true) : newNode;
6217 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
6218 * @param {String/HTMLElement/Roo.Element} el The context element
6219 * @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'})
6220 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6221 * @return {HTMLElement/Roo.Element} The new node or Element
6223 overwrite : function(el, values, returnElement){
6224 el = Roo.getDom(el);
6225 el.innerHTML = this.applyTemplate(values);
6226 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
6230 * Alias for {@link #applyTemplate}
6233 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
6236 Roo.DomHelper.Template = Roo.Template;
6239 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
6240 * @param {String/HTMLElement} el A DOM element or its id
6241 * @returns {Roo.Template} The created template
6244 Roo.Template.from = function(el){
6245 el = Roo.getDom(el);
6246 return new Roo.Template(el.value || el.innerHTML);
6249 * Ext JS Library 1.1.1
6250 * Copyright(c) 2006-2007, Ext JS, LLC.
6252 * Originally Released Under LGPL - original licence link has changed is not relivant.
6255 * <script type="text/javascript">
6260 * This is code is also distributed under MIT license for use
6261 * with jQuery and prototype JavaScript libraries.
6264 * @class Roo.DomQuery
6265 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).
6267 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>
6270 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.
6272 <h4>Element Selectors:</h4>
6274 <li> <b>*</b> any element</li>
6275 <li> <b>E</b> an element with the tag E</li>
6276 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
6277 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
6278 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
6279 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
6281 <h4>Attribute Selectors:</h4>
6282 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
6284 <li> <b>E[foo]</b> has an attribute "foo"</li>
6285 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
6286 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
6287 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
6288 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
6289 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
6290 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
6292 <h4>Pseudo Classes:</h4>
6294 <li> <b>E:first-child</b> E is the first child of its parent</li>
6295 <li> <b>E:last-child</b> E is the last child of its parent</li>
6296 <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>
6297 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
6298 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
6299 <li> <b>E:only-child</b> E is the only child of its parent</li>
6300 <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>
6301 <li> <b>E:first</b> the first E in the resultset</li>
6302 <li> <b>E:last</b> the last E in the resultset</li>
6303 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
6304 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
6305 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
6306 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
6307 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
6308 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
6309 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
6310 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
6311 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
6313 <h4>CSS Value Selectors:</h4>
6315 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
6316 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
6317 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
6318 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
6319 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
6320 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
6324 Roo.DomQuery = function(){
6325 var cache = {}, simpleCache = {}, valueCache = {};
6326 var nonSpace = /\S/;
6327 var trimRe = /^\s+|\s+$/g;
6328 var tplRe = /\{(\d+)\}/g;
6329 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
6330 var tagTokenRe = /^(#)?([\w-\*]+)/;
6331 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
6333 function child(p, index){
6335 var n = p.firstChild;
6337 if(n.nodeType == 1){
6348 while((n = n.nextSibling) && n.nodeType != 1);
6353 while((n = n.previousSibling) && n.nodeType != 1);
6357 function children(d){
6358 var n = d.firstChild, ni = -1;
6360 var nx = n.nextSibling;
6361 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
6371 function byClassName(c, a, v){
6375 var r = [], ri = -1, cn;
6376 for(var i = 0, ci; ci = c[i]; i++){
6380 ( (ci instanceof SVGElement) ? ci.className.baseVal : ci.className)
6381 +' ').indexOf(v) != -1){
6388 function attrValue(n, attr){
6389 if(!n.tagName && typeof n.length != "undefined"){
6398 if(attr == "class" || attr == "className"){
6399 return (n instanceof SVGElement) ? n.className.baseVal : n.className;
6401 return n.getAttribute(attr) || n[attr];
6405 function getNodes(ns, mode, tagName){
6406 var result = [], ri = -1, cs;
6410 tagName = tagName || "*";
6411 if(typeof ns.getElementsByTagName != "undefined"){
6415 for(var i = 0, ni; ni = ns[i]; i++){
6416 cs = ni.getElementsByTagName(tagName);
6417 for(var j = 0, ci; ci = cs[j]; j++){
6421 }else if(mode == "/" || mode == ">"){
6422 var utag = tagName.toUpperCase();
6423 for(var i = 0, ni, cn; ni = ns[i]; i++){
6424 cn = ni.children || ni.childNodes;
6425 for(var j = 0, cj; cj = cn[j]; j++){
6426 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
6431 }else if(mode == "+"){
6432 var utag = tagName.toUpperCase();
6433 for(var i = 0, n; n = ns[i]; i++){
6434 while((n = n.nextSibling) && n.nodeType != 1);
6435 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
6439 }else if(mode == "~"){
6440 for(var i = 0, n; n = ns[i]; i++){
6441 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
6450 function concat(a, b){
6454 for(var i = 0, l = b.length; i < l; i++){
6460 function byTag(cs, tagName){
6461 if(cs.tagName || cs == document){
6467 var r = [], ri = -1;
6468 tagName = tagName.toLowerCase();
6469 for(var i = 0, ci; ci = cs[i]; i++){
6470 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
6477 function byId(cs, attr, id){
6478 if(cs.tagName || cs == document){
6484 var r = [], ri = -1;
6485 for(var i = 0,ci; ci = cs[i]; i++){
6486 if(ci && ci.id == id){
6494 function byAttribute(cs, attr, value, op, custom){
6495 var r = [], ri = -1, st = custom=="{";
6496 var f = Roo.DomQuery.operators[op];
6497 for(var i = 0, ci; ci = cs[i]; i++){
6500 a = Roo.DomQuery.getStyle(ci, attr);
6502 else if(attr == "class" || attr == "className"){
6503 a = (ci instanceof SVGElement) ? ci.className.baseVal : ci.className;
6504 }else if(attr == "for"){
6506 }else if(attr == "href"){
6507 a = ci.getAttribute("href", 2);
6509 a = ci.getAttribute(attr);
6511 if((f && f(a, value)) || (!f && a)){
6518 function byPseudo(cs, name, value){
6519 return Roo.DomQuery.pseudos[name](cs, value);
6522 // This is for IE MSXML which does not support expandos.
6523 // IE runs the same speed using setAttribute, however FF slows way down
6524 // and Safari completely fails so they need to continue to use expandos.
6525 var isIE = window.ActiveXObject ? true : false;
6527 // this eval is stop the compressor from
6528 // renaming the variable to something shorter
6530 /** eval:var:batch */
6535 function nodupIEXml(cs){
6537 cs[0].setAttribute("_nodup", d);
6539 for(var i = 1, len = cs.length; i < len; i++){
6541 if(!c.getAttribute("_nodup") != d){
6542 c.setAttribute("_nodup", d);
6546 for(var i = 0, len = cs.length; i < len; i++){
6547 cs[i].removeAttribute("_nodup");
6556 var len = cs.length, c, i, r = cs, cj, ri = -1;
6557 if(!len || typeof cs.nodeType != "undefined" || len == 1){
6560 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
6561 return nodupIEXml(cs);
6565 for(i = 1; c = cs[i]; i++){
6570 for(var j = 0; j < i; j++){
6573 for(j = i+1; cj = cs[j]; j++){
6585 function quickDiffIEXml(c1, c2){
6587 for(var i = 0, len = c1.length; i < len; i++){
6588 c1[i].setAttribute("_qdiff", d);
6591 for(var i = 0, len = c2.length; i < len; i++){
6592 if(c2[i].getAttribute("_qdiff") != d){
6593 r[r.length] = c2[i];
6596 for(var i = 0, len = c1.length; i < len; i++){
6597 c1[i].removeAttribute("_qdiff");
6602 function quickDiff(c1, c2){
6603 var len1 = c1.length;
6607 if(isIE && c1[0].selectSingleNode){
6608 return quickDiffIEXml(c1, c2);
6611 for(var i = 0; i < len1; i++){
6615 for(var i = 0, len = c2.length; i < len; i++){
6616 if(c2[i]._qdiff != d){
6617 r[r.length] = c2[i];
6623 function quickId(ns, mode, root, id){
6625 var d = root.ownerDocument || root;
6626 return d.getElementById(id);
6628 ns = getNodes(ns, mode, "*");
6629 return byId(ns, null, id);
6633 getStyle : function(el, name){
6634 return Roo.fly(el).getStyle(name);
6637 * Compiles a selector/xpath query into a reusable function. The returned function
6638 * takes one parameter "root" (optional), which is the context node from where the query should start.
6639 * @param {String} selector The selector/xpath query
6640 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
6641 * @return {Function}
6643 compile : function(path, type){
6644 type = type || "select";
6646 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
6647 var q = path, mode, lq;
6648 var tk = Roo.DomQuery.matchers;
6649 var tklen = tk.length;
6652 // accept leading mode switch
6653 var lmode = q.match(modeRe);
6654 if(lmode && lmode[1]){
6655 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
6656 q = q.replace(lmode[1], "");
6658 // strip leading slashes
6659 while(path.substr(0, 1)=="/"){
6660 path = path.substr(1);
6663 while(q && lq != q){
6665 var tm = q.match(tagTokenRe);
6666 if(type == "select"){
6669 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
6671 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
6673 q = q.replace(tm[0], "");
6674 }else if(q.substr(0, 1) != '@'){
6675 fn[fn.length] = 'n = getNodes(n, mode, "*");';
6680 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
6682 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
6684 q = q.replace(tm[0], "");
6687 while(!(mm = q.match(modeRe))){
6688 var matched = false;
6689 for(var j = 0; j < tklen; j++){
6691 var m = q.match(t.re);
6693 fn[fn.length] = t.select.replace(tplRe, function(x, i){
6696 q = q.replace(m[0], "");
6701 // prevent infinite loop on bad selector
6703 throw 'Error parsing selector, parsing failed at "' + q + '"';
6707 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
6708 q = q.replace(mm[1], "");
6711 fn[fn.length] = "return nodup(n);\n}";
6714 * list of variables that need from compression as they are used by eval.
6724 * eval:var:byClassName
6726 * eval:var:byAttribute
6727 * eval:var:attrValue
6735 * Selects a group of elements.
6736 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
6737 * @param {Node} root (optional) The start of the query (defaults to document).
6740 select : function(path, root, type){
6741 if(!root || root == document){
6744 if(typeof root == "string"){
6745 root = document.getElementById(root);
6747 var paths = path.split(",");
6749 for(var i = 0, len = paths.length; i < len; i++){
6750 var p = paths[i].replace(trimRe, "");
6752 cache[p] = Roo.DomQuery.compile(p);
6754 throw p + " is not a valid selector";
6757 var result = cache[p](root);
6758 if(result && result != document){
6759 results = results.concat(result);
6762 if(paths.length > 1){
6763 return nodup(results);
6769 * Selects a single element.
6770 * @param {String} selector The selector/xpath query
6771 * @param {Node} root (optional) The start of the query (defaults to document).
6774 selectNode : function(path, root){
6775 return Roo.DomQuery.select(path, root)[0];
6779 * Selects the value of a node, optionally replacing null with the defaultValue.
6780 * @param {String} selector The selector/xpath query
6781 * @param {Node} root (optional) The start of the query (defaults to document).
6782 * @param {String} defaultValue
6784 selectValue : function(path, root, defaultValue){
6785 path = path.replace(trimRe, "");
6786 if(!valueCache[path]){
6787 valueCache[path] = Roo.DomQuery.compile(path, "select");
6789 var n = valueCache[path](root);
6790 n = n[0] ? n[0] : n;
6791 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
6792 return ((v === null||v === undefined||v==='') ? defaultValue : v);
6796 * Selects the value of a node, parsing integers and floats.
6797 * @param {String} selector The selector/xpath query
6798 * @param {Node} root (optional) The start of the query (defaults to document).
6799 * @param {Number} defaultValue
6802 selectNumber : function(path, root, defaultValue){
6803 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
6804 return parseFloat(v);
6808 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
6809 * @param {String/HTMLElement/Array} el An element id, element or array of elements
6810 * @param {String} selector The simple selector to test
6813 is : function(el, ss){
6814 if(typeof el == "string"){
6815 el = document.getElementById(el);
6817 var isArray = (el instanceof Array);
6818 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
6819 return isArray ? (result.length == el.length) : (result.length > 0);
6823 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
6824 * @param {Array} el An array of elements to filter
6825 * @param {String} selector The simple selector to test
6826 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
6827 * the selector instead of the ones that match
6830 filter : function(els, ss, nonMatches){
6831 ss = ss.replace(trimRe, "");
6832 if(!simpleCache[ss]){
6833 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
6835 var result = simpleCache[ss](els);
6836 return nonMatches ? quickDiff(result, els) : result;
6840 * Collection of matching regular expressions and code snippets.
6844 select: 'n = byClassName(n, null, " {1} ");'
6846 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
6847 select: 'n = byPseudo(n, "{1}", "{2}");'
6849 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
6850 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
6853 select: 'n = byId(n, null, "{1}");'
6856 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
6861 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
6862 * 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, > <.
6865 "=" : function(a, v){
6868 "!=" : function(a, v){
6871 "^=" : function(a, v){
6872 return a && a.substr(0, v.length) == v;
6874 "$=" : function(a, v){
6875 return a && a.substr(a.length-v.length) == v;
6877 "*=" : function(a, v){
6878 return a && a.indexOf(v) !== -1;
6880 "%=" : function(a, v){
6881 return (a % v) == 0;
6883 "|=" : function(a, v){
6884 return a && (a == v || a.substr(0, v.length+1) == v+'-');
6886 "~=" : function(a, v){
6887 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
6892 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
6893 * and the argument (if any) supplied in the selector.
6896 "first-child" : function(c){
6897 var r = [], ri = -1, n;
6898 for(var i = 0, ci; ci = n = c[i]; i++){
6899 while((n = n.previousSibling) && n.nodeType != 1);
6907 "last-child" : function(c){
6908 var r = [], ri = -1, n;
6909 for(var i = 0, ci; ci = n = c[i]; i++){
6910 while((n = n.nextSibling) && n.nodeType != 1);
6918 "nth-child" : function(c, a) {
6919 var r = [], ri = -1;
6920 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
6921 var f = (m[1] || 1) - 0, l = m[2] - 0;
6922 for(var i = 0, n; n = c[i]; i++){
6923 var pn = n.parentNode;
6924 if (batch != pn._batch) {
6926 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
6927 if(cn.nodeType == 1){
6934 if (l == 0 || n.nodeIndex == l){
6937 } else if ((n.nodeIndex + l) % f == 0){
6945 "only-child" : function(c){
6946 var r = [], ri = -1;;
6947 for(var i = 0, ci; ci = c[i]; i++){
6948 if(!prev(ci) && !next(ci)){
6955 "empty" : function(c){
6956 var r = [], ri = -1;
6957 for(var i = 0, ci; ci = c[i]; i++){
6958 var cns = ci.childNodes, j = 0, cn, empty = true;
6961 if(cn.nodeType == 1 || cn.nodeType == 3){
6973 "contains" : function(c, v){
6974 var r = [], ri = -1;
6975 for(var i = 0, ci; ci = c[i]; i++){
6976 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
6983 "nodeValue" : function(c, v){
6984 var r = [], ri = -1;
6985 for(var i = 0, ci; ci = c[i]; i++){
6986 if(ci.firstChild && ci.firstChild.nodeValue == v){
6993 "checked" : function(c){
6994 var r = [], ri = -1;
6995 for(var i = 0, ci; ci = c[i]; i++){
6996 if(ci.checked == true){
7003 "not" : function(c, ss){
7004 return Roo.DomQuery.filter(c, ss, true);
7007 "odd" : function(c){
7008 return this["nth-child"](c, "odd");
7011 "even" : function(c){
7012 return this["nth-child"](c, "even");
7015 "nth" : function(c, a){
7016 return c[a-1] || [];
7019 "first" : function(c){
7023 "last" : function(c){
7024 return c[c.length-1] || [];
7027 "has" : function(c, ss){
7028 var s = Roo.DomQuery.select;
7029 var r = [], ri = -1;
7030 for(var i = 0, ci; ci = c[i]; i++){
7031 if(s(ss, ci).length > 0){
7038 "next" : function(c, ss){
7039 var is = Roo.DomQuery.is;
7040 var r = [], ri = -1;
7041 for(var i = 0, ci; ci = c[i]; i++){
7050 "prev" : function(c, ss){
7051 var is = Roo.DomQuery.is;
7052 var r = [], ri = -1;
7053 for(var i = 0, ci; ci = c[i]; i++){
7066 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
7067 * @param {String} path The selector/xpath query
7068 * @param {Node} root (optional) The start of the query (defaults to document).
7073 Roo.query = Roo.DomQuery.select;
7076 * Ext JS Library 1.1.1
7077 * Copyright(c) 2006-2007, Ext JS, LLC.
7079 * Originally Released Under LGPL - original licence link has changed is not relivant.
7082 * <script type="text/javascript">
7086 * @class Roo.util.Observable
7087 * Base class that provides a common interface for publishing events. Subclasses are expected to
7088 * to have a property "events" with all the events defined.<br>
7091 Employee = function(name){
7098 Roo.extend(Employee, Roo.util.Observable);
7100 * @param {Object} config properties to use (incuding events / listeners)
7103 Roo.util.Observable = function(cfg){
7106 this.addEvents(cfg.events || {});
7108 delete cfg.events; // make sure
7111 Roo.apply(this, cfg);
7114 this.on(this.listeners);
7115 delete this.listeners;
7118 Roo.util.Observable.prototype = {
7120 * @cfg {Object} listeners list of events and functions to call for this object,
7124 'click' : function(e) {
7134 * Fires the specified event with the passed parameters (minus the event name).
7135 * @param {String} eventName
7136 * @param {Object...} args Variable number of parameters are passed to handlers
7137 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
7139 fireEvent : function(){
7140 var ce = this.events[arguments[0].toLowerCase()];
7141 if(typeof ce == "object"){
7142 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
7149 filterOptRe : /^(?:scope|delay|buffer|single)$/,
7152 * Appends an event handler to this component
7153 * @param {String} eventName The type of event to listen for
7154 * @param {Function} handler The method the event invokes
7155 * @param {Object} scope (optional) The scope in which to execute the handler
7156 * function. The handler function's "this" context.
7157 * @param {Object} options (optional) An object containing handler configuration
7158 * properties. This may contain any of the following properties:<ul>
7159 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7160 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7161 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7162 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7163 * by the specified number of milliseconds. If the event fires again within that time, the original
7164 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7167 * <b>Combining Options</b><br>
7168 * Using the options argument, it is possible to combine different types of listeners:<br>
7170 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
7172 el.on('click', this.onClick, this, {
7179 * <b>Attaching multiple handlers in 1 call</b><br>
7180 * The method also allows for a single argument to be passed which is a config object containing properties
7181 * which specify multiple handlers.
7190 fn: this.onMouseOver,
7194 fn: this.onMouseOut,
7200 * Or a shorthand syntax which passes the same scope object to all handlers:
7203 'click': this.onClick,
7204 'mouseover': this.onMouseOver,
7205 'mouseout': this.onMouseOut,
7210 addListener : function(eventName, fn, scope, o){
7211 if(typeof eventName == "object"){
7214 if(this.filterOptRe.test(e)){
7217 if(typeof o[e] == "function"){
7219 this.addListener(e, o[e], o.scope, o);
7221 // individual options
7222 this.addListener(e, o[e].fn, o[e].scope, o[e]);
7227 o = (!o || typeof o == "boolean") ? {} : o;
7228 eventName = eventName.toLowerCase();
7229 var ce = this.events[eventName] || true;
7230 if(typeof ce == "boolean"){
7231 ce = new Roo.util.Event(this, eventName);
7232 this.events[eventName] = ce;
7234 ce.addListener(fn, scope, o);
7238 * Removes a listener
7239 * @param {String} eventName The type of event to listen for
7240 * @param {Function} handler The handler to remove
7241 * @param {Object} scope (optional) The scope (this object) for the handler
7243 removeListener : function(eventName, fn, scope){
7244 var ce = this.events[eventName.toLowerCase()];
7245 if(typeof ce == "object"){
7246 ce.removeListener(fn, scope);
7251 * Removes all listeners for this object
7253 purgeListeners : function(){
7254 for(var evt in this.events){
7255 if(typeof this.events[evt] == "object"){
7256 this.events[evt].clearListeners();
7261 relayEvents : function(o, events){
7262 var createHandler = function(ename){
7265 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
7268 for(var i = 0, len = events.length; i < len; i++){
7269 var ename = events[i];
7270 if(!this.events[ename]){
7271 this.events[ename] = true;
7273 o.on(ename, createHandler(ename), this);
7278 * Used to define events on this Observable
7279 * @param {Object} object The object with the events defined
7281 addEvents : function(o){
7285 Roo.applyIf(this.events, o);
7289 * Checks to see if this object has any listeners for a specified event
7290 * @param {String} eventName The name of the event to check for
7291 * @return {Boolean} True if the event is being listened for, else false
7293 hasListener : function(eventName){
7294 var e = this.events[eventName];
7295 return typeof e == "object" && e.listeners.length > 0;
7299 * Appends an event handler to this element (shorthand for addListener)
7300 * @param {String} eventName The type of event to listen for
7301 * @param {Function} handler The method the event invokes
7302 * @param {Object} scope (optional) The scope in which to execute the handler
7303 * function. The handler function's "this" context.
7304 * @param {Object} options (optional)
7307 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
7309 * Removes a listener (shorthand for removeListener)
7310 * @param {String} eventName The type of event to listen for
7311 * @param {Function} handler The handler to remove
7312 * @param {Object} scope (optional) The scope (this object) for the handler
7315 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
7318 * Starts capture on the specified Observable. All events will be passed
7319 * to the supplied function with the event name + standard signature of the event
7320 * <b>before</b> the event is fired. If the supplied function returns false,
7321 * the event will not fire.
7322 * @param {Observable} o The Observable to capture
7323 * @param {Function} fn The function to call
7324 * @param {Object} scope (optional) The scope (this object) for the fn
7327 Roo.util.Observable.capture = function(o, fn, scope){
7328 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
7332 * Removes <b>all</b> added captures from the Observable.
7333 * @param {Observable} o The Observable to release
7336 Roo.util.Observable.releaseCapture = function(o){
7337 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
7342 var createBuffered = function(h, o, scope){
7343 var task = new Roo.util.DelayedTask();
7345 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
7349 var createSingle = function(h, e, fn, scope){
7351 e.removeListener(fn, scope);
7352 return h.apply(scope, arguments);
7356 var createDelayed = function(h, o, scope){
7358 var args = Array.prototype.slice.call(arguments, 0);
7359 setTimeout(function(){
7360 h.apply(scope, args);
7365 Roo.util.Event = function(obj, name){
7368 this.listeners = [];
7371 Roo.util.Event.prototype = {
7372 addListener : function(fn, scope, options){
7373 var o = options || {};
7374 scope = scope || this.obj;
7375 if(!this.isListening(fn, scope)){
7376 var l = {fn: fn, scope: scope, options: o};
7379 h = createDelayed(h, o, scope);
7382 h = createSingle(h, this, fn, scope);
7385 h = createBuffered(h, o, scope);
7388 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
7389 this.listeners.push(l);
7391 this.listeners = this.listeners.slice(0);
7392 this.listeners.push(l);
7397 findListener : function(fn, scope){
7398 scope = scope || this.obj;
7399 var ls = this.listeners;
7400 for(var i = 0, len = ls.length; i < len; i++){
7402 if(l.fn == fn && l.scope == scope){
7409 isListening : function(fn, scope){
7410 return this.findListener(fn, scope) != -1;
7413 removeListener : function(fn, scope){
7415 if((index = this.findListener(fn, scope)) != -1){
7417 this.listeners.splice(index, 1);
7419 this.listeners = this.listeners.slice(0);
7420 this.listeners.splice(index, 1);
7427 clearListeners : function(){
7428 this.listeners = [];
7432 var ls = this.listeners, scope, len = ls.length;
7435 var args = Array.prototype.slice.call(arguments, 0);
7436 for(var i = 0; i < len; i++){
7438 if(l.fireFn.apply(l.scope||this.obj||window, args) === false){
7439 this.firing = false;
7443 this.firing = false;
7450 * Copyright(c) 2007-2017, Roo J Solutions Ltd
7457 * @class Roo.Document
7458 * @extends Roo.util.Observable
7459 * This is a convience class to wrap up the main document loading code.. , rather than adding Roo.onReady(......)
7461 * @param {Object} config the methods and properties of the 'base' class for the application.
7463 * Generic Page handler - implement this to start your app..
7466 * MyProject = new Roo.Document({
7468 'load' : true // your events..
7471 'ready' : function() {
7472 // fired on Roo.onReady()
7477 Roo.Document = function(cfg) {
7482 Roo.util.Observable.call(this,cfg);
7486 Roo.onReady(function() {
7487 _this.fireEvent('ready');
7493 Roo.extend(Roo.Document, Roo.util.Observable, {});/*
7495 * Ext JS Library 1.1.1
7496 * Copyright(c) 2006-2007, Ext JS, LLC.
7498 * Originally Released Under LGPL - original licence link has changed is not relivant.
7501 * <script type="text/javascript">
7505 * @class Roo.EventManager
7506 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
7507 * several useful events directly.
7508 * See {@link Roo.EventObject} for more details on normalized event objects.
7511 Roo.EventManager = function(){
7512 var docReadyEvent, docReadyProcId, docReadyState = false;
7513 var resizeEvent, resizeTask, textEvent, textSize;
7514 var E = Roo.lib.Event;
7515 var D = Roo.lib.Dom;
7520 var fireDocReady = function(){
7522 docReadyState = true;
7525 clearInterval(docReadyProcId);
7527 if(Roo.isGecko || Roo.isOpera) {
7528 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
7531 var defer = document.getElementById("ie-deferred-loader");
7533 defer.onreadystatechange = null;
7534 defer.parentNode.removeChild(defer);
7538 docReadyEvent.fire();
7539 docReadyEvent.clearListeners();
7544 var initDocReady = function(){
7545 docReadyEvent = new Roo.util.Event();
7546 if(Roo.isGecko || Roo.isOpera) {
7547 document.addEventListener("DOMContentLoaded", fireDocReady, false);
7549 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
7550 var defer = document.getElementById("ie-deferred-loader");
7551 defer.onreadystatechange = function(){
7552 if(this.readyState == "complete"){
7556 }else if(Roo.isSafari){
7557 docReadyProcId = setInterval(function(){
7558 var rs = document.readyState;
7559 if(rs == "complete") {
7564 // no matter what, make sure it fires on load
7565 E.on(window, "load", fireDocReady);
7568 var createBuffered = function(h, o){
7569 var task = new Roo.util.DelayedTask(h);
7571 // create new event object impl so new events don't wipe out properties
7572 e = new Roo.EventObjectImpl(e);
7573 task.delay(o.buffer, h, null, [e]);
7577 var createSingle = function(h, el, ename, fn){
7579 Roo.EventManager.removeListener(el, ename, fn);
7584 var createDelayed = function(h, o){
7586 // create new event object impl so new events don't wipe out properties
7587 e = new Roo.EventObjectImpl(e);
7588 setTimeout(function(){
7593 var transitionEndVal = false;
7595 var transitionEnd = function()
7597 if (transitionEndVal) {
7598 return transitionEndVal;
7600 var el = document.createElement('div');
7602 var transEndEventNames = {
7603 WebkitTransition : 'webkitTransitionEnd',
7604 MozTransition : 'transitionend',
7605 OTransition : 'oTransitionEnd otransitionend',
7606 transition : 'transitionend'
7609 for (var name in transEndEventNames) {
7610 if (el.style[name] !== undefined) {
7611 transitionEndVal = transEndEventNames[name];
7612 return transitionEndVal ;
7619 var listen = function(element, ename, opt, fn, scope)
7621 var o = (!opt || typeof opt == "boolean") ? {} : opt;
7622 fn = fn || o.fn; scope = scope || o.scope;
7623 var el = Roo.getDom(element);
7627 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
7630 if (ename == 'transitionend') {
7631 ename = transitionEnd();
7633 var h = function(e){
7634 e = Roo.EventObject.setEvent(e);
7637 t = e.getTarget(o.delegate, el);
7644 if(o.stopEvent === true){
7647 if(o.preventDefault === true){
7650 if(o.stopPropagation === true){
7651 e.stopPropagation();
7654 if(o.normalized === false){
7658 fn.call(scope || el, e, t, o);
7661 h = createDelayed(h, o);
7664 h = createSingle(h, el, ename, fn);
7667 h = createBuffered(h, o);
7670 fn._handlers = fn._handlers || [];
7673 fn._handlers.push([Roo.id(el), ename, h]);
7677 E.on(el, ename, h); // this adds the actuall listener to the object..
7680 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
7681 el.addEventListener("DOMMouseScroll", h, false);
7682 E.on(window, 'unload', function(){
7683 el.removeEventListener("DOMMouseScroll", h, false);
7686 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7687 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
7692 var stopListening = function(el, ename, fn){
7693 var id = Roo.id(el), hds = fn._handlers, hd = fn;
7695 for(var i = 0, len = hds.length; i < len; i++){
7697 if(h[0] == id && h[1] == ename){
7704 E.un(el, ename, hd);
7705 el = Roo.getDom(el);
7706 if(ename == "mousewheel" && el.addEventListener){
7707 el.removeEventListener("DOMMouseScroll", hd, false);
7709 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7710 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
7714 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
7721 * @scope Roo.EventManager
7726 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
7727 * object with a Roo.EventObject
7728 * @param {Function} fn The method the event invokes
7729 * @param {Object} scope An object that becomes the scope of the handler
7730 * @param {boolean} override If true, the obj passed in becomes
7731 * the execution scope of the listener
7732 * @return {Function} The wrapped function
7735 wrap : function(fn, scope, override){
7737 Roo.EventObject.setEvent(e);
7738 fn.call(override ? scope || window : window, Roo.EventObject, scope);
7743 * Appends an event handler to an element (shorthand for addListener)
7744 * @param {String/HTMLElement} element The html element or id to assign the
7745 * @param {String} eventName The type of event to listen for
7746 * @param {Function} handler The method the event invokes
7747 * @param {Object} scope (optional) The scope in which to execute the handler
7748 * function. The handler function's "this" context.
7749 * @param {Object} options (optional) An object containing handler configuration
7750 * properties. This may contain any of the following properties:<ul>
7751 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7752 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7753 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7754 * <li>preventDefault {Boolean} True to prevent the default action</li>
7755 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7756 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7757 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7758 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7759 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7760 * by the specified number of milliseconds. If the event fires again within that time, the original
7761 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7764 * <b>Combining Options</b><br>
7765 * Using the options argument, it is possible to combine different types of listeners:<br>
7767 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7769 el.on('click', this.onClick, this, {
7776 * <b>Attaching multiple handlers in 1 call</b><br>
7777 * The method also allows for a single argument to be passed which is a config object containing properties
7778 * which specify multiple handlers.
7788 fn: this.onMouseOver
7797 * Or a shorthand syntax:<br>
7800 'click' : this.onClick,
7801 'mouseover' : this.onMouseOver,
7802 'mouseout' : this.onMouseOut
7806 addListener : function(element, eventName, fn, scope, options){
7807 if(typeof eventName == "object"){
7813 if(typeof o[e] == "function"){
7815 listen(element, e, o, o[e], o.scope);
7817 // individual options
7818 listen(element, e, o[e]);
7823 return listen(element, eventName, options, fn, scope);
7827 * Removes an event handler
7829 * @param {String/HTMLElement} element The id or html element to remove the
7831 * @param {String} eventName The type of event
7832 * @param {Function} fn
7833 * @return {Boolean} True if a listener was actually removed
7835 removeListener : function(element, eventName, fn){
7836 return stopListening(element, eventName, fn);
7840 * Fires when the document is ready (before onload and before images are loaded). Can be
7841 * accessed shorthanded Roo.onReady().
7842 * @param {Function} fn The method the event invokes
7843 * @param {Object} scope An object that becomes the scope of the handler
7844 * @param {boolean} options
7846 onDocumentReady : function(fn, scope, options){
7847 if(docReadyState){ // if it already fired
7848 docReadyEvent.addListener(fn, scope, options);
7849 docReadyEvent.fire();
7850 docReadyEvent.clearListeners();
7856 docReadyEvent.addListener(fn, scope, options);
7860 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
7861 * @param {Function} fn The method the event invokes
7862 * @param {Object} scope An object that becomes the scope of the handler
7863 * @param {boolean} options
7865 onWindowResize : function(fn, scope, options)
7868 resizeEvent = new Roo.util.Event();
7869 resizeTask = new Roo.util.DelayedTask(function(){
7870 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7872 E.on(window, "resize", function()
7875 resizeTask.delay(50);
7877 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7881 resizeEvent.addListener(fn, scope, options);
7885 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
7886 * @param {Function} fn The method the event invokes
7887 * @param {Object} scope An object that becomes the scope of the handler
7888 * @param {boolean} options
7890 onTextResize : function(fn, scope, options){
7892 textEvent = new Roo.util.Event();
7893 var textEl = new Roo.Element(document.createElement('div'));
7894 textEl.dom.className = 'x-text-resize';
7895 textEl.dom.innerHTML = 'X';
7896 textEl.appendTo(document.body);
7897 textSize = textEl.dom.offsetHeight;
7898 setInterval(function(){
7899 if(textEl.dom.offsetHeight != textSize){
7900 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
7902 }, this.textResizeInterval);
7904 textEvent.addListener(fn, scope, options);
7908 * Removes the passed window resize listener.
7909 * @param {Function} fn The method the event invokes
7910 * @param {Object} scope The scope of handler
7912 removeResizeListener : function(fn, scope){
7914 resizeEvent.removeListener(fn, scope);
7919 fireResize : function(){
7921 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7925 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
7929 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
7931 textResizeInterval : 50
7936 * @scopeAlias pub=Roo.EventManager
7940 * Appends an event handler to an element (shorthand for addListener)
7941 * @param {String/HTMLElement} element The html element or id to assign the
7942 * @param {String} eventName The type of event to listen for
7943 * @param {Function} handler The method the event invokes
7944 * @param {Object} scope (optional) The scope in which to execute the handler
7945 * function. The handler function's "this" context.
7946 * @param {Object} options (optional) An object containing handler configuration
7947 * properties. This may contain any of the following properties:<ul>
7948 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7949 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7950 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7951 * <li>preventDefault {Boolean} True to prevent the default action</li>
7952 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7953 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7954 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7955 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7956 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7957 * by the specified number of milliseconds. If the event fires again within that time, the original
7958 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7961 * <b>Combining Options</b><br>
7962 * Using the options argument, it is possible to combine different types of listeners:<br>
7964 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7966 el.on('click', this.onClick, this, {
7973 * <b>Attaching multiple handlers in 1 call</b><br>
7974 * The method also allows for a single argument to be passed which is a config object containing properties
7975 * which specify multiple handlers.
7985 fn: this.onMouseOver
7994 * Or a shorthand syntax:<br>
7997 'click' : this.onClick,
7998 'mouseover' : this.onMouseOver,
7999 'mouseout' : this.onMouseOut
8003 pub.on = pub.addListener;
8004 pub.un = pub.removeListener;
8006 pub.stoppedMouseDownEvent = new Roo.util.Event();
8010 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
8011 * @param {Function} fn The method the event invokes
8012 * @param {Object} scope An object that becomes the scope of the handler
8013 * @param {boolean} override If true, the obj passed in becomes
8014 * the execution scope of the listener
8018 Roo.onReady = Roo.EventManager.onDocumentReady;
8020 Roo.onReady(function(){
8021 var bd = Roo.get(document.body);
8026 : Roo.isIE11 ? "roo-ie11"
8027 : Roo.isEdge ? "roo-edge"
8028 : Roo.isGecko ? "roo-gecko"
8029 : Roo.isOpera ? "roo-opera"
8030 : Roo.isSafari ? "roo-safari" : ""];
8033 cls.push("roo-mac");
8036 cls.push("roo-linux");
8039 cls.push("roo-ios");
8042 cls.push("roo-touch");
8044 if(Roo.isBorderBox){
8045 cls.push('roo-border-box');
8047 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
8048 var p = bd.dom.parentNode;
8050 p.className += ' roo-strict';
8053 bd.addClass(cls.join(' '));
8057 * @class Roo.EventObject
8058 * EventObject exposes the Yahoo! UI Event functionality directly on the object
8059 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
8062 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
8064 var target = e.getTarget();
8067 var myDiv = Roo.get("myDiv");
8068 myDiv.on("click", handleClick);
8070 Roo.EventManager.on("myDiv", 'click', handleClick);
8071 Roo.EventManager.addListener("myDiv", 'click', handleClick);
8075 Roo.EventObject = function(){
8077 var E = Roo.lib.Event;
8079 // safari keypress events for special keys return bad keycodes
8082 63235 : 39, // right
8085 63276 : 33, // page up
8086 63277 : 34, // page down
8087 63272 : 46, // delete
8092 // normalize button clicks
8093 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
8094 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
8096 Roo.EventObjectImpl = function(e){
8098 this.setEvent(e.browserEvent || e);
8101 Roo.EventObjectImpl.prototype = {
8103 * Used to fix doc tools.
8104 * @scope Roo.EventObject.prototype
8110 /** The normal browser event */
8111 browserEvent : null,
8112 /** The button pressed in a mouse event */
8114 /** True if the shift key was down during the event */
8116 /** True if the control key was down during the event */
8118 /** True if the alt key was down during the event */
8177 setEvent : function(e){
8178 if(e == this || (e && e.browserEvent)){ // already wrapped
8181 this.browserEvent = e;
8183 // normalize buttons
8184 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
8185 if(e.type == 'click' && this.button == -1){
8189 this.shiftKey = e.shiftKey;
8190 // mac metaKey behaves like ctrlKey
8191 this.ctrlKey = e.ctrlKey || e.metaKey;
8192 this.altKey = e.altKey;
8193 // in getKey these will be normalized for the mac
8194 this.keyCode = e.keyCode;
8195 // keyup warnings on firefox.
8196 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
8197 // cache the target for the delayed and or buffered events
8198 this.target = E.getTarget(e);
8200 this.xy = E.getXY(e);
8203 this.shiftKey = false;
8204 this.ctrlKey = false;
8205 this.altKey = false;
8215 * Stop the event (preventDefault and stopPropagation)
8217 stopEvent : function(){
8218 if(this.browserEvent){
8219 if(this.browserEvent.type == 'mousedown'){
8220 Roo.EventManager.stoppedMouseDownEvent.fire(this);
8222 E.stopEvent(this.browserEvent);
8227 * Prevents the browsers default handling of the event.
8229 preventDefault : function(){
8230 if(this.browserEvent){
8231 E.preventDefault(this.browserEvent);
8236 isNavKeyPress : function(){
8237 var k = this.keyCode;
8238 k = Roo.isSafari ? (safariKeys[k] || k) : k;
8239 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
8242 isSpecialKey : function(){
8243 var k = this.keyCode;
8244 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
8245 (k == 16) || (k == 17) ||
8246 (k >= 18 && k <= 20) ||
8247 (k >= 33 && k <= 35) ||
8248 (k >= 36 && k <= 39) ||
8249 (k >= 44 && k <= 45);
8252 * Cancels bubbling of the event.
8254 stopPropagation : function(){
8255 if(this.browserEvent){
8256 if(this.type == 'mousedown'){
8257 Roo.EventManager.stoppedMouseDownEvent.fire(this);
8259 E.stopPropagation(this.browserEvent);
8264 * Gets the key code for the event.
8267 getCharCode : function(){
8268 return this.charCode || this.keyCode;
8272 * Returns a normalized keyCode for the event.
8273 * @return {Number} The key code
8275 getKey : function(){
8276 var k = this.keyCode || this.charCode;
8277 return Roo.isSafari ? (safariKeys[k] || k) : k;
8281 * Gets the x coordinate of the event.
8284 getPageX : function(){
8289 * Gets the y coordinate of the event.
8292 getPageY : function(){
8297 * Gets the time of the event.
8300 getTime : function(){
8301 if(this.browserEvent){
8302 return E.getTime(this.browserEvent);
8308 * Gets the page coordinates of the event.
8309 * @return {Array} The xy values like [x, y]
8316 * Gets the target for the event.
8317 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
8318 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8319 search as a number or element (defaults to 10 || document.body)
8320 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8321 * @return {HTMLelement}
8323 getTarget : function(selector, maxDepth, returnEl){
8324 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
8327 * Gets the related target.
8328 * @return {HTMLElement}
8330 getRelatedTarget : function(){
8331 if(this.browserEvent){
8332 return E.getRelatedTarget(this.browserEvent);
8338 * Normalizes mouse wheel delta across browsers
8339 * @return {Number} The delta
8341 getWheelDelta : function(){
8342 var e = this.browserEvent;
8344 if(e.wheelDelta){ /* IE/Opera. */
8345 delta = e.wheelDelta/120;
8346 }else if(e.detail){ /* Mozilla case. */
8347 delta = -e.detail/3;
8353 * Returns true if the control, meta, shift or alt key was pressed during this event.
8356 hasModifier : function(){
8357 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
8361 * Returns true if the target of this event equals el or is a child of el
8362 * @param {String/HTMLElement/Element} el
8363 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
8366 within : function(el, related){
8367 var t = this[related ? "getRelatedTarget" : "getTarget"]();
8368 return t && Roo.fly(el).contains(t);
8371 getPoint : function(){
8372 return new Roo.lib.Point(this.xy[0], this.xy[1]);
8376 return new Roo.EventObjectImpl();
8381 * Ext JS Library 1.1.1
8382 * Copyright(c) 2006-2007, Ext JS, LLC.
8384 * Originally Released Under LGPL - original licence link has changed is not relivant.
8387 * <script type="text/javascript">
8391 // was in Composite Element!??!?!
8394 var D = Roo.lib.Dom;
8395 var E = Roo.lib.Event;
8396 var A = Roo.lib.Anim;
8398 // local style camelizing for speed
8400 var camelRe = /(-[a-z])/gi;
8401 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
8402 var view = document.defaultView;
8405 * @class Roo.Element
8406 * Represents an Element in the DOM.<br><br>
8409 var el = Roo.get("my-div");
8412 var el = getEl("my-div");
8414 // or with a DOM element
8415 var el = Roo.get(myDivElement);
8417 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
8418 * each call instead of constructing a new one.<br><br>
8419 * <b>Animations</b><br />
8420 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
8421 * should either be a boolean (true) or an object literal with animation options. The animation options are:
8423 Option Default Description
8424 --------- -------- ---------------------------------------------
8425 duration .35 The duration of the animation in seconds
8426 easing easeOut The YUI easing method
8427 callback none A function to execute when the anim completes
8428 scope this The scope (this) of the callback function
8430 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
8431 * manipulate the animation. Here's an example:
8433 var el = Roo.get("my-div");
8438 // default animation
8439 el.setWidth(100, true);
8441 // animation with some options set
8448 // using the "anim" property to get the Anim object
8454 el.setWidth(100, opt);
8456 if(opt.anim.isAnimated()){
8460 * <b> Composite (Collections of) Elements</b><br />
8461 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
8462 * @constructor Create a new Element directly.
8463 * @param {String/HTMLElement} element
8464 * @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).
8466 Roo.Element = function(element, forceNew)
8468 var dom = typeof element == "string" ?
8469 document.getElementById(element) : element;
8471 this.listeners = {};
8473 if(!dom){ // invalid id/element
8477 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
8478 return Roo.Element.cache[id];
8488 * The DOM element ID
8491 this.id = id || Roo.id(dom);
8493 return this; // assumed for cctor?
8496 var El = Roo.Element;
8500 * The element's default display mode (defaults to "")
8503 originalDisplay : "",
8506 // note this is overridden in BS version..
8509 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
8515 * Sets the element's visibility mode. When setVisible() is called it
8516 * will use this to determine whether to set the visibility or the display property.
8517 * @param visMode Element.VISIBILITY or Element.DISPLAY
8518 * @return {Roo.Element} this
8520 setVisibilityMode : function(visMode){
8521 this.visibilityMode = visMode;
8525 * Convenience method for setVisibilityMode(Element.DISPLAY)
8526 * @param {String} display (optional) What to set display to when visible
8527 * @return {Roo.Element} this
8529 enableDisplayMode : function(display){
8530 this.setVisibilityMode(El.DISPLAY);
8531 if(typeof display != "undefined") { this.originalDisplay = display; }
8536 * 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)
8537 * @param {String} selector The simple selector to test
8538 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8539 search as a number or element (defaults to 10 || document.body)
8540 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8541 * @return {HTMLElement} The matching DOM node (or null if no match was found)
8543 findParent : function(simpleSelector, maxDepth, returnEl){
8544 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
8545 maxDepth = maxDepth || 50;
8546 if(typeof maxDepth != "number"){
8547 stopEl = Roo.getDom(maxDepth);
8550 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
8551 if(dq.is(p, simpleSelector)){
8552 return returnEl ? Roo.get(p) : p;
8562 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
8563 * @param {String} selector The simple selector to test
8564 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8565 search as a number or element (defaults to 10 || document.body)
8566 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8567 * @return {HTMLElement} The matching DOM node (or null if no match was found)
8569 findParentNode : function(simpleSelector, maxDepth, returnEl){
8570 var p = Roo.fly(this.dom.parentNode, '_internal');
8571 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
8575 * Looks at the scrollable parent element
8577 findScrollableParent : function()
8579 var overflowRegex = /(auto|scroll)/;
8581 if(this.getStyle('position') === 'fixed'){
8582 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8585 var excludeStaticParent = this.getStyle('position') === "absolute";
8587 for (var parent = this; (parent = Roo.get(parent.dom.parentNode));){
8589 if (excludeStaticParent && parent.getStyle('position') === "static") {
8593 if (overflowRegex.test(parent.getStyle('overflow') + parent.getStyle('overflow-x') + parent.getStyle('overflow-y'))){
8597 if(parent.dom.nodeName.toLowerCase() == 'body'){
8598 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8602 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8606 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
8607 * This is a shortcut for findParentNode() that always returns an Roo.Element.
8608 * @param {String} selector The simple selector to test
8609 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8610 search as a number or element (defaults to 10 || document.body)
8611 * @return {Roo.Element} The matching DOM node (or null if no match was found)
8613 up : function(simpleSelector, maxDepth){
8614 return this.findParentNode(simpleSelector, maxDepth, true);
8620 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
8621 * @param {String} selector The simple selector to test
8622 * @return {Boolean} True if this element matches the selector, else false
8624 is : function(simpleSelector){
8625 return Roo.DomQuery.is(this.dom, simpleSelector);
8629 * Perform animation on this element.
8630 * @param {Object} args The YUI animation control args
8631 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
8632 * @param {Function} onComplete (optional) Function to call when animation completes
8633 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
8634 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
8635 * @return {Roo.Element} this
8637 animate : function(args, duration, onComplete, easing, animType){
8638 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
8643 * @private Internal animation call
8645 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
8646 animType = animType || 'run';
8648 var anim = Roo.lib.Anim[animType](
8650 (opt.duration || defaultDur) || .35,
8651 (opt.easing || defaultEase) || 'easeOut',
8653 Roo.callback(cb, this);
8654 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
8662 // private legacy anim prep
8663 preanim : function(a, i){
8664 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
8668 * Removes worthless text nodes
8669 * @param {Boolean} forceReclean (optional) By default the element
8670 * keeps track if it has been cleaned already so
8671 * you can call this over and over. However, if you update the element and
8672 * need to force a reclean, you can pass true.
8674 clean : function(forceReclean){
8675 if(this.isCleaned && forceReclean !== true){
8679 var d = this.dom, n = d.firstChild, ni = -1;
8681 var nx = n.nextSibling;
8682 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
8689 this.isCleaned = true;
8694 calcOffsetsTo : function(el){
8697 var restorePos = false;
8698 if(el.getStyle('position') == 'static'){
8699 el.position('relative');
8704 while(op && op != d && op.tagName != 'HTML'){
8707 op = op.offsetParent;
8710 el.position('static');
8716 * Scrolls this element into view within the passed container.
8717 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
8718 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
8719 * @return {Roo.Element} this
8721 scrollIntoView : function(container, hscroll){
8722 var c = Roo.getDom(container) || document.body;
8725 var o = this.calcOffsetsTo(c),
8728 b = t+el.offsetHeight,
8729 r = l+el.offsetWidth;
8731 var ch = c.clientHeight;
8732 var ct = parseInt(c.scrollTop, 10);
8733 var cl = parseInt(c.scrollLeft, 10);
8735 var cr = cl + c.clientWidth;
8743 if(hscroll !== false){
8747 c.scrollLeft = r-c.clientWidth;
8754 scrollChildIntoView : function(child, hscroll){
8755 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
8759 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
8760 * the new height may not be available immediately.
8761 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
8762 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
8763 * @param {Function} onComplete (optional) Function to call when animation completes
8764 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
8765 * @return {Roo.Element} this
8767 autoHeight : function(animate, duration, onComplete, easing){
8768 var oldHeight = this.getHeight();
8770 this.setHeight(1); // force clipping
8771 setTimeout(function(){
8772 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
8774 this.setHeight(height);
8776 if(typeof onComplete == "function"){
8780 this.setHeight(oldHeight); // restore original height
8781 this.setHeight(height, animate, duration, function(){
8783 if(typeof onComplete == "function") { onComplete(); }
8784 }.createDelegate(this), easing);
8786 }.createDelegate(this), 0);
8791 * Returns true if this element is an ancestor of the passed element
8792 * @param {HTMLElement/String} el The element to check
8793 * @return {Boolean} True if this element is an ancestor of el, else false
8795 contains : function(el){
8796 if(!el){return false;}
8797 return D.isAncestor(this.dom, el.dom ? el.dom : el);
8801 * Checks whether the element is currently visible using both visibility and display properties.
8802 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
8803 * @return {Boolean} True if the element is currently visible, else false
8805 isVisible : function(deep) {
8806 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
8807 if(deep !== true || !vis){
8810 var p = this.dom.parentNode;
8811 while(p && p.tagName.toLowerCase() != "body"){
8812 if(!Roo.fly(p, '_isVisible').isVisible()){
8821 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
8822 * @param {String} selector The CSS selector
8823 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
8824 * @return {CompositeElement/CompositeElementLite} The composite element
8826 select : function(selector, unique){
8827 return El.select(selector, unique, this.dom);
8831 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
8832 * @param {String} selector The CSS selector
8833 * @return {Array} An array of the matched nodes
8835 query : function(selector, unique){
8836 return Roo.DomQuery.select(selector, this.dom);
8840 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
8841 * @param {String} selector The CSS selector
8842 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8843 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8845 child : function(selector, returnDom){
8846 var n = Roo.DomQuery.selectNode(selector, this.dom);
8847 return returnDom ? n : Roo.get(n);
8851 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
8852 * @param {String} selector The CSS selector
8853 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8854 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8856 down : function(selector, returnDom){
8857 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
8858 return returnDom ? n : Roo.get(n);
8862 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
8863 * @param {String} group The group the DD object is member of
8864 * @param {Object} config The DD config object
8865 * @param {Object} overrides An object containing methods to override/implement on the DD object
8866 * @return {Roo.dd.DD} The DD object
8868 initDD : function(group, config, overrides){
8869 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
8870 return Roo.apply(dd, overrides);
8874 * Initializes a {@link Roo.dd.DDProxy} object for this element.
8875 * @param {String} group The group the DDProxy object is member of
8876 * @param {Object} config The DDProxy config object
8877 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
8878 * @return {Roo.dd.DDProxy} The DDProxy object
8880 initDDProxy : function(group, config, overrides){
8881 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
8882 return Roo.apply(dd, overrides);
8886 * Initializes a {@link Roo.dd.DDTarget} object for this element.
8887 * @param {String} group The group the DDTarget object is member of
8888 * @param {Object} config The DDTarget config object
8889 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
8890 * @return {Roo.dd.DDTarget} The DDTarget object
8892 initDDTarget : function(group, config, overrides){
8893 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
8894 return Roo.apply(dd, overrides);
8898 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
8899 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
8900 * @param {Boolean} visible Whether the element is visible
8901 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8902 * @return {Roo.Element} this
8904 setVisible : function(visible, animate){
8906 if(this.visibilityMode == El.DISPLAY){
8907 this.setDisplayed(visible);
8910 this.dom.style.visibility = visible ? "visible" : "hidden";
8913 // closure for composites
8915 var visMode = this.visibilityMode;
8917 this.setOpacity(.01);
8918 this.setVisible(true);
8920 this.anim({opacity: { to: (visible?1:0) }},
8921 this.preanim(arguments, 1),
8922 null, .35, 'easeIn', function(){
8924 if(visMode == El.DISPLAY){
8925 dom.style.display = "none";
8927 dom.style.visibility = "hidden";
8929 Roo.get(dom).setOpacity(1);
8937 * Returns true if display is not "none"
8940 isDisplayed : function() {
8941 return this.getStyle("display") != "none";
8945 * Toggles the element's visibility or display, depending on visibility mode.
8946 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8947 * @return {Roo.Element} this
8949 toggle : function(animate){
8950 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
8955 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
8956 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
8957 * @return {Roo.Element} this
8959 setDisplayed : function(value) {
8960 if(typeof value == "boolean"){
8961 value = value ? this.originalDisplay : "none";
8963 this.setStyle("display", value);
8968 * Tries to focus the element. Any exceptions are caught and ignored.
8969 * @return {Roo.Element} this
8971 focus : function() {
8979 * Tries to blur the element. Any exceptions are caught and ignored.
8980 * @return {Roo.Element} this
8990 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
8991 * @param {String/Array} className The CSS class to add, or an array of classes
8992 * @return {Roo.Element} this
8994 addClass : function(className){
8995 if(className instanceof Array){
8996 for(var i = 0, len = className.length; i < len; i++) {
8997 this.addClass(className[i]);
9000 if(className && !this.hasClass(className)){
9001 if (this.dom instanceof SVGElement) {
9002 this.dom.className.baseVal =this.dom.className.baseVal + " " + className;
9004 this.dom.className = this.dom.className + " " + className;
9012 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
9013 * @param {String/Array} className The CSS class to add, or an array of classes
9014 * @return {Roo.Element} this
9016 radioClass : function(className){
9017 var siblings = this.dom.parentNode.childNodes;
9018 for(var i = 0; i < siblings.length; i++) {
9019 var s = siblings[i];
9020 if(s.nodeType == 1){
9021 Roo.get(s).removeClass(className);
9024 this.addClass(className);
9029 * Removes one or more CSS classes from the element.
9030 * @param {String/Array} className The CSS class to remove, or an array of classes
9031 * @return {Roo.Element} this
9033 removeClass : function(className){
9035 var cn = this.dom instanceof SVGElement ? this.dom.className.baseVal : this.dom.className;
9036 if(!className || !cn){
9039 if(className instanceof Array){
9040 for(var i = 0, len = className.length; i < len; i++) {
9041 this.removeClass(className[i]);
9044 if(this.hasClass(className)){
9045 var re = this.classReCache[className];
9047 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
9048 this.classReCache[className] = re;
9050 if (this.dom instanceof SVGElement) {
9051 this.dom.className.baseVal = cn.replace(re, " ");
9053 this.dom.className = cn.replace(re, " ");
9064 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
9065 * @param {String} className The CSS class to toggle
9066 * @return {Roo.Element} this
9068 toggleClass : function(className){
9069 if(this.hasClass(className)){
9070 this.removeClass(className);
9072 this.addClass(className);
9078 * Checks if the specified CSS class exists on this element's DOM node.
9079 * @param {String} className The CSS class to check for
9080 * @return {Boolean} True if the class exists, else false
9082 hasClass : function(className){
9083 if (this.dom instanceof SVGElement) {
9084 return className && (' '+this.dom.className.baseVal +' ').indexOf(' '+className+' ') != -1;
9086 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
9090 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
9091 * @param {String} oldClassName The CSS class to replace
9092 * @param {String} newClassName The replacement CSS class
9093 * @return {Roo.Element} this
9095 replaceClass : function(oldClassName, newClassName){
9096 this.removeClass(oldClassName);
9097 this.addClass(newClassName);
9102 * Returns an object with properties matching the styles requested.
9103 * For example, el.getStyles('color', 'font-size', 'width') might return
9104 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
9105 * @param {String} style1 A style name
9106 * @param {String} style2 A style name
9107 * @param {String} etc.
9108 * @return {Object} The style object
9110 getStyles : function(){
9111 var a = arguments, len = a.length, r = {};
9112 for(var i = 0; i < len; i++){
9113 r[a[i]] = this.getStyle(a[i]);
9119 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
9120 * @param {String} property The style property whose value is returned.
9121 * @return {String} The current value of the style property for this element.
9123 getStyle : function(){
9124 return view && view.getComputedStyle ?
9126 var el = this.dom, v, cs, camel;
9127 if(prop == 'float'){
9130 if(el.style && (v = el.style[prop])){
9133 if(cs = view.getComputedStyle(el, "")){
9134 if(!(camel = propCache[prop])){
9135 camel = propCache[prop] = prop.replace(camelRe, camelFn);
9142 var el = this.dom, v, cs, camel;
9143 if(prop == 'opacity'){
9144 if(typeof el.style.filter == 'string'){
9145 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
9147 var fv = parseFloat(m[1]);
9149 return fv ? fv / 100 : 0;
9154 }else if(prop == 'float'){
9155 prop = "styleFloat";
9157 if(!(camel = propCache[prop])){
9158 camel = propCache[prop] = prop.replace(camelRe, camelFn);
9160 if(v = el.style[camel]){
9163 if(cs = el.currentStyle){
9171 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
9172 * @param {String/Object} property The style property to be set, or an object of multiple styles.
9173 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
9174 * @return {Roo.Element} this
9176 setStyle : function(prop, value){
9177 if(typeof prop == "string"){
9179 if (prop == 'float') {
9180 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
9185 if(!(camel = propCache[prop])){
9186 camel = propCache[prop] = prop.replace(camelRe, camelFn);
9189 if(camel == 'opacity') {
9190 this.setOpacity(value);
9192 this.dom.style[camel] = value;
9195 for(var style in prop){
9196 if(typeof prop[style] != "function"){
9197 this.setStyle(style, prop[style]);
9205 * More flexible version of {@link #setStyle} for setting style properties.
9206 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
9207 * a function which returns such a specification.
9208 * @return {Roo.Element} this
9210 applyStyles : function(style){
9211 Roo.DomHelper.applyStyles(this.dom, style);
9216 * 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).
9217 * @return {Number} The X position of the element
9220 return D.getX(this.dom);
9224 * 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).
9225 * @return {Number} The Y position of the element
9228 return D.getY(this.dom);
9232 * 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).
9233 * @return {Array} The XY position of the element
9236 return D.getXY(this.dom);
9240 * 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).
9241 * @param {Number} The X position of the element
9242 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9243 * @return {Roo.Element} this
9245 setX : function(x, animate){
9247 D.setX(this.dom, x);
9249 this.setXY([x, this.getY()], this.preanim(arguments, 1));
9255 * 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).
9256 * @param {Number} The Y position of the element
9257 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9258 * @return {Roo.Element} this
9260 setY : function(y, animate){
9262 D.setY(this.dom, y);
9264 this.setXY([this.getX(), y], this.preanim(arguments, 1));
9270 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
9271 * @param {String} left The left CSS property value
9272 * @return {Roo.Element} this
9274 setLeft : function(left){
9275 this.setStyle("left", this.addUnits(left));
9280 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
9281 * @param {String} top The top CSS property value
9282 * @return {Roo.Element} this
9284 setTop : function(top){
9285 this.setStyle("top", this.addUnits(top));
9290 * Sets the element's CSS right style.
9291 * @param {String} right The right CSS property value
9292 * @return {Roo.Element} this
9294 setRight : function(right){
9295 this.setStyle("right", this.addUnits(right));
9300 * Sets the element's CSS bottom style.
9301 * @param {String} bottom The bottom CSS property value
9302 * @return {Roo.Element} this
9304 setBottom : function(bottom){
9305 this.setStyle("bottom", this.addUnits(bottom));
9310 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
9311 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
9312 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
9313 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9314 * @return {Roo.Element} this
9316 setXY : function(pos, animate){
9318 D.setXY(this.dom, pos);
9320 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
9326 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
9327 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
9328 * @param {Number} x X value for new position (coordinates are page-based)
9329 * @param {Number} y Y value for new position (coordinates are page-based)
9330 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9331 * @return {Roo.Element} this
9333 setLocation : function(x, y, animate){
9334 this.setXY([x, y], this.preanim(arguments, 2));
9339 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
9340 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
9341 * @param {Number} x X value for new position (coordinates are page-based)
9342 * @param {Number} y Y value for new position (coordinates are page-based)
9343 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9344 * @return {Roo.Element} this
9346 moveTo : function(x, y, animate){
9347 this.setXY([x, y], this.preanim(arguments, 2));
9352 * Returns the region of the given element.
9353 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
9354 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
9356 getRegion : function(){
9357 return D.getRegion(this.dom);
9361 * Returns the offset height of the element
9362 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
9363 * @return {Number} The element's height
9365 getHeight : function(contentHeight){
9366 var h = this.dom.offsetHeight || 0;
9367 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
9371 * Returns the offset width of the element
9372 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
9373 * @return {Number} The element's width
9375 getWidth : function(contentWidth){
9376 var w = this.dom.offsetWidth || 0;
9377 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
9381 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
9382 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
9383 * if a height has not been set using CSS.
9386 getComputedHeight : function(){
9387 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
9389 h = parseInt(this.getStyle('height'), 10) || 0;
9390 if(!this.isBorderBox()){
9391 h += this.getFrameWidth('tb');
9398 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
9399 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
9400 * if a width has not been set using CSS.
9403 getComputedWidth : function(){
9404 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
9406 w = parseInt(this.getStyle('width'), 10) || 0;
9407 if(!this.isBorderBox()){
9408 w += this.getFrameWidth('lr');
9415 * Returns the size of the element.
9416 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
9417 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
9419 getSize : function(contentSize){
9420 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
9424 * Returns the width and height of the viewport.
9425 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
9427 getViewSize : function(){
9428 var d = this.dom, doc = document, aw = 0, ah = 0;
9429 if(d == doc || d == doc.body){
9430 return {width : D.getViewWidth(), height: D.getViewHeight()};
9433 width : d.clientWidth,
9434 height: d.clientHeight
9440 * Returns the value of the "value" attribute
9441 * @param {Boolean} asNumber true to parse the value as a number
9442 * @return {String/Number}
9444 getValue : function(asNumber){
9445 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
9449 adjustWidth : function(width){
9450 if(typeof width == "number"){
9451 if(this.autoBoxAdjust && !this.isBorderBox()){
9452 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
9462 adjustHeight : function(height){
9463 if(typeof height == "number"){
9464 if(this.autoBoxAdjust && !this.isBorderBox()){
9465 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
9475 * Set the width of the element
9476 * @param {Number} width The new width
9477 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9478 * @return {Roo.Element} this
9480 setWidth : function(width, animate){
9481 width = this.adjustWidth(width);
9483 this.dom.style.width = this.addUnits(width);
9485 this.anim({width: {to: width}}, this.preanim(arguments, 1));
9491 * Set the height of the element
9492 * @param {Number} height The new height
9493 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9494 * @return {Roo.Element} this
9496 setHeight : function(height, animate){
9497 height = this.adjustHeight(height);
9499 this.dom.style.height = this.addUnits(height);
9501 this.anim({height: {to: height}}, this.preanim(arguments, 1));
9507 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
9508 * @param {Number} width The new width
9509 * @param {Number} height The new height
9510 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9511 * @return {Roo.Element} this
9513 setSize : function(width, height, animate){
9514 if(typeof width == "object"){ // in case of object from getSize()
9515 height = width.height; width = width.width;
9517 width = this.adjustWidth(width); height = this.adjustHeight(height);
9519 this.dom.style.width = this.addUnits(width);
9520 this.dom.style.height = this.addUnits(height);
9522 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
9528 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
9529 * @param {Number} x X value for new position (coordinates are page-based)
9530 * @param {Number} y Y value for new position (coordinates are page-based)
9531 * @param {Number} width The new width
9532 * @param {Number} height The new height
9533 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9534 * @return {Roo.Element} this
9536 setBounds : function(x, y, width, height, animate){
9538 this.setSize(width, height);
9539 this.setLocation(x, y);
9541 width = this.adjustWidth(width); height = this.adjustHeight(height);
9542 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
9543 this.preanim(arguments, 4), 'motion');
9549 * 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.
9550 * @param {Roo.lib.Region} region The region to fill
9551 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9552 * @return {Roo.Element} this
9554 setRegion : function(region, animate){
9555 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
9560 * Appends an event handler
9562 * @param {String} eventName The type of event to append
9563 * @param {Function} fn The method the event invokes
9564 * @param {Object} scope (optional) The scope (this object) of the fn
9565 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
9567 addListener : function(eventName, fn, scope, options)
9569 if (eventName == 'dblclick') { // doublclick (touchstart) - faked on touch.
9570 this.addListener('touchstart', this.onTapHandler, this);
9573 // we need to handle a special case where dom element is a svg element.
9574 // in this case we do not actua
9579 if (this.dom instanceof SVGElement && !(this.dom instanceof SVGSVGElement)) {
9580 if (typeof(this.listeners[eventName]) == 'undefined') {
9581 this.listeners[eventName] = new Roo.util.Event(this, eventName);
9583 this.listeners[eventName].addListener(fn, scope, options);
9588 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
9593 onTapHandler : function(event)
9595 if(!this.tapedTwice) {
9596 this.tapedTwice = true;
9598 setTimeout( function() {
9599 s.tapedTwice = false;
9603 event.preventDefault();
9604 var revent = new MouseEvent('dblclick', {
9610 this.dom.dispatchEvent(revent);
9611 //action on double tap goes below
9616 * Removes an event handler from this element
9617 * @param {String} eventName the type of event to remove
9618 * @param {Function} fn the method the event invokes
9619 * @param {Function} scope (needed for svg fake listeners)
9620 * @return {Roo.Element} this
9622 removeListener : function(eventName, fn, scope){
9623 Roo.EventManager.removeListener(this.dom, eventName, fn);
9624 if (typeof(this.listeners) == 'undefined' || typeof(this.listeners[eventName]) == 'undefined') {
9627 this.listeners[eventName].removeListener(fn, scope);
9632 * Removes all previous added listeners from this element
9633 * @return {Roo.Element} this
9635 removeAllListeners : function(){
9636 E.purgeElement(this.dom);
9637 this.listeners = {};
9641 relayEvent : function(eventName, observable){
9642 this.on(eventName, function(e){
9643 observable.fireEvent(eventName, e);
9649 * Set the opacity of the element
9650 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
9651 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9652 * @return {Roo.Element} this
9654 setOpacity : function(opacity, animate){
9656 var s = this.dom.style;
9659 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
9660 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
9662 s.opacity = opacity;
9665 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
9671 * Gets the left X coordinate
9672 * @param {Boolean} local True to get the local css position instead of page coordinate
9675 getLeft : function(local){
9679 return parseInt(this.getStyle("left"), 10) || 0;
9684 * Gets the right X coordinate of the element (element X position + element width)
9685 * @param {Boolean} local True to get the local css position instead of page coordinate
9688 getRight : function(local){
9690 return this.getX() + this.getWidth();
9692 return (this.getLeft(true) + this.getWidth()) || 0;
9697 * Gets the top Y coordinate
9698 * @param {Boolean} local True to get the local css position instead of page coordinate
9701 getTop : function(local) {
9705 return parseInt(this.getStyle("top"), 10) || 0;
9710 * Gets the bottom Y coordinate of the element (element Y position + element height)
9711 * @param {Boolean} local True to get the local css position instead of page coordinate
9714 getBottom : function(local){
9716 return this.getY() + this.getHeight();
9718 return (this.getTop(true) + this.getHeight()) || 0;
9723 * Initializes positioning on this element. If a desired position is not passed, it will make the
9724 * the element positioned relative IF it is not already positioned.
9725 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
9726 * @param {Number} zIndex (optional) The zIndex to apply
9727 * @param {Number} x (optional) Set the page X position
9728 * @param {Number} y (optional) Set the page Y position
9730 position : function(pos, zIndex, x, y){
9732 if(this.getStyle('position') == 'static'){
9733 this.setStyle('position', 'relative');
9736 this.setStyle("position", pos);
9739 this.setStyle("z-index", zIndex);
9741 if(x !== undefined && y !== undefined){
9743 }else if(x !== undefined){
9745 }else if(y !== undefined){
9751 * Clear positioning back to the default when the document was loaded
9752 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
9753 * @return {Roo.Element} this
9755 clearPositioning : function(value){
9763 "position" : "static"
9769 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
9770 * snapshot before performing an update and then restoring the element.
9773 getPositioning : function(){
9774 var l = this.getStyle("left");
9775 var t = this.getStyle("top");
9777 "position" : this.getStyle("position"),
9779 "right" : l ? "" : this.getStyle("right"),
9781 "bottom" : t ? "" : this.getStyle("bottom"),
9782 "z-index" : this.getStyle("z-index")
9787 * Gets the width of the border(s) for the specified side(s)
9788 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9789 * passing lr would get the border (l)eft width + the border (r)ight width.
9790 * @return {Number} The width of the sides passed added together
9792 getBorderWidth : function(side){
9793 return this.addStyles(side, El.borders);
9797 * Gets the width of the padding(s) for the specified side(s)
9798 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9799 * passing lr would get the padding (l)eft + the padding (r)ight.
9800 * @return {Number} The padding of the sides passed added together
9802 getPadding : function(side){
9803 return this.addStyles(side, El.paddings);
9807 * Set positioning with an object returned by getPositioning().
9808 * @param {Object} posCfg
9809 * @return {Roo.Element} this
9811 setPositioning : function(pc){
9812 this.applyStyles(pc);
9813 if(pc.right == "auto"){
9814 this.dom.style.right = "";
9816 if(pc.bottom == "auto"){
9817 this.dom.style.bottom = "";
9823 fixDisplay : function(){
9824 if(this.getStyle("display") == "none"){
9825 this.setStyle("visibility", "hidden");
9826 this.setStyle("display", this.originalDisplay); // first try reverting to default
9827 if(this.getStyle("display") == "none"){ // if that fails, default to block
9828 this.setStyle("display", "block");
9834 * Quick set left and top adding default units
9835 * @param {String} left The left CSS property value
9836 * @param {String} top The top CSS property value
9837 * @return {Roo.Element} this
9839 setLeftTop : function(left, top){
9840 this.dom.style.left = this.addUnits(left);
9841 this.dom.style.top = this.addUnits(top);
9846 * Move this element relative to its current position.
9847 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9848 * @param {Number} distance How far to move the element in pixels
9849 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9850 * @return {Roo.Element} this
9852 move : function(direction, distance, animate){
9853 var xy = this.getXY();
9854 direction = direction.toLowerCase();
9858 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
9862 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
9867 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
9872 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
9879 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
9880 * @return {Roo.Element} this
9883 if(!this.isClipped){
9884 this.isClipped = true;
9885 this.originalClip = {
9886 "o": this.getStyle("overflow"),
9887 "x": this.getStyle("overflow-x"),
9888 "y": this.getStyle("overflow-y")
9890 this.setStyle("overflow", "hidden");
9891 this.setStyle("overflow-x", "hidden");
9892 this.setStyle("overflow-y", "hidden");
9898 * Return clipping (overflow) to original clipping before clip() was called
9899 * @return {Roo.Element} this
9901 unclip : function(){
9903 this.isClipped = false;
9904 var o = this.originalClip;
9905 if(o.o){this.setStyle("overflow", o.o);}
9906 if(o.x){this.setStyle("overflow-x", o.x);}
9907 if(o.y){this.setStyle("overflow-y", o.y);}
9914 * Gets the x,y coordinates specified by the anchor position on the element.
9915 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
9916 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
9917 * {width: (target width), height: (target height)} (defaults to the element's current size)
9918 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
9919 * @return {Array} [x, y] An array containing the element's x and y coordinates
9921 getAnchorXY : function(anchor, local, s){
9922 //Passing a different size is useful for pre-calculating anchors,
9923 //especially for anchored animations that change the el size.
9925 var w, h, vp = false;
9928 if(d == document.body || d == document){
9930 w = D.getViewWidth(); h = D.getViewHeight();
9932 w = this.getWidth(); h = this.getHeight();
9935 w = s.width; h = s.height;
9937 var x = 0, y = 0, r = Math.round;
9938 switch((anchor || "tl").toLowerCase()){
9980 var sc = this.getScroll();
9981 return [x + sc.left, y + sc.top];
9983 //Add the element's offset xy
9984 var o = this.getXY();
9985 return [x+o[0], y+o[1]];
9989 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
9990 * supported position values.
9991 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9992 * @param {String} position The position to align to.
9993 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9994 * @return {Array} [x, y]
9996 getAlignToXY : function(el, p, o)
10001 throw "Element.alignTo with an element that doesn't exist";
10003 var c = false; //constrain to viewport
10004 var p1 = "", p2 = "";
10009 }else if(p == "?"){
10011 }else if(p.indexOf("-") == -1){
10014 p = p.toLowerCase();
10015 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
10017 throw "Element.alignTo with an invalid alignment " + p;
10019 p1 = m[1]; p2 = m[2]; c = !!m[3];
10021 //Subtract the aligned el's internal xy from the target's offset xy
10022 //plus custom offset to get the aligned el's new offset xy
10023 var a1 = this.getAnchorXY(p1, true);
10024 var a2 = el.getAnchorXY(p2, false);
10025 var x = a2[0] - a1[0] + o[0];
10026 var y = a2[1] - a1[1] + o[1];
10028 //constrain the aligned el to viewport if necessary
10029 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
10030 // 5px of margin for ie
10031 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
10033 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
10034 //perpendicular to the vp border, allow the aligned el to slide on that border,
10035 //otherwise swap the aligned el to the opposite border of the target.
10036 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
10037 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
10038 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t") );
10039 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
10041 var doc = document;
10042 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
10043 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
10045 if((x+w) > dw + scrollX){
10046 x = swapX ? r.left-w : dw+scrollX-w;
10049 x = swapX ? r.right : scrollX;
10051 if((y+h) > dh + scrollY){
10052 y = swapY ? r.top-h : dh+scrollY-h;
10055 y = swapY ? r.bottom : scrollY;
10062 getConstrainToXY : function(){
10063 var os = {top:0, left:0, bottom:0, right: 0};
10065 return function(el, local, offsets, proposedXY){
10067 offsets = offsets ? Roo.applyIf(offsets, os) : os;
10069 var vw, vh, vx = 0, vy = 0;
10070 if(el.dom == document.body || el.dom == document){
10071 vw = Roo.lib.Dom.getViewWidth();
10072 vh = Roo.lib.Dom.getViewHeight();
10074 vw = el.dom.clientWidth;
10075 vh = el.dom.clientHeight;
10077 var vxy = el.getXY();
10083 var s = el.getScroll();
10085 vx += offsets.left + s.left;
10086 vy += offsets.top + s.top;
10088 vw -= offsets.right;
10089 vh -= offsets.bottom;
10094 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
10095 var x = xy[0], y = xy[1];
10096 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
10098 // only move it if it needs it
10101 // first validate right/bottom
10110 // then make sure top/left isn't negative
10119 return moved ? [x, y] : false;
10124 adjustForConstraints : function(xy, parent, offsets){
10125 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
10129 * Aligns this element with another element relative to the specified anchor points. If the other element is the
10130 * document it aligns it to the viewport.
10131 * The position parameter is optional, and can be specified in any one of the following formats:
10133 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
10134 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
10135 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
10136 * deprecated in favor of the newer two anchor syntax below</i>.</li>
10137 * <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
10138 * element's anchor point, and the second value is used as the target's anchor point.</li>
10140 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
10141 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
10142 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
10143 * that specified in order to enforce the viewport constraints.
10144 * Following are all of the supported anchor positions:
10147 ----- -----------------------------
10148 tl The top left corner (default)
10149 t The center of the top edge
10150 tr The top right corner
10151 l The center of the left edge
10152 c In the center of the element
10153 r The center of the right edge
10154 bl The bottom left corner
10155 b The center of the bottom edge
10156 br The bottom right corner
10160 // align el to other-el using the default positioning ("tl-bl", non-constrained)
10161 el.alignTo("other-el");
10163 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
10164 el.alignTo("other-el", "tr?");
10166 // align the bottom right corner of el with the center left edge of other-el
10167 el.alignTo("other-el", "br-l?");
10169 // align the center of el with the bottom left corner of other-el and
10170 // adjust the x position by -6 pixels (and the y position by 0)
10171 el.alignTo("other-el", "c-bl", [-6, 0]);
10173 * @param {String/HTMLElement/Roo.Element} element The element to align to.
10174 * @param {String} position The position to align to.
10175 * @param {Array} offsets (optional) Offset the positioning by [x, y]
10176 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10177 * @return {Roo.Element} this
10179 alignTo : function(element, position, offsets, animate){
10180 var xy = this.getAlignToXY(element, position, offsets);
10181 this.setXY(xy, this.preanim(arguments, 3));
10186 * Anchors an element to another element and realigns it when the window is resized.
10187 * @param {String/HTMLElement/Roo.Element} element The element to align to.
10188 * @param {String} position The position to align to.
10189 * @param {Array} offsets (optional) Offset the positioning by [x, y]
10190 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
10191 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
10192 * is a number, it is used as the buffer delay (defaults to 50ms).
10193 * @param {Function} callback The function to call after the animation finishes
10194 * @return {Roo.Element} this
10196 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
10197 var action = function(){
10198 this.alignTo(el, alignment, offsets, animate);
10199 Roo.callback(callback, this);
10201 Roo.EventManager.onWindowResize(action, this);
10202 var tm = typeof monitorScroll;
10203 if(tm != 'undefined'){
10204 Roo.EventManager.on(window, 'scroll', action, this,
10205 {buffer: tm == 'number' ? monitorScroll : 50});
10207 action.call(this); // align immediately
10211 * Clears any opacity settings from this element. Required in some cases for IE.
10212 * @return {Roo.Element} this
10214 clearOpacity : function(){
10215 if (window.ActiveXObject) {
10216 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
10217 this.dom.style.filter = "";
10220 this.dom.style.opacity = "";
10221 this.dom.style["-moz-opacity"] = "";
10222 this.dom.style["-khtml-opacity"] = "";
10228 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
10229 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10230 * @return {Roo.Element} this
10232 hide : function(animate){
10233 this.setVisible(false, this.preanim(arguments, 0));
10238 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
10239 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10240 * @return {Roo.Element} this
10242 show : function(animate){
10243 this.setVisible(true, this.preanim(arguments, 0));
10248 * @private Test if size has a unit, otherwise appends the default
10250 addUnits : function(size){
10251 return Roo.Element.addUnits(size, this.defaultUnit);
10255 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
10256 * @return {Roo.Element} this
10258 beginMeasure : function(){
10260 if(el.offsetWidth || el.offsetHeight){
10261 return this; // offsets work already
10264 var p = this.dom, b = document.body; // start with this element
10265 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
10266 var pe = Roo.get(p);
10267 if(pe.getStyle('display') == 'none'){
10268 changed.push({el: p, visibility: pe.getStyle("visibility")});
10269 p.style.visibility = "hidden";
10270 p.style.display = "block";
10274 this._measureChanged = changed;
10280 * Restores displays to before beginMeasure was called
10281 * @return {Roo.Element} this
10283 endMeasure : function(){
10284 var changed = this._measureChanged;
10286 for(var i = 0, len = changed.length; i < len; i++) {
10287 var r = changed[i];
10288 r.el.style.visibility = r.visibility;
10289 r.el.style.display = "none";
10291 this._measureChanged = null;
10297 * Update the innerHTML of this element, optionally searching for and processing scripts
10298 * @param {String} html The new HTML
10299 * @param {Boolean} loadScripts (optional) true to look for and process scripts
10300 * @param {Function} callback For async script loading you can be noticed when the update completes
10301 * @return {Roo.Element} this
10303 update : function(html, loadScripts, callback){
10304 if(typeof html == "undefined"){
10307 if(loadScripts !== true){
10308 this.dom.innerHTML = html;
10309 if(typeof callback == "function"){
10315 var dom = this.dom;
10317 html += '<span id="' + id + '"></span>';
10319 E.onAvailable(id, function(){
10320 var hd = document.getElementsByTagName("head")[0];
10321 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
10322 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
10323 var typeRe = /\stype=([\'\"])(.*?)\1/i;
10326 while(match = re.exec(html)){
10327 var attrs = match[1];
10328 var srcMatch = attrs ? attrs.match(srcRe) : false;
10329 if(srcMatch && srcMatch[2]){
10330 var s = document.createElement("script");
10331 s.src = srcMatch[2];
10332 var typeMatch = attrs.match(typeRe);
10333 if(typeMatch && typeMatch[2]){
10334 s.type = typeMatch[2];
10337 }else if(match[2] && match[2].length > 0){
10338 if(window.execScript) {
10339 window.execScript(match[2]);
10347 window.eval(match[2]);
10351 var el = document.getElementById(id);
10352 if(el){el.parentNode.removeChild(el);}
10353 if(typeof callback == "function"){
10357 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
10362 * Direct access to the UpdateManager update() method (takes the same parameters).
10363 * @param {String/Function} url The url for this request or a function to call to get the url
10364 * @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}
10365 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
10366 * @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.
10367 * @return {Roo.Element} this
10370 var um = this.getUpdateManager();
10371 um.update.apply(um, arguments);
10376 * Gets this element's UpdateManager
10377 * @return {Roo.UpdateManager} The UpdateManager
10379 getUpdateManager : function(){
10380 if(!this.updateManager){
10381 this.updateManager = new Roo.UpdateManager(this);
10383 return this.updateManager;
10387 * Disables text selection for this element (normalized across browsers)
10388 * @return {Roo.Element} this
10390 unselectable : function(){
10391 this.dom.unselectable = "on";
10392 this.swallowEvent("selectstart", true);
10393 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
10394 this.addClass("x-unselectable");
10399 * Calculates the x, y to center this element on the screen
10400 * @return {Array} The x, y values [x, y]
10402 getCenterXY : function(){
10403 return this.getAlignToXY(document, 'c-c');
10407 * Centers the Element in either the viewport, or another Element.
10408 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
10410 center : function(centerIn){
10411 this.alignTo(centerIn || document, 'c-c');
10416 * Tests various css rules/browsers to determine if this element uses a border box
10417 * @return {Boolean}
10419 isBorderBox : function(){
10420 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
10424 * Return a box {x, y, width, height} that can be used to set another elements
10425 * size/location to match this element.
10426 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
10427 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
10428 * @return {Object} box An object in the format {x, y, width, height}
10430 getBox : function(contentBox, local){
10435 var left = parseInt(this.getStyle("left"), 10) || 0;
10436 var top = parseInt(this.getStyle("top"), 10) || 0;
10439 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
10441 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
10443 var l = this.getBorderWidth("l")+this.getPadding("l");
10444 var r = this.getBorderWidth("r")+this.getPadding("r");
10445 var t = this.getBorderWidth("t")+this.getPadding("t");
10446 var b = this.getBorderWidth("b")+this.getPadding("b");
10447 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)};
10449 bx.right = bx.x + bx.width;
10450 bx.bottom = bx.y + bx.height;
10455 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
10456 for more information about the sides.
10457 * @param {String} sides
10460 getFrameWidth : function(sides, onlyContentBox){
10461 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
10465 * 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.
10466 * @param {Object} box The box to fill {x, y, width, height}
10467 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
10468 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10469 * @return {Roo.Element} this
10471 setBox : function(box, adjust, animate){
10472 var w = box.width, h = box.height;
10473 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
10474 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
10475 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
10477 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
10482 * Forces the browser to repaint this element
10483 * @return {Roo.Element} this
10485 repaint : function(){
10486 var dom = this.dom;
10487 this.addClass("x-repaint");
10488 setTimeout(function(){
10489 Roo.get(dom).removeClass("x-repaint");
10495 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
10496 * then it returns the calculated width of the sides (see getPadding)
10497 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
10498 * @return {Object/Number}
10500 getMargins : function(side){
10503 top: parseInt(this.getStyle("margin-top"), 10) || 0,
10504 left: parseInt(this.getStyle("margin-left"), 10) || 0,
10505 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
10506 right: parseInt(this.getStyle("margin-right"), 10) || 0
10509 return this.addStyles(side, El.margins);
10514 addStyles : function(sides, styles){
10516 for(var i = 0, len = sides.length; i < len; i++){
10517 v = this.getStyle(styles[sides.charAt(i)]);
10519 w = parseInt(v, 10);
10527 * Creates a proxy element of this element
10528 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
10529 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
10530 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
10531 * @return {Roo.Element} The new proxy element
10533 createProxy : function(config, renderTo, matchBox){
10535 renderTo = Roo.getDom(renderTo);
10537 renderTo = document.body;
10539 config = typeof config == "object" ?
10540 config : {tag : "div", cls: config};
10541 var proxy = Roo.DomHelper.append(renderTo, config, true);
10543 proxy.setBox(this.getBox());
10549 * Puts a mask over this element to disable user interaction. Requires core.css.
10550 * This method can only be applied to elements which accept child nodes.
10551 * @param {String} msg (optional) A message to display in the mask
10552 * @param {String} msgCls (optional) A css class to apply to the msg element - use no-spinner to hide the spinner on bootstrap
10553 * @return {Element} The mask element
10555 mask : function(msg, msgCls)
10557 if(this.getStyle("position") == "static" && this.dom.tagName !== 'BODY'){
10558 this.setStyle("position", "relative");
10561 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
10564 this.addClass("x-masked");
10565 this._mask.setDisplayed(true);
10569 var dom = this.dom;
10570 while (dom && dom.style) {
10571 if (!isNaN(parseInt(dom.style.zIndex))) {
10572 z = Math.max(z, parseInt(dom.style.zIndex));
10574 dom = dom.parentNode;
10576 // if we are masking the body - then it hides everything..
10577 if (this.dom == document.body) {
10579 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
10580 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
10583 if(typeof msg == 'string'){
10584 if(!this._maskMsg){
10585 this._maskMsg = Roo.DomHelper.append(this.dom, {
10586 cls: "roo-el-mask-msg",
10590 cls: 'fa fa-spinner fa-spin'
10598 var mm = this._maskMsg;
10599 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
10600 if (mm.dom.lastChild) { // weird IE issue?
10601 mm.dom.lastChild.innerHTML = msg;
10603 mm.setDisplayed(true);
10605 mm.setStyle('z-index', z + 102);
10607 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
10608 this._mask.setHeight(this.getHeight());
10610 this._mask.setStyle('z-index', z + 100);
10616 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
10617 * it is cached for reuse.
10619 unmask : function(removeEl){
10621 if(removeEl === true){
10622 this._mask.remove();
10625 this._maskMsg.remove();
10626 delete this._maskMsg;
10629 this._mask.setDisplayed(false);
10631 this._maskMsg.setDisplayed(false);
10635 this.removeClass("x-masked");
10639 * Returns true if this element is masked
10640 * @return {Boolean}
10642 isMasked : function(){
10643 return this._mask && this._mask.isVisible();
10647 * Creates an iframe shim for this element to keep selects and other windowed objects from
10649 * @return {Roo.Element} The new shim element
10651 createShim : function(){
10652 var el = document.createElement('iframe');
10653 el.frameBorder = 'no';
10654 el.className = 'roo-shim';
10655 if(Roo.isIE && Roo.isSecure){
10656 el.src = Roo.SSL_SECURE_URL;
10658 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
10659 shim.autoBoxAdjust = false;
10664 * Removes this element from the DOM and deletes it from the cache
10666 remove : function(){
10667 if(this.dom.parentNode){
10668 this.dom.parentNode.removeChild(this.dom);
10670 delete El.cache[this.dom.id];
10674 * Sets up event handlers to add and remove a css class when the mouse is over this element
10675 * @param {String} className
10676 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
10677 * mouseout events for children elements
10678 * @return {Roo.Element} this
10680 addClassOnOver : function(className, preventFlicker){
10681 this.on("mouseover", function(){
10682 Roo.fly(this, '_internal').addClass(className);
10684 var removeFn = function(e){
10685 if(preventFlicker !== true || !e.within(this, true)){
10686 Roo.fly(this, '_internal').removeClass(className);
10689 this.on("mouseout", removeFn, this.dom);
10694 * Sets up event handlers to add and remove a css class when this element has the focus
10695 * @param {String} className
10696 * @return {Roo.Element} this
10698 addClassOnFocus : function(className){
10699 this.on("focus", function(){
10700 Roo.fly(this, '_internal').addClass(className);
10702 this.on("blur", function(){
10703 Roo.fly(this, '_internal').removeClass(className);
10708 * 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)
10709 * @param {String} className
10710 * @return {Roo.Element} this
10712 addClassOnClick : function(className){
10713 var dom = this.dom;
10714 this.on("mousedown", function(){
10715 Roo.fly(dom, '_internal').addClass(className);
10716 var d = Roo.get(document);
10717 var fn = function(){
10718 Roo.fly(dom, '_internal').removeClass(className);
10719 d.removeListener("mouseup", fn);
10721 d.on("mouseup", fn);
10727 * Stops the specified event from bubbling and optionally prevents the default action
10728 * @param {String} eventName
10729 * @param {Boolean} preventDefault (optional) true to prevent the default action too
10730 * @return {Roo.Element} this
10732 swallowEvent : function(eventName, preventDefault){
10733 var fn = function(e){
10734 e.stopPropagation();
10735 if(preventDefault){
10736 e.preventDefault();
10739 if(eventName instanceof Array){
10740 for(var i = 0, len = eventName.length; i < len; i++){
10741 this.on(eventName[i], fn);
10745 this.on(eventName, fn);
10752 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
10755 * Sizes this element to its parent element's dimensions performing
10756 * neccessary box adjustments.
10757 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
10758 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
10759 * @return {Roo.Element} this
10761 fitToParent : function(monitorResize, targetParent) {
10762 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
10763 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
10764 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
10767 var p = Roo.get(targetParent || this.dom.parentNode);
10768 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
10769 if (monitorResize === true) {
10770 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
10771 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
10777 * Gets the next sibling, skipping text nodes
10778 * @return {HTMLElement} The next sibling or null
10780 getNextSibling : function(){
10781 var n = this.dom.nextSibling;
10782 while(n && n.nodeType != 1){
10789 * Gets the previous sibling, skipping text nodes
10790 * @return {HTMLElement} The previous sibling or null
10792 getPrevSibling : function(){
10793 var n = this.dom.previousSibling;
10794 while(n && n.nodeType != 1){
10795 n = n.previousSibling;
10802 * Appends the passed element(s) to this element
10803 * @param {String/HTMLElement/Array/Element/CompositeElement} el
10804 * @return {Roo.Element} this
10806 appendChild: function(el){
10813 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
10814 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
10815 * automatically generated with the specified attributes.
10816 * @param {HTMLElement} insertBefore (optional) a child element of this element
10817 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
10818 * @return {Roo.Element} The new child element
10820 createChild: function(config, insertBefore, returnDom){
10821 config = config || {tag:'div'};
10823 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
10825 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
10829 * Appends this element to the passed element
10830 * @param {String/HTMLElement/Element} el The new parent element
10831 * @return {Roo.Element} this
10833 appendTo: function(el){
10834 el = Roo.getDom(el);
10835 el.appendChild(this.dom);
10840 * Inserts this element before the passed element in the DOM
10841 * @param {String/HTMLElement/Element} el The element to insert before
10842 * @return {Roo.Element} this
10844 insertBefore: function(el){
10845 el = Roo.getDom(el);
10846 el.parentNode.insertBefore(this.dom, el);
10851 * Inserts this element after the passed element in the DOM
10852 * @param {String/HTMLElement/Element} el The element to insert after
10853 * @return {Roo.Element} this
10855 insertAfter: function(el){
10856 el = Roo.getDom(el);
10857 el.parentNode.insertBefore(this.dom, el.nextSibling);
10862 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
10863 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10864 * @return {Roo.Element} The new child
10866 insertFirst: function(el, returnDom){
10868 if(typeof el == 'object' && !el.nodeType){ // dh config
10869 return this.createChild(el, this.dom.firstChild, returnDom);
10871 el = Roo.getDom(el);
10872 this.dom.insertBefore(el, this.dom.firstChild);
10873 return !returnDom ? Roo.get(el) : el;
10878 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
10879 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10880 * @param {String} where (optional) 'before' or 'after' defaults to before
10881 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10882 * @return {Roo.Element} the inserted Element
10884 insertSibling: function(el, where, returnDom){
10885 where = where ? where.toLowerCase() : 'before';
10887 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
10889 if(typeof el == 'object' && !el.nodeType){ // dh config
10890 if(where == 'after' && !this.dom.nextSibling){
10891 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
10893 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
10897 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
10898 where == 'before' ? this.dom : this.dom.nextSibling);
10907 * Creates and wraps this element with another element
10908 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
10909 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10910 * @return {HTMLElement/Element} The newly created wrapper element
10912 wrap: function(config, returnDom){
10914 config = {tag: "div"};
10916 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
10917 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
10922 * Replaces the passed element with this element
10923 * @param {String/HTMLElement/Element} el The element to replace
10924 * @return {Roo.Element} this
10926 replace: function(el){
10928 this.insertBefore(el);
10934 * Inserts an html fragment into this element
10935 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
10936 * @param {String} html The HTML fragment
10937 * @param {Boolean} returnEl True to return an Roo.Element
10938 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
10940 insertHtml : function(where, html, returnEl){
10941 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
10942 return returnEl ? Roo.get(el) : el;
10946 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
10947 * @param {Object} o The object with the attributes
10948 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
10949 * @return {Roo.Element} this
10951 set : function(o, useSet){
10953 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
10954 for(var attr in o){
10955 if(attr == "style" || typeof o[attr] == "function") { continue; }
10957 el.className = o["cls"];
10960 el.setAttribute(attr, o[attr]);
10962 el[attr] = o[attr];
10967 Roo.DomHelper.applyStyles(el, o.style);
10973 * Convenience method for constructing a KeyMap
10974 * @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:
10975 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
10976 * @param {Function} fn The function to call
10977 * @param {Object} scope (optional) The scope of the function
10978 * @return {Roo.KeyMap} The KeyMap created
10980 addKeyListener : function(key, fn, scope){
10982 if(typeof key != "object" || key instanceof Array){
10998 return new Roo.KeyMap(this, config);
11002 * Creates a KeyMap for this element
11003 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
11004 * @return {Roo.KeyMap} The KeyMap created
11006 addKeyMap : function(config){
11007 return new Roo.KeyMap(this, config);
11011 * Returns true if this element is scrollable.
11012 * @return {Boolean}
11014 isScrollable : function(){
11015 var dom = this.dom;
11016 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
11020 * 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().
11021 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
11022 * @param {Number} value The new scroll value
11023 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
11024 * @return {Element} this
11027 scrollTo : function(side, value, animate){
11028 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
11029 if(!animate || !A){
11030 this.dom[prop] = value;
11032 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
11033 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
11039 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
11040 * within this element's scrollable range.
11041 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
11042 * @param {Number} distance How far to scroll the element in pixels
11043 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
11044 * @return {Boolean} Returns true if a scroll was triggered or false if the element
11045 * was scrolled as far as it could go.
11047 scroll : function(direction, distance, animate){
11048 if(!this.isScrollable()){
11052 var l = el.scrollLeft, t = el.scrollTop;
11053 var w = el.scrollWidth, h = el.scrollHeight;
11054 var cw = el.clientWidth, ch = el.clientHeight;
11055 direction = direction.toLowerCase();
11056 var scrolled = false;
11057 var a = this.preanim(arguments, 2);
11062 var v = Math.min(l + distance, w-cw);
11063 this.scrollTo("left", v, a);
11070 var v = Math.max(l - distance, 0);
11071 this.scrollTo("left", v, a);
11079 var v = Math.max(t - distance, 0);
11080 this.scrollTo("top", v, a);
11088 var v = Math.min(t + distance, h-ch);
11089 this.scrollTo("top", v, a);
11098 * Translates the passed page coordinates into left/top css values for this element
11099 * @param {Number/Array} x The page x or an array containing [x, y]
11100 * @param {Number} y The page y
11101 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
11103 translatePoints : function(x, y){
11104 if(typeof x == 'object' || x instanceof Array){
11105 y = x[1]; x = x[0];
11107 var p = this.getStyle('position');
11108 var o = this.getXY();
11110 var l = parseInt(this.getStyle('left'), 10);
11111 var t = parseInt(this.getStyle('top'), 10);
11114 l = (p == "relative") ? 0 : this.dom.offsetLeft;
11117 t = (p == "relative") ? 0 : this.dom.offsetTop;
11120 return {left: (x - o[0] + l), top: (y - o[1] + t)};
11124 * Returns the current scroll position of the element.
11125 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
11127 getScroll : function(){
11128 var d = this.dom, doc = document;
11129 if(d == doc || d == doc.body){
11130 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
11131 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
11132 return {left: l, top: t};
11134 return {left: d.scrollLeft, top: d.scrollTop};
11139 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
11140 * are convert to standard 6 digit hex color.
11141 * @param {String} attr The css attribute
11142 * @param {String} defaultValue The default value to use when a valid color isn't found
11143 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
11146 getColor : function(attr, defaultValue, prefix){
11147 var v = this.getStyle(attr);
11148 if(!v || v == "transparent" || v == "inherit") {
11149 return defaultValue;
11151 var color = typeof prefix == "undefined" ? "#" : prefix;
11152 if(v.substr(0, 4) == "rgb("){
11153 var rvs = v.slice(4, v.length -1).split(",");
11154 for(var i = 0; i < 3; i++){
11155 var h = parseInt(rvs[i]).toString(16);
11162 if(v.substr(0, 1) == "#"){
11163 if(v.length == 4) {
11164 for(var i = 1; i < 4; i++){
11165 var c = v.charAt(i);
11168 }else if(v.length == 7){
11169 color += v.substr(1);
11173 return(color.length > 5 ? color.toLowerCase() : defaultValue);
11177 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
11178 * gradient background, rounded corners and a 4-way shadow.
11179 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
11180 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
11181 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
11182 * @return {Roo.Element} this
11184 boxWrap : function(cls){
11185 cls = cls || 'x-box';
11186 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
11187 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
11192 * Returns the value of a namespaced attribute from the element's underlying DOM node.
11193 * @param {String} namespace The namespace in which to look for the attribute
11194 * @param {String} name The attribute name
11195 * @return {String} The attribute value
11197 getAttributeNS : Roo.isIE ? function(ns, name){
11199 var type = typeof d[ns+":"+name];
11200 if(type != 'undefined' && type != 'unknown'){
11201 return d[ns+":"+name];
11204 } : function(ns, name){
11206 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
11211 * Sets or Returns the value the dom attribute value
11212 * @param {String|Object} name The attribute name (or object to set multiple attributes)
11213 * @param {String} value (optional) The value to set the attribute to
11214 * @return {String} The attribute value
11216 attr : function(name){
11217 if (arguments.length > 1) {
11218 this.dom.setAttribute(name, arguments[1]);
11219 return arguments[1];
11221 if (typeof(name) == 'object') {
11222 for(var i in name) {
11223 this.attr(i, name[i]);
11229 if (!this.dom.hasAttribute(name)) {
11232 return this.dom.getAttribute(name);
11239 var ep = El.prototype;
11242 * Appends an event handler (Shorthand for addListener)
11243 * @param {String} eventName The type of event to append
11244 * @param {Function} fn The method the event invokes
11245 * @param {Object} scope (optional) The scope (this object) of the fn
11246 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
11249 ep.on = ep.addListener;
11250 // backwards compat
11251 ep.mon = ep.addListener;
11254 * Removes an event handler from this element (shorthand for removeListener)
11255 * @param {String} eventName the type of event to remove
11256 * @param {Function} fn the method the event invokes
11257 * @return {Roo.Element} this
11260 ep.un = ep.removeListener;
11263 * true to automatically adjust width and height settings for box-model issues (default to true)
11265 ep.autoBoxAdjust = true;
11268 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
11271 El.addUnits = function(v, defaultUnit){
11272 if(v === "" || v == "auto"){
11275 if(v === undefined){
11278 if(typeof v == "number" || !El.unitPattern.test(v)){
11279 return v + (defaultUnit || 'px');
11284 // special markup used throughout Roo when box wrapping elements
11285 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>';
11287 * Visibility mode constant - Use visibility to hide element
11293 * Visibility mode constant - Use display to hide element
11299 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
11300 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
11301 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
11313 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
11314 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
11315 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
11316 * @return {Element} The Element object
11319 El.get = function(el){
11321 if(!el){ return null; }
11322 if(typeof el == "string"){ // element id
11323 if(!(elm = document.getElementById(el))){
11326 if(ex = El.cache[el]){
11329 ex = El.cache[el] = new El(elm);
11332 }else if(el.tagName){ // dom element
11336 if(ex = El.cache[id]){
11339 ex = El.cache[id] = new El(el);
11342 }else if(el instanceof El){
11344 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
11345 // catch case where it hasn't been appended
11346 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
11349 }else if(el.isComposite){
11351 }else if(el instanceof Array){
11352 return El.select(el);
11353 }else if(el == document){
11354 // create a bogus element object representing the document object
11356 var f = function(){};
11357 f.prototype = El.prototype;
11359 docEl.dom = document;
11367 El.uncache = function(el){
11368 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
11370 delete El.cache[a[i].id || a[i]];
11376 // Garbage collection - uncache elements/purge listeners on orphaned elements
11377 // so we don't hold a reference and cause the browser to retain them
11378 El.garbageCollect = function(){
11379 if(!Roo.enableGarbageCollector){
11380 clearInterval(El.collectorThread);
11383 for(var eid in El.cache){
11384 var el = El.cache[eid], d = el.dom;
11385 // -------------------------------------------------------
11386 // Determining what is garbage:
11387 // -------------------------------------------------------
11389 // dom node is null, definitely garbage
11390 // -------------------------------------------------------
11392 // no parentNode == direct orphan, definitely garbage
11393 // -------------------------------------------------------
11394 // !d.offsetParent && !document.getElementById(eid)
11395 // display none elements have no offsetParent so we will
11396 // also try to look it up by it's id. However, check
11397 // offsetParent first so we don't do unneeded lookups.
11398 // This enables collection of elements that are not orphans
11399 // directly, but somewhere up the line they have an orphan
11401 // -------------------------------------------------------
11402 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
11403 delete El.cache[eid];
11404 if(d && Roo.enableListenerCollection){
11410 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
11414 El.Flyweight = function(dom){
11417 El.Flyweight.prototype = El.prototype;
11419 El._flyweights = {};
11421 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
11422 * the dom node can be overwritten by other code.
11423 * @param {String/HTMLElement} el The dom node or id
11424 * @param {String} named (optional) Allows for creation of named reusable flyweights to
11425 * prevent conflicts (e.g. internally Roo uses "_internal")
11427 * @return {Element} The shared Element object
11429 El.fly = function(el, named){
11430 named = named || '_global';
11431 el = Roo.getDom(el);
11435 if(!El._flyweights[named]){
11436 El._flyweights[named] = new El.Flyweight();
11438 El._flyweights[named].dom = el;
11439 return El._flyweights[named];
11443 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
11444 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
11445 * Shorthand of {@link Roo.Element#get}
11446 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
11447 * @return {Element} The Element object
11453 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
11454 * the dom node can be overwritten by other code.
11455 * Shorthand of {@link Roo.Element#fly}
11456 * @param {String/HTMLElement} el The dom node or id
11457 * @param {String} named (optional) Allows for creation of named reusable flyweights to
11458 * prevent conflicts (e.g. internally Roo uses "_internal")
11460 * @return {Element} The shared Element object
11466 // speedy lookup for elements never to box adjust
11467 var noBoxAdjust = Roo.isStrict ? {
11470 input:1, select:1, textarea:1
11472 if(Roo.isIE || Roo.isGecko){
11473 noBoxAdjust['button'] = 1;
11477 Roo.EventManager.on(window, 'unload', function(){
11479 delete El._flyweights;
11487 Roo.Element.selectorFunction = Roo.DomQuery.select;
11490 Roo.Element.select = function(selector, unique, root){
11492 if(typeof selector == "string"){
11493 els = Roo.Element.selectorFunction(selector, root);
11494 }else if(selector.length !== undefined){
11497 throw "Invalid selector";
11499 if(unique === true){
11500 return new Roo.CompositeElement(els);
11502 return new Roo.CompositeElementLite(els);
11506 * Selects elements based on the passed CSS selector to enable working on them as 1.
11507 * @param {String/Array} selector The CSS selector or an array of elements
11508 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
11509 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
11510 * @return {CompositeElementLite/CompositeElement}
11514 Roo.select = Roo.Element.select;
11531 * Ext JS Library 1.1.1
11532 * Copyright(c) 2006-2007, Ext JS, LLC.
11534 * Originally Released Under LGPL - original licence link has changed is not relivant.
11537 * <script type="text/javascript">
11542 //Notifies Element that fx methods are available
11543 Roo.enableFx = true;
11547 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
11548 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
11549 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
11550 * Element effects to work.</p><br/>
11552 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
11553 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
11554 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
11555 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
11556 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
11557 * expected results and should be done with care.</p><br/>
11559 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
11560 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
11563 ----- -----------------------------
11564 tl The top left corner
11565 t The center of the top edge
11566 tr The top right corner
11567 l The center of the left edge
11568 r The center of the right edge
11569 bl The bottom left corner
11570 b The center of the bottom edge
11571 br The bottom right corner
11573 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
11574 * below are common options that can be passed to any Fx method.</b>
11575 * @cfg {Function} callback A function called when the effect is finished
11576 * @cfg {Object} scope The scope of the effect function
11577 * @cfg {String} easing A valid Easing value for the effect
11578 * @cfg {String} afterCls A css class to apply after the effect
11579 * @cfg {Number} duration The length of time (in seconds) that the effect should last
11580 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
11581 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
11582 * effects that end with the element being visually hidden, ignored otherwise)
11583 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
11584 * a function which returns such a specification that will be applied to the Element after the effect finishes
11585 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
11586 * @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
11587 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
11591 * Slides the element into view. An anchor point can be optionally passed to set the point of
11592 * origin for the slide effect. This function automatically handles wrapping the element with
11593 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11596 // default: slide the element in from the top
11599 // custom: slide the element in from the right with a 2-second duration
11600 el.slideIn('r', { duration: 2 });
11602 // common config options shown with default values
11608 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11609 * @param {Object} options (optional) Object literal with any of the Fx config options
11610 * @return {Roo.Element} The Element
11612 slideIn : function(anchor, o){
11613 var el = this.getFxEl();
11616 el.queueFx(o, function(){
11618 anchor = anchor || "t";
11620 // fix display to visibility
11623 // restore values after effect
11624 var r = this.getFxRestore();
11625 var b = this.getBox();
11626 // fixed size for slide
11630 var wrap = this.fxWrap(r.pos, o, "hidden");
11632 var st = this.dom.style;
11633 st.visibility = "visible";
11634 st.position = "absolute";
11636 // clear out temp styles after slide and unwrap
11637 var after = function(){
11638 el.fxUnwrap(wrap, r.pos, o);
11639 st.width = r.width;
11640 st.height = r.height;
11643 // time to calc the positions
11644 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
11646 switch(anchor.toLowerCase()){
11648 wrap.setSize(b.width, 0);
11649 st.left = st.bottom = "0";
11653 wrap.setSize(0, b.height);
11654 st.right = st.top = "0";
11658 wrap.setSize(0, b.height);
11659 wrap.setX(b.right);
11660 st.left = st.top = "0";
11661 a = {width: bw, points: pt};
11664 wrap.setSize(b.width, 0);
11665 wrap.setY(b.bottom);
11666 st.left = st.top = "0";
11667 a = {height: bh, points: pt};
11670 wrap.setSize(0, 0);
11671 st.right = st.bottom = "0";
11672 a = {width: bw, height: bh};
11675 wrap.setSize(0, 0);
11676 wrap.setY(b.y+b.height);
11677 st.right = st.top = "0";
11678 a = {width: bw, height: bh, points: pt};
11681 wrap.setSize(0, 0);
11682 wrap.setXY([b.right, b.bottom]);
11683 st.left = st.top = "0";
11684 a = {width: bw, height: bh, points: pt};
11687 wrap.setSize(0, 0);
11688 wrap.setX(b.x+b.width);
11689 st.left = st.bottom = "0";
11690 a = {width: bw, height: bh, points: pt};
11693 this.dom.style.visibility = "visible";
11696 arguments.callee.anim = wrap.fxanim(a,
11706 * Slides the element out of view. An anchor point can be optionally passed to set the end point
11707 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
11708 * 'hidden') but block elements will still take up space in the document. The element must be removed
11709 * from the DOM using the 'remove' config option if desired. This function automatically handles
11710 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11713 // default: slide the element out to the top
11716 // custom: slide the element out to the right with a 2-second duration
11717 el.slideOut('r', { duration: 2 });
11719 // common config options shown with default values
11727 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11728 * @param {Object} options (optional) Object literal with any of the Fx config options
11729 * @return {Roo.Element} The Element
11731 slideOut : function(anchor, o){
11732 var el = this.getFxEl();
11735 el.queueFx(o, function(){
11737 anchor = anchor || "t";
11739 // restore values after effect
11740 var r = this.getFxRestore();
11742 var b = this.getBox();
11743 // fixed size for slide
11747 var wrap = this.fxWrap(r.pos, o, "visible");
11749 var st = this.dom.style;
11750 st.visibility = "visible";
11751 st.position = "absolute";
11755 var after = function(){
11757 el.setDisplayed(false);
11762 el.fxUnwrap(wrap, r.pos, o);
11764 st.width = r.width;
11765 st.height = r.height;
11770 var a, zero = {to: 0};
11771 switch(anchor.toLowerCase()){
11773 st.left = st.bottom = "0";
11774 a = {height: zero};
11777 st.right = st.top = "0";
11781 st.left = st.top = "0";
11782 a = {width: zero, points: {to:[b.right, b.y]}};
11785 st.left = st.top = "0";
11786 a = {height: zero, points: {to:[b.x, b.bottom]}};
11789 st.right = st.bottom = "0";
11790 a = {width: zero, height: zero};
11793 st.right = st.top = "0";
11794 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
11797 st.left = st.top = "0";
11798 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
11801 st.left = st.bottom = "0";
11802 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
11806 arguments.callee.anim = wrap.fxanim(a,
11816 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
11817 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
11818 * The element must be removed from the DOM using the 'remove' config option if desired.
11824 // common config options shown with default values
11832 * @param {Object} options (optional) Object literal with any of the Fx config options
11833 * @return {Roo.Element} The Element
11835 puff : function(o){
11836 var el = this.getFxEl();
11839 el.queueFx(o, function(){
11840 this.clearOpacity();
11843 // restore values after effect
11844 var r = this.getFxRestore();
11845 var st = this.dom.style;
11847 var after = function(){
11849 el.setDisplayed(false);
11856 el.setPositioning(r.pos);
11857 st.width = r.width;
11858 st.height = r.height;
11863 var width = this.getWidth();
11864 var height = this.getHeight();
11866 arguments.callee.anim = this.fxanim({
11867 width : {to: this.adjustWidth(width * 2)},
11868 height : {to: this.adjustHeight(height * 2)},
11869 points : {by: [-(width * .5), -(height * .5)]},
11871 fontSize: {to:200, unit: "%"}
11882 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
11883 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
11884 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
11890 // all config options shown with default values
11898 * @param {Object} options (optional) Object literal with any of the Fx config options
11899 * @return {Roo.Element} The Element
11901 switchOff : function(o){
11902 var el = this.getFxEl();
11905 el.queueFx(o, function(){
11906 this.clearOpacity();
11909 // restore values after effect
11910 var r = this.getFxRestore();
11911 var st = this.dom.style;
11913 var after = function(){
11915 el.setDisplayed(false);
11921 el.setPositioning(r.pos);
11922 st.width = r.width;
11923 st.height = r.height;
11928 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
11929 this.clearOpacity();
11933 points:{by:[0, this.getHeight() * .5]}
11934 }, o, 'motion', 0.3, 'easeIn', after);
11935 }).defer(100, this);
11942 * Highlights the Element by setting a color (applies to the background-color by default, but can be
11943 * changed using the "attr" config option) and then fading back to the original color. If no original
11944 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
11947 // default: highlight background to yellow
11950 // custom: highlight foreground text to blue for 2 seconds
11951 el.highlight("0000ff", { attr: 'color', duration: 2 });
11953 // common config options shown with default values
11954 el.highlight("ffff9c", {
11955 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
11956 endColor: (current color) or "ffffff",
11961 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
11962 * @param {Object} options (optional) Object literal with any of the Fx config options
11963 * @return {Roo.Element} The Element
11965 highlight : function(color, o){
11966 var el = this.getFxEl();
11969 el.queueFx(o, function(){
11970 color = color || "ffff9c";
11971 attr = o.attr || "backgroundColor";
11973 this.clearOpacity();
11976 var origColor = this.getColor(attr);
11977 var restoreColor = this.dom.style[attr];
11978 endColor = (o.endColor || origColor) || "ffffff";
11980 var after = function(){
11981 el.dom.style[attr] = restoreColor;
11986 a[attr] = {from: color, to: endColor};
11987 arguments.callee.anim = this.fxanim(a,
11997 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
12000 // default: a single light blue ripple
12003 // custom: 3 red ripples lasting 3 seconds total
12004 el.frame("ff0000", 3, { duration: 3 });
12006 // common config options shown with default values
12007 el.frame("C3DAF9", 1, {
12008 duration: 1 //duration of entire animation (not each individual ripple)
12009 // Note: Easing is not configurable and will be ignored if included
12012 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
12013 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
12014 * @param {Object} options (optional) Object literal with any of the Fx config options
12015 * @return {Roo.Element} The Element
12017 frame : function(color, count, o){
12018 var el = this.getFxEl();
12021 el.queueFx(o, function(){
12022 color = color || "#C3DAF9";
12023 if(color.length == 6){
12024 color = "#" + color;
12026 count = count || 1;
12027 duration = o.duration || 1;
12030 var b = this.getBox();
12031 var animFn = function(){
12032 var proxy = this.createProxy({
12035 visbility:"hidden",
12036 position:"absolute",
12037 "z-index":"35000", // yee haw
12038 border:"0px solid " + color
12041 var scale = Roo.isBorderBox ? 2 : 1;
12043 top:{from:b.y, to:b.y - 20},
12044 left:{from:b.x, to:b.x - 20},
12045 borderWidth:{from:0, to:10},
12046 opacity:{from:1, to:0},
12047 height:{from:b.height, to:(b.height + (20*scale))},
12048 width:{from:b.width, to:(b.width + (20*scale))}
12049 }, duration, function(){
12053 animFn.defer((duration/2)*1000, this);
12064 * Creates a pause before any subsequent queued effects begin. If there are
12065 * no effects queued after the pause it will have no effect.
12070 * @param {Number} seconds The length of time to pause (in seconds)
12071 * @return {Roo.Element} The Element
12073 pause : function(seconds){
12074 var el = this.getFxEl();
12077 el.queueFx(o, function(){
12078 setTimeout(function(){
12080 }, seconds * 1000);
12086 * Fade an element in (from transparent to opaque). The ending opacity can be specified
12087 * using the "endOpacity" config option.
12090 // default: fade in from opacity 0 to 100%
12093 // custom: fade in from opacity 0 to 75% over 2 seconds
12094 el.fadeIn({ endOpacity: .75, duration: 2});
12096 // common config options shown with default values
12098 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
12103 * @param {Object} options (optional) Object literal with any of the Fx config options
12104 * @return {Roo.Element} The Element
12106 fadeIn : function(o){
12107 var el = this.getFxEl();
12109 el.queueFx(o, function(){
12110 this.setOpacity(0);
12112 this.dom.style.visibility = 'visible';
12113 var to = o.endOpacity || 1;
12114 arguments.callee.anim = this.fxanim({opacity:{to:to}},
12115 o, null, .5, "easeOut", function(){
12117 this.clearOpacity();
12126 * Fade an element out (from opaque to transparent). The ending opacity can be specified
12127 * using the "endOpacity" config option.
12130 // default: fade out from the element's current opacity to 0
12133 // custom: fade out from the element's current opacity to 25% over 2 seconds
12134 el.fadeOut({ endOpacity: .25, duration: 2});
12136 // common config options shown with default values
12138 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
12145 * @param {Object} options (optional) Object literal with any of the Fx config options
12146 * @return {Roo.Element} The Element
12148 fadeOut : function(o){
12149 var el = this.getFxEl();
12151 el.queueFx(o, function(){
12152 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
12153 o, null, .5, "easeOut", function(){
12154 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
12155 this.dom.style.display = "none";
12157 this.dom.style.visibility = "hidden";
12159 this.clearOpacity();
12167 * Animates the transition of an element's dimensions from a starting height/width
12168 * to an ending height/width.
12171 // change height and width to 100x100 pixels
12172 el.scale(100, 100);
12174 // common config options shown with default values. The height and width will default to
12175 // the element's existing values if passed as null.
12178 [element's height], {
12183 * @param {Number} width The new width (pass undefined to keep the original width)
12184 * @param {Number} height The new height (pass undefined to keep the original height)
12185 * @param {Object} options (optional) Object literal with any of the Fx config options
12186 * @return {Roo.Element} The Element
12188 scale : function(w, h, o){
12189 this.shift(Roo.apply({}, o, {
12197 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
12198 * Any of these properties not specified in the config object will not be changed. This effect
12199 * requires that at least one new dimension, position or opacity setting must be passed in on
12200 * the config object in order for the function to have any effect.
12203 // slide the element horizontally to x position 200 while changing the height and opacity
12204 el.shift({ x: 200, height: 50, opacity: .8 });
12206 // common config options shown with default values.
12208 width: [element's width],
12209 height: [element's height],
12210 x: [element's x position],
12211 y: [element's y position],
12212 opacity: [element's opacity],
12217 * @param {Object} options Object literal with any of the Fx config options
12218 * @return {Roo.Element} The Element
12220 shift : function(o){
12221 var el = this.getFxEl();
12223 el.queueFx(o, function(){
12224 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
12225 if(w !== undefined){
12226 a.width = {to: this.adjustWidth(w)};
12228 if(h !== undefined){
12229 a.height = {to: this.adjustHeight(h)};
12231 if(x !== undefined || y !== undefined){
12233 x !== undefined ? x : this.getX(),
12234 y !== undefined ? y : this.getY()
12237 if(op !== undefined){
12238 a.opacity = {to: op};
12240 if(o.xy !== undefined){
12241 a.points = {to: o.xy};
12243 arguments.callee.anim = this.fxanim(a,
12244 o, 'motion', .35, "easeOut", function(){
12252 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
12253 * ending point of the effect.
12256 // default: slide the element downward while fading out
12259 // custom: slide the element out to the right with a 2-second duration
12260 el.ghost('r', { duration: 2 });
12262 // common config options shown with default values
12270 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
12271 * @param {Object} options (optional) Object literal with any of the Fx config options
12272 * @return {Roo.Element} The Element
12274 ghost : function(anchor, o){
12275 var el = this.getFxEl();
12278 el.queueFx(o, function(){
12279 anchor = anchor || "b";
12281 // restore values after effect
12282 var r = this.getFxRestore();
12283 var w = this.getWidth(),
12284 h = this.getHeight();
12286 var st = this.dom.style;
12288 var after = function(){
12290 el.setDisplayed(false);
12296 el.setPositioning(r.pos);
12297 st.width = r.width;
12298 st.height = r.height;
12303 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
12304 switch(anchor.toLowerCase()){
12331 arguments.callee.anim = this.fxanim(a,
12341 * Ensures that all effects queued after syncFx is called on the element are
12342 * run concurrently. This is the opposite of {@link #sequenceFx}.
12343 * @return {Roo.Element} The Element
12345 syncFx : function(){
12346 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
12355 * Ensures that all effects queued after sequenceFx is called on the element are
12356 * run in sequence. This is the opposite of {@link #syncFx}.
12357 * @return {Roo.Element} The Element
12359 sequenceFx : function(){
12360 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
12362 concurrent : false,
12369 nextFx : function(){
12370 var ef = this.fxQueue[0];
12377 * Returns true if the element has any effects actively running or queued, else returns false.
12378 * @return {Boolean} True if element has active effects, else false
12380 hasActiveFx : function(){
12381 return this.fxQueue && this.fxQueue[0];
12385 * Stops any running effects and clears the element's internal effects queue if it contains
12386 * any additional effects that haven't started yet.
12387 * @return {Roo.Element} The Element
12389 stopFx : function(){
12390 if(this.hasActiveFx()){
12391 var cur = this.fxQueue[0];
12392 if(cur && cur.anim && cur.anim.isAnimated()){
12393 this.fxQueue = [cur]; // clear out others
12394 cur.anim.stop(true);
12401 beforeFx : function(o){
12402 if(this.hasActiveFx() && !o.concurrent){
12413 * Returns true if the element is currently blocking so that no other effect can be queued
12414 * until this effect is finished, else returns false if blocking is not set. This is commonly
12415 * used to ensure that an effect initiated by a user action runs to completion prior to the
12416 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
12417 * @return {Boolean} True if blocking, else false
12419 hasFxBlock : function(){
12420 var q = this.fxQueue;
12421 return q && q[0] && q[0].block;
12425 queueFx : function(o, fn){
12429 if(!this.hasFxBlock()){
12430 Roo.applyIf(o, this.fxDefaults);
12432 var run = this.beforeFx(o);
12433 fn.block = o.block;
12434 this.fxQueue.push(fn);
12446 fxWrap : function(pos, o, vis){
12448 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
12451 wrapXY = this.getXY();
12453 var div = document.createElement("div");
12454 div.style.visibility = vis;
12455 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
12456 wrap.setPositioning(pos);
12457 if(wrap.getStyle("position") == "static"){
12458 wrap.position("relative");
12460 this.clearPositioning('auto');
12462 wrap.dom.appendChild(this.dom);
12464 wrap.setXY(wrapXY);
12471 fxUnwrap : function(wrap, pos, o){
12472 this.clearPositioning();
12473 this.setPositioning(pos);
12475 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
12481 getFxRestore : function(){
12482 var st = this.dom.style;
12483 return {pos: this.getPositioning(), width: st.width, height : st.height};
12487 afterFx : function(o){
12489 this.applyStyles(o.afterStyle);
12492 this.addClass(o.afterCls);
12494 if(o.remove === true){
12497 Roo.callback(o.callback, o.scope, [this]);
12499 this.fxQueue.shift();
12505 getFxEl : function(){ // support for composite element fx
12506 return Roo.get(this.dom);
12510 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
12511 animType = animType || 'run';
12513 var anim = Roo.lib.Anim[animType](
12515 (opt.duration || defaultDur) || .35,
12516 (opt.easing || defaultEase) || 'easeOut',
12518 Roo.callback(cb, this);
12527 // backwords compat
12528 Roo.Fx.resize = Roo.Fx.scale;
12530 //When included, Roo.Fx is automatically applied to Element so that all basic
12531 //effects are available directly via the Element API
12532 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
12534 * Ext JS Library 1.1.1
12535 * Copyright(c) 2006-2007, Ext JS, LLC.
12537 * Originally Released Under LGPL - original licence link has changed is not relivant.
12540 * <script type="text/javascript">
12545 * @class Roo.CompositeElement
12546 * Standard composite class. Creates a Roo.Element for every element in the collection.
12548 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12549 * actions will be performed on all the elements in this collection.</b>
12551 * All methods return <i>this</i> and can be chained.
12553 var els = Roo.select("#some-el div.some-class", true);
12554 // or select directly from an existing element
12555 var el = Roo.get('some-el');
12556 el.select('div.some-class', true);
12558 els.setWidth(100); // all elements become 100 width
12559 els.hide(true); // all elements fade out and hide
12561 els.setWidth(100).hide(true);
12564 Roo.CompositeElement = function(els){
12565 this.elements = [];
12566 this.addElements(els);
12568 Roo.CompositeElement.prototype = {
12570 addElements : function(els){
12574 if(typeof els == "string"){
12575 els = Roo.Element.selectorFunction(els);
12577 var yels = this.elements;
12578 var index = yels.length-1;
12579 for(var i = 0, len = els.length; i < len; i++) {
12580 yels[++index] = Roo.get(els[i]);
12586 * Clears this composite and adds the elements returned by the passed selector.
12587 * @param {String/Array} els A string CSS selector, an array of elements or an element
12588 * @return {CompositeElement} this
12590 fill : function(els){
12591 this.elements = [];
12597 * Filters this composite to only elements that match the passed selector.
12598 * @param {String} selector A string CSS selector
12599 * @param {Boolean} inverse return inverse filter (not matches)
12600 * @return {CompositeElement} this
12602 filter : function(selector, inverse){
12604 inverse = inverse || false;
12605 this.each(function(el){
12606 var match = inverse ? !el.is(selector) : el.is(selector);
12608 els[els.length] = el.dom;
12615 invoke : function(fn, args){
12616 var els = this.elements;
12617 for(var i = 0, len = els.length; i < len; i++) {
12618 Roo.Element.prototype[fn].apply(els[i], args);
12623 * Adds elements to this composite.
12624 * @param {String/Array} els A string CSS selector, an array of elements or an element
12625 * @return {CompositeElement} this
12627 add : function(els){
12628 if(typeof els == "string"){
12629 this.addElements(Roo.Element.selectorFunction(els));
12630 }else if(els.length !== undefined){
12631 this.addElements(els);
12633 this.addElements([els]);
12638 * Calls the passed function passing (el, this, index) for each element in this composite.
12639 * @param {Function} fn The function to call
12640 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12641 * @return {CompositeElement} this
12643 each : function(fn, scope){
12644 var els = this.elements;
12645 for(var i = 0, len = els.length; i < len; i++){
12646 if(fn.call(scope || els[i], els[i], this, i) === false) {
12654 * Returns the Element object at the specified index
12655 * @param {Number} index
12656 * @return {Roo.Element}
12658 item : function(index){
12659 return this.elements[index] || null;
12663 * Returns the first Element
12664 * @return {Roo.Element}
12666 first : function(){
12667 return this.item(0);
12671 * Returns the last Element
12672 * @return {Roo.Element}
12675 return this.item(this.elements.length-1);
12679 * Returns the number of elements in this composite
12682 getCount : function(){
12683 return this.elements.length;
12687 * Returns true if this composite contains the passed element
12690 contains : function(el){
12691 return this.indexOf(el) !== -1;
12695 * Returns true if this composite contains the passed element
12698 indexOf : function(el){
12699 return this.elements.indexOf(Roo.get(el));
12704 * Removes the specified element(s).
12705 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
12706 * or an array of any of those.
12707 * @param {Boolean} removeDom (optional) True to also remove the element from the document
12708 * @return {CompositeElement} this
12710 removeElement : function(el, removeDom){
12711 if(el instanceof Array){
12712 for(var i = 0, len = el.length; i < len; i++){
12713 this.removeElement(el[i]);
12717 var index = typeof el == 'number' ? el : this.indexOf(el);
12720 var d = this.elements[index];
12724 d.parentNode.removeChild(d);
12727 this.elements.splice(index, 1);
12733 * Replaces the specified element with the passed element.
12734 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
12736 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
12737 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
12738 * @return {CompositeElement} this
12740 replaceElement : function(el, replacement, domReplace){
12741 var index = typeof el == 'number' ? el : this.indexOf(el);
12744 this.elements[index].replaceWith(replacement);
12746 this.elements.splice(index, 1, Roo.get(replacement))
12753 * Removes all elements.
12755 clear : function(){
12756 this.elements = [];
12760 Roo.CompositeElement.createCall = function(proto, fnName){
12761 if(!proto[fnName]){
12762 proto[fnName] = function(){
12763 return this.invoke(fnName, arguments);
12767 for(var fnName in Roo.Element.prototype){
12768 if(typeof Roo.Element.prototype[fnName] == "function"){
12769 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
12775 * Ext JS Library 1.1.1
12776 * Copyright(c) 2006-2007, Ext JS, LLC.
12778 * Originally Released Under LGPL - original licence link has changed is not relivant.
12781 * <script type="text/javascript">
12785 * @class Roo.CompositeElementLite
12786 * @extends Roo.CompositeElement
12787 * Flyweight composite class. Reuses the same Roo.Element for element operations.
12789 var els = Roo.select("#some-el div.some-class");
12790 // or select directly from an existing element
12791 var el = Roo.get('some-el');
12792 el.select('div.some-class');
12794 els.setWidth(100); // all elements become 100 width
12795 els.hide(true); // all elements fade out and hide
12797 els.setWidth(100).hide(true);
12798 </code></pre><br><br>
12799 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12800 * actions will be performed on all the elements in this collection.</b>
12802 Roo.CompositeElementLite = function(els){
12803 Roo.CompositeElementLite.superclass.constructor.call(this, els);
12804 this.el = new Roo.Element.Flyweight();
12806 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
12807 addElements : function(els){
12809 if(els instanceof Array){
12810 this.elements = this.elements.concat(els);
12812 var yels = this.elements;
12813 var index = yels.length-1;
12814 for(var i = 0, len = els.length; i < len; i++) {
12815 yels[++index] = els[i];
12821 invoke : function(fn, args){
12822 var els = this.elements;
12824 for(var i = 0, len = els.length; i < len; i++) {
12826 Roo.Element.prototype[fn].apply(el, args);
12831 * Returns a flyweight Element of the dom element object at the specified index
12832 * @param {Number} index
12833 * @return {Roo.Element}
12835 item : function(index){
12836 if(!this.elements[index]){
12839 this.el.dom = this.elements[index];
12843 // fixes scope with flyweight
12844 addListener : function(eventName, handler, scope, opt){
12845 var els = this.elements;
12846 for(var i = 0, len = els.length; i < len; i++) {
12847 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
12853 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
12854 * passed is the flyweight (shared) Roo.Element instance, so if you require a
12855 * a reference to the dom node, use el.dom.</b>
12856 * @param {Function} fn The function to call
12857 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12858 * @return {CompositeElement} this
12860 each : function(fn, scope){
12861 var els = this.elements;
12863 for(var i = 0, len = els.length; i < len; i++){
12865 if(fn.call(scope || el, el, this, i) === false){
12872 indexOf : function(el){
12873 return this.elements.indexOf(Roo.getDom(el));
12876 replaceElement : function(el, replacement, domReplace){
12877 var index = typeof el == 'number' ? el : this.indexOf(el);
12879 replacement = Roo.getDom(replacement);
12881 var d = this.elements[index];
12882 d.parentNode.insertBefore(replacement, d);
12883 d.parentNode.removeChild(d);
12885 this.elements.splice(index, 1, replacement);
12890 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
12894 * Ext JS Library 1.1.1
12895 * Copyright(c) 2006-2007, Ext JS, LLC.
12897 * Originally Released Under LGPL - original licence link has changed is not relivant.
12900 * <script type="text/javascript">
12906 * @class Roo.data.Connection
12907 * @extends Roo.util.Observable
12908 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
12909 * either to a configured URL, or to a URL specified at request time.
12911 * Requests made by this class are asynchronous, and will return immediately. No data from
12912 * the server will be available to the statement immediately following the {@link #request} call.
12913 * To process returned data, use a callback in the request options object, or an event listener.
12915 * Note: If you are doing a file upload, you will not get a normal response object sent back to
12916 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
12917 * The response object is created using the innerHTML of the IFRAME's document as the responseText
12918 * property and, if present, the IFRAME's XML document as the responseXML property.
12920 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
12921 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
12922 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
12923 * standard DOM methods.
12925 * @param {Object} config a configuration object.
12927 Roo.data.Connection = function(config){
12928 Roo.apply(this, config);
12931 * @event beforerequest
12932 * Fires before a network request is made to retrieve a data object.
12933 * @param {Connection} conn This Connection object.
12934 * @param {Object} options The options config object passed to the {@link #request} method.
12936 "beforerequest" : true,
12938 * @event requestcomplete
12939 * Fires if the request was successfully completed.
12940 * @param {Connection} conn This Connection object.
12941 * @param {Object} response The XHR object containing the response data.
12942 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12943 * @param {Object} options The options config object passed to the {@link #request} method.
12945 "requestcomplete" : true,
12947 * @event requestexception
12948 * Fires if an error HTTP status was returned from the server.
12949 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
12950 * @param {Connection} conn This Connection object.
12951 * @param {Object} response The XHR object containing the response data.
12952 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12953 * @param {Object} options The options config object passed to the {@link #request} method.
12955 "requestexception" : true
12957 Roo.data.Connection.superclass.constructor.call(this);
12960 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
12962 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
12965 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
12966 * extra parameters to each request made by this object. (defaults to undefined)
12969 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
12970 * to each request made by this object. (defaults to undefined)
12973 * @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)
12976 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12980 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
12986 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12989 disableCaching: true,
12992 * Sends an HTTP request to a remote server.
12993 * @param {Object} options An object which may contain the following properties:<ul>
12994 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
12995 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
12996 * request, a url encoded string or a function to call to get either.</li>
12997 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
12998 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
12999 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
13000 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
13001 * <li>options {Object} The parameter to the request call.</li>
13002 * <li>success {Boolean} True if the request succeeded.</li>
13003 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
13005 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
13006 * The callback is passed the following parameters:<ul>
13007 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
13008 * <li>options {Object} The parameter to the request call.</li>
13010 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
13011 * The callback is passed the following parameters:<ul>
13012 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
13013 * <li>options {Object} The parameter to the request call.</li>
13015 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
13016 * for the callback function. Defaults to the browser window.</li>
13017 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
13018 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
13019 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
13020 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
13021 * params for the post data. Any params will be appended to the URL.</li>
13022 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
13024 * @return {Number} transactionId
13026 request : function(o){
13027 if(this.fireEvent("beforerequest", this, o) !== false){
13030 if(typeof p == "function"){
13031 p = p.call(o.scope||window, o);
13033 if(typeof p == "object"){
13034 p = Roo.urlEncode(o.params);
13036 if(this.extraParams){
13037 var extras = Roo.urlEncode(this.extraParams);
13038 p = p ? (p + '&' + extras) : extras;
13041 var url = o.url || this.url;
13042 if(typeof url == 'function'){
13043 url = url.call(o.scope||window, o);
13047 var form = Roo.getDom(o.form);
13048 url = url || form.action;
13050 var enctype = form.getAttribute("enctype");
13053 return this.doFormDataUpload(o, url);
13056 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
13057 return this.doFormUpload(o, p, url);
13059 var f = Roo.lib.Ajax.serializeForm(form);
13060 p = p ? (p + '&' + f) : f;
13063 if (!o.form && o.formData) {
13064 o.formData = o.formData === true ? new FormData() : o.formData;
13065 for (var k in o.params) {
13066 o.formData.append(k,o.params[k]);
13069 return this.doFormDataUpload(o, url);
13073 var hs = o.headers;
13074 if(this.defaultHeaders){
13075 hs = Roo.apply(hs || {}, this.defaultHeaders);
13082 success: this.handleResponse,
13083 failure: this.handleFailure,
13085 argument: {options: o},
13086 timeout : o.timeout || this.timeout
13089 var method = o.method||this.method||(p ? "POST" : "GET");
13091 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
13092 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
13095 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
13099 }else if(this.autoAbort !== false){
13103 if((method == 'GET' && p) || o.xmlData){
13104 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
13107 Roo.lib.Ajax.useDefaultHeader = typeof(o.headers) == 'undefined' || typeof(o.headers['Content-Type']) == 'undefined';
13108 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
13109 Roo.lib.Ajax.useDefaultHeader == true;
13110 return this.transId;
13112 Roo.callback(o.callback, o.scope, [o, null, null]);
13118 * Determine whether this object has a request outstanding.
13119 * @param {Number} transactionId (Optional) defaults to the last transaction
13120 * @return {Boolean} True if there is an outstanding request.
13122 isLoading : function(transId){
13124 return Roo.lib.Ajax.isCallInProgress(transId);
13126 return this.transId ? true : false;
13131 * Aborts any outstanding request.
13132 * @param {Number} transactionId (Optional) defaults to the last transaction
13134 abort : function(transId){
13135 if(transId || this.isLoading()){
13136 Roo.lib.Ajax.abort(transId || this.transId);
13141 handleResponse : function(response){
13142 this.transId = false;
13143 var options = response.argument.options;
13144 response.argument = options ? options.argument : null;
13145 this.fireEvent("requestcomplete", this, response, options);
13146 Roo.callback(options.success, options.scope, [response, options]);
13147 Roo.callback(options.callback, options.scope, [options, true, response]);
13151 handleFailure : function(response, e){
13152 this.transId = false;
13153 var options = response.argument.options;
13154 response.argument = options ? options.argument : null;
13155 this.fireEvent("requestexception", this, response, options, e);
13156 Roo.callback(options.failure, options.scope, [response, options]);
13157 Roo.callback(options.callback, options.scope, [options, false, response]);
13161 doFormUpload : function(o, ps, url){
13163 var frame = document.createElement('iframe');
13166 frame.className = 'x-hidden';
13168 frame.src = Roo.SSL_SECURE_URL;
13170 document.body.appendChild(frame);
13173 document.frames[id].name = id;
13176 var form = Roo.getDom(o.form);
13178 form.method = 'POST';
13179 form.enctype = form.encoding = 'multipart/form-data';
13185 if(ps){ // add dynamic params
13187 ps = Roo.urlDecode(ps, false);
13189 if(ps.hasOwnProperty(k)){
13190 hd = document.createElement('input');
13191 hd.type = 'hidden';
13194 form.appendChild(hd);
13201 var r = { // bogus response object
13206 r.argument = o ? o.argument : null;
13211 doc = frame.contentWindow.document;
13213 doc = (frame.contentDocument || window.frames[id].document);
13215 if(doc && doc.body){
13216 r.responseText = doc.body.innerHTML;
13218 if(doc && doc.XMLDocument){
13219 r.responseXML = doc.XMLDocument;
13221 r.responseXML = doc;
13228 Roo.EventManager.removeListener(frame, 'load', cb, this);
13230 this.fireEvent("requestcomplete", this, r, o);
13231 Roo.callback(o.success, o.scope, [r, o]);
13232 Roo.callback(o.callback, o.scope, [o, true, r]);
13234 setTimeout(function(){document.body.removeChild(frame);}, 100);
13237 Roo.EventManager.on(frame, 'load', cb, this);
13240 if(hiddens){ // remove dynamic params
13241 for(var i = 0, len = hiddens.length; i < len; i++){
13242 form.removeChild(hiddens[i]);
13246 // this is a 'formdata version???'
13249 doFormDataUpload : function(o, url)
13253 var form = Roo.getDom(o.form);
13254 form.enctype = form.encoding = 'multipart/form-data';
13255 formData = o.formData === true ? new FormData(form) : o.formData;
13257 formData = o.formData === true ? new FormData() : o.formData;
13262 success: this.handleResponse,
13263 failure: this.handleFailure,
13265 argument: {options: o},
13266 timeout : o.timeout || this.timeout
13269 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
13273 }else if(this.autoAbort !== false){
13277 //Roo.lib.Ajax.defaultPostHeader = null;
13278 Roo.lib.Ajax.useDefaultHeader = false;
13279 this.transId = Roo.lib.Ajax.request( "POST", url, cb, formData, o);
13280 Roo.lib.Ajax.useDefaultHeader = true;
13288 * Ext JS Library 1.1.1
13289 * Copyright(c) 2006-2007, Ext JS, LLC.
13291 * Originally Released Under LGPL - original licence link has changed is not relivant.
13294 * <script type="text/javascript">
13298 * Global Ajax request class.
13301 * @extends Roo.data.Connection
13304 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
13305 * @cfg {Object} extraParams An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
13306 * @cfg {Object} defaultHeaders An object containing request headers which are added to each request made by this object. (defaults to undefined)
13307 * @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)
13308 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
13309 * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
13310 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
13312 Roo.Ajax = new Roo.data.Connection({
13321 * Serialize the passed form into a url encoded string
13323 * @param {String/HTMLElement} form
13326 serializeForm : function(form){
13327 return Roo.lib.Ajax.serializeForm(form);
13331 * Ext JS Library 1.1.1
13332 * Copyright(c) 2006-2007, Ext JS, LLC.
13334 * Originally Released Under LGPL - original licence link has changed is not relivant.
13337 * <script type="text/javascript">
13342 * @class Roo.UpdateManager
13343 * @extends Roo.util.Observable
13344 * Provides AJAX-style update for Element object.<br><br>
13347 * // Get it from a Roo.Element object
13348 * var el = Roo.get("foo");
13349 * var mgr = el.getUpdateManager();
13350 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
13352 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
13354 * // or directly (returns the same UpdateManager instance)
13355 * var mgr = new Roo.UpdateManager("myElementId");
13356 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
13357 * mgr.on("update", myFcnNeedsToKnow);
13359 // short handed call directly from the element object
13360 Roo.get("foo").load({
13364 text: "Loading Foo..."
13368 * Create new UpdateManager directly.
13369 * @param {String/HTMLElement/Roo.Element} el The element to update
13370 * @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).
13372 Roo.UpdateManager = function(el, forceNew){
13374 if(!forceNew && el.updateManager){
13375 return el.updateManager;
13378 * The Element object
13379 * @type Roo.Element
13383 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
13386 this.defaultUrl = null;
13390 * @event beforeupdate
13391 * Fired before an update is made, return false from your handler and the update is cancelled.
13392 * @param {Roo.Element} el
13393 * @param {String/Object/Function} url
13394 * @param {String/Object} params
13396 "beforeupdate": true,
13399 * Fired after successful update is made.
13400 * @param {Roo.Element} el
13401 * @param {Object} oResponseObject The response Object
13406 * Fired on update failure.
13407 * @param {Roo.Element} el
13408 * @param {Object} oResponseObject The response Object
13412 var d = Roo.UpdateManager.defaults;
13414 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
13417 this.sslBlankUrl = d.sslBlankUrl;
13419 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
13422 this.disableCaching = d.disableCaching;
13424 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
13427 this.indicatorText = d.indicatorText;
13429 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
13432 this.showLoadIndicator = d.showLoadIndicator;
13434 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
13437 this.timeout = d.timeout;
13440 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
13443 this.loadScripts = d.loadScripts;
13446 * Transaction object of current executing transaction
13448 this.transaction = null;
13453 this.autoRefreshProcId = null;
13455 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
13458 this.refreshDelegate = this.refresh.createDelegate(this);
13460 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
13463 this.updateDelegate = this.update.createDelegate(this);
13465 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
13468 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
13472 this.successDelegate = this.processSuccess.createDelegate(this);
13476 this.failureDelegate = this.processFailure.createDelegate(this);
13478 if(!this.renderer){
13480 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
13482 this.renderer = new Roo.UpdateManager.BasicRenderer();
13485 Roo.UpdateManager.superclass.constructor.call(this);
13488 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
13490 * Get the Element this UpdateManager is bound to
13491 * @return {Roo.Element} The element
13493 getEl : function(){
13497 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
13498 * @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:
13501 url: "your-url.php",<br/>
13502 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
13503 callback: yourFunction,<br/>
13504 scope: yourObject, //(optional scope) <br/>
13505 discardUrl: false, <br/>
13506 nocache: false,<br/>
13507 text: "Loading...",<br/>
13509 scripts: false<br/>
13512 * The only required property is url. The optional properties nocache, text and scripts
13513 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
13514 * @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}
13515 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13516 * @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.
13518 update : function(url, params, callback, discardUrl){
13519 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
13520 var method = this.method,
13522 if(typeof url == "object"){ // must be config object
13525 params = params || cfg.params;
13526 callback = callback || cfg.callback;
13527 discardUrl = discardUrl || cfg.discardUrl;
13528 if(callback && cfg.scope){
13529 callback = callback.createDelegate(cfg.scope);
13531 if(typeof cfg.method != "undefined"){method = cfg.method;};
13532 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
13533 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
13534 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
13535 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
13537 this.showLoading();
13539 this.defaultUrl = url;
13541 if(typeof url == "function"){
13542 url = url.call(this);
13545 method = method || (params ? "POST" : "GET");
13546 if(method == "GET"){
13547 url = this.prepareUrl(url);
13550 var o = Roo.apply(cfg ||{}, {
13553 success: this.successDelegate,
13554 failure: this.failureDelegate,
13555 callback: undefined,
13556 timeout: (this.timeout*1000),
13557 argument: {"url": url, "form": null, "callback": callback, "params": params}
13559 Roo.log("updated manager called with timeout of " + o.timeout);
13560 this.transaction = Roo.Ajax.request(o);
13565 * 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.
13566 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
13567 * @param {String/HTMLElement} form The form Id or form element
13568 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
13569 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
13570 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13572 formUpdate : function(form, url, reset, callback){
13573 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
13574 if(typeof url == "function"){
13575 url = url.call(this);
13577 form = Roo.getDom(form);
13578 this.transaction = Roo.Ajax.request({
13581 success: this.successDelegate,
13582 failure: this.failureDelegate,
13583 timeout: (this.timeout*1000),
13584 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
13586 this.showLoading.defer(1, this);
13591 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
13592 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13594 refresh : function(callback){
13595 if(this.defaultUrl == null){
13598 this.update(this.defaultUrl, null, callback, true);
13602 * Set this element to auto refresh.
13603 * @param {Number} interval How often to update (in seconds).
13604 * @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)
13605 * @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}
13606 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13607 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
13609 startAutoRefresh : function(interval, url, params, callback, refreshNow){
13611 this.update(url || this.defaultUrl, params, callback, true);
13613 if(this.autoRefreshProcId){
13614 clearInterval(this.autoRefreshProcId);
13616 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
13620 * Stop auto refresh on this element.
13622 stopAutoRefresh : function(){
13623 if(this.autoRefreshProcId){
13624 clearInterval(this.autoRefreshProcId);
13625 delete this.autoRefreshProcId;
13629 isAutoRefreshing : function(){
13630 return this.autoRefreshProcId ? true : false;
13633 * Called to update the element to "Loading" state. Override to perform custom action.
13635 showLoading : function(){
13636 if(this.showLoadIndicator){
13637 this.el.update(this.indicatorText);
13642 * Adds unique parameter to query string if disableCaching = true
13645 prepareUrl : function(url){
13646 if(this.disableCaching){
13647 var append = "_dc=" + (new Date().getTime());
13648 if(url.indexOf("?") !== -1){
13649 url += "&" + append;
13651 url += "?" + append;
13660 processSuccess : function(response){
13661 this.transaction = null;
13662 if(response.argument.form && response.argument.reset){
13663 try{ // put in try/catch since some older FF releases had problems with this
13664 response.argument.form.reset();
13667 if(this.loadScripts){
13668 this.renderer.render(this.el, response, this,
13669 this.updateComplete.createDelegate(this, [response]));
13671 this.renderer.render(this.el, response, this);
13672 this.updateComplete(response);
13676 updateComplete : function(response){
13677 this.fireEvent("update", this.el, response);
13678 if(typeof response.argument.callback == "function"){
13679 response.argument.callback(this.el, true, response);
13686 processFailure : function(response){
13687 this.transaction = null;
13688 this.fireEvent("failure", this.el, response);
13689 if(typeof response.argument.callback == "function"){
13690 response.argument.callback(this.el, false, response);
13695 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
13696 * @param {Object} renderer The object implementing the render() method
13698 setRenderer : function(renderer){
13699 this.renderer = renderer;
13702 getRenderer : function(){
13703 return this.renderer;
13707 * Set the defaultUrl used for updates
13708 * @param {String/Function} defaultUrl The url or a function to call to get the url
13710 setDefaultUrl : function(defaultUrl){
13711 this.defaultUrl = defaultUrl;
13715 * Aborts the executing transaction
13717 abort : function(){
13718 if(this.transaction){
13719 Roo.Ajax.abort(this.transaction);
13724 * Returns true if an update is in progress
13725 * @return {Boolean}
13727 isUpdating : function(){
13728 if(this.transaction){
13729 return Roo.Ajax.isLoading(this.transaction);
13736 * @class Roo.UpdateManager.defaults
13737 * @static (not really - but it helps the doc tool)
13738 * The defaults collection enables customizing the default properties of UpdateManager
13740 Roo.UpdateManager.defaults = {
13742 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
13748 * True to process scripts by default (Defaults to false).
13751 loadScripts : false,
13754 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
13757 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
13759 * Whether to append unique parameter on get request to disable caching (Defaults to false).
13762 disableCaching : false,
13764 * Whether to show indicatorText when loading (Defaults to true).
13767 showLoadIndicator : true,
13769 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
13772 indicatorText : '<div class="loading-indicator">Loading...</div>'
13776 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
13778 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
13779 * @param {String/HTMLElement/Roo.Element} el The element to update
13780 * @param {String} url The url
13781 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
13782 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
13785 * @member Roo.UpdateManager
13787 Roo.UpdateManager.updateElement = function(el, url, params, options){
13788 var um = Roo.get(el, true).getUpdateManager();
13789 Roo.apply(um, options);
13790 um.update(url, params, options ? options.callback : null);
13792 // alias for backwards compat
13793 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
13795 * @class Roo.UpdateManager.BasicRenderer
13796 * Default Content renderer. Updates the elements innerHTML with the responseText.
13798 Roo.UpdateManager.BasicRenderer = function(){};
13800 Roo.UpdateManager.BasicRenderer.prototype = {
13802 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
13803 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
13804 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
13805 * @param {Roo.Element} el The element being rendered
13806 * @param {Object} response The YUI Connect response object
13807 * @param {UpdateManager} updateManager The calling update manager
13808 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
13810 render : function(el, response, updateManager, callback){
13811 el.update(response.responseText, updateManager.loadScripts, callback);
13817 * (c)) Alan Knowles
13823 * @class Roo.DomTemplate
13824 * @extends Roo.Template
13825 * An effort at a dom based template engine..
13827 * Similar to XTemplate, except it uses dom parsing to create the template..
13829 * Supported features:
13834 {a_variable} - output encoded.
13835 {a_variable.format:("Y-m-d")} - call a method on the variable
13836 {a_variable:raw} - unencoded output
13837 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
13838 {a_variable:this.method_on_template(...)} - call a method on the template object.
13843 <div roo-for="a_variable or condition.."></div>
13844 <div roo-if="a_variable or condition"></div>
13845 <div roo-exec="some javascript"></div>
13846 <div roo-name="named_template"></div>
13851 Roo.DomTemplate = function()
13853 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
13860 Roo.extend(Roo.DomTemplate, Roo.Template, {
13862 * id counter for sub templates.
13866 * flag to indicate if dom parser is inside a pre,
13867 * it will strip whitespace if not.
13872 * The various sub templates
13880 * basic tag replacing syntax
13883 * // you can fake an object call by doing this
13887 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
13888 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
13890 iterChild : function (node, method) {
13892 var oldPre = this.inPre;
13893 if (node.tagName == 'PRE') {
13896 for( var i = 0; i < node.childNodes.length; i++) {
13897 method.call(this, node.childNodes[i]);
13899 this.inPre = oldPre;
13905 * compile the template
13907 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
13910 compile: function()
13914 // covert the html into DOM...
13918 doc = document.implementation.createHTMLDocument("");
13919 doc.documentElement.innerHTML = this.html ;
13920 div = doc.documentElement;
13922 // old IE... - nasty -- it causes all sorts of issues.. with
13923 // images getting pulled from server..
13924 div = document.createElement('div');
13925 div.innerHTML = this.html;
13927 //doc.documentElement.innerHTML = htmlBody
13933 this.iterChild(div, function(n) {_t.compileNode(n, true); });
13935 var tpls = this.tpls;
13937 // create a top level template from the snippet..
13939 //Roo.log(div.innerHTML);
13946 body : div.innerHTML,
13959 Roo.each(tpls, function(tp){
13960 this.compileTpl(tp);
13961 this.tpls[tp.id] = tp;
13964 this.master = tpls[0];
13970 compileNode : function(node, istop) {
13975 // skip anything not a tag..
13976 if (node.nodeType != 1) {
13977 if (node.nodeType == 3 && !this.inPre) {
13978 // reduce white space..
13979 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
14002 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
14003 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
14004 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
14005 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
14011 // just itterate children..
14012 this.iterChild(node,this.compileNode);
14015 tpl.uid = this.id++;
14016 tpl.value = node.getAttribute('roo-' + tpl.attr);
14017 node.removeAttribute('roo-'+ tpl.attr);
14018 if (tpl.attr != 'name') {
14019 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
14020 node.parentNode.replaceChild(placeholder, node);
14023 var placeholder = document.createElement('span');
14024 placeholder.className = 'roo-tpl-' + tpl.value;
14025 node.parentNode.replaceChild(placeholder, node);
14028 // parent now sees '{domtplXXXX}
14029 this.iterChild(node,this.compileNode);
14031 // we should now have node body...
14032 var div = document.createElement('div');
14033 div.appendChild(node);
14035 // this has the unfortunate side effect of converting tagged attributes
14036 // eg. href="{...}" into %7C...%7D
14037 // this has been fixed by searching for those combo's although it's a bit hacky..
14040 tpl.body = div.innerHTML;
14047 switch (tpl.value) {
14048 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
14049 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
14050 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
14055 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
14059 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
14063 tpl.id = tpl.value; // replace non characters???
14069 this.tpls.push(tpl);
14079 * Compile a segment of the template into a 'sub-template'
14085 compileTpl : function(tpl)
14087 var fm = Roo.util.Format;
14088 var useF = this.disableFormats !== true;
14090 var sep = Roo.isGecko ? "+\n" : ",\n";
14092 var undef = function(str) {
14093 Roo.debug && Roo.log("Property not found :" + str);
14097 //Roo.log(tpl.body);
14101 var fn = function(m, lbrace, name, format, args)
14104 //Roo.log(arguments);
14105 args = args ? args.replace(/\\'/g,"'") : args;
14106 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
14107 if (typeof(format) == 'undefined') {
14108 format = 'htmlEncode';
14110 if (format == 'raw' ) {
14114 if(name.substr(0, 6) == 'domtpl'){
14115 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
14118 // build an array of options to determine if value is undefined..
14120 // basically get 'xxxx.yyyy' then do
14121 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
14122 // (function () { Roo.log("Property not found"); return ''; })() :
14127 Roo.each(name.split('.'), function(st) {
14128 lookfor += (lookfor.length ? '.': '') + st;
14129 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
14132 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
14135 if(format && useF){
14137 args = args ? ',' + args : "";
14139 if(format.substr(0, 5) != "this."){
14140 format = "fm." + format + '(';
14142 format = 'this.call("'+ format.substr(5) + '", ';
14146 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
14149 if (args && args.length) {
14150 // called with xxyx.yuu:(test,test)
14152 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
14154 // raw.. - :raw modifier..
14155 return "'"+ sep + udef_st + name + ")"+sep+"'";
14159 // branched to use + in gecko and [].join() in others
14161 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
14162 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
14165 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
14166 body.push(tpl.body.replace(/(\r\n|\n)/g,
14167 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
14168 body.push("'].join('');};};");
14169 body = body.join('');
14172 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
14174 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
14181 * same as applyTemplate, except it's done to one of the subTemplates
14182 * when using named templates, you can do:
14184 * var str = pl.applySubTemplate('your-name', values);
14187 * @param {Number} id of the template
14188 * @param {Object} values to apply to template
14189 * @param {Object} parent (normaly the instance of this object)
14191 applySubTemplate : function(id, values, parent)
14195 var t = this.tpls[id];
14199 if(t.ifCall && !t.ifCall.call(this, values, parent)){
14200 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
14204 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
14211 if(t.execCall && t.execCall.call(this, values, parent)){
14215 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
14221 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
14222 parent = t.target ? values : parent;
14223 if(t.forCall && vs instanceof Array){
14225 for(var i = 0, len = vs.length; i < len; i++){
14227 buf[buf.length] = t.compiled.call(this, vs[i], parent);
14229 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
14231 //Roo.log(t.compiled);
14235 return buf.join('');
14238 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
14243 return t.compiled.call(this, vs, parent);
14245 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
14247 //Roo.log(t.compiled);
14255 applyTemplate : function(values){
14256 return this.master.compiled.call(this, values, {});
14257 //var s = this.subs;
14260 apply : function(){
14261 return this.applyTemplate.apply(this, arguments);
14266 Roo.DomTemplate.from = function(el){
14267 el = Roo.getDom(el);
14268 return new Roo.Domtemplate(el.value || el.innerHTML);
14271 * Ext JS Library 1.1.1
14272 * Copyright(c) 2006-2007, Ext JS, LLC.
14274 * Originally Released Under LGPL - original licence link has changed is not relivant.
14277 * <script type="text/javascript">
14281 * @class Roo.util.DelayedTask
14282 * Provides a convenient method of performing setTimeout where a new
14283 * timeout cancels the old timeout. An example would be performing validation on a keypress.
14284 * You can use this class to buffer
14285 * the keypress events for a certain number of milliseconds, and perform only if they stop
14286 * for that amount of time.
14287 * @constructor The parameters to this constructor serve as defaults and are not required.
14288 * @param {Function} fn (optional) The default function to timeout
14289 * @param {Object} scope (optional) The default scope of that timeout
14290 * @param {Array} args (optional) The default Array of arguments
14292 Roo.util.DelayedTask = function(fn, scope, args){
14293 var id = null, d, t;
14295 var call = function(){
14296 var now = new Date().getTime();
14300 fn.apply(scope, args || []);
14304 * Cancels any pending timeout and queues a new one
14305 * @param {Number} delay The milliseconds to delay
14306 * @param {Function} newFn (optional) Overrides function passed to constructor
14307 * @param {Object} newScope (optional) Overrides scope passed to constructor
14308 * @param {Array} newArgs (optional) Overrides args passed to constructor
14310 this.delay = function(delay, newFn, newScope, newArgs){
14311 if(id && delay != d){
14315 t = new Date().getTime();
14317 scope = newScope || scope;
14318 args = newArgs || args;
14320 id = setInterval(call, d);
14325 * Cancel the last queued timeout
14327 this.cancel = function(){
14335 * Ext JS Library 1.1.1
14336 * Copyright(c) 2006-2007, Ext JS, LLC.
14338 * Originally Released Under LGPL - original licence link has changed is not relivant.
14341 * <script type="text/javascript">
14344 * @class Roo.util.TaskRunner
14345 * Manage background tasks - not sure why this is better that setInterval?
14350 Roo.util.TaskRunner = function(interval){
14351 interval = interval || 10;
14352 var tasks = [], removeQueue = [];
14354 var running = false;
14356 var stopThread = function(){
14362 var startThread = function(){
14365 id = setInterval(runTasks, interval);
14369 var removeTask = function(task){
14370 removeQueue.push(task);
14376 var runTasks = function(){
14377 if(removeQueue.length > 0){
14378 for(var i = 0, len = removeQueue.length; i < len; i++){
14379 tasks.remove(removeQueue[i]);
14382 if(tasks.length < 1){
14387 var now = new Date().getTime();
14388 for(var i = 0, len = tasks.length; i < len; ++i){
14390 var itime = now - t.taskRunTime;
14391 if(t.interval <= itime){
14392 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
14393 t.taskRunTime = now;
14394 if(rt === false || t.taskRunCount === t.repeat){
14399 if(t.duration && t.duration <= (now - t.taskStartTime)){
14406 * Queues a new task.
14407 * @param {Object} task
14409 * Task property : interval = how frequent to run.
14410 * Task object should implement
14412 * Task object may implement
14413 * function onStop()
14415 this.start = function(task){
14417 task.taskStartTime = new Date().getTime();
14418 task.taskRunTime = 0;
14419 task.taskRunCount = 0;
14425 * @param {Object} task
14427 this.stop = function(task){
14434 this.stopAll = function(){
14436 for(var i = 0, len = tasks.length; i < len; i++){
14437 if(tasks[i].onStop){
14446 Roo.TaskMgr = new Roo.util.TaskRunner();/*
14448 * Ext JS Library 1.1.1
14449 * Copyright(c) 2006-2007, Ext JS, LLC.
14451 * Originally Released Under LGPL - original licence link has changed is not relivant.
14454 * <script type="text/javascript">
14459 * @class Roo.util.MixedCollection
14460 * @extends Roo.util.Observable
14461 * A Collection class that maintains both numeric indexes and keys and exposes events.
14463 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
14464 * collection (defaults to false)
14465 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
14466 * and return the key value for that item. This is used when available to look up the key on items that
14467 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
14468 * equivalent to providing an implementation for the {@link #getKey} method.
14470 Roo.util.MixedCollection = function(allowFunctions, keyFn){
14478 * Fires when the collection is cleared.
14483 * Fires when an item is added to the collection.
14484 * @param {Number} index The index at which the item was added.
14485 * @param {Object} o The item added.
14486 * @param {String} key The key associated with the added item.
14491 * Fires when an item is replaced in the collection.
14492 * @param {String} key he key associated with the new added.
14493 * @param {Object} old The item being replaced.
14494 * @param {Object} new The new item.
14499 * Fires when an item is removed from the collection.
14500 * @param {Object} o The item being removed.
14501 * @param {String} key (optional) The key associated with the removed item.
14506 this.allowFunctions = allowFunctions === true;
14508 this.getKey = keyFn;
14510 Roo.util.MixedCollection.superclass.constructor.call(this);
14513 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
14514 allowFunctions : false,
14517 * Adds an item to the collection.
14518 * @param {String} key The key to associate with the item
14519 * @param {Object} o The item to add.
14520 * @return {Object} The item added.
14522 add : function(key, o){
14523 if(arguments.length == 1){
14525 key = this.getKey(o);
14527 if(typeof key == "undefined" || key === null){
14529 this.items.push(o);
14530 this.keys.push(null);
14532 var old = this.map[key];
14534 return this.replace(key, o);
14537 this.items.push(o);
14539 this.keys.push(key);
14541 this.fireEvent("add", this.length-1, o, key);
14546 * MixedCollection has a generic way to fetch keys if you implement getKey.
14549 var mc = new Roo.util.MixedCollection();
14550 mc.add(someEl.dom.id, someEl);
14551 mc.add(otherEl.dom.id, otherEl);
14555 var mc = new Roo.util.MixedCollection();
14556 mc.getKey = function(el){
14562 // or via the constructor
14563 var mc = new Roo.util.MixedCollection(false, function(el){
14569 * @param o {Object} The item for which to find the key.
14570 * @return {Object} The key for the passed item.
14572 getKey : function(o){
14577 * Replaces an item in the collection.
14578 * @param {String} key The key associated with the item to replace, or the item to replace.
14579 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
14580 * @return {Object} The new item.
14582 replace : function(key, o){
14583 if(arguments.length == 1){
14585 key = this.getKey(o);
14587 var old = this.item(key);
14588 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
14589 return this.add(key, o);
14591 var index = this.indexOfKey(key);
14592 this.items[index] = o;
14594 this.fireEvent("replace", key, old, o);
14599 * Adds all elements of an Array or an Object to the collection.
14600 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
14601 * an Array of values, each of which are added to the collection.
14603 addAll : function(objs){
14604 if(arguments.length > 1 || objs instanceof Array){
14605 var args = arguments.length > 1 ? arguments : objs;
14606 for(var i = 0, len = args.length; i < len; i++){
14610 for(var key in objs){
14611 if(this.allowFunctions || typeof objs[key] != "function"){
14612 this.add(key, objs[key]);
14619 * Executes the specified function once for every item in the collection, passing each
14620 * item as the first and only parameter. returning false from the function will stop the iteration.
14621 * @param {Function} fn The function to execute for each item.
14622 * @param {Object} scope (optional) The scope in which to execute the function.
14624 each : function(fn, scope){
14625 var items = [].concat(this.items); // each safe for removal
14626 for(var i = 0, len = items.length; i < len; i++){
14627 if(fn.call(scope || items[i], items[i], i, len) === false){
14634 * Executes the specified function once for every key in the collection, passing each
14635 * key, and its associated item as the first two parameters.
14636 * @param {Function} fn The function to execute for each item.
14637 * @param {Object} scope (optional) The scope in which to execute the function.
14639 eachKey : function(fn, scope){
14640 for(var i = 0, len = this.keys.length; i < len; i++){
14641 fn.call(scope || window, this.keys[i], this.items[i], i, len);
14646 * Returns the first item in the collection which elicits a true return value from the
14647 * passed selection function.
14648 * @param {Function} fn The selection function to execute for each item.
14649 * @param {Object} scope (optional) The scope in which to execute the function.
14650 * @return {Object} The first item in the collection which returned true from the selection function.
14652 find : function(fn, scope){
14653 for(var i = 0, len = this.items.length; i < len; i++){
14654 if(fn.call(scope || window, this.items[i], this.keys[i])){
14655 return this.items[i];
14662 * Inserts an item at the specified index in the collection.
14663 * @param {Number} index The index to insert the item at.
14664 * @param {String} key The key to associate with the new item, or the item itself.
14665 * @param {Object} o (optional) If the second parameter was a key, the new item.
14666 * @return {Object} The item inserted.
14668 insert : function(index, key, o){
14669 if(arguments.length == 2){
14671 key = this.getKey(o);
14673 if(index >= this.length){
14674 return this.add(key, o);
14677 this.items.splice(index, 0, o);
14678 if(typeof key != "undefined" && key != null){
14681 this.keys.splice(index, 0, key);
14682 this.fireEvent("add", index, o, key);
14687 * Removed an item from the collection.
14688 * @param {Object} o The item to remove.
14689 * @return {Object} The item removed.
14691 remove : function(o){
14692 return this.removeAt(this.indexOf(o));
14696 * Remove an item from a specified index in the collection.
14697 * @param {Number} index The index within the collection of the item to remove.
14699 removeAt : function(index){
14700 if(index < this.length && index >= 0){
14702 var o = this.items[index];
14703 this.items.splice(index, 1);
14704 var key = this.keys[index];
14705 if(typeof key != "undefined"){
14706 delete this.map[key];
14708 this.keys.splice(index, 1);
14709 this.fireEvent("remove", o, key);
14714 * Removed an item associated with the passed key fom the collection.
14715 * @param {String} key The key of the item to remove.
14717 removeKey : function(key){
14718 return this.removeAt(this.indexOfKey(key));
14722 * Returns the number of items in the collection.
14723 * @return {Number} the number of items in the collection.
14725 getCount : function(){
14726 return this.length;
14730 * Returns index within the collection of the passed Object.
14731 * @param {Object} o The item to find the index of.
14732 * @return {Number} index of the item.
14734 indexOf : function(o){
14735 if(!this.items.indexOf){
14736 for(var i = 0, len = this.items.length; i < len; i++){
14737 if(this.items[i] == o) {
14743 return this.items.indexOf(o);
14748 * Returns index within the collection of the passed key.
14749 * @param {String} key The key to find the index of.
14750 * @return {Number} index of the key.
14752 indexOfKey : function(key){
14753 if(!this.keys.indexOf){
14754 for(var i = 0, len = this.keys.length; i < len; i++){
14755 if(this.keys[i] == key) {
14761 return this.keys.indexOf(key);
14766 * Returns the item associated with the passed key OR index. Key has priority over index.
14767 * @param {String/Number} key The key or index of the item.
14768 * @return {Object} The item associated with the passed key.
14770 item : function(key){
14771 if (key === 'length') {
14774 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
14775 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
14779 * Returns the item at the specified index.
14780 * @param {Number} index The index of the item.
14783 itemAt : function(index){
14784 return this.items[index];
14788 * Returns the item associated with the passed key.
14789 * @param {String/Number} key The key of the item.
14790 * @return {Object} The item associated with the passed key.
14792 key : function(key){
14793 return this.map[key];
14797 * Returns true if the collection contains the passed Object as an item.
14798 * @param {Object} o The Object to look for in the collection.
14799 * @return {Boolean} True if the collection contains the Object as an item.
14801 contains : function(o){
14802 return this.indexOf(o) != -1;
14806 * Returns true if the collection contains the passed Object as a key.
14807 * @param {String} key The key to look for in the collection.
14808 * @return {Boolean} True if the collection contains the Object as a key.
14810 containsKey : function(key){
14811 return typeof this.map[key] != "undefined";
14815 * Removes all items from the collection.
14817 clear : function(){
14822 this.fireEvent("clear");
14826 * Returns the first item in the collection.
14827 * @return {Object} the first item in the collection..
14829 first : function(){
14830 return this.items[0];
14834 * Returns the last item in the collection.
14835 * @return {Object} the last item in the collection..
14838 return this.items[this.length-1];
14841 _sort : function(property, dir, fn){
14842 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
14843 fn = fn || function(a, b){
14846 var c = [], k = this.keys, items = this.items;
14847 for(var i = 0, len = items.length; i < len; i++){
14848 c[c.length] = {key: k[i], value: items[i], index: i};
14850 c.sort(function(a, b){
14851 var v = fn(a[property], b[property]) * dsc;
14853 v = (a.index < b.index ? -1 : 1);
14857 for(var i = 0, len = c.length; i < len; i++){
14858 items[i] = c[i].value;
14861 this.fireEvent("sort", this);
14865 * Sorts this collection with the passed comparison function
14866 * @param {String} direction (optional) "ASC" or "DESC"
14867 * @param {Function} fn (optional) comparison function
14869 sort : function(dir, fn){
14870 this._sort("value", dir, fn);
14874 * Sorts this collection by keys
14875 * @param {String} direction (optional) "ASC" or "DESC"
14876 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
14878 keySort : function(dir, fn){
14879 this._sort("key", dir, fn || function(a, b){
14880 return String(a).toUpperCase()-String(b).toUpperCase();
14885 * Returns a range of items in this collection
14886 * @param {Number} startIndex (optional) defaults to 0
14887 * @param {Number} endIndex (optional) default to the last item
14888 * @return {Array} An array of items
14890 getRange : function(start, end){
14891 var items = this.items;
14892 if(items.length < 1){
14895 start = start || 0;
14896 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
14899 for(var i = start; i <= end; i++) {
14900 r[r.length] = items[i];
14903 for(var i = start; i >= end; i--) {
14904 r[r.length] = items[i];
14911 * Filter the <i>objects</i> in this collection by a specific property.
14912 * Returns a new collection that has been filtered.
14913 * @param {String} property A property on your objects
14914 * @param {String/RegExp} value Either string that the property values
14915 * should start with or a RegExp to test against the property
14916 * @return {MixedCollection} The new filtered collection
14918 filter : function(property, value){
14919 if(!value.exec){ // not a regex
14920 value = String(value);
14921 if(value.length == 0){
14922 return this.clone();
14924 value = new RegExp("^" + Roo.escapeRe(value), "i");
14926 return this.filterBy(function(o){
14927 return o && value.test(o[property]);
14932 * Filter by a function. * Returns a new collection that has been filtered.
14933 * The passed function will be called with each
14934 * object in the collection. If the function returns true, the value is included
14935 * otherwise it is filtered.
14936 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
14937 * @param {Object} scope (optional) The scope of the function (defaults to this)
14938 * @return {MixedCollection} The new filtered collection
14940 filterBy : function(fn, scope){
14941 var r = new Roo.util.MixedCollection();
14942 r.getKey = this.getKey;
14943 var k = this.keys, it = this.items;
14944 for(var i = 0, len = it.length; i < len; i++){
14945 if(fn.call(scope||this, it[i], k[i])){
14946 r.add(k[i], it[i]);
14953 * Creates a duplicate of this collection
14954 * @return {MixedCollection}
14956 clone : function(){
14957 var r = new Roo.util.MixedCollection();
14958 var k = this.keys, it = this.items;
14959 for(var i = 0, len = it.length; i < len; i++){
14960 r.add(k[i], it[i]);
14962 r.getKey = this.getKey;
14967 * Returns the item associated with the passed key or index.
14969 * @param {String/Number} key The key or index of the item.
14970 * @return {Object} The item associated with the passed key.
14972 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
14974 * Ext JS Library 1.1.1
14975 * Copyright(c) 2006-2007, Ext JS, LLC.
14977 * Originally Released Under LGPL - original licence link has changed is not relivant.
14980 * <script type="text/javascript">
14983 * @class Roo.util.JSON
14984 * Modified version of Douglas Crockford"s json.js that doesn"t
14985 * mess with the Object prototype
14986 * http://www.json.org/js.html
14989 Roo.util.JSON = new (function(){
14990 var useHasOwn = {}.hasOwnProperty ? true : false;
14992 // crashes Safari in some instances
14993 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
14995 var pad = function(n) {
14996 return n < 10 ? "0" + n : n;
15009 var encodeString = function(s){
15010 if (/["\\\x00-\x1f]/.test(s)) {
15011 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
15016 c = b.charCodeAt();
15018 Math.floor(c / 16).toString(16) +
15019 (c % 16).toString(16);
15022 return '"' + s + '"';
15025 var encodeArray = function(o){
15026 var a = ["["], b, i, l = o.length, v;
15027 for (i = 0; i < l; i += 1) {
15029 switch (typeof v) {
15038 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
15046 var encodeDate = function(o){
15047 return '"' + o.getFullYear() + "-" +
15048 pad(o.getMonth() + 1) + "-" +
15049 pad(o.getDate()) + "T" +
15050 pad(o.getHours()) + ":" +
15051 pad(o.getMinutes()) + ":" +
15052 pad(o.getSeconds()) + '"';
15056 * Encodes an Object, Array or other value
15057 * @param {Mixed} o The variable to encode
15058 * @return {String} The JSON string
15060 this.encode = function(o)
15062 // should this be extended to fully wrap stringify..
15064 if(typeof o == "undefined" || o === null){
15066 }else if(o instanceof Array){
15067 return encodeArray(o);
15068 }else if(o instanceof Date){
15069 return encodeDate(o);
15070 }else if(typeof o == "string"){
15071 return encodeString(o);
15072 }else if(typeof o == "number"){
15073 return isFinite(o) ? String(o) : "null";
15074 }else if(typeof o == "boolean"){
15077 var a = ["{"], b, i, v;
15079 if(!useHasOwn || o.hasOwnProperty(i)) {
15081 switch (typeof v) {
15090 a.push(this.encode(i), ":",
15091 v === null ? "null" : this.encode(v));
15102 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
15103 * @param {String} json The JSON string
15104 * @return {Object} The resulting object
15106 this.decode = function(json){
15108 return /** eval:var:json */ eval("(" + json + ')');
15112 * Shorthand for {@link Roo.util.JSON#encode}
15113 * @member Roo encode
15115 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
15117 * Shorthand for {@link Roo.util.JSON#decode}
15118 * @member Roo decode
15120 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
15123 * Ext JS Library 1.1.1
15124 * Copyright(c) 2006-2007, Ext JS, LLC.
15126 * Originally Released Under LGPL - original licence link has changed is not relivant.
15129 * <script type="text/javascript">
15133 * @class Roo.util.Format
15134 * Reusable data formatting functions
15137 Roo.util.Format = function(){
15138 var trimRe = /^\s+|\s+$/g;
15141 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
15142 * @param {String} value The string to truncate
15143 * @param {Number} length The maximum length to allow before truncating
15144 * @return {String} The converted text
15146 ellipsis : function(value, len){
15147 if(value && value.length > len){
15148 return value.substr(0, len-3)+"...";
15154 * Checks a reference and converts it to empty string if it is undefined
15155 * @param {Mixed} value Reference to check
15156 * @return {Mixed} Empty string if converted, otherwise the original value
15158 undef : function(value){
15159 return typeof value != "undefined" ? value : "";
15163 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
15164 * @param {String} value The string to encode
15165 * @return {String} The encoded text
15167 htmlEncode : function(value){
15168 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
15172 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
15173 * @param {String} value The string to decode
15174 * @return {String} The decoded text
15176 htmlDecode : function(value){
15177 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
15181 * Trims any whitespace from either side of a string
15182 * @param {String} value The text to trim
15183 * @return {String} The trimmed text
15185 trim : function(value){
15186 return String(value).replace(trimRe, "");
15190 * Returns a substring from within an original string
15191 * @param {String} value The original text
15192 * @param {Number} start The start index of the substring
15193 * @param {Number} length The length of the substring
15194 * @return {String} The substring
15196 substr : function(value, start, length){
15197 return String(value).substr(start, length);
15201 * Converts a string to all lower case letters
15202 * @param {String} value The text to convert
15203 * @return {String} The converted text
15205 lowercase : function(value){
15206 return String(value).toLowerCase();
15210 * Converts a string to all upper case letters
15211 * @param {String} value The text to convert
15212 * @return {String} The converted text
15214 uppercase : function(value){
15215 return String(value).toUpperCase();
15219 * Converts the first character only of a string to upper case
15220 * @param {String} value The text to convert
15221 * @return {String} The converted text
15223 capitalize : function(value){
15224 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
15228 call : function(value, fn){
15229 if(arguments.length > 2){
15230 var args = Array.prototype.slice.call(arguments, 2);
15231 args.unshift(value);
15233 return /** eval:var:value */ eval(fn).apply(window, args);
15235 /** eval:var:value */
15236 return /** eval:var:value */ eval(fn).call(window, value);
15242 * safer version of Math.toFixed..??/
15243 * @param {Number/String} value The numeric value to format
15244 * @param {Number/String} value Decimal places
15245 * @return {String} The formatted currency string
15247 toFixed : function(v, n)
15249 // why not use to fixed - precision is buggered???
15251 return Math.round(v-0);
15253 var fact = Math.pow(10,n+1);
15254 v = (Math.round((v-0)*fact))/fact;
15255 var z = (''+fact).substring(2);
15256 if (v == Math.floor(v)) {
15257 return Math.floor(v) + '.' + z;
15260 // now just padd decimals..
15261 var ps = String(v).split('.');
15262 var fd = (ps[1] + z);
15263 var r = fd.substring(0,n);
15264 var rm = fd.substring(n);
15266 return ps[0] + '.' + r;
15268 r*=1; // turn it into a number;
15270 if (String(r).length != n) {
15273 r = String(r).substring(1); // chop the end off.
15276 return ps[0] + '.' + r;
15281 * Format a number as US currency
15282 * @param {Number/String} value The numeric value to format
15283 * @return {String} The formatted currency string
15285 usMoney : function(v){
15286 return '$' + Roo.util.Format.number(v);
15291 * eventually this should probably emulate php's number_format
15292 * @param {Number/String} value The numeric value to format
15293 * @param {Number} decimals number of decimal places
15294 * @param {String} delimiter for thousands (default comma)
15295 * @return {String} The formatted currency string
15297 number : function(v, decimals, thousandsDelimiter)
15299 // multiply and round.
15300 decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
15301 thousandsDelimiter = typeof(thousandsDelimiter) == 'undefined' ? ',' : thousandsDelimiter;
15303 var mul = Math.pow(10, decimals);
15304 var zero = String(mul).substring(1);
15305 v = (Math.round((v-0)*mul))/mul;
15307 // if it's '0' number.. then
15309 //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
15311 var ps = v.split('.');
15314 var r = /(\d+)(\d{3})/;
15317 if(thousandsDelimiter.length != 0) {
15318 whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsDelimiter );
15323 (decimals ? ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
15324 // does not have decimals
15325 (decimals ? ('.' + zero) : '');
15328 return whole + sub ;
15332 * Parse a value into a formatted date using the specified format pattern.
15333 * @param {Mixed} value The value to format
15334 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
15335 * @return {String} The formatted date string
15337 date : function(v, format){
15341 if(!(v instanceof Date)){
15342 v = new Date(Date.parse(v));
15344 return v.dateFormat(format || Roo.util.Format.defaults.date);
15348 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
15349 * @param {String} format Any valid date format string
15350 * @return {Function} The date formatting function
15352 dateRenderer : function(format){
15353 return function(v){
15354 return Roo.util.Format.date(v, format);
15359 stripTagsRE : /<\/?[^>]+>/gi,
15362 * Strips all HTML tags
15363 * @param {Mixed} value The text from which to strip tags
15364 * @return {String} The stripped text
15366 stripTags : function(v){
15367 return !v ? v : String(v).replace(this.stripTagsRE, "");
15371 * Size in Mb,Gb etc.
15372 * @param {Number} value The number to be formated
15373 * @param {number} decimals how many decimal places
15374 * @return {String} the formated string
15376 size : function(value, decimals)
15378 var sizes = ['b', 'k', 'M', 'G', 'T'];
15382 var i = parseInt(Math.floor(Math.log(value) / Math.log(1024)));
15383 return Roo.util.Format.number(value/ Math.pow(1024, i) ,decimals) + sizes[i];
15390 Roo.util.Format.defaults = {
15394 * Ext JS Library 1.1.1
15395 * Copyright(c) 2006-2007, Ext JS, LLC.
15397 * Originally Released Under LGPL - original licence link has changed is not relivant.
15400 * <script type="text/javascript">
15407 * @class Roo.MasterTemplate
15408 * @extends Roo.Template
15409 * Provides a template that can have child templates. The syntax is:
15411 var t = new Roo.MasterTemplate(
15412 '<select name="{name}">',
15413 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
15416 t.add('options', {value: 'foo', text: 'bar'});
15417 // or you can add multiple child elements in one shot
15418 t.addAll('options', [
15419 {value: 'foo', text: 'bar'},
15420 {value: 'foo2', text: 'bar2'},
15421 {value: 'foo3', text: 'bar3'}
15423 // then append, applying the master template values
15424 t.append('my-form', {name: 'my-select'});
15426 * A name attribute for the child template is not required if you have only one child
15427 * template or you want to refer to them by index.
15429 Roo.MasterTemplate = function(){
15430 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
15431 this.originalHtml = this.html;
15433 var m, re = this.subTemplateRe;
15436 while(m = re.exec(this.html)){
15437 var name = m[1], content = m[2];
15442 tpl : new Roo.Template(content)
15445 st[name] = st[subIndex];
15447 st[subIndex].tpl.compile();
15448 st[subIndex].tpl.call = this.call.createDelegate(this);
15451 this.subCount = subIndex;
15454 Roo.extend(Roo.MasterTemplate, Roo.Template, {
15456 * The regular expression used to match sub templates
15460 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
15463 * Applies the passed values to a child template.
15464 * @param {String/Number} name (optional) The name or index of the child template
15465 * @param {Array/Object} values The values to be applied to the template
15466 * @return {MasterTemplate} this
15468 add : function(name, values){
15469 if(arguments.length == 1){
15470 values = arguments[0];
15473 var s = this.subs[name];
15474 s.buffer[s.buffer.length] = s.tpl.apply(values);
15479 * Applies all the passed values to a child template.
15480 * @param {String/Number} name (optional) The name or index of the child template
15481 * @param {Array} values The values to be applied to the template, this should be an array of objects.
15482 * @param {Boolean} reset (optional) True to reset the template first
15483 * @return {MasterTemplate} this
15485 fill : function(name, values, reset){
15487 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
15495 for(var i = 0, len = values.length; i < len; i++){
15496 this.add(name, values[i]);
15502 * Resets the template for reuse
15503 * @return {MasterTemplate} this
15505 reset : function(){
15507 for(var i = 0; i < this.subCount; i++){
15513 applyTemplate : function(values){
15515 var replaceIndex = -1;
15516 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
15517 return s[++replaceIndex].buffer.join("");
15519 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
15522 apply : function(){
15523 return this.applyTemplate.apply(this, arguments);
15526 compile : function(){return this;}
15530 * Alias for fill().
15533 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
15535 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
15536 * var tpl = Roo.MasterTemplate.from('element-id');
15537 * @param {String/HTMLElement} el
15538 * @param {Object} config
15541 Roo.MasterTemplate.from = function(el, config){
15542 el = Roo.getDom(el);
15543 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
15546 * Ext JS Library 1.1.1
15547 * Copyright(c) 2006-2007, Ext JS, LLC.
15549 * Originally Released Under LGPL - original licence link has changed is not relivant.
15552 * <script type="text/javascript">
15557 * @class Roo.util.CSS
15558 * Utility class for manipulating CSS rules
15562 Roo.util.CSS = function(){
15564 var doc = document;
15566 var camelRe = /(-[a-z])/gi;
15567 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
15571 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
15572 * tag and appended to the HEAD of the document.
15573 * @param {String|Object} cssText The text containing the css rules
15574 * @param {String} id An id to add to the stylesheet for later removal
15575 * @return {StyleSheet}
15577 createStyleSheet : function(cssText, id){
15579 var head = doc.getElementsByTagName("head")[0];
15580 var nrules = doc.createElement("style");
15581 nrules.setAttribute("type", "text/css");
15583 nrules.setAttribute("id", id);
15585 if (typeof(cssText) != 'string') {
15586 // support object maps..
15587 // not sure if this a good idea..
15588 // perhaps it should be merged with the general css handling
15589 // and handle js style props.
15590 var cssTextNew = [];
15591 for(var n in cssText) {
15593 for(var k in cssText[n]) {
15594 citems.push( k + ' : ' +cssText[n][k] + ';' );
15596 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
15599 cssText = cssTextNew.join("\n");
15605 head.appendChild(nrules);
15606 ss = nrules.styleSheet;
15607 ss.cssText = cssText;
15610 nrules.appendChild(doc.createTextNode(cssText));
15612 nrules.cssText = cssText;
15614 head.appendChild(nrules);
15615 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
15617 this.cacheStyleSheet(ss);
15622 * Removes a style or link tag by id
15623 * @param {String} id The id of the tag
15625 removeStyleSheet : function(id){
15626 var existing = doc.getElementById(id);
15628 existing.parentNode.removeChild(existing);
15633 * Dynamically swaps an existing stylesheet reference for a new one
15634 * @param {String} id The id of an existing link tag to remove
15635 * @param {String} url The href of the new stylesheet to include
15637 swapStyleSheet : function(id, url){
15638 this.removeStyleSheet(id);
15639 var ss = doc.createElement("link");
15640 ss.setAttribute("rel", "stylesheet");
15641 ss.setAttribute("type", "text/css");
15642 ss.setAttribute("id", id);
15643 ss.setAttribute("href", url);
15644 doc.getElementsByTagName("head")[0].appendChild(ss);
15648 * Refresh the rule cache if you have dynamically added stylesheets
15649 * @return {Object} An object (hash) of rules indexed by selector
15651 refreshCache : function(){
15652 return this.getRules(true);
15656 cacheStyleSheet : function(stylesheet){
15660 try{// try catch for cross domain access issue
15661 var ssRules = stylesheet.cssRules || stylesheet.rules;
15662 for(var j = ssRules.length-1; j >= 0; --j){
15663 rules[ssRules[j].selectorText] = ssRules[j];
15669 * Gets all css rules for the document
15670 * @param {Boolean} refreshCache true to refresh the internal cache
15671 * @return {Object} An object (hash) of rules indexed by selector
15673 getRules : function(refreshCache){
15674 if(rules == null || refreshCache){
15676 var ds = doc.styleSheets;
15677 for(var i =0, len = ds.length; i < len; i++){
15679 this.cacheStyleSheet(ds[i]);
15687 * Gets an an individual CSS rule by selector(s)
15688 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
15689 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
15690 * @return {CSSRule} The CSS rule or null if one is not found
15692 getRule : function(selector, refreshCache){
15693 var rs = this.getRules(refreshCache);
15694 if(!(selector instanceof Array)){
15695 return rs[selector];
15697 for(var i = 0; i < selector.length; i++){
15698 if(rs[selector[i]]){
15699 return rs[selector[i]];
15707 * Updates a rule property
15708 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
15709 * @param {String} property The css property
15710 * @param {String} value The new value for the property
15711 * @return {Boolean} true If a rule was found and updated
15713 updateRule : function(selector, property, value){
15714 if(!(selector instanceof Array)){
15715 var rule = this.getRule(selector);
15717 rule.style[property.replace(camelRe, camelFn)] = value;
15721 for(var i = 0; i < selector.length; i++){
15722 if(this.updateRule(selector[i], property, value)){
15732 * Ext JS Library 1.1.1
15733 * Copyright(c) 2006-2007, Ext JS, LLC.
15735 * Originally Released Under LGPL - original licence link has changed is not relivant.
15738 * <script type="text/javascript">
15744 * @class Roo.util.ClickRepeater
15745 * @extends Roo.util.Observable
15747 * A wrapper class which can be applied to any element. Fires a "click" event while the
15748 * mouse is pressed. The interval between firings may be specified in the config but
15749 * defaults to 10 milliseconds.
15751 * Optionally, a CSS class may be applied to the element during the time it is pressed.
15753 * @cfg {String/HTMLElement/Element} el The element to act as a button.
15754 * @cfg {Number} delay The initial delay before the repeating event begins firing.
15755 * Similar to an autorepeat key delay.
15756 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
15757 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
15758 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
15759 * "interval" and "delay" are ignored. "immediate" is honored.
15760 * @cfg {Boolean} preventDefault True to prevent the default click event
15761 * @cfg {Boolean} stopDefault True to stop the default click event
15764 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
15765 * 2007-02-02 jvs Renamed to ClickRepeater
15766 * 2007-02-03 jvs Modifications for FF Mac and Safari
15769 * @param {String/HTMLElement/Element} el The element to listen on
15770 * @param {Object} config
15772 Roo.util.ClickRepeater = function(el, config)
15774 this.el = Roo.get(el);
15775 this.el.unselectable();
15777 Roo.apply(this, config);
15782 * Fires when the mouse button is depressed.
15783 * @param {Roo.util.ClickRepeater} this
15785 "mousedown" : true,
15788 * Fires on a specified interval during the time the element is pressed.
15789 * @param {Roo.util.ClickRepeater} this
15794 * Fires when the mouse key is released.
15795 * @param {Roo.util.ClickRepeater} this
15800 this.el.on("mousedown", this.handleMouseDown, this);
15801 if(this.preventDefault || this.stopDefault){
15802 this.el.on("click", function(e){
15803 if(this.preventDefault){
15804 e.preventDefault();
15806 if(this.stopDefault){
15812 // allow inline handler
15814 this.on("click", this.handler, this.scope || this);
15817 Roo.util.ClickRepeater.superclass.constructor.call(this);
15820 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
15823 preventDefault : true,
15824 stopDefault : false,
15828 handleMouseDown : function(){
15829 clearTimeout(this.timer);
15831 if(this.pressClass){
15832 this.el.addClass(this.pressClass);
15834 this.mousedownTime = new Date();
15836 Roo.get(document).on("mouseup", this.handleMouseUp, this);
15837 this.el.on("mouseout", this.handleMouseOut, this);
15839 this.fireEvent("mousedown", this);
15840 this.fireEvent("click", this);
15842 this.timer = this.click.defer(this.delay || this.interval, this);
15846 click : function(){
15847 this.fireEvent("click", this);
15848 this.timer = this.click.defer(this.getInterval(), this);
15852 getInterval: function(){
15853 if(!this.accelerate){
15854 return this.interval;
15856 var pressTime = this.mousedownTime.getElapsed();
15857 if(pressTime < 500){
15859 }else if(pressTime < 1700){
15861 }else if(pressTime < 2600){
15863 }else if(pressTime < 3500){
15865 }else if(pressTime < 4400){
15867 }else if(pressTime < 5300){
15869 }else if(pressTime < 6200){
15877 handleMouseOut : function(){
15878 clearTimeout(this.timer);
15879 if(this.pressClass){
15880 this.el.removeClass(this.pressClass);
15882 this.el.on("mouseover", this.handleMouseReturn, this);
15886 handleMouseReturn : function(){
15887 this.el.un("mouseover", this.handleMouseReturn);
15888 if(this.pressClass){
15889 this.el.addClass(this.pressClass);
15895 handleMouseUp : function(){
15896 clearTimeout(this.timer);
15897 this.el.un("mouseover", this.handleMouseReturn);
15898 this.el.un("mouseout", this.handleMouseOut);
15899 Roo.get(document).un("mouseup", this.handleMouseUp);
15900 this.el.removeClass(this.pressClass);
15901 this.fireEvent("mouseup", this);
15904 * @class Roo.util.Clipboard
15910 Roo.util.Clipboard = {
15912 * Writes a string to the clipboard - using the Clipboard API if https, otherwise using text area.
15913 * @param {String} text to copy to clipboard
15915 write : function(text) {
15916 // navigator clipboard api needs a secure context (https)
15917 if (navigator.clipboard && window.isSecureContext) {
15918 // navigator clipboard api method'
15919 navigator.clipboard.writeText(text);
15922 // text area method
15923 var ta = document.createElement("textarea");
15925 // make the textarea out of viewport
15926 ta.style.position = "fixed";
15927 ta.style.left = "-999999px";
15928 ta.style.top = "-999999px";
15929 document.body.appendChild(ta);
15932 document.execCommand('copy');
15942 * Ext JS Library 1.1.1
15943 * Copyright(c) 2006-2007, Ext JS, LLC.
15945 * Originally Released Under LGPL - original licence link has changed is not relivant.
15948 * <script type="text/javascript">
15953 * @class Roo.KeyNav
15954 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
15955 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
15956 * way to implement custom navigation schemes for any UI component.</p>
15957 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
15958 * pageUp, pageDown, del, home, end. Usage:</p>
15960 var nav = new Roo.KeyNav("my-element", {
15961 "left" : function(e){
15962 this.moveLeft(e.ctrlKey);
15964 "right" : function(e){
15965 this.moveRight(e.ctrlKey);
15967 "enter" : function(e){
15974 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15975 * @param {Object} config The config
15977 Roo.KeyNav = function(el, config){
15978 this.el = Roo.get(el);
15979 Roo.apply(this, config);
15980 if(!this.disabled){
15981 this.disabled = true;
15986 Roo.KeyNav.prototype = {
15988 * @cfg {Boolean} disabled
15989 * True to disable this KeyNav instance (defaults to false)
15993 * @cfg {String} defaultEventAction
15994 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
15995 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
15996 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
15998 defaultEventAction: "stopEvent",
16000 * @cfg {Boolean} forceKeyDown
16001 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
16002 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
16003 * handle keydown instead of keypress.
16005 forceKeyDown : false,
16008 prepareEvent : function(e){
16009 var k = e.getKey();
16010 var h = this.keyToHandler[k];
16011 //if(h && this[h]){
16012 // e.stopPropagation();
16014 if(Roo.isSafari && h && k >= 37 && k <= 40){
16020 relay : function(e){
16021 var k = e.getKey();
16022 var h = this.keyToHandler[k];
16024 if(this.doRelay(e, this[h], h) !== true){
16025 e[this.defaultEventAction]();
16031 doRelay : function(e, h, hname){
16032 return h.call(this.scope || this, e);
16035 // possible handlers
16049 // quick lookup hash
16066 * Enable this KeyNav
16068 enable: function(){
16070 // ie won't do special keys on keypress, no one else will repeat keys with keydown
16071 // the EventObject will normalize Safari automatically
16072 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
16073 this.el.on("keydown", this.relay, this);
16075 this.el.on("keydown", this.prepareEvent, this);
16076 this.el.on("keypress", this.relay, this);
16078 this.disabled = false;
16083 * Disable this KeyNav
16085 disable: function(){
16086 if(!this.disabled){
16087 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
16088 this.el.un("keydown", this.relay);
16090 this.el.un("keydown", this.prepareEvent);
16091 this.el.un("keypress", this.relay);
16093 this.disabled = true;
16098 * Ext JS Library 1.1.1
16099 * Copyright(c) 2006-2007, Ext JS, LLC.
16101 * Originally Released Under LGPL - original licence link has changed is not relivant.
16104 * <script type="text/javascript">
16109 * @class Roo.KeyMap
16110 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
16111 * The constructor accepts the same config object as defined by {@link #addBinding}.
16112 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
16113 * combination it will call the function with this signature (if the match is a multi-key
16114 * combination the callback will still be called only once): (String key, Roo.EventObject e)
16115 * A KeyMap can also handle a string representation of keys.<br />
16118 // map one key by key code
16119 var map = new Roo.KeyMap("my-element", {
16120 key: 13, // or Roo.EventObject.ENTER
16125 // map multiple keys to one action by string
16126 var map = new Roo.KeyMap("my-element", {
16132 // map multiple keys to multiple actions by strings and array of codes
16133 var map = new Roo.KeyMap("my-element", [
16136 fn: function(){ alert("Return was pressed"); }
16139 fn: function(){ alert('a, b or c was pressed'); }
16144 fn: function(){ alert('Control + shift + tab was pressed.'); }
16148 * <b>Note: A KeyMap starts enabled</b>
16150 * @param {String/HTMLElement/Roo.Element} el The element to bind to
16151 * @param {Object} config The config (see {@link #addBinding})
16152 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
16154 Roo.KeyMap = function(el, config, eventName){
16155 this.el = Roo.get(el);
16156 this.eventName = eventName || "keydown";
16157 this.bindings = [];
16159 this.addBinding(config);
16164 Roo.KeyMap.prototype = {
16166 * True to stop the event from bubbling and prevent the default browser action if the
16167 * key was handled by the KeyMap (defaults to false)
16173 * Add a new binding to this KeyMap. The following config object properties are supported:
16175 Property Type Description
16176 ---------- --------------- ----------------------------------------------------------------------
16177 key String/Array A single keycode or an array of keycodes to handle
16178 shift Boolean True to handle key only when shift is pressed (defaults to false)
16179 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
16180 alt Boolean True to handle key only when alt is pressed (defaults to false)
16181 fn Function The function to call when KeyMap finds the expected key combination
16182 scope Object The scope of the callback function
16188 var map = new Roo.KeyMap(document, {
16189 key: Roo.EventObject.ENTER,
16194 //Add a new binding to the existing KeyMap later
16202 * @param {Object/Array} config A single KeyMap config or an array of configs
16204 addBinding : function(config){
16205 if(config instanceof Array){
16206 for(var i = 0, len = config.length; i < len; i++){
16207 this.addBinding(config[i]);
16211 var keyCode = config.key,
16212 shift = config.shift,
16213 ctrl = config.ctrl,
16216 scope = config.scope;
16217 if(typeof keyCode == "string"){
16219 var keyString = keyCode.toUpperCase();
16220 for(var j = 0, len = keyString.length; j < len; j++){
16221 ks.push(keyString.charCodeAt(j));
16225 var keyArray = keyCode instanceof Array;
16226 var handler = function(e){
16227 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
16228 var k = e.getKey();
16230 for(var i = 0, len = keyCode.length; i < len; i++){
16231 if(keyCode[i] == k){
16232 if(this.stopEvent){
16235 fn.call(scope || window, k, e);
16241 if(this.stopEvent){
16244 fn.call(scope || window, k, e);
16249 this.bindings.push(handler);
16253 * Shorthand for adding a single key listener
16254 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
16255 * following options:
16256 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
16257 * @param {Function} fn The function to call
16258 * @param {Object} scope (optional) The scope of the function
16260 on : function(key, fn, scope){
16261 var keyCode, shift, ctrl, alt;
16262 if(typeof key == "object" && !(key instanceof Array)){
16281 handleKeyDown : function(e){
16282 if(this.enabled){ //just in case
16283 var b = this.bindings;
16284 for(var i = 0, len = b.length; i < len; i++){
16285 b[i].call(this, e);
16291 * Returns true if this KeyMap is enabled
16292 * @return {Boolean}
16294 isEnabled : function(){
16295 return this.enabled;
16299 * Enables this KeyMap
16301 enable: function(){
16303 this.el.on(this.eventName, this.handleKeyDown, this);
16304 this.enabled = true;
16309 * Disable this KeyMap
16311 disable: function(){
16313 this.el.removeListener(this.eventName, this.handleKeyDown, this);
16314 this.enabled = false;
16319 * Ext JS Library 1.1.1
16320 * Copyright(c) 2006-2007, Ext JS, LLC.
16322 * Originally Released Under LGPL - original licence link has changed is not relivant.
16325 * <script type="text/javascript">
16330 * @class Roo.util.TextMetrics
16331 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
16332 * wide, in pixels, a given block of text will be.
16335 Roo.util.TextMetrics = function(){
16339 * Measures the size of the specified text
16340 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
16341 * that can affect the size of the rendered text
16342 * @param {String} text The text to measure
16343 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
16344 * in order to accurately measure the text height
16345 * @return {Object} An object containing the text's size {width: (width), height: (height)}
16347 measure : function(el, text, fixedWidth){
16349 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
16352 shared.setFixedWidth(fixedWidth || 'auto');
16353 return shared.getSize(text);
16357 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
16358 * the overhead of multiple calls to initialize the style properties on each measurement.
16359 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
16360 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
16361 * in order to accurately measure the text height
16362 * @return {Roo.util.TextMetrics.Instance} instance The new instance
16364 createInstance : function(el, fixedWidth){
16365 return Roo.util.TextMetrics.Instance(el, fixedWidth);
16371 * @class Roo.util.TextMetrics.Instance
16372 * Instance of TextMetrics Calcuation
16374 * Create a new TextMetrics Instance
16375 * @param {Object} bindto
16376 * @param {Boolean} fixedWidth
16379 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth)
16381 var ml = new Roo.Element(document.createElement('div'));
16382 document.body.appendChild(ml.dom);
16383 ml.position('absolute');
16384 ml.setLeftTop(-1000, -1000);
16388 ml.setWidth(fixedWidth);
16393 * Returns the size of the specified text based on the internal element's style and width properties
16394 * @param {String} text The text to measure
16395 * @return {Object} An object containing the text's size {width: (width), height: (height)}
16397 getSize : function(text){
16399 var s = ml.getSize();
16405 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
16406 * that can affect the size of the rendered text
16407 * @param {String/HTMLElement} el The element, dom node or id
16409 bind : function(el){
16411 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
16416 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
16417 * to set a fixed width in order to accurately measure the text height.
16418 * @param {Number} width The width to set on the element
16420 setFixedWidth : function(width){
16421 ml.setWidth(width);
16425 * Returns the measured width of the specified text
16426 * @param {String} text The text to measure
16427 * @return {Number} width The width in pixels
16429 getWidth : function(text){
16430 ml.dom.style.width = 'auto';
16431 return this.getSize(text).width;
16435 * Returns the measured height of the specified text. For multiline text, be sure to call
16436 * {@link #setFixedWidth} if necessary.
16437 * @param {String} text The text to measure
16438 * @return {Number} height The height in pixels
16440 getHeight : function(text){
16441 return this.getSize(text).height;
16445 instance.bind(bindTo);
16450 // backwards compat
16451 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
16453 * Ext JS Library 1.1.1
16454 * Copyright(c) 2006-2007, Ext JS, LLC.
16456 * Originally Released Under LGPL - original licence link has changed is not relivant.
16459 * <script type="text/javascript">
16463 * @class Roo.state.Provider
16464 * Abstract base class for state provider implementations. This class provides methods
16465 * for encoding and decoding <b>typed</b> variables including dates and defines the
16466 * Provider interface.
16468 Roo.state.Provider = function(){
16470 * @event statechange
16471 * Fires when a state change occurs.
16472 * @param {Provider} this This state provider
16473 * @param {String} key The state key which was changed
16474 * @param {String} value The encoded value for the state
16477 "statechange": true
16480 Roo.state.Provider.superclass.constructor.call(this);
16482 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
16484 * Returns the current value for a key
16485 * @param {String} name The key name
16486 * @param {Mixed} defaultValue A default value to return if the key's value is not found
16487 * @return {Mixed} The state data
16489 get : function(name, defaultValue){
16490 return typeof this.state[name] == "undefined" ?
16491 defaultValue : this.state[name];
16495 * Clears a value from the state
16496 * @param {String} name The key name
16498 clear : function(name){
16499 delete this.state[name];
16500 this.fireEvent("statechange", this, name, null);
16504 * Sets the value for a key
16505 * @param {String} name The key name
16506 * @param {Mixed} value The value to set
16508 set : function(name, value){
16509 this.state[name] = value;
16510 this.fireEvent("statechange", this, name, value);
16514 * Decodes a string previously encoded with {@link #encodeValue}.
16515 * @param {String} value The value to decode
16516 * @return {Mixed} The decoded value
16518 decodeValue : function(cookie){
16519 var re = /^(a|n|d|b|s|o)\:(.*)$/;
16520 var matches = re.exec(unescape(cookie));
16521 if(!matches || !matches[1]) {
16522 return; // non state cookie
16524 var type = matches[1];
16525 var v = matches[2];
16528 return parseFloat(v);
16530 return new Date(Date.parse(v));
16535 var values = v.split("^");
16536 for(var i = 0, len = values.length; i < len; i++){
16537 all.push(this.decodeValue(values[i]));
16542 var values = v.split("^");
16543 for(var i = 0, len = values.length; i < len; i++){
16544 var kv = values[i].split("=");
16545 all[kv[0]] = this.decodeValue(kv[1]);
16554 * Encodes a value including type information. Decode with {@link #decodeValue}.
16555 * @param {Mixed} value The value to encode
16556 * @return {String} The encoded value
16558 encodeValue : function(v){
16560 if(typeof v == "number"){
16562 }else if(typeof v == "boolean"){
16563 enc = "b:" + (v ? "1" : "0");
16564 }else if(v instanceof Date){
16565 enc = "d:" + v.toGMTString();
16566 }else if(v instanceof Array){
16568 for(var i = 0, len = v.length; i < len; i++){
16569 flat += this.encodeValue(v[i]);
16575 }else if(typeof v == "object"){
16578 if(typeof v[key] != "function"){
16579 flat += key + "=" + this.encodeValue(v[key]) + "^";
16582 enc = "o:" + flat.substring(0, flat.length-1);
16586 return escape(enc);
16592 * Ext JS Library 1.1.1
16593 * Copyright(c) 2006-2007, Ext JS, LLC.
16595 * Originally Released Under LGPL - original licence link has changed is not relivant.
16598 * <script type="text/javascript">
16601 * @class Roo.state.Manager
16602 * This is the global state manager. By default all components that are "state aware" check this class
16603 * for state information if you don't pass them a custom state provider. In order for this class
16604 * to be useful, it must be initialized with a provider when your application initializes.
16606 // in your initialization function
16608 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
16610 // supposed you have a {@link Roo.BorderLayout}
16611 var layout = new Roo.BorderLayout(...);
16612 layout.restoreState();
16613 // or a {Roo.BasicDialog}
16614 var dialog = new Roo.BasicDialog(...);
16615 dialog.restoreState();
16619 Roo.state.Manager = function(){
16620 var provider = new Roo.state.Provider();
16624 * Configures the default state provider for your application
16625 * @param {Provider} stateProvider The state provider to set
16627 setProvider : function(stateProvider){
16628 provider = stateProvider;
16632 * Returns the current value for a key
16633 * @param {String} name The key name
16634 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
16635 * @return {Mixed} The state data
16637 get : function(key, defaultValue){
16638 return provider.get(key, defaultValue);
16642 * Sets the value for a key
16643 * @param {String} name The key name
16644 * @param {Mixed} value The state data
16646 set : function(key, value){
16647 provider.set(key, value);
16651 * Clears a value from the state
16652 * @param {String} name The key name
16654 clear : function(key){
16655 provider.clear(key);
16659 * Gets the currently configured state provider
16660 * @return {Provider} The state provider
16662 getProvider : function(){
16669 * Ext JS Library 1.1.1
16670 * Copyright(c) 2006-2007, Ext JS, LLC.
16672 * Originally Released Under LGPL - original licence link has changed is not relivant.
16675 * <script type="text/javascript">
16678 * @class Roo.state.CookieProvider
16679 * @extends Roo.state.Provider
16680 * The default Provider implementation which saves state via cookies.
16683 var cp = new Roo.state.CookieProvider({
16685 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
16686 domain: "roojs.com"
16688 Roo.state.Manager.setProvider(cp);
16690 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
16691 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
16692 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
16693 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
16694 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
16695 * domain the page is running on including the 'www' like 'www.roojs.com')
16696 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
16698 * Create a new CookieProvider
16699 * @param {Object} config The configuration object
16701 Roo.state.CookieProvider = function(config){
16702 Roo.state.CookieProvider.superclass.constructor.call(this);
16704 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
16705 this.domain = null;
16706 this.secure = false;
16707 Roo.apply(this, config);
16708 this.state = this.readCookies();
16711 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
16713 set : function(name, value){
16714 if(typeof value == "undefined" || value === null){
16718 this.setCookie(name, value);
16719 Roo.state.CookieProvider.superclass.set.call(this, name, value);
16723 clear : function(name){
16724 this.clearCookie(name);
16725 Roo.state.CookieProvider.superclass.clear.call(this, name);
16729 readCookies : function(){
16731 var c = document.cookie + ";";
16732 var re = /\s?(.*?)=(.*?);/g;
16734 while((matches = re.exec(c)) != null){
16735 var name = matches[1];
16736 var value = matches[2];
16737 if(name && name.substring(0,3) == "ys-"){
16738 cookies[name.substr(3)] = this.decodeValue(value);
16745 setCookie : function(name, value){
16746 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
16747 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
16748 ((this.path == null) ? "" : ("; path=" + this.path)) +
16749 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16750 ((this.secure == true) ? "; secure" : "");
16754 clearCookie : function(name){
16755 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
16756 ((this.path == null) ? "" : ("; path=" + this.path)) +
16757 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16758 ((this.secure == true) ? "; secure" : "");
16762 * Ext JS Library 1.1.1
16763 * Copyright(c) 2006-2007, Ext JS, LLC.
16765 * Originally Released Under LGPL - original licence link has changed is not relivant.
16768 * <script type="text/javascript">
16773 * @class Roo.ComponentMgr
16774 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
16777 Roo.ComponentMgr = function(){
16778 var all = new Roo.util.MixedCollection();
16782 * Registers a component.
16783 * @param {Roo.Component} c The component
16785 register : function(c){
16790 * Unregisters a component.
16791 * @param {Roo.Component} c The component
16793 unregister : function(c){
16798 * Returns a component by id
16799 * @param {String} id The component id
16801 get : function(id){
16802 return all.get(id);
16806 * Registers a function that will be called when a specified component is added to ComponentMgr
16807 * @param {String} id The component id
16808 * @param {Funtction} fn The callback function
16809 * @param {Object} scope The scope of the callback
16811 onAvailable : function(id, fn, scope){
16812 all.on("add", function(index, o){
16814 fn.call(scope || o, o);
16815 all.un("add", fn, scope);
16822 * Ext JS Library 1.1.1
16823 * Copyright(c) 2006-2007, Ext JS, LLC.
16825 * Originally Released Under LGPL - original licence link has changed is not relivant.
16828 * <script type="text/javascript">
16832 * @class Roo.Component
16833 * @extends Roo.util.Observable
16834 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
16835 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
16836 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
16837 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
16838 * All visual components (widgets) that require rendering into a layout should subclass Component.
16840 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
16841 * 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
16842 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
16844 Roo.Component = function(config){
16845 config = config || {};
16846 if(config.tagName || config.dom || typeof config == "string"){ // element object
16847 config = {el: config, id: config.id || config};
16849 this.initialConfig = config;
16851 Roo.apply(this, config);
16855 * Fires after the component is disabled.
16856 * @param {Roo.Component} this
16861 * Fires after the component is enabled.
16862 * @param {Roo.Component} this
16866 * @event beforeshow
16867 * Fires before the component is shown. Return false to stop the show.
16868 * @param {Roo.Component} this
16873 * Fires after the component is shown.
16874 * @param {Roo.Component} this
16878 * @event beforehide
16879 * Fires before the component is hidden. Return false to stop the hide.
16880 * @param {Roo.Component} this
16885 * Fires after the component is hidden.
16886 * @param {Roo.Component} this
16890 * @event beforerender
16891 * Fires before the component is rendered. Return false to stop the render.
16892 * @param {Roo.Component} this
16894 beforerender : true,
16897 * Fires after the component is rendered.
16898 * @param {Roo.Component} this
16902 * @event beforedestroy
16903 * Fires before the component is destroyed. Return false to stop the destroy.
16904 * @param {Roo.Component} this
16906 beforedestroy : true,
16909 * Fires after the component is destroyed.
16910 * @param {Roo.Component} this
16915 this.id = "roo-comp-" + (++Roo.Component.AUTO_ID);
16917 Roo.ComponentMgr.register(this);
16918 Roo.Component.superclass.constructor.call(this);
16919 this.initComponent();
16920 if(this.renderTo){ // not supported by all components yet. use at your own risk!
16921 this.render(this.renderTo);
16922 delete this.renderTo;
16927 Roo.Component.AUTO_ID = 1000;
16929 Roo.extend(Roo.Component, Roo.util.Observable, {
16931 * @scope Roo.Component.prototype
16933 * true if this component is hidden. Read-only.
16938 * true if this component is disabled. Read-only.
16943 * true if this component has been rendered. Read-only.
16947 /** @cfg {String} disableClass
16948 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
16950 disabledClass : "x-item-disabled",
16951 /** @cfg {Boolean} allowDomMove
16952 * Whether the component can move the Dom node when rendering (defaults to true).
16954 allowDomMove : true,
16955 /** @cfg {String} hideMode (display|visibility)
16956 * How this component should hidden. Supported values are
16957 * "visibility" (css visibility), "offsets" (negative offset position) and
16958 * "display" (css display) - defaults to "display".
16960 hideMode: 'display',
16963 ctype : "Roo.Component",
16966 * @cfg {String} actionMode
16967 * which property holds the element that used for hide() / show() / disable() / enable()
16968 * default is 'el' for forms you probably want to set this to fieldEl
16973 getActionEl : function(){
16974 return this[this.actionMode];
16977 initComponent : Roo.emptyFn,
16979 * If this is a lazy rendering component, render it to its container element.
16980 * @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.
16982 render : function(container, position){
16988 if(this.fireEvent("beforerender", this) === false){
16992 if(!container && this.el){
16993 this.el = Roo.get(this.el);
16994 container = this.el.dom.parentNode;
16995 this.allowDomMove = false;
16997 this.container = Roo.get(container);
16998 this.rendered = true;
16999 if(position !== undefined){
17000 if(typeof position == 'number'){
17001 position = this.container.dom.childNodes[position];
17003 position = Roo.getDom(position);
17006 this.onRender(this.container, position || null);
17008 this.el.addClass(this.cls);
17012 this.el.applyStyles(this.style);
17015 this.fireEvent("render", this);
17016 this.afterRender(this.container);
17029 // default function is not really useful
17030 onRender : function(ct, position){
17032 this.el = Roo.get(this.el);
17033 if(this.allowDomMove !== false){
17034 ct.dom.insertBefore(this.el.dom, position);
17040 getAutoCreate : function(){
17041 var cfg = typeof this.autoCreate == "object" ?
17042 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
17043 if(this.id && !cfg.id){
17050 afterRender : Roo.emptyFn,
17053 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
17054 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
17056 destroy : function(){
17057 if(this.fireEvent("beforedestroy", this) !== false){
17058 this.purgeListeners();
17059 this.beforeDestroy();
17061 this.el.removeAllListeners();
17063 if(this.actionMode == "container"){
17064 this.container.remove();
17068 Roo.ComponentMgr.unregister(this);
17069 this.fireEvent("destroy", this);
17074 beforeDestroy : function(){
17079 onDestroy : function(){
17084 * Returns the underlying {@link Roo.Element}.
17085 * @return {Roo.Element} The element
17087 getEl : function(){
17092 * Returns the id of this component.
17095 getId : function(){
17100 * Try to focus this component.
17101 * @param {Boolean} selectText True to also select the text in this component (if applicable)
17102 * @return {Roo.Component} this
17104 focus : function(selectText){
17107 if(selectText === true){
17108 this.el.dom.select();
17123 * Disable this component.
17124 * @return {Roo.Component} this
17126 disable : function(){
17130 this.disabled = true;
17131 this.fireEvent("disable", this);
17136 onDisable : function(){
17137 this.getActionEl().addClass(this.disabledClass);
17138 this.el.dom.disabled = true;
17142 * Enable this component.
17143 * @return {Roo.Component} this
17145 enable : function(){
17149 this.disabled = false;
17150 this.fireEvent("enable", this);
17155 onEnable : function(){
17156 this.getActionEl().removeClass(this.disabledClass);
17157 this.el.dom.disabled = false;
17161 * Convenience function for setting disabled/enabled by boolean.
17162 * @param {Boolean} disabled
17164 setDisabled : function(disabled){
17165 this[disabled ? "disable" : "enable"]();
17169 * Show this component.
17170 * @return {Roo.Component} this
17173 if(this.fireEvent("beforeshow", this) !== false){
17174 this.hidden = false;
17178 this.fireEvent("show", this);
17184 onShow : function(){
17185 var ae = this.getActionEl();
17186 if(this.hideMode == 'visibility'){
17187 ae.dom.style.visibility = "visible";
17188 }else if(this.hideMode == 'offsets'){
17189 ae.removeClass('x-hidden');
17191 ae.dom.style.display = "";
17196 * Hide this component.
17197 * @return {Roo.Component} this
17200 if(this.fireEvent("beforehide", this) !== false){
17201 this.hidden = true;
17205 this.fireEvent("hide", this);
17211 onHide : function(){
17212 var ae = this.getActionEl();
17213 if(this.hideMode == 'visibility'){
17214 ae.dom.style.visibility = "hidden";
17215 }else if(this.hideMode == 'offsets'){
17216 ae.addClass('x-hidden');
17218 ae.dom.style.display = "none";
17223 * Convenience function to hide or show this component by boolean.
17224 * @param {Boolean} visible True to show, false to hide
17225 * @return {Roo.Component} this
17227 setVisible: function(visible){
17237 * Returns true if this component is visible.
17239 isVisible : function(){
17240 return this.getActionEl().isVisible();
17243 cloneConfig : function(overrides){
17244 overrides = overrides || {};
17245 var id = overrides.id || Roo.id();
17246 var cfg = Roo.applyIf(overrides, this.initialConfig);
17247 cfg.id = id; // prevent dup id
17248 return new this.constructor(cfg);
17252 * Ext JS Library 1.1.1
17253 * Copyright(c) 2006-2007, Ext JS, LLC.
17255 * Originally Released Under LGPL - original licence link has changed is not relivant.
17258 * <script type="text/javascript">
17262 * @class Roo.BoxComponent
17263 * @extends Roo.Component
17264 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
17265 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
17266 * container classes should subclass BoxComponent so that they will work consistently when nested within other Roo
17267 * layout containers.
17269 * @param {Roo.Element/String/Object} config The configuration options.
17271 Roo.BoxComponent = function(config){
17272 Roo.Component.call(this, config);
17276 * Fires after the component is resized.
17277 * @param {Roo.Component} this
17278 * @param {Number} adjWidth The box-adjusted width that was set
17279 * @param {Number} adjHeight The box-adjusted height that was set
17280 * @param {Number} rawWidth The width that was originally specified
17281 * @param {Number} rawHeight The height that was originally specified
17286 * Fires after the component is moved.
17287 * @param {Roo.Component} this
17288 * @param {Number} x The new x position
17289 * @param {Number} y The new y position
17295 Roo.extend(Roo.BoxComponent, Roo.Component, {
17296 // private, set in afterRender to signify that the component has been rendered
17298 // private, used to defer height settings to subclasses
17299 deferHeight: false,
17300 /** @cfg {Number} width
17301 * width (optional) size of component
17303 /** @cfg {Number} height
17304 * height (optional) size of component
17308 * Sets the width and height of the component. This method fires the resize event. This method can accept
17309 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
17310 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
17311 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
17312 * @return {Roo.BoxComponent} this
17314 setSize : function(w, h){
17315 // support for standard size objects
17316 if(typeof w == 'object'){
17321 if(!this.boxReady){
17327 // prevent recalcs when not needed
17328 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
17331 this.lastSize = {width: w, height: h};
17333 var adj = this.adjustSize(w, h);
17334 var aw = adj.width, ah = adj.height;
17335 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
17336 var rz = this.getResizeEl();
17337 if(!this.deferHeight && aw !== undefined && ah !== undefined){
17338 rz.setSize(aw, ah);
17339 }else if(!this.deferHeight && ah !== undefined){
17341 }else if(aw !== undefined){
17344 this.onResize(aw, ah, w, h);
17345 this.fireEvent('resize', this, aw, ah, w, h);
17351 * Gets the current size of the component's underlying element.
17352 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
17354 getSize : function(){
17355 return this.el.getSize();
17359 * Gets the current XY position of the component's underlying element.
17360 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
17361 * @return {Array} The XY position of the element (e.g., [100, 200])
17363 getPosition : function(local){
17364 if(local === true){
17365 return [this.el.getLeft(true), this.el.getTop(true)];
17367 return this.xy || this.el.getXY();
17371 * Gets the current box measurements of the component's underlying element.
17372 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
17373 * @returns {Object} box An object in the format {x, y, width, height}
17375 getBox : function(local){
17376 var s = this.el.getSize();
17378 s.x = this.el.getLeft(true);
17379 s.y = this.el.getTop(true);
17381 var xy = this.xy || this.el.getXY();
17389 * Sets the current box measurements of the component's underlying element.
17390 * @param {Object} box An object in the format {x, y, width, height}
17391 * @returns {Roo.BoxComponent} this
17393 updateBox : function(box){
17394 this.setSize(box.width, box.height);
17395 this.setPagePosition(box.x, box.y);
17400 getResizeEl : function(){
17401 return this.resizeEl || this.el;
17405 getPositionEl : function(){
17406 return this.positionEl || this.el;
17410 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
17411 * This method fires the move event.
17412 * @param {Number} left The new left
17413 * @param {Number} top The new top
17414 * @returns {Roo.BoxComponent} this
17416 setPosition : function(x, y){
17419 if(!this.boxReady){
17422 var adj = this.adjustPosition(x, y);
17423 var ax = adj.x, ay = adj.y;
17425 var el = this.getPositionEl();
17426 if(ax !== undefined || ay !== undefined){
17427 if(ax !== undefined && ay !== undefined){
17428 el.setLeftTop(ax, ay);
17429 }else if(ax !== undefined){
17431 }else if(ay !== undefined){
17434 this.onPosition(ax, ay);
17435 this.fireEvent('move', this, ax, ay);
17441 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
17442 * This method fires the move event.
17443 * @param {Number} x The new x position
17444 * @param {Number} y The new y position
17445 * @returns {Roo.BoxComponent} this
17447 setPagePosition : function(x, y){
17450 if(!this.boxReady){
17453 if(x === undefined || y === undefined){ // cannot translate undefined points
17456 var p = this.el.translatePoints(x, y);
17457 this.setPosition(p.left, p.top);
17462 onRender : function(ct, position){
17463 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
17465 this.resizeEl = Roo.get(this.resizeEl);
17467 if(this.positionEl){
17468 this.positionEl = Roo.get(this.positionEl);
17473 afterRender : function(){
17474 Roo.BoxComponent.superclass.afterRender.call(this);
17475 this.boxReady = true;
17476 this.setSize(this.width, this.height);
17477 if(this.x || this.y){
17478 this.setPosition(this.x, this.y);
17480 if(this.pageX || this.pageY){
17481 this.setPagePosition(this.pageX, this.pageY);
17486 * Force the component's size to recalculate based on the underlying element's current height and width.
17487 * @returns {Roo.BoxComponent} this
17489 syncSize : function(){
17490 delete this.lastSize;
17491 this.setSize(this.el.getWidth(), this.el.getHeight());
17496 * Called after the component is resized, this method is empty by default but can be implemented by any
17497 * subclass that needs to perform custom logic after a resize occurs.
17498 * @param {Number} adjWidth The box-adjusted width that was set
17499 * @param {Number} adjHeight The box-adjusted height that was set
17500 * @param {Number} rawWidth The width that was originally specified
17501 * @param {Number} rawHeight The height that was originally specified
17503 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
17508 * Called after the component is moved, this method is empty by default but can be implemented by any
17509 * subclass that needs to perform custom logic after a move occurs.
17510 * @param {Number} x The new x position
17511 * @param {Number} y The new y position
17513 onPosition : function(x, y){
17518 adjustSize : function(w, h){
17519 if(this.autoWidth){
17522 if(this.autoHeight){
17525 return {width : w, height: h};
17529 adjustPosition : function(x, y){
17530 return {x : x, y: y};
17534 * Ext JS Library 1.1.1
17535 * Copyright(c) 2006-2007, Ext JS, LLC.
17537 * Originally Released Under LGPL - original licence link has changed is not relivant.
17540 * <script type="text/javascript">
17545 * @extends Roo.Element
17546 * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
17547 * automatic maintaining of shadow/shim positions.
17548 * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
17549 * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
17550 * you can pass a string with a CSS class name. False turns off the shadow.
17551 * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
17552 * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
17553 * @cfg {String} cls CSS class to add to the element
17554 * @cfg {Number} zindex Starting z-index (defaults to 11000)
17555 * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
17557 * @param {Object} config An object with config options.
17558 * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
17561 Roo.Layer = function(config, existingEl){
17562 config = config || {};
17563 var dh = Roo.DomHelper;
17564 var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
17566 this.dom = Roo.getDom(existingEl);
17569 var o = config.dh || {tag: "div", cls: "x-layer"};
17570 this.dom = dh.append(pel, o);
17573 this.addClass(config.cls);
17575 this.constrain = config.constrain !== false;
17576 this.visibilityMode = Roo.Element.VISIBILITY;
17578 this.id = this.dom.id = config.id;
17580 this.id = Roo.id(this.dom);
17582 this.zindex = config.zindex || this.getZIndex();
17583 this.position("absolute", this.zindex);
17585 this.shadowOffset = config.shadowOffset || 4;
17586 this.shadow = new Roo.Shadow({
17587 offset : this.shadowOffset,
17588 mode : config.shadow
17591 this.shadowOffset = 0;
17593 this.useShim = config.shim !== false && Roo.useShims;
17594 this.useDisplay = config.useDisplay;
17598 var supr = Roo.Element.prototype;
17600 // shims are shared among layer to keep from having 100 iframes
17603 Roo.extend(Roo.Layer, Roo.Element, {
17605 getZIndex : function(){
17606 return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
17609 getShim : function(){
17616 var shim = shims.shift();
17618 shim = this.createShim();
17619 shim.enableDisplayMode('block');
17620 shim.dom.style.display = 'none';
17621 shim.dom.style.visibility = 'visible';
17623 var pn = this.dom.parentNode;
17624 if(shim.dom.parentNode != pn){
17625 pn.insertBefore(shim.dom, this.dom);
17627 shim.setStyle('z-index', this.getZIndex()-2);
17632 hideShim : function(){
17634 this.shim.setDisplayed(false);
17635 shims.push(this.shim);
17640 disableShadow : function(){
17642 this.shadowDisabled = true;
17643 this.shadow.hide();
17644 this.lastShadowOffset = this.shadowOffset;
17645 this.shadowOffset = 0;
17649 enableShadow : function(show){
17651 this.shadowDisabled = false;
17652 this.shadowOffset = this.lastShadowOffset;
17653 delete this.lastShadowOffset;
17661 // this code can execute repeatedly in milliseconds (i.e. during a drag) so
17662 // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
17663 sync : function(doShow){
17664 var sw = this.shadow;
17665 if(!this.updating && this.isVisible() && (sw || this.useShim)){
17666 var sh = this.getShim();
17668 var w = this.getWidth(),
17669 h = this.getHeight();
17671 var l = this.getLeft(true),
17672 t = this.getTop(true);
17674 if(sw && !this.shadowDisabled){
17675 if(doShow && !sw.isVisible()){
17678 sw.realign(l, t, w, h);
17684 // fit the shim behind the shadow, so it is shimmed too
17685 var a = sw.adjusts, s = sh.dom.style;
17686 s.left = (Math.min(l, l+a.l))+"px";
17687 s.top = (Math.min(t, t+a.t))+"px";
17688 s.width = (w+a.w)+"px";
17689 s.height = (h+a.h)+"px";
17696 sh.setLeftTop(l, t);
17703 destroy : function(){
17706 this.shadow.hide();
17708 this.removeAllListeners();
17709 var pn = this.dom.parentNode;
17711 pn.removeChild(this.dom);
17713 Roo.Element.uncache(this.id);
17716 remove : function(){
17721 beginUpdate : function(){
17722 this.updating = true;
17726 endUpdate : function(){
17727 this.updating = false;
17732 hideUnders : function(negOffset){
17734 this.shadow.hide();
17740 constrainXY : function(){
17741 if(this.constrain){
17742 var vw = Roo.lib.Dom.getViewWidth(),
17743 vh = Roo.lib.Dom.getViewHeight();
17744 var s = Roo.get(document).getScroll();
17746 var xy = this.getXY();
17747 var x = xy[0], y = xy[1];
17748 var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
17749 // only move it if it needs it
17751 // first validate right/bottom
17752 if((x + w) > vw+s.left){
17753 x = vw - w - this.shadowOffset;
17756 if((y + h) > vh+s.top){
17757 y = vh - h - this.shadowOffset;
17760 // then make sure top/left isn't negative
17771 var ay = this.avoidY;
17772 if(y <= ay && (y+h) >= ay){
17778 supr.setXY.call(this, xy);
17784 isVisible : function(){
17785 return this.visible;
17789 showAction : function(){
17790 this.visible = true; // track visibility to prevent getStyle calls
17791 if(this.useDisplay === true){
17792 this.setDisplayed("");
17793 }else if(this.lastXY){
17794 supr.setXY.call(this, this.lastXY);
17795 }else if(this.lastLT){
17796 supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
17801 hideAction : function(){
17802 this.visible = false;
17803 if(this.useDisplay === true){
17804 this.setDisplayed(false);
17806 this.setLeftTop(-10000,-10000);
17810 // overridden Element method
17811 setVisible : function(v, a, d, c, e){
17816 var cb = function(){
17821 }.createDelegate(this);
17822 supr.setVisible.call(this, true, true, d, cb, e);
17825 this.hideUnders(true);
17834 }.createDelegate(this);
17836 supr.setVisible.call(this, v, a, d, cb, e);
17845 storeXY : function(xy){
17846 delete this.lastLT;
17850 storeLeftTop : function(left, top){
17851 delete this.lastXY;
17852 this.lastLT = [left, top];
17856 beforeFx : function(){
17857 this.beforeAction();
17858 return Roo.Layer.superclass.beforeFx.apply(this, arguments);
17862 afterFx : function(){
17863 Roo.Layer.superclass.afterFx.apply(this, arguments);
17864 this.sync(this.isVisible());
17868 beforeAction : function(){
17869 if(!this.updating && this.shadow){
17870 this.shadow.hide();
17874 // overridden Element method
17875 setLeft : function(left){
17876 this.storeLeftTop(left, this.getTop(true));
17877 supr.setLeft.apply(this, arguments);
17881 setTop : function(top){
17882 this.storeLeftTop(this.getLeft(true), top);
17883 supr.setTop.apply(this, arguments);
17887 setLeftTop : function(left, top){
17888 this.storeLeftTop(left, top);
17889 supr.setLeftTop.apply(this, arguments);
17893 setXY : function(xy, a, d, c, e){
17895 this.beforeAction();
17897 var cb = this.createCB(c);
17898 supr.setXY.call(this, xy, a, d, cb, e);
17905 createCB : function(c){
17916 // overridden Element method
17917 setX : function(x, a, d, c, e){
17918 this.setXY([x, this.getY()], a, d, c, e);
17921 // overridden Element method
17922 setY : function(y, a, d, c, e){
17923 this.setXY([this.getX(), y], a, d, c, e);
17926 // overridden Element method
17927 setSize : function(w, h, a, d, c, e){
17928 this.beforeAction();
17929 var cb = this.createCB(c);
17930 supr.setSize.call(this, w, h, a, d, cb, e);
17936 // overridden Element method
17937 setWidth : function(w, a, d, c, e){
17938 this.beforeAction();
17939 var cb = this.createCB(c);
17940 supr.setWidth.call(this, w, a, d, cb, e);
17946 // overridden Element method
17947 setHeight : function(h, a, d, c, e){
17948 this.beforeAction();
17949 var cb = this.createCB(c);
17950 supr.setHeight.call(this, h, a, d, cb, e);
17956 // overridden Element method
17957 setBounds : function(x, y, w, h, a, d, c, e){
17958 this.beforeAction();
17959 var cb = this.createCB(c);
17961 this.storeXY([x, y]);
17962 supr.setXY.call(this, [x, y]);
17963 supr.setSize.call(this, w, h, a, d, cb, e);
17966 supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
17972 * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
17973 * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
17974 * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
17975 * @param {Number} zindex The new z-index to set
17976 * @return {this} The Layer
17978 setZIndex : function(zindex){
17979 this.zindex = zindex;
17980 this.setStyle("z-index", zindex + 2);
17982 this.shadow.setZIndex(zindex + 1);
17985 this.shim.setStyle("z-index", zindex);
17990 * Original code for Roojs - LGPL
17991 * <script type="text/javascript">
17995 * @class Roo.XComponent
17996 * A delayed Element creator...
17997 * Or a way to group chunks of interface together.
17998 * technically this is a wrapper around a tree of Roo elements (which defines a 'module'),
17999 * used in conjunction with XComponent.build() it will create an instance of each element,
18000 * then call addxtype() to build the User interface.
18002 * Mypart.xyx = new Roo.XComponent({
18004 parent : 'Mypart.xyz', // empty == document.element.!!
18008 disabled : function() {}
18010 tree : function() { // return an tree of xtype declared components
18014 xtype : 'NestedLayoutPanel',
18021 * It can be used to build a big heiracy, with parent etc.
18022 * or you can just use this to render a single compoent to a dom element
18023 * MYPART.render(Roo.Element | String(id) | dom_element )
18030 * Roo is designed primarily as a single page application, so the UI build for a standard interface will
18031 * expect a single 'TOP' level module normally indicated by the 'parent' of the XComponent definition being defined as false.
18033 * Each sub module is expected to have a parent pointing to the class name of it's parent module.
18035 * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
18036 * - if mulitple topModules exist, the last one is defined as the top module.
18040 * When the top level or multiple modules are to embedded into a existing HTML page,
18041 * the parent element can container '#id' of the element where the module will be drawn.
18045 * Unlike classic Roo, the bootstrap tends not to be used as a single page.
18046 * it relies more on a include mechanism, where sub modules are included into an outer page.
18047 * This is normally managed by the builder tools using Roo.apply( options, Included.Sub.Module )
18049 * Bootstrap Roo Included elements
18051 * Our builder application needs the ability to preview these sub compoennts. They will normally have parent=false set,
18052 * hence confusing the component builder as it thinks there are multiple top level elements.
18054 * String Over-ride & Translations
18056 * Our builder application writes all the strings as _strings and _named_strings. This is to enable the translation of elements,
18057 * and also the 'overlaying of string values - needed when different versions of the same application with different text content
18058 * are needed. @see Roo.XComponent.overlayString
18062 * @extends Roo.util.Observable
18064 * @param cfg {Object} configuration of component
18067 Roo.XComponent = function(cfg) {
18068 Roo.apply(this, cfg);
18072 * Fires when this the componnt is built
18073 * @param {Roo.XComponent} c the component
18078 this.region = this.region || 'center'; // default..
18079 Roo.XComponent.register(this);
18080 this.modules = false;
18081 this.el = false; // where the layout goes..
18085 Roo.extend(Roo.XComponent, Roo.util.Observable, {
18088 * The created element (with Roo.factory())
18089 * @type {Roo.Layout}
18095 * for BC - use el in new code
18096 * @type {Roo.Layout}
18102 * for BC - use el in new code
18103 * @type {Roo.Layout}
18108 * @cfg {Function|boolean} disabled
18109 * If this module is disabled by some rule, return true from the funtion
18114 * @cfg {String} parent
18115 * Name of parent element which it get xtype added to..
18120 * @cfg {String} order
18121 * Used to set the order in which elements are created (usefull for multiple tabs)
18126 * @cfg {String} name
18127 * String to display while loading.
18131 * @cfg {String} region
18132 * Region to render component to (defaults to center)
18137 * @cfg {Array} items
18138 * A single item array - the first element is the root of the tree..
18139 * It's done this way to stay compatible with the Xtype system...
18145 * The method that retuns the tree of parts that make up this compoennt
18152 * render element to dom or tree
18153 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
18156 render : function(el)
18160 var hp = this.parent ? 1 : 0;
18161 Roo.debug && Roo.log(this);
18163 var tree = this._tree ? this._tree() : this.tree();
18166 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
18167 // if parent is a '#.....' string, then let's use that..
18168 var ename = this.parent.substr(1);
18169 this.parent = false;
18170 Roo.debug && Roo.log(ename);
18172 case 'bootstrap-body':
18173 if (typeof(tree.el) != 'undefined' && tree.el == document.body) {
18174 // this is the BorderLayout standard?
18175 this.parent = { el : true };
18178 if (["Nest", "Content", "Grid", "Tree"].indexOf(tree.xtype) > -1) {
18179 // need to insert stuff...
18181 el : new Roo.bootstrap.layout.Border({
18182 el : document.body,
18188 tabPosition: 'top',
18189 //resizeTabs: true,
18190 alwaysShowTabs: true,
18200 if (typeof(Roo.bootstrap.Body) != 'undefined' ) {
18201 this.parent = { el : new Roo.bootstrap.Body() };
18202 Roo.debug && Roo.log("setting el to doc body");
18205 throw "Container is bootstrap body, but Roo.bootstrap.Body is not defined";
18209 this.parent = { el : true};
18212 el = Roo.get(ename);
18213 if (typeof(Roo.bootstrap) != 'undefined' && tree['|xns'] == 'Roo.bootstrap') {
18214 this.parent = { el : true};
18221 if (!el && !this.parent) {
18222 Roo.debug && Roo.log("Warning - element can not be found :#" + ename );
18227 Roo.debug && Roo.log("EL:");
18228 Roo.debug && Roo.log(el);
18229 Roo.debug && Roo.log("this.parent.el:");
18230 Roo.debug && Roo.log(this.parent.el);
18233 // altertive root elements ??? - we need a better way to indicate these.
18234 var is_alt = Roo.XComponent.is_alt ||
18235 (typeof(tree.el) != 'undefined' && tree.el == document.body) ||
18236 (typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) ||
18237 (typeof(Roo.mailer) != 'undefined' && tree.xns == Roo.mailer) ;
18241 if (!this.parent && is_alt) {
18242 //el = Roo.get(document.body);
18243 this.parent = { el : true };
18248 if (!this.parent) {
18250 Roo.debug && Roo.log("no parent - creating one");
18252 el = el ? Roo.get(el) : false;
18254 if (typeof(Roo.BorderLayout) == 'undefined' ) {
18257 el : new Roo.bootstrap.layout.Border({
18258 el: el || document.body,
18264 tabPosition: 'top',
18265 //resizeTabs: true,
18266 alwaysShowTabs: false,
18269 overflow: 'visible'
18275 // it's a top level one..
18277 el : new Roo.BorderLayout(el || document.body, {
18282 tabPosition: 'top',
18283 //resizeTabs: true,
18284 alwaysShowTabs: el && hp? false : true,
18285 hideTabs: el || !hp ? true : false,
18293 if (!this.parent.el) {
18294 // probably an old style ctor, which has been disabled.
18298 // The 'tree' method is '_tree now'
18300 tree.region = tree.region || this.region;
18301 var is_body = false;
18302 if (this.parent.el === true) {
18303 // bootstrap... - body..
18307 this.parent.el = Roo.factory(tree);
18311 this.el = this.parent.el.addxtype(tree, undefined, is_body);
18312 this.fireEvent('built', this);
18314 this.panel = this.el;
18315 this.layout = this.panel.layout;
18316 this.parentLayout = this.parent.layout || false;
18322 Roo.apply(Roo.XComponent, {
18324 * @property hideProgress
18325 * true to disable the building progress bar.. usefull on single page renders.
18328 hideProgress : false,
18330 * @property buildCompleted
18331 * True when the builder has completed building the interface.
18334 buildCompleted : false,
18337 * @property topModule
18338 * the upper most module - uses document.element as it's constructor.
18345 * @property modules
18346 * array of modules to be created by registration system.
18347 * @type {Array} of Roo.XComponent
18352 * @property elmodules
18353 * array of modules to be created by which use #ID
18354 * @type {Array} of Roo.XComponent
18361 * Is an alternative Root - normally used by bootstrap or other systems,
18362 * where the top element in the tree can wrap 'body'
18363 * @type {boolean} (default false)
18368 * @property build_from_html
18369 * Build elements from html - used by bootstrap HTML stuff
18370 * - this is cleared after build is completed
18371 * @type {boolean} (default false)
18374 build_from_html : false,
18376 * Register components to be built later.
18378 * This solves the following issues
18379 * - Building is not done on page load, but after an authentication process has occured.
18380 * - Interface elements are registered on page load
18381 * - Parent Interface elements may not be loaded before child, so this handles that..
18388 module : 'Pman.Tab.projectMgr',
18390 parent : 'Pman.layout',
18391 disabled : false, // or use a function..
18394 * * @param {Object} details about module
18396 register : function(obj) {
18398 Roo.XComponent.event.fireEvent('register', obj);
18399 switch(typeof(obj.disabled) ) {
18405 if ( obj.disabled() ) {
18411 if (obj.disabled || obj.region == '#disabled') {
18417 this.modules.push(obj);
18421 * convert a string to an object..
18422 * eg. 'AAA.BBB' -> finds AAA.BBB
18426 toObject : function(str)
18428 if (!str || typeof(str) == 'object') {
18431 if (str.substring(0,1) == '#') {
18435 var ar = str.split('.');
18440 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
18442 throw "Module not found : " + str;
18446 throw "Module not found : " + str;
18448 Roo.each(ar, function(e) {
18449 if (typeof(o[e]) == 'undefined') {
18450 throw "Module not found : " + str;
18461 * move modules into their correct place in the tree..
18464 preBuild : function ()
18467 Roo.each(this.modules , function (obj)
18469 Roo.XComponent.event.fireEvent('beforebuild', obj);
18471 var opar = obj.parent;
18473 obj.parent = this.toObject(opar);
18475 Roo.debug && Roo.log("parent:toObject failed: " + e.toString());
18480 Roo.debug && Roo.log("GOT top level module");
18481 Roo.debug && Roo.log(obj);
18482 obj.modules = new Roo.util.MixedCollection(false,
18483 function(o) { return o.order + '' }
18485 this.topModule = obj;
18488 // parent is a string (usually a dom element name..)
18489 if (typeof(obj.parent) == 'string') {
18490 this.elmodules.push(obj);
18493 if (obj.parent.constructor != Roo.XComponent) {
18494 Roo.debug && Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
18496 if (!obj.parent.modules) {
18497 obj.parent.modules = new Roo.util.MixedCollection(false,
18498 function(o) { return o.order + '' }
18501 if (obj.parent.disabled) {
18502 obj.disabled = true;
18504 obj.parent.modules.add(obj);
18509 * make a list of modules to build.
18510 * @return {Array} list of modules.
18513 buildOrder : function()
18516 var cmp = function(a,b) {
18517 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
18519 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
18520 throw "No top level modules to build";
18523 // make a flat list in order of modules to build.
18524 var mods = this.topModule ? [ this.topModule ] : [];
18527 // elmodules (is a list of DOM based modules )
18528 Roo.each(this.elmodules, function(e) {
18530 if (!this.topModule &&
18531 typeof(e.parent) == 'string' &&
18532 e.parent.substring(0,1) == '#' &&
18533 Roo.get(e.parent.substr(1))
18536 _this.topModule = e;
18542 // add modules to their parents..
18543 var addMod = function(m) {
18544 Roo.debug && Roo.log("build Order: add: " + m.name);
18547 if (m.modules && !m.disabled) {
18548 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
18549 m.modules.keySort('ASC', cmp );
18550 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
18552 m.modules.each(addMod);
18554 Roo.debug && Roo.log("build Order: no child modules");
18556 // not sure if this is used any more..
18558 m.finalize.name = m.name + " (clean up) ";
18559 mods.push(m.finalize);
18563 if (this.topModule && this.topModule.modules) {
18564 this.topModule.modules.keySort('ASC', cmp );
18565 this.topModule.modules.each(addMod);
18571 * Build the registered modules.
18572 * @param {Object} parent element.
18573 * @param {Function} optional method to call after module has been added.
18577 build : function(opts)
18580 if (typeof(opts) != 'undefined') {
18581 Roo.apply(this,opts);
18585 var mods = this.buildOrder();
18587 //this.allmods = mods;
18588 //Roo.debug && Roo.log(mods);
18590 if (!mods.length) { // should not happen
18591 throw "NO modules!!!";
18595 var msg = "Building Interface...";
18596 // flash it up as modal - so we store the mask!?
18597 if (!this.hideProgress && Roo.MessageBox) {
18598 Roo.MessageBox.show({ title: 'loading' });
18599 Roo.MessageBox.show({
18600 title: "Please wait...",
18610 var total = mods.length;
18613 var progressRun = function() {
18614 if (!mods.length) {
18615 Roo.debug && Roo.log('hide?');
18616 if (!this.hideProgress && Roo.MessageBox) {
18617 Roo.MessageBox.hide();
18619 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
18621 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
18627 var m = mods.shift();
18630 Roo.debug && Roo.log(m);
18631 // not sure if this is supported any more.. - modules that are are just function
18632 if (typeof(m) == 'function') {
18634 return progressRun.defer(10, _this);
18638 msg = "Building Interface " + (total - mods.length) +
18640 (m.name ? (' - ' + m.name) : '');
18641 Roo.debug && Roo.log(msg);
18642 if (!_this.hideProgress && Roo.MessageBox) {
18643 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
18647 // is the module disabled?
18648 var disabled = (typeof(m.disabled) == 'function') ?
18649 m.disabled.call(m.module.disabled) : m.disabled;
18653 return progressRun(); // we do not update the display!
18661 // it's 10 on top level, and 1 on others??? why...
18662 return progressRun.defer(10, _this);
18665 progressRun.defer(1, _this);
18671 * Overlay a set of modified strings onto a component
18672 * This is dependant on our builder exporting the strings and 'named strings' elements.
18674 * @param {Object} element to overlay on - eg. Pman.Dialog.Login
18675 * @param {Object} associative array of 'named' string and it's new value.
18678 overlayStrings : function( component, strings )
18680 if (typeof(component['_named_strings']) == 'undefined') {
18681 throw "ERROR: component does not have _named_strings";
18683 for ( var k in strings ) {
18684 var md = typeof(component['_named_strings'][k]) == 'undefined' ? false : component['_named_strings'][k];
18685 if (md !== false) {
18686 component['_strings'][md] = strings[k];
18688 Roo.log('could not find named string: ' + k + ' in');
18689 Roo.log(component);
18704 * wrapper for event.on - aliased later..
18705 * Typically use to register a event handler for register:
18707 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
18716 Roo.XComponent.event = new Roo.util.Observable({
18720 * Fires when an Component is registered,
18721 * set the disable property on the Component to stop registration.
18722 * @param {Roo.XComponent} c the component being registerd.
18727 * @event beforebuild
18728 * Fires before each Component is built
18729 * can be used to apply permissions.
18730 * @param {Roo.XComponent} c the component being registerd.
18733 'beforebuild' : true,
18735 * @event buildcomplete
18736 * Fires on the top level element when all elements have been built
18737 * @param {Roo.XComponent} the top level component.
18739 'buildcomplete' : true
18744 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);
18747 * marked - a markdown parser
18748 * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
18749 * https://github.com/chjj/marked
18755 * Roo.Markdown - is a very crude wrapper around marked..
18759 * alert( Roo.Markdown.toHtml("Markdown *rocks*.") );
18761 * Note: move the sample code to the bottom of this
18762 * file before uncommenting it.
18767 Roo.Markdown.toHtml = function(text) {
18769 var c = new Roo.Markdown.marked.setOptions({
18770 renderer: new Roo.Markdown.marked.Renderer(),
18781 text = text.replace(/\\\n/g,' ');
18782 return Roo.Markdown.marked(text);
18787 // Wraps all "globals" so that the only thing
18788 // exposed is makeHtml().
18794 * eval:var:unescape
18802 var escape = function (html, encode) {
18804 .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
18805 .replace(/</g, '<')
18806 .replace(/>/g, '>')
18807 .replace(/"/g, '"')
18808 .replace(/'/g, ''');
18811 var unescape = function (html) {
18812 // explicitly match decimal, hex, and named HTML entities
18813 return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
18814 n = n.toLowerCase();
18815 if (n === 'colon') { return ':'; }
18816 if (n.charAt(0) === '#') {
18817 return n.charAt(1) === 'x'
18818 ? String.fromCharCode(parseInt(n.substring(2), 16))
18819 : String.fromCharCode(+n.substring(1));
18825 var replace = function (regex, opt) {
18826 regex = regex.source;
18828 return function self(name, val) {
18829 if (!name) { return new RegExp(regex, opt); }
18830 val = val.source || val;
18831 val = val.replace(/(^|[^\[])\^/g, '$1');
18832 regex = regex.replace(name, val);
18841 var noop = function () {}
18847 var merge = function (obj) {
18852 for (; i < arguments.length; i++) {
18853 target = arguments[i];
18854 for (key in target) {
18855 if (Object.prototype.hasOwnProperty.call(target, key)) {
18856 obj[key] = target[key];
18866 * Block-Level Grammar
18874 code: /^( {4}[^\n]+\n*)+/,
18876 hr: /^( *[-*_]){3,} *(?:\n+|$)/,
18877 heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
18879 lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
18880 blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
18881 list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
18882 html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
18883 def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
18885 paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
18889 block.bullet = /(?:[*+-]|\d+\.)/;
18890 block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
18891 block.item = replace(block.item, 'gm')
18892 (/bull/g, block.bullet)
18895 block.list = replace(block.list)
18896 (/bull/g, block.bullet)
18897 ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
18898 ('def', '\\n+(?=' + block.def.source + ')')
18901 block.blockquote = replace(block.blockquote)
18905 block._tag = '(?!(?:'
18906 + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
18907 + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
18908 + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
18910 block.html = replace(block.html)
18911 ('comment', /<!--[\s\S]*?-->/)
18912 ('closed', /<(tag)[\s\S]+?<\/\1>/)
18913 ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
18914 (/tag/g, block._tag)
18917 block.paragraph = replace(block.paragraph)
18919 ('heading', block.heading)
18920 ('lheading', block.lheading)
18921 ('blockquote', block.blockquote)
18922 ('tag', '<' + block._tag)
18927 * Normal Block Grammar
18930 block.normal = merge({}, block);
18933 * GFM Block Grammar
18936 block.gfm = merge({}, block.normal, {
18937 fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
18939 heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
18942 block.gfm.paragraph = replace(block.paragraph)
18944 + block.gfm.fences.source.replace('\\1', '\\2') + '|'
18945 + block.list.source.replace('\\1', '\\3') + '|')
18949 * GFM + Tables Block Grammar
18952 block.tables = merge({}, block.gfm, {
18953 nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
18954 table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
18961 var Lexer = function (options) {
18963 this.tokens.links = {};
18964 this.options = options || marked.defaults;
18965 this.rules = block.normal;
18967 if (this.options.gfm) {
18968 if (this.options.tables) {
18969 this.rules = block.tables;
18971 this.rules = block.gfm;
18977 * Expose Block Rules
18980 Lexer.rules = block;
18983 * Static Lex Method
18986 Lexer.lex = function(src, options) {
18987 var lexer = new Lexer(options);
18988 return lexer.lex(src);
18995 Lexer.prototype.lex = function(src) {
18997 .replace(/\r\n|\r/g, '\n')
18998 .replace(/\t/g, ' ')
18999 .replace(/\u00a0/g, ' ')
19000 .replace(/\u2424/g, '\n');
19002 return this.token(src, true);
19009 Lexer.prototype.token = function(src, top, bq) {
19010 var src = src.replace(/^ +$/gm, '')
19023 if (cap = this.rules.newline.exec(src)) {
19024 src = src.substring(cap[0].length);
19025 if (cap[0].length > 1) {
19033 if (cap = this.rules.code.exec(src)) {
19034 src = src.substring(cap[0].length);
19035 cap = cap[0].replace(/^ {4}/gm, '');
19038 text: !this.options.pedantic
19039 ? cap.replace(/\n+$/, '')
19046 if (cap = this.rules.fences.exec(src)) {
19047 src = src.substring(cap[0].length);
19057 if (cap = this.rules.heading.exec(src)) {
19058 src = src.substring(cap[0].length);
19061 depth: cap[1].length,
19067 // table no leading pipe (gfm)
19068 if (top && (cap = this.rules.nptable.exec(src))) {
19069 src = src.substring(cap[0].length);
19073 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
19074 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
19075 cells: cap[3].replace(/\n$/, '').split('\n')
19078 for (i = 0; i < item.align.length; i++) {
19079 if (/^ *-+: *$/.test(item.align[i])) {
19080 item.align[i] = 'right';
19081 } else if (/^ *:-+: *$/.test(item.align[i])) {
19082 item.align[i] = 'center';
19083 } else if (/^ *:-+ *$/.test(item.align[i])) {
19084 item.align[i] = 'left';
19086 item.align[i] = null;
19090 for (i = 0; i < item.cells.length; i++) {
19091 item.cells[i] = item.cells[i].split(/ *\| */);
19094 this.tokens.push(item);
19100 if (cap = this.rules.lheading.exec(src)) {
19101 src = src.substring(cap[0].length);
19104 depth: cap[2] === '=' ? 1 : 2,
19111 if (cap = this.rules.hr.exec(src)) {
19112 src = src.substring(cap[0].length);
19120 if (cap = this.rules.blockquote.exec(src)) {
19121 src = src.substring(cap[0].length);
19124 type: 'blockquote_start'
19127 cap = cap[0].replace(/^ *> ?/gm, '');
19129 // Pass `top` to keep the current
19130 // "toplevel" state. This is exactly
19131 // how markdown.pl works.
19132 this.token(cap, top, true);
19135 type: 'blockquote_end'
19142 if (cap = this.rules.list.exec(src)) {
19143 src = src.substring(cap[0].length);
19147 type: 'list_start',
19148 ordered: bull.length > 1
19151 // Get each top-level item.
19152 cap = cap[0].match(this.rules.item);
19158 for (; i < l; i++) {
19161 // Remove the list item's bullet
19162 // so it is seen as the next token.
19163 space = item.length;
19164 item = item.replace(/^ *([*+-]|\d+\.) +/, '');
19166 // Outdent whatever the
19167 // list item contains. Hacky.
19168 if (~item.indexOf('\n ')) {
19169 space -= item.length;
19170 item = !this.options.pedantic
19171 ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
19172 : item.replace(/^ {1,4}/gm, '');
19175 // Determine whether the next list item belongs here.
19176 // Backpedal if it does not belong in this list.
19177 if (this.options.smartLists && i !== l - 1) {
19178 b = block.bullet.exec(cap[i + 1])[0];
19179 if (bull !== b && !(bull.length > 1 && b.length > 1)) {
19180 src = cap.slice(i + 1).join('\n') + src;
19185 // Determine whether item is loose or not.
19186 // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
19187 // for discount behavior.
19188 loose = next || /\n\n(?!\s*$)/.test(item);
19190 next = item.charAt(item.length - 1) === '\n';
19191 if (!loose) { loose = next; }
19196 ? 'loose_item_start'
19197 : 'list_item_start'
19201 this.token(item, false, bq);
19204 type: 'list_item_end'
19216 if (cap = this.rules.html.exec(src)) {
19217 src = src.substring(cap[0].length);
19219 type: this.options.sanitize
19222 pre: !this.options.sanitizer
19223 && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
19230 if ((!bq && top) && (cap = this.rules.def.exec(src))) {
19231 src = src.substring(cap[0].length);
19232 this.tokens.links[cap[1].toLowerCase()] = {
19240 if (top && (cap = this.rules.table.exec(src))) {
19241 src = src.substring(cap[0].length);
19245 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
19246 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
19247 cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
19250 for (i = 0; i < item.align.length; i++) {
19251 if (/^ *-+: *$/.test(item.align[i])) {
19252 item.align[i] = 'right';
19253 } else if (/^ *:-+: *$/.test(item.align[i])) {
19254 item.align[i] = 'center';
19255 } else if (/^ *:-+ *$/.test(item.align[i])) {
19256 item.align[i] = 'left';
19258 item.align[i] = null;
19262 for (i = 0; i < item.cells.length; i++) {
19263 item.cells[i] = item.cells[i]
19264 .replace(/^ *\| *| *\| *$/g, '')
19268 this.tokens.push(item);
19273 // top-level paragraph
19274 if (top && (cap = this.rules.paragraph.exec(src))) {
19275 src = src.substring(cap[0].length);
19278 text: cap[1].charAt(cap[1].length - 1) === '\n'
19279 ? cap[1].slice(0, -1)
19286 if (cap = this.rules.text.exec(src)) {
19287 // Top-level should never reach here.
19288 src = src.substring(cap[0].length);
19298 Error('Infinite loop on byte: ' + src.charCodeAt(0));
19302 return this.tokens;
19306 * Inline-Level Grammar
19310 escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
19311 autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
19313 tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
19314 link: /^!?\[(inside)\]\(href\)/,
19315 reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
19316 nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
19317 strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
19318 em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
19319 code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
19320 br: /^ {2,}\n(?!\s*$)/,
19322 text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
19325 inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
19326 inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
19328 inline.link = replace(inline.link)
19329 ('inside', inline._inside)
19330 ('href', inline._href)
19333 inline.reflink = replace(inline.reflink)
19334 ('inside', inline._inside)
19338 * Normal Inline Grammar
19341 inline.normal = merge({}, inline);
19344 * Pedantic Inline Grammar
19347 inline.pedantic = merge({}, inline.normal, {
19348 strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
19349 em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
19353 * GFM Inline Grammar
19356 inline.gfm = merge({}, inline.normal, {
19357 escape: replace(inline.escape)('])', '~|])')(),
19358 url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
19359 del: /^~~(?=\S)([\s\S]*?\S)~~/,
19360 text: replace(inline.text)
19362 ('|', '|https?://|')
19367 * GFM + Line Breaks Inline Grammar
19370 inline.breaks = merge({}, inline.gfm, {
19371 br: replace(inline.br)('{2,}', '*')(),
19372 text: replace(inline.gfm.text)('{2,}', '*')()
19376 * Inline Lexer & Compiler
19379 var InlineLexer = function (links, options) {
19380 this.options = options || marked.defaults;
19381 this.links = links;
19382 this.rules = inline.normal;
19383 this.renderer = this.options.renderer || new Renderer;
19384 this.renderer.options = this.options;
19388 Error('Tokens array requires a `links` property.');
19391 if (this.options.gfm) {
19392 if (this.options.breaks) {
19393 this.rules = inline.breaks;
19395 this.rules = inline.gfm;
19397 } else if (this.options.pedantic) {
19398 this.rules = inline.pedantic;
19403 * Expose Inline Rules
19406 InlineLexer.rules = inline;
19409 * Static Lexing/Compiling Method
19412 InlineLexer.output = function(src, links, options) {
19413 var inline = new InlineLexer(links, options);
19414 return inline.output(src);
19421 InlineLexer.prototype.output = function(src) {
19430 if (cap = this.rules.escape.exec(src)) {
19431 src = src.substring(cap[0].length);
19437 if (cap = this.rules.autolink.exec(src)) {
19438 src = src.substring(cap[0].length);
19439 if (cap[2] === '@') {
19440 text = cap[1].charAt(6) === ':'
19441 ? this.mangle(cap[1].substring(7))
19442 : this.mangle(cap[1]);
19443 href = this.mangle('mailto:') + text;
19445 text = escape(cap[1]);
19448 out += this.renderer.link(href, null, text);
19453 if (!this.inLink && (cap = this.rules.url.exec(src))) {
19454 src = src.substring(cap[0].length);
19455 text = escape(cap[1]);
19457 out += this.renderer.link(href, null, text);
19462 if (cap = this.rules.tag.exec(src)) {
19463 if (!this.inLink && /^<a /i.test(cap[0])) {
19464 this.inLink = true;
19465 } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
19466 this.inLink = false;
19468 src = src.substring(cap[0].length);
19469 out += this.options.sanitize
19470 ? this.options.sanitizer
19471 ? this.options.sanitizer(cap[0])
19478 if (cap = this.rules.link.exec(src)) {
19479 src = src.substring(cap[0].length);
19480 this.inLink = true;
19481 out += this.outputLink(cap, {
19485 this.inLink = false;
19490 if ((cap = this.rules.reflink.exec(src))
19491 || (cap = this.rules.nolink.exec(src))) {
19492 src = src.substring(cap[0].length);
19493 link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
19494 link = this.links[link.toLowerCase()];
19495 if (!link || !link.href) {
19496 out += cap[0].charAt(0);
19497 src = cap[0].substring(1) + src;
19500 this.inLink = true;
19501 out += this.outputLink(cap, link);
19502 this.inLink = false;
19507 if (cap = this.rules.strong.exec(src)) {
19508 src = src.substring(cap[0].length);
19509 out += this.renderer.strong(this.output(cap[2] || cap[1]));
19514 if (cap = this.rules.em.exec(src)) {
19515 src = src.substring(cap[0].length);
19516 out += this.renderer.em(this.output(cap[2] || cap[1]));
19521 if (cap = this.rules.code.exec(src)) {
19522 src = src.substring(cap[0].length);
19523 out += this.renderer.codespan(escape(cap[2], true));
19528 if (cap = this.rules.br.exec(src)) {
19529 src = src.substring(cap[0].length);
19530 out += this.renderer.br();
19535 if (cap = this.rules.del.exec(src)) {
19536 src = src.substring(cap[0].length);
19537 out += this.renderer.del(this.output(cap[1]));
19542 if (cap = this.rules.text.exec(src)) {
19543 src = src.substring(cap[0].length);
19544 out += this.renderer.text(escape(this.smartypants(cap[0])));
19550 Error('Infinite loop on byte: ' + src.charCodeAt(0));
19561 InlineLexer.prototype.outputLink = function(cap, link) {
19562 var href = escape(link.href)
19563 , title = link.title ? escape(link.title) : null;
19565 return cap[0].charAt(0) !== '!'
19566 ? this.renderer.link(href, title, this.output(cap[1]))
19567 : this.renderer.image(href, title, escape(cap[1]));
19571 * Smartypants Transformations
19574 InlineLexer.prototype.smartypants = function(text) {
19575 if (!this.options.smartypants) { return text; }
19578 .replace(/---/g, '\u2014')
19580 .replace(/--/g, '\u2013')
19582 .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
19583 // closing singles & apostrophes
19584 .replace(/'/g, '\u2019')
19586 .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
19588 .replace(/"/g, '\u201d')
19590 .replace(/\.{3}/g, '\u2026');
19597 InlineLexer.prototype.mangle = function(text) {
19598 if (!this.options.mangle) { return text; }
19604 for (; i < l; i++) {
19605 ch = text.charCodeAt(i);
19606 if (Math.random() > 0.5) {
19607 ch = 'x' + ch.toString(16);
19609 out += '&#' + ch + ';';
19620 * eval:var:Renderer
19623 var Renderer = function (options) {
19624 this.options = options || {};
19627 Renderer.prototype.code = function(code, lang, escaped) {
19628 if (this.options.highlight) {
19629 var out = this.options.highlight(code, lang);
19630 if (out != null && out !== code) {
19635 // hack!!! - it's already escapeD?
19640 return '<pre><code>'
19641 + (escaped ? code : escape(code, true))
19642 + '\n</code></pre>';
19645 return '<pre><code class="'
19646 + this.options.langPrefix
19647 + escape(lang, true)
19649 + (escaped ? code : escape(code, true))
19650 + '\n</code></pre>\n';
19653 Renderer.prototype.blockquote = function(quote) {
19654 return '<blockquote>\n' + quote + '</blockquote>\n';
19657 Renderer.prototype.html = function(html) {
19661 Renderer.prototype.heading = function(text, level, raw) {
19665 + this.options.headerPrefix
19666 + raw.toLowerCase().replace(/[^\w]+/g, '-')
19674 Renderer.prototype.hr = function() {
19675 return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
19678 Renderer.prototype.list = function(body, ordered) {
19679 var type = ordered ? 'ol' : 'ul';
19680 return '<' + type + '>\n' + body + '</' + type + '>\n';
19683 Renderer.prototype.listitem = function(text) {
19684 return '<li>' + text + '</li>\n';
19687 Renderer.prototype.paragraph = function(text) {
19688 return '<p>' + text + '</p>\n';
19691 Renderer.prototype.table = function(header, body) {
19692 return '<table class="table table-striped">\n'
19702 Renderer.prototype.tablerow = function(content) {
19703 return '<tr>\n' + content + '</tr>\n';
19706 Renderer.prototype.tablecell = function(content, flags) {
19707 var type = flags.header ? 'th' : 'td';
19708 var tag = flags.align
19709 ? '<' + type + ' style="text-align:' + flags.align + '">'
19710 : '<' + type + '>';
19711 return tag + content + '</' + type + '>\n';
19714 // span level renderer
19715 Renderer.prototype.strong = function(text) {
19716 return '<strong>' + text + '</strong>';
19719 Renderer.prototype.em = function(text) {
19720 return '<em>' + text + '</em>';
19723 Renderer.prototype.codespan = function(text) {
19724 return '<code>' + text + '</code>';
19727 Renderer.prototype.br = function() {
19728 return this.options.xhtml ? '<br/>' : '<br>';
19731 Renderer.prototype.del = function(text) {
19732 return '<del>' + text + '</del>';
19735 Renderer.prototype.link = function(href, title, text) {
19736 if (this.options.sanitize) {
19738 var prot = decodeURIComponent(unescape(href))
19739 .replace(/[^\w:]/g, '')
19744 if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
19748 var out = '<a href="' + href + '"';
19750 out += ' title="' + title + '"';
19752 out += '>' + text + '</a>';
19756 Renderer.prototype.image = function(href, title, text) {
19757 var out = '<img src="' + href + '" alt="' + text + '"';
19759 out += ' title="' + title + '"';
19761 out += this.options.xhtml ? '/>' : '>';
19765 Renderer.prototype.text = function(text) {
19770 * Parsing & Compiling
19776 var Parser= function (options) {
19779 this.options = options || marked.defaults;
19780 this.options.renderer = this.options.renderer || new Renderer;
19781 this.renderer = this.options.renderer;
19782 this.renderer.options = this.options;
19786 * Static Parse Method
19789 Parser.parse = function(src, options, renderer) {
19790 var parser = new Parser(options, renderer);
19791 return parser.parse(src);
19798 Parser.prototype.parse = function(src) {
19799 this.inline = new InlineLexer(src.links, this.options, this.renderer);
19800 this.tokens = src.reverse();
19803 while (this.next()) {
19814 Parser.prototype.next = function() {
19815 return this.token = this.tokens.pop();
19819 * Preview Next Token
19822 Parser.prototype.peek = function() {
19823 return this.tokens[this.tokens.length - 1] || 0;
19827 * Parse Text Tokens
19830 Parser.prototype.parseText = function() {
19831 var body = this.token.text;
19833 while (this.peek().type === 'text') {
19834 body += '\n' + this.next().text;
19837 return this.inline.output(body);
19841 * Parse Current Token
19844 Parser.prototype.tok = function() {
19845 switch (this.token.type) {
19850 return this.renderer.hr();
19853 return this.renderer.heading(
19854 this.inline.output(this.token.text),
19859 return this.renderer.code(this.token.text,
19861 this.token.escaped);
19874 for (i = 0; i < this.token.header.length; i++) {
19875 flags = { header: true, align: this.token.align[i] };
19876 cell += this.renderer.tablecell(
19877 this.inline.output(this.token.header[i]),
19878 { header: true, align: this.token.align[i] }
19881 header += this.renderer.tablerow(cell);
19883 for (i = 0; i < this.token.cells.length; i++) {
19884 row = this.token.cells[i];
19887 for (j = 0; j < row.length; j++) {
19888 cell += this.renderer.tablecell(
19889 this.inline.output(row[j]),
19890 { header: false, align: this.token.align[j] }
19894 body += this.renderer.tablerow(cell);
19896 return this.renderer.table(header, body);
19898 case 'blockquote_start': {
19901 while (this.next().type !== 'blockquote_end') {
19902 body += this.tok();
19905 return this.renderer.blockquote(body);
19907 case 'list_start': {
19909 , ordered = this.token.ordered;
19911 while (this.next().type !== 'list_end') {
19912 body += this.tok();
19915 return this.renderer.list(body, ordered);
19917 case 'list_item_start': {
19920 while (this.next().type !== 'list_item_end') {
19921 body += this.token.type === 'text'
19926 return this.renderer.listitem(body);
19928 case 'loose_item_start': {
19931 while (this.next().type !== 'list_item_end') {
19932 body += this.tok();
19935 return this.renderer.listitem(body);
19938 var html = !this.token.pre && !this.options.pedantic
19939 ? this.inline.output(this.token.text)
19941 return this.renderer.html(html);
19943 case 'paragraph': {
19944 return this.renderer.paragraph(this.inline.output(this.token.text));
19947 return this.renderer.paragraph(this.parseText());
19959 var marked = function (src, opt, callback) {
19960 if (callback || typeof opt === 'function') {
19966 opt = merge({}, marked.defaults, opt || {});
19968 var highlight = opt.highlight
19974 tokens = Lexer.lex(src, opt)
19976 return callback(e);
19979 pending = tokens.length;
19983 var done = function(err) {
19985 opt.highlight = highlight;
19986 return callback(err);
19992 out = Parser.parse(tokens, opt);
19997 opt.highlight = highlight;
20001 : callback(null, out);
20004 if (!highlight || highlight.length < 3) {
20008 delete opt.highlight;
20010 if (!pending) { return done(); }
20012 for (; i < tokens.length; i++) {
20014 if (token.type !== 'code') {
20015 return --pending || done();
20017 return highlight(token.text, token.lang, function(err, code) {
20018 if (err) { return done(err); }
20019 if (code == null || code === token.text) {
20020 return --pending || done();
20023 token.escaped = true;
20024 --pending || done();
20032 if (opt) { opt = merge({}, marked.defaults, opt); }
20033 return Parser.parse(Lexer.lex(src, opt), opt);
20035 e.message += '\nPlease report this to https://github.com/chjj/marked.';
20036 if ((opt || marked.defaults).silent) {
20037 return '<p>An error occured:</p><pre>'
20038 + escape(e.message + '', true)
20050 marked.setOptions = function(opt) {
20051 merge(marked.defaults, opt);
20055 marked.defaults = {
20066 langPrefix: 'lang-',
20067 smartypants: false,
20069 renderer: new Renderer,
20077 marked.Parser = Parser;
20078 marked.parser = Parser.parse;
20080 marked.Renderer = Renderer;
20082 marked.Lexer = Lexer;
20083 marked.lexer = Lexer.lex;
20085 marked.InlineLexer = InlineLexer;
20086 marked.inlineLexer = InlineLexer.output;
20088 marked.parse = marked;
20090 Roo.Markdown.marked = marked;
20094 * Ext JS Library 1.1.1
20095 * Copyright(c) 2006-2007, Ext JS, LLC.
20097 * Originally Released Under LGPL - original licence link has changed is not relivant.
20100 * <script type="text/javascript">
20106 * These classes are derivatives of the similarly named classes in the YUI Library.
20107 * The original license:
20108 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
20109 * Code licensed under the BSD License:
20110 * http://developer.yahoo.net/yui/license.txt
20115 var Event=Roo.EventManager;
20116 var Dom=Roo.lib.Dom;
20119 * @class Roo.dd.DragDrop
20120 * @extends Roo.util.Observable
20121 * Defines the interface and base operation of items that that can be
20122 * dragged or can be drop targets. It was designed to be extended, overriding
20123 * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
20124 * Up to three html elements can be associated with a DragDrop instance:
20126 * <li>linked element: the element that is passed into the constructor.
20127 * This is the element which defines the boundaries for interaction with
20128 * other DragDrop objects.</li>
20129 * <li>handle element(s): The drag operation only occurs if the element that
20130 * was clicked matches a handle element. By default this is the linked
20131 * element, but there are times that you will want only a portion of the
20132 * linked element to initiate the drag operation, and the setHandleElId()
20133 * method provides a way to define this.</li>
20134 * <li>drag element: this represents the element that would be moved along
20135 * with the cursor during a drag operation. By default, this is the linked
20136 * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
20137 * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
20140 * This class should not be instantiated until the onload event to ensure that
20141 * the associated elements are available.
20142 * The following would define a DragDrop obj that would interact with any
20143 * other DragDrop obj in the "group1" group:
20145 * dd = new Roo.dd.DragDrop("div1", "group1");
20147 * Since none of the event handlers have been implemented, nothing would
20148 * actually happen if you were to run the code above. Normally you would
20149 * override this class or one of the default implementations, but you can
20150 * also override the methods you want on an instance of the class...
20152 * dd.onDragDrop = function(e, id) {
20153 * alert("dd was dropped on " + id);
20157 * @param {String} id of the element that is linked to this instance
20158 * @param {String} sGroup the group of related DragDrop objects
20159 * @param {object} config an object containing configurable attributes
20160 * Valid properties for DragDrop:
20161 * padding, isTarget, maintainOffset, primaryButtonOnly
20163 Roo.dd.DragDrop = function(id, sGroup, config) {
20165 this.init(id, sGroup, config);
20170 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
20173 * The id of the element associated with this object. This is what we
20174 * refer to as the "linked element" because the size and position of
20175 * this element is used to determine when the drag and drop objects have
20183 * Configuration attributes passed into the constructor
20190 * The id of the element that will be dragged. By default this is same
20191 * as the linked element , but could be changed to another element. Ex:
20193 * @property dragElId
20200 * the id of the element that initiates the drag operation. By default
20201 * this is the linked element, but could be changed to be a child of this
20202 * element. This lets us do things like only starting the drag when the
20203 * header element within the linked html element is clicked.
20204 * @property handleElId
20211 * An associative array of HTML tags that will be ignored if clicked.
20212 * @property invalidHandleTypes
20213 * @type {string: string}
20215 invalidHandleTypes: null,
20218 * An associative array of ids for elements that will be ignored if clicked
20219 * @property invalidHandleIds
20220 * @type {string: string}
20222 invalidHandleIds: null,
20225 * An indexted array of css class names for elements that will be ignored
20227 * @property invalidHandleClasses
20230 invalidHandleClasses: null,
20233 * The linked element's absolute X position at the time the drag was
20235 * @property startPageX
20242 * The linked element's absolute X position at the time the drag was
20244 * @property startPageY
20251 * The group defines a logical collection of DragDrop objects that are
20252 * related. Instances only get events when interacting with other
20253 * DragDrop object in the same group. This lets us define multiple
20254 * groups using a single DragDrop subclass if we want.
20256 * @type {string: string}
20261 * Individual drag/drop instances can be locked. This will prevent
20262 * onmousedown start drag.
20270 * Lock this instance
20273 lock: function() { this.locked = true; },
20276 * Unlock this instace
20279 unlock: function() { this.locked = false; },
20282 * By default, all insances can be a drop target. This can be disabled by
20283 * setting isTarget to false.
20290 * The padding configured for this drag and drop object for calculating
20291 * the drop zone intersection with this object.
20298 * Cached reference to the linked element
20299 * @property _domRef
20305 * Internal typeof flag
20306 * @property __ygDragDrop
20309 __ygDragDrop: true,
20312 * Set to true when horizontal contraints are applied
20313 * @property constrainX
20320 * Set to true when vertical contraints are applied
20321 * @property constrainY
20328 * The left constraint
20336 * The right constraint
20344 * The up constraint
20353 * The down constraint
20361 * Maintain offsets when we resetconstraints. Set to true when you want
20362 * the position of the element relative to its parent to stay the same
20363 * when the page changes
20365 * @property maintainOffset
20368 maintainOffset: false,
20371 * Array of pixel locations the element will snap to if we specified a
20372 * horizontal graduation/interval. This array is generated automatically
20373 * when you define a tick interval.
20380 * Array of pixel locations the element will snap to if we specified a
20381 * vertical graduation/interval. This array is generated automatically
20382 * when you define a tick interval.
20389 * By default the drag and drop instance will only respond to the primary
20390 * button click (left button for a right-handed mouse). Set to true to
20391 * allow drag and drop to start with any mouse click that is propogated
20393 * @property primaryButtonOnly
20396 primaryButtonOnly: true,
20399 * The availabe property is false until the linked dom element is accessible.
20400 * @property available
20406 * By default, drags can only be initiated if the mousedown occurs in the
20407 * region the linked element is. This is done in part to work around a
20408 * bug in some browsers that mis-report the mousedown if the previous
20409 * mouseup happened outside of the window. This property is set to true
20410 * if outer handles are defined.
20412 * @property hasOuterHandles
20416 hasOuterHandles: false,
20419 * Code that executes immediately before the startDrag event
20420 * @method b4StartDrag
20423 b4StartDrag: function(x, y) { },
20426 * Abstract method called after a drag/drop object is clicked
20427 * and the drag or mousedown time thresholds have beeen met.
20428 * @method startDrag
20429 * @param {int} X click location
20430 * @param {int} Y click location
20432 startDrag: function(x, y) { /* override this */ },
20435 * Code that executes immediately before the onDrag event
20439 b4Drag: function(e) { },
20442 * Abstract method called during the onMouseMove event while dragging an
20445 * @param {Event} e the mousemove event
20447 onDrag: function(e) { /* override this */ },
20450 * Abstract method called when this element fist begins hovering over
20451 * another DragDrop obj
20452 * @method onDragEnter
20453 * @param {Event} e the mousemove event
20454 * @param {String|DragDrop[]} id In POINT mode, the element
20455 * id this is hovering over. In INTERSECT mode, an array of one or more
20456 * dragdrop items being hovered over.
20458 onDragEnter: function(e, id) { /* override this */ },
20461 * Code that executes immediately before the onDragOver event
20462 * @method b4DragOver
20465 b4DragOver: function(e) { },
20468 * Abstract method called when this element is hovering over another
20470 * @method onDragOver
20471 * @param {Event} e the mousemove event
20472 * @param {String|DragDrop[]} id In POINT mode, the element
20473 * id this is hovering over. In INTERSECT mode, an array of dd items
20474 * being hovered over.
20476 onDragOver: function(e, id) { /* override this */ },
20479 * Code that executes immediately before the onDragOut event
20480 * @method b4DragOut
20483 b4DragOut: function(e) { },
20486 * Abstract method called when we are no longer hovering over an element
20487 * @method onDragOut
20488 * @param {Event} e the mousemove event
20489 * @param {String|DragDrop[]} id In POINT mode, the element
20490 * id this was hovering over. In INTERSECT mode, an array of dd items
20491 * that the mouse is no longer over.
20493 onDragOut: function(e, id) { /* override this */ },
20496 * Code that executes immediately before the onDragDrop event
20497 * @method b4DragDrop
20500 b4DragDrop: function(e) { },
20503 * Abstract method called when this item is dropped on another DragDrop
20505 * @method onDragDrop
20506 * @param {Event} e the mouseup event
20507 * @param {String|DragDrop[]} id In POINT mode, the element
20508 * id this was dropped on. In INTERSECT mode, an array of dd items this
20511 onDragDrop: function(e, id) { /* override this */ },
20514 * Abstract method called when this item is dropped on an area with no
20516 * @method onInvalidDrop
20517 * @param {Event} e the mouseup event
20519 onInvalidDrop: function(e) { /* override this */ },
20522 * Code that executes immediately before the endDrag event
20523 * @method b4EndDrag
20526 b4EndDrag: function(e) { },
20529 * Fired when we are done dragging the object
20531 * @param {Event} e the mouseup event
20533 endDrag: function(e) { /* override this */ },
20536 * Code executed immediately before the onMouseDown event
20537 * @method b4MouseDown
20538 * @param {Event} e the mousedown event
20541 b4MouseDown: function(e) { },
20544 * Event handler that fires when a drag/drop obj gets a mousedown
20545 * @method onMouseDown
20546 * @param {Event} e the mousedown event
20548 onMouseDown: function(e) { /* override this */ },
20551 * Event handler that fires when a drag/drop obj gets a mouseup
20552 * @method onMouseUp
20553 * @param {Event} e the mouseup event
20555 onMouseUp: function(e) { /* override this */ },
20558 * Override the onAvailable method to do what is needed after the initial
20559 * position was determined.
20560 * @method onAvailable
20562 onAvailable: function () {
20566 * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
20569 defaultPadding : {left:0, right:0, top:0, bottom:0},
20572 * Initializes the drag drop object's constraints to restrict movement to a certain element.
20576 var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
20577 { dragElId: "existingProxyDiv" });
20578 dd.startDrag = function(){
20579 this.constrainTo("parent-id");
20582 * Or you can initalize it using the {@link Roo.Element} object:
20584 Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
20585 startDrag : function(){
20586 this.constrainTo("parent-id");
20590 * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
20591 * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
20592 * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
20593 * an object containing the sides to pad. For example: {right:10, bottom:10}
20594 * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
20596 constrainTo : function(constrainTo, pad, inContent){
20597 if(typeof pad == "number"){
20598 pad = {left: pad, right:pad, top:pad, bottom:pad};
20600 pad = pad || this.defaultPadding;
20601 var b = Roo.get(this.getEl()).getBox();
20602 var ce = Roo.get(constrainTo);
20603 var s = ce.getScroll();
20604 var c, cd = ce.dom;
20605 if(cd == document.body){
20606 c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
20609 c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
20613 var topSpace = b.y - c.y;
20614 var leftSpace = b.x - c.x;
20616 this.resetConstraints();
20617 this.setXConstraint(leftSpace - (pad.left||0), // left
20618 c.width - leftSpace - b.width - (pad.right||0) //right
20620 this.setYConstraint(topSpace - (pad.top||0), //top
20621 c.height - topSpace - b.height - (pad.bottom||0) //bottom
20626 * Returns a reference to the linked element
20628 * @return {HTMLElement} the html element
20630 getEl: function() {
20631 if (!this._domRef) {
20632 this._domRef = Roo.getDom(this.id);
20635 return this._domRef;
20639 * Returns a reference to the actual element to drag. By default this is
20640 * the same as the html element, but it can be assigned to another
20641 * element. An example of this can be found in Roo.dd.DDProxy
20642 * @method getDragEl
20643 * @return {HTMLElement} the html element
20645 getDragEl: function() {
20646 return Roo.getDom(this.dragElId);
20650 * Sets up the DragDrop object. Must be called in the constructor of any
20651 * Roo.dd.DragDrop subclass
20653 * @param id the id of the linked element
20654 * @param {String} sGroup the group of related items
20655 * @param {object} config configuration attributes
20657 init: function(id, sGroup, config) {
20658 this.initTarget(id, sGroup, config);
20659 if (!Roo.isTouch) {
20660 Event.on(this.id, "mousedown", this.handleMouseDown, this);
20662 Event.on(this.id, "touchstart", this.handleMouseDown, this);
20663 // Event.on(this.id, "selectstart", Event.preventDefault);
20667 * Initializes Targeting functionality only... the object does not
20668 * get a mousedown handler.
20669 * @method initTarget
20670 * @param id the id of the linked element
20671 * @param {String} sGroup the group of related items
20672 * @param {object} config configuration attributes
20674 initTarget: function(id, sGroup, config) {
20676 // configuration attributes
20677 this.config = config || {};
20679 // create a local reference to the drag and drop manager
20680 this.DDM = Roo.dd.DDM;
20681 // initialize the groups array
20684 // assume that we have an element reference instead of an id if the
20685 // parameter is not a string
20686 if (typeof id !== "string") {
20693 // add to an interaction group
20694 this.addToGroup((sGroup) ? sGroup : "default");
20696 // We don't want to register this as the handle with the manager
20697 // so we just set the id rather than calling the setter.
20698 this.handleElId = id;
20700 // the linked element is the element that gets dragged by default
20701 this.setDragElId(id);
20703 // by default, clicked anchors will not start drag operations.
20704 this.invalidHandleTypes = { A: "A" };
20705 this.invalidHandleIds = {};
20706 this.invalidHandleClasses = [];
20708 this.applyConfig();
20710 this.handleOnAvailable();
20714 * Applies the configuration parameters that were passed into the constructor.
20715 * This is supposed to happen at each level through the inheritance chain. So
20716 * a DDProxy implentation will execute apply config on DDProxy, DD, and
20717 * DragDrop in order to get all of the parameters that are available in
20719 * @method applyConfig
20721 applyConfig: function() {
20723 // configurable properties:
20724 // padding, isTarget, maintainOffset, primaryButtonOnly
20725 this.padding = this.config.padding || [0, 0, 0, 0];
20726 this.isTarget = (this.config.isTarget !== false);
20727 this.maintainOffset = (this.config.maintainOffset);
20728 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
20733 * Executed when the linked element is available
20734 * @method handleOnAvailable
20737 handleOnAvailable: function() {
20738 this.available = true;
20739 this.resetConstraints();
20740 this.onAvailable();
20744 * Configures the padding for the target zone in px. Effectively expands
20745 * (or reduces) the virtual object size for targeting calculations.
20746 * Supports css-style shorthand; if only one parameter is passed, all sides
20747 * will have that padding, and if only two are passed, the top and bottom
20748 * will have the first param, the left and right the second.
20749 * @method setPadding
20750 * @param {int} iTop Top pad
20751 * @param {int} iRight Right pad
20752 * @param {int} iBot Bot pad
20753 * @param {int} iLeft Left pad
20755 setPadding: function(iTop, iRight, iBot, iLeft) {
20756 // this.padding = [iLeft, iRight, iTop, iBot];
20757 if (!iRight && 0 !== iRight) {
20758 this.padding = [iTop, iTop, iTop, iTop];
20759 } else if (!iBot && 0 !== iBot) {
20760 this.padding = [iTop, iRight, iTop, iRight];
20762 this.padding = [iTop, iRight, iBot, iLeft];
20767 * Stores the initial placement of the linked element.
20768 * @method setInitialPosition
20769 * @param {int} diffX the X offset, default 0
20770 * @param {int} diffY the Y offset, default 0
20772 setInitPosition: function(diffX, diffY) {
20773 var el = this.getEl();
20775 if (!this.DDM.verifyEl(el)) {
20779 var dx = diffX || 0;
20780 var dy = diffY || 0;
20782 var p = Dom.getXY( el );
20784 this.initPageX = p[0] - dx;
20785 this.initPageY = p[1] - dy;
20787 this.lastPageX = p[0];
20788 this.lastPageY = p[1];
20791 this.setStartPosition(p);
20795 * Sets the start position of the element. This is set when the obj
20796 * is initialized, the reset when a drag is started.
20797 * @method setStartPosition
20798 * @param pos current position (from previous lookup)
20801 setStartPosition: function(pos) {
20802 var p = pos || Dom.getXY( this.getEl() );
20803 this.deltaSetXY = null;
20805 this.startPageX = p[0];
20806 this.startPageY = p[1];
20810 * Add this instance to a group of related drag/drop objects. All
20811 * instances belong to at least one group, and can belong to as many
20812 * groups as needed.
20813 * @method addToGroup
20814 * @param sGroup {string} the name of the group
20816 addToGroup: function(sGroup) {
20817 this.groups[sGroup] = true;
20818 this.DDM.regDragDrop(this, sGroup);
20822 * Remove's this instance from the supplied interaction group
20823 * @method removeFromGroup
20824 * @param {string} sGroup The group to drop
20826 removeFromGroup: function(sGroup) {
20827 if (this.groups[sGroup]) {
20828 delete this.groups[sGroup];
20831 this.DDM.removeDDFromGroup(this, sGroup);
20835 * Allows you to specify that an element other than the linked element
20836 * will be moved with the cursor during a drag
20837 * @method setDragElId
20838 * @param id {string} the id of the element that will be used to initiate the drag
20840 setDragElId: function(id) {
20841 this.dragElId = id;
20845 * Allows you to specify a child of the linked element that should be
20846 * used to initiate the drag operation. An example of this would be if
20847 * you have a content div with text and links. Clicking anywhere in the
20848 * content area would normally start the drag operation. Use this method
20849 * to specify that an element inside of the content div is the element
20850 * that starts the drag operation.
20851 * @method setHandleElId
20852 * @param id {string} the id of the element that will be used to
20853 * initiate the drag.
20855 setHandleElId: function(id) {
20856 if (typeof id !== "string") {
20859 this.handleElId = id;
20860 this.DDM.regHandle(this.id, id);
20864 * Allows you to set an element outside of the linked element as a drag
20866 * @method setOuterHandleElId
20867 * @param id the id of the element that will be used to initiate the drag
20869 setOuterHandleElId: function(id) {
20870 if (typeof id !== "string") {
20873 Event.on(id, "mousedown",
20874 this.handleMouseDown, this);
20875 this.setHandleElId(id);
20877 this.hasOuterHandles = true;
20881 * Remove all drag and drop hooks for this element
20884 unreg: function() {
20885 Event.un(this.id, "mousedown",
20886 this.handleMouseDown);
20887 Event.un(this.id, "touchstart",
20888 this.handleMouseDown);
20889 this._domRef = null;
20890 this.DDM._remove(this);
20893 destroy : function(){
20898 * Returns true if this instance is locked, or the drag drop mgr is locked
20899 * (meaning that all drag/drop is disabled on the page.)
20901 * @return {boolean} true if this obj or all drag/drop is locked, else
20904 isLocked: function() {
20905 return (this.DDM.isLocked() || this.locked);
20909 * Fired when this object is clicked
20910 * @method handleMouseDown
20912 * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
20915 handleMouseDown: function(e, oDD){
20917 if (!Roo.isTouch && this.primaryButtonOnly && e.button != 0) {
20918 //Roo.log('not touch/ button !=0');
20921 if (e.browserEvent.touches && e.browserEvent.touches.length != 1) {
20922 return; // double touch..
20926 if (this.isLocked()) {
20927 //Roo.log('locked');
20931 this.DDM.refreshCache(this.groups);
20932 // Roo.log([Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e)]);
20933 var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
20934 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
20935 //Roo.log('no outer handes or not over target');
20938 // Roo.log('check validator');
20939 if (this.clickValidator(e)) {
20940 // Roo.log('validate success');
20941 // set the initial element position
20942 this.setStartPosition();
20945 this.b4MouseDown(e);
20946 this.onMouseDown(e);
20948 this.DDM.handleMouseDown(e, this);
20950 this.DDM.stopEvent(e);
20958 clickValidator: function(e) {
20959 var target = e.getTarget();
20960 return ( this.isValidHandleChild(target) &&
20961 (this.id == this.handleElId ||
20962 this.DDM.handleWasClicked(target, this.id)) );
20966 * Allows you to specify a tag name that should not start a drag operation
20967 * when clicked. This is designed to facilitate embedding links within a
20968 * drag handle that do something other than start the drag.
20969 * @method addInvalidHandleType
20970 * @param {string} tagName the type of element to exclude
20972 addInvalidHandleType: function(tagName) {
20973 var type = tagName.toUpperCase();
20974 this.invalidHandleTypes[type] = type;
20978 * Lets you to specify an element id for a child of a drag handle
20979 * that should not initiate a drag
20980 * @method addInvalidHandleId
20981 * @param {string} id the element id of the element you wish to ignore
20983 addInvalidHandleId: function(id) {
20984 if (typeof id !== "string") {
20987 this.invalidHandleIds[id] = id;
20991 * Lets you specify a css class of elements that will not initiate a drag
20992 * @method addInvalidHandleClass
20993 * @param {string} cssClass the class of the elements you wish to ignore
20995 addInvalidHandleClass: function(cssClass) {
20996 this.invalidHandleClasses.push(cssClass);
21000 * Unsets an excluded tag name set by addInvalidHandleType
21001 * @method removeInvalidHandleType
21002 * @param {string} tagName the type of element to unexclude
21004 removeInvalidHandleType: function(tagName) {
21005 var type = tagName.toUpperCase();
21006 // this.invalidHandleTypes[type] = null;
21007 delete this.invalidHandleTypes[type];
21011 * Unsets an invalid handle id
21012 * @method removeInvalidHandleId
21013 * @param {string} id the id of the element to re-enable
21015 removeInvalidHandleId: function(id) {
21016 if (typeof id !== "string") {
21019 delete this.invalidHandleIds[id];
21023 * Unsets an invalid css class
21024 * @method removeInvalidHandleClass
21025 * @param {string} cssClass the class of the element(s) you wish to
21028 removeInvalidHandleClass: function(cssClass) {
21029 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
21030 if (this.invalidHandleClasses[i] == cssClass) {
21031 delete this.invalidHandleClasses[i];
21037 * Checks the tag exclusion list to see if this click should be ignored
21038 * @method isValidHandleChild
21039 * @param {HTMLElement} node the HTMLElement to evaluate
21040 * @return {boolean} true if this is a valid tag type, false if not
21042 isValidHandleChild: function(node) {
21045 // var n = (node.nodeName == "#text") ? node.parentNode : node;
21048 nodeName = node.nodeName.toUpperCase();
21050 nodeName = node.nodeName;
21052 valid = valid && !this.invalidHandleTypes[nodeName];
21053 valid = valid && !this.invalidHandleIds[node.id];
21055 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
21056 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
21065 * Create the array of horizontal tick marks if an interval was specified
21066 * in setXConstraint().
21067 * @method setXTicks
21070 setXTicks: function(iStartX, iTickSize) {
21072 this.xTickSize = iTickSize;
21076 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
21078 this.xTicks[this.xTicks.length] = i;
21083 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
21085 this.xTicks[this.xTicks.length] = i;
21090 this.xTicks.sort(this.DDM.numericSort) ;
21094 * Create the array of vertical tick marks if an interval was specified in
21095 * setYConstraint().
21096 * @method setYTicks
21099 setYTicks: function(iStartY, iTickSize) {
21101 this.yTickSize = iTickSize;
21105 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
21107 this.yTicks[this.yTicks.length] = i;
21112 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
21114 this.yTicks[this.yTicks.length] = i;
21119 this.yTicks.sort(this.DDM.numericSort) ;
21123 * By default, the element can be dragged any place on the screen. Use
21124 * this method to limit the horizontal travel of the element. Pass in
21125 * 0,0 for the parameters if you want to lock the drag to the y axis.
21126 * @method setXConstraint
21127 * @param {int} iLeft the number of pixels the element can move to the left
21128 * @param {int} iRight the number of pixels the element can move to the
21130 * @param {int} iTickSize optional parameter for specifying that the
21132 * should move iTickSize pixels at a time.
21134 setXConstraint: function(iLeft, iRight, iTickSize) {
21135 this.leftConstraint = iLeft;
21136 this.rightConstraint = iRight;
21138 this.minX = this.initPageX - iLeft;
21139 this.maxX = this.initPageX + iRight;
21140 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
21142 this.constrainX = true;
21146 * Clears any constraints applied to this instance. Also clears ticks
21147 * since they can't exist independent of a constraint at this time.
21148 * @method clearConstraints
21150 clearConstraints: function() {
21151 this.constrainX = false;
21152 this.constrainY = false;
21157 * Clears any tick interval defined for this instance
21158 * @method clearTicks
21160 clearTicks: function() {
21161 this.xTicks = null;
21162 this.yTicks = null;
21163 this.xTickSize = 0;
21164 this.yTickSize = 0;
21168 * By default, the element can be dragged any place on the screen. Set
21169 * this to limit the vertical travel of the element. Pass in 0,0 for the
21170 * parameters if you want to lock the drag to the x axis.
21171 * @method setYConstraint
21172 * @param {int} iUp the number of pixels the element can move up
21173 * @param {int} iDown the number of pixels the element can move down
21174 * @param {int} iTickSize optional parameter for specifying that the
21175 * element should move iTickSize pixels at a time.
21177 setYConstraint: function(iUp, iDown, iTickSize) {
21178 this.topConstraint = iUp;
21179 this.bottomConstraint = iDown;
21181 this.minY = this.initPageY - iUp;
21182 this.maxY = this.initPageY + iDown;
21183 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
21185 this.constrainY = true;
21190 * resetConstraints must be called if you manually reposition a dd element.
21191 * @method resetConstraints
21192 * @param {boolean} maintainOffset
21194 resetConstraints: function() {
21197 // Maintain offsets if necessary
21198 if (this.initPageX || this.initPageX === 0) {
21199 // figure out how much this thing has moved
21200 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
21201 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
21203 this.setInitPosition(dx, dy);
21205 // This is the first time we have detected the element's position
21207 this.setInitPosition();
21210 if (this.constrainX) {
21211 this.setXConstraint( this.leftConstraint,
21212 this.rightConstraint,
21216 if (this.constrainY) {
21217 this.setYConstraint( this.topConstraint,
21218 this.bottomConstraint,
21224 * Normally the drag element is moved pixel by pixel, but we can specify
21225 * that it move a number of pixels at a time. This method resolves the
21226 * location when we have it set up like this.
21228 * @param {int} val where we want to place the object
21229 * @param {int[]} tickArray sorted array of valid points
21230 * @return {int} the closest tick
21233 getTick: function(val, tickArray) {
21236 // If tick interval is not defined, it is effectively 1 pixel,
21237 // so we return the value passed to us.
21239 } else if (tickArray[0] >= val) {
21240 // The value is lower than the first tick, so we return the first
21242 return tickArray[0];
21244 for (var i=0, len=tickArray.length; i<len; ++i) {
21246 if (tickArray[next] && tickArray[next] >= val) {
21247 var diff1 = val - tickArray[i];
21248 var diff2 = tickArray[next] - val;
21249 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
21253 // The value is larger than the last tick, so we return the last
21255 return tickArray[tickArray.length - 1];
21262 * @return {string} string representation of the dd obj
21264 toString: function() {
21265 return ("DragDrop " + this.id);
21273 * Ext JS Library 1.1.1
21274 * Copyright(c) 2006-2007, Ext JS, LLC.
21276 * Originally Released Under LGPL - original licence link has changed is not relivant.
21279 * <script type="text/javascript">
21284 * The drag and drop utility provides a framework for building drag and drop
21285 * applications. In addition to enabling drag and drop for specific elements,
21286 * the drag and drop elements are tracked by the manager class, and the
21287 * interactions between the various elements are tracked during the drag and
21288 * the implementing code is notified about these important moments.
21291 // Only load the library once. Rewriting the manager class would orphan
21292 // existing drag and drop instances.
21293 if (!Roo.dd.DragDropMgr) {
21296 * @class Roo.dd.DragDropMgr
21297 * DragDropMgr is a singleton that tracks the element interaction for
21298 * all DragDrop items in the window. Generally, you will not call
21299 * this class directly, but it does have helper methods that could
21300 * be useful in your DragDrop implementations.
21303 Roo.dd.DragDropMgr = function() {
21305 var Event = Roo.EventManager;
21310 * Two dimensional Array of registered DragDrop objects. The first
21311 * dimension is the DragDrop item group, the second the DragDrop
21314 * @type {string: string}
21321 * Array of element ids defined as drag handles. Used to determine
21322 * if the element that generated the mousedown event is actually the
21323 * handle and not the html element itself.
21324 * @property handleIds
21325 * @type {string: string}
21332 * the DragDrop object that is currently being dragged
21333 * @property dragCurrent
21341 * the DragDrop object(s) that are being hovered over
21342 * @property dragOvers
21350 * the X distance between the cursor and the object being dragged
21359 * the Y distance between the cursor and the object being dragged
21368 * Flag to determine if we should prevent the default behavior of the
21369 * events we define. By default this is true, but this can be set to
21370 * false if you need the default behavior (not recommended)
21371 * @property preventDefault
21375 preventDefault: true,
21378 * Flag to determine if we should stop the propagation of the events
21379 * we generate. This is true by default but you may want to set it to
21380 * false if the html element contains other features that require the
21382 * @property stopPropagation
21386 stopPropagation: true,
21389 * Internal flag that is set to true when drag and drop has been
21391 * @property initialized
21398 * All drag and drop can be disabled.
21406 * Called the first time an element is registered.
21412 this.initialized = true;
21416 * In point mode, drag and drop interaction is defined by the
21417 * location of the cursor during the drag/drop
21425 * In intersect mode, drag and drop interactio nis defined by the
21426 * overlap of two or more drag and drop objects.
21427 * @property INTERSECT
21434 * The current drag and drop mode. Default: POINT
21442 * Runs method on all drag and drop objects
21443 * @method _execOnAll
21447 _execOnAll: function(sMethod, args) {
21448 for (var i in this.ids) {
21449 for (var j in this.ids[i]) {
21450 var oDD = this.ids[i][j];
21451 if (! this.isTypeOfDD(oDD)) {
21454 oDD[sMethod].apply(oDD, args);
21460 * Drag and drop initialization. Sets up the global event handlers
21465 _onLoad: function() {
21469 if (!Roo.isTouch) {
21470 Event.on(document, "mouseup", this.handleMouseUp, this, true);
21471 Event.on(document, "mousemove", this.handleMouseMove, this, true);
21473 Event.on(document, "touchend", this.handleMouseUp, this, true);
21474 Event.on(document, "touchmove", this.handleMouseMove, this, true);
21476 Event.on(window, "unload", this._onUnload, this, true);
21477 Event.on(window, "resize", this._onResize, this, true);
21478 // Event.on(window, "mouseout", this._test);
21483 * Reset constraints on all drag and drop objs
21484 * @method _onResize
21488 _onResize: function(e) {
21489 this._execOnAll("resetConstraints", []);
21493 * Lock all drag and drop functionality
21497 lock: function() { this.locked = true; },
21500 * Unlock all drag and drop functionality
21504 unlock: function() { this.locked = false; },
21507 * Is drag and drop locked?
21509 * @return {boolean} True if drag and drop is locked, false otherwise.
21512 isLocked: function() { return this.locked; },
21515 * Location cache that is set for all drag drop objects when a drag is
21516 * initiated, cleared when the drag is finished.
21517 * @property locationCache
21524 * Set useCache to false if you want to force object the lookup of each
21525 * drag and drop linked element constantly during a drag.
21526 * @property useCache
21533 * The number of pixels that the mouse needs to move after the
21534 * mousedown before the drag is initiated. Default=3;
21535 * @property clickPixelThresh
21539 clickPixelThresh: 3,
21542 * The number of milliseconds after the mousedown event to initiate the
21543 * drag if we don't get a mouseup event. Default=1000
21544 * @property clickTimeThresh
21548 clickTimeThresh: 350,
21551 * Flag that indicates that either the drag pixel threshold or the
21552 * mousdown time threshold has been met
21553 * @property dragThreshMet
21558 dragThreshMet: false,
21561 * Timeout used for the click time threshold
21562 * @property clickTimeout
21567 clickTimeout: null,
21570 * The X position of the mousedown event stored for later use when a
21571 * drag threshold is met.
21580 * The Y position of the mousedown event stored for later use when a
21581 * drag threshold is met.
21590 * Each DragDrop instance must be registered with the DragDropMgr.
21591 * This is executed in DragDrop.init()
21592 * @method regDragDrop
21593 * @param {DragDrop} oDD the DragDrop object to register
21594 * @param {String} sGroup the name of the group this element belongs to
21597 regDragDrop: function(oDD, sGroup) {
21598 if (!this.initialized) { this.init(); }
21600 if (!this.ids[sGroup]) {
21601 this.ids[sGroup] = {};
21603 this.ids[sGroup][oDD.id] = oDD;
21607 * Removes the supplied dd instance from the supplied group. Executed
21608 * by DragDrop.removeFromGroup, so don't call this function directly.
21609 * @method removeDDFromGroup
21613 removeDDFromGroup: function(oDD, sGroup) {
21614 if (!this.ids[sGroup]) {
21615 this.ids[sGroup] = {};
21618 var obj = this.ids[sGroup];
21619 if (obj && obj[oDD.id]) {
21620 delete obj[oDD.id];
21625 * Unregisters a drag and drop item. This is executed in
21626 * DragDrop.unreg, use that method instead of calling this directly.
21631 _remove: function(oDD) {
21632 for (var g in oDD.groups) {
21633 if (g && this.ids[g][oDD.id]) {
21634 delete this.ids[g][oDD.id];
21637 delete this.handleIds[oDD.id];
21641 * Each DragDrop handle element must be registered. This is done
21642 * automatically when executing DragDrop.setHandleElId()
21643 * @method regHandle
21644 * @param {String} sDDId the DragDrop id this element is a handle for
21645 * @param {String} sHandleId the id of the element that is the drag
21649 regHandle: function(sDDId, sHandleId) {
21650 if (!this.handleIds[sDDId]) {
21651 this.handleIds[sDDId] = {};
21653 this.handleIds[sDDId][sHandleId] = sHandleId;
21657 * Utility function to determine if a given element has been
21658 * registered as a drag drop item.
21659 * @method isDragDrop
21660 * @param {String} id the element id to check
21661 * @return {boolean} true if this element is a DragDrop item,
21665 isDragDrop: function(id) {
21666 return ( this.getDDById(id) ) ? true : false;
21670 * Returns the drag and drop instances that are in all groups the
21671 * passed in instance belongs to.
21672 * @method getRelated
21673 * @param {DragDrop} p_oDD the obj to get related data for
21674 * @param {boolean} bTargetsOnly if true, only return targetable objs
21675 * @return {DragDrop[]} the related instances
21678 getRelated: function(p_oDD, bTargetsOnly) {
21680 for (var i in p_oDD.groups) {
21681 for (j in this.ids[i]) {
21682 var dd = this.ids[i][j];
21683 if (! this.isTypeOfDD(dd)) {
21686 if (!bTargetsOnly || dd.isTarget) {
21687 oDDs[oDDs.length] = dd;
21696 * Returns true if the specified dd target is a legal target for
21697 * the specifice drag obj
21698 * @method isLegalTarget
21699 * @param {DragDrop} the drag obj
21700 * @param {DragDrop} the target
21701 * @return {boolean} true if the target is a legal target for the
21705 isLegalTarget: function (oDD, oTargetDD) {
21706 var targets = this.getRelated(oDD, true);
21707 for (var i=0, len=targets.length;i<len;++i) {
21708 if (targets[i].id == oTargetDD.id) {
21717 * My goal is to be able to transparently determine if an object is
21718 * typeof DragDrop, and the exact subclass of DragDrop. typeof
21719 * returns "object", oDD.constructor.toString() always returns
21720 * "DragDrop" and not the name of the subclass. So for now it just
21721 * evaluates a well-known variable in DragDrop.
21722 * @method isTypeOfDD
21723 * @param {Object} the object to evaluate
21724 * @return {boolean} true if typeof oDD = DragDrop
21727 isTypeOfDD: function (oDD) {
21728 return (oDD && oDD.__ygDragDrop);
21732 * Utility function to determine if a given element has been
21733 * registered as a drag drop handle for the given Drag Drop object.
21735 * @param {String} id the element id to check
21736 * @return {boolean} true if this element is a DragDrop handle, false
21740 isHandle: function(sDDId, sHandleId) {
21741 return ( this.handleIds[sDDId] &&
21742 this.handleIds[sDDId][sHandleId] );
21746 * Returns the DragDrop instance for a given id
21747 * @method getDDById
21748 * @param {String} id the id of the DragDrop object
21749 * @return {DragDrop} the drag drop object, null if it is not found
21752 getDDById: function(id) {
21753 for (var i in this.ids) {
21754 if (this.ids[i][id]) {
21755 return this.ids[i][id];
21762 * Fired after a registered DragDrop object gets the mousedown event.
21763 * Sets up the events required to track the object being dragged
21764 * @method handleMouseDown
21765 * @param {Event} e the event
21766 * @param oDD the DragDrop object being dragged
21770 handleMouseDown: function(e, oDD) {
21772 Roo.QuickTips.disable();
21774 this.currentTarget = e.getTarget();
21776 this.dragCurrent = oDD;
21778 var el = oDD.getEl();
21780 // track start position
21781 this.startX = e.getPageX();
21782 this.startY = e.getPageY();
21784 this.deltaX = this.startX - el.offsetLeft;
21785 this.deltaY = this.startY - el.offsetTop;
21787 this.dragThreshMet = false;
21789 this.clickTimeout = setTimeout(
21791 var DDM = Roo.dd.DDM;
21792 DDM.startDrag(DDM.startX, DDM.startY);
21794 this.clickTimeThresh );
21798 * Fired when either the drag pixel threshol or the mousedown hold
21799 * time threshold has been met.
21800 * @method startDrag
21801 * @param x {int} the X position of the original mousedown
21802 * @param y {int} the Y position of the original mousedown
21805 startDrag: function(x, y) {
21806 clearTimeout(this.clickTimeout);
21807 if (this.dragCurrent) {
21808 this.dragCurrent.b4StartDrag(x, y);
21809 this.dragCurrent.startDrag(x, y);
21811 this.dragThreshMet = true;
21815 * Internal function to handle the mouseup event. Will be invoked
21816 * from the context of the document.
21817 * @method handleMouseUp
21818 * @param {Event} e the event
21822 handleMouseUp: function(e) {
21825 Roo.QuickTips.enable();
21827 if (! this.dragCurrent) {
21831 clearTimeout(this.clickTimeout);
21833 if (this.dragThreshMet) {
21834 this.fireEvents(e, true);
21844 * Utility to stop event propagation and event default, if these
21845 * features are turned on.
21846 * @method stopEvent
21847 * @param {Event} e the event as returned by this.getEvent()
21850 stopEvent: function(e){
21851 if(this.stopPropagation) {
21852 e.stopPropagation();
21855 if (this.preventDefault) {
21856 e.preventDefault();
21861 * Internal function to clean up event handlers after the drag
21862 * operation is complete
21864 * @param {Event} e the event
21868 stopDrag: function(e) {
21869 // Fire the drag end event for the item that was dragged
21870 if (this.dragCurrent) {
21871 if (this.dragThreshMet) {
21872 this.dragCurrent.b4EndDrag(e);
21873 this.dragCurrent.endDrag(e);
21876 this.dragCurrent.onMouseUp(e);
21879 this.dragCurrent = null;
21880 this.dragOvers = {};
21884 * Internal function to handle the mousemove event. Will be invoked
21885 * from the context of the html element.
21887 * @TODO figure out what we can do about mouse events lost when the
21888 * user drags objects beyond the window boundary. Currently we can
21889 * detect this in internet explorer by verifying that the mouse is
21890 * down during the mousemove event. Firefox doesn't give us the
21891 * button state on the mousemove event.
21892 * @method handleMouseMove
21893 * @param {Event} e the event
21897 handleMouseMove: function(e) {
21898 if (! this.dragCurrent) {
21902 // var button = e.which || e.button;
21904 // check for IE mouseup outside of page boundary
21905 if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
21907 return this.handleMouseUp(e);
21910 if (!this.dragThreshMet) {
21911 var diffX = Math.abs(this.startX - e.getPageX());
21912 var diffY = Math.abs(this.startY - e.getPageY());
21913 if (diffX > this.clickPixelThresh ||
21914 diffY > this.clickPixelThresh) {
21915 this.startDrag(this.startX, this.startY);
21919 if (this.dragThreshMet) {
21920 this.dragCurrent.b4Drag(e);
21921 this.dragCurrent.onDrag(e);
21922 if(!this.dragCurrent.moveOnly){
21923 this.fireEvents(e, false);
21933 * Iterates over all of the DragDrop elements to find ones we are
21934 * hovering over or dropping on
21935 * @method fireEvents
21936 * @param {Event} e the event
21937 * @param {boolean} isDrop is this a drop op or a mouseover op?
21941 fireEvents: function(e, isDrop) {
21942 var dc = this.dragCurrent;
21944 // If the user did the mouse up outside of the window, we could
21945 // get here even though we have ended the drag.
21946 if (!dc || dc.isLocked()) {
21950 var pt = e.getPoint();
21952 // cache the previous dragOver array
21958 var enterEvts = [];
21960 // Check to see if the object(s) we were hovering over is no longer
21961 // being hovered over so we can fire the onDragOut event
21962 for (var i in this.dragOvers) {
21964 var ddo = this.dragOvers[i];
21966 if (! this.isTypeOfDD(ddo)) {
21970 if (! this.isOverTarget(pt, ddo, this.mode)) {
21971 outEvts.push( ddo );
21974 oldOvers[i] = true;
21975 delete this.dragOvers[i];
21978 for (var sGroup in dc.groups) {
21980 if ("string" != typeof sGroup) {
21984 for (i in this.ids[sGroup]) {
21985 var oDD = this.ids[sGroup][i];
21986 if (! this.isTypeOfDD(oDD)) {
21990 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
21991 if (this.isOverTarget(pt, oDD, this.mode)) {
21992 // look for drop interactions
21994 dropEvts.push( oDD );
21995 // look for drag enter and drag over interactions
21998 // initial drag over: dragEnter fires
21999 if (!oldOvers[oDD.id]) {
22000 enterEvts.push( oDD );
22001 // subsequent drag overs: dragOver fires
22003 overEvts.push( oDD );
22006 this.dragOvers[oDD.id] = oDD;
22014 if (outEvts.length) {
22015 dc.b4DragOut(e, outEvts);
22016 dc.onDragOut(e, outEvts);
22019 if (enterEvts.length) {
22020 dc.onDragEnter(e, enterEvts);
22023 if (overEvts.length) {
22024 dc.b4DragOver(e, overEvts);
22025 dc.onDragOver(e, overEvts);
22028 if (dropEvts.length) {
22029 dc.b4DragDrop(e, dropEvts);
22030 dc.onDragDrop(e, dropEvts);
22034 // fire dragout events
22036 for (i=0, len=outEvts.length; i<len; ++i) {
22037 dc.b4DragOut(e, outEvts[i].id);
22038 dc.onDragOut(e, outEvts[i].id);
22041 // fire enter events
22042 for (i=0,len=enterEvts.length; i<len; ++i) {
22043 // dc.b4DragEnter(e, oDD.id);
22044 dc.onDragEnter(e, enterEvts[i].id);
22047 // fire over events
22048 for (i=0,len=overEvts.length; i<len; ++i) {
22049 dc.b4DragOver(e, overEvts[i].id);
22050 dc.onDragOver(e, overEvts[i].id);
22053 // fire drop events
22054 for (i=0, len=dropEvts.length; i<len; ++i) {
22055 dc.b4DragDrop(e, dropEvts[i].id);
22056 dc.onDragDrop(e, dropEvts[i].id);
22061 // notify about a drop that did not find a target
22062 if (isDrop && !dropEvts.length) {
22063 dc.onInvalidDrop(e);
22069 * Helper function for getting the best match from the list of drag
22070 * and drop objects returned by the drag and drop events when we are
22071 * in INTERSECT mode. It returns either the first object that the
22072 * cursor is over, or the object that has the greatest overlap with
22073 * the dragged element.
22074 * @method getBestMatch
22075 * @param {DragDrop[]} dds The array of drag and drop objects
22077 * @return {DragDrop} The best single match
22080 getBestMatch: function(dds) {
22082 // Return null if the input is not what we expect
22083 //if (!dds || !dds.length || dds.length == 0) {
22085 // If there is only one item, it wins
22086 //} else if (dds.length == 1) {
22088 var len = dds.length;
22093 // Loop through the targeted items
22094 for (var i=0; i<len; ++i) {
22096 // If the cursor is over the object, it wins. If the
22097 // cursor is over multiple matches, the first one we come
22099 if (dd.cursorIsOver) {
22102 // Otherwise the object with the most overlap wins
22105 winner.overlap.getArea() < dd.overlap.getArea()) {
22116 * Refreshes the cache of the top-left and bottom-right points of the
22117 * drag and drop objects in the specified group(s). This is in the
22118 * format that is stored in the drag and drop instance, so typical
22121 * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
22125 * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
22127 * @TODO this really should be an indexed array. Alternatively this
22128 * method could accept both.
22129 * @method refreshCache
22130 * @param {Object} groups an associative array of groups to refresh
22133 refreshCache: function(groups) {
22134 for (var sGroup in groups) {
22135 if ("string" != typeof sGroup) {
22138 for (var i in this.ids[sGroup]) {
22139 var oDD = this.ids[sGroup][i];
22141 if (this.isTypeOfDD(oDD)) {
22142 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
22143 var loc = this.getLocation(oDD);
22145 this.locationCache[oDD.id] = loc;
22147 delete this.locationCache[oDD.id];
22148 // this will unregister the drag and drop object if
22149 // the element is not in a usable state
22158 * This checks to make sure an element exists and is in the DOM. The
22159 * main purpose is to handle cases where innerHTML is used to remove
22160 * drag and drop objects from the DOM. IE provides an 'unspecified
22161 * error' when trying to access the offsetParent of such an element
22163 * @param {HTMLElement} el the element to check
22164 * @return {boolean} true if the element looks usable
22167 verifyEl: function(el) {
22172 parent = el.offsetParent;
22175 parent = el.offsetParent;
22186 * Returns a Region object containing the drag and drop element's position
22187 * and size, including the padding configured for it
22188 * @method getLocation
22189 * @param {DragDrop} oDD the drag and drop object to get the
22191 * @return {Roo.lib.Region} a Region object representing the total area
22192 * the element occupies, including any padding
22193 * the instance is configured for.
22196 getLocation: function(oDD) {
22197 if (! this.isTypeOfDD(oDD)) {
22201 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
22204 pos= Roo.lib.Dom.getXY(el);
22212 x2 = x1 + el.offsetWidth;
22214 y2 = y1 + el.offsetHeight;
22216 t = y1 - oDD.padding[0];
22217 r = x2 + oDD.padding[1];
22218 b = y2 + oDD.padding[2];
22219 l = x1 - oDD.padding[3];
22221 return new Roo.lib.Region( t, r, b, l );
22225 * Checks the cursor location to see if it over the target
22226 * @method isOverTarget
22227 * @param {Roo.lib.Point} pt The point to evaluate
22228 * @param {DragDrop} oTarget the DragDrop object we are inspecting
22229 * @return {boolean} true if the mouse is over the target
22233 isOverTarget: function(pt, oTarget, intersect) {
22234 // use cache if available
22235 var loc = this.locationCache[oTarget.id];
22236 if (!loc || !this.useCache) {
22237 loc = this.getLocation(oTarget);
22238 this.locationCache[oTarget.id] = loc;
22246 oTarget.cursorIsOver = loc.contains( pt );
22248 // DragDrop is using this as a sanity check for the initial mousedown
22249 // in this case we are done. In POINT mode, if the drag obj has no
22250 // contraints, we are also done. Otherwise we need to evaluate the
22251 // location of the target as related to the actual location of the
22252 // dragged element.
22253 var dc = this.dragCurrent;
22254 if (!dc || !dc.getTargetCoord ||
22255 (!intersect && !dc.constrainX && !dc.constrainY)) {
22256 return oTarget.cursorIsOver;
22259 oTarget.overlap = null;
22261 // Get the current location of the drag element, this is the
22262 // location of the mouse event less the delta that represents
22263 // where the original mousedown happened on the element. We
22264 // need to consider constraints and ticks as well.
22265 var pos = dc.getTargetCoord(pt.x, pt.y);
22267 var el = dc.getDragEl();
22268 var curRegion = new Roo.lib.Region( pos.y,
22269 pos.x + el.offsetWidth,
22270 pos.y + el.offsetHeight,
22273 var overlap = curRegion.intersect(loc);
22276 oTarget.overlap = overlap;
22277 return (intersect) ? true : oTarget.cursorIsOver;
22284 * unload event handler
22285 * @method _onUnload
22289 _onUnload: function(e, me) {
22290 Roo.dd.DragDropMgr.unregAll();
22294 * Cleans up the drag and drop events and objects.
22299 unregAll: function() {
22301 if (this.dragCurrent) {
22303 this.dragCurrent = null;
22306 this._execOnAll("unreg", []);
22308 for (i in this.elementCache) {
22309 delete this.elementCache[i];
22312 this.elementCache = {};
22317 * A cache of DOM elements
22318 * @property elementCache
22325 * Get the wrapper for the DOM element specified
22326 * @method getElWrapper
22327 * @param {String} id the id of the element to get
22328 * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
22330 * @deprecated This wrapper isn't that useful
22333 getElWrapper: function(id) {
22334 var oWrapper = this.elementCache[id];
22335 if (!oWrapper || !oWrapper.el) {
22336 oWrapper = this.elementCache[id] =
22337 new this.ElementWrapper(Roo.getDom(id));
22343 * Returns the actual DOM element
22344 * @method getElement
22345 * @param {String} id the id of the elment to get
22346 * @return {Object} The element
22347 * @deprecated use Roo.getDom instead
22350 getElement: function(id) {
22351 return Roo.getDom(id);
22355 * Returns the style property for the DOM element (i.e.,
22356 * document.getElById(id).style)
22358 * @param {String} id the id of the elment to get
22359 * @return {Object} The style property of the element
22360 * @deprecated use Roo.getDom instead
22363 getCss: function(id) {
22364 var el = Roo.getDom(id);
22365 return (el) ? el.style : null;
22369 * Inner class for cached elements
22370 * @class DragDropMgr.ElementWrapper
22375 ElementWrapper: function(el) {
22380 this.el = el || null;
22385 this.id = this.el && el.id;
22387 * A reference to the style property
22390 this.css = this.el && el.style;
22394 * Returns the X position of an html element
22396 * @param el the element for which to get the position
22397 * @return {int} the X coordinate
22399 * @deprecated use Roo.lib.Dom.getX instead
22402 getPosX: function(el) {
22403 return Roo.lib.Dom.getX(el);
22407 * Returns the Y position of an html element
22409 * @param el the element for which to get the position
22410 * @return {int} the Y coordinate
22411 * @deprecated use Roo.lib.Dom.getY instead
22414 getPosY: function(el) {
22415 return Roo.lib.Dom.getY(el);
22419 * Swap two nodes. In IE, we use the native method, for others we
22420 * emulate the IE behavior
22422 * @param n1 the first node to swap
22423 * @param n2 the other node to swap
22426 swapNode: function(n1, n2) {
22430 var p = n2.parentNode;
22431 var s = n2.nextSibling;
22434 p.insertBefore(n1, n2);
22435 } else if (n2 == n1.nextSibling) {
22436 p.insertBefore(n2, n1);
22438 n1.parentNode.replaceChild(n2, n1);
22439 p.insertBefore(n1, s);
22445 * Returns the current scroll position
22446 * @method getScroll
22450 getScroll: function () {
22451 var t, l, dde=document.documentElement, db=document.body;
22452 if (dde && (dde.scrollTop || dde.scrollLeft)) {
22454 l = dde.scrollLeft;
22461 return { top: t, left: l };
22465 * Returns the specified element style property
22467 * @param {HTMLElement} el the element
22468 * @param {string} styleProp the style property
22469 * @return {string} The value of the style property
22470 * @deprecated use Roo.lib.Dom.getStyle
22473 getStyle: function(el, styleProp) {
22474 return Roo.fly(el).getStyle(styleProp);
22478 * Gets the scrollTop
22479 * @method getScrollTop
22480 * @return {int} the document's scrollTop
22483 getScrollTop: function () { return this.getScroll().top; },
22486 * Gets the scrollLeft
22487 * @method getScrollLeft
22488 * @return {int} the document's scrollTop
22491 getScrollLeft: function () { return this.getScroll().left; },
22494 * Sets the x/y position of an element to the location of the
22497 * @param {HTMLElement} moveEl The element to move
22498 * @param {HTMLElement} targetEl The position reference element
22501 moveToEl: function (moveEl, targetEl) {
22502 var aCoord = Roo.lib.Dom.getXY(targetEl);
22503 Roo.lib.Dom.setXY(moveEl, aCoord);
22507 * Numeric array sort function
22508 * @method numericSort
22511 numericSort: function(a, b) { return (a - b); },
22515 * @property _timeoutCount
22522 * Trying to make the load order less important. Without this we get
22523 * an error if this file is loaded before the Event Utility.
22524 * @method _addListeners
22528 _addListeners: function() {
22529 var DDM = Roo.dd.DDM;
22530 if ( Roo.lib.Event && document ) {
22533 if (DDM._timeoutCount > 2000) {
22535 setTimeout(DDM._addListeners, 10);
22536 if (document && document.body) {
22537 DDM._timeoutCount += 1;
22544 * Recursively searches the immediate parent and all child nodes for
22545 * the handle element in order to determine wheter or not it was
22547 * @method handleWasClicked
22548 * @param node the html element to inspect
22551 handleWasClicked: function(node, id) {
22552 if (this.isHandle(id, node.id)) {
22555 // check to see if this is a text node child of the one we want
22556 var p = node.parentNode;
22559 if (this.isHandle(id, p.id)) {
22574 // shorter alias, save a few bytes
22575 Roo.dd.DDM = Roo.dd.DragDropMgr;
22576 Roo.dd.DDM._addListeners();
22580 * Ext JS Library 1.1.1
22581 * Copyright(c) 2006-2007, Ext JS, LLC.
22583 * Originally Released Under LGPL - original licence link has changed is not relivant.
22586 * <script type="text/javascript">
22591 * A DragDrop implementation where the linked element follows the
22592 * mouse cursor during a drag.
22593 * @extends Roo.dd.DragDrop
22595 * @param {String} id the id of the linked element
22596 * @param {String} sGroup the group of related DragDrop items
22597 * @param {object} config an object containing configurable attributes
22598 * Valid properties for DD:
22601 Roo.dd.DD = function(id, sGroup, config) {
22603 this.init(id, sGroup, config);
22607 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
22610 * When set to true, the utility automatically tries to scroll the browser
22611 * window wehn a drag and drop element is dragged near the viewport boundary.
22612 * Defaults to true.
22619 * Sets the pointer offset to the distance between the linked element's top
22620 * left corner and the location the element was clicked
22621 * @method autoOffset
22622 * @param {int} iPageX the X coordinate of the click
22623 * @param {int} iPageY the Y coordinate of the click
22625 autoOffset: function(iPageX, iPageY) {
22626 var x = iPageX - this.startPageX;
22627 var y = iPageY - this.startPageY;
22628 this.setDelta(x, y);
22632 * Sets the pointer offset. You can call this directly to force the
22633 * offset to be in a particular location (e.g., pass in 0,0 to set it
22634 * to the center of the object)
22636 * @param {int} iDeltaX the distance from the left
22637 * @param {int} iDeltaY the distance from the top
22639 setDelta: function(iDeltaX, iDeltaY) {
22640 this.deltaX = iDeltaX;
22641 this.deltaY = iDeltaY;
22645 * Sets the drag element to the location of the mousedown or click event,
22646 * maintaining the cursor location relative to the location on the element
22647 * that was clicked. Override this if you want to place the element in a
22648 * location other than where the cursor is.
22649 * @method setDragElPos
22650 * @param {int} iPageX the X coordinate of the mousedown or drag event
22651 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22653 setDragElPos: function(iPageX, iPageY) {
22654 // the first time we do this, we are going to check to make sure
22655 // the element has css positioning
22657 var el = this.getDragEl();
22658 this.alignElWithMouse(el, iPageX, iPageY);
22662 * Sets the element to the location of the mousedown or click event,
22663 * maintaining the cursor location relative to the location on the element
22664 * that was clicked. Override this if you want to place the element in a
22665 * location other than where the cursor is.
22666 * @method alignElWithMouse
22667 * @param {HTMLElement} el the element to move
22668 * @param {int} iPageX the X coordinate of the mousedown or drag event
22669 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22671 alignElWithMouse: function(el, iPageX, iPageY) {
22672 var oCoord = this.getTargetCoord(iPageX, iPageY);
22673 var fly = el.dom ? el : Roo.fly(el);
22674 if (!this.deltaSetXY) {
22675 var aCoord = [oCoord.x, oCoord.y];
22677 var newLeft = fly.getLeft(true);
22678 var newTop = fly.getTop(true);
22679 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
22681 fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
22684 this.cachePosition(oCoord.x, oCoord.y);
22685 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
22690 * Saves the most recent position so that we can reset the constraints and
22691 * tick marks on-demand. We need to know this so that we can calculate the
22692 * number of pixels the element is offset from its original position.
22693 * @method cachePosition
22694 * @param iPageX the current x position (optional, this just makes it so we
22695 * don't have to look it up again)
22696 * @param iPageY the current y position (optional, this just makes it so we
22697 * don't have to look it up again)
22699 cachePosition: function(iPageX, iPageY) {
22701 this.lastPageX = iPageX;
22702 this.lastPageY = iPageY;
22704 var aCoord = Roo.lib.Dom.getXY(this.getEl());
22705 this.lastPageX = aCoord[0];
22706 this.lastPageY = aCoord[1];
22711 * Auto-scroll the window if the dragged object has been moved beyond the
22712 * visible window boundary.
22713 * @method autoScroll
22714 * @param {int} x the drag element's x position
22715 * @param {int} y the drag element's y position
22716 * @param {int} h the height of the drag element
22717 * @param {int} w the width of the drag element
22720 autoScroll: function(x, y, h, w) {
22723 // The client height
22724 var clientH = Roo.lib.Dom.getViewWidth();
22726 // The client width
22727 var clientW = Roo.lib.Dom.getViewHeight();
22729 // The amt scrolled down
22730 var st = this.DDM.getScrollTop();
22732 // The amt scrolled right
22733 var sl = this.DDM.getScrollLeft();
22735 // Location of the bottom of the element
22738 // Location of the right of the element
22741 // The distance from the cursor to the bottom of the visible area,
22742 // adjusted so that we don't scroll if the cursor is beyond the
22743 // element drag constraints
22744 var toBot = (clientH + st - y - this.deltaY);
22746 // The distance from the cursor to the right of the visible area
22747 var toRight = (clientW + sl - x - this.deltaX);
22750 // How close to the edge the cursor must be before we scroll
22751 // var thresh = (document.all) ? 100 : 40;
22754 // How many pixels to scroll per autoscroll op. This helps to reduce
22755 // clunky scrolling. IE is more sensitive about this ... it needs this
22756 // value to be higher.
22757 var scrAmt = (document.all) ? 80 : 30;
22759 // Scroll down if we are near the bottom of the visible page and the
22760 // obj extends below the crease
22761 if ( bot > clientH && toBot < thresh ) {
22762 window.scrollTo(sl, st + scrAmt);
22765 // Scroll up if the window is scrolled down and the top of the object
22766 // goes above the top border
22767 if ( y < st && st > 0 && y - st < thresh ) {
22768 window.scrollTo(sl, st - scrAmt);
22771 // Scroll right if the obj is beyond the right border and the cursor is
22772 // near the border.
22773 if ( right > clientW && toRight < thresh ) {
22774 window.scrollTo(sl + scrAmt, st);
22777 // Scroll left if the window has been scrolled to the right and the obj
22778 // extends past the left border
22779 if ( x < sl && sl > 0 && x - sl < thresh ) {
22780 window.scrollTo(sl - scrAmt, st);
22786 * Finds the location the element should be placed if we want to move
22787 * it to where the mouse location less the click offset would place us.
22788 * @method getTargetCoord
22789 * @param {int} iPageX the X coordinate of the click
22790 * @param {int} iPageY the Y coordinate of the click
22791 * @return an object that contains the coordinates (Object.x and Object.y)
22794 getTargetCoord: function(iPageX, iPageY) {
22797 var x = iPageX - this.deltaX;
22798 var y = iPageY - this.deltaY;
22800 if (this.constrainX) {
22801 if (x < this.minX) { x = this.minX; }
22802 if (x > this.maxX) { x = this.maxX; }
22805 if (this.constrainY) {
22806 if (y < this.minY) { y = this.minY; }
22807 if (y > this.maxY) { y = this.maxY; }
22810 x = this.getTick(x, this.xTicks);
22811 y = this.getTick(y, this.yTicks);
22818 * Sets up config options specific to this class. Overrides
22819 * Roo.dd.DragDrop, but all versions of this method through the
22820 * inheritance chain are called
22822 applyConfig: function() {
22823 Roo.dd.DD.superclass.applyConfig.call(this);
22824 this.scroll = (this.config.scroll !== false);
22828 * Event that fires prior to the onMouseDown event. Overrides
22831 b4MouseDown: function(e) {
22832 // this.resetConstraints();
22833 this.autoOffset(e.getPageX(),
22838 * Event that fires prior to the onDrag event. Overrides
22841 b4Drag: function(e) {
22842 this.setDragElPos(e.getPageX(),
22846 toString: function() {
22847 return ("DD " + this.id);
22850 //////////////////////////////////////////////////////////////////////////
22851 // Debugging ygDragDrop events that can be overridden
22852 //////////////////////////////////////////////////////////////////////////
22854 startDrag: function(x, y) {
22857 onDrag: function(e) {
22860 onDragEnter: function(e, id) {
22863 onDragOver: function(e, id) {
22866 onDragOut: function(e, id) {
22869 onDragDrop: function(e, id) {
22872 endDrag: function(e) {
22879 * Ext JS Library 1.1.1
22880 * Copyright(c) 2006-2007, Ext JS, LLC.
22882 * Originally Released Under LGPL - original licence link has changed is not relivant.
22885 * <script type="text/javascript">
22889 * @class Roo.dd.DDProxy
22890 * A DragDrop implementation that inserts an empty, bordered div into
22891 * the document that follows the cursor during drag operations. At the time of
22892 * the click, the frame div is resized to the dimensions of the linked html
22893 * element, and moved to the exact location of the linked element.
22895 * References to the "frame" element refer to the single proxy element that
22896 * was created to be dragged in place of all DDProxy elements on the
22899 * @extends Roo.dd.DD
22901 * @param {String} id the id of the linked html element
22902 * @param {String} sGroup the group of related DragDrop objects
22903 * @param {object} config an object containing configurable attributes
22904 * Valid properties for DDProxy in addition to those in DragDrop:
22905 * resizeFrame, centerFrame, dragElId
22907 Roo.dd.DDProxy = function(id, sGroup, config) {
22909 this.init(id, sGroup, config);
22915 * The default drag frame div id
22916 * @property Roo.dd.DDProxy.dragElId
22920 Roo.dd.DDProxy.dragElId = "ygddfdiv";
22922 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
22925 * By default we resize the drag frame to be the same size as the element
22926 * we want to drag (this is to get the frame effect). We can turn it off
22927 * if we want a different behavior.
22928 * @property resizeFrame
22934 * By default the frame is positioned exactly where the drag element is, so
22935 * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
22936 * you do not have constraints on the obj is to have the drag frame centered
22937 * around the cursor. Set centerFrame to true for this effect.
22938 * @property centerFrame
22941 centerFrame: false,
22944 * Creates the proxy element if it does not yet exist
22945 * @method createFrame
22947 createFrame: function() {
22949 var body = document.body;
22951 if (!body || !body.firstChild) {
22952 setTimeout( function() { self.createFrame(); }, 50 );
22956 var div = this.getDragEl();
22959 div = document.createElement("div");
22960 div.id = this.dragElId;
22963 s.position = "absolute";
22964 s.visibility = "hidden";
22966 s.border = "2px solid #aaa";
22969 // appendChild can blow up IE if invoked prior to the window load event
22970 // while rendering a table. It is possible there are other scenarios
22971 // that would cause this to happen as well.
22972 body.insertBefore(div, body.firstChild);
22977 * Initialization for the drag frame element. Must be called in the
22978 * constructor of all subclasses
22979 * @method initFrame
22981 initFrame: function() {
22982 this.createFrame();
22985 applyConfig: function() {
22986 Roo.dd.DDProxy.superclass.applyConfig.call(this);
22988 this.resizeFrame = (this.config.resizeFrame !== false);
22989 this.centerFrame = (this.config.centerFrame);
22990 this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
22994 * Resizes the drag frame to the dimensions of the clicked object, positions
22995 * it over the object, and finally displays it
22996 * @method showFrame
22997 * @param {int} iPageX X click position
22998 * @param {int} iPageY Y click position
23001 showFrame: function(iPageX, iPageY) {
23002 var el = this.getEl();
23003 var dragEl = this.getDragEl();
23004 var s = dragEl.style;
23006 this._resizeProxy();
23008 if (this.centerFrame) {
23009 this.setDelta( Math.round(parseInt(s.width, 10)/2),
23010 Math.round(parseInt(s.height, 10)/2) );
23013 this.setDragElPos(iPageX, iPageY);
23015 Roo.fly(dragEl).show();
23019 * The proxy is automatically resized to the dimensions of the linked
23020 * element when a drag is initiated, unless resizeFrame is set to false
23021 * @method _resizeProxy
23024 _resizeProxy: function() {
23025 if (this.resizeFrame) {
23026 var el = this.getEl();
23027 Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
23031 // overrides Roo.dd.DragDrop
23032 b4MouseDown: function(e) {
23033 var x = e.getPageX();
23034 var y = e.getPageY();
23035 this.autoOffset(x, y);
23036 this.setDragElPos(x, y);
23039 // overrides Roo.dd.DragDrop
23040 b4StartDrag: function(x, y) {
23041 // show the drag frame
23042 this.showFrame(x, y);
23045 // overrides Roo.dd.DragDrop
23046 b4EndDrag: function(e) {
23047 Roo.fly(this.getDragEl()).hide();
23050 // overrides Roo.dd.DragDrop
23051 // By default we try to move the element to the last location of the frame.
23052 // This is so that the default behavior mirrors that of Roo.dd.DD.
23053 endDrag: function(e) {
23055 var lel = this.getEl();
23056 var del = this.getDragEl();
23058 // Show the drag frame briefly so we can get its position
23059 del.style.visibility = "";
23062 // Hide the linked element before the move to get around a Safari
23064 lel.style.visibility = "hidden";
23065 Roo.dd.DDM.moveToEl(lel, del);
23066 del.style.visibility = "hidden";
23067 lel.style.visibility = "";
23072 beforeMove : function(){
23076 afterDrag : function(){
23080 toString: function() {
23081 return ("DDProxy " + this.id);
23087 * Ext JS Library 1.1.1
23088 * Copyright(c) 2006-2007, Ext JS, LLC.
23090 * Originally Released Under LGPL - original licence link has changed is not relivant.
23093 * <script type="text/javascript">
23097 * @class Roo.dd.DDTarget
23098 * A DragDrop implementation that does not move, but can be a drop
23099 * target. You would get the same result by simply omitting implementation
23100 * for the event callbacks, but this way we reduce the processing cost of the
23101 * event listener and the callbacks.
23102 * @extends Roo.dd.DragDrop
23104 * @param {String} id the id of the element that is a drop target
23105 * @param {String} sGroup the group of related DragDrop objects
23106 * @param {object} config an object containing configurable attributes
23107 * Valid properties for DDTarget in addition to those in
23111 Roo.dd.DDTarget = function(id, sGroup, config) {
23113 this.initTarget(id, sGroup, config);
23115 if (config && (config.listeners || config.events)) {
23116 Roo.dd.DragDrop.superclass.constructor.call(this, {
23117 listeners : config.listeners || {},
23118 events : config.events || {}
23123 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
23124 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
23125 toString: function() {
23126 return ("DDTarget " + this.id);
23131 * Ext JS Library 1.1.1
23132 * Copyright(c) 2006-2007, Ext JS, LLC.
23134 * Originally Released Under LGPL - original licence link has changed is not relivant.
23137 * <script type="text/javascript">
23142 * @class Roo.dd.ScrollManager
23143 * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
23144 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
23147 Roo.dd.ScrollManager = function(){
23148 var ddm = Roo.dd.DragDropMgr;
23155 var onStop = function(e){
23160 var triggerRefresh = function(){
23161 if(ddm.dragCurrent){
23162 ddm.refreshCache(ddm.dragCurrent.groups);
23166 var doScroll = function(){
23167 if(ddm.dragCurrent){
23168 var dds = Roo.dd.ScrollManager;
23170 if(proc.el.scroll(proc.dir, dds.increment)){
23174 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
23179 var clearProc = function(){
23181 clearInterval(proc.id);
23188 var startProc = function(el, dir){
23189 Roo.log('scroll startproc');
23193 proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
23196 var onFire = function(e, isDrop){
23198 if(isDrop || !ddm.dragCurrent){ return; }
23199 var dds = Roo.dd.ScrollManager;
23200 if(!dragEl || dragEl != ddm.dragCurrent){
23201 dragEl = ddm.dragCurrent;
23202 // refresh regions on drag start
23203 dds.refreshCache();
23206 var xy = Roo.lib.Event.getXY(e);
23207 var pt = new Roo.lib.Point(xy[0], xy[1]);
23208 for(var id in els){
23209 var el = els[id], r = el._region;
23210 if(r && r.contains(pt) && el.isScrollable()){
23211 if(r.bottom - pt.y <= dds.thresh){
23213 startProc(el, "down");
23216 }else if(r.right - pt.x <= dds.thresh){
23218 startProc(el, "left");
23221 }else if(pt.y - r.top <= dds.thresh){
23223 startProc(el, "up");
23226 }else if(pt.x - r.left <= dds.thresh){
23228 startProc(el, "right");
23237 ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
23238 ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
23242 * Registers new overflow element(s) to auto scroll
23243 * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
23245 register : function(el){
23246 if(el instanceof Array){
23247 for(var i = 0, len = el.length; i < len; i++) {
23248 this.register(el[i]);
23254 Roo.dd.ScrollManager.els = els;
23258 * Unregisters overflow element(s) so they are no longer scrolled
23259 * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
23261 unregister : function(el){
23262 if(el instanceof Array){
23263 for(var i = 0, len = el.length; i < len; i++) {
23264 this.unregister(el[i]);
23273 * The number of pixels from the edge of a container the pointer needs to be to
23274 * trigger scrolling (defaults to 25)
23280 * The number of pixels to scroll in each scroll increment (defaults to 50)
23286 * The frequency of scrolls in milliseconds (defaults to 500)
23292 * True to animate the scroll (defaults to true)
23298 * The animation duration in seconds -
23299 * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
23305 * Manually trigger a cache refresh.
23307 refreshCache : function(){
23308 for(var id in els){
23309 if(typeof els[id] == 'object'){ // for people extending the object prototype
23310 els[id]._region = els[id].getRegion();
23317 * Ext JS Library 1.1.1
23318 * Copyright(c) 2006-2007, Ext JS, LLC.
23320 * Originally Released Under LGPL - original licence link has changed is not relivant.
23323 * <script type="text/javascript">
23328 * @class Roo.dd.Registry
23329 * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
23330 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
23333 Roo.dd.Registry = function(){
23336 var autoIdSeed = 0;
23338 var getId = function(el, autogen){
23339 if(typeof el == "string"){
23343 if(!id && autogen !== false){
23344 id = "roodd-" + (++autoIdSeed);
23352 * Register a drag drop element
23353 * @param {String|HTMLElement} element The id or DOM node to register
23354 * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
23355 * in drag drop operations. You can populate this object with any arbitrary properties that your own code
23356 * knows how to interpret, plus there are some specific properties known to the Registry that should be
23357 * populated in the data object (if applicable):
23359 Value Description<br />
23360 --------- ------------------------------------------<br />
23361 handles Array of DOM nodes that trigger dragging<br />
23362 for the element being registered<br />
23363 isHandle True if the element passed in triggers<br />
23364 dragging itself, else false
23367 register : function(el, data){
23369 if(typeof el == "string"){
23370 el = document.getElementById(el);
23373 elements[getId(el)] = data;
23374 if(data.isHandle !== false){
23375 handles[data.ddel.id] = data;
23378 var hs = data.handles;
23379 for(var i = 0, len = hs.length; i < len; i++){
23380 handles[getId(hs[i])] = data;
23386 * Unregister a drag drop element
23387 * @param {String|HTMLElement} element The id or DOM node to unregister
23389 unregister : function(el){
23390 var id = getId(el, false);
23391 var data = elements[id];
23393 delete elements[id];
23395 var hs = data.handles;
23396 for(var i = 0, len = hs.length; i < len; i++){
23397 delete handles[getId(hs[i], false)];
23404 * Returns the handle registered for a DOM Node by id
23405 * @param {String|HTMLElement} id The DOM node or id to look up
23406 * @return {Object} handle The custom handle data
23408 getHandle : function(id){
23409 if(typeof id != "string"){ // must be element?
23412 return handles[id];
23416 * Returns the handle that is registered for the DOM node that is the target of the event
23417 * @param {Event} e The event
23418 * @return {Object} handle The custom handle data
23420 getHandleFromEvent : function(e){
23421 var t = Roo.lib.Event.getTarget(e);
23422 return t ? handles[t.id] : null;
23426 * Returns a custom data object that is registered for a DOM node by id
23427 * @param {String|HTMLElement} id The DOM node or id to look up
23428 * @return {Object} data The custom data
23430 getTarget : function(id){
23431 if(typeof id != "string"){ // must be element?
23434 return elements[id];
23438 * Returns a custom data object that is registered for the DOM node that is the target of the event
23439 * @param {Event} e The event
23440 * @return {Object} data The custom data
23442 getTargetFromEvent : function(e){
23443 var t = Roo.lib.Event.getTarget(e);
23444 return t ? elements[t.id] || handles[t.id] : null;
23449 * Ext JS Library 1.1.1
23450 * Copyright(c) 2006-2007, Ext JS, LLC.
23452 * Originally Released Under LGPL - original licence link has changed is not relivant.
23455 * <script type="text/javascript">
23460 * @class Roo.dd.StatusProxy
23461 * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
23462 * default drag proxy used by all Roo.dd components.
23464 * @param {Object} config
23466 Roo.dd.StatusProxy = function(config){
23467 Roo.apply(this, config);
23468 this.id = this.id || Roo.id();
23469 this.el = new Roo.Layer({
23471 id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
23472 {tag: "div", cls: "x-dd-drop-icon"},
23473 {tag: "div", cls: "x-dd-drag-ghost"}
23476 shadow: !config || config.shadow !== false
23478 this.ghost = Roo.get(this.el.dom.childNodes[1]);
23479 this.dropStatus = this.dropNotAllowed;
23482 Roo.dd.StatusProxy.prototype = {
23484 * @cfg {String} dropAllowed
23485 * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
23487 dropAllowed : "x-dd-drop-ok",
23489 * @cfg {String} dropNotAllowed
23490 * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
23492 dropNotAllowed : "x-dd-drop-nodrop",
23495 * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
23496 * over the current target element.
23497 * @param {String} cssClass The css class for the new drop status indicator image
23499 setStatus : function(cssClass){
23500 cssClass = cssClass || this.dropNotAllowed;
23501 if(this.dropStatus != cssClass){
23502 this.el.replaceClass(this.dropStatus, cssClass);
23503 this.dropStatus = cssClass;
23508 * Resets the status indicator to the default dropNotAllowed value
23509 * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
23511 reset : function(clearGhost){
23512 this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
23513 this.dropStatus = this.dropNotAllowed;
23515 this.ghost.update("");
23520 * Updates the contents of the ghost element
23521 * @param {String} html The html that will replace the current innerHTML of the ghost element
23523 update : function(html){
23524 if(typeof html == "string"){
23525 this.ghost.update(html);
23527 this.ghost.update("");
23528 html.style.margin = "0";
23529 this.ghost.dom.appendChild(html);
23531 // ensure float = none set?? cant remember why though.
23532 var el = this.ghost.dom.firstChild;
23534 Roo.fly(el).setStyle('float', 'none');
23539 * Returns the underlying proxy {@link Roo.Layer}
23540 * @return {Roo.Layer} el
23542 getEl : function(){
23547 * Returns the ghost element
23548 * @return {Roo.Element} el
23550 getGhost : function(){
23556 * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
23558 hide : function(clear){
23566 * Stops the repair animation if it's currently running
23569 if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
23575 * Displays this proxy
23582 * Force the Layer to sync its shadow and shim positions to the element
23589 * Causes the proxy to return to its position of origin via an animation. Should be called after an
23590 * invalid drop operation by the item being dragged.
23591 * @param {Array} xy The XY position of the element ([x, y])
23592 * @param {Function} callback The function to call after the repair is complete
23593 * @param {Object} scope The scope in which to execute the callback
23595 repair : function(xy, callback, scope){
23596 this.callback = callback;
23597 this.scope = scope;
23598 if(xy && this.animRepair !== false){
23599 this.el.addClass("x-dd-drag-repair");
23600 this.el.hideUnders(true);
23601 this.anim = this.el.shift({
23602 duration: this.repairDuration || .5,
23606 callback: this.afterRepair,
23610 this.afterRepair();
23615 afterRepair : function(){
23617 if(typeof this.callback == "function"){
23618 this.callback.call(this.scope || this);
23620 this.callback = null;
23625 * Ext JS Library 1.1.1
23626 * Copyright(c) 2006-2007, Ext JS, LLC.
23628 * Originally Released Under LGPL - original licence link has changed is not relivant.
23631 * <script type="text/javascript">
23635 * @class Roo.dd.DragSource
23636 * @extends Roo.dd.DDProxy
23637 * A simple class that provides the basic implementation needed to make any element draggable.
23639 * @param {String/HTMLElement/Element} el The container element
23640 * @param {Object} config
23642 Roo.dd.DragSource = function(el, config){
23643 this.el = Roo.get(el);
23644 this.dragData = {};
23646 Roo.apply(this, config);
23649 this.proxy = new Roo.dd.StatusProxy();
23652 Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
23653 {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
23655 this.dragging = false;
23658 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
23660 * @cfg {String} dropAllowed
23661 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23663 dropAllowed : "x-dd-drop-ok",
23665 * @cfg {String} dropNotAllowed
23666 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23668 dropNotAllowed : "x-dd-drop-nodrop",
23671 * Returns the data object associated with this drag source
23672 * @return {Object} data An object containing arbitrary data
23674 getDragData : function(e){
23675 return this.dragData;
23679 onDragEnter : function(e, id){
23680 var target = Roo.dd.DragDropMgr.getDDById(id);
23681 this.cachedTarget = target;
23682 if(this.beforeDragEnter(target, e, id) !== false){
23683 if(target.isNotifyTarget){
23684 var status = target.notifyEnter(this, e, this.dragData);
23685 this.proxy.setStatus(status);
23687 this.proxy.setStatus(this.dropAllowed);
23690 if(this.afterDragEnter){
23692 * An empty function by default, but provided so that you can perform a custom action
23693 * when the dragged item enters the drop target by providing an implementation.
23694 * @param {Roo.dd.DragDrop} target The drop target
23695 * @param {Event} e The event object
23696 * @param {String} id The id of the dragged element
23697 * @method afterDragEnter
23699 this.afterDragEnter(target, e, id);
23705 * An empty function by default, but provided so that you can perform a custom action
23706 * before the dragged item enters the drop target and optionally cancel the onDragEnter.
23707 * @param {Roo.dd.DragDrop} target The drop target
23708 * @param {Event} e The event object
23709 * @param {String} id The id of the dragged element
23710 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23712 beforeDragEnter : function(target, e, id){
23717 alignElWithMouse: function() {
23718 Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
23723 onDragOver : function(e, id){
23724 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23725 if(this.beforeDragOver(target, e, id) !== false){
23726 if(target.isNotifyTarget){
23727 var status = target.notifyOver(this, e, this.dragData);
23728 this.proxy.setStatus(status);
23731 if(this.afterDragOver){
23733 * An empty function by default, but provided so that you can perform a custom action
23734 * while the dragged item is over the drop target by providing an implementation.
23735 * @param {Roo.dd.DragDrop} target The drop target
23736 * @param {Event} e The event object
23737 * @param {String} id The id of the dragged element
23738 * @method afterDragOver
23740 this.afterDragOver(target, e, id);
23746 * An empty function by default, but provided so that you can perform a custom action
23747 * while the dragged item is over the drop target and optionally cancel the onDragOver.
23748 * @param {Roo.dd.DragDrop} target The drop target
23749 * @param {Event} e The event object
23750 * @param {String} id The id of the dragged element
23751 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23753 beforeDragOver : function(target, e, id){
23758 onDragOut : function(e, id){
23759 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23760 if(this.beforeDragOut(target, e, id) !== false){
23761 if(target.isNotifyTarget){
23762 target.notifyOut(this, e, this.dragData);
23764 this.proxy.reset();
23765 if(this.afterDragOut){
23767 * An empty function by default, but provided so that you can perform a custom action
23768 * after the dragged item is dragged out of the target without dropping.
23769 * @param {Roo.dd.DragDrop} target The drop target
23770 * @param {Event} e The event object
23771 * @param {String} id The id of the dragged element
23772 * @method afterDragOut
23774 this.afterDragOut(target, e, id);
23777 this.cachedTarget = null;
23781 * An empty function by default, but provided so that you can perform a custom action before the dragged
23782 * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
23783 * @param {Roo.dd.DragDrop} target The drop target
23784 * @param {Event} e The event object
23785 * @param {String} id The id of the dragged element
23786 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23788 beforeDragOut : function(target, e, id){
23793 onDragDrop : function(e, id){
23794 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23795 if(this.beforeDragDrop(target, e, id) !== false){
23796 if(target.isNotifyTarget){
23797 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
23798 this.onValidDrop(target, e, id);
23800 this.onInvalidDrop(target, e, id);
23803 this.onValidDrop(target, e, id);
23806 if(this.afterDragDrop){
23808 * An empty function by default, but provided so that you can perform a custom action
23809 * after a valid drag drop has occurred by providing an implementation.
23810 * @param {Roo.dd.DragDrop} target The drop target
23811 * @param {Event} e The event object
23812 * @param {String} id The id of the dropped element
23813 * @method afterDragDrop
23815 this.afterDragDrop(target, e, id);
23818 delete this.cachedTarget;
23822 * An empty function by default, but provided so that you can perform a custom action before the dragged
23823 * item is dropped onto the target and optionally cancel the onDragDrop.
23824 * @param {Roo.dd.DragDrop} target The drop target
23825 * @param {Event} e The event object
23826 * @param {String} id The id of the dragged element
23827 * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
23829 beforeDragDrop : function(target, e, id){
23834 onValidDrop : function(target, e, id){
23836 if(this.afterValidDrop){
23838 * An empty function by default, but provided so that you can perform a custom action
23839 * after a valid drop has occurred by providing an implementation.
23840 * @param {Object} target The target DD
23841 * @param {Event} e The event object
23842 * @param {String} id The id of the dropped element
23843 * @method afterInvalidDrop
23845 this.afterValidDrop(target, e, id);
23850 getRepairXY : function(e, data){
23851 return this.el.getXY();
23855 onInvalidDrop : function(target, e, id){
23856 this.beforeInvalidDrop(target, e, id);
23857 if(this.cachedTarget){
23858 if(this.cachedTarget.isNotifyTarget){
23859 this.cachedTarget.notifyOut(this, e, this.dragData);
23861 this.cacheTarget = null;
23863 this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
23865 if(this.afterInvalidDrop){
23867 * An empty function by default, but provided so that you can perform a custom action
23868 * after an invalid drop has occurred by providing an implementation.
23869 * @param {Event} e The event object
23870 * @param {String} id The id of the dropped element
23871 * @method afterInvalidDrop
23873 this.afterInvalidDrop(e, id);
23878 afterRepair : function(){
23880 this.el.highlight(this.hlColor || "c3daf9");
23882 this.dragging = false;
23886 * An empty function by default, but provided so that you can perform a custom action after an invalid
23887 * drop has occurred.
23888 * @param {Roo.dd.DragDrop} target The drop target
23889 * @param {Event} e The event object
23890 * @param {String} id The id of the dragged element
23891 * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
23893 beforeInvalidDrop : function(target, e, id){
23898 handleMouseDown : function(e){
23899 if(this.dragging) {
23902 var data = this.getDragData(e);
23903 if(data && this.onBeforeDrag(data, e) !== false){
23904 this.dragData = data;
23906 Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
23911 * An empty function by default, but provided so that you can perform a custom action before the initial
23912 * drag event begins and optionally cancel it.
23913 * @param {Object} data An object containing arbitrary data to be shared with drop targets
23914 * @param {Event} e The event object
23915 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23917 onBeforeDrag : function(data, e){
23922 * An empty function by default, but provided so that you can perform a custom action once the initial
23923 * drag event has begun. The drag cannot be canceled from this function.
23924 * @param {Number} x The x position of the click on the dragged object
23925 * @param {Number} y The y position of the click on the dragged object
23927 onStartDrag : Roo.emptyFn,
23929 // private - YUI override
23930 startDrag : function(x, y){
23931 this.proxy.reset();
23932 this.dragging = true;
23933 this.proxy.update("");
23934 this.onInitDrag(x, y);
23939 onInitDrag : function(x, y){
23940 var clone = this.el.dom.cloneNode(true);
23941 clone.id = Roo.id(); // prevent duplicate ids
23942 this.proxy.update(clone);
23943 this.onStartDrag(x, y);
23948 * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
23949 * @return {Roo.dd.StatusProxy} proxy The StatusProxy
23951 getProxy : function(){
23956 * Hides the drag source's {@link Roo.dd.StatusProxy}
23958 hideProxy : function(){
23960 this.proxy.reset(true);
23961 this.dragging = false;
23965 triggerCacheRefresh : function(){
23966 Roo.dd.DDM.refreshCache(this.groups);
23969 // private - override to prevent hiding
23970 b4EndDrag: function(e) {
23973 // private - override to prevent moving
23974 endDrag : function(e){
23975 this.onEndDrag(this.dragData, e);
23979 onEndDrag : function(data, e){
23982 // private - pin to cursor
23983 autoOffset : function(x, y) {
23984 this.setDelta(-12, -20);
23988 * Ext JS Library 1.1.1
23989 * Copyright(c) 2006-2007, Ext JS, LLC.
23991 * Originally Released Under LGPL - original licence link has changed is not relivant.
23994 * <script type="text/javascript">
23999 * @class Roo.dd.DropTarget
24000 * @extends Roo.dd.DDTarget
24001 * A simple class that provides the basic implementation needed to make any element a drop target that can have
24002 * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
24004 * @param {String/HTMLElement/Element} el The container element
24005 * @param {Object} config
24007 Roo.dd.DropTarget = function(el, config){
24008 this.el = Roo.get(el);
24010 var listeners = false; ;
24011 if (config && config.listeners) {
24012 listeners= config.listeners;
24013 delete config.listeners;
24015 Roo.apply(this, config);
24017 if(this.containerScroll){
24018 Roo.dd.ScrollManager.register(this.el);
24022 * @scope Roo.dd.DropTarget
24027 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
24028 * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
24029 * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
24031 * IMPORTANT : it should set this.valid to true|false
24033 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
24034 * @param {Event} e The event
24035 * @param {Object} data An object containing arbitrary data supplied by the drag source
24041 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
24042 * This method will be called on every mouse movement while the drag source is over the drop target.
24043 * This default implementation simply returns the dropAllowed config value.
24045 * IMPORTANT : it should set this.valid to true|false
24047 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
24048 * @param {Event} e The event
24049 * @param {Object} data An object containing arbitrary data supplied by the drag source
24055 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
24056 * out of the target without dropping. This default implementation simply removes the CSS class specified by
24057 * overClass (if any) from the drop element.
24060 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
24061 * @param {Event} e The event
24062 * @param {Object} data An object containing arbitrary data supplied by the drag source
24068 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
24069 * been dropped on it. This method has no default implementation and returns false, so you must provide an
24070 * implementation that does something to process the drop event and returns true so that the drag source's
24071 * repair action does not run.
24073 * IMPORTANT : it should set this.success
24075 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
24076 * @param {Event} e The event
24077 * @param {Object} data An object containing arbitrary data supplied by the drag source
24083 Roo.dd.DropTarget.superclass.constructor.call( this,
24085 this.ddGroup || this.group,
24088 listeners : listeners || {}
24096 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
24098 * @cfg {String} overClass
24099 * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
24102 * @cfg {String} ddGroup
24103 * The drag drop group to handle drop events for
24107 * @cfg {String} dropAllowed
24108 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
24110 dropAllowed : "x-dd-drop-ok",
24112 * @cfg {String} dropNotAllowed
24113 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
24115 dropNotAllowed : "x-dd-drop-nodrop",
24117 * @cfg {boolean} success
24118 * set this after drop listener..
24122 * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
24123 * if the drop point is valid for over/enter..
24130 isNotifyTarget : true,
24135 notifyEnter : function(dd, e, data)
24138 this.fireEvent('enter', dd, e, data);
24139 if(this.overClass){
24140 this.el.addClass(this.overClass);
24142 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
24143 this.valid ? this.dropAllowed : this.dropNotAllowed
24150 notifyOver : function(dd, e, data)
24153 this.fireEvent('over', dd, e, data);
24154 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
24155 this.valid ? this.dropAllowed : this.dropNotAllowed
24162 notifyOut : function(dd, e, data)
24164 this.fireEvent('out', dd, e, data);
24165 if(this.overClass){
24166 this.el.removeClass(this.overClass);
24173 notifyDrop : function(dd, e, data)
24175 this.success = false;
24176 this.fireEvent('drop', dd, e, data);
24177 return this.success;
24181 * Ext JS Library 1.1.1
24182 * Copyright(c) 2006-2007, Ext JS, LLC.
24184 * Originally Released Under LGPL - original licence link has changed is not relivant.
24187 * <script type="text/javascript">
24192 * @class Roo.dd.DragZone
24193 * @extends Roo.dd.DragSource
24194 * This class provides a container DD instance that proxies for multiple child node sources.<br />
24195 * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
24197 * @param {String/HTMLElement/Element} el The container element
24198 * @param {Object} config
24200 Roo.dd.DragZone = function(el, config){
24201 Roo.dd.DragZone.superclass.constructor.call(this, el, config);
24202 if(this.containerScroll){
24203 Roo.dd.ScrollManager.register(this.el);
24207 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
24209 * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
24210 * for auto scrolling during drag operations.
24213 * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
24214 * method after a failed drop (defaults to "c3daf9" - light blue)
24218 * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
24219 * for a valid target to drag based on the mouse down. Override this method
24220 * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
24221 * object has a "ddel" attribute (with an HTML Element) for other functions to work.
24222 * @param {EventObject} e The mouse down event
24223 * @return {Object} The dragData
24225 getDragData : function(e){
24226 return Roo.dd.Registry.getHandleFromEvent(e);
24230 * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
24231 * this.dragData.ddel
24232 * @param {Number} x The x position of the click on the dragged object
24233 * @param {Number} y The y position of the click on the dragged object
24234 * @return {Boolean} true to continue the drag, false to cancel
24236 onInitDrag : function(x, y){
24237 this.proxy.update(this.dragData.ddel.cloneNode(true));
24238 this.onStartDrag(x, y);
24243 * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
24245 afterRepair : function(){
24247 Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
24249 this.dragging = false;
24253 * Called before a repair of an invalid drop to get the XY to animate to. By default returns
24254 * the XY of this.dragData.ddel
24255 * @param {EventObject} e The mouse up event
24256 * @return {Array} The xy location (e.g. [100, 200])
24258 getRepairXY : function(e){
24259 return Roo.Element.fly(this.dragData.ddel).getXY();
24263 * Ext JS Library 1.1.1
24264 * Copyright(c) 2006-2007, Ext JS, LLC.
24266 * Originally Released Under LGPL - original licence link has changed is not relivant.
24269 * <script type="text/javascript">
24272 * @class Roo.dd.DropZone
24273 * @extends Roo.dd.DropTarget
24274 * This class provides a container DD instance that proxies for multiple child node targets.<br />
24275 * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
24277 * @param {String/HTMLElement/Element} el The container element
24278 * @param {Object} config
24280 Roo.dd.DropZone = function(el, config){
24281 Roo.dd.DropZone.superclass.constructor.call(this, el, config);
24284 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
24286 * Returns a custom data object associated with the DOM node that is the target of the event. By default
24287 * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
24288 * provide your own custom lookup.
24289 * @param {Event} e The event
24290 * @return {Object} data The custom data
24292 getTargetFromEvent : function(e){
24293 return Roo.dd.Registry.getTargetFromEvent(e);
24297 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
24298 * that it has registered. This method has no default implementation and should be overridden to provide
24299 * node-specific processing if necessary.
24300 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24301 * {@link #getTargetFromEvent} for this node)
24302 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24303 * @param {Event} e The event
24304 * @param {Object} data An object containing arbitrary data supplied by the drag source
24306 onNodeEnter : function(n, dd, e, data){
24311 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
24312 * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
24313 * overridden to provide the proper feedback.
24314 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24315 * {@link #getTargetFromEvent} for this node)
24316 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24317 * @param {Event} e The event
24318 * @param {Object} data An object containing arbitrary data supplied by the drag source
24319 * @return {String} status The CSS class that communicates the drop status back to the source so that the
24320 * underlying {@link Roo.dd.StatusProxy} can be updated
24322 onNodeOver : function(n, dd, e, data){
24323 return this.dropAllowed;
24327 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
24328 * the drop node without dropping. This method has no default implementation and should be overridden to provide
24329 * node-specific processing if necessary.
24330 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24331 * {@link #getTargetFromEvent} for this node)
24332 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24333 * @param {Event} e The event
24334 * @param {Object} data An object containing arbitrary data supplied by the drag source
24336 onNodeOut : function(n, dd, e, data){
24341 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
24342 * the drop node. The default implementation returns false, so it should be overridden to provide the
24343 * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
24344 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24345 * {@link #getTargetFromEvent} for this node)
24346 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24347 * @param {Event} e The event
24348 * @param {Object} data An object containing arbitrary data supplied by the drag source
24349 * @return {Boolean} True if the drop was valid, else false
24351 onNodeDrop : function(n, dd, e, data){
24356 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
24357 * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
24358 * it should be overridden to provide the proper feedback if necessary.
24359 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24360 * @param {Event} e The event
24361 * @param {Object} data An object containing arbitrary data supplied by the drag source
24362 * @return {String} status The CSS class that communicates the drop status back to the source so that the
24363 * underlying {@link Roo.dd.StatusProxy} can be updated
24365 onContainerOver : function(dd, e, data){
24366 return this.dropNotAllowed;
24370 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
24371 * but not on any of its registered drop nodes. The default implementation returns false, so it should be
24372 * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
24373 * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
24374 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24375 * @param {Event} e The event
24376 * @param {Object} data An object containing arbitrary data supplied by the drag source
24377 * @return {Boolean} True if the drop was valid, else false
24379 onContainerDrop : function(dd, e, data){
24384 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
24385 * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
24386 * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
24387 * you should override this method and provide a custom implementation.
24388 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24389 * @param {Event} e The event
24390 * @param {Object} data An object containing arbitrary data supplied by the drag source
24391 * @return {String} status The CSS class that communicates the drop status back to the source so that the
24392 * underlying {@link Roo.dd.StatusProxy} can be updated
24394 notifyEnter : function(dd, e, data){
24395 return this.dropNotAllowed;
24399 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
24400 * This method will be called on every mouse movement while the drag source is over the drop zone.
24401 * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
24402 * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
24403 * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
24404 * registered node, it will call {@link #onContainerOver}.
24405 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24406 * @param {Event} e The event
24407 * @param {Object} data An object containing arbitrary data supplied by the drag source
24408 * @return {String} status The CSS class that communicates the drop status back to the source so that the
24409 * underlying {@link Roo.dd.StatusProxy} can be updated
24411 notifyOver : function(dd, e, data){
24412 var n = this.getTargetFromEvent(e);
24413 if(!n){ // not over valid drop target
24414 if(this.lastOverNode){
24415 this.onNodeOut(this.lastOverNode, dd, e, data);
24416 this.lastOverNode = null;
24418 return this.onContainerOver(dd, e, data);
24420 if(this.lastOverNode != n){
24421 if(this.lastOverNode){
24422 this.onNodeOut(this.lastOverNode, dd, e, data);
24424 this.onNodeEnter(n, dd, e, data);
24425 this.lastOverNode = n;
24427 return this.onNodeOver(n, dd, e, data);
24431 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
24432 * out of the zone without dropping. If the drag source is currently over a registered node, the notification
24433 * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
24434 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
24435 * @param {Event} e The event
24436 * @param {Object} data An object containing arbitrary data supplied by the drag zone
24438 notifyOut : function(dd, e, data){
24439 if(this.lastOverNode){
24440 this.onNodeOut(this.lastOverNode, dd, e, data);
24441 this.lastOverNode = null;
24446 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
24447 * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
24448 * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
24449 * otherwise it will call {@link #onContainerDrop}.
24450 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24451 * @param {Event} e The event
24452 * @param {Object} data An object containing arbitrary data supplied by the drag source
24453 * @return {Boolean} True if the drop was valid, else false
24455 notifyDrop : function(dd, e, data){
24456 if(this.lastOverNode){
24457 this.onNodeOut(this.lastOverNode, dd, e, data);
24458 this.lastOverNode = null;
24460 var n = this.getTargetFromEvent(e);
24462 this.onNodeDrop(n, dd, e, data) :
24463 this.onContainerDrop(dd, e, data);
24467 triggerCacheRefresh : function(){
24468 Roo.dd.DDM.refreshCache(this.groups);
24472 * Ext JS Library 1.1.1
24473 * Copyright(c) 2006-2007, Ext JS, LLC.
24475 * Originally Released Under LGPL - original licence link has changed is not relivant.
24478 * <script type="text/javascript">
24483 * @class Roo.data.SortTypes
24485 * Defines the default sorting (casting?) comparison functions used when sorting data.
24487 Roo.data.SortTypes = {
24489 * Default sort that does nothing
24490 * @param {Mixed} s The value being converted
24491 * @return {Mixed} The comparison value
24493 none : function(s){
24498 * The regular expression used to strip tags
24502 stripTagsRE : /<\/?[^>]+>/gi,
24505 * Strips all HTML tags to sort on text only
24506 * @param {Mixed} s The value being converted
24507 * @return {String} The comparison value
24509 asText : function(s){
24510 return String(s).replace(this.stripTagsRE, "");
24514 * Strips all HTML tags to sort on text only - Case insensitive
24515 * @param {Mixed} s The value being converted
24516 * @return {String} The comparison value
24518 asUCText : function(s){
24519 return String(s).toUpperCase().replace(this.stripTagsRE, "");
24523 * Case insensitive string
24524 * @param {Mixed} s The value being converted
24525 * @return {String} The comparison value
24527 asUCString : function(s) {
24528 return String(s).toUpperCase();
24533 * @param {Mixed} s The value being converted
24534 * @return {Number} The comparison value
24536 asDate : function(s) {
24540 if(s instanceof Date){
24541 return s.getTime();
24543 return Date.parse(String(s));
24548 * @param {Mixed} s The value being converted
24549 * @return {Float} The comparison value
24551 asFloat : function(s) {
24552 var val = parseFloat(String(s).replace(/,/g, ""));
24561 * @param {Mixed} s The value being converted
24562 * @return {Number} The comparison value
24564 asInt : function(s) {
24565 var val = parseInt(String(s).replace(/,/g, ""));
24573 * Ext JS Library 1.1.1
24574 * Copyright(c) 2006-2007, Ext JS, LLC.
24576 * Originally Released Under LGPL - original licence link has changed is not relivant.
24579 * <script type="text/javascript">
24583 * @class Roo.data.Record
24584 * Instances of this class encapsulate both record <em>definition</em> information, and record
24585 * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
24586 * to access Records cached in an {@link Roo.data.Store} object.<br>
24588 * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
24589 * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
24592 * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
24594 * This constructor should not be used to create Record objects. Instead, use the constructor generated by
24595 * {@link #create}. The parameters are the same.
24596 * @param {Array} data An associative Array of data values keyed by the field name.
24597 * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
24598 * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
24599 * not specified an integer id is generated.
24601 Roo.data.Record = function(data, id){
24602 this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
24607 * Generate a constructor for a specific record layout.
24608 * @param {Array} o An Array of field definition objects which specify field names, and optionally,
24609 * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
24610 * Each field definition object may contain the following properties: <ul>
24611 * <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,
24612 * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
24613 * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
24614 * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
24615 * is being used, then this is a string containing the javascript expression to reference the data relative to
24616 * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
24617 * to the data item relative to the record element. If the mapping expression is the same as the field name,
24618 * this may be omitted.</p></li>
24619 * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
24620 * <ul><li>auto (Default, implies no conversion)</li>
24625 * <li>date</li></ul></p></li>
24626 * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
24627 * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
24628 * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
24629 * by the Reader into an object that will be stored in the Record. It is passed the
24630 * following parameters:<ul>
24631 * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
24633 * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
24635 * <br>usage:<br><pre><code>
24636 var TopicRecord = Roo.data.Record.create(
24637 {name: 'title', mapping: 'topic_title'},
24638 {name: 'author', mapping: 'username'},
24639 {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
24640 {name: 'lastPost', mapping: 'post_time', type: 'date'},
24641 {name: 'lastPoster', mapping: 'user2'},
24642 {name: 'excerpt', mapping: 'post_text'}
24645 var myNewRecord = new TopicRecord({
24646 title: 'Do my job please',
24649 lastPost: new Date(),
24650 lastPoster: 'Animal',
24651 excerpt: 'No way dude!'
24653 myStore.add(myNewRecord);
24658 Roo.data.Record.create = function(o){
24659 var f = function(){
24660 f.superclass.constructor.apply(this, arguments);
24662 Roo.extend(f, Roo.data.Record);
24663 var p = f.prototype;
24664 p.fields = new Roo.util.MixedCollection(false, function(field){
24667 for(var i = 0, len = o.length; i < len; i++){
24668 p.fields.add(new Roo.data.Field(o[i]));
24670 f.getField = function(name){
24671 return p.fields.get(name);
24676 Roo.data.Record.AUTO_ID = 1000;
24677 Roo.data.Record.EDIT = 'edit';
24678 Roo.data.Record.REJECT = 'reject';
24679 Roo.data.Record.COMMIT = 'commit';
24681 Roo.data.Record.prototype = {
24683 * Readonly flag - true if this record has been modified.
24692 join : function(store){
24693 this.store = store;
24697 * Set the named field to the specified value.
24698 * @param {String} name The name of the field to set.
24699 * @param {Object} value The value to set the field to.
24701 set : function(name, value){
24702 if(this.data[name] == value){
24706 if(!this.modified){
24707 this.modified = {};
24709 if(typeof this.modified[name] == 'undefined'){
24710 this.modified[name] = this.data[name];
24712 this.data[name] = value;
24713 if(!this.editing && this.store){
24714 this.store.afterEdit(this);
24719 * Get the value of the named field.
24720 * @param {String} name The name of the field to get the value of.
24721 * @return {Object} The value of the field.
24723 get : function(name){
24724 return this.data[name];
24728 beginEdit : function(){
24729 this.editing = true;
24730 this.modified = {};
24734 cancelEdit : function(){
24735 this.editing = false;
24736 delete this.modified;
24740 endEdit : function(){
24741 this.editing = false;
24742 if(this.dirty && this.store){
24743 this.store.afterEdit(this);
24748 * Usually called by the {@link Roo.data.Store} which owns the Record.
24749 * Rejects all changes made to the Record since either creation, or the last commit operation.
24750 * Modified fields are reverted to their original values.
24752 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
24753 * of reject operations.
24755 reject : function(){
24756 var m = this.modified;
24758 if(typeof m[n] != "function"){
24759 this.data[n] = m[n];
24762 this.dirty = false;
24763 delete this.modified;
24764 this.editing = false;
24766 this.store.afterReject(this);
24771 * Usually called by the {@link Roo.data.Store} which owns the Record.
24772 * Commits all changes made to the Record since either creation, or the last commit operation.
24774 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
24775 * of commit operations.
24777 commit : function(){
24778 this.dirty = false;
24779 delete this.modified;
24780 this.editing = false;
24782 this.store.afterCommit(this);
24787 hasError : function(){
24788 return this.error != null;
24792 clearError : function(){
24797 * Creates a copy of this record.
24798 * @param {String} id (optional) A new record id if you don't want to use this record's id
24801 copy : function(newId) {
24802 return new this.constructor(Roo.apply({}, this.data), newId || this.id);
24806 * Ext JS Library 1.1.1
24807 * Copyright(c) 2006-2007, Ext JS, LLC.
24809 * Originally Released Under LGPL - original licence link has changed is not relivant.
24812 * <script type="text/javascript">
24818 * @class Roo.data.Store
24819 * @extends Roo.util.Observable
24820 * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
24821 * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
24823 * 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
24824 * has no knowledge of the format of the data returned by the Proxy.<br>
24826 * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
24827 * instances from the data object. These records are cached and made available through accessor functions.
24829 * Creates a new Store.
24830 * @param {Object} config A config object containing the objects needed for the Store to access data,
24831 * and read the data into Records.
24833 Roo.data.Store = function(config){
24834 this.data = new Roo.util.MixedCollection(false);
24835 this.data.getKey = function(o){
24838 this.baseParams = {};
24840 this.paramNames = {
24845 "multisort" : "_multisort"
24848 if(config && config.data){
24849 this.inlineData = config.data;
24850 delete config.data;
24853 Roo.apply(this, config);
24855 if(this.reader){ // reader passed
24856 this.reader = Roo.factory(this.reader, Roo.data);
24857 this.reader.xmodule = this.xmodule || false;
24858 if(!this.recordType){
24859 this.recordType = this.reader.recordType;
24861 if(this.reader.onMetaChange){
24862 this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
24866 if(this.recordType){
24867 this.fields = this.recordType.prototype.fields;
24869 this.modified = [];
24873 * @event datachanged
24874 * Fires when the data cache has changed, and a widget which is using this Store
24875 * as a Record cache should refresh its view.
24876 * @param {Store} this
24878 datachanged : true,
24880 * @event metachange
24881 * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
24882 * @param {Store} this
24883 * @param {Object} meta The JSON metadata
24888 * Fires when Records have been added to the Store
24889 * @param {Store} this
24890 * @param {Roo.data.Record[]} records The array of Records added
24891 * @param {Number} index The index at which the record(s) were added
24896 * Fires when a Record has been removed from the Store
24897 * @param {Store} this
24898 * @param {Roo.data.Record} record The Record that was removed
24899 * @param {Number} index The index at which the record was removed
24904 * Fires when a Record has been updated
24905 * @param {Store} this
24906 * @param {Roo.data.Record} record The Record that was updated
24907 * @param {String} operation The update operation being performed. Value may be one of:
24909 Roo.data.Record.EDIT
24910 Roo.data.Record.REJECT
24911 Roo.data.Record.COMMIT
24917 * Fires when the data cache has been cleared.
24918 * @param {Store} this
24922 * @event beforeload
24923 * Fires before a request is made for a new data object. If the beforeload handler returns false
24924 * the load action will be canceled.
24925 * @param {Store} this
24926 * @param {Object} options The loading options that were specified (see {@link #load} for details)
24930 * @event beforeloadadd
24931 * Fires after a new set of Records has been loaded.
24932 * @param {Store} this
24933 * @param {Roo.data.Record[]} records The Records that were loaded
24934 * @param {Object} options The loading options that were specified (see {@link #load} for details)
24936 beforeloadadd : true,
24939 * Fires after a new set of Records has been loaded, before they are added to the store.
24940 * @param {Store} this
24941 * @param {Roo.data.Record[]} records The Records that were loaded
24942 * @param {Object} options The loading options that were specified (see {@link #load} for details)
24943 * @params {Object} return from reader
24947 * @event loadexception
24948 * Fires if an exception occurs in the Proxy during loading.
24949 * Called with the signature of the Proxy's "loadexception" event.
24950 * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
24953 * @param {Object} return from JsonData.reader() - success, totalRecords, records
24954 * @param {Object} load options
24955 * @param {Object} jsonData from your request (normally this contains the Exception)
24957 loadexception : true
24961 this.proxy = Roo.factory(this.proxy, Roo.data);
24962 this.proxy.xmodule = this.xmodule || false;
24963 this.relayEvents(this.proxy, ["loadexception"]);
24965 this.sortToggle = {};
24966 this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
24968 Roo.data.Store.superclass.constructor.call(this);
24970 if(this.inlineData){
24971 this.loadData(this.inlineData);
24972 delete this.inlineData;
24976 Roo.extend(Roo.data.Store, Roo.util.Observable, {
24978 * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
24979 * without a remote query - used by combo/forms at present.
24983 * @cfg {Roo.data.DataProxy} proxy [required] The Proxy object which provides access to a data object.
24986 * @cfg {Array} data Inline data to be loaded when the store is initialized.
24989 * @cfg {Roo.data.DataReader} reader [required] The Reader object which processes the data object and returns
24990 * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
24993 * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
24994 * on any HTTP request
24997 * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
25000 * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
25004 * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
25005 * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
25007 remoteSort : false,
25010 * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
25011 * loaded or when a record is removed. (defaults to false).
25013 pruneModifiedRecords : false,
25016 lastOptions : null,
25019 * Add Records to the Store and fires the add event.
25020 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
25022 add : function(records){
25023 records = [].concat(records);
25024 for(var i = 0, len = records.length; i < len; i++){
25025 records[i].join(this);
25027 var index = this.data.length;
25028 this.data.addAll(records);
25029 this.fireEvent("add", this, records, index);
25033 * Remove a Record from the Store and fires the remove event.
25034 * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
25036 remove : function(record){
25037 var index = this.data.indexOf(record);
25038 this.data.removeAt(index);
25040 if(this.pruneModifiedRecords){
25041 this.modified.remove(record);
25043 this.fireEvent("remove", this, record, index);
25047 * Remove all Records from the Store and fires the clear event.
25049 removeAll : function(){
25051 if(this.pruneModifiedRecords){
25052 this.modified = [];
25054 this.fireEvent("clear", this);
25058 * Inserts Records to the Store at the given index and fires the add event.
25059 * @param {Number} index The start index at which to insert the passed Records.
25060 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
25062 insert : function(index, records){
25063 records = [].concat(records);
25064 for(var i = 0, len = records.length; i < len; i++){
25065 this.data.insert(index, records[i]);
25066 records[i].join(this);
25068 this.fireEvent("add", this, records, index);
25072 * Get the index within the cache of the passed Record.
25073 * @param {Roo.data.Record} record The Roo.data.Record object to to find.
25074 * @return {Number} The index of the passed Record. Returns -1 if not found.
25076 indexOf : function(record){
25077 return this.data.indexOf(record);
25081 * Get the index within the cache of the Record with the passed id.
25082 * @param {String} id The id of the Record to find.
25083 * @return {Number} The index of the Record. Returns -1 if not found.
25085 indexOfId : function(id){
25086 return this.data.indexOfKey(id);
25090 * Get the Record with the specified id.
25091 * @param {String} id The id of the Record to find.
25092 * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
25094 getById : function(id){
25095 return this.data.key(id);
25099 * Get the Record at the specified index.
25100 * @param {Number} index The index of the Record to find.
25101 * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
25103 getAt : function(index){
25104 return this.data.itemAt(index);
25108 * Returns a range of Records between specified indices.
25109 * @param {Number} startIndex (optional) The starting index (defaults to 0)
25110 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
25111 * @return {Roo.data.Record[]} An array of Records
25113 getRange : function(start, end){
25114 return this.data.getRange(start, end);
25118 storeOptions : function(o){
25119 o = Roo.apply({}, o);
25122 this.lastOptions = o;
25126 * Loads the Record cache from the configured Proxy using the configured Reader.
25128 * If using remote paging, then the first load call must specify the <em>start</em>
25129 * and <em>limit</em> properties in the options.params property to establish the initial
25130 * position within the dataset, and the number of Records to cache on each read from the Proxy.
25132 * <strong>It is important to note that for remote data sources, loading is asynchronous,
25133 * and this call will return before the new data has been loaded. Perform any post-processing
25134 * in a callback function, or in a "load" event handler.</strong>
25136 * @param {Object} options An object containing properties which control loading options:<ul>
25137 * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
25138 * <li>params.data {Object} if you are using a MemoryProxy / JsonReader, use this as the data to load stuff..
25141 data : data, // array of key=>value data like JsonReader
25142 total : data.length,
25148 * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
25149 * passed the following arguments:<ul>
25150 * <li>r : Roo.data.Record[]</li>
25151 * <li>options: Options object from the load call</li>
25152 * <li>success: Boolean success indicator</li></ul></li>
25153 * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
25154 * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
25157 load : function(options){
25158 options = options || {};
25159 if(this.fireEvent("beforeload", this, options) !== false){
25160 this.storeOptions(options);
25161 var p = Roo.apply(options.params || {}, this.baseParams);
25162 // if meta was not loaded from remote source.. try requesting it.
25163 if (!this.reader.metaFromRemote) {
25164 p._requestMeta = 1;
25166 if(this.sortInfo && this.remoteSort){
25167 var pn = this.paramNames;
25168 p[pn["sort"]] = this.sortInfo.field;
25169 p[pn["dir"]] = this.sortInfo.direction;
25171 if (this.multiSort) {
25172 var pn = this.paramNames;
25173 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
25176 this.proxy.load(p, this.reader, this.loadRecords, this, options);
25181 * Reloads the Record cache from the configured Proxy using the configured Reader and
25182 * the options from the last load operation performed.
25183 * @param {Object} options (optional) An object containing properties which may override the options
25184 * used in the last load operation. See {@link #load} for details (defaults to null, in which case
25185 * the most recently used options are reused).
25187 reload : function(options){
25188 this.load(Roo.applyIf(options||{}, this.lastOptions));
25192 // Called as a callback by the Reader during a load operation.
25193 loadRecords : function(o, options, success){
25196 if(success !== false){
25197 this.fireEvent("load", this, [], options, o);
25199 if(options.callback){
25200 options.callback.call(options.scope || this, [], options, false);
25204 // if data returned failure - throw an exception.
25205 if (o.success === false) {
25206 // show a message if no listener is registered.
25207 if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
25208 Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
25210 // loadmask wil be hooked into this..
25211 this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
25214 var r = o.records, t = o.totalRecords || r.length;
25216 this.fireEvent("beforeloadadd", this, r, options, o);
25218 if(!options || options.add !== true){
25219 if(this.pruneModifiedRecords){
25220 this.modified = [];
25222 for(var i = 0, len = r.length; i < len; i++){
25226 this.data = this.snapshot;
25227 delete this.snapshot;
25230 this.data.addAll(r);
25231 this.totalLength = t;
25233 this.fireEvent("datachanged", this);
25235 this.totalLength = Math.max(t, this.data.length+r.length);
25239 if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
25241 var e = new Roo.data.Record({});
25243 e.set(this.parent.displayField, this.parent.emptyTitle);
25244 e.set(this.parent.valueField, '');
25249 this.fireEvent("load", this, r, options, o);
25250 if(options.callback){
25251 options.callback.call(options.scope || this, r, options, true);
25257 * Loads data from a passed data block. A Reader which understands the format of the data
25258 * must have been configured in the constructor.
25259 * @param {Object} data The data block from which to read the Records. The format of the data expected
25260 * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
25261 * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
25263 loadData : function(o, append){
25264 var r = this.reader.readRecords(o);
25265 this.loadRecords(r, {add: append}, true);
25269 * using 'cn' the nested child reader read the child array into it's child stores.
25270 * @param {Object} rec The record with a 'children array
25272 loadDataFromChildren : function(rec)
25274 this.loadData(this.reader.toLoadData(rec));
25279 * Gets the number of cached records.
25281 * <em>If using paging, this may not be the total size of the dataset. If the data object
25282 * used by the Reader contains the dataset size, then the getTotalCount() function returns
25283 * the data set size</em>
25285 getCount : function(){
25286 return this.data.length || 0;
25290 * Gets the total number of records in the dataset as returned by the server.
25292 * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
25293 * the dataset size</em>
25295 getTotalCount : function(){
25296 return this.totalLength || 0;
25300 * Returns the sort state of the Store as an object with two properties:
25302 field {String} The name of the field by which the Records are sorted
25303 direction {String} The sort order, "ASC" or "DESC"
25306 getSortState : function(){
25307 return this.sortInfo;
25311 applySort : function(){
25312 if(this.sortInfo && !this.remoteSort){
25313 var s = this.sortInfo, f = s.field;
25314 var st = this.fields.get(f).sortType;
25315 var fn = function(r1, r2){
25316 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
25317 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
25319 this.data.sort(s.direction, fn);
25320 if(this.snapshot && this.snapshot != this.data){
25321 this.snapshot.sort(s.direction, fn);
25327 * Sets the default sort column and order to be used by the next load operation.
25328 * @param {String} fieldName The name of the field to sort by.
25329 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
25331 setDefaultSort : function(field, dir){
25332 this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
25336 * Sort the Records.
25337 * If remote sorting is used, the sort is performed on the server, and the cache is
25338 * reloaded. If local sorting is used, the cache is sorted internally.
25339 * @param {String} fieldName The name of the field to sort by.
25340 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
25342 sort : function(fieldName, dir){
25343 var f = this.fields.get(fieldName);
25345 this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
25347 if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
25348 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
25353 this.sortToggle[f.name] = dir;
25354 this.sortInfo = {field: f.name, direction: dir};
25355 if(!this.remoteSort){
25357 this.fireEvent("datachanged", this);
25359 this.load(this.lastOptions);
25364 * Calls the specified function for each of the Records in the cache.
25365 * @param {Function} fn The function to call. The Record is passed as the first parameter.
25366 * Returning <em>false</em> aborts and exits the iteration.
25367 * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
25369 each : function(fn, scope){
25370 this.data.each(fn, scope);
25374 * Gets all records modified since the last commit. Modified records are persisted across load operations
25375 * (e.g., during paging).
25376 * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
25378 getModifiedRecords : function(){
25379 return this.modified;
25383 createFilterFn : function(property, value, anyMatch){
25384 if(!value.exec){ // not a regex
25385 value = String(value);
25386 if(value.length == 0){
25389 value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
25391 return function(r){
25392 return value.test(r.data[property]);
25397 * Sums the value of <i>property</i> for each record between start and end and returns the result.
25398 * @param {String} property A field on your records
25399 * @param {Number} start The record index to start at (defaults to 0)
25400 * @param {Number} end The last record index to include (defaults to length - 1)
25401 * @return {Number} The sum
25403 sum : function(property, start, end){
25404 var rs = this.data.items, v = 0;
25405 start = start || 0;
25406 end = (end || end === 0) ? end : rs.length-1;
25408 for(var i = start; i <= end; i++){
25409 v += (rs[i].data[property] || 0);
25415 * Filter the records by a specified property.
25416 * @param {String} field A field on your records
25417 * @param {String/RegExp} value Either a string that the field
25418 * should start with or a RegExp to test against the field
25419 * @param {Boolean} anyMatch True to match any part not just the beginning
25421 filter : function(property, value, anyMatch){
25422 var fn = this.createFilterFn(property, value, anyMatch);
25423 return fn ? this.filterBy(fn) : this.clearFilter();
25427 * Filter by a function. The specified function will be called with each
25428 * record in this data source. If the function returns true the record is included,
25429 * otherwise it is filtered.
25430 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
25431 * @param {Object} scope (optional) The scope of the function (defaults to this)
25433 filterBy : function(fn, scope){
25434 this.snapshot = this.snapshot || this.data;
25435 this.data = this.queryBy(fn, scope||this);
25436 this.fireEvent("datachanged", this);
25440 * Query the records by a specified property.
25441 * @param {String} field A field on your records
25442 * @param {String/RegExp} value Either a string that the field
25443 * should start with or a RegExp to test against the field
25444 * @param {Boolean} anyMatch True to match any part not just the beginning
25445 * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
25447 query : function(property, value, anyMatch){
25448 var fn = this.createFilterFn(property, value, anyMatch);
25449 return fn ? this.queryBy(fn) : this.data.clone();
25453 * Query by a function. The specified function will be called with each
25454 * record in this data source. If the function returns true the record is included
25456 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
25457 * @param {Object} scope (optional) The scope of the function (defaults to this)
25458 @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
25460 queryBy : function(fn, scope){
25461 var data = this.snapshot || this.data;
25462 return data.filterBy(fn, scope||this);
25466 * Collects unique values for a particular dataIndex from this store.
25467 * @param {String} dataIndex The property to collect
25468 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
25469 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
25470 * @return {Array} An array of the unique values
25472 collect : function(dataIndex, allowNull, bypassFilter){
25473 var d = (bypassFilter === true && this.snapshot) ?
25474 this.snapshot.items : this.data.items;
25475 var v, sv, r = [], l = {};
25476 for(var i = 0, len = d.length; i < len; i++){
25477 v = d[i].data[dataIndex];
25479 if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
25488 * Revert to a view of the Record cache with no filtering applied.
25489 * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
25491 clearFilter : function(suppressEvent){
25492 if(this.snapshot && this.snapshot != this.data){
25493 this.data = this.snapshot;
25494 delete this.snapshot;
25495 if(suppressEvent !== true){
25496 this.fireEvent("datachanged", this);
25502 afterEdit : function(record){
25503 if(this.modified.indexOf(record) == -1){
25504 this.modified.push(record);
25506 this.fireEvent("update", this, record, Roo.data.Record.EDIT);
25510 afterReject : function(record){
25511 this.modified.remove(record);
25512 this.fireEvent("update", this, record, Roo.data.Record.REJECT);
25516 afterCommit : function(record){
25517 this.modified.remove(record);
25518 this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
25522 * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
25523 * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
25525 commitChanges : function(){
25526 var m = this.modified.slice(0);
25527 this.modified = [];
25528 for(var i = 0, len = m.length; i < len; i++){
25534 * Cancel outstanding changes on all changed records.
25536 rejectChanges : function(){
25537 var m = this.modified.slice(0);
25538 this.modified = [];
25539 for(var i = 0, len = m.length; i < len; i++){
25544 onMetaChange : function(meta, rtype, o){
25545 this.recordType = rtype;
25546 this.fields = rtype.prototype.fields;
25547 delete this.snapshot;
25548 this.sortInfo = meta.sortInfo || this.sortInfo;
25549 this.modified = [];
25550 this.fireEvent('metachange', this, this.reader.meta);
25553 moveIndex : function(data, type)
25555 var index = this.indexOf(data);
25557 var newIndex = index + type;
25561 this.insert(newIndex, data);
25566 * Ext JS Library 1.1.1
25567 * Copyright(c) 2006-2007, Ext JS, LLC.
25569 * Originally Released Under LGPL - original licence link has changed is not relivant.
25572 * <script type="text/javascript">
25576 * @class Roo.data.SimpleStore
25577 * @extends Roo.data.Store
25578 * Small helper class to make creating Stores from Array data easier.
25579 * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
25580 * @cfg {Array} fields An array of field definition objects, or field name strings.
25581 * @cfg {Object} an existing reader (eg. copied from another store)
25582 * @cfg {Array} data The multi-dimensional array of data
25583 * @cfg {Roo.data.DataProxy} proxy [not-required]
25584 * @cfg {Roo.data.Reader} reader [not-required]
25586 * @param {Object} config
25588 Roo.data.SimpleStore = function(config)
25590 Roo.data.SimpleStore.superclass.constructor.call(this, {
25592 reader: typeof(config.reader) != 'undefined' ? config.reader : new Roo.data.ArrayReader({
25595 Roo.data.Record.create(config.fields)
25597 proxy : new Roo.data.MemoryProxy(config.data)
25601 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
25603 * Ext JS Library 1.1.1
25604 * Copyright(c) 2006-2007, Ext JS, LLC.
25606 * Originally Released Under LGPL - original licence link has changed is not relivant.
25609 * <script type="text/javascript">
25614 * @extends Roo.data.Store
25615 * @class Roo.data.JsonStore
25616 * Small helper class to make creating Stores for JSON data easier. <br/>
25618 var store = new Roo.data.JsonStore({
25619 url: 'get-images.php',
25621 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
25624 * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
25625 * JsonReader and HttpProxy (unless inline data is provided).</b>
25626 * @cfg {Array} fields An array of field definition objects, or field name strings.
25628 * @param {Object} config
25630 Roo.data.JsonStore = function(c){
25631 Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
25632 proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
25633 reader: new Roo.data.JsonReader(c, c.fields)
25636 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
25638 * Ext JS Library 1.1.1
25639 * Copyright(c) 2006-2007, Ext JS, LLC.
25641 * Originally Released Under LGPL - original licence link has changed is not relivant.
25644 * <script type="text/javascript">
25648 Roo.data.Field = function(config){
25649 if(typeof config == "string"){
25650 config = {name: config};
25652 Roo.apply(this, config);
25655 this.type = "auto";
25658 var st = Roo.data.SortTypes;
25659 // named sortTypes are supported, here we look them up
25660 if(typeof this.sortType == "string"){
25661 this.sortType = st[this.sortType];
25664 // set default sortType for strings and dates
25665 if(!this.sortType){
25668 this.sortType = st.asUCString;
25671 this.sortType = st.asDate;
25674 this.sortType = st.none;
25679 var stripRe = /[\$,%]/g;
25681 // prebuilt conversion function for this field, instead of
25682 // switching every time we're reading a value
25684 var cv, dateFormat = this.dateFormat;
25689 cv = function(v){ return v; };
25692 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
25696 return v !== undefined && v !== null && v !== '' ?
25697 parseInt(String(v).replace(stripRe, ""), 10) : '';
25702 return v !== undefined && v !== null && v !== '' ?
25703 parseFloat(String(v).replace(stripRe, ""), 10) : '';
25708 cv = function(v){ return v === true || v === "true" || v == 1; };
25715 if(v instanceof Date){
25719 if(dateFormat == "timestamp"){
25720 return new Date(v*1000);
25722 return Date.parseDate(v, dateFormat);
25724 var parsed = Date.parse(v);
25725 return parsed ? new Date(parsed) : null;
25734 Roo.data.Field.prototype = {
25742 * Ext JS Library 1.1.1
25743 * Copyright(c) 2006-2007, Ext JS, LLC.
25745 * Originally Released Under LGPL - original licence link has changed is not relivant.
25748 * <script type="text/javascript">
25751 // Base class for reading structured data from a data source. This class is intended to be
25752 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
25755 * @class Roo.data.DataReader
25757 * Base class for reading structured data from a data source. This class is intended to be
25758 * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
25761 Roo.data.DataReader = function(meta, recordType){
25765 this.recordType = recordType instanceof Array ?
25766 Roo.data.Record.create(recordType) : recordType;
25769 Roo.data.DataReader.prototype = {
25772 readerType : 'Data',
25774 * Create an empty record
25775 * @param {Object} data (optional) - overlay some values
25776 * @return {Roo.data.Record} record created.
25778 newRow : function(d) {
25780 this.recordType.prototype.fields.each(function(c) {
25782 case 'int' : da[c.name] = 0; break;
25783 case 'date' : da[c.name] = new Date(); break;
25784 case 'float' : da[c.name] = 0.0; break;
25785 case 'boolean' : da[c.name] = false; break;
25786 default : da[c.name] = ""; break;
25790 return new this.recordType(Roo.apply(da, d));
25796 * Ext JS Library 1.1.1
25797 * Copyright(c) 2006-2007, Ext JS, LLC.
25799 * Originally Released Under LGPL - original licence link has changed is not relivant.
25802 * <script type="text/javascript">
25806 * @class Roo.data.DataProxy
25807 * @extends Roo.util.Observable
25809 * This class is an abstract base class for implementations which provide retrieval of
25810 * unformatted data objects.<br>
25812 * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
25813 * (of the appropriate type which knows how to parse the data object) to provide a block of
25814 * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
25816 * Custom implementations must implement the load method as described in
25817 * {@link Roo.data.HttpProxy#load}.
25819 Roo.data.DataProxy = function(){
25822 * @event beforeload
25823 * Fires before a network request is made to retrieve a data object.
25824 * @param {Object} This DataProxy object.
25825 * @param {Object} params The params parameter to the load function.
25830 * Fires before the load method's callback is called.
25831 * @param {Object} This DataProxy object.
25832 * @param {Object} o The data object.
25833 * @param {Object} arg The callback argument object passed to the load function.
25837 * @event loadexception
25838 * Fires if an Exception occurs during data retrieval.
25839 * @param {Object} This DataProxy object.
25840 * @param {Object} o The data object.
25841 * @param {Object} arg The callback argument object passed to the load function.
25842 * @param {Object} e The Exception.
25844 loadexception : true
25846 Roo.data.DataProxy.superclass.constructor.call(this);
25849 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
25852 * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
25856 * Ext JS Library 1.1.1
25857 * Copyright(c) 2006-2007, Ext JS, LLC.
25859 * Originally Released Under LGPL - original licence link has changed is not relivant.
25862 * <script type="text/javascript">
25865 * @class Roo.data.MemoryProxy
25866 * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
25867 * to the Reader when its load method is called.
25869 * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
25871 Roo.data.MemoryProxy = function(data){
25875 Roo.data.MemoryProxy.superclass.constructor.call(this);
25879 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
25882 * Load data from the requested source (in this case an in-memory
25883 * data object passed to the constructor), read the data object into
25884 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
25885 * process that block using the passed callback.
25886 * @param {Object} params This parameter is not used by the MemoryProxy class.
25887 * @param {Roo.data.DataReader} reader The Reader object which converts the data
25888 * object into a block of Roo.data.Records.
25889 * @param {Function} callback The function into which to pass the block of Roo.data.records.
25890 * The function must be passed <ul>
25891 * <li>The Record block object</li>
25892 * <li>The "arg" argument from the load function</li>
25893 * <li>A boolean success indicator</li>
25895 * @param {Object} scope The scope in which to call the callback
25896 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
25898 load : function(params, reader, callback, scope, arg){
25899 params = params || {};
25902 result = reader.readRecords(params.data ? params.data :this.data);
25904 this.fireEvent("loadexception", this, arg, null, e);
25905 callback.call(scope, null, arg, false);
25908 callback.call(scope, result, arg, true);
25912 update : function(params, records){
25917 * Ext JS Library 1.1.1
25918 * Copyright(c) 2006-2007, Ext JS, LLC.
25920 * Originally Released Under LGPL - original licence link has changed is not relivant.
25923 * <script type="text/javascript">
25926 * @class Roo.data.HttpProxy
25927 * @extends Roo.data.DataProxy
25928 * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
25929 * configured to reference a certain URL.<br><br>
25931 * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
25932 * from which the running page was served.<br><br>
25934 * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
25936 * Be aware that to enable the browser to parse an XML document, the server must set
25937 * the Content-Type header in the HTTP response to "text/xml".
25939 * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
25940 * an {@link Roo.data.Connection} object. If a Connection config is passed, the singleton {@link Roo.Ajax} object
25941 * will be used to make the request.
25943 Roo.data.HttpProxy = function(conn){
25944 Roo.data.HttpProxy.superclass.constructor.call(this);
25945 // is conn a conn config or a real conn?
25947 this.useAjax = !conn || !conn.events;
25951 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
25952 // thse are take from connection...
25955 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
25958 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
25959 * extra parameters to each request made by this object. (defaults to undefined)
25962 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
25963 * to each request made by this object. (defaults to undefined)
25966 * @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)
25969 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
25972 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
25978 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
25982 * Return the {@link Roo.data.Connection} object being used by this Proxy.
25983 * @return {Connection} The Connection object. This object may be used to subscribe to events on
25984 * a finer-grained basis than the DataProxy events.
25986 getConnection : function(){
25987 return this.useAjax ? Roo.Ajax : this.conn;
25991 * Load data from the configured {@link Roo.data.Connection}, read the data object into
25992 * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
25993 * process that block using the passed callback.
25994 * @param {Object} params An object containing properties which are to be used as HTTP parameters
25995 * for the request to the remote server.
25996 * @param {Roo.data.DataReader} reader The Reader object which converts the data
25997 * object into a block of Roo.data.Records.
25998 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
25999 * The function must be passed <ul>
26000 * <li>The Record block object</li>
26001 * <li>The "arg" argument from the load function</li>
26002 * <li>A boolean success indicator</li>
26004 * @param {Object} scope The scope in which to call the callback
26005 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
26007 load : function(params, reader, callback, scope, arg){
26008 if(this.fireEvent("beforeload", this, params) !== false){
26010 params : params || {},
26012 callback : callback,
26017 callback : this.loadResponse,
26021 Roo.applyIf(o, this.conn);
26022 if(this.activeRequest){
26023 Roo.Ajax.abort(this.activeRequest);
26025 this.activeRequest = Roo.Ajax.request(o);
26027 this.conn.request(o);
26030 callback.call(scope||this, null, arg, false);
26035 loadResponse : function(o, success, response){
26036 delete this.activeRequest;
26038 this.fireEvent("loadexception", this, o, response);
26039 o.request.callback.call(o.request.scope, null, o.request.arg, false);
26044 result = o.reader.read(response);
26047 o.raw = { errorMsg : response.responseText };
26048 this.fireEvent("loadexception", this, o, response, e);
26049 o.request.callback.call(o.request.scope, o, o.request.arg, false);
26053 this.fireEvent("load", this, o, o.request.arg);
26054 o.request.callback.call(o.request.scope, result, o.request.arg, true);
26058 update : function(dataSet){
26063 updateResponse : function(dataSet){
26068 * Ext JS Library 1.1.1
26069 * Copyright(c) 2006-2007, Ext JS, LLC.
26071 * Originally Released Under LGPL - original licence link has changed is not relivant.
26074 * <script type="text/javascript">
26078 * @class Roo.data.ScriptTagProxy
26079 * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
26080 * other than the originating domain of the running page.<br><br>
26082 * <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
26083 * of the running page, you must use this class, rather than DataProxy.</em><br><br>
26085 * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
26086 * source code that is used as the source inside a <script> tag.<br><br>
26088 * In order for the browser to process the returned data, the server must wrap the data object
26089 * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
26090 * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
26091 * depending on whether the callback name was passed:
26094 boolean scriptTag = false;
26095 String cb = request.getParameter("callback");
26098 response.setContentType("text/javascript");
26100 response.setContentType("application/x-json");
26102 Writer out = response.getWriter();
26104 out.write(cb + "(");
26106 out.print(dataBlock.toJsonString());
26113 * @param {Object} config A configuration object.
26115 Roo.data.ScriptTagProxy = function(config){
26116 Roo.data.ScriptTagProxy.superclass.constructor.call(this);
26117 Roo.apply(this, config);
26118 this.head = document.getElementsByTagName("head")[0];
26121 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
26123 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
26125 * @cfg {String} url The URL from which to request the data object.
26128 * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
26132 * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
26133 * the server the name of the callback function set up by the load call to process the returned data object.
26134 * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
26135 * javascript output which calls this named function passing the data object as its only parameter.
26137 callbackParam : "callback",
26139 * @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
26140 * name to the request.
26145 * Load data from the configured URL, read the data object into
26146 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
26147 * process that block using the passed callback.
26148 * @param {Object} params An object containing properties which are to be used as HTTP parameters
26149 * for the request to the remote server.
26150 * @param {Roo.data.DataReader} reader The Reader object which converts the data
26151 * object into a block of Roo.data.Records.
26152 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
26153 * The function must be passed <ul>
26154 * <li>The Record block object</li>
26155 * <li>The "arg" argument from the load function</li>
26156 * <li>A boolean success indicator</li>
26158 * @param {Object} scope The scope in which to call the callback
26159 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
26161 load : function(params, reader, callback, scope, arg){
26162 if(this.fireEvent("beforeload", this, params) !== false){
26164 var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
26166 var url = this.url;
26167 url += (url.indexOf("?") != -1 ? "&" : "?") + p;
26169 url += "&_dc=" + (new Date().getTime());
26171 var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
26174 cb : "stcCallback"+transId,
26175 scriptId : "stcScript"+transId,
26179 callback : callback,
26185 window[trans.cb] = function(o){
26186 conn.handleResponse(o, trans);
26189 url += String.format("&{0}={1}", this.callbackParam, trans.cb);
26191 if(this.autoAbort !== false){
26195 trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
26197 var script = document.createElement("script");
26198 script.setAttribute("src", url);
26199 script.setAttribute("type", "text/javascript");
26200 script.setAttribute("id", trans.scriptId);
26201 this.head.appendChild(script);
26203 this.trans = trans;
26205 callback.call(scope||this, null, arg, false);
26210 isLoading : function(){
26211 return this.trans ? true : false;
26215 * Abort the current server request.
26217 abort : function(){
26218 if(this.isLoading()){
26219 this.destroyTrans(this.trans);
26224 destroyTrans : function(trans, isLoaded){
26225 this.head.removeChild(document.getElementById(trans.scriptId));
26226 clearTimeout(trans.timeoutId);
26228 window[trans.cb] = undefined;
26230 delete window[trans.cb];
26233 // if hasn't been loaded, wait for load to remove it to prevent script error
26234 window[trans.cb] = function(){
26235 window[trans.cb] = undefined;
26237 delete window[trans.cb];
26244 handleResponse : function(o, trans){
26245 this.trans = false;
26246 this.destroyTrans(trans, true);
26249 result = trans.reader.readRecords(o);
26251 this.fireEvent("loadexception", this, o, trans.arg, e);
26252 trans.callback.call(trans.scope||window, null, trans.arg, false);
26255 this.fireEvent("load", this, o, trans.arg);
26256 trans.callback.call(trans.scope||window, result, trans.arg, true);
26260 handleFailure : function(trans){
26261 this.trans = false;
26262 this.destroyTrans(trans, false);
26263 this.fireEvent("loadexception", this, null, trans.arg);
26264 trans.callback.call(trans.scope||window, null, trans.arg, false);
26268 * Ext JS Library 1.1.1
26269 * Copyright(c) 2006-2007, Ext JS, LLC.
26271 * Originally Released Under LGPL - original licence link has changed is not relivant.
26274 * <script type="text/javascript">
26278 * @class Roo.data.JsonReader
26279 * @extends Roo.data.DataReader
26280 * Data reader class to create an Array of Roo.data.Record objects from a JSON response
26281 * based on mappings in a provided Roo.data.Record constructor.
26283 * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
26284 * in the reply previously.
26289 var RecordDef = Roo.data.Record.create([
26290 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
26291 {name: 'occupation'} // This field will use "occupation" as the mapping.
26293 var myReader = new Roo.data.JsonReader({
26294 totalProperty: "results", // The property which contains the total dataset size (optional)
26295 root: "rows", // The property which contains an Array of row objects
26296 id: "id" // The property within each row object that provides an ID for the record (optional)
26300 * This would consume a JSON file like this:
26302 { 'results': 2, 'rows': [
26303 { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
26304 { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
26307 * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
26308 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
26309 * paged from the remote server.
26310 * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
26311 * @cfg {String} root name of the property which contains the Array of row objects.
26312 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
26313 * @cfg {Array} fields Array of field definition objects
26315 * Create a new JsonReader
26316 * @param {Object} meta Metadata configuration options
26317 * @param {Object} recordType Either an Array of field definition objects,
26318 * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
26320 Roo.data.JsonReader = function(meta, recordType){
26323 // set some defaults:
26324 Roo.applyIf(meta, {
26325 totalProperty: 'total',
26326 successProperty : 'success',
26331 Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
26333 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
26335 readerType : 'Json',
26338 * @prop {Boolean} metaFromRemote - if the meta data was loaded from the remote source.
26339 * Used by Store query builder to append _requestMeta to params.
26342 metaFromRemote : false,
26344 * This method is only used by a DataProxy which has retrieved data from a remote server.
26345 * @param {Object} response The XHR object which contains the JSON data in its responseText.
26346 * @return {Object} data A data block which is used by an Roo.data.Store object as
26347 * a cache of Roo.data.Records.
26349 read : function(response){
26350 var json = response.responseText;
26352 var o = /* eval:var:o */ eval("("+json+")");
26354 throw {message: "JsonReader.read: Json object not found"};
26360 this.metaFromRemote = true;
26361 this.meta = o.metaData;
26362 this.recordType = Roo.data.Record.create(o.metaData.fields);
26363 this.onMetaChange(this.meta, this.recordType, o);
26365 return this.readRecords(o);
26368 // private function a store will implement
26369 onMetaChange : function(meta, recordType, o){
26376 simpleAccess: function(obj, subsc) {
26383 getJsonAccessor: function(){
26385 return function(expr) {
26387 return(re.test(expr))
26388 ? new Function("obj", "return obj." + expr)
26393 return Roo.emptyFn;
26398 * Create a data block containing Roo.data.Records from an XML document.
26399 * @param {Object} o An object which contains an Array of row objects in the property specified
26400 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
26401 * which contains the total size of the dataset.
26402 * @return {Object} data A data block which is used by an Roo.data.Store object as
26403 * a cache of Roo.data.Records.
26405 readRecords : function(o){
26407 * After any data loads, the raw JSON data is available for further custom processing.
26411 var s = this.meta, Record = this.recordType,
26412 f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
26414 // Generate extraction functions for the totalProperty, the root, the id, and for each field
26416 if(s.totalProperty) {
26417 this.getTotal = this.getJsonAccessor(s.totalProperty);
26419 if(s.successProperty) {
26420 this.getSuccess = this.getJsonAccessor(s.successProperty);
26422 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
26424 var g = this.getJsonAccessor(s.id);
26425 this.getId = function(rec) {
26427 return (r === undefined || r === "") ? null : r;
26430 this.getId = function(){return null;};
26433 for(var jj = 0; jj < fl; jj++){
26435 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
26436 this.ef[jj] = this.getJsonAccessor(map);
26440 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
26441 if(s.totalProperty){
26442 var vt = parseInt(this.getTotal(o), 10);
26447 if(s.successProperty){
26448 var vs = this.getSuccess(o);
26449 if(vs === false || vs === 'false'){
26454 for(var i = 0; i < c; i++){
26457 var id = this.getId(n);
26458 for(var j = 0; j < fl; j++){
26460 var v = this.ef[j](n);
26462 Roo.log('missing convert for ' + f.name);
26466 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
26470 raw : { errorMsg : "JSON Reader Error: fields or metadata not available to create Record" },
26476 var record = new Record(values, id);
26478 records[i] = record;
26484 totalRecords : totalRecords
26487 // used when loading children.. @see loadDataFromChildren
26488 toLoadData: function(rec)
26490 // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
26491 var data = typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
26492 return { data : data, total : data.length };
26497 * Ext JS Library 1.1.1
26498 * Copyright(c) 2006-2007, Ext JS, LLC.
26500 * Originally Released Under LGPL - original licence link has changed is not relivant.
26503 * <script type="text/javascript">
26507 * @class Roo.data.XmlReader
26508 * @extends Roo.data.DataReader
26509 * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
26510 * based on mappings in a provided Roo.data.Record constructor.<br><br>
26512 * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
26513 * header in the HTTP response must be set to "text/xml".</em>
26517 var RecordDef = Roo.data.Record.create([
26518 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
26519 {name: 'occupation'} // This field will use "occupation" as the mapping.
26521 var myReader = new Roo.data.XmlReader({
26522 totalRecords: "results", // The element which contains the total dataset size (optional)
26523 record: "row", // The repeated element which contains row information
26524 id: "id" // The element within the row that provides an ID for the record (optional)
26528 * This would consume an XML file like this:
26532 <results>2</results>
26535 <name>Bill</name>
26536 <occupation>Gardener</occupation>
26540 <name>Ben</name>
26541 <occupation>Horticulturalist</occupation>
26545 * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
26546 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
26547 * paged from the remote server.
26548 * @cfg {String} record The DomQuery path to the repeated element which contains record information.
26549 * @cfg {String} success The DomQuery path to the success attribute used by forms.
26550 * @cfg {String} id The DomQuery path relative from the record element to the element that contains
26551 * a record identifier value.
26553 * Create a new XmlReader
26554 * @param {Object} meta Metadata configuration options
26555 * @param {Mixed} recordType The definition of the data record type to produce. This can be either a valid
26556 * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
26557 * Roo.data.Record.create. See the {@link Roo.data.Record} class for more details.
26559 Roo.data.XmlReader = function(meta, recordType){
26561 Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
26563 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
26565 readerType : 'Xml',
26568 * This method is only used by a DataProxy which has retrieved data from a remote server.
26569 * @param {Object} response The XHR object which contains the parsed XML document. The response is expected
26570 * to contain a method called 'responseXML' that returns an XML document object.
26571 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
26572 * a cache of Roo.data.Records.
26574 read : function(response){
26575 var doc = response.responseXML;
26577 throw {message: "XmlReader.read: XML Document not available"};
26579 return this.readRecords(doc);
26583 * Create a data block containing Roo.data.Records from an XML document.
26584 * @param {Object} doc A parsed XML document.
26585 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
26586 * a cache of Roo.data.Records.
26588 readRecords : function(doc){
26590 * After any data loads/reads, the raw XML Document is available for further custom processing.
26591 * @type XMLDocument
26593 this.xmlData = doc;
26594 var root = doc.documentElement || doc;
26595 var q = Roo.DomQuery;
26596 var recordType = this.recordType, fields = recordType.prototype.fields;
26597 var sid = this.meta.id;
26598 var totalRecords = 0, success = true;
26599 if(this.meta.totalRecords){
26600 totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
26603 if(this.meta.success){
26604 var sv = q.selectValue(this.meta.success, root, true);
26605 success = sv !== false && sv !== 'false';
26608 var ns = q.select(this.meta.record, root);
26609 for(var i = 0, len = ns.length; i < len; i++) {
26612 var id = sid ? q.selectValue(sid, n) : undefined;
26613 for(var j = 0, jlen = fields.length; j < jlen; j++){
26614 var f = fields.items[j];
26615 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
26617 values[f.name] = v;
26619 var record = new recordType(values, id);
26621 records[records.length] = record;
26627 totalRecords : totalRecords || records.length
26632 * Ext JS Library 1.1.1
26633 * Copyright(c) 2006-2007, Ext JS, LLC.
26635 * Originally Released Under LGPL - original licence link has changed is not relivant.
26638 * <script type="text/javascript">
26642 * @class Roo.data.ArrayReader
26643 * @extends Roo.data.DataReader
26644 * Data reader class to create an Array of Roo.data.Record objects from an Array.
26645 * Each element of that Array represents a row of data fields. The
26646 * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
26647 * of the field definition if it exists, or the field's ordinal position in the definition.<br>
26651 var RecordDef = Roo.data.Record.create([
26652 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
26653 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
26655 var myReader = new Roo.data.ArrayReader({
26656 id: 0 // The subscript within row Array that provides an ID for the Record (optional)
26660 * This would consume an Array like this:
26662 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
26666 * Create a new JsonReader
26667 * @param {Object} meta Metadata configuration options.
26668 * @param {Object|Array} recordType Either an Array of field definition objects
26670 * @cfg {Array} fields Array of field definition objects
26671 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
26672 * as specified to {@link Roo.data.Record#create},
26673 * or an {@link Roo.data.Record} object
26676 * created using {@link Roo.data.Record#create}.
26678 Roo.data.ArrayReader = function(meta, recordType)
26680 Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
26683 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
26686 * Create a data block containing Roo.data.Records from an XML document.
26687 * @param {Object} o An Array of row objects which represents the dataset.
26688 * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
26689 * a cache of Roo.data.Records.
26691 readRecords : function(o)
26693 var sid = this.meta ? this.meta.id : null;
26694 var recordType = this.recordType, fields = recordType.prototype.fields;
26697 for(var i = 0; i < root.length; i++){
26700 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
26701 for(var j = 0, jlen = fields.length; j < jlen; j++){
26702 var f = fields.items[j];
26703 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
26704 var v = n[k] !== undefined ? n[k] : f.defaultValue;
26706 values[f.name] = v;
26708 var record = new recordType(values, id);
26710 records[records.length] = record;
26714 totalRecords : records.length
26717 // used when loading children.. @see loadDataFromChildren
26718 toLoadData: function(rec)
26720 // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
26721 return typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
26728 * Ext JS Library 1.1.1
26729 * Copyright(c) 2006-2007, Ext JS, LLC.
26731 * Originally Released Under LGPL - original licence link has changed is not relivant.
26734 * <script type="text/javascript">
26739 * @class Roo.data.Tree
26740 * @extends Roo.util.Observable
26741 * Represents a tree data structure and bubbles all the events for its nodes. The nodes
26742 * in the tree have most standard DOM functionality.
26744 * @param {Node} root (optional) The root node
26746 Roo.data.Tree = function(root){
26747 this.nodeHash = {};
26749 * The root node for this tree
26754 this.setRootNode(root);
26759 * Fires when a new child node is appended to a node in this tree.
26760 * @param {Tree} tree The owner tree
26761 * @param {Node} parent The parent node
26762 * @param {Node} node The newly appended node
26763 * @param {Number} index The index of the newly appended node
26768 * Fires when a child node is removed from a node in this tree.
26769 * @param {Tree} tree The owner tree
26770 * @param {Node} parent The parent node
26771 * @param {Node} node The child node removed
26776 * Fires when a node is moved to a new location in the tree
26777 * @param {Tree} tree The owner tree
26778 * @param {Node} node The node moved
26779 * @param {Node} oldParent The old parent of this node
26780 * @param {Node} newParent The new parent of this node
26781 * @param {Number} index The index it was moved to
26786 * Fires when a new child node is inserted in a node in this tree.
26787 * @param {Tree} tree The owner tree
26788 * @param {Node} parent The parent node
26789 * @param {Node} node The child node inserted
26790 * @param {Node} refNode The child node the node was inserted before
26794 * @event beforeappend
26795 * Fires before a new child is appended to a node in this tree, return false to cancel the append.
26796 * @param {Tree} tree The owner tree
26797 * @param {Node} parent The parent node
26798 * @param {Node} node The child node to be appended
26800 "beforeappend" : true,
26802 * @event beforeremove
26803 * Fires before a child is removed from a node in this tree, return false to cancel the remove.
26804 * @param {Tree} tree The owner tree
26805 * @param {Node} parent The parent node
26806 * @param {Node} node The child node to be removed
26808 "beforeremove" : true,
26810 * @event beforemove
26811 * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
26812 * @param {Tree} tree The owner tree
26813 * @param {Node} node The node being moved
26814 * @param {Node} oldParent The parent of the node
26815 * @param {Node} newParent The new parent the node is moving to
26816 * @param {Number} index The index it is being moved to
26818 "beforemove" : true,
26820 * @event beforeinsert
26821 * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
26822 * @param {Tree} tree The owner tree
26823 * @param {Node} parent The parent node
26824 * @param {Node} node The child node to be inserted
26825 * @param {Node} refNode The child node the node is being inserted before
26827 "beforeinsert" : true
26830 Roo.data.Tree.superclass.constructor.call(this);
26833 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
26834 pathSeparator: "/",
26836 proxyNodeEvent : function(){
26837 return this.fireEvent.apply(this, arguments);
26841 * Returns the root node for this tree.
26844 getRootNode : function(){
26849 * Sets the root node for this tree.
26850 * @param {Node} node
26853 setRootNode : function(node){
26855 node.ownerTree = this;
26856 node.isRoot = true;
26857 this.registerNode(node);
26862 * Gets a node in this tree by its id.
26863 * @param {String} id
26866 getNodeById : function(id){
26867 return this.nodeHash[id];
26870 registerNode : function(node){
26871 this.nodeHash[node.id] = node;
26874 unregisterNode : function(node){
26875 delete this.nodeHash[node.id];
26878 toString : function(){
26879 return "[Tree"+(this.id?" "+this.id:"")+"]";
26884 * @class Roo.data.Node
26885 * @extends Roo.util.Observable
26886 * @cfg {Boolean} leaf true if this node is a leaf and does not have children
26887 * @cfg {String} id The id for this node. If one is not specified, one is generated.
26889 * @param {Object} attributes The attributes/config for the node
26891 Roo.data.Node = function(attributes){
26893 * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
26896 this.attributes = attributes || {};
26897 this.leaf = this.attributes.leaf;
26899 * The node id. @type String
26901 this.id = this.attributes.id;
26903 this.id = Roo.id(null, "ynode-");
26904 this.attributes.id = this.id;
26909 * All child nodes of this node. @type Array
26911 this.childNodes = [];
26912 if(!this.childNodes.indexOf){ // indexOf is a must
26913 this.childNodes.indexOf = function(o){
26914 for(var i = 0, len = this.length; i < len; i++){
26923 * The parent node for this node. @type Node
26925 this.parentNode = null;
26927 * The first direct child node of this node, or null if this node has no child nodes. @type Node
26929 this.firstChild = null;
26931 * The last direct child node of this node, or null if this node has no child nodes. @type Node
26933 this.lastChild = null;
26935 * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
26937 this.previousSibling = null;
26939 * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
26941 this.nextSibling = null;
26946 * Fires when a new child node is appended
26947 * @param {Tree} tree The owner tree
26948 * @param {Node} this This node
26949 * @param {Node} node The newly appended node
26950 * @param {Number} index The index of the newly appended node
26955 * Fires when a child node is removed
26956 * @param {Tree} tree The owner tree
26957 * @param {Node} this This node
26958 * @param {Node} node The removed node
26963 * Fires when this node is moved to a new location in the tree
26964 * @param {Tree} tree The owner tree
26965 * @param {Node} this This node
26966 * @param {Node} oldParent The old parent of this node
26967 * @param {Node} newParent The new parent of this node
26968 * @param {Number} index The index it was moved to
26973 * Fires when a new child node is inserted.
26974 * @param {Tree} tree The owner tree
26975 * @param {Node} this This node
26976 * @param {Node} node The child node inserted
26977 * @param {Node} refNode The child node the node was inserted before
26981 * @event beforeappend
26982 * Fires before a new child is appended, return false to cancel the append.
26983 * @param {Tree} tree The owner tree
26984 * @param {Node} this This node
26985 * @param {Node} node The child node to be appended
26987 "beforeappend" : true,
26989 * @event beforeremove
26990 * Fires before a child is removed, return false to cancel the remove.
26991 * @param {Tree} tree The owner tree
26992 * @param {Node} this This node
26993 * @param {Node} node The child node to be removed
26995 "beforeremove" : true,
26997 * @event beforemove
26998 * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
26999 * @param {Tree} tree The owner tree
27000 * @param {Node} this This node
27001 * @param {Node} oldParent The parent of this node
27002 * @param {Node} newParent The new parent this node is moving to
27003 * @param {Number} index The index it is being moved to
27005 "beforemove" : true,
27007 * @event beforeinsert
27008 * Fires before a new child is inserted, return false to cancel the insert.
27009 * @param {Tree} tree The owner tree
27010 * @param {Node} this This node
27011 * @param {Node} node The child node to be inserted
27012 * @param {Node} refNode The child node the node is being inserted before
27014 "beforeinsert" : true
27016 this.listeners = this.attributes.listeners;
27017 Roo.data.Node.superclass.constructor.call(this);
27020 Roo.extend(Roo.data.Node, Roo.util.Observable, {
27021 fireEvent : function(evtName){
27022 // first do standard event for this node
27023 if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
27026 // then bubble it up to the tree if the event wasn't cancelled
27027 var ot = this.getOwnerTree();
27029 if(ot.proxyNodeEvent.apply(ot, arguments) === false){
27037 * Returns true if this node is a leaf
27038 * @return {Boolean}
27040 isLeaf : function(){
27041 return this.leaf === true;
27045 setFirstChild : function(node){
27046 this.firstChild = node;
27050 setLastChild : function(node){
27051 this.lastChild = node;
27056 * Returns true if this node is the last child of its parent
27057 * @return {Boolean}
27059 isLast : function(){
27060 return (!this.parentNode ? true : this.parentNode.lastChild == this);
27064 * Returns true if this node is the first child of its parent
27065 * @return {Boolean}
27067 isFirst : function(){
27068 return (!this.parentNode ? true : this.parentNode.firstChild == this);
27071 hasChildNodes : function(){
27072 return !this.isLeaf() && this.childNodes.length > 0;
27076 * Insert node(s) as the last child node of this node.
27077 * @param {Node/Array} node The node or Array of nodes to append
27078 * @return {Node} The appended node if single append, or null if an array was passed
27080 appendChild : function(node){
27082 if(node instanceof Array){
27084 }else if(arguments.length > 1){
27088 // if passed an array or multiple args do them one by one
27090 for(var i = 0, len = multi.length; i < len; i++) {
27091 this.appendChild(multi[i]);
27094 if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
27097 var index = this.childNodes.length;
27098 var oldParent = node.parentNode;
27099 // it's a move, make sure we move it cleanly
27101 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
27104 oldParent.removeChild(node);
27107 index = this.childNodes.length;
27109 this.setFirstChild(node);
27111 this.childNodes.push(node);
27112 node.parentNode = this;
27113 var ps = this.childNodes[index-1];
27115 node.previousSibling = ps;
27116 ps.nextSibling = node;
27118 node.previousSibling = null;
27120 node.nextSibling = null;
27121 this.setLastChild(node);
27122 node.setOwnerTree(this.getOwnerTree());
27123 this.fireEvent("append", this.ownerTree, this, node, index);
27124 if(this.ownerTree) {
27125 this.ownerTree.fireEvent("appendnode", this, node, index);
27128 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
27135 * Removes a child node from this node.
27136 * @param {Node} node The node to remove
27137 * @return {Node} The removed node
27139 removeChild : function(node){
27140 var index = this.childNodes.indexOf(node);
27144 if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
27148 // remove it from childNodes collection
27149 this.childNodes.splice(index, 1);
27152 if(node.previousSibling){
27153 node.previousSibling.nextSibling = node.nextSibling;
27155 if(node.nextSibling){
27156 node.nextSibling.previousSibling = node.previousSibling;
27159 // update child refs
27160 if(this.firstChild == node){
27161 this.setFirstChild(node.nextSibling);
27163 if(this.lastChild == node){
27164 this.setLastChild(node.previousSibling);
27167 node.setOwnerTree(null);
27168 // clear any references from the node
27169 node.parentNode = null;
27170 node.previousSibling = null;
27171 node.nextSibling = null;
27172 this.fireEvent("remove", this.ownerTree, this, node);
27177 * Inserts the first node before the second node in this nodes childNodes collection.
27178 * @param {Node} node The node to insert
27179 * @param {Node} refNode The node to insert before (if null the node is appended)
27180 * @return {Node} The inserted node
27182 insertBefore : function(node, refNode){
27183 if(!refNode){ // like standard Dom, refNode can be null for append
27184 return this.appendChild(node);
27187 if(node == refNode){
27191 if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
27194 var index = this.childNodes.indexOf(refNode);
27195 var oldParent = node.parentNode;
27196 var refIndex = index;
27198 // when moving internally, indexes will change after remove
27199 if(oldParent == this && this.childNodes.indexOf(node) < index){
27203 // it's a move, make sure we move it cleanly
27205 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
27208 oldParent.removeChild(node);
27211 this.setFirstChild(node);
27213 this.childNodes.splice(refIndex, 0, node);
27214 node.parentNode = this;
27215 var ps = this.childNodes[refIndex-1];
27217 node.previousSibling = ps;
27218 ps.nextSibling = node;
27220 node.previousSibling = null;
27222 node.nextSibling = refNode;
27223 refNode.previousSibling = node;
27224 node.setOwnerTree(this.getOwnerTree());
27225 this.fireEvent("insert", this.ownerTree, this, node, refNode);
27227 node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
27233 * Returns the child node at the specified index.
27234 * @param {Number} index
27237 item : function(index){
27238 return this.childNodes[index];
27242 * Replaces one child node in this node with another.
27243 * @param {Node} newChild The replacement node
27244 * @param {Node} oldChild The node to replace
27245 * @return {Node} The replaced node
27247 replaceChild : function(newChild, oldChild){
27248 this.insertBefore(newChild, oldChild);
27249 this.removeChild(oldChild);
27254 * Returns the index of a child node
27255 * @param {Node} node
27256 * @return {Number} The index of the node or -1 if it was not found
27258 indexOf : function(child){
27259 return this.childNodes.indexOf(child);
27263 * Returns the tree this node is in.
27266 getOwnerTree : function(){
27267 // if it doesn't have one, look for one
27268 if(!this.ownerTree){
27272 this.ownerTree = p.ownerTree;
27278 return this.ownerTree;
27282 * Returns depth of this node (the root node has a depth of 0)
27285 getDepth : function(){
27288 while(p.parentNode){
27296 setOwnerTree : function(tree){
27297 // if it's move, we need to update everyone
27298 if(tree != this.ownerTree){
27299 if(this.ownerTree){
27300 this.ownerTree.unregisterNode(this);
27302 this.ownerTree = tree;
27303 var cs = this.childNodes;
27304 for(var i = 0, len = cs.length; i < len; i++) {
27305 cs[i].setOwnerTree(tree);
27308 tree.registerNode(this);
27314 * Returns the path for this node. The path can be used to expand or select this node programmatically.
27315 * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
27316 * @return {String} The path
27318 getPath : function(attr){
27319 attr = attr || "id";
27320 var p = this.parentNode;
27321 var b = [this.attributes[attr]];
27323 b.unshift(p.attributes[attr]);
27326 var sep = this.getOwnerTree().pathSeparator;
27327 return sep + b.join(sep);
27331 * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
27332 * function call will be the scope provided or the current node. The arguments to the function
27333 * will be the args provided or the current node. If the function returns false at any point,
27334 * the bubble is stopped.
27335 * @param {Function} fn The function to call
27336 * @param {Object} scope (optional) The scope of the function (defaults to current node)
27337 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
27339 bubble : function(fn, scope, args){
27342 if(fn.call(scope || p, args || p) === false){
27350 * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
27351 * function call will be the scope provided or the current node. The arguments to the function
27352 * will be the args provided or the current node. If the function returns false at any point,
27353 * the cascade is stopped on that branch.
27354 * @param {Function} fn The function to call
27355 * @param {Object} scope (optional) The scope of the function (defaults to current node)
27356 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
27358 cascade : function(fn, scope, args){
27359 if(fn.call(scope || this, args || this) !== false){
27360 var cs = this.childNodes;
27361 for(var i = 0, len = cs.length; i < len; i++) {
27362 cs[i].cascade(fn, scope, args);
27368 * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
27369 * function call will be the scope provided or the current node. The arguments to the function
27370 * will be the args provided or the current node. If the function returns false at any point,
27371 * the iteration stops.
27372 * @param {Function} fn The function to call
27373 * @param {Object} scope (optional) The scope of the function (defaults to current node)
27374 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
27376 eachChild : function(fn, scope, args){
27377 var cs = this.childNodes;
27378 for(var i = 0, len = cs.length; i < len; i++) {
27379 if(fn.call(scope || this, args || cs[i]) === false){
27386 * Finds the first child that has the attribute with the specified value.
27387 * @param {String} attribute The attribute name
27388 * @param {Mixed} value The value to search for
27389 * @return {Node} The found child or null if none was found
27391 findChild : function(attribute, value){
27392 var cs = this.childNodes;
27393 for(var i = 0, len = cs.length; i < len; i++) {
27394 if(cs[i].attributes[attribute] == value){
27402 * Finds the first child by a custom function. The child matches if the function passed
27404 * @param {Function} fn
27405 * @param {Object} scope (optional)
27406 * @return {Node} The found child or null if none was found
27408 findChildBy : function(fn, scope){
27409 var cs = this.childNodes;
27410 for(var i = 0, len = cs.length; i < len; i++) {
27411 if(fn.call(scope||cs[i], cs[i]) === true){
27419 * Sorts this nodes children using the supplied sort function
27420 * @param {Function} fn
27421 * @param {Object} scope (optional)
27423 sort : function(fn, scope){
27424 var cs = this.childNodes;
27425 var len = cs.length;
27427 var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
27429 for(var i = 0; i < len; i++){
27431 n.previousSibling = cs[i-1];
27432 n.nextSibling = cs[i+1];
27434 this.setFirstChild(n);
27437 this.setLastChild(n);
27444 * Returns true if this node is an ancestor (at any point) of the passed node.
27445 * @param {Node} node
27446 * @return {Boolean}
27448 contains : function(node){
27449 return node.isAncestor(this);
27453 * Returns true if the passed node is an ancestor (at any point) of this node.
27454 * @param {Node} node
27455 * @return {Boolean}
27457 isAncestor : function(node){
27458 var p = this.parentNode;
27468 toString : function(){
27469 return "[Node"+(this.id?" "+this.id:"")+"]";
27473 * Ext JS Library 1.1.1
27474 * Copyright(c) 2006-2007, Ext JS, LLC.
27476 * Originally Released Under LGPL - original licence link has changed is not relivant.
27479 * <script type="text/javascript">
27484 * @class Roo.Shadow
27485 * Simple class that can provide a shadow effect for any element. Note that the element MUST be absolutely positioned,
27486 * and the shadow does not provide any shimming. This should be used only in simple cases -- for more advanced
27487 * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
27489 * Create a new Shadow
27490 * @param {Object} config The config object
27492 Roo.Shadow = function(config){
27493 Roo.apply(this, config);
27494 if(typeof this.mode != "string"){
27495 this.mode = this.defaultMode;
27497 var o = this.offset, a = {h: 0};
27498 var rad = Math.floor(this.offset/2);
27499 switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
27505 a.l -= this.offset + rad;
27506 a.t -= this.offset + rad;
27517 a.l -= (this.offset - rad);
27518 a.t -= this.offset + rad;
27520 a.w -= (this.offset - rad)*2;
27531 a.l -= (this.offset - rad);
27532 a.t -= (this.offset - rad);
27534 a.w -= (this.offset + rad + 1);
27535 a.h -= (this.offset + rad);
27544 Roo.Shadow.prototype = {
27546 * @cfg {String} mode
27547 * The shadow display mode. Supports the following options:<br />
27548 * sides: Shadow displays on both sides and bottom only<br />
27549 * frame: Shadow displays equally on all four sides<br />
27550 * drop: Traditional bottom-right drop shadow (default)
27554 * @cfg {String} offset
27555 * The number of pixels to offset the shadow from the element (defaults to 4)
27560 defaultMode: "drop",
27563 * Displays the shadow under the target element
27564 * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
27566 show : function(target){
27567 target = Roo.get(target);
27569 this.el = Roo.Shadow.Pool.pull();
27570 if(this.el.dom.nextSibling != target.dom){
27571 this.el.insertBefore(target);
27574 this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
27576 this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
27579 target.getLeft(true),
27580 target.getTop(true),
27584 this.el.dom.style.display = "block";
27588 * Returns true if the shadow is visible, else false
27590 isVisible : function(){
27591 return this.el ? true : false;
27595 * Direct alignment when values are already available. Show must be called at least once before
27596 * calling this method to ensure it is initialized.
27597 * @param {Number} left The target element left position
27598 * @param {Number} top The target element top position
27599 * @param {Number} width The target element width
27600 * @param {Number} height The target element height
27602 realign : function(l, t, w, h){
27606 var a = this.adjusts, d = this.el.dom, s = d.style;
27608 s.left = (l+a.l)+"px";
27609 s.top = (t+a.t)+"px";
27610 var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
27612 if(s.width != sws || s.height != shs){
27616 var cn = d.childNodes;
27617 var sww = Math.max(0, (sw-12))+"px";
27618 cn[0].childNodes[1].style.width = sww;
27619 cn[1].childNodes[1].style.width = sww;
27620 cn[2].childNodes[1].style.width = sww;
27621 cn[1].style.height = Math.max(0, (sh-12))+"px";
27627 * Hides this shadow
27631 this.el.dom.style.display = "none";
27632 Roo.Shadow.Pool.push(this.el);
27638 * Adjust the z-index of this shadow
27639 * @param {Number} zindex The new z-index
27641 setZIndex : function(z){
27644 this.el.setStyle("z-index", z);
27649 // Private utility class that manages the internal Shadow cache
27650 Roo.Shadow.Pool = function(){
27652 var markup = Roo.isIE ?
27653 '<div class="x-ie-shadow"></div>' :
27654 '<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>';
27657 var sh = p.shift();
27659 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
27660 sh.autoBoxAdjust = false;
27665 push : function(sh){
27671 * Ext JS Library 1.1.1
27672 * Copyright(c) 2006-2007, Ext JS, LLC.
27674 * Originally Released Under LGPL - original licence link has changed is not relivant.
27677 * <script type="text/javascript">
27682 * @class Roo.SplitBar
27683 * @extends Roo.util.Observable
27684 * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
27688 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
27689 Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
27690 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
27691 split.minSize = 100;
27692 split.maxSize = 600;
27693 split.animate = true;
27694 split.on('moved', splitterMoved);
27697 * Create a new SplitBar
27698 * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar.
27699 * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged
27700 * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
27701 * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or
27702 Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
27703 position of the SplitBar).
27705 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
27708 this.el = Roo.get(dragElement, true);
27709 this.el.dom.unselectable = "on";
27711 this.resizingEl = Roo.get(resizingElement, true);
27715 * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
27716 * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
27719 this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
27722 * The minimum size of the resizing element. (Defaults to 0)
27728 * The maximum size of the resizing element. (Defaults to 2000)
27731 this.maxSize = 2000;
27734 * Whether to animate the transition to the new size
27737 this.animate = false;
27740 * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
27743 this.useShim = false;
27748 if(!existingProxy){
27750 this.proxy = Roo.SplitBar.createProxy(this.orientation);
27752 this.proxy = Roo.get(existingProxy).dom;
27755 this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
27758 this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
27761 this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
27764 this.dragSpecs = {};
27767 * @private The adapter to use to positon and resize elements
27769 this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
27770 this.adapter.init(this);
27772 if(this.orientation == Roo.SplitBar.HORIZONTAL){
27774 this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
27775 this.el.addClass("x-splitbar-h");
27778 this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
27779 this.el.addClass("x-splitbar-v");
27785 * Fires when the splitter is moved (alias for {@link #event-moved})
27786 * @param {Roo.SplitBar} this
27787 * @param {Number} newSize the new width or height
27792 * Fires when the splitter is moved
27793 * @param {Roo.SplitBar} this
27794 * @param {Number} newSize the new width or height
27798 * @event beforeresize
27799 * Fires before the splitter is dragged
27800 * @param {Roo.SplitBar} this
27802 "beforeresize" : true,
27804 "beforeapply" : true
27807 Roo.util.Observable.call(this);
27810 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
27811 onStartProxyDrag : function(x, y){
27812 this.fireEvent("beforeresize", this);
27814 var o = Roo.DomHelper.insertFirst(document.body, {cls: "x-drag-overlay", html: " "}, true);
27816 o.enableDisplayMode("block");
27817 // all splitbars share the same overlay
27818 Roo.SplitBar.prototype.overlay = o;
27820 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
27821 this.overlay.show();
27822 Roo.get(this.proxy).setDisplayed("block");
27823 var size = this.adapter.getElementSize(this);
27824 this.activeMinSize = this.getMinimumSize();;
27825 this.activeMaxSize = this.getMaximumSize();;
27826 var c1 = size - this.activeMinSize;
27827 var c2 = Math.max(this.activeMaxSize - size, 0);
27828 if(this.orientation == Roo.SplitBar.HORIZONTAL){
27829 this.dd.resetConstraints();
27830 this.dd.setXConstraint(
27831 this.placement == Roo.SplitBar.LEFT ? c1 : c2,
27832 this.placement == Roo.SplitBar.LEFT ? c2 : c1
27834 this.dd.setYConstraint(0, 0);
27836 this.dd.resetConstraints();
27837 this.dd.setXConstraint(0, 0);
27838 this.dd.setYConstraint(
27839 this.placement == Roo.SplitBar.TOP ? c1 : c2,
27840 this.placement == Roo.SplitBar.TOP ? c2 : c1
27843 this.dragSpecs.startSize = size;
27844 this.dragSpecs.startPoint = [x, y];
27845 Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
27849 * @private Called after the drag operation by the DDProxy
27851 onEndProxyDrag : function(e){
27852 Roo.get(this.proxy).setDisplayed(false);
27853 var endPoint = Roo.lib.Event.getXY(e);
27855 this.overlay.hide();
27858 if(this.orientation == Roo.SplitBar.HORIZONTAL){
27859 newSize = this.dragSpecs.startSize +
27860 (this.placement == Roo.SplitBar.LEFT ?
27861 endPoint[0] - this.dragSpecs.startPoint[0] :
27862 this.dragSpecs.startPoint[0] - endPoint[0]
27865 newSize = this.dragSpecs.startSize +
27866 (this.placement == Roo.SplitBar.TOP ?
27867 endPoint[1] - this.dragSpecs.startPoint[1] :
27868 this.dragSpecs.startPoint[1] - endPoint[1]
27871 newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
27872 if(newSize != this.dragSpecs.startSize){
27873 if(this.fireEvent('beforeapply', this, newSize) !== false){
27874 this.adapter.setElementSize(this, newSize);
27875 this.fireEvent("moved", this, newSize);
27876 this.fireEvent("resize", this, newSize);
27882 * Get the adapter this SplitBar uses
27883 * @return The adapter object
27885 getAdapter : function(){
27886 return this.adapter;
27890 * Set the adapter this SplitBar uses
27891 * @param {Object} adapter A SplitBar adapter object
27893 setAdapter : function(adapter){
27894 this.adapter = adapter;
27895 this.adapter.init(this);
27899 * Gets the minimum size for the resizing element
27900 * @return {Number} The minimum size
27902 getMinimumSize : function(){
27903 return this.minSize;
27907 * Sets the minimum size for the resizing element
27908 * @param {Number} minSize The minimum size
27910 setMinimumSize : function(minSize){
27911 this.minSize = minSize;
27915 * Gets the maximum size for the resizing element
27916 * @return {Number} The maximum size
27918 getMaximumSize : function(){
27919 return this.maxSize;
27923 * Sets the maximum size for the resizing element
27924 * @param {Number} maxSize The maximum size
27926 setMaximumSize : function(maxSize){
27927 this.maxSize = maxSize;
27931 * Sets the initialize size for the resizing element
27932 * @param {Number} size The initial size
27934 setCurrentSize : function(size){
27935 var oldAnimate = this.animate;
27936 this.animate = false;
27937 this.adapter.setElementSize(this, size);
27938 this.animate = oldAnimate;
27942 * Destroy this splitbar.
27943 * @param {Boolean} removeEl True to remove the element
27945 destroy : function(removeEl){
27947 this.shim.remove();
27950 this.proxy.parentNode.removeChild(this.proxy);
27958 * @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.
27960 Roo.SplitBar.createProxy = function(dir){
27961 var proxy = new Roo.Element(document.createElement("div"));
27962 proxy.unselectable();
27963 var cls = 'x-splitbar-proxy';
27964 proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
27965 document.body.appendChild(proxy.dom);
27970 * @class Roo.SplitBar.BasicLayoutAdapter
27971 * Default Adapter. It assumes the splitter and resizing element are not positioned
27972 * elements and only gets/sets the width of the element. Generally used for table based layouts.
27974 Roo.SplitBar.BasicLayoutAdapter = function(){
27977 Roo.SplitBar.BasicLayoutAdapter.prototype = {
27978 // do nothing for now
27979 init : function(s){
27983 * Called before drag operations to get the current size of the resizing element.
27984 * @param {Roo.SplitBar} s The SplitBar using this adapter
27986 getElementSize : function(s){
27987 if(s.orientation == Roo.SplitBar.HORIZONTAL){
27988 return s.resizingEl.getWidth();
27990 return s.resizingEl.getHeight();
27995 * Called after drag operations to set the size of the resizing element.
27996 * @param {Roo.SplitBar} s The SplitBar using this adapter
27997 * @param {Number} newSize The new size to set
27998 * @param {Function} onComplete A function to be invoked when resizing is complete
28000 setElementSize : function(s, newSize, onComplete){
28001 if(s.orientation == Roo.SplitBar.HORIZONTAL){
28003 s.resizingEl.setWidth(newSize);
28005 onComplete(s, newSize);
28008 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
28013 s.resizingEl.setHeight(newSize);
28015 onComplete(s, newSize);
28018 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
28025 *@class Roo.SplitBar.AbsoluteLayoutAdapter
28026 * @extends Roo.SplitBar.BasicLayoutAdapter
28027 * Adapter that moves the splitter element to align with the resized sizing element.
28028 * Used with an absolute positioned SplitBar.
28029 * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
28030 * document.body, make sure you assign an id to the body element.
28032 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
28033 this.basic = new Roo.SplitBar.BasicLayoutAdapter();
28034 this.container = Roo.get(container);
28037 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
28038 init : function(s){
28039 this.basic.init(s);
28042 getElementSize : function(s){
28043 return this.basic.getElementSize(s);
28046 setElementSize : function(s, newSize, onComplete){
28047 this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
28050 moveSplitter : function(s){
28051 var yes = Roo.SplitBar;
28052 switch(s.placement){
28054 s.el.setX(s.resizingEl.getRight());
28057 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
28060 s.el.setY(s.resizingEl.getBottom());
28063 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
28070 * Orientation constant - Create a vertical SplitBar
28074 Roo.SplitBar.VERTICAL = 1;
28077 * Orientation constant - Create a horizontal SplitBar
28081 Roo.SplitBar.HORIZONTAL = 2;
28084 * Placement constant - The resizing element is to the left of the splitter element
28088 Roo.SplitBar.LEFT = 1;
28091 * Placement constant - The resizing element is to the right of the splitter element
28095 Roo.SplitBar.RIGHT = 2;
28098 * Placement constant - The resizing element is positioned above the splitter element
28102 Roo.SplitBar.TOP = 3;
28105 * Placement constant - The resizing element is positioned under splitter element
28109 Roo.SplitBar.BOTTOM = 4;
28112 * Ext JS Library 1.1.1
28113 * Copyright(c) 2006-2007, Ext JS, LLC.
28115 * Originally Released Under LGPL - original licence link has changed is not relivant.
28118 * <script type="text/javascript">
28123 * @extends Roo.util.Observable
28124 * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template.
28125 * This class also supports single and multi selection modes. <br>
28126 * Create a data model bound view:
28128 var store = new Roo.data.Store(...);
28130 var view = new Roo.View({
28132 tpl : '<div id="{0}">{2} - {1}</div>', // auto create template
28134 singleSelect: true,
28135 selectedClass: "ydataview-selected",
28139 // listen for node click?
28140 view.on("click", function(vw, index, node, e){
28141 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
28145 dataModel.load("foobar.xml");
28147 For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
28149 * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
28150 * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
28152 * Note: old style constructor is still suported (container, template, config)
28155 * Create a new View
28156 * @param {Object} config The config object
28159 Roo.View = function(config, depreciated_tpl, depreciated_config){
28161 this.parent = false;
28163 if (typeof(depreciated_tpl) == 'undefined') {
28164 // new way.. - universal constructor.
28165 Roo.apply(this, config);
28166 this.el = Roo.get(this.el);
28169 this.el = Roo.get(config);
28170 this.tpl = depreciated_tpl;
28171 Roo.apply(this, depreciated_config);
28173 this.wrapEl = this.el.wrap().wrap();
28174 ///this.el = this.wrapEla.appendChild(document.createElement("div"));
28177 if(typeof(this.tpl) == "string"){
28178 this.tpl = new Roo.Template(this.tpl);
28180 // support xtype ctors..
28181 this.tpl = new Roo.factory(this.tpl, Roo);
28185 this.tpl.compile();
28190 * @event beforeclick
28191 * Fires before a click is processed. Returns false to cancel the default action.
28192 * @param {Roo.View} this
28193 * @param {Number} index The index of the target node
28194 * @param {HTMLElement} node The target node
28195 * @param {Roo.EventObject} e The raw event object
28197 "beforeclick" : true,
28200 * Fires when a template node is clicked.
28201 * @param {Roo.View} this
28202 * @param {Number} index The index of the target node
28203 * @param {HTMLElement} node The target node
28204 * @param {Roo.EventObject} e The raw event object
28209 * Fires when a template node is double clicked.
28210 * @param {Roo.View} this
28211 * @param {Number} index The index of the target node
28212 * @param {HTMLElement} node The target node
28213 * @param {Roo.EventObject} e The raw event object
28217 * @event contextmenu
28218 * Fires when a template node is right clicked.
28219 * @param {Roo.View} this
28220 * @param {Number} index The index of the target node
28221 * @param {HTMLElement} node The target node
28222 * @param {Roo.EventObject} e The raw event object
28224 "contextmenu" : true,
28226 * @event selectionchange
28227 * Fires when the selected nodes change.
28228 * @param {Roo.View} this
28229 * @param {Array} selections Array of the selected nodes
28231 "selectionchange" : true,
28234 * @event beforeselect
28235 * Fires before a selection is made. If any handlers return false, the selection is cancelled.
28236 * @param {Roo.View} this
28237 * @param {HTMLElement} node The node to be selected
28238 * @param {Array} selections Array of currently selected nodes
28240 "beforeselect" : true,
28242 * @event preparedata
28243 * Fires on every row to render, to allow you to change the data.
28244 * @param {Roo.View} this
28245 * @param {Object} data to be rendered (change this)
28247 "preparedata" : true
28255 "click": this.onClick,
28256 "dblclick": this.onDblClick,
28257 "contextmenu": this.onContextMenu,
28261 this.selections = [];
28263 this.cmp = new Roo.CompositeElementLite([]);
28265 this.store = Roo.factory(this.store, Roo.data);
28266 this.setStore(this.store, true);
28269 if ( this.footer && this.footer.xtype) {
28271 var fctr = this.wrapEl.appendChild(document.createElement("div"));
28273 this.footer.dataSource = this.store;
28274 this.footer.container = fctr;
28275 this.footer = Roo.factory(this.footer, Roo);
28276 fctr.insertFirst(this.el);
28278 // this is a bit insane - as the paging toolbar seems to detach the el..
28279 // dom.parentNode.parentNode.parentNode
28280 // they get detached?
28284 Roo.View.superclass.constructor.call(this);
28289 Roo.extend(Roo.View, Roo.util.Observable, {
28292 * @cfg {Roo.data.Store} store Data store to load data from.
28297 * @cfg {String|Roo.Element} el The container element.
28302 * @cfg {String|Roo.Template} tpl The template used by this View
28306 * @cfg {String} dataName the named area of the template to use as the data area
28307 * Works with domtemplates roo-name="name"
28311 * @cfg {String} selectedClass The css class to add to selected nodes
28313 selectedClass : "x-view-selected",
28315 * @cfg {String} emptyText The empty text to show when nothing is loaded.
28320 * @cfg {String} text to display on mask (default Loading)
28324 * @cfg {Boolean} multiSelect Allow multiple selection
28326 multiSelect : false,
28328 * @cfg {Boolean} singleSelect Allow single selection
28330 singleSelect: false,
28333 * @cfg {Boolean} toggleSelect - selecting
28335 toggleSelect : false,
28338 * @cfg {Boolean} tickable - selecting
28343 * Returns the element this view is bound to.
28344 * @return {Roo.Element}
28346 getEl : function(){
28347 return this.wrapEl;
28353 * Refreshes the view. - called by datachanged on the store. - do not call directly.
28355 refresh : function(){
28356 //Roo.log('refresh');
28359 // if we are using something like 'domtemplate', then
28360 // the what gets used is:
28361 // t.applySubtemplate(NAME, data, wrapping data..)
28362 // the outer template then get' applied with
28363 // the store 'extra data'
28364 // and the body get's added to the
28365 // roo-name="data" node?
28366 // <span class='roo-tpl-{name}'></span> ?????
28370 this.clearSelections();
28371 this.el.update("");
28373 var records = this.store.getRange();
28374 if(records.length < 1) {
28376 // is this valid?? = should it render a template??
28378 this.el.update(this.emptyText);
28382 if (this.dataName) {
28383 this.el.update(t.apply(this.store.meta)); //????
28384 el = this.el.child('.roo-tpl-' + this.dataName);
28387 for(var i = 0, len = records.length; i < len; i++){
28388 var data = this.prepareData(records[i].data, i, records[i]);
28389 this.fireEvent("preparedata", this, data, i, records[i]);
28391 var d = Roo.apply({}, data);
28394 Roo.apply(d, {'roo-id' : Roo.id()});
28398 Roo.each(this.parent.item, function(item){
28399 if(item[_this.parent.valueField] != data[_this.parent.valueField]){
28402 Roo.apply(d, {'roo-data-checked' : 'checked'});
28406 html[html.length] = Roo.util.Format.trim(
28408 t.applySubtemplate(this.dataName, d, this.store.meta) :
28415 el.update(html.join(""));
28416 this.nodes = el.dom.childNodes;
28417 this.updateIndexes(0);
28422 * Function to override to reformat the data that is sent to
28423 * the template for each node.
28424 * DEPRICATED - use the preparedata event handler.
28425 * @param {Array/Object} data The raw data (array of colData for a data model bound view or
28426 * a JSON object for an UpdateManager bound view).
28428 prepareData : function(data, index, record)
28430 this.fireEvent("preparedata", this, data, index, record);
28434 onUpdate : function(ds, record){
28435 // Roo.log('on update');
28436 this.clearSelections();
28437 var index = this.store.indexOf(record);
28438 var n = this.nodes[index];
28439 this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
28440 n.parentNode.removeChild(n);
28441 this.updateIndexes(index, index);
28447 onAdd : function(ds, records, index)
28449 //Roo.log(['on Add', ds, records, index] );
28450 this.clearSelections();
28451 if(this.nodes.length == 0){
28455 var n = this.nodes[index];
28456 for(var i = 0, len = records.length; i < len; i++){
28457 var d = this.prepareData(records[i].data, i, records[i]);
28459 this.tpl.insertBefore(n, d);
28462 this.tpl.append(this.el, d);
28465 this.updateIndexes(index);
28468 onRemove : function(ds, record, index){
28469 // Roo.log('onRemove');
28470 this.clearSelections();
28471 var el = this.dataName ?
28472 this.el.child('.roo-tpl-' + this.dataName) :
28475 el.dom.removeChild(this.nodes[index]);
28476 this.updateIndexes(index);
28480 * Refresh an individual node.
28481 * @param {Number} index
28483 refreshNode : function(index){
28484 this.onUpdate(this.store, this.store.getAt(index));
28487 updateIndexes : function(startIndex, endIndex){
28488 var ns = this.nodes;
28489 startIndex = startIndex || 0;
28490 endIndex = endIndex || ns.length - 1;
28491 for(var i = startIndex; i <= endIndex; i++){
28492 ns[i].nodeIndex = i;
28497 * Changes the data store this view uses and refresh the view.
28498 * @param {Store} store
28500 setStore : function(store, initial){
28501 if(!initial && this.store){
28502 this.store.un("datachanged", this.refresh);
28503 this.store.un("add", this.onAdd);
28504 this.store.un("remove", this.onRemove);
28505 this.store.un("update", this.onUpdate);
28506 this.store.un("clear", this.refresh);
28507 this.store.un("beforeload", this.onBeforeLoad);
28508 this.store.un("load", this.onLoad);
28509 this.store.un("loadexception", this.onLoad);
28513 store.on("datachanged", this.refresh, this);
28514 store.on("add", this.onAdd, this);
28515 store.on("remove", this.onRemove, this);
28516 store.on("update", this.onUpdate, this);
28517 store.on("clear", this.refresh, this);
28518 store.on("beforeload", this.onBeforeLoad, this);
28519 store.on("load", this.onLoad, this);
28520 store.on("loadexception", this.onLoad, this);
28528 * onbeforeLoad - masks the loading area.
28531 onBeforeLoad : function(store,opts)
28533 //Roo.log('onBeforeLoad');
28535 this.el.update("");
28537 this.el.mask(this.mask ? this.mask : "Loading" );
28539 onLoad : function ()
28546 * Returns the template node the passed child belongs to or null if it doesn't belong to one.
28547 * @param {HTMLElement} node
28548 * @return {HTMLElement} The template node
28550 findItemFromChild : function(node){
28551 var el = this.dataName ?
28552 this.el.child('.roo-tpl-' + this.dataName,true) :
28555 if(!node || node.parentNode == el){
28558 var p = node.parentNode;
28559 while(p && p != el){
28560 if(p.parentNode == el){
28569 onClick : function(e){
28570 var item = this.findItemFromChild(e.getTarget());
28572 var index = this.indexOf(item);
28573 if(this.onItemClick(item, index, e) !== false){
28574 this.fireEvent("click", this, index, item, e);
28577 this.clearSelections();
28582 onContextMenu : function(e){
28583 var item = this.findItemFromChild(e.getTarget());
28585 this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
28590 onDblClick : function(e){
28591 var item = this.findItemFromChild(e.getTarget());
28593 this.fireEvent("dblclick", this, this.indexOf(item), item, e);
28597 onItemClick : function(item, index, e)
28599 if(this.fireEvent("beforeclick", this, index, item, e) === false){
28602 if (this.toggleSelect) {
28603 var m = this.isSelected(item) ? 'unselect' : 'select';
28606 _t[m](item, true, false);
28609 if(this.multiSelect || this.singleSelect){
28610 if(this.multiSelect && e.shiftKey && this.lastSelection){
28611 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
28613 this.select(item, this.multiSelect && e.ctrlKey);
28614 this.lastSelection = item;
28617 if(!this.tickable){
28618 e.preventDefault();
28626 * Get the number of selected nodes.
28629 getSelectionCount : function(){
28630 return this.selections.length;
28634 * Get the currently selected nodes.
28635 * @return {Array} An array of HTMLElements
28637 getSelectedNodes : function(){
28638 return this.selections;
28642 * Get the indexes of the selected nodes.
28645 getSelectedIndexes : function(){
28646 var indexes = [], s = this.selections;
28647 for(var i = 0, len = s.length; i < len; i++){
28648 indexes.push(s[i].nodeIndex);
28654 * Clear all selections
28655 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
28657 clearSelections : function(suppressEvent){
28658 if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
28659 this.cmp.elements = this.selections;
28660 this.cmp.removeClass(this.selectedClass);
28661 this.selections = [];
28662 if(!suppressEvent){
28663 this.fireEvent("selectionchange", this, this.selections);
28669 * Returns true if the passed node is selected
28670 * @param {HTMLElement/Number} node The node or node index
28671 * @return {Boolean}
28673 isSelected : function(node){
28674 var s = this.selections;
28678 node = this.getNode(node);
28679 return s.indexOf(node) !== -1;
28684 * @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
28685 * @param {Boolean} keepExisting (optional) true to keep existing selections
28686 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
28688 select : function(nodeInfo, keepExisting, suppressEvent){
28689 if(nodeInfo instanceof Array){
28691 this.clearSelections(true);
28693 for(var i = 0, len = nodeInfo.length; i < len; i++){
28694 this.select(nodeInfo[i], true, true);
28698 var node = this.getNode(nodeInfo);
28699 if(!node || this.isSelected(node)){
28700 return; // already selected.
28703 this.clearSelections(true);
28706 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
28707 Roo.fly(node).addClass(this.selectedClass);
28708 this.selections.push(node);
28709 if(!suppressEvent){
28710 this.fireEvent("selectionchange", this, this.selections);
28718 * @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
28719 * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
28720 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
28722 unselect : function(nodeInfo, keepExisting, suppressEvent)
28724 if(nodeInfo instanceof Array){
28725 Roo.each(this.selections, function(s) {
28726 this.unselect(s, nodeInfo);
28730 var node = this.getNode(nodeInfo);
28731 if(!node || !this.isSelected(node)){
28732 //Roo.log("not selected");
28733 return; // not selected.
28737 Roo.each(this.selections, function(s) {
28739 Roo.fly(node).removeClass(this.selectedClass);
28746 this.selections= ns;
28747 this.fireEvent("selectionchange", this, this.selections);
28751 * Gets a template node.
28752 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
28753 * @return {HTMLElement} The node or null if it wasn't found
28755 getNode : function(nodeInfo){
28756 if(typeof nodeInfo == "string"){
28757 return document.getElementById(nodeInfo);
28758 }else if(typeof nodeInfo == "number"){
28759 return this.nodes[nodeInfo];
28765 * Gets a range template nodes.
28766 * @param {Number} startIndex
28767 * @param {Number} endIndex
28768 * @return {Array} An array of nodes
28770 getNodes : function(start, end){
28771 var ns = this.nodes;
28772 start = start || 0;
28773 end = typeof end == "undefined" ? ns.length - 1 : end;
28776 for(var i = start; i <= end; i++){
28780 for(var i = start; i >= end; i--){
28788 * Finds the index of the passed node
28789 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
28790 * @return {Number} The index of the node or -1
28792 indexOf : function(node){
28793 node = this.getNode(node);
28794 if(typeof node.nodeIndex == "number"){
28795 return node.nodeIndex;
28797 var ns = this.nodes;
28798 for(var i = 0, len = ns.length; i < len; i++){
28808 * Ext JS Library 1.1.1
28809 * Copyright(c) 2006-2007, Ext JS, LLC.
28811 * Originally Released Under LGPL - original licence link has changed is not relivant.
28814 * <script type="text/javascript">
28818 * @class Roo.JsonView
28819 * @extends Roo.View
28820 * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
28822 var view = new Roo.JsonView({
28823 container: "my-element",
28824 tpl: '<div id="{id}">{foo} - {bar}</div>', // auto create template
28829 // listen for node click?
28830 view.on("click", function(vw, index, node, e){
28831 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
28834 // direct load of JSON data
28835 view.load("foobar.php");
28837 // Example from my blog list
28838 var tpl = new Roo.Template(
28839 '<div class="entry">' +
28840 '<a class="entry-title" href="{link}">{title}</a>' +
28841 "<h4>{date} by {author} | {comments} Comments</h4>{description}" +
28842 "</div><hr />"
28845 var moreView = new Roo.JsonView({
28846 container : "entry-list",
28850 moreView.on("beforerender", this.sortEntries, this);
28852 url: "/blog/get-posts.php",
28853 params: "allposts=true",
28854 text: "Loading Blog Entries..."
28858 * Note: old code is supported with arguments : (container, template, config)
28862 * Create a new JsonView
28864 * @param {Object} config The config object
28867 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
28870 Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
28872 var um = this.el.getUpdateManager();
28873 um.setRenderer(this);
28874 um.on("update", this.onLoad, this);
28875 um.on("failure", this.onLoadException, this);
28878 * @event beforerender
28879 * Fires before rendering of the downloaded JSON data.
28880 * @param {Roo.JsonView} this
28881 * @param {Object} data The JSON data loaded
28885 * Fires when data is loaded.
28886 * @param {Roo.JsonView} this
28887 * @param {Object} data The JSON data loaded
28888 * @param {Object} response The raw Connect response object
28891 * @event loadexception
28892 * Fires when loading fails.
28893 * @param {Roo.JsonView} this
28894 * @param {Object} response The raw Connect response object
28897 'beforerender' : true,
28899 'loadexception' : true
28902 Roo.extend(Roo.JsonView, Roo.View, {
28904 * @type {String} The root property in the loaded JSON object that contains the data
28909 * Refreshes the view.
28911 refresh : function(){
28912 this.clearSelections();
28913 this.el.update("");
28915 var o = this.jsonData;
28916 if(o && o.length > 0){
28917 for(var i = 0, len = o.length; i < len; i++){
28918 var data = this.prepareData(o[i], i, o);
28919 html[html.length] = this.tpl.apply(data);
28922 html.push(this.emptyText);
28924 this.el.update(html.join(""));
28925 this.nodes = this.el.dom.childNodes;
28926 this.updateIndexes(0);
28930 * 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.
28931 * @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:
28934 url: "your-url.php",
28935 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
28936 callback: yourFunction,
28937 scope: yourObject, //(optional scope)
28940 text: "Loading...",
28945 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
28946 * 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.
28947 * @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}
28948 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
28949 * @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.
28952 var um = this.el.getUpdateManager();
28953 um.update.apply(um, arguments);
28956 // note - render is a standard framework call...
28957 // using it for the response is really flaky... - it's called by UpdateManager normally, except when called by the XComponent/addXtype.
28958 render : function(el, response){
28960 this.clearSelections();
28961 this.el.update("");
28964 if (response != '') {
28965 o = Roo.util.JSON.decode(response.responseText);
28968 o = o[this.jsonRoot];
28974 * The current JSON data or null
28977 this.beforeRender();
28982 * Get the number of records in the current JSON dataset
28985 getCount : function(){
28986 return this.jsonData ? this.jsonData.length : 0;
28990 * Returns the JSON object for the specified node(s)
28991 * @param {HTMLElement/Array} node The node or an array of nodes
28992 * @return {Object/Array} If you pass in an array, you get an array back, otherwise
28993 * you get the JSON object for the node
28995 getNodeData : function(node){
28996 if(node instanceof Array){
28998 for(var i = 0, len = node.length; i < len; i++){
28999 data.push(this.getNodeData(node[i]));
29003 return this.jsonData[this.indexOf(node)] || null;
29006 beforeRender : function(){
29007 this.snapshot = this.jsonData;
29009 this.sort.apply(this, this.sortInfo);
29011 this.fireEvent("beforerender", this, this.jsonData);
29014 onLoad : function(el, o){
29015 this.fireEvent("load", this, this.jsonData, o);
29018 onLoadException : function(el, o){
29019 this.fireEvent("loadexception", this, o);
29023 * Filter the data by a specific property.
29024 * @param {String} property A property on your JSON objects
29025 * @param {String/RegExp} value Either string that the property values
29026 * should start with, or a RegExp to test against the property
29028 filter : function(property, value){
29031 var ss = this.snapshot;
29032 if(typeof value == "string"){
29033 var vlen = value.length;
29035 this.clearFilter();
29038 value = value.toLowerCase();
29039 for(var i = 0, len = ss.length; i < len; i++){
29041 if(o[property].substr(0, vlen).toLowerCase() == value){
29045 } else if(value.exec){ // regex?
29046 for(var i = 0, len = ss.length; i < len; i++){
29048 if(value.test(o[property])){
29055 this.jsonData = data;
29061 * Filter by a function. The passed function will be called with each
29062 * object in the current dataset. If the function returns true the value is kept,
29063 * otherwise it is filtered.
29064 * @param {Function} fn
29065 * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
29067 filterBy : function(fn, scope){
29070 var ss = this.snapshot;
29071 for(var i = 0, len = ss.length; i < len; i++){
29073 if(fn.call(scope || this, o)){
29077 this.jsonData = data;
29083 * Clears the current filter.
29085 clearFilter : function(){
29086 if(this.snapshot && this.jsonData != this.snapshot){
29087 this.jsonData = this.snapshot;
29094 * Sorts the data for this view and refreshes it.
29095 * @param {String} property A property on your JSON objects to sort on
29096 * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
29097 * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
29099 sort : function(property, dir, sortType){
29100 this.sortInfo = Array.prototype.slice.call(arguments, 0);
29103 var dsc = dir && dir.toLowerCase() == "desc";
29104 var f = function(o1, o2){
29105 var v1 = sortType ? sortType(o1[p]) : o1[p];
29106 var v2 = sortType ? sortType(o2[p]) : o2[p];
29109 return dsc ? +1 : -1;
29110 } else if(v1 > v2){
29111 return dsc ? -1 : +1;
29116 this.jsonData.sort(f);
29118 if(this.jsonData != this.snapshot){
29119 this.snapshot.sort(f);
29125 * Ext JS Library 1.1.1
29126 * Copyright(c) 2006-2007, Ext JS, LLC.
29128 * Originally Released Under LGPL - original licence link has changed is not relivant.
29131 * <script type="text/javascript">
29136 * @class Roo.ColorPalette
29137 * @extends Roo.Component
29138 * Simple color palette class for choosing colors. The palette can be rendered to any container.<br />
29139 * Here's an example of typical usage:
29141 var cp = new Roo.ColorPalette({value:'993300'}); // initial selected color
29142 cp.render('my-div');
29144 cp.on('select', function(palette, selColor){
29145 // do something with selColor
29149 * Create a new ColorPalette
29150 * @param {Object} config The config object
29152 Roo.ColorPalette = function(config){
29153 Roo.ColorPalette.superclass.constructor.call(this, config);
29157 * Fires when a color is selected
29158 * @param {ColorPalette} this
29159 * @param {String} color The 6-digit color hex code (without the # symbol)
29165 this.on("select", this.handler, this.scope, true);
29168 Roo.extend(Roo.ColorPalette, Roo.Component, {
29170 * @cfg {String} itemCls
29171 * The CSS class to apply to the containing element (defaults to "x-color-palette")
29173 itemCls : "x-color-palette",
29175 * @cfg {String} value
29176 * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol). Note that
29177 * the hex codes are case-sensitive.
29180 clickEvent:'click',
29182 ctype: "Roo.ColorPalette",
29185 * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
29187 allowReselect : false,
29190 * <p>An array of 6-digit color hex code strings (without the # symbol). This array can contain any number
29191 * of colors, and each hex code should be unique. The width of the palette is controlled via CSS by adjusting
29192 * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
29193 * of colors with the width setting until the box is symmetrical.</p>
29194 * <p>You can override individual colors if needed:</p>
29196 var cp = new Roo.ColorPalette();
29197 cp.colors[0] = "FF0000"; // change the first box to red
29200 Or you can provide a custom array of your own for complete control:
29202 var cp = new Roo.ColorPalette();
29203 cp.colors = ["000000", "993300", "333300"];
29208 "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
29209 "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
29210 "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
29211 "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
29212 "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
29216 onRender : function(container, position){
29217 var t = new Roo.MasterTemplate(
29218 '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on"> </span></em></a></tpl>'
29220 var c = this.colors;
29221 for(var i = 0, len = c.length; i < len; i++){
29224 var el = document.createElement("div");
29225 el.className = this.itemCls;
29227 container.dom.insertBefore(el, position);
29228 this.el = Roo.get(el);
29229 this.el.on(this.clickEvent, this.handleClick, this, {delegate: "a"});
29230 if(this.clickEvent != 'click'){
29231 this.el.on('click', Roo.emptyFn, this, {delegate: "a", preventDefault:true});
29236 afterRender : function(){
29237 Roo.ColorPalette.superclass.afterRender.call(this);
29239 var s = this.value;
29246 handleClick : function(e, t){
29247 e.preventDefault();
29248 if(!this.disabled){
29249 var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
29250 this.select(c.toUpperCase());
29255 * Selects the specified color in the palette (fires the select event)
29256 * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
29258 select : function(color){
29259 color = color.replace("#", "");
29260 if(color != this.value || this.allowReselect){
29263 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
29265 el.child("a.color-"+color).addClass("x-color-palette-sel");
29266 this.value = color;
29267 this.fireEvent("select", this, color);
29272 * Ext JS Library 1.1.1
29273 * Copyright(c) 2006-2007, Ext JS, LLC.
29275 * Originally Released Under LGPL - original licence link has changed is not relivant.
29278 * <script type="text/javascript">
29282 * @class Roo.DatePicker
29283 * @extends Roo.Component
29284 * Simple date picker class.
29286 * Create a new DatePicker
29287 * @param {Object} config The config object
29289 Roo.DatePicker = function(config){
29290 Roo.DatePicker.superclass.constructor.call(this, config);
29292 this.value = config && config.value ?
29293 config.value.clearTime() : new Date().clearTime();
29298 * Fires when a date is selected
29299 * @param {DatePicker} this
29300 * @param {Date} date The selected date
29304 * @event monthchange
29305 * Fires when the displayed month changes
29306 * @param {DatePicker} this
29307 * @param {Date} date The selected month
29309 'monthchange': true
29313 this.on("select", this.handler, this.scope || this);
29315 // build the disabledDatesRE
29316 if(!this.disabledDatesRE && this.disabledDates){
29317 var dd = this.disabledDates;
29319 for(var i = 0; i < dd.length; i++){
29321 if(i != dd.length-1) {
29325 this.disabledDatesRE = new RegExp(re + ")");
29329 Roo.extend(Roo.DatePicker, Roo.Component, {
29331 * @cfg {String} todayText
29332 * The text to display on the button that selects the current date (defaults to "Today")
29334 todayText : "Today",
29336 * @cfg {String} okText
29337 * The text to display on the ok button
29339 okText : " OK ", //   to give the user extra clicking room
29341 * @cfg {String} cancelText
29342 * The text to display on the cancel button
29344 cancelText : "Cancel",
29346 * @cfg {String} todayTip
29347 * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
29349 todayTip : "{0} (Spacebar)",
29351 * @cfg {Date} minDate
29352 * Minimum allowable date (JavaScript date object, defaults to null)
29356 * @cfg {Date} maxDate
29357 * Maximum allowable date (JavaScript date object, defaults to null)
29361 * @cfg {String} minText
29362 * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
29364 minText : "This date is before the minimum date",
29366 * @cfg {String} maxText
29367 * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
29369 maxText : "This date is after the maximum date",
29371 * @cfg {String} format
29372 * The default date format string which can be overriden for localization support. The format must be
29373 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
29377 * @cfg {Array} disabledDays
29378 * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
29380 disabledDays : null,
29382 * @cfg {String} disabledDaysText
29383 * The tooltip to display when the date falls on a disabled day (defaults to "")
29385 disabledDaysText : "",
29387 * @cfg {RegExp} disabledDatesRE
29388 * JavaScript regular expression used to disable a pattern of dates (defaults to null)
29390 disabledDatesRE : null,
29392 * @cfg {String} disabledDatesText
29393 * The tooltip text to display when the date falls on a disabled date (defaults to "")
29395 disabledDatesText : "",
29397 * @cfg {Boolean} constrainToViewport
29398 * True to constrain the date picker to the viewport (defaults to true)
29400 constrainToViewport : true,
29402 * @cfg {Array} monthNames
29403 * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
29405 monthNames : Date.monthNames,
29407 * @cfg {Array} dayNames
29408 * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
29410 dayNames : Date.dayNames,
29412 * @cfg {String} nextText
29413 * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
29415 nextText: 'Next Month (Control+Right)',
29417 * @cfg {String} prevText
29418 * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
29420 prevText: 'Previous Month (Control+Left)',
29422 * @cfg {String} monthYearText
29423 * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
29425 monthYearText: 'Choose a month (Control+Up/Down to move years)',
29427 * @cfg {Number} startDay
29428 * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
29432 * @cfg {Bool} showClear
29433 * Show a clear button (usefull for date form elements that can be blank.)
29439 * Sets the value of the date field
29440 * @param {Date} value The date to set
29442 setValue : function(value){
29443 var old = this.value;
29445 if (typeof(value) == 'string') {
29447 value = Date.parseDate(value, this.format);
29450 value = new Date();
29453 this.value = value.clearTime(true);
29455 this.update(this.value);
29460 * Gets the current selected value of the date field
29461 * @return {Date} The selected date
29463 getValue : function(){
29468 focus : function(){
29470 this.update(this.activeDate);
29475 onRender : function(container, position){
29478 '<table cellspacing="0">',
29479 '<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>',
29480 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
29481 var dn = this.dayNames;
29482 for(var i = 0; i < 7; i++){
29483 var d = this.startDay+i;
29487 m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
29489 m[m.length] = "</tr></thead><tbody><tr>";
29490 for(var i = 0; i < 42; i++) {
29491 if(i % 7 == 0 && i != 0){
29492 m[m.length] = "</tr><tr>";
29494 m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
29496 m[m.length] = '</tr></tbody></table></td></tr><tr>'+
29497 '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
29499 var el = document.createElement("div");
29500 el.className = "x-date-picker";
29501 el.innerHTML = m.join("");
29503 container.dom.insertBefore(el, position);
29505 this.el = Roo.get(el);
29506 this.eventEl = Roo.get(el.firstChild);
29508 new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
29509 handler: this.showPrevMonth,
29511 preventDefault:true,
29515 new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
29516 handler: this.showNextMonth,
29518 preventDefault:true,
29522 this.eventEl.on("mousewheel", this.handleMouseWheel, this);
29524 this.monthPicker = this.el.down('div.x-date-mp');
29525 this.monthPicker.enableDisplayMode('block');
29527 var kn = new Roo.KeyNav(this.eventEl, {
29528 "left" : function(e){
29530 this.showPrevMonth() :
29531 this.update(this.activeDate.add("d", -1));
29534 "right" : function(e){
29536 this.showNextMonth() :
29537 this.update(this.activeDate.add("d", 1));
29540 "up" : function(e){
29542 this.showNextYear() :
29543 this.update(this.activeDate.add("d", -7));
29546 "down" : function(e){
29548 this.showPrevYear() :
29549 this.update(this.activeDate.add("d", 7));
29552 "pageUp" : function(e){
29553 this.showNextMonth();
29556 "pageDown" : function(e){
29557 this.showPrevMonth();
29560 "enter" : function(e){
29561 e.stopPropagation();
29568 this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"});
29570 this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday, this);
29572 this.el.unselectable();
29574 this.cells = this.el.select("table.x-date-inner tbody td");
29575 this.textNodes = this.el.query("table.x-date-inner tbody span");
29577 this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
29579 tooltip: this.monthYearText
29582 this.mbtn.on('click', this.showMonthPicker, this);
29583 this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
29586 var today = (new Date()).dateFormat(this.format);
29588 var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
29589 if (this.showClear) {
29590 baseTb.add( new Roo.Toolbar.Fill());
29593 text: String.format(this.todayText, today),
29594 tooltip: String.format(this.todayTip, today),
29595 handler: this.selectToday,
29599 //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
29602 if (this.showClear) {
29604 baseTb.add( new Roo.Toolbar.Fill());
29607 cls: 'x-btn-icon x-btn-clear',
29608 handler: function() {
29610 this.fireEvent("select", this, '');
29620 this.update(this.value);
29623 createMonthPicker : function(){
29624 if(!this.monthPicker.dom.firstChild){
29625 var buf = ['<table border="0" cellspacing="0">'];
29626 for(var i = 0; i < 6; i++){
29628 '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
29629 '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
29631 '<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>' :
29632 '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
29636 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
29638 '</button><button type="button" class="x-date-mp-cancel">',
29640 '</button></td></tr>',
29643 this.monthPicker.update(buf.join(''));
29644 this.monthPicker.on('click', this.onMonthClick, this);
29645 this.monthPicker.on('dblclick', this.onMonthDblClick, this);
29647 this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
29648 this.mpYears = this.monthPicker.select('td.x-date-mp-year');
29650 this.mpMonths.each(function(m, a, i){
29653 m.dom.xmonth = 5 + Math.round(i * .5);
29655 m.dom.xmonth = Math.round((i-1) * .5);
29661 showMonthPicker : function(){
29662 this.createMonthPicker();
29663 var size = this.el.getSize();
29664 this.monthPicker.setSize(size);
29665 this.monthPicker.child('table').setSize(size);
29667 this.mpSelMonth = (this.activeDate || this.value).getMonth();
29668 this.updateMPMonth(this.mpSelMonth);
29669 this.mpSelYear = (this.activeDate || this.value).getFullYear();
29670 this.updateMPYear(this.mpSelYear);
29672 this.monthPicker.slideIn('t', {duration:.2});
29675 updateMPYear : function(y){
29677 var ys = this.mpYears.elements;
29678 for(var i = 1; i <= 10; i++){
29679 var td = ys[i-1], y2;
29681 y2 = y + Math.round(i * .5);
29682 td.firstChild.innerHTML = y2;
29685 y2 = y - (5-Math.round(i * .5));
29686 td.firstChild.innerHTML = y2;
29689 this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
29693 updateMPMonth : function(sm){
29694 this.mpMonths.each(function(m, a, i){
29695 m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
29699 selectMPMonth: function(m){
29703 onMonthClick : function(e, t){
29705 var el = new Roo.Element(t), pn;
29706 if(el.is('button.x-date-mp-cancel')){
29707 this.hideMonthPicker();
29709 else if(el.is('button.x-date-mp-ok')){
29710 this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
29711 this.hideMonthPicker();
29713 else if(pn = el.up('td.x-date-mp-month', 2)){
29714 this.mpMonths.removeClass('x-date-mp-sel');
29715 pn.addClass('x-date-mp-sel');
29716 this.mpSelMonth = pn.dom.xmonth;
29718 else if(pn = el.up('td.x-date-mp-year', 2)){
29719 this.mpYears.removeClass('x-date-mp-sel');
29720 pn.addClass('x-date-mp-sel');
29721 this.mpSelYear = pn.dom.xyear;
29723 else if(el.is('a.x-date-mp-prev')){
29724 this.updateMPYear(this.mpyear-10);
29726 else if(el.is('a.x-date-mp-next')){
29727 this.updateMPYear(this.mpyear+10);
29731 onMonthDblClick : function(e, t){
29733 var el = new Roo.Element(t), pn;
29734 if(pn = el.up('td.x-date-mp-month', 2)){
29735 this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
29736 this.hideMonthPicker();
29738 else if(pn = el.up('td.x-date-mp-year', 2)){
29739 this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
29740 this.hideMonthPicker();
29744 hideMonthPicker : function(disableAnim){
29745 if(this.monthPicker){
29746 if(disableAnim === true){
29747 this.monthPicker.hide();
29749 this.monthPicker.slideOut('t', {duration:.2});
29755 showPrevMonth : function(e){
29756 this.update(this.activeDate.add("mo", -1));
29760 showNextMonth : function(e){
29761 this.update(this.activeDate.add("mo", 1));
29765 showPrevYear : function(){
29766 this.update(this.activeDate.add("y", -1));
29770 showNextYear : function(){
29771 this.update(this.activeDate.add("y", 1));
29775 handleMouseWheel : function(e){
29776 var delta = e.getWheelDelta();
29778 this.showPrevMonth();
29780 } else if(delta < 0){
29781 this.showNextMonth();
29787 handleDateClick : function(e, t){
29789 if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
29790 this.setValue(new Date(t.dateValue));
29791 this.fireEvent("select", this, this.value);
29796 selectToday : function(){
29797 this.setValue(new Date().clearTime());
29798 this.fireEvent("select", this, this.value);
29802 update : function(date)
29804 var vd = this.activeDate;
29805 this.activeDate = date;
29807 var t = date.getTime();
29808 if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
29809 this.cells.removeClass("x-date-selected");
29810 this.cells.each(function(c){
29811 if(c.dom.firstChild.dateValue == t){
29812 c.addClass("x-date-selected");
29813 setTimeout(function(){
29814 try{c.dom.firstChild.focus();}catch(e){}
29823 var days = date.getDaysInMonth();
29824 var firstOfMonth = date.getFirstDateOfMonth();
29825 var startingPos = firstOfMonth.getDay()-this.startDay;
29827 if(startingPos <= this.startDay){
29831 var pm = date.add("mo", -1);
29832 var prevStart = pm.getDaysInMonth()-startingPos;
29834 var cells = this.cells.elements;
29835 var textEls = this.textNodes;
29836 days += startingPos;
29838 // convert everything to numbers so it's fast
29839 var day = 86400000;
29840 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
29841 var today = new Date().clearTime().getTime();
29842 var sel = date.clearTime().getTime();
29843 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
29844 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
29845 var ddMatch = this.disabledDatesRE;
29846 var ddText = this.disabledDatesText;
29847 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
29848 var ddaysText = this.disabledDaysText;
29849 var format = this.format;
29851 var setCellClass = function(cal, cell){
29853 var t = d.getTime();
29854 cell.firstChild.dateValue = t;
29856 cell.className += " x-date-today";
29857 cell.title = cal.todayText;
29860 cell.className += " x-date-selected";
29861 setTimeout(function(){
29862 try{cell.firstChild.focus();}catch(e){}
29867 cell.className = " x-date-disabled";
29868 cell.title = cal.minText;
29872 cell.className = " x-date-disabled";
29873 cell.title = cal.maxText;
29877 if(ddays.indexOf(d.getDay()) != -1){
29878 cell.title = ddaysText;
29879 cell.className = " x-date-disabled";
29882 if(ddMatch && format){
29883 var fvalue = d.dateFormat(format);
29884 if(ddMatch.test(fvalue)){
29885 cell.title = ddText.replace("%0", fvalue);
29886 cell.className = " x-date-disabled";
29892 for(; i < startingPos; i++) {
29893 textEls[i].innerHTML = (++prevStart);
29894 d.setDate(d.getDate()+1);
29895 cells[i].className = "x-date-prevday";
29896 setCellClass(this, cells[i]);
29898 for(; i < days; i++){
29899 intDay = i - startingPos + 1;
29900 textEls[i].innerHTML = (intDay);
29901 d.setDate(d.getDate()+1);
29902 cells[i].className = "x-date-active";
29903 setCellClass(this, cells[i]);
29906 for(; i < 42; i++) {
29907 textEls[i].innerHTML = (++extraDays);
29908 d.setDate(d.getDate()+1);
29909 cells[i].className = "x-date-nextday";
29910 setCellClass(this, cells[i]);
29913 this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
29914 this.fireEvent('monthchange', this, date);
29916 if(!this.internalRender){
29917 var main = this.el.dom.firstChild;
29918 var w = main.offsetWidth;
29919 this.el.setWidth(w + this.el.getBorderWidth("lr"));
29920 Roo.fly(main).setWidth(w);
29921 this.internalRender = true;
29922 // opera does not respect the auto grow header center column
29923 // then, after it gets a width opera refuses to recalculate
29924 // without a second pass
29925 if(Roo.isOpera && !this.secondPass){
29926 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
29927 this.secondPass = true;
29928 this.update.defer(10, this, [date]);
29936 * Ext JS Library 1.1.1
29937 * Copyright(c) 2006-2007, Ext JS, LLC.
29939 * Originally Released Under LGPL - original licence link has changed is not relivant.
29942 * <script type="text/javascript">
29945 * @class Roo.TabPanel
29946 * @extends Roo.util.Observable
29947 * A lightweight tab container.
29951 // basic tabs 1, built from existing content
29952 var tabs = new Roo.TabPanel("tabs1");
29953 tabs.addTab("script", "View Script");
29954 tabs.addTab("markup", "View Markup");
29955 tabs.activate("script");
29957 // more advanced tabs, built from javascript
29958 var jtabs = new Roo.TabPanel("jtabs");
29959 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
29961 // set up the UpdateManager
29962 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
29963 var updater = tab2.getUpdateManager();
29964 updater.setDefaultUrl("ajax1.htm");
29965 tab2.on('activate', updater.refresh, updater, true);
29967 // Use setUrl for Ajax loading
29968 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
29969 tab3.setUrl("ajax2.htm", null, true);
29972 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
29975 jtabs.activate("jtabs-1");
29978 * Create a new TabPanel.
29979 * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
29980 * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
29982 Roo.TabPanel = function(container, config){
29984 * The container element for this TabPanel.
29985 * @type Roo.Element
29987 this.el = Roo.get(container, true);
29989 if(typeof config == "boolean"){
29990 this.tabPosition = config ? "bottom" : "top";
29992 Roo.apply(this, config);
29995 if(this.tabPosition == "bottom"){
29996 this.bodyEl = Roo.get(this.createBody(this.el.dom));
29997 this.el.addClass("x-tabs-bottom");
29999 this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
30000 this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
30001 this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
30003 Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
30005 if(this.tabPosition != "bottom"){
30006 /** The body element that contains {@link Roo.TabPanelItem} bodies. +
30007 * @type Roo.Element
30009 this.bodyEl = Roo.get(this.createBody(this.el.dom));
30010 this.el.addClass("x-tabs-top");
30014 this.bodyEl.setStyle("position", "relative");
30016 this.active = null;
30017 this.activateDelegate = this.activate.createDelegate(this);
30022 * Fires when the active tab changes
30023 * @param {Roo.TabPanel} this
30024 * @param {Roo.TabPanelItem} activePanel The new active tab
30028 * @event beforetabchange
30029 * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
30030 * @param {Roo.TabPanel} this
30031 * @param {Object} e Set cancel to true on this object to cancel the tab change
30032 * @param {Roo.TabPanelItem} tab The tab being changed to
30034 "beforetabchange" : true
30037 Roo.EventManager.onWindowResize(this.onResize, this);
30038 this.cpad = this.el.getPadding("lr");
30039 this.hiddenCount = 0;
30042 // toolbar on the tabbar support...
30043 if (this.toolbar) {
30044 var tcfg = this.toolbar;
30045 tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');
30046 this.toolbar = new Roo.Toolbar(tcfg);
30047 if (Roo.isSafari) {
30048 var tbl = tcfg.container.child('table', true);
30049 tbl.setAttribute('width', '100%');
30056 Roo.TabPanel.superclass.constructor.call(this);
30059 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
30061 *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
30063 tabPosition : "top",
30065 *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
30067 currentTabWidth : 0,
30069 *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
30073 *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
30077 *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
30079 preferredTabWidth : 175,
30081 *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
30083 resizeTabs : false,
30085 *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
30087 monitorResize : true,
30089 *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar.
30094 * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
30095 * @param {String} id The id of the div to use <b>or create</b>
30096 * @param {String} text The text for the tab
30097 * @param {String} content (optional) Content to put in the TabPanelItem body
30098 * @param {Boolean} closable (optional) True to create a close icon on the tab
30099 * @return {Roo.TabPanelItem} The created TabPanelItem
30101 addTab : function(id, text, content, closable){
30102 var item = new Roo.TabPanelItem(this, id, text, closable);
30103 this.addTabItem(item);
30105 item.setContent(content);
30111 * Returns the {@link Roo.TabPanelItem} with the specified id/index
30112 * @param {String/Number} id The id or index of the TabPanelItem to fetch.
30113 * @return {Roo.TabPanelItem}
30115 getTab : function(id){
30116 return this.items[id];
30120 * Hides the {@link Roo.TabPanelItem} with the specified id/index
30121 * @param {String/Number} id The id or index of the TabPanelItem to hide.
30123 hideTab : function(id){
30124 var t = this.items[id];
30127 this.hiddenCount++;
30128 this.autoSizeTabs();
30133 * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
30134 * @param {String/Number} id The id or index of the TabPanelItem to unhide.
30136 unhideTab : function(id){
30137 var t = this.items[id];
30139 t.setHidden(false);
30140 this.hiddenCount--;
30141 this.autoSizeTabs();
30146 * Adds an existing {@link Roo.TabPanelItem}.
30147 * @param {Roo.TabPanelItem} item The TabPanelItem to add
30149 addTabItem : function(item){
30150 this.items[item.id] = item;
30151 this.items.push(item);
30152 if(this.resizeTabs){
30153 item.setWidth(this.currentTabWidth || this.preferredTabWidth);
30154 this.autoSizeTabs();
30161 * Removes a {@link Roo.TabPanelItem}.
30162 * @param {String/Number} id The id or index of the TabPanelItem to remove.
30164 removeTab : function(id){
30165 var items = this.items;
30166 var tab = items[id];
30167 if(!tab) { return; }
30168 var index = items.indexOf(tab);
30169 if(this.active == tab && items.length > 1){
30170 var newTab = this.getNextAvailable(index);
30175 this.stripEl.dom.removeChild(tab.pnode.dom);
30176 if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
30177 this.bodyEl.dom.removeChild(tab.bodyEl.dom);
30179 items.splice(index, 1);
30180 delete this.items[tab.id];
30181 tab.fireEvent("close", tab);
30182 tab.purgeListeners();
30183 this.autoSizeTabs();
30186 getNextAvailable : function(start){
30187 var items = this.items;
30189 // look for a next tab that will slide over to
30190 // replace the one being removed
30191 while(index < items.length){
30192 var item = items[++index];
30193 if(item && !item.isHidden()){
30197 // if one isn't found select the previous tab (on the left)
30200 var item = items[--index];
30201 if(item && !item.isHidden()){
30209 * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
30210 * @param {String/Number} id The id or index of the TabPanelItem to disable.
30212 disableTab : function(id){
30213 var tab = this.items[id];
30214 if(tab && this.active != tab){
30220 * Enables a {@link Roo.TabPanelItem} that is disabled.
30221 * @param {String/Number} id The id or index of the TabPanelItem to enable.
30223 enableTab : function(id){
30224 var tab = this.items[id];
30229 * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
30230 * @param {String/Number} id The id or index of the TabPanelItem to activate.
30231 * @return {Roo.TabPanelItem} The TabPanelItem.
30233 activate : function(id){
30234 var tab = this.items[id];
30238 if(tab == this.active || tab.disabled){
30242 this.fireEvent("beforetabchange", this, e, tab);
30243 if(e.cancel !== true && !tab.disabled){
30245 this.active.hide();
30247 this.active = this.items[id];
30248 this.active.show();
30249 this.fireEvent("tabchange", this, this.active);
30255 * Gets the active {@link Roo.TabPanelItem}.
30256 * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
30258 getActiveTab : function(){
30259 return this.active;
30263 * Updates the tab body element to fit the height of the container element
30264 * for overflow scrolling
30265 * @param {Number} targetHeight (optional) Override the starting height from the elements height
30267 syncHeight : function(targetHeight){
30268 var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
30269 var bm = this.bodyEl.getMargins();
30270 var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
30271 this.bodyEl.setHeight(newHeight);
30275 onResize : function(){
30276 if(this.monitorResize){
30277 this.autoSizeTabs();
30282 * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
30284 beginUpdate : function(){
30285 this.updating = true;
30289 * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
30291 endUpdate : function(){
30292 this.updating = false;
30293 this.autoSizeTabs();
30297 * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
30299 autoSizeTabs : function(){
30300 var count = this.items.length;
30301 var vcount = count - this.hiddenCount;
30302 if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
30305 var w = Math.max(this.el.getWidth() - this.cpad, 10);
30306 var availWidth = Math.floor(w / vcount);
30307 var b = this.stripBody;
30308 if(b.getWidth() > w){
30309 var tabs = this.items;
30310 this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
30311 if(availWidth < this.minTabWidth){
30312 /*if(!this.sleft){ // incomplete scrolling code
30313 this.createScrollButtons();
30316 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
30319 if(this.currentTabWidth < this.preferredTabWidth){
30320 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
30326 * Returns the number of tabs in this TabPanel.
30329 getCount : function(){
30330 return this.items.length;
30334 * Resizes all the tabs to the passed width
30335 * @param {Number} The new width
30337 setTabWidth : function(width){
30338 this.currentTabWidth = width;
30339 for(var i = 0, len = this.items.length; i < len; i++) {
30340 if(!this.items[i].isHidden()) {
30341 this.items[i].setWidth(width);
30347 * Destroys this TabPanel
30348 * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
30350 destroy : function(removeEl){
30351 Roo.EventManager.removeResizeListener(this.onResize, this);
30352 for(var i = 0, len = this.items.length; i < len; i++){
30353 this.items[i].purgeListeners();
30355 if(removeEl === true){
30356 this.el.update("");
30363 * @class Roo.TabPanelItem
30364 * @extends Roo.util.Observable
30365 * Represents an individual item (tab plus body) in a TabPanel.
30366 * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
30367 * @param {String} id The id of this TabPanelItem
30368 * @param {String} text The text for the tab of this TabPanelItem
30369 * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
30371 Roo.TabPanelItem = function(tabPanel, id, text, closable){
30373 * The {@link Roo.TabPanel} this TabPanelItem belongs to
30374 * @type Roo.TabPanel
30376 this.tabPanel = tabPanel;
30378 * The id for this TabPanelItem
30383 this.disabled = false;
30387 this.loaded = false;
30388 this.closable = closable;
30391 * The body element for this TabPanelItem.
30392 * @type Roo.Element
30394 this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
30395 this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
30396 this.bodyEl.setStyle("display", "block");
30397 this.bodyEl.setStyle("zoom", "1");
30400 var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
30402 this.el = Roo.get(els.el, true);
30403 this.inner = Roo.get(els.inner, true);
30404 this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
30405 this.pnode = Roo.get(els.el.parentNode, true);
30406 this.el.on("mousedown", this.onTabMouseDown, this);
30407 this.el.on("click", this.onTabClick, this);
30410 var c = Roo.get(els.close, true);
30411 c.dom.title = this.closeText;
30412 c.addClassOnOver("close-over");
30413 c.on("click", this.closeClick, this);
30419 * Fires when this tab becomes the active tab.
30420 * @param {Roo.TabPanel} tabPanel The parent TabPanel
30421 * @param {Roo.TabPanelItem} this
30425 * @event beforeclose
30426 * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
30427 * @param {Roo.TabPanelItem} this
30428 * @param {Object} e Set cancel to true on this object to cancel the close.
30430 "beforeclose": true,
30433 * Fires when this tab is closed.
30434 * @param {Roo.TabPanelItem} this
30438 * @event deactivate
30439 * Fires when this tab is no longer the active tab.
30440 * @param {Roo.TabPanel} tabPanel The parent TabPanel
30441 * @param {Roo.TabPanelItem} this
30443 "deactivate" : true
30445 this.hidden = false;
30447 Roo.TabPanelItem.superclass.constructor.call(this);
30450 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
30451 purgeListeners : function(){
30452 Roo.util.Observable.prototype.purgeListeners.call(this);
30453 this.el.removeAllListeners();
30456 * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
30459 this.pnode.addClass("on");
30462 this.tabPanel.stripWrap.repaint();
30464 this.fireEvent("activate", this.tabPanel, this);
30468 * Returns true if this tab is the active tab.
30469 * @return {Boolean}
30471 isActive : function(){
30472 return this.tabPanel.getActiveTab() == this;
30476 * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
30479 this.pnode.removeClass("on");
30481 this.fireEvent("deactivate", this.tabPanel, this);
30484 hideAction : function(){
30485 this.bodyEl.hide();
30486 this.bodyEl.setStyle("position", "absolute");
30487 this.bodyEl.setLeft("-20000px");
30488 this.bodyEl.setTop("-20000px");
30491 showAction : function(){
30492 this.bodyEl.setStyle("position", "relative");
30493 this.bodyEl.setTop("");
30494 this.bodyEl.setLeft("");
30495 this.bodyEl.show();
30499 * Set the tooltip for the tab.
30500 * @param {String} tooltip The tab's tooltip
30502 setTooltip : function(text){
30503 if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
30504 this.textEl.dom.qtip = text;
30505 this.textEl.dom.removeAttribute('title');
30507 this.textEl.dom.title = text;
30511 onTabClick : function(e){
30512 e.preventDefault();
30513 this.tabPanel.activate(this.id);
30516 onTabMouseDown : function(e){
30517 e.preventDefault();
30518 this.tabPanel.activate(this.id);
30521 getWidth : function(){
30522 return this.inner.getWidth();
30525 setWidth : function(width){
30526 var iwidth = width - this.pnode.getPadding("lr");
30527 this.inner.setWidth(iwidth);
30528 this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
30529 this.pnode.setWidth(width);
30533 * Show or hide the tab
30534 * @param {Boolean} hidden True to hide or false to show.
30536 setHidden : function(hidden){
30537 this.hidden = hidden;
30538 this.pnode.setStyle("display", hidden ? "none" : "");
30542 * Returns true if this tab is "hidden"
30543 * @return {Boolean}
30545 isHidden : function(){
30546 return this.hidden;
30550 * Returns the text for this tab
30553 getText : function(){
30557 autoSize : function(){
30558 //this.el.beginMeasure();
30559 this.textEl.setWidth(1);
30561 * #2804 [new] Tabs in Roojs
30562 * increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
30564 this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
30565 //this.el.endMeasure();
30569 * Sets the text for the tab (Note: this also sets the tooltip text)
30570 * @param {String} text The tab's text and tooltip
30572 setText : function(text){
30574 this.textEl.update(text);
30575 this.setTooltip(text);
30576 if(!this.tabPanel.resizeTabs){
30581 * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
30583 activate : function(){
30584 this.tabPanel.activate(this.id);
30588 * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
30590 disable : function(){
30591 if(this.tabPanel.active != this){
30592 this.disabled = true;
30593 this.pnode.addClass("disabled");
30598 * Enables this TabPanelItem if it was previously disabled.
30600 enable : function(){
30601 this.disabled = false;
30602 this.pnode.removeClass("disabled");
30606 * Sets the content for this TabPanelItem.
30607 * @param {String} content The content
30608 * @param {Boolean} loadScripts true to look for and load scripts
30610 setContent : function(content, loadScripts){
30611 this.bodyEl.update(content, loadScripts);
30615 * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
30616 * @return {Roo.UpdateManager} The UpdateManager
30618 getUpdateManager : function(){
30619 return this.bodyEl.getUpdateManager();
30623 * Set a URL to be used to load the content for this TabPanelItem.
30624 * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
30625 * @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)
30626 * @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)
30627 * @return {Roo.UpdateManager} The UpdateManager
30629 setUrl : function(url, params, loadOnce){
30630 if(this.refreshDelegate){
30631 this.un('activate', this.refreshDelegate);
30633 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
30634 this.on("activate", this.refreshDelegate);
30635 return this.bodyEl.getUpdateManager();
30639 _handleRefresh : function(url, params, loadOnce){
30640 if(!loadOnce || !this.loaded){
30641 var updater = this.bodyEl.getUpdateManager();
30642 updater.update(url, params, this._setLoaded.createDelegate(this));
30647 * Forces a content refresh from the URL specified in the {@link #setUrl} method.
30648 * Will fail silently if the setUrl method has not been called.
30649 * This does not activate the panel, just updates its content.
30651 refresh : function(){
30652 if(this.refreshDelegate){
30653 this.loaded = false;
30654 this.refreshDelegate();
30659 _setLoaded : function(){
30660 this.loaded = true;
30664 closeClick : function(e){
30667 this.fireEvent("beforeclose", this, o);
30668 if(o.cancel !== true){
30669 this.tabPanel.removeTab(this.id);
30673 * The text displayed in the tooltip for the close icon.
30676 closeText : "Close this tab"
30680 Roo.TabPanel.prototype.createStrip = function(container){
30681 var strip = document.createElement("div");
30682 strip.className = "x-tabs-wrap";
30683 container.appendChild(strip);
30687 Roo.TabPanel.prototype.createStripList = function(strip){
30688 // div wrapper for retard IE
30689 // returns the "tr" element.
30690 strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
30691 '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
30692 '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
30693 return strip.firstChild.firstChild.firstChild.firstChild;
30696 Roo.TabPanel.prototype.createBody = function(container){
30697 var body = document.createElement("div");
30698 Roo.id(body, "tab-body");
30699 Roo.fly(body).addClass("x-tabs-body");
30700 container.appendChild(body);
30704 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
30705 var body = Roo.getDom(id);
30707 body = document.createElement("div");
30710 Roo.fly(body).addClass("x-tabs-item-body");
30711 bodyEl.insertBefore(body, bodyEl.firstChild);
30715 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
30716 var td = document.createElement("td");
30717 stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
30718 //stripEl.appendChild(td);
30720 td.className = "x-tabs-closable";
30721 if(!this.closeTpl){
30722 this.closeTpl = new Roo.Template(
30723 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
30724 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
30725 '<div unselectable="on" class="close-icon"> </div></em></span></a>'
30728 var el = this.closeTpl.overwrite(td, {"text": text});
30729 var close = el.getElementsByTagName("div")[0];
30730 var inner = el.getElementsByTagName("em")[0];
30731 return {"el": el, "close": close, "inner": inner};
30734 this.tabTpl = new Roo.Template(
30735 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
30736 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
30739 var el = this.tabTpl.overwrite(td, {"text": text});
30740 var inner = el.getElementsByTagName("em")[0];
30741 return {"el": el, "inner": inner};
30745 * Ext JS Library 1.1.1
30746 * Copyright(c) 2006-2007, Ext JS, LLC.
30748 * Originally Released Under LGPL - original licence link has changed is not relivant.
30751 * <script type="text/javascript">
30755 * @class Roo.Button
30756 * @extends Roo.util.Observable
30757 * Simple Button class
30758 * @cfg {String} text The button text
30759 * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
30760 * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
30761 * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
30762 * @cfg {Object} scope The scope of the handler
30763 * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
30764 * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
30765 * @cfg {Boolean} hidden True to start hidden (defaults to false)
30766 * @cfg {Boolean} disabled True to start disabled (defaults to false)
30767 * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
30768 * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
30769 applies if enableToggle = true)
30770 * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
30771 * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
30772 an {@link Roo.util.ClickRepeater} config object (defaults to false).
30774 * Create a new button
30775 * @param {Object} config The config object
30777 Roo.Button = function(renderTo, config)
30781 renderTo = config.renderTo || false;
30784 Roo.apply(this, config);
30788 * Fires when this button is clicked
30789 * @param {Button} this
30790 * @param {EventObject} e The click event
30795 * Fires when the "pressed" state of this button changes (only if enableToggle = true)
30796 * @param {Button} this
30797 * @param {Boolean} pressed
30802 * Fires when the mouse hovers over the button
30803 * @param {Button} this
30804 * @param {Event} e The event object
30806 'mouseover' : true,
30809 * Fires when the mouse exits the button
30810 * @param {Button} this
30811 * @param {Event} e The event object
30816 * Fires when the button is rendered
30817 * @param {Button} this
30822 this.menu = Roo.menu.MenuMgr.get(this.menu);
30824 // register listeners first!! - so render can be captured..
30825 Roo.util.Observable.call(this);
30827 this.render(renderTo);
30833 Roo.extend(Roo.Button, Roo.util.Observable, {
30839 * Read-only. True if this button is hidden
30844 * Read-only. True if this button is disabled
30849 * Read-only. True if this button is pressed (only if enableToggle = true)
30855 * @cfg {Number} tabIndex
30856 * The DOM tabIndex for this button (defaults to undefined)
30858 tabIndex : undefined,
30861 * @cfg {Boolean} enableToggle
30862 * True to enable pressed/not pressed toggling (defaults to false)
30864 enableToggle: false,
30866 * @cfg {Roo.menu.Menu} menu
30867 * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
30871 * @cfg {String} menuAlign
30872 * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
30874 menuAlign : "tl-bl?",
30877 * @cfg {String} iconCls
30878 * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
30880 iconCls : undefined,
30882 * @cfg {String} type
30883 * The button's type, corresponding to the DOM input element type attribute. Either "submit," "reset" or "button" (default).
30888 menuClassTarget: 'tr',
30891 * @cfg {String} clickEvent
30892 * The type of event to map to the button's event handler (defaults to 'click')
30894 clickEvent : 'click',
30897 * @cfg {Boolean} handleMouseEvents
30898 * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
30900 handleMouseEvents : true,
30903 * @cfg {String} tooltipType
30904 * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
30906 tooltipType : 'qtip',
30909 * @cfg {String} cls
30910 * A CSS class to apply to the button's main element.
30914 * @cfg {Roo.Template} template (Optional)
30915 * An {@link Roo.Template} with which to create the Button's main element. This Template must
30916 * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
30917 * require code modifications if required elements (e.g. a button) aren't present.
30921 render : function(renderTo){
30923 if(this.hideParent){
30924 this.parentEl = Roo.get(renderTo);
30926 if(!this.dhconfig){
30927 if(!this.template){
30928 if(!Roo.Button.buttonTemplate){
30929 // hideous table template
30930 Roo.Button.buttonTemplate = new Roo.Template(
30931 '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
30932 '<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>',
30933 "</tr></tbody></table>");
30935 this.template = Roo.Button.buttonTemplate;
30937 btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
30938 var btnEl = btn.child("button:first");
30939 btnEl.on('focus', this.onFocus, this);
30940 btnEl.on('blur', this.onBlur, this);
30942 btn.addClass(this.cls);
30945 btnEl.setStyle('background-image', 'url(' +this.icon +')');
30948 btnEl.addClass(this.iconCls);
30950 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
30953 if(this.tabIndex !== undefined){
30954 btnEl.dom.tabIndex = this.tabIndex;
30957 if(typeof this.tooltip == 'object'){
30958 Roo.QuickTips.tips(Roo.apply({
30962 btnEl.dom[this.tooltipType] = this.tooltip;
30966 btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
30970 this.el.dom.id = this.el.id = this.id;
30973 this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
30974 this.menu.on("show", this.onMenuShow, this);
30975 this.menu.on("hide", this.onMenuHide, this);
30977 btn.addClass("x-btn");
30978 if(Roo.isIE && !Roo.isIE7){
30979 this.autoWidth.defer(1, this);
30983 if(this.handleMouseEvents){
30984 btn.on("mouseover", this.onMouseOver, this);
30985 btn.on("mouseout", this.onMouseOut, this);
30986 btn.on("mousedown", this.onMouseDown, this);
30988 btn.on(this.clickEvent, this.onClick, this);
30989 //btn.on("mouseup", this.onMouseUp, this);
30996 Roo.ButtonToggleMgr.register(this);
30998 this.el.addClass("x-btn-pressed");
31001 var repeater = new Roo.util.ClickRepeater(btn,
31002 typeof this.repeat == "object" ? this.repeat : {}
31004 repeater.on("click", this.onClick, this);
31007 this.fireEvent('render', this);
31011 * Returns the button's underlying element
31012 * @return {Roo.Element} The element
31014 getEl : function(){
31019 * Destroys this Button and removes any listeners.
31021 destroy : function(){
31022 Roo.ButtonToggleMgr.unregister(this);
31023 this.el.removeAllListeners();
31024 this.purgeListeners();
31029 autoWidth : function(){
31031 this.el.setWidth("auto");
31032 if(Roo.isIE7 && Roo.isStrict){
31033 var ib = this.el.child('button');
31034 if(ib && ib.getWidth() > 20){
31036 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
31041 this.el.beginMeasure();
31043 if(this.el.getWidth() < this.minWidth){
31044 this.el.setWidth(this.minWidth);
31047 this.el.endMeasure();
31054 * Assigns this button's click handler
31055 * @param {Function} handler The function to call when the button is clicked
31056 * @param {Object} scope (optional) Scope for the function passed in
31058 setHandler : function(handler, scope){
31059 this.handler = handler;
31060 this.scope = scope;
31064 * Sets this button's text
31065 * @param {String} text The button text
31067 setText : function(text){
31070 this.el.child("td.x-btn-center button.x-btn-text").update(text);
31076 * Gets the text for this button
31077 * @return {String} The button text
31079 getText : function(){
31087 this.hidden = false;
31089 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
31097 this.hidden = true;
31099 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
31104 * Convenience function for boolean show/hide
31105 * @param {Boolean} visible True to show, false to hide
31107 setVisible: function(visible){
31116 * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
31117 * @param {Boolean} state (optional) Force a particular state
31119 toggle : function(state){
31120 state = state === undefined ? !this.pressed : state;
31121 if(state != this.pressed){
31123 this.el.addClass("x-btn-pressed");
31124 this.pressed = true;
31125 this.fireEvent("toggle", this, true);
31127 this.el.removeClass("x-btn-pressed");
31128 this.pressed = false;
31129 this.fireEvent("toggle", this, false);
31131 if(this.toggleHandler){
31132 this.toggleHandler.call(this.scope || this, this, state);
31140 focus : function(){
31141 this.el.child('button:first').focus();
31145 * Disable this button
31147 disable : function(){
31149 this.el.addClass("x-btn-disabled");
31151 this.disabled = true;
31155 * Enable this button
31157 enable : function(){
31159 this.el.removeClass("x-btn-disabled");
31161 this.disabled = false;
31165 * Convenience function for boolean enable/disable
31166 * @param {Boolean} enabled True to enable, false to disable
31168 setDisabled : function(v){
31169 this[v !== true ? "enable" : "disable"]();
31173 onClick : function(e)
31176 e.preventDefault();
31181 if(!this.disabled){
31182 if(this.enableToggle){
31185 if(this.menu && !this.menu.isVisible()){
31186 this.menu.show(this.el, this.menuAlign);
31188 this.fireEvent("click", this, e);
31190 this.el.removeClass("x-btn-over");
31191 this.handler.call(this.scope || this, this, e);
31196 onMouseOver : function(e){
31197 if(!this.disabled){
31198 this.el.addClass("x-btn-over");
31199 this.fireEvent('mouseover', this, e);
31203 onMouseOut : function(e){
31204 if(!e.within(this.el, true)){
31205 this.el.removeClass("x-btn-over");
31206 this.fireEvent('mouseout', this, e);
31210 onFocus : function(e){
31211 if(!this.disabled){
31212 this.el.addClass("x-btn-focus");
31216 onBlur : function(e){
31217 this.el.removeClass("x-btn-focus");
31220 onMouseDown : function(e){
31221 if(!this.disabled && e.button == 0){
31222 this.el.addClass("x-btn-click");
31223 Roo.get(document).on('mouseup', this.onMouseUp, this);
31227 onMouseUp : function(e){
31229 this.el.removeClass("x-btn-click");
31230 Roo.get(document).un('mouseup', this.onMouseUp, this);
31234 onMenuShow : function(e){
31235 this.el.addClass("x-btn-menu-active");
31238 onMenuHide : function(e){
31239 this.el.removeClass("x-btn-menu-active");
31243 // Private utility class used by Button
31244 Roo.ButtonToggleMgr = function(){
31247 function toggleGroup(btn, state){
31249 var g = groups[btn.toggleGroup];
31250 for(var i = 0, l = g.length; i < l; i++){
31252 g[i].toggle(false);
31259 register : function(btn){
31260 if(!btn.toggleGroup){
31263 var g = groups[btn.toggleGroup];
31265 g = groups[btn.toggleGroup] = [];
31268 btn.on("toggle", toggleGroup);
31271 unregister : function(btn){
31272 if(!btn.toggleGroup){
31275 var g = groups[btn.toggleGroup];
31278 btn.un("toggle", toggleGroup);
31284 * Ext JS Library 1.1.1
31285 * Copyright(c) 2006-2007, Ext JS, LLC.
31287 * Originally Released Under LGPL - original licence link has changed is not relivant.
31290 * <script type="text/javascript">
31294 * @class Roo.SplitButton
31295 * @extends Roo.Button
31296 * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
31297 * click event of the button. Typically this would be used to display a dropdown menu that provides additional
31298 * options to the primary button action, but any custom handler can provide the arrowclick implementation.
31299 * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
31300 * @cfg {String} arrowTooltip The title attribute of the arrow
31302 * Create a new menu button
31303 * @param {String/HTMLElement/Element} renderTo The element to append the button to
31304 * @param {Object} config The config object
31306 Roo.SplitButton = function(renderTo, config){
31307 Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
31309 * @event arrowclick
31310 * Fires when this button's arrow is clicked
31311 * @param {SplitButton} this
31312 * @param {EventObject} e The click event
31314 this.addEvents({"arrowclick":true});
31317 Roo.extend(Roo.SplitButton, Roo.Button, {
31318 render : function(renderTo){
31319 // this is one sweet looking template!
31320 var tpl = new Roo.Template(
31321 '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
31322 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
31323 '<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>',
31324 "</tbody></table></td><td>",
31325 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
31326 '<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>',
31327 "</tbody></table></td></tr></table>"
31329 var btn = tpl.append(renderTo, [this.text, this.type], true);
31330 var btnEl = btn.child("button");
31332 btn.addClass(this.cls);
31335 btnEl.setStyle('background-image', 'url(' +this.icon +')');
31338 btnEl.addClass(this.iconCls);
31340 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
31344 if(this.handleMouseEvents){
31345 btn.on("mouseover", this.onMouseOver, this);
31346 btn.on("mouseout", this.onMouseOut, this);
31347 btn.on("mousedown", this.onMouseDown, this);
31348 btn.on("mouseup", this.onMouseUp, this);
31350 btn.on(this.clickEvent, this.onClick, this);
31352 if(typeof this.tooltip == 'object'){
31353 Roo.QuickTips.tips(Roo.apply({
31357 btnEl.dom[this.tooltipType] = this.tooltip;
31360 if(this.arrowTooltip){
31361 btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
31370 this.el.addClass("x-btn-pressed");
31372 if(Roo.isIE && !Roo.isIE7){
31373 this.autoWidth.defer(1, this);
31378 this.menu.on("show", this.onMenuShow, this);
31379 this.menu.on("hide", this.onMenuHide, this);
31381 this.fireEvent('render', this);
31385 autoWidth : function(){
31387 var tbl = this.el.child("table:first");
31388 var tbl2 = this.el.child("table:last");
31389 this.el.setWidth("auto");
31390 tbl.setWidth("auto");
31391 if(Roo.isIE7 && Roo.isStrict){
31392 var ib = this.el.child('button:first');
31393 if(ib && ib.getWidth() > 20){
31395 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
31400 this.el.beginMeasure();
31402 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
31403 tbl.setWidth(this.minWidth-tbl2.getWidth());
31406 this.el.endMeasure();
31409 this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
31413 * Sets this button's click handler
31414 * @param {Function} handler The function to call when the button is clicked
31415 * @param {Object} scope (optional) Scope for the function passed above
31417 setHandler : function(handler, scope){
31418 this.handler = handler;
31419 this.scope = scope;
31423 * Sets this button's arrow click handler
31424 * @param {Function} handler The function to call when the arrow is clicked
31425 * @param {Object} scope (optional) Scope for the function passed above
31427 setArrowHandler : function(handler, scope){
31428 this.arrowHandler = handler;
31429 this.scope = scope;
31435 focus : function(){
31437 this.el.child("button:first").focus();
31442 onClick : function(e){
31443 e.preventDefault();
31444 if(!this.disabled){
31445 if(e.getTarget(".x-btn-menu-arrow-wrap")){
31446 if(this.menu && !this.menu.isVisible()){
31447 this.menu.show(this.el, this.menuAlign);
31449 this.fireEvent("arrowclick", this, e);
31450 if(this.arrowHandler){
31451 this.arrowHandler.call(this.scope || this, this, e);
31454 this.fireEvent("click", this, e);
31456 this.handler.call(this.scope || this, this, e);
31462 onMouseDown : function(e){
31463 if(!this.disabled){
31464 Roo.fly(e.getTarget("table")).addClass("x-btn-click");
31468 onMouseUp : function(e){
31469 Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
31474 // backwards compat
31475 Roo.MenuButton = Roo.SplitButton;/*
31477 * Ext JS Library 1.1.1
31478 * Copyright(c) 2006-2007, Ext JS, LLC.
31480 * Originally Released Under LGPL - original licence link has changed is not relivant.
31483 * <script type="text/javascript">
31487 * @class Roo.Toolbar
31488 * @children Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
31489 * Basic Toolbar class.
31491 * Creates a new Toolbar
31492 * @param {Object} container The config object
31494 Roo.Toolbar = function(container, buttons, config)
31496 /// old consturctor format still supported..
31497 if(container instanceof Array){ // omit the container for later rendering
31498 buttons = container;
31502 if (typeof(container) == 'object' && container.xtype) {
31503 config = container;
31504 container = config.container;
31505 buttons = config.buttons || []; // not really - use items!!
31508 if (config && config.items) {
31509 xitems = config.items;
31510 delete config.items;
31512 Roo.apply(this, config);
31513 this.buttons = buttons;
31516 this.render(container);
31518 this.xitems = xitems;
31519 Roo.each(xitems, function(b) {
31525 Roo.Toolbar.prototype = {
31527 * @cfg {Array} items
31528 * array of button configs or elements to add (will be converted to a MixedCollection)
31532 * @cfg {String/HTMLElement/Element} container
31533 * The id or element that will contain the toolbar
31536 render : function(ct){
31537 this.el = Roo.get(ct);
31539 this.el.addClass(this.cls);
31541 // using a table allows for vertical alignment
31542 // 100% width is needed by Safari...
31543 this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
31544 this.tr = this.el.child("tr", true);
31546 this.items = new Roo.util.MixedCollection(false, function(o){
31547 return o.id || ("item" + (++autoId));
31550 this.add.apply(this, this.buttons);
31551 delete this.buttons;
31556 * Adds element(s) to the toolbar -- this function takes a variable number of
31557 * arguments of mixed type and adds them to the toolbar.
31558 * @param {Mixed} arg1 The following types of arguments are all valid:<br />
31560 * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
31561 * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
31562 * <li>Field: Any form field (equivalent to {@link #addField})</li>
31563 * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
31564 * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
31565 * Note that there are a few special strings that are treated differently as explained nRoo.</li>
31566 * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
31567 * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
31568 * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
31570 * @param {Mixed} arg2
31571 * @param {Mixed} etc.
31574 var a = arguments, l = a.length;
31575 for(var i = 0; i < l; i++){
31580 _add : function(el) {
31583 el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
31586 if (el.applyTo){ // some kind of form field
31587 return this.addField(el);
31589 if (el.render){ // some kind of Toolbar.Item
31590 return this.addItem(el);
31592 if (typeof el == "string"){ // string
31593 if(el == "separator" || el == "-"){
31594 return this.addSeparator();
31597 return this.addSpacer();
31600 return this.addFill();
31602 return this.addText(el);
31605 if(el.tagName){ // element
31606 return this.addElement(el);
31608 if(typeof el == "object"){ // must be button config?
31609 return this.addButton(el);
31611 // and now what?!?!
31617 * Add an Xtype element
31618 * @param {Object} xtype Xtype Object
31619 * @return {Object} created Object
31621 addxtype : function(e){
31622 return this.add(e);
31626 * Returns the Element for this toolbar.
31627 * @return {Roo.Element}
31629 getEl : function(){
31635 * @return {Roo.Toolbar.Item} The separator item
31637 addSeparator : function(){
31638 return this.addItem(new Roo.Toolbar.Separator());
31642 * Adds a spacer element
31643 * @return {Roo.Toolbar.Spacer} The spacer item
31645 addSpacer : function(){
31646 return this.addItem(new Roo.Toolbar.Spacer());
31650 * Adds a fill element that forces subsequent additions to the right side of the toolbar
31651 * @return {Roo.Toolbar.Fill} The fill item
31653 addFill : function(){
31654 return this.addItem(new Roo.Toolbar.Fill());
31658 * Adds any standard HTML element to the toolbar
31659 * @param {String/HTMLElement/Element} el The element or id of the element to add
31660 * @return {Roo.Toolbar.Item} The element's item
31662 addElement : function(el){
31663 return this.addItem(new Roo.Toolbar.Item(el));
31666 * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
31667 * @type Roo.util.MixedCollection
31672 * Adds any Toolbar.Item or subclass
31673 * @param {Roo.Toolbar.Item} item
31674 * @return {Roo.Toolbar.Item} The item
31676 addItem : function(item){
31677 var td = this.nextBlock();
31679 this.items.add(item);
31684 * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
31685 * @param {Object/Array} config A button config or array of configs
31686 * @return {Roo.Toolbar.Button/Array}
31688 addButton : function(config){
31689 if(config instanceof Array){
31691 for(var i = 0, len = config.length; i < len; i++) {
31692 buttons.push(this.addButton(config[i]));
31697 if(!(config instanceof Roo.Toolbar.Button)){
31699 new Roo.Toolbar.SplitButton(config) :
31700 new Roo.Toolbar.Button(config);
31702 var td = this.nextBlock();
31709 * Adds text to the toolbar
31710 * @param {String} text The text to add
31711 * @return {Roo.Toolbar.Item} The element's item
31713 addText : function(text){
31714 return this.addItem(new Roo.Toolbar.TextItem(text));
31718 * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
31719 * @param {Number} index The index where the item is to be inserted
31720 * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
31721 * @return {Roo.Toolbar.Button/Item}
31723 insertButton : function(index, item){
31724 if(item instanceof Array){
31726 for(var i = 0, len = item.length; i < len; i++) {
31727 buttons.push(this.insertButton(index + i, item[i]));
31731 if (!(item instanceof Roo.Toolbar.Button)){
31732 item = new Roo.Toolbar.Button(item);
31734 var td = document.createElement("td");
31735 this.tr.insertBefore(td, this.tr.childNodes[index]);
31737 this.items.insert(index, item);
31742 * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
31743 * @param {Object} config
31744 * @return {Roo.Toolbar.Item} The element's item
31746 addDom : function(config, returnEl){
31747 var td = this.nextBlock();
31748 Roo.DomHelper.overwrite(td, config);
31749 var ti = new Roo.Toolbar.Item(td.firstChild);
31751 this.items.add(ti);
31756 * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
31757 * @type Roo.util.MixedCollection
31762 * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
31763 * Note: the field should not have been rendered yet. For a field that has already been
31764 * rendered, use {@link #addElement}.
31765 * @param {Roo.form.Field} field
31766 * @return {Roo.ToolbarItem}
31770 addField : function(field) {
31771 if (!this.fields) {
31773 this.fields = new Roo.util.MixedCollection(false, function(o){
31774 return o.id || ("item" + (++autoId));
31779 var td = this.nextBlock();
31781 var ti = new Roo.Toolbar.Item(td.firstChild);
31783 this.items.add(ti);
31784 this.fields.add(field);
31795 this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
31796 this.el.child('div').hide();
31804 this.el.child('div').show();
31808 nextBlock : function(){
31809 var td = document.createElement("td");
31810 this.tr.appendChild(td);
31815 destroy : function(){
31816 if(this.items){ // rendered?
31817 Roo.destroy.apply(Roo, this.items.items);
31819 if(this.fields){ // rendered?
31820 Roo.destroy.apply(Roo, this.fields.items);
31822 Roo.Element.uncache(this.el, this.tr);
31827 * @class Roo.Toolbar.Item
31828 * The base class that other classes should extend in order to get some basic common toolbar item functionality.
31830 * Creates a new Item
31831 * @param {HTMLElement} el
31833 Roo.Toolbar.Item = function(el){
31835 if (typeof (el.xtype) != 'undefined') {
31840 this.el = Roo.getDom(el);
31841 this.id = Roo.id(this.el);
31842 this.hidden = false;
31847 * Fires when the button is rendered
31848 * @param {Button} this
31852 Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
31854 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
31855 //Roo.Toolbar.Item.prototype = {
31858 * Get this item's HTML Element
31859 * @return {HTMLElement}
31861 getEl : function(){
31866 render : function(td){
31869 td.appendChild(this.el);
31871 this.fireEvent('render', this);
31875 * Removes and destroys this item.
31877 destroy : function(){
31878 this.td.parentNode.removeChild(this.td);
31885 this.hidden = false;
31886 this.td.style.display = "";
31893 this.hidden = true;
31894 this.td.style.display = "none";
31898 * Convenience function for boolean show/hide.
31899 * @param {Boolean} visible true to show/false to hide
31901 setVisible: function(visible){
31910 * Try to focus this item.
31912 focus : function(){
31913 Roo.fly(this.el).focus();
31917 * Disables this item.
31919 disable : function(){
31920 Roo.fly(this.td).addClass("x-item-disabled");
31921 this.disabled = true;
31922 this.el.disabled = true;
31926 * Enables this item.
31928 enable : function(){
31929 Roo.fly(this.td).removeClass("x-item-disabled");
31930 this.disabled = false;
31931 this.el.disabled = false;
31937 * @class Roo.Toolbar.Separator
31938 * @extends Roo.Toolbar.Item
31939 * A simple toolbar separator class
31941 * Creates a new Separator
31943 Roo.Toolbar.Separator = function(cfg){
31945 var s = document.createElement("span");
31946 s.className = "ytb-sep";
31951 Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
31953 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
31954 enable:Roo.emptyFn,
31955 disable:Roo.emptyFn,
31960 * @class Roo.Toolbar.Spacer
31961 * @extends Roo.Toolbar.Item
31962 * A simple element that adds extra horizontal space to a toolbar.
31964 * Creates a new Spacer
31966 Roo.Toolbar.Spacer = function(cfg){
31967 var s = document.createElement("div");
31968 s.className = "ytb-spacer";
31972 Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
31974 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
31975 enable:Roo.emptyFn,
31976 disable:Roo.emptyFn,
31981 * @class Roo.Toolbar.Fill
31982 * @extends Roo.Toolbar.Spacer
31983 * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
31985 * Creates a new Spacer
31987 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
31989 render : function(td){
31990 td.style.width = '100%';
31991 Roo.Toolbar.Fill.superclass.render.call(this, td);
31996 * @class Roo.Toolbar.TextItem
31997 * @extends Roo.Toolbar.Item
31998 * A simple class that renders text directly into a toolbar.
32000 * Creates a new TextItem
32001 * @cfg {string} text
32003 Roo.Toolbar.TextItem = function(cfg){
32004 var text = cfg || "";
32005 if (typeof(cfg) == 'object') {
32006 text = cfg.text || "";
32010 var s = document.createElement("span");
32011 s.className = "ytb-text";
32012 s.innerHTML = text;
32017 Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg || s);
32019 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
32022 enable:Roo.emptyFn,
32023 disable:Roo.emptyFn,
32026 * Shows this button
32029 this.hidden = false;
32030 this.el.style.display = "";
32034 * Hides this button
32037 this.hidden = true;
32038 this.el.style.display = "none";
32044 * @class Roo.Toolbar.Button
32045 * @extends Roo.Button
32046 * A button that renders into a toolbar.
32048 * Creates a new Button
32049 * @param {Object} config A standard {@link Roo.Button} config object
32051 Roo.Toolbar.Button = function(config){
32052 Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
32054 Roo.extend(Roo.Toolbar.Button, Roo.Button,
32058 render : function(td){
32060 Roo.Toolbar.Button.superclass.render.call(this, td);
32064 * Removes and destroys this button
32066 destroy : function(){
32067 Roo.Toolbar.Button.superclass.destroy.call(this);
32068 this.td.parentNode.removeChild(this.td);
32072 * Shows this button
32075 this.hidden = false;
32076 this.td.style.display = "";
32080 * Hides this button
32083 this.hidden = true;
32084 this.td.style.display = "none";
32088 * Disables this item
32090 disable : function(){
32091 Roo.fly(this.td).addClass("x-item-disabled");
32092 this.disabled = true;
32096 * Enables this item
32098 enable : function(){
32099 Roo.fly(this.td).removeClass("x-item-disabled");
32100 this.disabled = false;
32103 // backwards compat
32104 Roo.ToolbarButton = Roo.Toolbar.Button;
32107 * @class Roo.Toolbar.SplitButton
32108 * @extends Roo.SplitButton
32109 * A menu button that renders into a toolbar.
32111 * Creates a new SplitButton
32112 * @param {Object} config A standard {@link Roo.SplitButton} config object
32114 Roo.Toolbar.SplitButton = function(config){
32115 Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
32117 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
32118 render : function(td){
32120 Roo.Toolbar.SplitButton.superclass.render.call(this, td);
32124 * Removes and destroys this button
32126 destroy : function(){
32127 Roo.Toolbar.SplitButton.superclass.destroy.call(this);
32128 this.td.parentNode.removeChild(this.td);
32132 * Shows this button
32135 this.hidden = false;
32136 this.td.style.display = "";
32140 * Hides this button
32143 this.hidden = true;
32144 this.td.style.display = "none";
32148 // backwards compat
32149 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
32151 * Ext JS Library 1.1.1
32152 * Copyright(c) 2006-2007, Ext JS, LLC.
32154 * Originally Released Under LGPL - original licence link has changed is not relivant.
32157 * <script type="text/javascript">
32161 * @class Roo.PagingToolbar
32162 * @extends Roo.Toolbar
32163 * @children Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
32164 * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
32166 * Create a new PagingToolbar
32167 * @param {Object} config The config object
32169 Roo.PagingToolbar = function(el, ds, config)
32171 // old args format still supported... - xtype is prefered..
32172 if (typeof(el) == 'object' && el.xtype) {
32173 // created from xtype...
32175 ds = el.dataSource;
32176 el = config.container;
32179 if (config.items) {
32180 items = config.items;
32184 Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
32187 this.renderButtons(this.el);
32190 // supprot items array.
32192 Roo.each(items, function(e) {
32193 this.add(Roo.factory(e));
32198 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
32201 * @cfg {String/HTMLElement/Element} container
32202 * container The id or element that will contain the toolbar
32205 * @cfg {Boolean} displayInfo
32206 * True to display the displayMsg (defaults to false)
32211 * @cfg {Number} pageSize
32212 * The number of records to display per page (defaults to 20)
32216 * @cfg {String} displayMsg
32217 * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
32219 displayMsg : 'Displaying {0} - {1} of {2}',
32221 * @cfg {String} emptyMsg
32222 * The message to display when no records are found (defaults to "No data to display")
32224 emptyMsg : 'No data to display',
32226 * Customizable piece of the default paging text (defaults to "Page")
32229 beforePageText : "Page",
32231 * Customizable piece of the default paging text (defaults to "of %0")
32234 afterPageText : "of {0}",
32236 * Customizable piece of the default paging text (defaults to "First Page")
32239 firstText : "First Page",
32241 * Customizable piece of the default paging text (defaults to "Previous Page")
32244 prevText : "Previous Page",
32246 * Customizable piece of the default paging text (defaults to "Next Page")
32249 nextText : "Next Page",
32251 * Customizable piece of the default paging text (defaults to "Last Page")
32254 lastText : "Last Page",
32256 * Customizable piece of the default paging text (defaults to "Refresh")
32259 refreshText : "Refresh",
32262 renderButtons : function(el){
32263 Roo.PagingToolbar.superclass.render.call(this, el);
32264 this.first = this.addButton({
32265 tooltip: this.firstText,
32266 cls: "x-btn-icon x-grid-page-first",
32268 handler: this.onClick.createDelegate(this, ["first"])
32270 this.prev = this.addButton({
32271 tooltip: this.prevText,
32272 cls: "x-btn-icon x-grid-page-prev",
32274 handler: this.onClick.createDelegate(this, ["prev"])
32276 //this.addSeparator();
32277 this.add(this.beforePageText);
32278 this.field = Roo.get(this.addDom({
32283 cls: "x-grid-page-number"
32285 this.field.on("keydown", this.onPagingKeydown, this);
32286 this.field.on("focus", function(){this.dom.select();});
32287 this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
32288 this.field.setHeight(18);
32289 //this.addSeparator();
32290 this.next = this.addButton({
32291 tooltip: this.nextText,
32292 cls: "x-btn-icon x-grid-page-next",
32294 handler: this.onClick.createDelegate(this, ["next"])
32296 this.last = this.addButton({
32297 tooltip: this.lastText,
32298 cls: "x-btn-icon x-grid-page-last",
32300 handler: this.onClick.createDelegate(this, ["last"])
32302 //this.addSeparator();
32303 this.loading = this.addButton({
32304 tooltip: this.refreshText,
32305 cls: "x-btn-icon x-grid-loading",
32306 handler: this.onClick.createDelegate(this, ["refresh"])
32309 if(this.displayInfo){
32310 this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
32315 updateInfo : function(){
32316 if(this.displayEl){
32317 var count = this.ds.getCount();
32318 var msg = count == 0 ?
32322 this.cursor+1, this.cursor+count, this.ds.getTotalCount()
32324 this.displayEl.update(msg);
32329 onLoad : function(ds, r, o){
32330 this.cursor = o.params ? o.params.start : 0;
32331 var d = this.getPageData(), ap = d.activePage, ps = d.pages;
32333 this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
32334 this.field.dom.value = ap;
32335 this.first.setDisabled(ap == 1);
32336 this.prev.setDisabled(ap == 1);
32337 this.next.setDisabled(ap == ps);
32338 this.last.setDisabled(ap == ps);
32339 this.loading.enable();
32344 getPageData : function(){
32345 var total = this.ds.getTotalCount();
32348 activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
32349 pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
32354 onLoadError : function(){
32355 this.loading.enable();
32359 onPagingKeydown : function(e){
32360 var k = e.getKey();
32361 var d = this.getPageData();
32363 var v = this.field.dom.value, pageNum;
32364 if(!v || isNaN(pageNum = parseInt(v, 10))){
32365 this.field.dom.value = d.activePage;
32368 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
32369 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
32372 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))
32374 var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
32375 this.field.dom.value = pageNum;
32376 this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
32379 else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
32381 var v = this.field.dom.value, pageNum;
32382 var increment = (e.shiftKey) ? 10 : 1;
32383 if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
32386 if(!v || isNaN(pageNum = parseInt(v, 10))) {
32387 this.field.dom.value = d.activePage;
32390 else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
32392 this.field.dom.value = parseInt(v, 10) + increment;
32393 pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
32394 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
32401 beforeLoad : function(){
32403 this.loading.disable();
32408 onClick : function(which){
32412 ds.load({params:{start: 0, limit: this.pageSize}});
32415 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
32418 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
32421 var total = ds.getTotalCount();
32422 var extra = total % this.pageSize;
32423 var lastStart = extra ? (total - extra) : total-this.pageSize;
32424 ds.load({params:{start: lastStart, limit: this.pageSize}});
32427 ds.load({params:{start: this.cursor, limit: this.pageSize}});
32433 * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
32434 * @param {Roo.data.Store} store The data store to unbind
32436 unbind : function(ds){
32437 ds.un("beforeload", this.beforeLoad, this);
32438 ds.un("load", this.onLoad, this);
32439 ds.un("loadexception", this.onLoadError, this);
32440 ds.un("remove", this.updateInfo, this);
32441 ds.un("add", this.updateInfo, this);
32442 this.ds = undefined;
32446 * Binds the paging toolbar to the specified {@link Roo.data.Store}
32447 * @param {Roo.data.Store} store The data store to bind
32449 bind : function(ds){
32450 ds.on("beforeload", this.beforeLoad, this);
32451 ds.on("load", this.onLoad, this);
32452 ds.on("loadexception", this.onLoadError, this);
32453 ds.on("remove", this.updateInfo, this);
32454 ds.on("add", this.updateInfo, this);
32459 * Ext JS Library 1.1.1
32460 * Copyright(c) 2006-2007, Ext JS, LLC.
32462 * Originally Released Under LGPL - original licence link has changed is not relivant.
32465 * <script type="text/javascript">
32469 * @class Roo.Resizable
32470 * @extends Roo.util.Observable
32471 * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
32472 * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
32473 * 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
32474 * the element will be wrapped for you automatically.</p>
32475 * <p>Here is the list of valid resize handles:</p>
32478 ------ -------------------
32487 'hd' horizontal drag
32490 * <p>Here's an example showing the creation of a typical Resizable:</p>
32492 var resizer = new Roo.Resizable("element-id", {
32500 resizer.on("resize", myHandler);
32502 * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
32503 * resizer.east.setDisplayed(false);</p>
32504 * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
32505 * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
32506 * resize operation's new size (defaults to [0, 0])
32507 * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
32508 * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
32509 * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
32510 * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
32511 * @cfg {Boolean} enabled False to disable resizing (defaults to true)
32512 * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
32513 * @cfg {Number} width The width of the element in pixels (defaults to null)
32514 * @cfg {Number} height The height of the element in pixels (defaults to null)
32515 * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
32516 * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
32517 * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
32518 * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
32519 * @cfg {Boolean} multiDirectional <b>Deprecated</b>. The old style of adding multi-direction resize handles, deprecated
32520 * in favor of the handles config option (defaults to false)
32521 * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
32522 * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
32523 * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
32524 * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
32525 * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
32526 * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
32527 * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
32528 * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
32529 * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
32530 * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
32531 * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
32533 * Create a new resizable component
32534 * @param {String/HTMLElement/Roo.Element} el The id or element to resize
32535 * @param {Object} config configuration options
32537 Roo.Resizable = function(el, config)
32539 this.el = Roo.get(el);
32541 if(config && config.wrap){
32542 config.resizeChild = this.el;
32543 this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
32544 this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
32545 this.el.setStyle("overflow", "hidden");
32546 this.el.setPositioning(config.resizeChild.getPositioning());
32547 config.resizeChild.clearPositioning();
32548 if(!config.width || !config.height){
32549 var csize = config.resizeChild.getSize();
32550 this.el.setSize(csize.width, csize.height);
32552 if(config.pinned && !config.adjustments){
32553 config.adjustments = "auto";
32557 this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
32558 this.proxy.unselectable();
32559 this.proxy.enableDisplayMode('block');
32561 Roo.apply(this, config);
32564 this.disableTrackOver = true;
32565 this.el.addClass("x-resizable-pinned");
32567 // if the element isn't positioned, make it relative
32568 var position = this.el.getStyle("position");
32569 if(position != "absolute" && position != "fixed"){
32570 this.el.setStyle("position", "relative");
32572 if(!this.handles){ // no handles passed, must be legacy style
32573 this.handles = 's,e,se';
32574 if(this.multiDirectional){
32575 this.handles += ',n,w';
32578 if(this.handles == "all"){
32579 this.handles = "n s e w ne nw se sw";
32581 var hs = this.handles.split(/\s*?[,;]\s*?| /);
32582 var ps = Roo.Resizable.positions;
32583 for(var i = 0, len = hs.length; i < len; i++){
32584 if(hs[i] && ps[hs[i]]){
32585 var pos = ps[hs[i]];
32586 this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
32590 this.corner = this.southeast;
32592 // updateBox = the box can move..
32593 if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
32594 this.updateBox = true;
32597 this.activeHandle = null;
32599 if(this.resizeChild){
32600 if(typeof this.resizeChild == "boolean"){
32601 this.resizeChild = Roo.get(this.el.dom.firstChild, true);
32603 this.resizeChild = Roo.get(this.resizeChild, true);
32607 if(this.adjustments == "auto"){
32608 var rc = this.resizeChild;
32609 var hw = this.west, he = this.east, hn = this.north, hs = this.south;
32610 if(rc && (hw || hn)){
32611 rc.position("relative");
32612 rc.setLeft(hw ? hw.el.getWidth() : 0);
32613 rc.setTop(hn ? hn.el.getHeight() : 0);
32615 this.adjustments = [
32616 (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
32617 (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
32621 if(this.draggable){
32622 this.dd = this.dynamic ?
32623 this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
32624 this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
32630 * @event beforeresize
32631 * Fired before resize is allowed. Set enabled to false to cancel resize.
32632 * @param {Roo.Resizable} this
32633 * @param {Roo.EventObject} e The mousedown event
32635 "beforeresize" : true,
32638 * Fired a resizing.
32639 * @param {Roo.Resizable} this
32640 * @param {Number} x The new x position
32641 * @param {Number} y The new y position
32642 * @param {Number} w The new w width
32643 * @param {Number} h The new h hight
32644 * @param {Roo.EventObject} e The mouseup event
32649 * Fired after a resize.
32650 * @param {Roo.Resizable} this
32651 * @param {Number} width The new width
32652 * @param {Number} height The new height
32653 * @param {Roo.EventObject} e The mouseup event
32658 if(this.width !== null && this.height !== null){
32659 this.resizeTo(this.width, this.height);
32661 this.updateChildSize();
32664 this.el.dom.style.zoom = 1;
32666 Roo.Resizable.superclass.constructor.call(this);
32669 Roo.extend(Roo.Resizable, Roo.util.Observable, {
32670 resizeChild : false,
32671 adjustments : [0, 0],
32681 multiDirectional : false,
32682 disableTrackOver : false,
32683 easing : 'easeOutStrong',
32684 widthIncrement : 0,
32685 heightIncrement : 0,
32689 preserveRatio : false,
32690 transparent: false,
32696 * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
32698 constrainTo: undefined,
32700 * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
32702 resizeRegion: undefined,
32706 * Perform a manual resize
32707 * @param {Number} width
32708 * @param {Number} height
32710 resizeTo : function(width, height){
32711 this.el.setSize(width, height);
32712 this.updateChildSize();
32713 this.fireEvent("resize", this, width, height, null);
32717 startSizing : function(e, handle){
32718 this.fireEvent("beforeresize", this, e);
32719 if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
32722 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: " "});
32723 this.overlay.unselectable();
32724 this.overlay.enableDisplayMode("block");
32725 this.overlay.on("mousemove", this.onMouseMove, this);
32726 this.overlay.on("mouseup", this.onMouseUp, this);
32728 this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
32730 this.resizing = true;
32731 this.startBox = this.el.getBox();
32732 this.startPoint = e.getXY();
32733 this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
32734 (this.startBox.y + this.startBox.height) - this.startPoint[1]];
32736 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
32737 this.overlay.show();
32739 if(this.constrainTo) {
32740 var ct = Roo.get(this.constrainTo);
32741 this.resizeRegion = ct.getRegion().adjust(
32742 ct.getFrameWidth('t'),
32743 ct.getFrameWidth('l'),
32744 -ct.getFrameWidth('b'),
32745 -ct.getFrameWidth('r')
32749 this.proxy.setStyle('visibility', 'hidden'); // workaround display none
32751 this.proxy.setBox(this.startBox);
32753 this.proxy.setStyle('visibility', 'visible');
32759 onMouseDown : function(handle, e){
32762 this.activeHandle = handle;
32763 this.startSizing(e, handle);
32768 onMouseUp : function(e){
32769 var size = this.resizeElement();
32770 this.resizing = false;
32772 this.overlay.hide();
32774 this.fireEvent("resize", this, size.width, size.height, e);
32778 updateChildSize : function(){
32780 if(this.resizeChild){
32782 var child = this.resizeChild;
32783 var adj = this.adjustments;
32784 if(el.dom.offsetWidth){
32785 var b = el.getSize(true);
32786 child.setSize(b.width+adj[0], b.height+adj[1]);
32788 // Second call here for IE
32789 // The first call enables instant resizing and
32790 // the second call corrects scroll bars if they
32793 setTimeout(function(){
32794 if(el.dom.offsetWidth){
32795 var b = el.getSize(true);
32796 child.setSize(b.width+adj[0], b.height+adj[1]);
32804 snap : function(value, inc, min){
32805 if(!inc || !value) {
32808 var newValue = value;
32809 var m = value % inc;
32812 newValue = value + (inc-m);
32814 newValue = value - m;
32817 return Math.max(min, newValue);
32821 resizeElement : function(){
32822 var box = this.proxy.getBox();
32823 if(this.updateBox){
32824 this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
32826 this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
32828 this.updateChildSize();
32836 constrain : function(v, diff, m, mx){
32839 }else if(v - diff > mx){
32846 onMouseMove : function(e){
32849 try{// try catch so if something goes wrong the user doesn't get hung
32851 if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
32855 //var curXY = this.startPoint;
32856 var curSize = this.curSize || this.startBox;
32857 var x = this.startBox.x, y = this.startBox.y;
32858 var ox = x, oy = y;
32859 var w = curSize.width, h = curSize.height;
32860 var ow = w, oh = h;
32861 var mw = this.minWidth, mh = this.minHeight;
32862 var mxw = this.maxWidth, mxh = this.maxHeight;
32863 var wi = this.widthIncrement;
32864 var hi = this.heightIncrement;
32866 var eventXY = e.getXY();
32867 var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
32868 var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
32870 var pos = this.activeHandle.position;
32875 w = Math.min(Math.max(mw, w), mxw);
32880 h = Math.min(Math.max(mh, h), mxh);
32885 w = Math.min(Math.max(mw, w), mxw);
32886 h = Math.min(Math.max(mh, h), mxh);
32889 diffY = this.constrain(h, diffY, mh, mxh);
32896 var adiffX = Math.abs(diffX);
32897 var sub = (adiffX % wi); // how much
32898 if (sub > (wi/2)) { // far enough to snap
32899 diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
32901 // remove difference..
32902 diffX = (diffX > 0) ? diffX-sub : diffX+sub;
32906 x = Math.max(this.minX, x);
32909 diffX = this.constrain(w, diffX, mw, mxw);
32915 w = Math.min(Math.max(mw, w), mxw);
32916 diffY = this.constrain(h, diffY, mh, mxh);
32921 diffX = this.constrain(w, diffX, mw, mxw);
32922 diffY = this.constrain(h, diffY, mh, mxh);
32929 diffX = this.constrain(w, diffX, mw, mxw);
32931 h = Math.min(Math.max(mh, h), mxh);
32937 var sw = this.snap(w, wi, mw);
32938 var sh = this.snap(h, hi, mh);
32939 if(sw != w || sh != h){
32962 if(this.preserveRatio){
32967 h = Math.min(Math.max(mh, h), mxh);
32972 w = Math.min(Math.max(mw, w), mxw);
32977 w = Math.min(Math.max(mw, w), mxw);
32983 w = Math.min(Math.max(mw, w), mxw);
32989 h = Math.min(Math.max(mh, h), mxh);
32997 h = Math.min(Math.max(mh, h), mxh);
33007 h = Math.min(Math.max(mh, h), mxh);
33015 if (pos == 'hdrag') {
33018 this.proxy.setBounds(x, y, w, h);
33020 this.resizeElement();
33024 this.fireEvent("resizing", this, x, y, w, h, e);
33028 handleOver : function(){
33030 this.el.addClass("x-resizable-over");
33035 handleOut : function(){
33036 if(!this.resizing){
33037 this.el.removeClass("x-resizable-over");
33042 * Returns the element this component is bound to.
33043 * @return {Roo.Element}
33045 getEl : function(){
33050 * Returns the resizeChild element (or null).
33051 * @return {Roo.Element}
33053 getResizeChild : function(){
33054 return this.resizeChild;
33056 groupHandler : function()
33061 * Destroys this resizable. If the element was wrapped and
33062 * removeEl is not true then the element remains.
33063 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
33065 destroy : function(removeEl){
33066 this.proxy.remove();
33068 this.overlay.removeAllListeners();
33069 this.overlay.remove();
33071 var ps = Roo.Resizable.positions;
33073 if(typeof ps[k] != "function" && this[ps[k]]){
33074 var h = this[ps[k]];
33075 h.el.removeAllListeners();
33080 this.el.update("");
33087 // hash to map config positions to true positions
33088 Roo.Resizable.positions = {
33089 n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast",
33094 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
33096 // only initialize the template if resizable is used
33097 var tpl = Roo.DomHelper.createTemplate(
33098 {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
33101 Roo.Resizable.Handle.prototype.tpl = tpl;
33103 this.position = pos;
33105 // show north drag fro topdra
33106 var handlepos = pos == 'hdrag' ? 'north' : pos;
33108 this.el = this.tpl.append(rz.el.dom, [handlepos], true);
33109 if (pos == 'hdrag') {
33110 this.el.setStyle('cursor', 'pointer');
33112 this.el.unselectable();
33114 this.el.setOpacity(0);
33116 this.el.on("mousedown", this.onMouseDown, this);
33117 if(!disableTrackOver){
33118 this.el.on("mouseover", this.onMouseOver, this);
33119 this.el.on("mouseout", this.onMouseOut, this);
33124 Roo.Resizable.Handle.prototype = {
33125 afterResize : function(rz){
33130 onMouseDown : function(e){
33131 this.rz.onMouseDown(this, e);
33134 onMouseOver : function(e){
33135 this.rz.handleOver(this, e);
33138 onMouseOut : function(e){
33139 this.rz.handleOut(this, e);
33143 * Ext JS Library 1.1.1
33144 * Copyright(c) 2006-2007, Ext JS, LLC.
33146 * Originally Released Under LGPL - original licence link has changed is not relivant.
33149 * <script type="text/javascript">
33153 * @class Roo.Editor
33154 * @extends Roo.Component
33155 * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
33157 * Create a new Editor
33158 * @param {Roo.form.Field} field The Field object (or descendant)
33159 * @param {Object} config The config object
33161 Roo.Editor = function(field, config){
33162 Roo.Editor.superclass.constructor.call(this, config);
33163 this.field = field;
33166 * @event beforestartedit
33167 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
33168 * false from the handler of this event.
33169 * @param {Editor} this
33170 * @param {Roo.Element} boundEl The underlying element bound to this editor
33171 * @param {Mixed} value The field value being set
33173 "beforestartedit" : true,
33176 * Fires when this editor is displayed
33177 * @param {Roo.Element} boundEl The underlying element bound to this editor
33178 * @param {Mixed} value The starting field value
33180 "startedit" : true,
33182 * @event beforecomplete
33183 * Fires after a change has been made to the field, but before the change is reflected in the underlying
33184 * field. Saving the change to the field can be canceled by returning false from the handler of this event.
33185 * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
33186 * event will not fire since no edit actually occurred.
33187 * @param {Editor} this
33188 * @param {Mixed} value The current field value
33189 * @param {Mixed} startValue The original field value
33191 "beforecomplete" : true,
33194 * Fires after editing is complete and any changed value has been written to the underlying field.
33195 * @param {Editor} this
33196 * @param {Mixed} value The current field value
33197 * @param {Mixed} startValue The original field value
33201 * @event specialkey
33202 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
33203 * {@link Roo.EventObject#getKey} to determine which key was pressed.
33204 * @param {Roo.form.Field} this
33205 * @param {Roo.EventObject} e The event object
33207 "specialkey" : true
33211 Roo.extend(Roo.Editor, Roo.Component, {
33213 * @cfg {Boolean/String} autosize
33214 * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
33215 * or "height" to adopt the height only (defaults to false)
33218 * @cfg {Boolean} revertInvalid
33219 * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
33220 * validation fails (defaults to true)
33223 * @cfg {Boolean} ignoreNoChange
33224 * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
33225 * the value has not changed (defaults to false). Applies only to string values - edits for other data types
33226 * will never be ignored.
33229 * @cfg {Boolean} hideEl
33230 * False to keep the bound element visible while the editor is displayed (defaults to true)
33233 * @cfg {Mixed} value
33234 * The data value of the underlying field (defaults to "")
33238 * @cfg {String} alignment
33239 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
33243 * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
33244 * for bottom-right shadow (defaults to "frame")
33248 * @cfg {Boolean} constrain True to constrain the editor to the viewport
33252 * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
33254 completeOnEnter : false,
33256 * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
33258 cancelOnEsc : false,
33260 * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
33265 onRender : function(ct, position){
33266 this.el = new Roo.Layer({
33267 shadow: this.shadow,
33273 constrain: this.constrain
33275 this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
33276 if(this.field.msgTarget != 'title'){
33277 this.field.msgTarget = 'qtip';
33279 this.field.render(this.el);
33281 this.field.el.dom.setAttribute('autocomplete', 'off');
33283 this.field.on("specialkey", this.onSpecialKey, this);
33284 if(this.swallowKeys){
33285 this.field.el.swallowEvent(['keydown','keypress']);
33288 this.field.on("blur", this.onBlur, this);
33289 if(this.field.grow){
33290 this.field.on("autosize", this.el.sync, this.el, {delay:1});
33294 onSpecialKey : function(field, e)
33296 //Roo.log('editor onSpecialKey');
33297 if(this.completeOnEnter && e.getKey() == e.ENTER){
33299 this.completeEdit();
33302 // do not fire special key otherwise it might hide close the editor...
33303 if(e.getKey() == e.ENTER){
33306 if(this.cancelOnEsc && e.getKey() == e.ESC){
33310 this.fireEvent('specialkey', field, e);
33315 * Starts the editing process and shows the editor.
33316 * @param {String/HTMLElement/Element} el The element to edit
33317 * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
33318 * to the innerHTML of el.
33320 startEdit : function(el, value){
33322 this.completeEdit();
33324 this.boundEl = Roo.get(el);
33325 var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
33326 if(!this.rendered){
33327 this.render(this.parentEl || document.body);
33329 if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
33332 this.startValue = v;
33333 this.field.setValue(v);
33335 var sz = this.boundEl.getSize();
33336 switch(this.autoSize){
33338 this.setSize(sz.width, "");
33341 this.setSize("", sz.height);
33344 this.setSize(sz.width, sz.height);
33347 this.el.alignTo(this.boundEl, this.alignment);
33348 this.editing = true;
33350 Roo.QuickTips.disable();
33356 * Sets the height and width of this editor.
33357 * @param {Number} width The new width
33358 * @param {Number} height The new height
33360 setSize : function(w, h){
33361 this.field.setSize(w, h);
33368 * Realigns the editor to the bound field based on the current alignment config value.
33370 realign : function(){
33371 this.el.alignTo(this.boundEl, this.alignment);
33375 * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
33376 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
33378 completeEdit : function(remainVisible){
33382 var v = this.getValue();
33383 if(this.revertInvalid !== false && !this.field.isValid()){
33384 v = this.startValue;
33385 this.cancelEdit(true);
33387 if(String(v) === String(this.startValue) && this.ignoreNoChange){
33388 this.editing = false;
33392 if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
33393 this.editing = false;
33394 if(this.updateEl && this.boundEl){
33395 this.boundEl.update(v);
33397 if(remainVisible !== true){
33400 this.fireEvent("complete", this, v, this.startValue);
33405 onShow : function(){
33407 if(this.hideEl !== false){
33408 this.boundEl.hide();
33411 if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
33412 this.fixIEFocus = true;
33413 this.deferredFocus.defer(50, this);
33415 this.field.focus();
33417 this.fireEvent("startedit", this.boundEl, this.startValue);
33420 deferredFocus : function(){
33422 this.field.focus();
33427 * Cancels the editing process and hides the editor without persisting any changes. The field value will be
33428 * reverted to the original starting value.
33429 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
33430 * cancel (defaults to false)
33432 cancelEdit : function(remainVisible){
33434 this.setValue(this.startValue);
33435 if(remainVisible !== true){
33442 onBlur : function(){
33443 if(this.allowBlur !== true && this.editing){
33444 this.completeEdit();
33449 onHide : function(){
33451 this.completeEdit();
33455 if(this.field.collapse){
33456 this.field.collapse();
33459 if(this.hideEl !== false){
33460 this.boundEl.show();
33463 Roo.QuickTips.enable();
33468 * Sets the data value of the editor
33469 * @param {Mixed} value Any valid value supported by the underlying field
33471 setValue : function(v){
33472 this.field.setValue(v);
33476 * Gets the data value of the editor
33477 * @return {Mixed} The data value
33479 getValue : function(){
33480 return this.field.getValue();
33484 * Ext JS Library 1.1.1
33485 * Copyright(c) 2006-2007, Ext JS, LLC.
33487 * Originally Released Under LGPL - original licence link has changed is not relivant.
33490 * <script type="text/javascript">
33494 * @class Roo.BasicDialog
33495 * @extends Roo.util.Observable
33496 * @parent none builder
33497 * Lightweight Dialog Class. The code below shows the creation of a typical dialog using existing HTML markup:
33499 var dlg = new Roo.BasicDialog("my-dlg", {
33508 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
33509 dlg.addButton('OK', dlg.hide, dlg); // Could call a save function instead of hiding
33510 dlg.addButton('Cancel', dlg.hide, dlg);
33513 <b>A Dialog should always be a direct child of the body element.</b>
33514 * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
33515 * @cfg {String} title Default text to display in the title bar (defaults to null)
33516 * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
33517 * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
33518 * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
33519 * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
33520 * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
33521 * (defaults to null with no animation)
33522 * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
33523 * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
33524 * property for valid values (defaults to 'all')
33525 * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
33526 * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
33527 * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
33528 * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
33529 * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
33530 * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
33531 * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
33532 * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
33533 * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
33534 * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
33535 * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
33536 * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
33537 * draggable = true (defaults to false)
33538 * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
33539 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
33540 * shadow (defaults to false)
33541 * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
33542 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
33543 * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
33544 * @cfg {Array} buttons Array of buttons
33545 * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
33547 * Create a new BasicDialog.
33548 * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
33549 * @param {Object} config Configuration options
33551 Roo.BasicDialog = function(el, config){
33552 this.el = Roo.get(el);
33553 var dh = Roo.DomHelper;
33554 if(!this.el && config && config.autoCreate){
33555 if(typeof config.autoCreate == "object"){
33556 if(!config.autoCreate.id){
33557 config.autoCreate.id = el;
33559 this.el = dh.append(document.body,
33560 config.autoCreate, true);
33562 this.el = dh.append(document.body,
33563 {tag: "div", id: el, style:'visibility:hidden;'}, true);
33567 el.setDisplayed(true);
33568 el.hide = this.hideAction;
33570 el.addClass("x-dlg");
33572 Roo.apply(this, config);
33574 this.proxy = el.createProxy("x-dlg-proxy");
33575 this.proxy.hide = this.hideAction;
33576 this.proxy.setOpacity(.5);
33580 el.setWidth(config.width);
33583 el.setHeight(config.height);
33585 this.size = el.getSize();
33586 if(typeof config.x != "undefined" && typeof config.y != "undefined"){
33587 this.xy = [config.x,config.y];
33589 this.xy = el.getCenterXY(true);
33591 /** The header element @type Roo.Element */
33592 this.header = el.child("> .x-dlg-hd");
33593 /** The body element @type Roo.Element */
33594 this.body = el.child("> .x-dlg-bd");
33595 /** The footer element @type Roo.Element */
33596 this.footer = el.child("> .x-dlg-ft");
33599 this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
33602 this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
33605 this.header.unselectable();
33607 this.header.update(this.title);
33609 // this element allows the dialog to be focused for keyboard event
33610 this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
33611 this.focusEl.swallowEvent("click", true);
33613 this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
33615 // wrap the body and footer for special rendering
33616 this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
33618 this.bwrap.dom.appendChild(this.footer.dom);
33621 this.bg = this.el.createChild({
33622 tag: "div", cls:"x-dlg-bg",
33623 html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
33625 this.centerBg = this.bg.child("div.x-dlg-bg-center");
33628 if(this.autoScroll !== false && !this.autoTabs){
33629 this.body.setStyle("overflow", "auto");
33632 this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
33634 if(this.closable !== false){
33635 this.el.addClass("x-dlg-closable");
33636 this.close = this.toolbox.createChild({cls:"x-dlg-close"});
33637 this.close.on("click", this.closeClick, this);
33638 this.close.addClassOnOver("x-dlg-close-over");
33640 if(this.collapsible !== false){
33641 this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
33642 this.collapseBtn.on("click", this.collapseClick, this);
33643 this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
33644 this.header.on("dblclick", this.collapseClick, this);
33646 if(this.resizable !== false){
33647 this.el.addClass("x-dlg-resizable");
33648 this.resizer = new Roo.Resizable(el, {
33649 minWidth: this.minWidth || 80,
33650 minHeight:this.minHeight || 80,
33651 handles: this.resizeHandles || "all",
33654 this.resizer.on("beforeresize", this.beforeResize, this);
33655 this.resizer.on("resize", this.onResize, this);
33657 if(this.draggable !== false){
33658 el.addClass("x-dlg-draggable");
33659 if (!this.proxyDrag) {
33660 var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
33663 var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
33665 dd.setHandleElId(this.header.id);
33666 dd.endDrag = this.endMove.createDelegate(this);
33667 dd.startDrag = this.startMove.createDelegate(this);
33668 dd.onDrag = this.onDrag.createDelegate(this);
33673 this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
33674 this.mask.enableDisplayMode("block");
33676 this.el.addClass("x-dlg-modal");
33679 this.shadow = new Roo.Shadow({
33680 mode : typeof this.shadow == "string" ? this.shadow : "sides",
33681 offset : this.shadowOffset
33684 this.shadowOffset = 0;
33686 if(Roo.useShims && this.shim !== false){
33687 this.shim = this.el.createShim();
33688 this.shim.hide = this.hideAction;
33696 if (this.buttons) {
33697 var bts= this.buttons;
33699 Roo.each(bts, function(b) {
33708 * Fires when a key is pressed
33709 * @param {Roo.BasicDialog} this
33710 * @param {Roo.EventObject} e
33715 * Fires when this dialog is moved by the user.
33716 * @param {Roo.BasicDialog} this
33717 * @param {Number} x The new page X
33718 * @param {Number} y The new page Y
33723 * Fires when this dialog is resized by the user.
33724 * @param {Roo.BasicDialog} this
33725 * @param {Number} width The new width
33726 * @param {Number} height The new height
33730 * @event beforehide
33731 * Fires before this dialog is hidden.
33732 * @param {Roo.BasicDialog} this
33734 "beforehide" : true,
33737 * Fires when this dialog is hidden.
33738 * @param {Roo.BasicDialog} this
33742 * @event beforeshow
33743 * Fires before this dialog is shown.
33744 * @param {Roo.BasicDialog} this
33746 "beforeshow" : true,
33749 * Fires when this dialog is shown.
33750 * @param {Roo.BasicDialog} this
33754 el.on("keydown", this.onKeyDown, this);
33755 el.on("mousedown", this.toFront, this);
33756 Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
33758 Roo.DialogManager.register(this);
33759 Roo.BasicDialog.superclass.constructor.call(this);
33762 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
33763 shadowOffset: Roo.isIE ? 6 : 5,
33766 minButtonWidth: 75,
33767 defaultButton: null,
33768 buttonAlign: "right",
33773 * Sets the dialog title text
33774 * @param {String} text The title text to display
33775 * @return {Roo.BasicDialog} this
33777 setTitle : function(text){
33778 this.header.update(text);
33783 closeClick : function(){
33788 collapseClick : function(){
33789 this[this.collapsed ? "expand" : "collapse"]();
33793 * Collapses the dialog to its minimized state (only the title bar is visible).
33794 * Equivalent to the user clicking the collapse dialog button.
33796 collapse : function(){
33797 if(!this.collapsed){
33798 this.collapsed = true;
33799 this.el.addClass("x-dlg-collapsed");
33800 this.restoreHeight = this.el.getHeight();
33801 this.resizeTo(this.el.getWidth(), this.header.getHeight());
33806 * Expands a collapsed dialog back to its normal state. Equivalent to the user
33807 * clicking the expand dialog button.
33809 expand : function(){
33810 if(this.collapsed){
33811 this.collapsed = false;
33812 this.el.removeClass("x-dlg-collapsed");
33813 this.resizeTo(this.el.getWidth(), this.restoreHeight);
33818 * Reinitializes the tabs component, clearing out old tabs and finding new ones.
33819 * @return {Roo.TabPanel} The tabs component
33821 initTabs : function(){
33822 var tabs = this.getTabs();
33823 while(tabs.getTab(0)){
33826 this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
33828 tabs.addTab(Roo.id(dom), dom.title);
33836 beforeResize : function(){
33837 this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
33841 onResize : function(){
33842 this.refreshSize();
33843 this.syncBodyHeight();
33844 this.adjustAssets();
33846 this.fireEvent("resize", this, this.size.width, this.size.height);
33850 onKeyDown : function(e){
33851 if(this.isVisible()){
33852 this.fireEvent("keydown", this, e);
33857 * Resizes the dialog.
33858 * @param {Number} width
33859 * @param {Number} height
33860 * @return {Roo.BasicDialog} this
33862 resizeTo : function(width, height){
33863 this.el.setSize(width, height);
33864 this.size = {width: width, height: height};
33865 this.syncBodyHeight();
33866 if(this.fixedcenter){
33869 if(this.isVisible()){
33870 this.constrainXY();
33871 this.adjustAssets();
33873 this.fireEvent("resize", this, width, height);
33879 * Resizes the dialog to fit the specified content size.
33880 * @param {Number} width
33881 * @param {Number} height
33882 * @return {Roo.BasicDialog} this
33884 setContentSize : function(w, h){
33885 h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
33886 w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
33887 //if(!this.el.isBorderBox()){
33888 h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
33889 w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
33892 h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
33893 w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
33895 this.resizeTo(w, h);
33900 * Adds a key listener for when this dialog is displayed. This allows you to hook in a function that will be
33901 * executed in response to a particular key being pressed while the dialog is active.
33902 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
33903 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
33904 * @param {Function} fn The function to call
33905 * @param {Object} scope (optional) The scope of the function
33906 * @return {Roo.BasicDialog} this
33908 addKeyListener : function(key, fn, scope){
33909 var keyCode, shift, ctrl, alt;
33910 if(typeof key == "object" && !(key instanceof Array)){
33911 keyCode = key["key"];
33912 shift = key["shift"];
33913 ctrl = key["ctrl"];
33918 var handler = function(dlg, e){
33919 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
33920 var k = e.getKey();
33921 if(keyCode instanceof Array){
33922 for(var i = 0, len = keyCode.length; i < len; i++){
33923 if(keyCode[i] == k){
33924 fn.call(scope || window, dlg, k, e);
33930 fn.call(scope || window, dlg, k, e);
33935 this.on("keydown", handler);
33940 * Returns the TabPanel component (creates it if it doesn't exist).
33941 * Note: If you wish to simply check for the existence of tabs without creating them,
33942 * check for a null 'tabs' property.
33943 * @return {Roo.TabPanel} The tabs component
33945 getTabs : function(){
33947 this.el.addClass("x-dlg-auto-tabs");
33948 this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
33949 this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
33955 * Adds a button to the footer section of the dialog.
33956 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
33957 * object or a valid Roo.DomHelper element config
33958 * @param {Function} handler The function called when the button is clicked
33959 * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
33960 * @return {Roo.Button} The new button
33962 addButton : function(config, handler, scope){
33963 var dh = Roo.DomHelper;
33965 this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
33967 if(!this.btnContainer){
33968 var tb = this.footer.createChild({
33970 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
33971 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
33973 this.btnContainer = tb.firstChild.firstChild.firstChild;
33978 minWidth: this.minButtonWidth,
33981 if(typeof config == "string"){
33982 bconfig.text = config;
33985 bconfig.dhconfig = config;
33987 Roo.apply(bconfig, config);
33991 if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
33992 bconfig.position = Math.max(0, bconfig.position);
33993 fc = this.btnContainer.childNodes[bconfig.position];
33996 var btn = new Roo.Button(
33998 this.btnContainer.insertBefore(document.createElement("td"),fc)
33999 : this.btnContainer.appendChild(document.createElement("td")),
34000 //Roo.get(this.btnContainer).createChild( { tag: 'td'}, fc ),
34003 this.syncBodyHeight();
34006 * Array of all the buttons that have been added to this dialog via addButton
34011 this.buttons.push(btn);
34016 * Sets the default button to be focused when the dialog is displayed.
34017 * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
34018 * @return {Roo.BasicDialog} this
34020 setDefaultButton : function(btn){
34021 this.defaultButton = btn;
34026 getHeaderFooterHeight : function(safe){
34029 height += this.header.getHeight();
34032 var fm = this.footer.getMargins();
34033 height += (this.footer.getHeight()+fm.top+fm.bottom);
34035 height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
34036 height += this.centerBg.getPadding("tb");
34041 syncBodyHeight : function()
34043 var bd = this.body, // the text
34044 cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
34046 var height = this.size.height - this.getHeaderFooterHeight(false);
34047 bd.setHeight(height-bd.getMargins("tb"));
34048 var hh = this.header.getHeight();
34049 var h = this.size.height-hh;
34052 bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
34053 bw.setHeight(h-cb.getPadding("tb"));
34055 bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
34056 bd.setWidth(bw.getWidth(true));
34058 this.tabs.syncHeight();
34060 this.tabs.el.repaint();
34066 * Restores the previous state of the dialog if Roo.state is configured.
34067 * @return {Roo.BasicDialog} this
34069 restoreState : function(){
34070 var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
34071 if(box && box.width){
34072 this.xy = [box.x, box.y];
34073 this.resizeTo(box.width, box.height);
34079 beforeShow : function(){
34081 if(this.fixedcenter){
34082 this.xy = this.el.getCenterXY(true);
34085 Roo.get(document.body).addClass("x-body-masked");
34086 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
34089 this.constrainXY();
34093 animShow : function(){
34094 var b = Roo.get(this.animateTarget).getBox();
34095 this.proxy.setSize(b.width, b.height);
34096 this.proxy.setLocation(b.x, b.y);
34098 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
34099 true, .35, this.showEl.createDelegate(this));
34103 * Shows the dialog.
34104 * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
34105 * @return {Roo.BasicDialog} this
34107 show : function(animateTarget){
34108 if (this.fireEvent("beforeshow", this) === false){
34111 if(this.syncHeightBeforeShow){
34112 this.syncBodyHeight();
34113 }else if(this.firstShow){
34114 this.firstShow = false;
34115 this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
34117 this.animateTarget = animateTarget || this.animateTarget;
34118 if(!this.el.isVisible()){
34120 if(this.animateTarget && Roo.get(this.animateTarget)){
34130 showEl : function(){
34132 this.el.setXY(this.xy);
34134 this.adjustAssets(true);
34137 // IE peekaboo bug - fix found by Dave Fenwick
34141 this.fireEvent("show", this);
34145 * Focuses the dialog. If a defaultButton is set, it will receive focus, otherwise the
34146 * dialog itself will receive focus.
34148 focus : function(){
34149 if(this.defaultButton){
34150 this.defaultButton.focus();
34152 this.focusEl.focus();
34157 constrainXY : function(){
34158 if(this.constraintoviewport !== false){
34159 if(!this.viewSize){
34160 if(this.container){
34161 var s = this.container.getSize();
34162 this.viewSize = [s.width, s.height];
34164 this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
34167 var s = Roo.get(this.container||document).getScroll();
34169 var x = this.xy[0], y = this.xy[1];
34170 var w = this.size.width, h = this.size.height;
34171 var vw = this.viewSize[0], vh = this.viewSize[1];
34172 // only move it if it needs it
34174 // first validate right/bottom
34175 if(x + w > vw+s.left){
34179 if(y + h > vh+s.top){
34183 // then make sure top/left isn't negative
34195 if(this.isVisible()){
34196 this.el.setLocation(x, y);
34197 this.adjustAssets();
34204 onDrag : function(){
34205 if(!this.proxyDrag){
34206 this.xy = this.el.getXY();
34207 this.adjustAssets();
34212 adjustAssets : function(doShow){
34213 var x = this.xy[0], y = this.xy[1];
34214 var w = this.size.width, h = this.size.height;
34215 if(doShow === true){
34217 this.shadow.show(this.el);
34223 if(this.shadow && this.shadow.isVisible()){
34224 this.shadow.show(this.el);
34226 if(this.shim && this.shim.isVisible()){
34227 this.shim.setBounds(x, y, w, h);
34232 adjustViewport : function(w, h){
34234 w = Roo.lib.Dom.getViewWidth();
34235 h = Roo.lib.Dom.getViewHeight();
34238 this.viewSize = [w, h];
34239 if(this.modal && this.mask.isVisible()){
34240 this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
34241 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
34243 if(this.isVisible()){
34244 this.constrainXY();
34249 * Destroys this dialog and all its supporting elements (including any tabs, shim,
34250 * shadow, proxy, mask, etc.) Also removes all event listeners.
34251 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
34253 destroy : function(removeEl){
34254 if(this.isVisible()){
34255 this.animateTarget = null;
34258 Roo.EventManager.removeResizeListener(this.adjustViewport, this);
34260 this.tabs.destroy(removeEl);
34273 for(var i = 0, len = this.buttons.length; i < len; i++){
34274 this.buttons[i].destroy();
34277 this.el.removeAllListeners();
34278 if(removeEl === true){
34279 this.el.update("");
34282 Roo.DialogManager.unregister(this);
34286 startMove : function(){
34287 if(this.proxyDrag){
34290 if(this.constraintoviewport !== false){
34291 this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
34296 endMove : function(){
34297 if(!this.proxyDrag){
34298 Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
34300 Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
34303 this.refreshSize();
34304 this.adjustAssets();
34306 this.fireEvent("move", this, this.xy[0], this.xy[1]);
34310 * Brings this dialog to the front of any other visible dialogs
34311 * @return {Roo.BasicDialog} this
34313 toFront : function(){
34314 Roo.DialogManager.bringToFront(this);
34319 * Sends this dialog to the back (under) of any other visible dialogs
34320 * @return {Roo.BasicDialog} this
34322 toBack : function(){
34323 Roo.DialogManager.sendToBack(this);
34328 * Centers this dialog in the viewport
34329 * @return {Roo.BasicDialog} this
34331 center : function(){
34332 var xy = this.el.getCenterXY(true);
34333 this.moveTo(xy[0], xy[1]);
34338 * Moves the dialog's top-left corner to the specified point
34339 * @param {Number} x
34340 * @param {Number} y
34341 * @return {Roo.BasicDialog} this
34343 moveTo : function(x, y){
34345 if(this.isVisible()){
34346 this.el.setXY(this.xy);
34347 this.adjustAssets();
34353 * Aligns the dialog to the specified element
34354 * @param {String/HTMLElement/Roo.Element} element The element to align to.
34355 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
34356 * @param {Array} offsets (optional) Offset the positioning by [x, y]
34357 * @return {Roo.BasicDialog} this
34359 alignTo : function(element, position, offsets){
34360 this.xy = this.el.getAlignToXY(element, position, offsets);
34361 if(this.isVisible()){
34362 this.el.setXY(this.xy);
34363 this.adjustAssets();
34369 * Anchors an element to another element and realigns it when the window is resized.
34370 * @param {String/HTMLElement/Roo.Element} element The element to align to.
34371 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
34372 * @param {Array} offsets (optional) Offset the positioning by [x, y]
34373 * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
34374 * is a number, it is used as the buffer delay (defaults to 50ms).
34375 * @return {Roo.BasicDialog} this
34377 anchorTo : function(el, alignment, offsets, monitorScroll){
34378 var action = function(){
34379 this.alignTo(el, alignment, offsets);
34381 Roo.EventManager.onWindowResize(action, this);
34382 var tm = typeof monitorScroll;
34383 if(tm != 'undefined'){
34384 Roo.EventManager.on(window, 'scroll', action, this,
34385 {buffer: tm == 'number' ? monitorScroll : 50});
34392 * Returns true if the dialog is visible
34393 * @return {Boolean}
34395 isVisible : function(){
34396 return this.el.isVisible();
34400 animHide : function(callback){
34401 var b = Roo.get(this.animateTarget).getBox();
34403 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
34405 this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
34406 this.hideEl.createDelegate(this, [callback]));
34410 * Hides the dialog.
34411 * @param {Function} callback (optional) Function to call when the dialog is hidden
34412 * @return {Roo.BasicDialog} this
34414 hide : function(callback){
34415 if (this.fireEvent("beforehide", this) === false){
34419 this.shadow.hide();
34424 // sometimes animateTarget seems to get set.. causing problems...
34425 // this just double checks..
34426 if(this.animateTarget && Roo.get(this.animateTarget)) {
34427 this.animHide(callback);
34430 this.hideEl(callback);
34436 hideEl : function(callback){
34440 Roo.get(document.body).removeClass("x-body-masked");
34442 this.fireEvent("hide", this);
34443 if(typeof callback == "function"){
34449 hideAction : function(){
34450 this.setLeft("-10000px");
34451 this.setTop("-10000px");
34452 this.setStyle("visibility", "hidden");
34456 refreshSize : function(){
34457 this.size = this.el.getSize();
34458 this.xy = this.el.getXY();
34459 Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
34463 // z-index is managed by the DialogManager and may be overwritten at any time
34464 setZIndex : function(index){
34466 this.mask.setStyle("z-index", index);
34469 this.shim.setStyle("z-index", ++index);
34472 this.shadow.setZIndex(++index);
34474 this.el.setStyle("z-index", ++index);
34476 this.proxy.setStyle("z-index", ++index);
34479 this.resizer.proxy.setStyle("z-index", ++index);
34482 this.lastZIndex = index;
34486 * Returns the element for this dialog
34487 * @return {Roo.Element} The underlying dialog Element
34489 getEl : function(){
34495 * @class Roo.DialogManager
34496 * Provides global access to BasicDialogs that have been created and
34497 * support for z-indexing (layering) multiple open dialogs.
34499 Roo.DialogManager = function(){
34501 var accessList = [];
34505 var sortDialogs = function(d1, d2){
34506 return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
34510 var orderDialogs = function(){
34511 accessList.sort(sortDialogs);
34512 var seed = Roo.DialogManager.zseed;
34513 for(var i = 0, len = accessList.length; i < len; i++){
34514 var dlg = accessList[i];
34516 dlg.setZIndex(seed + (i*10));
34523 * The starting z-index for BasicDialogs (defaults to 9000)
34524 * @type Number The z-index value
34529 register : function(dlg){
34530 list[dlg.id] = dlg;
34531 accessList.push(dlg);
34535 unregister : function(dlg){
34536 delete list[dlg.id];
34539 if(!accessList.indexOf){
34540 for( i = 0, len = accessList.length; i < len; i++){
34541 if(accessList[i] == dlg){
34542 accessList.splice(i, 1);
34547 i = accessList.indexOf(dlg);
34549 accessList.splice(i, 1);
34555 * Gets a registered dialog by id
34556 * @param {String/Object} id The id of the dialog or a dialog
34557 * @return {Roo.BasicDialog} this
34559 get : function(id){
34560 return typeof id == "object" ? id : list[id];
34564 * Brings the specified dialog to the front
34565 * @param {String/Object} dlg The id of the dialog or a dialog
34566 * @return {Roo.BasicDialog} this
34568 bringToFront : function(dlg){
34569 dlg = this.get(dlg);
34572 dlg._lastAccess = new Date().getTime();
34579 * Sends the specified dialog to the back
34580 * @param {String/Object} dlg The id of the dialog or a dialog
34581 * @return {Roo.BasicDialog} this
34583 sendToBack : function(dlg){
34584 dlg = this.get(dlg);
34585 dlg._lastAccess = -(new Date().getTime());
34591 * Hides all dialogs
34593 hideAll : function(){
34594 for(var id in list){
34595 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
34604 * @class Roo.LayoutDialog
34605 * @extends Roo.BasicDialog
34606 * @children Roo.ContentPanel
34607 * @parent builder none
34608 * Dialog which provides adjustments for working with a layout in a Dialog.
34609 * Add your necessary layout config options to the dialog's config.<br>
34610 * Example usage (including a nested layout):
34613 dialog = new Roo.LayoutDialog("download-dlg", {
34622 // layout config merges with the dialog config
34624 tabPosition: "top",
34625 alwaysShowTabs: true
34628 dialog.addKeyListener(27, dialog.hide, dialog);
34629 dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
34630 dialog.addButton("Build It!", this.getDownload, this);
34632 // we can even add nested layouts
34633 var innerLayout = new Roo.BorderLayout("dl-inner", {
34643 innerLayout.beginUpdate();
34644 innerLayout.add("east", new Roo.ContentPanel("dl-details"));
34645 innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
34646 innerLayout.endUpdate(true);
34648 var layout = dialog.getLayout();
34649 layout.beginUpdate();
34650 layout.add("center", new Roo.ContentPanel("standard-panel",
34651 {title: "Download the Source", fitToFrame:true}));
34652 layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
34653 {title: "Build your own roo.js"}));
34654 layout.getRegion("center").showPanel(sp);
34655 layout.endUpdate();
34659 * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
34660 * @param {Object} config configuration options
34662 Roo.LayoutDialog = function(el, cfg){
34665 if (typeof(cfg) == 'undefined') {
34666 config = Roo.apply({}, el);
34667 // not sure why we use documentElement here.. - it should always be body.
34668 // IE7 borks horribly if we use documentElement.
34669 // webkit also does not like documentElement - it creates a body element...
34670 el = Roo.get( document.body || document.documentElement ).createChild();
34671 //config.autoCreate = true;
34675 config.autoTabs = false;
34676 Roo.LayoutDialog.superclass.constructor.call(this, el, config);
34677 this.body.setStyle({overflow:"hidden", position:"relative"});
34678 this.layout = new Roo.BorderLayout(this.body.dom, config);
34679 this.layout.monitorWindowResize = false;
34680 this.el.addClass("x-dlg-auto-layout");
34681 // fix case when center region overwrites center function
34682 this.center = Roo.BasicDialog.prototype.center;
34683 this.on("show", this.layout.layout, this.layout, true);
34684 if (config.items) {
34685 var xitems = config.items;
34686 delete config.items;
34687 Roo.each(xitems, this.addxtype, this);
34692 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
34696 * @cfg {Roo.LayoutRegion} east
34699 * @cfg {Roo.LayoutRegion} west
34702 * @cfg {Roo.LayoutRegion} south
34705 * @cfg {Roo.LayoutRegion} north
34708 * @cfg {Roo.LayoutRegion} center
34711 * @cfg {Roo.Button} buttons[] Bottom buttons..
34716 * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
34719 endUpdate : function(){
34720 this.layout.endUpdate();
34724 * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
34727 beginUpdate : function(){
34728 this.layout.beginUpdate();
34732 * Get the BorderLayout for this dialog
34733 * @return {Roo.BorderLayout}
34735 getLayout : function(){
34736 return this.layout;
34739 showEl : function(){
34740 Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
34742 this.layout.layout();
34747 // Use the syncHeightBeforeShow config option to control this automatically
34748 syncBodyHeight : function(){
34749 Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
34750 if(this.layout){this.layout.layout();}
34754 * Add an xtype element (actually adds to the layout.)
34755 * @return {Object} xdata xtype object data.
34758 addxtype : function(c) {
34759 return this.layout.addxtype(c);
34763 * Ext JS Library 1.1.1
34764 * Copyright(c) 2006-2007, Ext JS, LLC.
34766 * Originally Released Under LGPL - original licence link has changed is not relivant.
34769 * <script type="text/javascript">
34773 * @class Roo.MessageBox
34775 * Utility class for generating different styles of message boxes. The alias Roo.Msg can also be used.
34779 Roo.Msg.alert('Status', 'Changes saved successfully.');
34781 // Prompt for user data:
34782 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
34784 // process text value...
34788 // Show a dialog using config options:
34790 title:'Save Changes?',
34791 msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
34792 buttons: Roo.Msg.YESNOCANCEL,
34799 Roo.MessageBox = function(){
34800 var dlg, opt, mask, waitTimer;
34801 var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
34802 var buttons, activeTextEl, bwidth;
34805 var handleButton = function(button){
34807 Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
34811 var handleHide = function(){
34812 if(opt && opt.cls){
34813 dlg.el.removeClass(opt.cls);
34816 Roo.TaskMgr.stop(waitTimer);
34822 var updateButtons = function(b){
34825 buttons["ok"].hide();
34826 buttons["cancel"].hide();
34827 buttons["yes"].hide();
34828 buttons["no"].hide();
34829 dlg.footer.dom.style.display = 'none';
34832 dlg.footer.dom.style.display = '';
34833 for(var k in buttons){
34834 if(typeof buttons[k] != "function"){
34837 buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
34838 width += buttons[k].el.getWidth()+15;
34848 var handleEsc = function(d, k, e){
34849 if(opt && opt.closable !== false){
34859 * Returns a reference to the underlying {@link Roo.BasicDialog} element
34860 * @return {Roo.BasicDialog} The BasicDialog element
34862 getDialog : function(){
34864 dlg = new Roo.BasicDialog("x-msg-box", {
34869 constraintoviewport:false,
34871 collapsible : false,
34874 width:400, height:100,
34875 buttonAlign:"center",
34876 closeClick : function(){
34877 if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
34878 handleButton("no");
34880 handleButton("cancel");
34885 dlg.on("hide", handleHide);
34887 dlg.addKeyListener(27, handleEsc);
34889 var bt = this.buttonText;
34890 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
34891 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
34892 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
34893 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
34894 bodyEl = dlg.body.createChild({
34896 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>'
34898 msgEl = bodyEl.dom.firstChild;
34899 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
34900 textboxEl.enableDisplayMode();
34901 textboxEl.addKeyListener([10,13], function(){
34902 if(dlg.isVisible() && opt && opt.buttons){
34903 if(opt.buttons.ok){
34904 handleButton("ok");
34905 }else if(opt.buttons.yes){
34906 handleButton("yes");
34910 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
34911 textareaEl.enableDisplayMode();
34912 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
34913 progressEl.enableDisplayMode();
34914 var pf = progressEl.dom.firstChild;
34916 pp = Roo.get(pf.firstChild);
34917 pp.setHeight(pf.offsetHeight);
34925 * Updates the message box body text
34926 * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
34927 * the XHTML-compliant non-breaking space character '&#160;')
34928 * @return {Roo.MessageBox} This message box
34930 updateText : function(text){
34931 if(!dlg.isVisible() && !opt.width){
34932 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
34934 msgEl.innerHTML = text || ' ';
34936 var cw = Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
34937 //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
34939 Math.min(opt.width || cw , this.maxWidth),
34940 Math.max(opt.minWidth || this.minWidth, bwidth)
34943 activeTextEl.setWidth(w);
34945 if(dlg.isVisible()){
34946 dlg.fixedcenter = false;
34948 // to big, make it scroll. = But as usual stupid IE does not support
34951 if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
34952 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
34953 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
34955 bodyEl.dom.style.height = '';
34956 bodyEl.dom.style.overflowY = '';
34959 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
34961 bodyEl.dom.style.overflowX = '';
34964 dlg.setContentSize(w, bodyEl.getHeight());
34965 if(dlg.isVisible()){
34966 dlg.fixedcenter = true;
34972 * Updates a progress-style message box's text and progress bar. Only relevant on message boxes
34973 * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
34974 * @param {Number} value Any number between 0 and 1 (e.g., .5)
34975 * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
34976 * @return {Roo.MessageBox} This message box
34978 updateProgress : function(value, text){
34980 this.updateText(text);
34982 if (pp) { // weird bug on my firefox - for some reason this is not defined
34983 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
34989 * Returns true if the message box is currently displayed
34990 * @return {Boolean} True if the message box is visible, else false
34992 isVisible : function(){
34993 return dlg && dlg.isVisible();
34997 * Hides the message box if it is displayed
35000 if(this.isVisible()){
35006 * Displays a new message box, or reinitializes an existing message box, based on the config options
35007 * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
35008 * The following config object properties are supported:
35010 Property Type Description
35011 ---------- --------------- ------------------------------------------------------------------------------------
35012 animEl String/Element An id or Element from which the message box should animate as it opens and
35013 closes (defaults to undefined)
35014 buttons Object/Boolean A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
35015 cancel:'Bar'}), or false to not show any buttons (defaults to false)
35016 closable Boolean False to hide the top-right close button (defaults to true). Note that
35017 progress and wait dialogs will ignore this property and always hide the
35018 close button as they can only be closed programmatically.
35019 cls String A custom CSS class to apply to the message box element
35020 defaultTextHeight Number The default height in pixels of the message box's multiline textarea if
35021 displayed (defaults to 75)
35022 fn Function A callback function to execute after closing the dialog. The arguments to the
35023 function will be btn (the name of the button that was clicked, if applicable,
35024 e.g. "ok"), and text (the value of the active text field, if applicable).
35025 Progress and wait dialogs will ignore this option since they do not respond to
35026 user actions and can only be closed programmatically, so any required function
35027 should be called by the same code after it closes the dialog.
35028 icon String A CSS class that provides a background image to be used as an icon for
35029 the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
35030 maxWidth Number The maximum width in pixels of the message box (defaults to 600)
35031 minWidth Number The minimum width in pixels of the message box (defaults to 100)
35032 modal Boolean False to allow user interaction with the page while the message box is
35033 displayed (defaults to true)
35034 msg String A string that will replace the existing message box body text (defaults
35035 to the XHTML-compliant non-breaking space character ' ')
35036 multiline Boolean True to prompt the user to enter multi-line text (defaults to false)
35037 progress Boolean True to display a progress bar (defaults to false)
35038 progressText String The text to display inside the progress bar if progress = true (defaults to '')
35039 prompt Boolean True to prompt the user to enter single-line text (defaults to false)
35040 proxyDrag Boolean True to display a lightweight proxy while dragging (defaults to false)
35041 title String The title text
35042 value String The string value to set into the active textbox element if displayed
35043 wait Boolean True to display a progress bar (defaults to false)
35044 width Number The width of the dialog in pixels
35051 msg: 'Please enter your address:',
35053 buttons: Roo.MessageBox.OKCANCEL,
35056 animEl: 'addAddressBtn'
35059 * @param {Object} config Configuration options
35060 * @return {Roo.MessageBox} This message box
35062 show : function(options)
35065 // this causes nightmares if you show one dialog after another
35066 // especially on callbacks..
35068 if(this.isVisible()){
35071 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
35072 Roo.log("Old Dialog Message:" + msgEl.innerHTML );
35073 Roo.log("New Dialog Message:" + options.msg )
35074 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
35075 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
35078 var d = this.getDialog();
35080 d.setTitle(opt.title || " ");
35081 d.close.setDisplayed(opt.closable !== false);
35082 activeTextEl = textboxEl;
35083 opt.prompt = opt.prompt || (opt.multiline ? true : false);
35088 textareaEl.setHeight(typeof opt.multiline == "number" ?
35089 opt.multiline : this.defaultTextHeight);
35090 activeTextEl = textareaEl;
35099 progressEl.setDisplayed(opt.progress === true);
35100 this.updateProgress(0);
35101 activeTextEl.dom.value = opt.value || "";
35103 dlg.setDefaultButton(activeTextEl);
35105 var bs = opt.buttons;
35108 db = buttons["ok"];
35109 }else if(bs && bs.yes){
35110 db = buttons["yes"];
35112 dlg.setDefaultButton(db);
35114 bwidth = updateButtons(opt.buttons);
35115 this.updateText(opt.msg);
35117 d.el.addClass(opt.cls);
35119 d.proxyDrag = opt.proxyDrag === true;
35120 d.modal = opt.modal !== false;
35121 d.mask = opt.modal !== false ? mask : false;
35122 if(!d.isVisible()){
35123 // force it to the end of the z-index stack so it gets a cursor in FF
35124 document.body.appendChild(dlg.el.dom);
35125 d.animateTarget = null;
35126 d.show(options.animEl);
35133 * Displays a message box with a progress bar. This message box has no buttons and is not closeable by
35134 * the user. You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
35135 * and closing the message box when the process is complete.
35136 * @param {String} title The title bar text
35137 * @param {String} msg The message box body text
35138 * @return {Roo.MessageBox} This message box
35140 progress : function(title, msg){
35147 minWidth: this.minProgressWidth,
35154 * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
35155 * If a callback function is passed it will be called after the user clicks the button, and the
35156 * id of the button that was clicked will be passed as the only parameter to the callback
35157 * (could also be the top-right close button).
35158 * @param {String} title The title bar text
35159 * @param {String} msg The message box body text
35160 * @param {Function} fn (optional) The callback function invoked after the message box is closed
35161 * @param {Object} scope (optional) The scope of the callback function
35162 * @return {Roo.MessageBox} This message box
35164 alert : function(title, msg, fn, scope){
35177 * Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
35178 * interaction while waiting for a long-running process to complete that does not have defined intervals.
35179 * You are responsible for closing the message box when the process is complete.
35180 * @param {String} msg The message box body text
35181 * @param {String} title (optional) The title bar text
35182 * @return {Roo.MessageBox} This message box
35184 wait : function(msg, title){
35195 waitTimer = Roo.TaskMgr.start({
35197 Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
35205 * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
35206 * If a callback function is passed it will be called after the user clicks either button, and the id of the
35207 * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
35208 * @param {String} title The title bar text
35209 * @param {String} msg The message box body text
35210 * @param {Function} fn (optional) The callback function invoked after the message box is closed
35211 * @param {Object} scope (optional) The scope of the callback function
35212 * @return {Roo.MessageBox} This message box
35214 confirm : function(title, msg, fn, scope){
35218 buttons: this.YESNO,
35227 * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
35228 * JavaScript's Window.prompt). The prompt can be a single-line or multi-line textbox. If a callback function
35229 * is passed it will be called after the user clicks either button, and the id of the button that was clicked
35230 * (could also be the top-right close button) and the text that was entered will be passed as the two
35231 * parameters to the callback.
35232 * @param {String} title The title bar text
35233 * @param {String} msg The message box body text
35234 * @param {Function} fn (optional) The callback function invoked after the message box is closed
35235 * @param {Object} scope (optional) The scope of the callback function
35236 * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
35237 * property, or the height in pixels to create the textbox (defaults to false / single-line)
35238 * @return {Roo.MessageBox} This message box
35240 prompt : function(title, msg, fn, scope, multiline){
35244 buttons: this.OKCANCEL,
35249 multiline: multiline,
35256 * Button config that displays a single OK button
35261 * Button config that displays Yes and No buttons
35264 YESNO : {yes:true, no:true},
35266 * Button config that displays OK and Cancel buttons
35269 OKCANCEL : {ok:true, cancel:true},
35271 * Button config that displays Yes, No and Cancel buttons
35274 YESNOCANCEL : {yes:true, no:true, cancel:true},
35277 * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
35280 defaultTextHeight : 75,
35282 * The maximum width in pixels of the message box (defaults to 600)
35287 * The minimum width in pixels of the message box (defaults to 100)
35292 * The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
35293 * for setting a different minimum width than text-only dialogs may need (defaults to 250)
35296 minProgressWidth : 250,
35298 * An object containing the default button text strings that can be overriden for localized language support.
35299 * Supported properties are: ok, cancel, yes and no.
35300 * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
35313 * Shorthand for {@link Roo.MessageBox}
35315 Roo.Msg = Roo.MessageBox;/*
35317 * Ext JS Library 1.1.1
35318 * Copyright(c) 2006-2007, Ext JS, LLC.
35320 * Originally Released Under LGPL - original licence link has changed is not relivant.
35323 * <script type="text/javascript">
35326 * @class Roo.QuickTips
35327 * Provides attractive and customizable tooltips for any element.
35330 Roo.QuickTips = function(){
35331 var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
35332 var ce, bd, xy, dd;
35333 var visible = false, disabled = true, inited = false;
35334 var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
35336 var onOver = function(e){
35340 var t = e.getTarget();
35341 if(!t || t.nodeType !== 1 || t == document || t == document.body){
35344 if(ce && t == ce.el){
35345 clearTimeout(hideProc);
35348 if(t && tagEls[t.id]){
35349 tagEls[t.id].el = t;
35350 showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
35353 var ttp, et = Roo.fly(t);
35354 var ns = cfg.namespace;
35355 if(tm.interceptTitles && t.title){
35358 t.removeAttribute("title");
35359 e.preventDefault();
35361 ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
35364 showProc = show.defer(tm.showDelay, tm, [{
35366 text: ttp.replace(/\\n/g,'<br/>'),
35367 width: et.getAttributeNS(ns, cfg.width),
35368 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
35369 title: et.getAttributeNS(ns, cfg.title),
35370 cls: et.getAttributeNS(ns, cfg.cls)
35375 var onOut = function(e){
35376 clearTimeout(showProc);
35377 var t = e.getTarget();
35378 if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
35379 hideProc = setTimeout(hide, tm.hideDelay);
35383 var onMove = function(e){
35389 if(tm.trackMouse && ce){
35394 var onDown = function(e){
35395 clearTimeout(showProc);
35396 clearTimeout(hideProc);
35398 if(tm.hideOnClick){
35401 tm.enable.defer(100, tm);
35406 var getPad = function(){
35407 return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
35410 var show = function(o){
35414 clearTimeout(dismissProc);
35416 if(removeCls){ // in case manually hidden
35417 el.removeClass(removeCls);
35421 el.addClass(ce.cls);
35422 removeCls = ce.cls;
35425 tipTitle.update(ce.title);
35428 tipTitle.update('');
35431 el.dom.style.width = tm.maxWidth+'px';
35432 //tipBody.dom.style.width = '';
35433 tipBodyText.update(o.text);
35434 var p = getPad(), w = ce.width;
35436 var td = tipBodyText.dom;
35437 var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
35438 if(aw > tm.maxWidth){
35440 }else if(aw < tm.minWidth){
35446 //tipBody.setWidth(w);
35447 el.setWidth(parseInt(w, 10) + p);
35448 if(ce.autoHide === false){
35449 close.setDisplayed(true);
35454 close.setDisplayed(false);
35460 el.avoidY = xy[1]-18;
35465 el.setStyle("visibility", "visible");
35466 el.fadeIn({callback: afterShow});
35472 var afterShow = function(){
35476 if(tm.autoDismiss && ce.autoHide !== false){
35477 dismissProc = setTimeout(hide, tm.autoDismissDelay);
35482 var hide = function(noanim){
35483 clearTimeout(dismissProc);
35484 clearTimeout(hideProc);
35486 if(el.isVisible()){
35488 if(noanim !== true && tm.animate){
35489 el.fadeOut({callback: afterHide});
35496 var afterHide = function(){
35499 el.removeClass(removeCls);
35506 * @cfg {Number} minWidth
35507 * The minimum width of the quick tip (defaults to 40)
35511 * @cfg {Number} maxWidth
35512 * The maximum width of the quick tip (defaults to 300)
35516 * @cfg {Boolean} interceptTitles
35517 * True to automatically use the element's DOM title value if available (defaults to false)
35519 interceptTitles : false,
35521 * @cfg {Boolean} trackMouse
35522 * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
35524 trackMouse : false,
35526 * @cfg {Boolean} hideOnClick
35527 * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
35529 hideOnClick : true,
35531 * @cfg {Number} showDelay
35532 * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
35536 * @cfg {Number} hideDelay
35537 * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
35541 * @cfg {Boolean} autoHide
35542 * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
35543 * Used in conjunction with hideDelay.
35548 * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
35549 * (defaults to true). Used in conjunction with autoDismissDelay.
35551 autoDismiss : true,
35554 * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
35556 autoDismissDelay : 5000,
35558 * @cfg {Boolean} animate
35559 * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
35564 * @cfg {String} title
35565 * Title text to display (defaults to ''). This can be any valid HTML markup.
35569 * @cfg {String} text
35570 * Body text to display (defaults to ''). This can be any valid HTML markup.
35574 * @cfg {String} cls
35575 * A CSS class to apply to the base quick tip element (defaults to '').
35579 * @cfg {Number} width
35580 * Width in pixels of the quick tip (defaults to auto). Width will be ignored if it exceeds the bounds of
35581 * minWidth or maxWidth.
35586 * Initialize and enable QuickTips for first use. This should be called once before the first attempt to access
35587 * or display QuickTips in a page.
35590 tm = Roo.QuickTips;
35591 cfg = tm.tagConfig;
35593 if(!Roo.isReady){ // allow calling of init() before onReady
35594 Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
35597 el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
35598 el.fxDefaults = {stopFx: true};
35599 // maximum custom styling
35600 //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>');
35601 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>');
35602 tipTitle = el.child('h3');
35603 tipTitle.enableDisplayMode("block");
35604 tipBody = el.child('div.x-tip-bd');
35605 tipBodyText = el.child('div.x-tip-bd-inner');
35606 //bdLeft = el.child('div.x-tip-bd-left');
35607 //bdRight = el.child('div.x-tip-bd-right');
35608 close = el.child('div.x-tip-close');
35609 close.enableDisplayMode("block");
35610 close.on("click", hide);
35611 var d = Roo.get(document);
35612 d.on("mousedown", onDown);
35613 d.on("mouseover", onOver);
35614 d.on("mouseout", onOut);
35615 d.on("mousemove", onMove);
35616 esc = d.addKeyListener(27, hide);
35619 dd = el.initDD("default", null, {
35620 onDrag : function(){
35624 dd.setHandleElId(tipTitle.id);
35633 * Configures a new quick tip instance and assigns it to a target element. The following config options
35636 Property Type Description
35637 ---------- --------------------- ------------------------------------------------------------------------
35638 target Element/String/Array An Element, id or array of ids that this quick tip should be tied to
35640 * @param {Object} config The config object
35642 register : function(config){
35643 var cs = config instanceof Array ? config : arguments;
35644 for(var i = 0, len = cs.length; i < len; i++) {
35646 var target = c.target;
35648 if(target instanceof Array){
35649 for(var j = 0, jlen = target.length; j < jlen; j++){
35650 tagEls[target[j]] = c;
35653 tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
35660 * Removes this quick tip from its element and destroys it.
35661 * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
35663 unregister : function(el){
35664 delete tagEls[Roo.id(el)];
35668 * Enable this quick tip.
35670 enable : function(){
35671 if(inited && disabled){
35673 if(locks.length < 1){
35680 * Disable this quick tip.
35682 disable : function(){
35684 clearTimeout(showProc);
35685 clearTimeout(hideProc);
35686 clearTimeout(dismissProc);
35694 * Returns true if the quick tip is enabled, else false.
35696 isEnabled : function(){
35702 namespace : "roo", // was ext?? this may break..
35703 alt_namespace : "ext",
35704 attribute : "qtip",
35714 // backwards compat
35715 Roo.QuickTips.tips = Roo.QuickTips.register;/*
35717 * Ext JS Library 1.1.1
35718 * Copyright(c) 2006-2007, Ext JS, LLC.
35720 * Originally Released Under LGPL - original licence link has changed is not relivant.
35723 * <script type="text/javascript">
35728 * @class Roo.tree.TreePanel
35729 * @extends Roo.data.Tree
35730 * @cfg {Roo.tree.TreeNode} root The root node
35731 * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
35732 * @cfg {Boolean} lines false to disable tree lines (defaults to true)
35733 * @cfg {Boolean} enableDD true to enable drag and drop
35734 * @cfg {Boolean} enableDrag true to enable just drag
35735 * @cfg {Boolean} enableDrop true to enable just drop
35736 * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
35737 * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
35738 * @cfg {String} ddGroup The DD group this TreePanel belongs to
35739 * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
35740 * @cfg {Boolean} ddScroll true to enable YUI body scrolling
35741 * @cfg {Boolean} containerScroll true to register this container with ScrollManager
35742 * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
35743 * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
35744 * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
35745 * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
35746 * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
35747 * @cfg {Roo.tree.TreeLoader} loader A TreeLoader for use with this TreePanel
35748 * @cfg {Roo.tree.TreeEditor} editor The TreeEditor to display when clicked.
35749 * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
35750 * @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>
35751 * @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>
35754 * @param {String/HTMLElement/Element} el The container element
35755 * @param {Object} config
35757 Roo.tree.TreePanel = function(el, config){
35759 var loader = false;
35761 root = config.root;
35762 delete config.root;
35764 if (config.loader) {
35765 loader = config.loader;
35766 delete config.loader;
35769 Roo.apply(this, config);
35770 Roo.tree.TreePanel.superclass.constructor.call(this);
35771 this.el = Roo.get(el);
35772 this.el.addClass('x-tree');
35773 //console.log(root);
35775 this.setRootNode( Roo.factory(root, Roo.tree));
35778 this.loader = Roo.factory(loader, Roo.tree);
35781 * Read-only. The id of the container element becomes this TreePanel's id.
35783 this.id = this.el.id;
35786 * @event beforeload
35787 * Fires before a node is loaded, return false to cancel
35788 * @param {Node} node The node being loaded
35790 "beforeload" : true,
35793 * Fires when a node is loaded
35794 * @param {Node} node The node that was loaded
35798 * @event textchange
35799 * Fires when the text for a node is changed
35800 * @param {Node} node The node
35801 * @param {String} text The new text
35802 * @param {String} oldText The old text
35804 "textchange" : true,
35806 * @event beforeexpand
35807 * Fires before a node is expanded, return false to cancel.
35808 * @param {Node} node The node
35809 * @param {Boolean} deep
35810 * @param {Boolean} anim
35812 "beforeexpand" : true,
35814 * @event beforecollapse
35815 * Fires before a node is collapsed, return false to cancel.
35816 * @param {Node} node The node
35817 * @param {Boolean} deep
35818 * @param {Boolean} anim
35820 "beforecollapse" : true,
35823 * Fires when a node is expanded
35824 * @param {Node} node The node
35828 * @event disabledchange
35829 * Fires when the disabled status of a node changes
35830 * @param {Node} node The node
35831 * @param {Boolean} disabled
35833 "disabledchange" : true,
35836 * Fires when a node is collapsed
35837 * @param {Node} node The node
35841 * @event beforeclick
35842 * Fires before click processing on a node. Return false to cancel the default action.
35843 * @param {Node} node The node
35844 * @param {Roo.EventObject} e The event object
35846 "beforeclick":true,
35848 * @event checkchange
35849 * Fires when a node with a checkbox's checked property changes
35850 * @param {Node} this This node
35851 * @param {Boolean} checked
35853 "checkchange":true,
35856 * Fires when a node is clicked
35857 * @param {Node} node The node
35858 * @param {Roo.EventObject} e The event object
35863 * Fires when a node is double clicked
35864 * @param {Node} node The node
35865 * @param {Roo.EventObject} e The event object
35869 * @event contextmenu
35870 * Fires when a node is right clicked
35871 * @param {Node} node The node
35872 * @param {Roo.EventObject} e The event object
35874 "contextmenu":true,
35876 * @event beforechildrenrendered
35877 * Fires right before the child nodes for a node are rendered
35878 * @param {Node} node The node
35880 "beforechildrenrendered":true,
35883 * Fires when a node starts being dragged
35884 * @param {Roo.tree.TreePanel} this
35885 * @param {Roo.tree.TreeNode} node
35886 * @param {event} e The raw browser event
35888 "startdrag" : true,
35891 * Fires when a drag operation is complete
35892 * @param {Roo.tree.TreePanel} this
35893 * @param {Roo.tree.TreeNode} node
35894 * @param {event} e The raw browser event
35899 * Fires when a dragged node is dropped on a valid DD target
35900 * @param {Roo.tree.TreePanel} this
35901 * @param {Roo.tree.TreeNode} node
35902 * @param {DD} dd The dd it was dropped on
35903 * @param {event} e The raw browser event
35907 * @event beforenodedrop
35908 * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
35909 * passed to handlers has the following properties:<br />
35910 * <ul style="padding:5px;padding-left:16px;">
35911 * <li>tree - The TreePanel</li>
35912 * <li>target - The node being targeted for the drop</li>
35913 * <li>data - The drag data from the drag source</li>
35914 * <li>point - The point of the drop - append, above or below</li>
35915 * <li>source - The drag source</li>
35916 * <li>rawEvent - Raw mouse event</li>
35917 * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
35918 * to be inserted by setting them on this object.</li>
35919 * <li>cancel - Set this to true to cancel the drop.</li>
35921 * @param {Object} dropEvent
35923 "beforenodedrop" : true,
35926 * Fires after a DD object is dropped on a node in this tree. The dropEvent
35927 * passed to handlers has the following properties:<br />
35928 * <ul style="padding:5px;padding-left:16px;">
35929 * <li>tree - The TreePanel</li>
35930 * <li>target - The node being targeted for the drop</li>
35931 * <li>data - The drag data from the drag source</li>
35932 * <li>point - The point of the drop - append, above or below</li>
35933 * <li>source - The drag source</li>
35934 * <li>rawEvent - Raw mouse event</li>
35935 * <li>dropNode - Dropped node(s).</li>
35937 * @param {Object} dropEvent
35941 * @event nodedragover
35942 * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
35943 * passed to handlers has the following properties:<br />
35944 * <ul style="padding:5px;padding-left:16px;">
35945 * <li>tree - The TreePanel</li>
35946 * <li>target - The node being targeted for the drop</li>
35947 * <li>data - The drag data from the drag source</li>
35948 * <li>point - The point of the drop - append, above or below</li>
35949 * <li>source - The drag source</li>
35950 * <li>rawEvent - Raw mouse event</li>
35951 * <li>dropNode - Drop node(s) provided by the source.</li>
35952 * <li>cancel - Set this to true to signal drop not allowed.</li>
35954 * @param {Object} dragOverEvent
35956 "nodedragover" : true,
35958 * @event appendnode
35959 * Fires when append node to the tree
35960 * @param {Roo.tree.TreePanel} this
35961 * @param {Roo.tree.TreeNode} node
35962 * @param {Number} index The index of the newly appended node
35964 "appendnode" : true
35967 if(this.singleExpand){
35968 this.on("beforeexpand", this.restrictExpand, this);
35971 this.editor.tree = this;
35972 this.editor = Roo.factory(this.editor, Roo.tree);
35975 if (this.selModel) {
35976 this.selModel = Roo.factory(this.selModel, Roo.tree);
35980 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
35981 rootVisible : true,
35982 animate: Roo.enableFx,
35985 hlDrop : Roo.enableFx,
35989 rendererTip: false,
35991 restrictExpand : function(node){
35992 var p = node.parentNode;
35994 if(p.expandedChild && p.expandedChild.parentNode == p){
35995 p.expandedChild.collapse();
35997 p.expandedChild = node;
36001 // private override
36002 setRootNode : function(node){
36003 Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
36004 if(!this.rootVisible){
36005 node.ui = new Roo.tree.RootTreeNodeUI(node);
36011 * Returns the container element for this TreePanel
36013 getEl : function(){
36018 * Returns the default TreeLoader for this TreePanel
36020 getLoader : function(){
36021 return this.loader;
36027 expandAll : function(){
36028 this.root.expand(true);
36032 * Collapse all nodes
36034 collapseAll : function(){
36035 this.root.collapse(true);
36039 * Returns the selection model used by this TreePanel
36041 getSelectionModel : function(){
36042 if(!this.selModel){
36043 this.selModel = new Roo.tree.DefaultSelectionModel();
36045 return this.selModel;
36049 * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
36050 * @param {String} attribute (optional) Defaults to null (return the actual nodes)
36051 * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
36054 getChecked : function(a, startNode){
36055 startNode = startNode || this.root;
36057 var f = function(){
36058 if(this.attributes.checked){
36059 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
36062 startNode.cascade(f);
36067 * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
36068 * @param {String} path
36069 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
36070 * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
36071 * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
36073 expandPath : function(path, attr, callback){
36074 attr = attr || "id";
36075 var keys = path.split(this.pathSeparator);
36076 var curNode = this.root;
36077 if(curNode.attributes[attr] != keys[1]){ // invalid root
36079 callback(false, null);
36084 var f = function(){
36085 if(++index == keys.length){
36087 callback(true, curNode);
36091 var c = curNode.findChild(attr, keys[index]);
36094 callback(false, curNode);
36099 c.expand(false, false, f);
36101 curNode.expand(false, false, f);
36105 * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
36106 * @param {String} path
36107 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
36108 * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
36109 * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
36111 selectPath : function(path, attr, callback){
36112 attr = attr || "id";
36113 var keys = path.split(this.pathSeparator);
36114 var v = keys.pop();
36115 if(keys.length > 0){
36116 var f = function(success, node){
36117 if(success && node){
36118 var n = node.findChild(attr, v);
36124 }else if(callback){
36125 callback(false, n);
36129 callback(false, n);
36133 this.expandPath(keys.join(this.pathSeparator), attr, f);
36135 this.root.select();
36137 callback(true, this.root);
36142 getTreeEl : function(){
36147 * Trigger rendering of this TreePanel
36149 render : function(){
36150 if (this.innerCt) {
36151 return this; // stop it rendering more than once!!
36154 this.innerCt = this.el.createChild({tag:"ul",
36155 cls:"x-tree-root-ct " +
36156 (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
36158 if(this.containerScroll){
36159 Roo.dd.ScrollManager.register(this.el);
36161 if((this.enableDD || this.enableDrop) && !this.dropZone){
36163 * The dropZone used by this tree if drop is enabled
36164 * @type Roo.tree.TreeDropZone
36166 this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
36167 ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
36170 if((this.enableDD || this.enableDrag) && !this.dragZone){
36172 * The dragZone used by this tree if drag is enabled
36173 * @type Roo.tree.TreeDragZone
36175 this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
36176 ddGroup: this.ddGroup || "TreeDD",
36177 scroll: this.ddScroll
36180 this.getSelectionModel().init(this);
36182 Roo.log("ROOT not set in tree");
36185 this.root.render();
36186 if(!this.rootVisible){
36187 this.root.renderChildren();
36193 * Ext JS Library 1.1.1
36194 * Copyright(c) 2006-2007, Ext JS, LLC.
36196 * Originally Released Under LGPL - original licence link has changed is not relivant.
36199 * <script type="text/javascript">
36204 * @class Roo.tree.DefaultSelectionModel
36205 * @extends Roo.util.Observable
36206 * The default single selection for a TreePanel.
36207 * @param {Object} cfg Configuration
36209 Roo.tree.DefaultSelectionModel = function(cfg){
36210 this.selNode = null;
36216 * @event selectionchange
36217 * Fires when the selected node changes
36218 * @param {DefaultSelectionModel} this
36219 * @param {TreeNode} node the new selection
36221 "selectionchange" : true,
36224 * @event beforeselect
36225 * Fires before the selected node changes, return false to cancel the change
36226 * @param {DefaultSelectionModel} this
36227 * @param {TreeNode} node the new selection
36228 * @param {TreeNode} node the old selection
36230 "beforeselect" : true
36233 Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
36236 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
36237 init : function(tree){
36239 tree.getTreeEl().on("keydown", this.onKeyDown, this);
36240 tree.on("click", this.onNodeClick, this);
36243 onNodeClick : function(node, e){
36244 if (e.ctrlKey && this.selNode == node) {
36245 this.unselect(node);
36253 * @param {TreeNode} node The node to select
36254 * @return {TreeNode} The selected node
36256 select : function(node){
36257 var last = this.selNode;
36258 if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
36260 last.ui.onSelectedChange(false);
36262 this.selNode = node;
36263 node.ui.onSelectedChange(true);
36264 this.fireEvent("selectionchange", this, node, last);
36271 * @param {TreeNode} node The node to unselect
36273 unselect : function(node){
36274 if(this.selNode == node){
36275 this.clearSelections();
36280 * Clear all selections
36282 clearSelections : function(){
36283 var n = this.selNode;
36285 n.ui.onSelectedChange(false);
36286 this.selNode = null;
36287 this.fireEvent("selectionchange", this, null);
36293 * Get the selected node
36294 * @return {TreeNode} The selected node
36296 getSelectedNode : function(){
36297 return this.selNode;
36301 * Returns true if the node is selected
36302 * @param {TreeNode} node The node to check
36303 * @return {Boolean}
36305 isSelected : function(node){
36306 return this.selNode == node;
36310 * Selects the node above the selected node in the tree, intelligently walking the nodes
36311 * @return TreeNode The new selection
36313 selectPrevious : function(){
36314 var s = this.selNode || this.lastSelNode;
36318 var ps = s.previousSibling;
36320 if(!ps.isExpanded() || ps.childNodes.length < 1){
36321 return this.select(ps);
36323 var lc = ps.lastChild;
36324 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
36327 return this.select(lc);
36329 } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
36330 return this.select(s.parentNode);
36336 * Selects the node above the selected node in the tree, intelligently walking the nodes
36337 * @return TreeNode The new selection
36339 selectNext : function(){
36340 var s = this.selNode || this.lastSelNode;
36344 if(s.firstChild && s.isExpanded()){
36345 return this.select(s.firstChild);
36346 }else if(s.nextSibling){
36347 return this.select(s.nextSibling);
36348 }else if(s.parentNode){
36350 s.parentNode.bubble(function(){
36351 if(this.nextSibling){
36352 newS = this.getOwnerTree().selModel.select(this.nextSibling);
36361 onKeyDown : function(e){
36362 var s = this.selNode || this.lastSelNode;
36363 // undesirable, but required
36368 var k = e.getKey();
36376 this.selectPrevious();
36379 e.preventDefault();
36380 if(s.hasChildNodes()){
36381 if(!s.isExpanded()){
36383 }else if(s.firstChild){
36384 this.select(s.firstChild, e);
36389 e.preventDefault();
36390 if(s.hasChildNodes() && s.isExpanded()){
36392 }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
36393 this.select(s.parentNode, e);
36401 * @class Roo.tree.MultiSelectionModel
36402 * @extends Roo.util.Observable
36403 * Multi selection for a TreePanel.
36404 * @param {Object} cfg Configuration
36406 Roo.tree.MultiSelectionModel = function(){
36407 this.selNodes = [];
36411 * @event selectionchange
36412 * Fires when the selected nodes change
36413 * @param {MultiSelectionModel} this
36414 * @param {Array} nodes Array of the selected nodes
36416 "selectionchange" : true
36418 Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
36422 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
36423 init : function(tree){
36425 tree.getTreeEl().on("keydown", this.onKeyDown, this);
36426 tree.on("click", this.onNodeClick, this);
36429 onNodeClick : function(node, e){
36430 this.select(node, e, e.ctrlKey);
36435 * @param {TreeNode} node The node to select
36436 * @param {EventObject} e (optional) An event associated with the selection
36437 * @param {Boolean} keepExisting True to retain existing selections
36438 * @return {TreeNode} The selected node
36440 select : function(node, e, keepExisting){
36441 if(keepExisting !== true){
36442 this.clearSelections(true);
36444 if(this.isSelected(node)){
36445 this.lastSelNode = node;
36448 this.selNodes.push(node);
36449 this.selMap[node.id] = node;
36450 this.lastSelNode = node;
36451 node.ui.onSelectedChange(true);
36452 this.fireEvent("selectionchange", this, this.selNodes);
36458 * @param {TreeNode} node The node to unselect
36460 unselect : function(node){
36461 if(this.selMap[node.id]){
36462 node.ui.onSelectedChange(false);
36463 var sn = this.selNodes;
36466 index = sn.indexOf(node);
36468 for(var i = 0, len = sn.length; i < len; i++){
36476 this.selNodes.splice(index, 1);
36478 delete this.selMap[node.id];
36479 this.fireEvent("selectionchange", this, this.selNodes);
36484 * Clear all selections
36486 clearSelections : function(suppressEvent){
36487 var sn = this.selNodes;
36489 for(var i = 0, len = sn.length; i < len; i++){
36490 sn[i].ui.onSelectedChange(false);
36492 this.selNodes = [];
36494 if(suppressEvent !== true){
36495 this.fireEvent("selectionchange", this, this.selNodes);
36501 * Returns true if the node is selected
36502 * @param {TreeNode} node The node to check
36503 * @return {Boolean}
36505 isSelected : function(node){
36506 return this.selMap[node.id] ? true : false;
36510 * Returns an array of the selected nodes
36513 getSelectedNodes : function(){
36514 return this.selNodes;
36517 onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
36519 selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
36521 selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
36524 * Ext JS Library 1.1.1
36525 * Copyright(c) 2006-2007, Ext JS, LLC.
36527 * Originally Released Under LGPL - original licence link has changed is not relivant.
36530 * <script type="text/javascript">
36534 * @class Roo.tree.TreeNode
36535 * @extends Roo.data.Node
36536 * @cfg {String} text The text for this node
36537 * @cfg {Boolean} expanded true to start the node expanded
36538 * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
36539 * @cfg {Boolean} allowDrop false if this node cannot be drop on
36540 * @cfg {Boolean} disabled true to start the node disabled
36541 * @cfg {String} icon The path to an icon for the node. The preferred way to do this
36542 * is to use the cls or iconCls attributes and add the icon via a CSS background image.
36543 * @cfg {String} cls A css class to be added to the node
36544 * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
36545 * @cfg {String} href URL of the link used for the node (defaults to #)
36546 * @cfg {String} hrefTarget target frame for the link
36547 * @cfg {String} qtip An Ext QuickTip for the node
36548 * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
36549 * @cfg {Boolean} singleClickExpand True for single click expand on this node
36550 * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
36551 * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
36552 * (defaults to undefined with no checkbox rendered)
36554 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
36556 Roo.tree.TreeNode = function(attributes){
36557 attributes = attributes || {};
36558 if(typeof attributes == "string"){
36559 attributes = {text: attributes};
36561 this.childrenRendered = false;
36562 this.rendered = false;
36563 Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
36564 this.expanded = attributes.expanded === true;
36565 this.isTarget = attributes.isTarget !== false;
36566 this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
36567 this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
36570 * Read-only. The text for this node. To change it use setText().
36573 this.text = attributes.text;
36575 * True if this node is disabled.
36578 this.disabled = attributes.disabled === true;
36582 * @event textchange
36583 * Fires when the text for this node is changed
36584 * @param {Node} this This node
36585 * @param {String} text The new text
36586 * @param {String} oldText The old text
36588 "textchange" : true,
36590 * @event beforeexpand
36591 * Fires before this node is expanded, return false to cancel.
36592 * @param {Node} this This node
36593 * @param {Boolean} deep
36594 * @param {Boolean} anim
36596 "beforeexpand" : true,
36598 * @event beforecollapse
36599 * Fires before this node is collapsed, return false to cancel.
36600 * @param {Node} this This node
36601 * @param {Boolean} deep
36602 * @param {Boolean} anim
36604 "beforecollapse" : true,
36607 * Fires when this node is expanded
36608 * @param {Node} this This node
36612 * @event disabledchange
36613 * Fires when the disabled status of this node changes
36614 * @param {Node} this This node
36615 * @param {Boolean} disabled
36617 "disabledchange" : true,
36620 * Fires when this node is collapsed
36621 * @param {Node} this This node
36625 * @event beforeclick
36626 * Fires before click processing. Return false to cancel the default action.
36627 * @param {Node} this This node
36628 * @param {Roo.EventObject} e The event object
36630 "beforeclick":true,
36632 * @event checkchange
36633 * Fires when a node with a checkbox's checked property changes
36634 * @param {Node} this This node
36635 * @param {Boolean} checked
36637 "checkchange":true,
36640 * Fires when this node is clicked
36641 * @param {Node} this This node
36642 * @param {Roo.EventObject} e The event object
36647 * Fires when this node is double clicked
36648 * @param {Node} this This node
36649 * @param {Roo.EventObject} e The event object
36653 * @event contextmenu
36654 * Fires when this node is right clicked
36655 * @param {Node} this This node
36656 * @param {Roo.EventObject} e The event object
36658 "contextmenu":true,
36660 * @event beforechildrenrendered
36661 * Fires right before the child nodes for this node are rendered
36662 * @param {Node} this This node
36664 "beforechildrenrendered":true
36667 var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
36670 * Read-only. The UI for this node
36673 this.ui = new uiClass(this);
36675 // finally support items[]
36676 if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
36681 Roo.each(this.attributes.items, function(c) {
36682 this.appendChild(Roo.factory(c,Roo.Tree));
36684 delete this.attributes.items;
36689 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
36690 preventHScroll: true,
36692 * Returns true if this node is expanded
36693 * @return {Boolean}
36695 isExpanded : function(){
36696 return this.expanded;
36700 * Returns the UI object for this node
36701 * @return {TreeNodeUI}
36703 getUI : function(){
36707 // private override
36708 setFirstChild : function(node){
36709 var of = this.firstChild;
36710 Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
36711 if(this.childrenRendered && of && node != of){
36712 of.renderIndent(true, true);
36715 this.renderIndent(true, true);
36719 // private override
36720 setLastChild : function(node){
36721 var ol = this.lastChild;
36722 Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
36723 if(this.childrenRendered && ol && node != ol){
36724 ol.renderIndent(true, true);
36727 this.renderIndent(true, true);
36731 // these methods are overridden to provide lazy rendering support
36732 // private override
36733 appendChild : function()
36735 var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
36736 if(node && this.childrenRendered){
36739 this.ui.updateExpandIcon();
36743 // private override
36744 removeChild : function(node){
36745 this.ownerTree.getSelectionModel().unselect(node);
36746 Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
36747 // if it's been rendered remove dom node
36748 if(this.childrenRendered){
36751 if(this.childNodes.length < 1){
36752 this.collapse(false, false);
36754 this.ui.updateExpandIcon();
36756 if(!this.firstChild) {
36757 this.childrenRendered = false;
36762 // private override
36763 insertBefore : function(node, refNode){
36764 var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
36765 if(newNode && refNode && this.childrenRendered){
36768 this.ui.updateExpandIcon();
36773 * Sets the text for this node
36774 * @param {String} text
36776 setText : function(text){
36777 var oldText = this.text;
36779 this.attributes.text = text;
36780 if(this.rendered){ // event without subscribing
36781 this.ui.onTextChange(this, text, oldText);
36783 this.fireEvent("textchange", this, text, oldText);
36787 * Triggers selection of this node
36789 select : function(){
36790 this.getOwnerTree().getSelectionModel().select(this);
36794 * Triggers deselection of this node
36796 unselect : function(){
36797 this.getOwnerTree().getSelectionModel().unselect(this);
36801 * Returns true if this node is selected
36802 * @return {Boolean}
36804 isSelected : function(){
36805 return this.getOwnerTree().getSelectionModel().isSelected(this);
36809 * Expand this node.
36810 * @param {Boolean} deep (optional) True to expand all children as well
36811 * @param {Boolean} anim (optional) false to cancel the default animation
36812 * @param {Function} callback (optional) A callback to be called when
36813 * expanding this node completes (does not wait for deep expand to complete).
36814 * Called with 1 parameter, this node.
36816 expand : function(deep, anim, callback){
36817 if(!this.expanded){
36818 if(this.fireEvent("beforeexpand", this, deep, anim) === false){
36821 if(!this.childrenRendered){
36822 this.renderChildren();
36824 this.expanded = true;
36826 if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
36827 this.ui.animExpand(function(){
36828 this.fireEvent("expand", this);
36829 if(typeof callback == "function"){
36833 this.expandChildNodes(true);
36835 }.createDelegate(this));
36839 this.fireEvent("expand", this);
36840 if(typeof callback == "function"){
36845 if(typeof callback == "function"){
36850 this.expandChildNodes(true);
36854 isHiddenRoot : function(){
36855 return this.isRoot && !this.getOwnerTree().rootVisible;
36859 * Collapse this node.
36860 * @param {Boolean} deep (optional) True to collapse all children as well
36861 * @param {Boolean} anim (optional) false to cancel the default animation
36863 collapse : function(deep, anim){
36864 if(this.expanded && !this.isHiddenRoot()){
36865 if(this.fireEvent("beforecollapse", this, deep, anim) === false){
36868 this.expanded = false;
36869 if((this.getOwnerTree().animate && anim !== false) || anim){
36870 this.ui.animCollapse(function(){
36871 this.fireEvent("collapse", this);
36873 this.collapseChildNodes(true);
36875 }.createDelegate(this));
36878 this.ui.collapse();
36879 this.fireEvent("collapse", this);
36883 var cs = this.childNodes;
36884 for(var i = 0, len = cs.length; i < len; i++) {
36885 cs[i].collapse(true, false);
36891 delayedExpand : function(delay){
36892 if(!this.expandProcId){
36893 this.expandProcId = this.expand.defer(delay, this);
36898 cancelExpand : function(){
36899 if(this.expandProcId){
36900 clearTimeout(this.expandProcId);
36902 this.expandProcId = false;
36906 * Toggles expanded/collapsed state of the node
36908 toggle : function(){
36917 * Ensures all parent nodes are expanded
36919 ensureVisible : function(callback){
36920 var tree = this.getOwnerTree();
36921 tree.expandPath(this.parentNode.getPath(), false, function(){
36922 tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
36923 Roo.callback(callback);
36924 }.createDelegate(this));
36928 * Expand all child nodes
36929 * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
36931 expandChildNodes : function(deep){
36932 var cs = this.childNodes;
36933 for(var i = 0, len = cs.length; i < len; i++) {
36934 cs[i].expand(deep);
36939 * Collapse all child nodes
36940 * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
36942 collapseChildNodes : function(deep){
36943 var cs = this.childNodes;
36944 for(var i = 0, len = cs.length; i < len; i++) {
36945 cs[i].collapse(deep);
36950 * Disables this node
36952 disable : function(){
36953 this.disabled = true;
36955 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
36956 this.ui.onDisableChange(this, true);
36958 this.fireEvent("disabledchange", this, true);
36962 * Enables this node
36964 enable : function(){
36965 this.disabled = false;
36966 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
36967 this.ui.onDisableChange(this, false);
36969 this.fireEvent("disabledchange", this, false);
36973 renderChildren : function(suppressEvent){
36974 if(suppressEvent !== false){
36975 this.fireEvent("beforechildrenrendered", this);
36977 var cs = this.childNodes;
36978 for(var i = 0, len = cs.length; i < len; i++){
36979 cs[i].render(true);
36981 this.childrenRendered = true;
36985 sort : function(fn, scope){
36986 Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
36987 if(this.childrenRendered){
36988 var cs = this.childNodes;
36989 for(var i = 0, len = cs.length; i < len; i++){
36990 cs[i].render(true);
36996 render : function(bulkRender){
36997 this.ui.render(bulkRender);
36998 if(!this.rendered){
36999 this.rendered = true;
37001 this.expanded = false;
37002 this.expand(false, false);
37008 renderIndent : function(deep, refresh){
37010 this.ui.childIndent = null;
37012 this.ui.renderIndent();
37013 if(deep === true && this.childrenRendered){
37014 var cs = this.childNodes;
37015 for(var i = 0, len = cs.length; i < len; i++){
37016 cs[i].renderIndent(true, refresh);
37022 * Ext JS Library 1.1.1
37023 * Copyright(c) 2006-2007, Ext JS, LLC.
37025 * Originally Released Under LGPL - original licence link has changed is not relivant.
37028 * <script type="text/javascript">
37032 * @class Roo.tree.AsyncTreeNode
37033 * @extends Roo.tree.TreeNode
37034 * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
37036 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
37038 Roo.tree.AsyncTreeNode = function(config){
37039 this.loaded = false;
37040 this.loading = false;
37041 Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
37043 * @event beforeload
37044 * Fires before this node is loaded, return false to cancel
37045 * @param {Node} this This node
37047 this.addEvents({'beforeload':true, 'load': true});
37050 * Fires when this node is loaded
37051 * @param {Node} this This node
37054 * The loader used by this node (defaults to using the tree's defined loader)
37059 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
37060 expand : function(deep, anim, callback){
37061 if(this.loading){ // if an async load is already running, waiting til it's done
37063 var f = function(){
37064 if(!this.loading){ // done loading
37065 clearInterval(timer);
37066 this.expand(deep, anim, callback);
37068 }.createDelegate(this);
37069 timer = setInterval(f, 200);
37073 if(this.fireEvent("beforeload", this) === false){
37076 this.loading = true;
37077 this.ui.beforeLoad(this);
37078 var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
37080 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
37084 Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
37088 * Returns true if this node is currently loading
37089 * @return {Boolean}
37091 isLoading : function(){
37092 return this.loading;
37095 loadComplete : function(deep, anim, callback){
37096 this.loading = false;
37097 this.loaded = true;
37098 this.ui.afterLoad(this);
37099 this.fireEvent("load", this);
37100 this.expand(deep, anim, callback);
37104 * Returns true if this node has been loaded
37105 * @return {Boolean}
37107 isLoaded : function(){
37108 return this.loaded;
37111 hasChildNodes : function(){
37112 if(!this.isLeaf() && !this.loaded){
37115 return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
37120 * Trigger a reload for this node
37121 * @param {Function} callback
37123 reload : function(callback){
37124 this.collapse(false, false);
37125 while(this.firstChild){
37126 this.removeChild(this.firstChild);
37128 this.childrenRendered = false;
37129 this.loaded = false;
37130 if(this.isHiddenRoot()){
37131 this.expanded = false;
37133 this.expand(false, false, callback);
37137 * Ext JS Library 1.1.1
37138 * Copyright(c) 2006-2007, Ext JS, LLC.
37140 * Originally Released Under LGPL - original licence link has changed is not relivant.
37143 * <script type="text/javascript">
37147 * @class Roo.tree.TreeNodeUI
37149 * @param {Object} node The node to render
37150 * The TreeNode UI implementation is separate from the
37151 * tree implementation. Unless you are customizing the tree UI,
37152 * you should never have to use this directly.
37154 Roo.tree.TreeNodeUI = function(node){
37156 this.rendered = false;
37157 this.animating = false;
37158 this.emptyIcon = Roo.BLANK_IMAGE_URL;
37161 Roo.tree.TreeNodeUI.prototype = {
37162 removeChild : function(node){
37164 this.ctNode.removeChild(node.ui.getEl());
37168 beforeLoad : function(){
37169 this.addClass("x-tree-node-loading");
37172 afterLoad : function(){
37173 this.removeClass("x-tree-node-loading");
37176 onTextChange : function(node, text, oldText){
37178 this.textNode.innerHTML = text;
37182 onDisableChange : function(node, state){
37183 this.disabled = state;
37185 this.addClass("x-tree-node-disabled");
37187 this.removeClass("x-tree-node-disabled");
37191 onSelectedChange : function(state){
37194 this.addClass("x-tree-selected");
37197 this.removeClass("x-tree-selected");
37201 onMove : function(tree, node, oldParent, newParent, index, refNode){
37202 this.childIndent = null;
37204 var targetNode = newParent.ui.getContainer();
37205 if(!targetNode){//target not rendered
37206 this.holder = document.createElement("div");
37207 this.holder.appendChild(this.wrap);
37210 var insertBefore = refNode ? refNode.ui.getEl() : null;
37212 targetNode.insertBefore(this.wrap, insertBefore);
37214 targetNode.appendChild(this.wrap);
37216 this.node.renderIndent(true);
37220 addClass : function(cls){
37222 Roo.fly(this.elNode).addClass(cls);
37226 removeClass : function(cls){
37228 Roo.fly(this.elNode).removeClass(cls);
37232 remove : function(){
37234 this.holder = document.createElement("div");
37235 this.holder.appendChild(this.wrap);
37239 fireEvent : function(){
37240 return this.node.fireEvent.apply(this.node, arguments);
37243 initEvents : function(){
37244 this.node.on("move", this.onMove, this);
37245 var E = Roo.EventManager;
37246 var a = this.anchor;
37248 var el = Roo.fly(a, '_treeui');
37250 if(Roo.isOpera){ // opera render bug ignores the CSS
37251 el.setStyle("text-decoration", "none");
37254 el.on("click", this.onClick, this);
37255 el.on("dblclick", this.onDblClick, this);
37258 Roo.EventManager.on(this.checkbox,
37259 Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
37262 el.on("contextmenu", this.onContextMenu, this);
37264 var icon = Roo.fly(this.iconNode);
37265 icon.on("click", this.onClick, this);
37266 icon.on("dblclick", this.onDblClick, this);
37267 icon.on("contextmenu", this.onContextMenu, this);
37268 E.on(this.ecNode, "click", this.ecClick, this, true);
37270 if(this.node.disabled){
37271 this.addClass("x-tree-node-disabled");
37273 if(this.node.hidden){
37274 this.addClass("x-tree-node-disabled");
37276 var ot = this.node.getOwnerTree();
37277 var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
37278 if(dd && (!this.node.isRoot || ot.rootVisible)){
37279 Roo.dd.Registry.register(this.elNode, {
37281 handles: this.getDDHandles(),
37287 getDDHandles : function(){
37288 return [this.iconNode, this.textNode];
37293 this.wrap.style.display = "none";
37299 this.wrap.style.display = "";
37303 onContextMenu : function(e){
37304 if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
37305 e.preventDefault();
37307 this.fireEvent("contextmenu", this.node, e);
37311 onClick : function(e){
37316 if(this.fireEvent("beforeclick", this.node, e) !== false){
37317 if(!this.disabled && this.node.attributes.href){
37318 this.fireEvent("click", this.node, e);
37321 e.preventDefault();
37326 if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
37327 this.node.toggle();
37330 this.fireEvent("click", this.node, e);
37336 onDblClick : function(e){
37337 e.preventDefault();
37342 this.toggleCheck();
37344 if(!this.animating && this.node.hasChildNodes()){
37345 this.node.toggle();
37347 this.fireEvent("dblclick", this.node, e);
37350 onCheckChange : function(){
37351 var checked = this.checkbox.checked;
37352 this.node.attributes.checked = checked;
37353 this.fireEvent('checkchange', this.node, checked);
37356 ecClick : function(e){
37357 if(!this.animating && this.node.hasChildNodes()){
37358 this.node.toggle();
37362 startDrop : function(){
37363 this.dropping = true;
37366 // delayed drop so the click event doesn't get fired on a drop
37367 endDrop : function(){
37368 setTimeout(function(){
37369 this.dropping = false;
37370 }.createDelegate(this), 50);
37373 expand : function(){
37374 this.updateExpandIcon();
37375 this.ctNode.style.display = "";
37378 focus : function(){
37379 if(!this.node.preventHScroll){
37380 try{this.anchor.focus();
37382 }else if(!Roo.isIE){
37384 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
37385 var l = noscroll.scrollLeft;
37386 this.anchor.focus();
37387 noscroll.scrollLeft = l;
37392 toggleCheck : function(value){
37393 var cb = this.checkbox;
37395 cb.checked = (value === undefined ? !cb.checked : value);
37401 this.anchor.blur();
37405 animExpand : function(callback){
37406 var ct = Roo.get(this.ctNode);
37408 if(!this.node.hasChildNodes()){
37409 this.updateExpandIcon();
37410 this.ctNode.style.display = "";
37411 Roo.callback(callback);
37414 this.animating = true;
37415 this.updateExpandIcon();
37418 callback : function(){
37419 this.animating = false;
37420 Roo.callback(callback);
37423 duration: this.node.ownerTree.duration || .25
37427 highlight : function(){
37428 var tree = this.node.getOwnerTree();
37429 Roo.fly(this.wrap).highlight(
37430 tree.hlColor || "C3DAF9",
37431 {endColor: tree.hlBaseColor}
37435 collapse : function(){
37436 this.updateExpandIcon();
37437 this.ctNode.style.display = "none";
37440 animCollapse : function(callback){
37441 var ct = Roo.get(this.ctNode);
37442 ct.enableDisplayMode('block');
37445 this.animating = true;
37446 this.updateExpandIcon();
37449 callback : function(){
37450 this.animating = false;
37451 Roo.callback(callback);
37454 duration: this.node.ownerTree.duration || .25
37458 getContainer : function(){
37459 return this.ctNode;
37462 getEl : function(){
37466 appendDDGhost : function(ghostNode){
37467 ghostNode.appendChild(this.elNode.cloneNode(true));
37470 getDDRepairXY : function(){
37471 return Roo.lib.Dom.getXY(this.iconNode);
37474 onRender : function(){
37478 render : function(bulkRender){
37479 var n = this.node, a = n.attributes;
37480 var targetNode = n.parentNode ?
37481 n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
37483 if(!this.rendered){
37484 this.rendered = true;
37486 this.renderElements(n, a, targetNode, bulkRender);
37489 if(this.textNode.setAttributeNS){
37490 this.textNode.setAttributeNS("ext", "qtip", a.qtip);
37492 this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
37495 this.textNode.setAttribute("ext:qtip", a.qtip);
37497 this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
37500 }else if(a.qtipCfg){
37501 a.qtipCfg.target = Roo.id(this.textNode);
37502 Roo.QuickTips.register(a.qtipCfg);
37505 if(!this.node.expanded){
37506 this.updateExpandIcon();
37509 if(bulkRender === true) {
37510 targetNode.appendChild(this.wrap);
37515 renderElements : function(n, a, targetNode, bulkRender)
37517 // add some indent caching, this helps performance when rendering a large tree
37518 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
37519 var t = n.getOwnerTree();
37520 var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
37521 if (typeof(n.attributes.html) != 'undefined') {
37522 txt = n.attributes.html;
37524 var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
37525 var cb = typeof a.checked == 'boolean';
37526 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
37527 var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
37528 '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
37529 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
37530 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
37531 cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
37532 '<a hidefocus="on" href="',href,'" tabIndex="1" ',
37533 a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "",
37534 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
37535 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
37538 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
37539 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
37540 n.nextSibling.ui.getEl(), buf.join(""));
37542 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
37545 this.elNode = this.wrap.childNodes[0];
37546 this.ctNode = this.wrap.childNodes[1];
37547 var cs = this.elNode.childNodes;
37548 this.indentNode = cs[0];
37549 this.ecNode = cs[1];
37550 this.iconNode = cs[2];
37553 this.checkbox = cs[3];
37556 this.anchor = cs[index];
37557 this.textNode = cs[index].firstChild;
37560 getAnchor : function(){
37561 return this.anchor;
37564 getTextEl : function(){
37565 return this.textNode;
37568 getIconEl : function(){
37569 return this.iconNode;
37572 isChecked : function(){
37573 return this.checkbox ? this.checkbox.checked : false;
37576 updateExpandIcon : function(){
37578 var n = this.node, c1, c2;
37579 var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
37580 var hasChild = n.hasChildNodes();
37584 c1 = "x-tree-node-collapsed";
37585 c2 = "x-tree-node-expanded";
37588 c1 = "x-tree-node-expanded";
37589 c2 = "x-tree-node-collapsed";
37592 this.removeClass("x-tree-node-leaf");
37593 this.wasLeaf = false;
37595 if(this.c1 != c1 || this.c2 != c2){
37596 Roo.fly(this.elNode).replaceClass(c1, c2);
37597 this.c1 = c1; this.c2 = c2;
37600 // this changes non-leafs into leafs if they have no children.
37601 // it's not very rational behaviour..
37603 if(!this.wasLeaf && this.node.leaf){
37604 Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
37607 this.wasLeaf = true;
37610 var ecc = "x-tree-ec-icon "+cls;
37611 if(this.ecc != ecc){
37612 this.ecNode.className = ecc;
37618 getChildIndent : function(){
37619 if(!this.childIndent){
37623 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
37625 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
37627 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
37632 this.childIndent = buf.join("");
37634 return this.childIndent;
37637 renderIndent : function(){
37640 var p = this.node.parentNode;
37642 indent = p.ui.getChildIndent();
37644 if(this.indentMarkup != indent){ // don't rerender if not required
37645 this.indentNode.innerHTML = indent;
37646 this.indentMarkup = indent;
37648 this.updateExpandIcon();
37653 Roo.tree.RootTreeNodeUI = function(){
37654 Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
37656 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
37657 render : function(){
37658 if(!this.rendered){
37659 var targetNode = this.node.ownerTree.innerCt.dom;
37660 this.node.expanded = true;
37661 targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
37662 this.wrap = this.ctNode = targetNode.firstChild;
37665 collapse : function(){
37667 expand : function(){
37671 * Ext JS Library 1.1.1
37672 * Copyright(c) 2006-2007, Ext JS, LLC.
37674 * Originally Released Under LGPL - original licence link has changed is not relivant.
37677 * <script type="text/javascript">
37680 * @class Roo.tree.TreeLoader
37681 * @extends Roo.util.Observable
37682 * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
37683 * nodes from a specified URL. The response must be a javascript Array definition
37684 * who's elements are node definition objects. eg:
37689 { 'id': 1, 'text': 'A folder Node', 'leaf': false },
37690 { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
37697 * The old style respose with just an array is still supported, but not recommended.
37700 * A server request is sent, and child nodes are loaded only when a node is expanded.
37701 * The loading node's id is passed to the server under the parameter name "node" to
37702 * enable the server to produce the correct child nodes.
37704 * To pass extra parameters, an event handler may be attached to the "beforeload"
37705 * event, and the parameters specified in the TreeLoader's baseParams property:
37707 myTreeLoader.on("beforeload", function(treeLoader, node) {
37708 this.baseParams.category = node.attributes.category;
37713 * This would pass an HTTP parameter called "category" to the server containing
37714 * the value of the Node's "category" attribute.
37716 * Creates a new Treeloader.
37717 * @param {Object} config A config object containing config properties.
37719 Roo.tree.TreeLoader = function(config){
37720 this.baseParams = {};
37721 this.requestMethod = "POST";
37722 Roo.apply(this, config);
37727 * @event beforeload
37728 * Fires before a network request is made to retrieve the Json text which specifies a node's children.
37729 * @param {Object} This TreeLoader object.
37730 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37731 * @param {Object} callback The callback function specified in the {@link #load} call.
37736 * Fires when the node has been successfuly loaded.
37737 * @param {Object} This TreeLoader object.
37738 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37739 * @param {Object} response The response object containing the data from the server.
37743 * @event loadexception
37744 * Fires if the network request failed.
37745 * @param {Object} This TreeLoader object.
37746 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37747 * @param {Object} response The response object containing the data from the server.
37749 loadexception : true,
37752 * Fires before a node is created, enabling you to return custom Node types
37753 * @param {Object} This TreeLoader object.
37754 * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
37759 Roo.tree.TreeLoader.superclass.constructor.call(this);
37762 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
37764 * @cfg {String} dataUrl The URL from which to request a Json string which
37765 * specifies an array of node definition object representing the child nodes
37769 * @cfg {String} requestMethod either GET or POST
37770 * defaults to POST (due to BC)
37774 * @cfg {Object} baseParams (optional) An object containing properties which
37775 * specify HTTP parameters to be passed to each request for child nodes.
37778 * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
37779 * created by this loader. If the attributes sent by the server have an attribute in this object,
37780 * they take priority.
37783 * @cfg {Object} uiProviders (optional) An object containing properties which
37785 * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
37786 * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
37787 * <i>uiProvider</i> attribute of a returned child node is a string rather
37788 * than a reference to a TreeNodeUI implementation, this that string value
37789 * is used as a property name in the uiProviders object. You can define the provider named
37790 * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
37795 * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
37796 * child nodes before loading.
37798 clearOnLoad : true,
37801 * @cfg {String} root (optional) Default to false. Use this to read data from an object
37802 * property on loading, rather than expecting an array. (eg. more compatible to a standard
37803 * Grid query { data : [ .....] }
37808 * @cfg {String} queryParam (optional)
37809 * Name of the query as it will be passed on the querystring (defaults to 'node')
37810 * eg. the request will be ?node=[id]
37817 * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
37818 * This is called automatically when a node is expanded, but may be used to reload
37819 * a node (or append new children if the {@link #clearOnLoad} option is false.)
37820 * @param {Roo.tree.TreeNode} node
37821 * @param {Function} callback
37823 load : function(node, callback){
37824 if(this.clearOnLoad){
37825 while(node.firstChild){
37826 node.removeChild(node.firstChild);
37829 if(node.attributes.children){ // preloaded json children
37830 var cs = node.attributes.children;
37831 for(var i = 0, len = cs.length; i < len; i++){
37832 node.appendChild(this.createNode(cs[i]));
37834 if(typeof callback == "function"){
37837 }else if(this.dataUrl){
37838 this.requestData(node, callback);
37842 getParams: function(node){
37843 var buf = [], bp = this.baseParams;
37844 for(var key in bp){
37845 if(typeof bp[key] != "function"){
37846 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
37849 var n = this.queryParam === false ? 'node' : this.queryParam;
37850 buf.push(n + "=", encodeURIComponent(node.id));
37851 return buf.join("");
37854 requestData : function(node, callback){
37855 if(this.fireEvent("beforeload", this, node, callback) !== false){
37856 this.transId = Roo.Ajax.request({
37857 method:this.requestMethod,
37858 url: this.dataUrl||this.url,
37859 success: this.handleResponse,
37860 failure: this.handleFailure,
37862 argument: {callback: callback, node: node},
37863 params: this.getParams(node)
37866 // if the load is cancelled, make sure we notify
37867 // the node that we are done
37868 if(typeof callback == "function"){
37874 isLoading : function(){
37875 return this.transId ? true : false;
37878 abort : function(){
37879 if(this.isLoading()){
37880 Roo.Ajax.abort(this.transId);
37885 createNode : function(attr)
37887 // apply baseAttrs, nice idea Corey!
37888 if(this.baseAttrs){
37889 Roo.applyIf(attr, this.baseAttrs);
37891 if(this.applyLoader !== false){
37892 attr.loader = this;
37894 // uiProvider = depreciated..
37896 if(typeof(attr.uiProvider) == 'string'){
37897 attr.uiProvider = this.uiProviders[attr.uiProvider] ||
37898 /** eval:var:attr */ eval(attr.uiProvider);
37900 if(typeof(this.uiProviders['default']) != 'undefined') {
37901 attr.uiProvider = this.uiProviders['default'];
37904 this.fireEvent('create', this, attr);
37906 attr.leaf = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
37908 new Roo.tree.TreeNode(attr) :
37909 new Roo.tree.AsyncTreeNode(attr));
37912 processResponse : function(response, node, callback)
37914 var json = response.responseText;
37917 var o = Roo.decode(json);
37919 if (this.root === false && typeof(o.success) != undefined) {
37920 this.root = 'data'; // the default behaviour for list like data..
37923 if (this.root !== false && !o.success) {
37924 // it's a failure condition.
37925 var a = response.argument;
37926 this.fireEvent("loadexception", this, a.node, response);
37927 Roo.log("Load failed - should have a handler really");
37933 if (this.root !== false) {
37937 for(var i = 0, len = o.length; i < len; i++){
37938 var n = this.createNode(o[i]);
37940 node.appendChild(n);
37943 if(typeof callback == "function"){
37944 callback(this, node);
37947 this.handleFailure(response);
37951 handleResponse : function(response){
37952 this.transId = false;
37953 var a = response.argument;
37954 this.processResponse(response, a.node, a.callback);
37955 this.fireEvent("load", this, a.node, response);
37958 handleFailure : function(response)
37960 // should handle failure better..
37961 this.transId = false;
37962 var a = response.argument;
37963 this.fireEvent("loadexception", this, a.node, response);
37964 if(typeof a.callback == "function"){
37965 a.callback(this, a.node);
37970 * Ext JS Library 1.1.1
37971 * Copyright(c) 2006-2007, Ext JS, LLC.
37973 * Originally Released Under LGPL - original licence link has changed is not relivant.
37976 * <script type="text/javascript">
37980 * @class Roo.tree.TreeFilter
37981 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
37982 * @param {TreePanel} tree
37983 * @param {Object} config (optional)
37985 Roo.tree.TreeFilter = function(tree, config){
37987 this.filtered = {};
37988 Roo.apply(this, config);
37991 Roo.tree.TreeFilter.prototype = {
37998 * Filter the data by a specific attribute.
37999 * @param {String/RegExp} value Either string that the attribute value
38000 * should start with or a RegExp to test against the attribute
38001 * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
38002 * @param {TreeNode} startNode (optional) The node to start the filter at.
38004 filter : function(value, attr, startNode){
38005 attr = attr || "text";
38007 if(typeof value == "string"){
38008 var vlen = value.length;
38009 // auto clear empty filter
38010 if(vlen == 0 && this.clearBlank){
38014 value = value.toLowerCase();
38016 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
38018 }else if(value.exec){ // regex?
38020 return value.test(n.attributes[attr]);
38023 throw 'Illegal filter type, must be string or regex';
38025 this.filterBy(f, null, startNode);
38029 * Filter by a function. The passed function will be called with each
38030 * node in the tree (or from the startNode). If the function returns true, the node is kept
38031 * otherwise it is filtered. If a node is filtered, its children are also filtered.
38032 * @param {Function} fn The filter function
38033 * @param {Object} scope (optional) The scope of the function (defaults to the current node)
38035 filterBy : function(fn, scope, startNode){
38036 startNode = startNode || this.tree.root;
38037 if(this.autoClear){
38040 var af = this.filtered, rv = this.reverse;
38041 var f = function(n){
38042 if(n == startNode){
38048 var m = fn.call(scope || n, n);
38056 startNode.cascade(f);
38059 if(typeof id != "function"){
38061 if(n && n.parentNode){
38062 n.parentNode.removeChild(n);
38070 * Clears the current filter. Note: with the "remove" option
38071 * set a filter cannot be cleared.
38073 clear : function(){
38075 var af = this.filtered;
38077 if(typeof id != "function"){
38084 this.filtered = {};
38089 * Ext JS Library 1.1.1
38090 * Copyright(c) 2006-2007, Ext JS, LLC.
38092 * Originally Released Under LGPL - original licence link has changed is not relivant.
38095 * <script type="text/javascript">
38100 * @class Roo.tree.TreeSorter
38101 * Provides sorting of nodes in a TreePanel
38103 * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
38104 * @cfg {String} property The named attribute on the node to sort by (defaults to text)
38105 * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
38106 * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
38107 * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
38108 * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
38110 * @param {TreePanel} tree
38111 * @param {Object} config
38113 Roo.tree.TreeSorter = function(tree, config){
38114 Roo.apply(this, config);
38115 tree.on("beforechildrenrendered", this.doSort, this);
38116 tree.on("append", this.updateSort, this);
38117 tree.on("insert", this.updateSort, this);
38119 var dsc = this.dir && this.dir.toLowerCase() == "desc";
38120 var p = this.property || "text";
38121 var sortType = this.sortType;
38122 var fs = this.folderSort;
38123 var cs = this.caseSensitive === true;
38124 var leafAttr = this.leafAttr || 'leaf';
38126 this.sortFn = function(n1, n2){
38128 if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
38131 if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
38135 var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
38136 var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
38138 return dsc ? +1 : -1;
38140 return dsc ? -1 : +1;
38147 Roo.tree.TreeSorter.prototype = {
38148 doSort : function(node){
38149 node.sort(this.sortFn);
38152 compareNodes : function(n1, n2){
38153 return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
38156 updateSort : function(tree, node){
38157 if(node.childrenRendered){
38158 this.doSort.defer(1, this, [node]);
38163 * Ext JS Library 1.1.1
38164 * Copyright(c) 2006-2007, Ext JS, LLC.
38166 * Originally Released Under LGPL - original licence link has changed is not relivant.
38169 * <script type="text/javascript">
38172 if(Roo.dd.DropZone){
38174 Roo.tree.TreeDropZone = function(tree, config){
38175 this.allowParentInsert = false;
38176 this.allowContainerDrop = false;
38177 this.appendOnly = false;
38178 Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
38180 this.lastInsertClass = "x-tree-no-status";
38181 this.dragOverData = {};
38184 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
38185 ddGroup : "TreeDD",
38188 expandDelay : 1000,
38190 expandNode : function(node){
38191 if(node.hasChildNodes() && !node.isExpanded()){
38192 node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
38196 queueExpand : function(node){
38197 this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
38200 cancelExpand : function(){
38201 if(this.expandProcId){
38202 clearTimeout(this.expandProcId);
38203 this.expandProcId = false;
38207 isValidDropPoint : function(n, pt, dd, e, data){
38208 if(!n || !data){ return false; }
38209 var targetNode = n.node;
38210 var dropNode = data.node;
38211 // default drop rules
38212 if(!(targetNode && targetNode.isTarget && pt)){
38215 if(pt == "append" && targetNode.allowChildren === false){
38218 if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
38221 if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
38224 // reuse the object
38225 var overEvent = this.dragOverData;
38226 overEvent.tree = this.tree;
38227 overEvent.target = targetNode;
38228 overEvent.data = data;
38229 overEvent.point = pt;
38230 overEvent.source = dd;
38231 overEvent.rawEvent = e;
38232 overEvent.dropNode = dropNode;
38233 overEvent.cancel = false;
38234 var result = this.tree.fireEvent("nodedragover", overEvent);
38235 return overEvent.cancel === false && result !== false;
38238 getDropPoint : function(e, n, dd)
38242 return tn.allowChildren !== false ? "append" : false; // always append for root
38244 var dragEl = n.ddel;
38245 var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
38246 var y = Roo.lib.Event.getPageY(e);
38247 //var noAppend = tn.allowChildren === false || tn.isLeaf();
38249 // we may drop nodes anywhere, as long as allowChildren has not been set to false..
38250 var noAppend = tn.allowChildren === false;
38251 if(this.appendOnly || tn.parentNode.allowChildren === false){
38252 return noAppend ? false : "append";
38254 var noBelow = false;
38255 if(!this.allowParentInsert){
38256 noBelow = tn.hasChildNodes() && tn.isExpanded();
38258 var q = (b - t) / (noAppend ? 2 : 3);
38259 if(y >= t && y < (t + q)){
38261 }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
38268 onNodeEnter : function(n, dd, e, data)
38270 this.cancelExpand();
38273 onNodeOver : function(n, dd, e, data)
38276 var pt = this.getDropPoint(e, n, dd);
38279 // auto node expand check
38280 if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
38281 this.queueExpand(node);
38282 }else if(pt != "append"){
38283 this.cancelExpand();
38286 // set the insert point style on the target node
38287 var returnCls = this.dropNotAllowed;
38288 if(this.isValidDropPoint(n, pt, dd, e, data)){
38293 returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
38294 cls = "x-tree-drag-insert-above";
38295 }else if(pt == "below"){
38296 returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
38297 cls = "x-tree-drag-insert-below";
38299 returnCls = "x-tree-drop-ok-append";
38300 cls = "x-tree-drag-append";
38302 if(this.lastInsertClass != cls){
38303 Roo.fly(el).replaceClass(this.lastInsertClass, cls);
38304 this.lastInsertClass = cls;
38311 onNodeOut : function(n, dd, e, data){
38313 this.cancelExpand();
38314 this.removeDropIndicators(n);
38317 onNodeDrop : function(n, dd, e, data){
38318 var point = this.getDropPoint(e, n, dd);
38319 var targetNode = n.node;
38320 targetNode.ui.startDrop();
38321 if(!this.isValidDropPoint(n, point, dd, e, data)){
38322 targetNode.ui.endDrop();
38325 // first try to find the drop node
38326 var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
38329 target: targetNode,
38334 dropNode: dropNode,
38337 var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
38338 if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
38339 targetNode.ui.endDrop();
38342 // allow target changing
38343 targetNode = dropEvent.target;
38344 if(point == "append" && !targetNode.isExpanded()){
38345 targetNode.expand(false, null, function(){
38346 this.completeDrop(dropEvent);
38347 }.createDelegate(this));
38349 this.completeDrop(dropEvent);
38354 completeDrop : function(de){
38355 var ns = de.dropNode, p = de.point, t = de.target;
38356 if(!(ns instanceof Array)){
38360 for(var i = 0, len = ns.length; i < len; i++){
38363 t.parentNode.insertBefore(n, t);
38364 }else if(p == "below"){
38365 t.parentNode.insertBefore(n, t.nextSibling);
38371 if(this.tree.hlDrop){
38375 this.tree.fireEvent("nodedrop", de);
38378 afterNodeMoved : function(dd, data, e, targetNode, dropNode){
38379 if(this.tree.hlDrop){
38380 dropNode.ui.focus();
38381 dropNode.ui.highlight();
38383 this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
38386 getTree : function(){
38390 removeDropIndicators : function(n){
38393 Roo.fly(el).removeClass([
38394 "x-tree-drag-insert-above",
38395 "x-tree-drag-insert-below",
38396 "x-tree-drag-append"]);
38397 this.lastInsertClass = "_noclass";
38401 beforeDragDrop : function(target, e, id){
38402 this.cancelExpand();
38406 afterRepair : function(data){
38407 if(data && Roo.enableFx){
38408 data.node.ui.highlight();
38418 * Ext JS Library 1.1.1
38419 * Copyright(c) 2006-2007, Ext JS, LLC.
38421 * Originally Released Under LGPL - original licence link has changed is not relivant.
38424 * <script type="text/javascript">
38428 if(Roo.dd.DragZone){
38429 Roo.tree.TreeDragZone = function(tree, config){
38430 Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
38434 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
38435 ddGroup : "TreeDD",
38437 onBeforeDrag : function(data, e){
38439 return n && n.draggable && !n.disabled;
38443 onInitDrag : function(e){
38444 var data = this.dragData;
38445 this.tree.getSelectionModel().select(data.node);
38446 this.proxy.update("");
38447 data.node.ui.appendDDGhost(this.proxy.ghost.dom);
38448 this.tree.fireEvent("startdrag", this.tree, data.node, e);
38451 getRepairXY : function(e, data){
38452 return data.node.ui.getDDRepairXY();
38455 onEndDrag : function(data, e){
38456 this.tree.fireEvent("enddrag", this.tree, data.node, e);
38461 onValidDrop : function(dd, e, id){
38462 this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
38466 beforeInvalidDrop : function(e, id){
38467 // this scrolls the original position back into view
38468 var sm = this.tree.getSelectionModel();
38469 sm.clearSelections();
38470 sm.select(this.dragData.node);
38475 * Ext JS Library 1.1.1
38476 * Copyright(c) 2006-2007, Ext JS, LLC.
38478 * Originally Released Under LGPL - original licence link has changed is not relivant.
38481 * <script type="text/javascript">
38484 * @class Roo.tree.TreeEditor
38485 * @extends Roo.Editor
38486 * Provides editor functionality for inline tree node editing. Any valid {@link Roo.form.Field} can be used
38487 * as the editor field.
38489 * @param {Object} config (used to be the tree panel.)
38490 * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
38492 * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
38493 * @cfg {Roo.form.TextField} field [required] The field configuration
38497 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
38500 if (oldconfig) { // old style..
38501 field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
38504 tree = config.tree;
38505 config.field = config.field || {};
38506 config.field.xtype = 'TextField';
38507 field = Roo.factory(config.field, Roo.form);
38509 config = config || {};
38514 * @event beforenodeedit
38515 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
38516 * false from the handler of this event.
38517 * @param {Editor} this
38518 * @param {Roo.tree.Node} node
38520 "beforenodeedit" : true
38524 Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
38528 tree.on('beforeclick', this.beforeNodeClick, this);
38529 tree.getTreeEl().on('mousedown', this.hide, this);
38530 this.on('complete', this.updateNode, this);
38531 this.on('beforestartedit', this.fitToTree, this);
38532 this.on('startedit', this.bindScroll, this, {delay:10});
38533 this.on('specialkey', this.onSpecialKey, this);
38536 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
38538 * @cfg {String} alignment
38539 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
38545 * @cfg {Boolean} hideEl
38546 * True to hide the bound element while the editor is displayed (defaults to false)
38550 * @cfg {String} cls
38551 * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
38553 cls: "x-small-editor x-tree-editor",
38555 * @cfg {Boolean} shim
38556 * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
38562 * @cfg {Number} maxWidth
38563 * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed
38564 * the containing tree element's size, it will be automatically limited for you to the container width, taking
38565 * scroll and client offsets into account prior to each edit.
38572 fitToTree : function(ed, el){
38573 var td = this.tree.getTreeEl().dom, nd = el.dom;
38574 if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible
38575 td.scrollLeft = nd.offsetLeft;
38579 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
38580 this.setSize(w, '');
38582 return this.fireEvent('beforenodeedit', this, this.editNode);
38587 triggerEdit : function(node){
38588 this.completeEdit();
38589 this.editNode = node;
38590 this.startEdit(node.ui.textNode, node.text);
38594 bindScroll : function(){
38595 this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
38599 beforeNodeClick : function(node, e){
38600 var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
38601 this.lastClick = new Date();
38602 if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
38604 this.triggerEdit(node);
38611 updateNode : function(ed, value){
38612 this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
38613 this.editNode.setText(value);
38617 onHide : function(){
38618 Roo.tree.TreeEditor.superclass.onHide.call(this);
38620 this.editNode.ui.focus();
38625 onSpecialKey : function(field, e){
38626 var k = e.getKey();
38630 }else if(k == e.ENTER && !e.hasModifier()){
38632 this.completeEdit();
38635 });//<Script type="text/javascript">
38638 * Ext JS Library 1.1.1
38639 * Copyright(c) 2006-2007, Ext JS, LLC.
38641 * Originally Released Under LGPL - original licence link has changed is not relivant.
38644 * <script type="text/javascript">
38648 * Not documented??? - probably should be...
38651 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
38652 //focus: Roo.emptyFn, // prevent odd scrolling behavior
38654 renderElements : function(n, a, targetNode, bulkRender){
38655 //consel.log("renderElements?");
38656 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
38658 var t = n.getOwnerTree();
38659 var tid = Pman.Tab.Document_TypesTree.tree.el.id;
38661 var cols = t.columns;
38662 var bw = t.borderWidth;
38664 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
38665 var cb = typeof a.checked == "boolean";
38666 var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
38667 var colcls = 'x-t-' + tid + '-c0';
38669 '<li class="x-tree-node">',
38672 '<div class="x-tree-node-el ', a.cls,'">',
38674 '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
38677 '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
38678 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon " />',
38679 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
38680 (a.icon ? ' x-tree-node-inline-icon' : ''),
38681 (a.iconCls ? ' '+a.iconCls : ''),
38682 '" unselectable="on" />',
38683 (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' +
38684 (a.checked ? 'checked="checked" />' : ' />')) : ''),
38686 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
38687 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
38688 '<span unselectable="on" qtip="' + tx + '">',
38692 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
38693 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
38695 for(var i = 1, len = cols.length; i < len; i++){
38697 colcls = 'x-t-' + tid + '-c' +i;
38698 tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
38699 buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
38700 '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
38706 '<div class="x-clear"></div></div>',
38707 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
38710 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
38711 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
38712 n.nextSibling.ui.getEl(), buf.join(""));
38714 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
38716 var el = this.wrap.firstChild;
38718 this.elNode = el.firstChild;
38719 this.ranchor = el.childNodes[1];
38720 this.ctNode = this.wrap.childNodes[1];
38721 var cs = el.firstChild.childNodes;
38722 this.indentNode = cs[0];
38723 this.ecNode = cs[1];
38724 this.iconNode = cs[2];
38727 this.checkbox = cs[3];
38730 this.anchor = cs[index];
38732 this.textNode = cs[index].firstChild;
38734 //el.on("click", this.onClick, this);
38735 //el.on("dblclick", this.onDblClick, this);
38738 // console.log(this);
38740 initEvents : function(){
38741 Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
38744 var a = this.ranchor;
38746 var el = Roo.get(a);
38748 if(Roo.isOpera){ // opera render bug ignores the CSS
38749 el.setStyle("text-decoration", "none");
38752 el.on("click", this.onClick, this);
38753 el.on("dblclick", this.onDblClick, this);
38754 el.on("contextmenu", this.onContextMenu, this);
38758 /*onSelectedChange : function(state){
38761 this.addClass("x-tree-selected");
38764 this.removeClass("x-tree-selected");
38767 addClass : function(cls){
38769 Roo.fly(this.elRow).addClass(cls);
38775 removeClass : function(cls){
38777 Roo.fly(this.elRow).removeClass(cls);
38783 });//<Script type="text/javascript">
38787 * Ext JS Library 1.1.1
38788 * Copyright(c) 2006-2007, Ext JS, LLC.
38790 * Originally Released Under LGPL - original licence link has changed is not relivant.
38793 * <script type="text/javascript">
38798 * @class Roo.tree.ColumnTree
38799 * @extends Roo.tree.TreePanel
38800 * @cfg {Object} columns Including width, header, renderer, cls, dataIndex
38801 * @cfg {int} borderWidth compined right/left border allowance
38803 * @param {String/HTMLElement/Element} el The container element
38804 * @param {Object} config
38806 Roo.tree.ColumnTree = function(el, config)
38808 Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
38812 * Fire this event on a container when it resizes
38813 * @param {int} w Width
38814 * @param {int} h Height
38818 this.on('resize', this.onResize, this);
38821 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
38825 borderWidth: Roo.isBorderBox ? 0 : 2,
38828 render : function(){
38829 // add the header.....
38831 Roo.tree.ColumnTree.superclass.render.apply(this);
38833 this.el.addClass('x-column-tree');
38835 this.headers = this.el.createChild(
38836 {cls:'x-tree-headers'},this.innerCt.dom);
38838 var cols = this.columns, c;
38839 var totalWidth = 0;
38841 var len = cols.length;
38842 for(var i = 0; i < len; i++){
38844 totalWidth += c.width;
38845 this.headEls.push(this.headers.createChild({
38846 cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
38848 cls:'x-tree-hd-text',
38851 style:'width:'+(c.width-this.borderWidth)+'px;'
38854 this.headers.createChild({cls:'x-clear'});
38855 // prevent floats from wrapping when clipped
38856 this.headers.setWidth(totalWidth);
38857 //this.innerCt.setWidth(totalWidth);
38858 this.innerCt.setStyle({ overflow: 'auto' });
38859 this.onResize(this.width, this.height);
38863 onResize : function(w,h)
38868 this.innerCt.setWidth(this.width);
38869 this.innerCt.setHeight(this.height-20);
38872 var cols = this.columns, c;
38873 var totalWidth = 0;
38875 var len = cols.length;
38876 for(var i = 0; i < len; i++){
38878 if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
38879 // it's the expander..
38880 expEl = this.headEls[i];
38883 totalWidth += c.width;
38887 expEl.setWidth( ((w - totalWidth)-this.borderWidth - 20));
38889 this.headers.setWidth(w-20);
38898 * Ext JS Library 1.1.1
38899 * Copyright(c) 2006-2007, Ext JS, LLC.
38901 * Originally Released Under LGPL - original licence link has changed is not relivant.
38904 * <script type="text/javascript">
38908 * @class Roo.menu.Menu
38909 * @extends Roo.util.Observable
38910 * @children Roo.menu.Item Roo.menu.Separator Roo.menu.TextItem
38911 * A menu object. This is the container to which you add all other menu items. Menu can also serve a as a base class
38912 * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
38914 * Creates a new Menu
38915 * @param {Object} config Configuration options
38917 Roo.menu.Menu = function(config){
38919 Roo.menu.Menu.superclass.constructor.call(this, config);
38921 this.id = this.id || Roo.id();
38924 * @event beforeshow
38925 * Fires before this menu is displayed
38926 * @param {Roo.menu.Menu} this
38930 * @event beforehide
38931 * Fires before this menu is hidden
38932 * @param {Roo.menu.Menu} this
38937 * Fires after this menu is displayed
38938 * @param {Roo.menu.Menu} this
38943 * Fires after this menu is hidden
38944 * @param {Roo.menu.Menu} this
38949 * Fires when this menu is clicked (or when the enter key is pressed while it is active)
38950 * @param {Roo.menu.Menu} this
38951 * @param {Roo.menu.Item} menuItem The menu item that was clicked
38952 * @param {Roo.EventObject} e
38957 * Fires when the mouse is hovering over this menu
38958 * @param {Roo.menu.Menu} this
38959 * @param {Roo.EventObject} e
38960 * @param {Roo.menu.Item} menuItem The menu item that was clicked
38965 * Fires when the mouse exits this menu
38966 * @param {Roo.menu.Menu} this
38967 * @param {Roo.EventObject} e
38968 * @param {Roo.menu.Item} menuItem The menu item that was clicked
38973 * Fires when a menu item contained in this menu is clicked
38974 * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
38975 * @param {Roo.EventObject} e
38979 if (this.registerMenu) {
38980 Roo.menu.MenuMgr.register(this);
38983 var mis = this.items;
38984 this.items = new Roo.util.MixedCollection();
38986 this.add.apply(this, mis);
38990 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
38992 * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
38996 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
38997 * for bottom-right shadow (defaults to "sides")
39001 * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
39002 * this menu (defaults to "tl-tr?")
39004 subMenuAlign : "tl-tr?",
39006 * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
39007 * relative to its element of origin (defaults to "tl-bl?")
39009 defaultAlign : "tl-bl?",
39011 * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
39013 allowOtherMenus : false,
39015 * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
39017 registerMenu : true,
39022 render : function(){
39026 var el = this.el = new Roo.Layer({
39028 shadow:this.shadow,
39030 parentEl: this.parentEl || document.body,
39034 this.keyNav = new Roo.menu.MenuNav(this);
39037 el.addClass("x-menu-plain");
39040 el.addClass(this.cls);
39042 // generic focus element
39043 this.focusEl = el.createChild({
39044 tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
39046 var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
39047 //disabling touch- as it's causing issues ..
39048 //ul.on(Roo.isTouch ? 'touchstart' : 'click' , this.onClick, this);
39049 ul.on('click' , this.onClick, this);
39052 ul.on("mouseover", this.onMouseOver, this);
39053 ul.on("mouseout", this.onMouseOut, this);
39054 this.items.each(function(item){
39059 var li = document.createElement("li");
39060 li.className = "x-menu-list-item";
39061 ul.dom.appendChild(li);
39062 item.render(li, this);
39069 autoWidth : function(){
39070 var el = this.el, ul = this.ul;
39074 var w = this.width;
39077 }else if(Roo.isIE){
39078 el.setWidth(this.minWidth);
39079 var t = el.dom.offsetWidth; // force recalc
39080 el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
39085 delayAutoWidth : function(){
39088 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
39090 this.awTask.delay(20);
39095 findTargetItem : function(e){
39096 var t = e.getTarget(".x-menu-list-item", this.ul, true);
39097 if(t && t.menuItemId){
39098 return this.items.get(t.menuItemId);
39103 onClick : function(e){
39104 Roo.log("menu.onClick");
39105 var t = this.findTargetItem(e);
39110 if (Roo.isTouch && e.type == 'touchstart' && t.menu && !t.disabled) {
39111 if(t == this.activeItem && t.shouldDeactivate(e)){
39112 this.activeItem.deactivate();
39113 delete this.activeItem;
39117 this.setActiveItem(t, true);
39125 this.fireEvent("click", this, t, e);
39129 setActiveItem : function(item, autoExpand){
39130 if(item != this.activeItem){
39131 if(this.activeItem){
39132 this.activeItem.deactivate();
39134 this.activeItem = item;
39135 item.activate(autoExpand);
39136 }else if(autoExpand){
39142 tryActivate : function(start, step){
39143 var items = this.items;
39144 for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
39145 var item = items.get(i);
39146 if(!item.disabled && item.canActivate){
39147 this.setActiveItem(item, false);
39155 onMouseOver : function(e){
39157 if(t = this.findTargetItem(e)){
39158 if(t.canActivate && !t.disabled){
39159 this.setActiveItem(t, true);
39162 this.fireEvent("mouseover", this, e, t);
39166 onMouseOut : function(e){
39168 if(t = this.findTargetItem(e)){
39169 if(t == this.activeItem && t.shouldDeactivate(e)){
39170 this.activeItem.deactivate();
39171 delete this.activeItem;
39174 this.fireEvent("mouseout", this, e, t);
39178 * Read-only. Returns true if the menu is currently displayed, else false.
39181 isVisible : function(){
39182 return this.el && !this.hidden;
39186 * Displays this menu relative to another element
39187 * @param {String/HTMLElement/Roo.Element} element The element to align to
39188 * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
39189 * the element (defaults to this.defaultAlign)
39190 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
39192 show : function(el, pos, parentMenu){
39193 this.parentMenu = parentMenu;
39197 this.fireEvent("beforeshow", this);
39198 this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
39202 * Displays this menu at a specific xy position
39203 * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
39204 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
39206 showAt : function(xy, parentMenu, /* private: */_e){
39207 this.parentMenu = parentMenu;
39212 this.fireEvent("beforeshow", this);
39213 xy = this.el.adjustForConstraints(xy);
39217 this.hidden = false;
39219 this.fireEvent("show", this);
39222 focus : function(){
39224 this.doFocus.defer(50, this);
39228 doFocus : function(){
39230 this.focusEl.focus();
39235 * Hides this menu and optionally all parent menus
39236 * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
39238 hide : function(deep){
39239 if(this.el && this.isVisible()){
39240 this.fireEvent("beforehide", this);
39241 if(this.activeItem){
39242 this.activeItem.deactivate();
39243 this.activeItem = null;
39246 this.hidden = true;
39247 this.fireEvent("hide", this);
39249 if(deep === true && this.parentMenu){
39250 this.parentMenu.hide(true);
39255 * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
39256 * Any of the following are valid:
39258 * <li>Any menu item object based on {@link Roo.menu.Item}</li>
39259 * <li>An HTMLElement object which will be converted to a menu item</li>
39260 * <li>A menu item config object that will be created as a new menu item</li>
39261 * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
39262 * it will be converted into a {@link Roo.menu.TextItem} and added</li>
39267 var menu = new Roo.menu.Menu();
39269 // Create a menu item to add by reference
39270 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
39272 // Add a bunch of items at once using different methods.
39273 // Only the last item added will be returned.
39274 var item = menu.add(
39275 menuItem, // add existing item by ref
39276 'Dynamic Item', // new TextItem
39277 '-', // new separator
39278 { text: 'Config Item' } // new item by config
39281 * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
39282 * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
39285 var a = arguments, l = a.length, item;
39286 for(var i = 0; i < l; i++){
39288 if ((typeof(el) == "object") && el.xtype && el.xns) {
39289 el = Roo.factory(el, Roo.menu);
39292 if(el.render){ // some kind of Item
39293 item = this.addItem(el);
39294 }else if(typeof el == "string"){ // string
39295 if(el == "separator" || el == "-"){
39296 item = this.addSeparator();
39298 item = this.addText(el);
39300 }else if(el.tagName || el.el){ // element
39301 item = this.addElement(el);
39302 }else if(typeof el == "object"){ // must be menu item config?
39303 item = this.addMenuItem(el);
39310 * Returns this menu's underlying {@link Roo.Element} object
39311 * @return {Roo.Element} The element
39313 getEl : function(){
39321 * Adds a separator bar to the menu
39322 * @return {Roo.menu.Item} The menu item that was added
39324 addSeparator : function(){
39325 return this.addItem(new Roo.menu.Separator());
39329 * Adds an {@link Roo.Element} object to the menu
39330 * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
39331 * @return {Roo.menu.Item} The menu item that was added
39333 addElement : function(el){
39334 return this.addItem(new Roo.menu.BaseItem(el));
39338 * Adds an existing object based on {@link Roo.menu.Item} to the menu
39339 * @param {Roo.menu.Item} item The menu item to add
39340 * @return {Roo.menu.Item} The menu item that was added
39342 addItem : function(item){
39343 this.items.add(item);
39345 var li = document.createElement("li");
39346 li.className = "x-menu-list-item";
39347 this.ul.dom.appendChild(li);
39348 item.render(li, this);
39349 this.delayAutoWidth();
39355 * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
39356 * @param {Object} config A MenuItem config object
39357 * @return {Roo.menu.Item} The menu item that was added
39359 addMenuItem : function(config){
39360 if(!(config instanceof Roo.menu.Item)){
39361 if(typeof config.checked == "boolean"){ // must be check menu item config?
39362 config = new Roo.menu.CheckItem(config);
39364 config = new Roo.menu.Item(config);
39367 return this.addItem(config);
39371 * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
39372 * @param {String} text The text to display in the menu item
39373 * @return {Roo.menu.Item} The menu item that was added
39375 addText : function(text){
39376 return this.addItem(new Roo.menu.TextItem({ text : text }));
39380 * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
39381 * @param {Number} index The index in the menu's list of current items where the new item should be inserted
39382 * @param {Roo.menu.Item} item The menu item to add
39383 * @return {Roo.menu.Item} The menu item that was added
39385 insert : function(index, item){
39386 this.items.insert(index, item);
39388 var li = document.createElement("li");
39389 li.className = "x-menu-list-item";
39390 this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
39391 item.render(li, this);
39392 this.delayAutoWidth();
39398 * Removes an {@link Roo.menu.Item} from the menu and destroys the object
39399 * @param {Roo.menu.Item} item The menu item to remove
39401 remove : function(item){
39402 this.items.removeKey(item.id);
39407 * Removes and destroys all items in the menu
39409 removeAll : function(){
39411 while(f = this.items.first()){
39417 // MenuNav is a private utility class used internally by the Menu
39418 Roo.menu.MenuNav = function(menu){
39419 Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
39420 this.scope = this.menu = menu;
39423 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
39424 doRelay : function(e, h){
39425 var k = e.getKey();
39426 if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
39427 this.menu.tryActivate(0, 1);
39430 return h.call(this.scope || this, e, this.menu);
39433 up : function(e, m){
39434 if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
39435 m.tryActivate(m.items.length-1, -1);
39439 down : function(e, m){
39440 if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
39441 m.tryActivate(0, 1);
39445 right : function(e, m){
39447 m.activeItem.expandMenu(true);
39451 left : function(e, m){
39453 if(m.parentMenu && m.parentMenu.activeItem){
39454 m.parentMenu.activeItem.activate();
39458 enter : function(e, m){
39460 e.stopPropagation();
39461 m.activeItem.onClick(e);
39462 m.fireEvent("click", this, m.activeItem);
39468 * Ext JS Library 1.1.1
39469 * Copyright(c) 2006-2007, Ext JS, LLC.
39471 * Originally Released Under LGPL - original licence link has changed is not relivant.
39474 * <script type="text/javascript">
39478 * @class Roo.menu.MenuMgr
39479 * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
39482 Roo.menu.MenuMgr = function(){
39483 var menus, active, groups = {}, attached = false, lastShow = new Date();
39485 // private - called when first menu is created
39488 active = new Roo.util.MixedCollection();
39489 Roo.get(document).addKeyListener(27, function(){
39490 if(active.length > 0){
39497 function hideAll(){
39498 if(active && active.length > 0){
39499 var c = active.clone();
39500 c.each(function(m){
39507 function onHide(m){
39509 if(active.length < 1){
39510 Roo.get(document).un("mousedown", onMouseDown);
39516 function onShow(m){
39517 var last = active.last();
39518 lastShow = new Date();
39521 Roo.get(document).on("mousedown", onMouseDown);
39525 m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
39526 m.parentMenu.activeChild = m;
39527 }else if(last && last.isVisible()){
39528 m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
39533 function onBeforeHide(m){
39535 m.activeChild.hide();
39537 if(m.autoHideTimer){
39538 clearTimeout(m.autoHideTimer);
39539 delete m.autoHideTimer;
39544 function onBeforeShow(m){
39545 var pm = m.parentMenu;
39546 if(!pm && !m.allowOtherMenus){
39548 }else if(pm && pm.activeChild && active != m){
39549 pm.activeChild.hide();
39554 function onMouseDown(e){
39555 if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
39561 function onBeforeCheck(mi, state){
39563 var g = groups[mi.group];
39564 for(var i = 0, l = g.length; i < l; i++){
39566 g[i].setChecked(false);
39575 * Hides all menus that are currently visible
39577 hideAll : function(){
39582 register : function(menu){
39586 menus[menu.id] = menu;
39587 menu.on("beforehide", onBeforeHide);
39588 menu.on("hide", onHide);
39589 menu.on("beforeshow", onBeforeShow);
39590 menu.on("show", onShow);
39591 var g = menu.group;
39592 if(g && menu.events["checkchange"]){
39596 groups[g].push(menu);
39597 menu.on("checkchange", onCheck);
39602 * Returns a {@link Roo.menu.Menu} object
39603 * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
39604 * be used to generate and return a new Menu instance.
39606 get : function(menu){
39607 if(typeof menu == "string"){ // menu id
39608 return menus[menu];
39609 }else if(menu.events){ // menu instance
39611 }else if(typeof menu.length == 'number'){ // array of menu items?
39612 return new Roo.menu.Menu({items:menu});
39613 }else{ // otherwise, must be a config
39614 return new Roo.menu.Menu(menu);
39619 unregister : function(menu){
39620 delete menus[menu.id];
39621 menu.un("beforehide", onBeforeHide);
39622 menu.un("hide", onHide);
39623 menu.un("beforeshow", onBeforeShow);
39624 menu.un("show", onShow);
39625 var g = menu.group;
39626 if(g && menu.events["checkchange"]){
39627 groups[g].remove(menu);
39628 menu.un("checkchange", onCheck);
39633 registerCheckable : function(menuItem){
39634 var g = menuItem.group;
39639 groups[g].push(menuItem);
39640 menuItem.on("beforecheckchange", onBeforeCheck);
39645 unregisterCheckable : function(menuItem){
39646 var g = menuItem.group;
39648 groups[g].remove(menuItem);
39649 menuItem.un("beforecheckchange", onBeforeCheck);
39655 * Ext JS Library 1.1.1
39656 * Copyright(c) 2006-2007, Ext JS, LLC.
39658 * Originally Released Under LGPL - original licence link has changed is not relivant.
39661 * <script type="text/javascript">
39666 * @class Roo.menu.BaseItem
39667 * @extends Roo.Component
39669 * The base class for all items that render into menus. BaseItem provides default rendering, activated state
39670 * management and base configuration options shared by all menu components.
39672 * Creates a new BaseItem
39673 * @param {Object} config Configuration options
39675 Roo.menu.BaseItem = function(config){
39676 Roo.menu.BaseItem.superclass.constructor.call(this, config);
39681 * Fires when this item is clicked
39682 * @param {Roo.menu.BaseItem} this
39683 * @param {Roo.EventObject} e
39688 * Fires when this item is activated
39689 * @param {Roo.menu.BaseItem} this
39693 * @event deactivate
39694 * Fires when this item is deactivated
39695 * @param {Roo.menu.BaseItem} this
39701 this.on("click", this.handler, this.scope, true);
39705 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
39707 * @cfg {Function} handler
39708 * A function that will handle the click event of this menu item (defaults to undefined)
39711 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
39713 canActivate : false,
39716 * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
39721 * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
39723 activeClass : "x-menu-item-active",
39725 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
39727 hideOnClick : true,
39729 * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
39734 ctype: "Roo.menu.BaseItem",
39737 actionMode : "container",
39740 render : function(container, parentMenu){
39741 this.parentMenu = parentMenu;
39742 Roo.menu.BaseItem.superclass.render.call(this, container);
39743 this.container.menuItemId = this.id;
39747 onRender : function(container, position){
39748 this.el = Roo.get(this.el);
39749 container.dom.appendChild(this.el.dom);
39753 onClick : function(e){
39754 if(!this.disabled && this.fireEvent("click", this, e) !== false
39755 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
39756 this.handleClick(e);
39763 activate : function(){
39767 var li = this.container;
39768 li.addClass(this.activeClass);
39769 this.region = li.getRegion().adjust(2, 2, -2, -2);
39770 this.fireEvent("activate", this);
39775 deactivate : function(){
39776 this.container.removeClass(this.activeClass);
39777 this.fireEvent("deactivate", this);
39781 shouldDeactivate : function(e){
39782 return !this.region || !this.region.contains(e.getPoint());
39786 handleClick : function(e){
39787 if(this.hideOnClick){
39788 this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
39793 expandMenu : function(autoActivate){
39798 hideMenu : function(){
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.Adapter
39814 * @extends Roo.menu.BaseItem
39816 * 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.
39817 * It provides basic rendering, activation management and enable/disable logic required to work in menus.
39819 * Creates a new Adapter
39820 * @param {Object} config Configuration options
39822 Roo.menu.Adapter = function(component, config){
39823 Roo.menu.Adapter.superclass.constructor.call(this, config);
39824 this.component = component;
39826 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
39828 canActivate : true,
39831 onRender : function(container, position){
39832 this.component.render(container);
39833 this.el = this.component.getEl();
39837 activate : function(){
39841 this.component.focus();
39842 this.fireEvent("activate", this);
39847 deactivate : function(){
39848 this.fireEvent("deactivate", this);
39852 disable : function(){
39853 this.component.disable();
39854 Roo.menu.Adapter.superclass.disable.call(this);
39858 enable : function(){
39859 this.component.enable();
39860 Roo.menu.Adapter.superclass.enable.call(this);
39864 * Ext JS Library 1.1.1
39865 * Copyright(c) 2006-2007, Ext JS, LLC.
39867 * Originally Released Under LGPL - original licence link has changed is not relivant.
39870 * <script type="text/javascript">
39874 * @class Roo.menu.TextItem
39875 * @extends Roo.menu.BaseItem
39876 * Adds a static text string to a menu, usually used as either a heading or group separator.
39877 * Note: old style constructor with text is still supported.
39880 * Creates a new TextItem
39881 * @param {Object} cfg Configuration
39883 Roo.menu.TextItem = function(cfg){
39884 if (typeof(cfg) == 'string') {
39887 Roo.apply(this,cfg);
39890 Roo.menu.TextItem.superclass.constructor.call(this);
39893 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
39895 * @cfg {String} text Text to show on item.
39900 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
39902 hideOnClick : false,
39904 * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
39906 itemCls : "x-menu-text",
39909 onRender : function(){
39910 var s = document.createElement("span");
39911 s.className = this.itemCls;
39912 s.innerHTML = this.text;
39914 Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
39918 * Ext JS Library 1.1.1
39919 * Copyright(c) 2006-2007, Ext JS, LLC.
39921 * Originally Released Under LGPL - original licence link has changed is not relivant.
39924 * <script type="text/javascript">
39928 * @class Roo.menu.Separator
39929 * @extends Roo.menu.BaseItem
39930 * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
39931 * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
39933 * @param {Object} config Configuration options
39935 Roo.menu.Separator = function(config){
39936 Roo.menu.Separator.superclass.constructor.call(this, config);
39939 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
39941 * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
39943 itemCls : "x-menu-sep",
39945 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
39947 hideOnClick : false,
39950 onRender : function(li){
39951 var s = document.createElement("span");
39952 s.className = this.itemCls;
39953 s.innerHTML = " ";
39955 li.addClass("x-menu-sep-li");
39956 Roo.menu.Separator.superclass.onRender.apply(this, arguments);
39960 * Ext JS Library 1.1.1
39961 * Copyright(c) 2006-2007, Ext JS, LLC.
39963 * Originally Released Under LGPL - original licence link has changed is not relivant.
39966 * <script type="text/javascript">
39969 * @class Roo.menu.Item
39970 * @extends Roo.menu.BaseItem
39971 * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
39972 * display items. Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
39973 * activation and click handling.
39975 * Creates a new Item
39976 * @param {Object} config Configuration options
39978 Roo.menu.Item = function(config){
39979 Roo.menu.Item.superclass.constructor.call(this, config);
39981 this.menu = Roo.menu.MenuMgr.get(this.menu);
39984 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
39986 * @cfg {Roo.menu.Menu} menu
39990 * @cfg {String} text
39991 * The text to show on the menu item.
39995 * @cfg {String} html to render in menu
39996 * The text to show on the menu item (HTML version).
40000 * @cfg {String} icon
40001 * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
40005 * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
40007 itemCls : "x-menu-item",
40009 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
40011 canActivate : true,
40013 * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
40016 // doc'd in BaseItem
40020 ctype: "Roo.menu.Item",
40023 onRender : function(container, position){
40024 var el = document.createElement("a");
40025 el.hideFocus = true;
40026 el.unselectable = "on";
40027 el.href = this.href || "#";
40028 if(this.hrefTarget){
40029 el.target = this.hrefTarget;
40031 el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : "");
40033 var html = this.html.length ? this.html : String.format('{0}',this.text);
40035 el.innerHTML = String.format(
40036 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
40037 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
40039 Roo.menu.Item.superclass.onRender.call(this, container, position);
40043 * Sets the text to display in this menu item
40044 * @param {String} text The text to display
40045 * @param {Boolean} isHTML true to indicate text is pure html.
40047 setText : function(text, isHTML){
40055 var html = this.html.length ? this.html : String.format('{0}',this.text);
40057 this.el.update(String.format(
40058 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
40059 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
40060 this.parentMenu.autoWidth();
40065 handleClick : function(e){
40066 if(!this.href){ // if no link defined, stop the event automatically
40069 Roo.menu.Item.superclass.handleClick.apply(this, arguments);
40073 activate : function(autoExpand){
40074 if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
40084 shouldDeactivate : function(e){
40085 if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
40086 if(this.menu && this.menu.isVisible()){
40087 return !this.menu.getEl().getRegion().contains(e.getPoint());
40095 deactivate : function(){
40096 Roo.menu.Item.superclass.deactivate.apply(this, arguments);
40101 expandMenu : function(autoActivate){
40102 if(!this.disabled && this.menu){
40103 clearTimeout(this.hideTimer);
40104 delete this.hideTimer;
40105 if(!this.menu.isVisible() && !this.showTimer){
40106 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
40107 }else if (this.menu.isVisible() && autoActivate){
40108 this.menu.tryActivate(0, 1);
40114 deferExpand : function(autoActivate){
40115 delete this.showTimer;
40116 this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
40118 this.menu.tryActivate(0, 1);
40123 hideMenu : function(){
40124 clearTimeout(this.showTimer);
40125 delete this.showTimer;
40126 if(!this.hideTimer && this.menu && this.menu.isVisible()){
40127 this.hideTimer = this.deferHide.defer(this.hideDelay, this);
40132 deferHide : function(){
40133 delete this.hideTimer;
40138 * Ext JS Library 1.1.1
40139 * Copyright(c) 2006-2007, Ext JS, LLC.
40141 * Originally Released Under LGPL - original licence link has changed is not relivant.
40144 * <script type="text/javascript">
40148 * @class Roo.menu.CheckItem
40149 * @extends Roo.menu.Item
40150 * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
40152 * Creates a new CheckItem
40153 * @param {Object} config Configuration options
40155 Roo.menu.CheckItem = function(config){
40156 Roo.menu.CheckItem.superclass.constructor.call(this, config);
40159 * @event beforecheckchange
40160 * Fires before the checked value is set, providing an opportunity to cancel if needed
40161 * @param {Roo.menu.CheckItem} this
40162 * @param {Boolean} checked The new checked value that will be set
40164 "beforecheckchange" : true,
40166 * @event checkchange
40167 * Fires after the checked value has been set
40168 * @param {Roo.menu.CheckItem} this
40169 * @param {Boolean} checked The checked value that was set
40171 "checkchange" : true
40173 if(this.checkHandler){
40174 this.on('checkchange', this.checkHandler, this.scope);
40177 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
40179 * @cfg {String} group
40180 * All check items with the same group name will automatically be grouped into a single-select
40181 * radio button group (defaults to '')
40184 * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
40186 itemCls : "x-menu-item x-menu-check-item",
40188 * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
40190 groupClass : "x-menu-group-item",
40193 * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false). Note that
40194 * if this checkbox is part of a radio group (group = true) only the last item in the group that is
40195 * initialized with checked = true will be rendered as checked.
40200 ctype: "Roo.menu.CheckItem",
40203 onRender : function(c){
40204 Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
40206 this.el.addClass(this.groupClass);
40208 Roo.menu.MenuMgr.registerCheckable(this);
40210 this.checked = false;
40211 this.setChecked(true, true);
40216 destroy : function(){
40218 Roo.menu.MenuMgr.unregisterCheckable(this);
40220 Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
40224 * Set the checked state of this item
40225 * @param {Boolean} checked The new checked value
40226 * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
40228 setChecked : function(state, suppressEvent){
40229 if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
40230 if(this.container){
40231 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
40233 this.checked = state;
40234 if(suppressEvent !== true){
40235 this.fireEvent("checkchange", this, state);
40241 handleClick : function(e){
40242 if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
40243 this.setChecked(!this.checked);
40245 Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
40249 * Ext JS Library 1.1.1
40250 * Copyright(c) 2006-2007, Ext JS, LLC.
40252 * Originally Released Under LGPL - original licence link has changed is not relivant.
40255 * <script type="text/javascript">
40259 * @class Roo.menu.DateItem
40260 * @extends Roo.menu.Adapter
40261 * A menu item that wraps the {@link Roo.DatPicker} component.
40263 * Creates a new DateItem
40264 * @param {Object} config Configuration options
40266 Roo.menu.DateItem = function(config){
40267 Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
40268 /** The Roo.DatePicker object @type Roo.DatePicker */
40269 this.picker = this.component;
40270 this.addEvents({select: true});
40272 this.picker.on("render", function(picker){
40273 picker.getEl().swallowEvent("click");
40274 picker.container.addClass("x-menu-date-item");
40277 this.picker.on("select", this.onSelect, this);
40280 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
40282 onSelect : function(picker, date){
40283 this.fireEvent("select", this, date, picker);
40284 Roo.menu.DateItem.superclass.handleClick.call(this);
40288 * Ext JS Library 1.1.1
40289 * Copyright(c) 2006-2007, Ext JS, LLC.
40291 * Originally Released Under LGPL - original licence link has changed is not relivant.
40294 * <script type="text/javascript">
40298 * @class Roo.menu.ColorItem
40299 * @extends Roo.menu.Adapter
40300 * A menu item that wraps the {@link Roo.ColorPalette} component.
40302 * Creates a new ColorItem
40303 * @param {Object} config Configuration options
40305 Roo.menu.ColorItem = function(config){
40306 Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
40307 /** The Roo.ColorPalette object @type Roo.ColorPalette */
40308 this.palette = this.component;
40309 this.relayEvents(this.palette, ["select"]);
40310 if(this.selectHandler){
40311 this.on('select', this.selectHandler, this.scope);
40314 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
40316 * Ext JS Library 1.1.1
40317 * Copyright(c) 2006-2007, Ext JS, LLC.
40319 * Originally Released Under LGPL - original licence link has changed is not relivant.
40322 * <script type="text/javascript">
40327 * @class Roo.menu.DateMenu
40328 * @extends Roo.menu.Menu
40329 * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
40331 * Creates a new DateMenu
40332 * @param {Object} config Configuration options
40334 Roo.menu.DateMenu = function(config){
40335 Roo.menu.DateMenu.superclass.constructor.call(this, config);
40337 var di = new Roo.menu.DateItem(config);
40340 * The {@link Roo.DatePicker} instance for this DateMenu
40343 this.picker = di.picker;
40346 * @param {DatePicker} picker
40347 * @param {Date} date
40349 this.relayEvents(di, ["select"]);
40350 this.on('beforeshow', function(){
40352 this.picker.hideMonthPicker(false);
40356 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
40360 * Ext JS Library 1.1.1
40361 * Copyright(c) 2006-2007, Ext JS, LLC.
40363 * Originally Released Under LGPL - original licence link has changed is not relivant.
40366 * <script type="text/javascript">
40371 * @class Roo.menu.ColorMenu
40372 * @extends Roo.menu.Menu
40373 * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
40375 * Creates a new ColorMenu
40376 * @param {Object} config Configuration options
40378 Roo.menu.ColorMenu = function(config){
40379 Roo.menu.ColorMenu.superclass.constructor.call(this, config);
40381 var ci = new Roo.menu.ColorItem(config);
40384 * The {@link Roo.ColorPalette} instance for this ColorMenu
40385 * @type ColorPalette
40387 this.palette = ci.palette;
40390 * @param {ColorPalette} palette
40391 * @param {String} color
40393 this.relayEvents(ci, ["select"]);
40395 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
40397 * Ext JS Library 1.1.1
40398 * Copyright(c) 2006-2007, Ext JS, LLC.
40400 * Originally Released Under LGPL - original licence link has changed is not relivant.
40403 * <script type="text/javascript">
40407 * @class Roo.form.TextItem
40408 * @extends Roo.BoxComponent
40409 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
40411 * Creates a new TextItem
40412 * @param {Object} config Configuration options
40414 Roo.form.TextItem = function(config){
40415 Roo.form.TextItem.superclass.constructor.call(this, config);
40418 Roo.extend(Roo.form.TextItem, Roo.BoxComponent, {
40421 * @cfg {String} tag the tag for this item (default div)
40425 * @cfg {String} html the content for this item
40429 getAutoCreate : function()
40442 onRender : function(ct, position)
40444 Roo.form.TextItem.superclass.onRender.call(this, ct, position);
40447 var cfg = this.getAutoCreate();
40449 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
40451 if (!cfg.name.length) {
40454 this.el = ct.createChild(cfg, position);
40459 * @param {String} html update the Contents of the element.
40461 setHTML : function(html)
40463 this.fieldEl.dom.innerHTML = html;
40468 * Ext JS Library 1.1.1
40469 * Copyright(c) 2006-2007, Ext JS, LLC.
40471 * Originally Released Under LGPL - original licence link has changed is not relivant.
40474 * <script type="text/javascript">
40478 * @class Roo.form.Field
40479 * @extends Roo.BoxComponent
40480 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
40482 * Creates a new Field
40483 * @param {Object} config Configuration options
40485 Roo.form.Field = function(config){
40486 Roo.form.Field.superclass.constructor.call(this, config);
40489 Roo.extend(Roo.form.Field, Roo.BoxComponent, {
40491 * @cfg {String} fieldLabel Label to use when rendering a form.
40494 * @cfg {String} qtip Mouse over tip
40498 * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
40500 invalidClass : "x-form-invalid",
40502 * @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")
40504 invalidText : "The value in this field is invalid",
40506 * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
40508 focusClass : "x-form-focus",
40510 * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
40511 automatic validation (defaults to "keyup").
40513 validationEvent : "keyup",
40515 * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
40517 validateOnBlur : true,
40519 * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
40521 validationDelay : 250,
40523 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
40524 * {tag: "input", type: "text", size: "20", autocomplete: "off"})
40526 defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
40528 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
40530 fieldClass : "x-form-field",
40532 * @cfg {String} msgTarget The location where error text should display. Should be one of the following values (defaults to 'qtip'):
40535 ----------- ----------------------------------------------------------------------
40536 qtip Display a quick tip when the user hovers over the field
40537 title Display a default browser title attribute popup
40538 under Add a block div beneath the field containing the error text
40539 side Add an error icon to the right of the field with a popup on hover
40540 [element id] Add the error text directly to the innerHTML of the specified element
40543 msgTarget : 'qtip',
40545 * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
40550 * @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.
40555 * @cfg {Boolean} disabled True to disable the field (defaults to false).
40560 * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
40562 inputType : undefined,
40565 * @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).
40567 tabIndex : undefined,
40570 isFormField : true,
40575 * @property {Roo.Element} fieldEl
40576 * Element Containing the rendered Field (with label etc.)
40579 * @cfg {Mixed} value A value to initialize this field with.
40584 * @cfg {String} name The field's HTML name attribute.
40587 * @cfg {String} cls A CSS class to apply to the field's underlying element.
40590 loadedValue : false,
40594 initComponent : function(){
40595 Roo.form.Field.superclass.initComponent.call(this);
40599 * Fires when this field receives input focus.
40600 * @param {Roo.form.Field} this
40605 * Fires when this field loses input focus.
40606 * @param {Roo.form.Field} this
40610 * @event specialkey
40611 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
40612 * {@link Roo.EventObject#getKey} to determine which key was pressed.
40613 * @param {Roo.form.Field} this
40614 * @param {Roo.EventObject} e The event object
40619 * Fires just before the field blurs if the field value has changed.
40620 * @param {Roo.form.Field} this
40621 * @param {Mixed} newValue The new value
40622 * @param {Mixed} oldValue The original value
40627 * Fires after the field has been marked as invalid.
40628 * @param {Roo.form.Field} this
40629 * @param {String} msg The validation message
40634 * Fires after the field has been validated with no errors.
40635 * @param {Roo.form.Field} this
40640 * Fires after the key up
40641 * @param {Roo.form.Field} this
40642 * @param {Roo.EventObject} e The event Object
40649 * Returns the name attribute of the field if available
40650 * @return {String} name The field name
40652 getName: function(){
40653 return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
40657 onRender : function(ct, position){
40658 Roo.form.Field.superclass.onRender.call(this, ct, position);
40660 var cfg = this.getAutoCreate();
40662 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
40664 if (!cfg.name.length) {
40667 if(this.inputType){
40668 cfg.type = this.inputType;
40670 this.el = ct.createChild(cfg, position);
40672 var type = this.el.dom.type;
40674 if(type == 'password'){
40677 this.el.addClass('x-form-'+type);
40680 this.el.dom.readOnly = true;
40682 if(this.tabIndex !== undefined){
40683 this.el.dom.setAttribute('tabIndex', this.tabIndex);
40686 this.el.addClass([this.fieldClass, this.cls]);
40691 * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
40692 * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
40693 * @return {Roo.form.Field} this
40695 applyTo : function(target){
40696 this.allowDomMove = false;
40697 this.el = Roo.get(target);
40698 this.render(this.el.dom.parentNode);
40703 initValue : function(){
40704 if(this.value !== undefined){
40705 this.setValue(this.value);
40706 }else if(this.el.dom.value.length > 0){
40707 this.setValue(this.el.dom.value);
40712 * Returns true if this field has been changed since it was originally loaded and is not disabled.
40713 * DEPRICATED - it never worked well - use hasChanged/resetHasChanged.
40715 isDirty : function() {
40716 if(this.disabled) {
40719 return String(this.getValue()) !== String(this.originalValue);
40723 * stores the current value in loadedValue
40725 resetHasChanged : function()
40727 this.loadedValue = String(this.getValue());
40730 * checks the current value against the 'loaded' value.
40731 * Note - will return false if 'resetHasChanged' has not been called first.
40733 hasChanged : function()
40735 if(this.disabled || this.readOnly) {
40738 return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
40744 afterRender : function(){
40745 Roo.form.Field.superclass.afterRender.call(this);
40750 fireKey : function(e){
40751 //Roo.log('field ' + e.getKey());
40752 if(e.isNavKeyPress()){
40753 this.fireEvent("specialkey", this, e);
40758 * Resets the current field value to the originally loaded value and clears any validation messages
40760 reset : function(){
40761 this.setValue(this.resetValue);
40762 this.originalValue = this.getValue();
40763 this.clearInvalid();
40767 initEvents : function(){
40768 // safari killled keypress - so keydown is now used..
40769 this.el.on("keydown" , this.fireKey, this);
40770 this.el.on("focus", this.onFocus, this);
40771 this.el.on("blur", this.onBlur, this);
40772 this.el.relayEvent('keyup', this);
40774 // reference to original value for reset
40775 this.originalValue = this.getValue();
40776 this.resetValue = this.getValue();
40780 onFocus : function(){
40781 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
40782 this.el.addClass(this.focusClass);
40784 if(!this.hasFocus){
40785 this.hasFocus = true;
40786 this.startValue = this.getValue();
40787 this.fireEvent("focus", this);
40791 beforeBlur : Roo.emptyFn,
40794 onBlur : function(){
40796 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
40797 this.el.removeClass(this.focusClass);
40799 this.hasFocus = false;
40800 if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
40803 var v = this.getValue();
40804 if(String(v) !== String(this.startValue)){
40805 this.fireEvent('change', this, v, this.startValue);
40807 this.fireEvent("blur", this);
40811 * Returns whether or not the field value is currently valid
40812 * @param {Boolean} preventMark True to disable marking the field invalid
40813 * @return {Boolean} True if the value is valid, else false
40815 isValid : function(preventMark){
40819 var restore = this.preventMark;
40820 this.preventMark = preventMark === true;
40821 var v = this.validateValue(this.processValue(this.getRawValue()));
40822 this.preventMark = restore;
40827 * Validates the field value
40828 * @return {Boolean} True if the value is valid, else false
40830 validate : function(){
40831 if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
40832 this.clearInvalid();
40838 processValue : function(value){
40843 // Subclasses should provide the validation implementation by overriding this
40844 validateValue : function(value){
40849 * Mark this field as invalid
40850 * @param {String} msg The validation message
40852 markInvalid : function(msg){
40853 if(!this.rendered || this.preventMark){ // not rendered
40857 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
40859 obj.el.addClass(this.invalidClass);
40860 msg = msg || this.invalidText;
40861 switch(this.msgTarget){
40863 obj.el.dom.qtip = msg;
40864 obj.el.dom.qclass = 'x-form-invalid-tip';
40865 if(Roo.QuickTips){ // fix for floating editors interacting with DND
40866 Roo.QuickTips.enable();
40870 this.el.dom.title = msg;
40874 var elp = this.el.findParent('.x-form-element', 5, true);
40875 this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
40876 this.errorEl.setWidth(elp.getWidth(true)-20);
40878 this.errorEl.update(msg);
40879 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
40882 if(!this.errorIcon){
40883 var elp = this.el.findParent('.x-form-element', 5, true);
40884 this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
40886 this.alignErrorIcon();
40887 this.errorIcon.dom.qtip = msg;
40888 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
40889 this.errorIcon.show();
40890 this.on('resize', this.alignErrorIcon, this);
40893 var t = Roo.getDom(this.msgTarget);
40895 t.style.display = this.msgDisplay;
40898 this.fireEvent('invalid', this, msg);
40902 alignErrorIcon : function(){
40903 this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
40907 * Clear any invalid styles/messages for this field
40909 clearInvalid : function(){
40910 if(!this.rendered || this.preventMark){ // not rendered
40913 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
40915 obj.el.removeClass(this.invalidClass);
40916 switch(this.msgTarget){
40918 obj.el.dom.qtip = '';
40921 this.el.dom.title = '';
40925 Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
40929 if(this.errorIcon){
40930 this.errorIcon.dom.qtip = '';
40931 this.errorIcon.hide();
40932 this.un('resize', this.alignErrorIcon, this);
40936 var t = Roo.getDom(this.msgTarget);
40938 t.style.display = 'none';
40941 this.fireEvent('valid', this);
40945 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
40946 * @return {Mixed} value The field value
40948 getRawValue : function(){
40949 var v = this.el.getValue();
40955 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
40956 * @return {Mixed} value The field value
40958 getValue : function(){
40959 var v = this.el.getValue();
40965 * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
40966 * @param {Mixed} value The value to set
40968 setRawValue : function(v){
40969 return this.el.dom.value = (v === null || v === undefined ? '' : v);
40973 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
40974 * @param {Mixed} value The value to set
40976 setValue : function(v){
40979 this.el.dom.value = (v === null || v === undefined ? '' : v);
40984 adjustSize : function(w, h){
40985 var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
40986 s.width = this.adjustWidth(this.el.dom.tagName, s.width);
40990 adjustWidth : function(tag, w){
40991 tag = tag.toLowerCase();
40992 if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
40993 if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
40994 if(tag == 'input'){
40997 if(tag == 'textarea'){
41000 }else if(Roo.isOpera){
41001 if(tag == 'input'){
41004 if(tag == 'textarea'){
41014 // anything other than normal should be considered experimental
41015 Roo.form.Field.msgFx = {
41017 show: function(msgEl, f){
41018 msgEl.setDisplayed('block');
41021 hide : function(msgEl, f){
41022 msgEl.setDisplayed(false).update('');
41027 show: function(msgEl, f){
41028 msgEl.slideIn('t', {stopFx:true});
41031 hide : function(msgEl, f){
41032 msgEl.slideOut('t', {stopFx:true,useDisplay:true});
41037 show: function(msgEl, f){
41038 msgEl.fixDisplay();
41039 msgEl.alignTo(f.el, 'tl-tr');
41040 msgEl.slideIn('l', {stopFx:true});
41043 hide : function(msgEl, f){
41044 msgEl.slideOut('l', {stopFx:true,useDisplay:true});
41049 * Ext JS Library 1.1.1
41050 * Copyright(c) 2006-2007, Ext JS, LLC.
41052 * Originally Released Under LGPL - original licence link has changed is not relivant.
41055 * <script type="text/javascript">
41060 * @class Roo.form.TextField
41061 * @extends Roo.form.Field
41062 * Basic text field. Can be used as a direct replacement for traditional text inputs, or as the base
41063 * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
41065 * Creates a new TextField
41066 * @param {Object} config Configuration options
41068 Roo.form.TextField = function(config){
41069 Roo.form.TextField.superclass.constructor.call(this, config);
41073 * Fires when the autosize function is triggered. The field may or may not have actually changed size
41074 * according to the default logic, but this event provides a hook for the developer to apply additional
41075 * logic at runtime to resize the field if needed.
41076 * @param {Roo.form.Field} this This text field
41077 * @param {Number} width The new field width
41083 Roo.extend(Roo.form.TextField, Roo.form.Field, {
41085 * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
41089 * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
41093 * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
41097 * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
41101 * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
41105 * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
41107 disableKeyFilter : false,
41109 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
41113 * @cfg {Number} minLength Minimum input field length required (defaults to 0)
41117 * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
41119 maxLength : Number.MAX_VALUE,
41121 * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
41123 minLengthText : "The minimum length for this field is {0}",
41125 * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
41127 maxLengthText : "The maximum length for this field is {0}",
41129 * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
41131 selectOnFocus : false,
41133 * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space
41135 allowLeadingSpace : false,
41137 * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
41139 blankText : "This field is required",
41141 * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
41142 * If available, this function will be called only after the basic validators all return true, and will be passed the
41143 * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
41147 * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
41148 * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
41149 * current field value. If the test fails, the field will be marked invalid using {@link #regexText}.
41153 * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
41157 * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
41163 initEvents : function()
41165 if (this.emptyText) {
41166 this.el.attr('placeholder', this.emptyText);
41169 Roo.form.TextField.superclass.initEvents.call(this);
41170 if(this.validationEvent == 'keyup'){
41171 this.validationTask = new Roo.util.DelayedTask(this.validate, this);
41172 this.el.on('keyup', this.filterValidation, this);
41174 else if(this.validationEvent !== false){
41175 this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
41178 if(this.selectOnFocus){
41179 this.on("focus", this.preFocus, this);
41181 if (!this.allowLeadingSpace) {
41182 this.on('blur', this.cleanLeadingSpace, this);
41185 if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
41186 this.el.on("keypress", this.filterKeys, this);
41189 this.el.on("keyup", this.onKeyUp, this, {buffer:50});
41190 this.el.on("click", this.autoSize, this);
41192 if(this.el.is('input[type=password]') && Roo.isSafari){
41193 this.el.on('keydown', this.SafariOnKeyDown, this);
41197 processValue : function(value){
41198 if(this.stripCharsRe){
41199 var newValue = value.replace(this.stripCharsRe, '');
41200 if(newValue !== value){
41201 this.setRawValue(newValue);
41208 filterValidation : function(e){
41209 if(!e.isNavKeyPress()){
41210 this.validationTask.delay(this.validationDelay);
41215 onKeyUp : function(e){
41216 if(!e.isNavKeyPress()){
41220 // private - clean the leading white space
41221 cleanLeadingSpace : function(e)
41223 if ( this.inputType == 'file') {
41227 this.setValue((this.getValue() + '').replace(/^\s+/,''));
41230 * Resets the current field value to the originally-loaded value and clears any validation messages.
41233 reset : function(){
41234 Roo.form.TextField.superclass.reset.call(this);
41238 preFocus : function(){
41240 if(this.selectOnFocus){
41241 this.el.dom.select();
41247 filterKeys : function(e){
41248 var k = e.getKey();
41249 if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
41252 var c = e.getCharCode(), cc = String.fromCharCode(c);
41253 if(Roo.isIE && (e.isSpecialKey() || !cc)){
41256 if(!this.maskRe.test(cc)){
41261 setValue : function(v){
41263 Roo.form.TextField.superclass.setValue.apply(this, arguments);
41269 * Validates a value according to the field's validation rules and marks the field as invalid
41270 * if the validation fails
41271 * @param {Mixed} value The value to validate
41272 * @return {Boolean} True if the value is valid, else false
41274 validateValue : function(value){
41275 if(value.length < 1) { // if it's blank
41276 if(this.allowBlank){
41277 this.clearInvalid();
41280 this.markInvalid(this.blankText);
41284 if(value.length < this.minLength){
41285 this.markInvalid(String.format(this.minLengthText, this.minLength));
41288 if(value.length > this.maxLength){
41289 this.markInvalid(String.format(this.maxLengthText, this.maxLength));
41293 var vt = Roo.form.VTypes;
41294 if(!vt[this.vtype](value, this)){
41295 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
41299 if(typeof this.validator == "function"){
41300 var msg = this.validator(value);
41302 this.markInvalid(msg);
41306 if(this.regex && !this.regex.test(value)){
41307 this.markInvalid(this.regexText);
41314 * Selects text in this field
41315 * @param {Number} start (optional) The index where the selection should start (defaults to 0)
41316 * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
41318 selectText : function(start, end){
41319 var v = this.getRawValue();
41321 start = start === undefined ? 0 : start;
41322 end = end === undefined ? v.length : end;
41323 var d = this.el.dom;
41324 if(d.setSelectionRange){
41325 d.setSelectionRange(start, end);
41326 }else if(d.createTextRange){
41327 var range = d.createTextRange();
41328 range.moveStart("character", start);
41329 range.moveEnd("character", v.length-end);
41336 * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
41337 * This only takes effect if grow = true, and fires the autosize event.
41339 autoSize : function(){
41340 if(!this.grow || !this.rendered){
41344 this.metrics = Roo.util.TextMetrics.createInstance(this.el);
41347 var v = el.dom.value;
41348 var d = document.createElement('div');
41349 d.appendChild(document.createTextNode(v));
41353 var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
41354 this.el.setWidth(w);
41355 this.fireEvent("autosize", this, w);
41359 SafariOnKeyDown : function(event)
41361 // this is a workaround for a password hang bug on chrome/ webkit.
41363 var isSelectAll = false;
41365 if(this.el.dom.selectionEnd > 0){
41366 isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
41368 if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
41369 event.preventDefault();
41374 if(isSelectAll && event.getCharCode() > 31){ // backspace and delete key
41376 event.preventDefault();
41377 // this is very hacky as keydown always get's upper case.
41379 var cc = String.fromCharCode(event.getCharCode());
41382 this.setValue( event.shiftKey ? cc : cc.toLowerCase());
41390 * Ext JS Library 1.1.1
41391 * Copyright(c) 2006-2007, Ext JS, LLC.
41393 * Originally Released Under LGPL - original licence link has changed is not relivant.
41396 * <script type="text/javascript">
41400 * @class Roo.form.Hidden
41401 * @extends Roo.form.TextField
41402 * Simple Hidden element used on forms
41404 * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
41407 * Creates a new Hidden form element.
41408 * @param {Object} config Configuration options
41413 // easy hidden field...
41414 Roo.form.Hidden = function(config){
41415 Roo.form.Hidden.superclass.constructor.call(this, config);
41418 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
41420 inputType: 'hidden',
41423 labelSeparator: '',
41425 itemCls : 'x-form-item-display-none'
41433 * Ext JS Library 1.1.1
41434 * Copyright(c) 2006-2007, Ext JS, LLC.
41436 * Originally Released Under LGPL - original licence link has changed is not relivant.
41439 * <script type="text/javascript">
41443 * @class Roo.form.TriggerField
41444 * @extends Roo.form.TextField
41445 * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
41446 * The trigger has no default action, so you must assign a function to implement the trigger click handler by
41447 * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
41448 * for which you can provide a custom implementation. For example:
41450 var trigger = new Roo.form.TriggerField();
41451 trigger.onTriggerClick = myTriggerFn;
41452 trigger.applyTo('my-field');
41455 * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
41456 * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
41457 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
41458 * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
41460 * Create a new TriggerField.
41461 * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
41462 * to the base TextField)
41464 Roo.form.TriggerField = function(config){
41465 this.mimicing = false;
41466 Roo.form.TriggerField.superclass.constructor.call(this, config);
41469 Roo.extend(Roo.form.TriggerField, Roo.form.TextField, {
41471 * @cfg {String} triggerClass A CSS class to apply to the trigger
41474 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
41475 * {tag: "input", type: "text", size: "16", autocomplete: "off"})
41477 defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
41479 * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
41483 /** @cfg {Boolean} grow @hide */
41484 /** @cfg {Number} growMin @hide */
41485 /** @cfg {Number} growMax @hide */
41491 autoSize: Roo.emptyFn,
41495 deferHeight : true,
41498 actionMode : 'wrap',
41500 onResize : function(w, h){
41501 Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
41502 if(typeof w == 'number'){
41503 var x = w - this.trigger.getWidth();
41504 this.el.setWidth(this.adjustWidth('input', x));
41505 this.trigger.setStyle('left', x+'px');
41510 adjustSize : Roo.BoxComponent.prototype.adjustSize,
41513 getResizeEl : function(){
41518 getPositionEl : function(){
41523 alignErrorIcon : function(){
41524 this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
41528 onRender : function(ct, position){
41529 Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
41530 this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
41531 this.trigger = this.wrap.createChild(this.triggerConfig ||
41532 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
41533 if(this.hideTrigger){
41534 this.trigger.setDisplayed(false);
41536 this.initTrigger();
41538 this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
41543 initTrigger : function(){
41544 this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
41545 this.trigger.addClassOnOver('x-form-trigger-over');
41546 this.trigger.addClassOnClick('x-form-trigger-click');
41550 onDestroy : function(){
41552 this.trigger.removeAllListeners();
41553 this.trigger.remove();
41556 this.wrap.remove();
41558 Roo.form.TriggerField.superclass.onDestroy.call(this);
41562 onFocus : function(){
41563 Roo.form.TriggerField.superclass.onFocus.call(this);
41564 if(!this.mimicing){
41565 this.wrap.addClass('x-trigger-wrap-focus');
41566 this.mimicing = true;
41567 Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
41568 if(this.monitorTab){
41569 this.el.on("keydown", this.checkTab, this);
41575 checkTab : function(e){
41576 if(e.getKey() == e.TAB){
41577 this.triggerBlur();
41582 onBlur : function(){
41587 mimicBlur : function(e, t){
41588 if(!this.wrap.contains(t) && this.validateBlur()){
41589 this.triggerBlur();
41594 triggerBlur : function(){
41595 this.mimicing = false;
41596 Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
41597 if(this.monitorTab){
41598 this.el.un("keydown", this.checkTab, this);
41600 this.wrap.removeClass('x-trigger-wrap-focus');
41601 Roo.form.TriggerField.superclass.onBlur.call(this);
41605 // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
41606 validateBlur : function(e, t){
41611 onDisable : function(){
41612 Roo.form.TriggerField.superclass.onDisable.call(this);
41614 this.wrap.addClass('x-item-disabled');
41619 onEnable : function(){
41620 Roo.form.TriggerField.superclass.onEnable.call(this);
41622 this.wrap.removeClass('x-item-disabled');
41627 onShow : function(){
41628 var ae = this.getActionEl();
41631 ae.dom.style.display = '';
41632 ae.dom.style.visibility = 'visible';
41638 onHide : function(){
41639 var ae = this.getActionEl();
41640 ae.dom.style.display = 'none';
41644 * The function that should handle the trigger's click event. This method does nothing by default until overridden
41645 * by an implementing function.
41647 * @param {EventObject} e
41649 onTriggerClick : Roo.emptyFn
41652 // TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
41653 // to be extended by an implementing class. For an example of implementing this class, see the custom
41654 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
41655 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
41656 initComponent : function(){
41657 Roo.form.TwinTriggerField.superclass.initComponent.call(this);
41659 this.triggerConfig = {
41660 tag:'span', cls:'x-form-twin-triggers', cn:[
41661 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
41662 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
41666 getTrigger : function(index){
41667 return this.triggers[index];
41670 initTrigger : function(){
41671 var ts = this.trigger.select('.x-form-trigger', true);
41672 this.wrap.setStyle('overflow', 'hidden');
41673 var triggerField = this;
41674 ts.each(function(t, all, index){
41675 t.hide = function(){
41676 var w = triggerField.wrap.getWidth();
41677 this.dom.style.display = 'none';
41678 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
41680 t.show = function(){
41681 var w = triggerField.wrap.getWidth();
41682 this.dom.style.display = '';
41683 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
41685 var triggerIndex = 'Trigger'+(index+1);
41687 if(this['hide'+triggerIndex]){
41688 t.dom.style.display = 'none';
41690 t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
41691 t.addClassOnOver('x-form-trigger-over');
41692 t.addClassOnClick('x-form-trigger-click');
41694 this.triggers = ts.elements;
41697 onTrigger1Click : Roo.emptyFn,
41698 onTrigger2Click : Roo.emptyFn
41701 * Ext JS Library 1.1.1
41702 * Copyright(c) 2006-2007, Ext JS, LLC.
41704 * Originally Released Under LGPL - original licence link has changed is not relivant.
41707 * <script type="text/javascript">
41711 * @class Roo.form.TextArea
41712 * @extends Roo.form.TextField
41713 * Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
41714 * support for auto-sizing.
41716 * Creates a new TextArea
41717 * @param {Object} config Configuration options
41719 Roo.form.TextArea = function(config){
41720 Roo.form.TextArea.superclass.constructor.call(this, config);
41721 // these are provided exchanges for backwards compat
41722 // minHeight/maxHeight were replaced by growMin/growMax to be
41723 // compatible with TextField growing config values
41724 if(this.minHeight !== undefined){
41725 this.growMin = this.minHeight;
41727 if(this.maxHeight !== undefined){
41728 this.growMax = this.maxHeight;
41732 Roo.extend(Roo.form.TextArea, Roo.form.TextField, {
41734 * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
41738 * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
41742 * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
41743 * in the field (equivalent to setting overflow: hidden, defaults to false)
41745 preventScrollbars: false,
41747 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
41748 * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
41752 onRender : function(ct, position){
41754 this.defaultAutoCreate = {
41756 style:"width:300px;height:60px;",
41757 autocomplete: "new-password"
41760 Roo.form.TextArea.superclass.onRender.call(this, ct, position);
41762 this.textSizeEl = Roo.DomHelper.append(document.body, {
41763 tag: "pre", cls: "x-form-grow-sizer"
41765 if(this.preventScrollbars){
41766 this.el.setStyle("overflow", "hidden");
41768 this.el.setHeight(this.growMin);
41772 onDestroy : function(){
41773 if(this.textSizeEl){
41774 this.textSizeEl.parentNode.removeChild(this.textSizeEl);
41776 Roo.form.TextArea.superclass.onDestroy.call(this);
41780 onKeyUp : function(e){
41781 if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
41787 * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
41788 * This only takes effect if grow = true, and fires the autosize event if the height changes.
41790 autoSize : function(){
41791 if(!this.grow || !this.textSizeEl){
41795 var v = el.dom.value;
41796 var ts = this.textSizeEl;
41799 ts.appendChild(document.createTextNode(v));
41802 Roo.fly(ts).setWidth(this.el.getWidth());
41804 v = "  ";
41807 v = v.replace(/\n/g, '<p> </p>');
41809 v += " \n ";
41812 var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
41813 if(h != this.lastHeight){
41814 this.lastHeight = h;
41815 this.el.setHeight(h);
41816 this.fireEvent("autosize", this, h);
41821 * Ext JS Library 1.1.1
41822 * Copyright(c) 2006-2007, Ext JS, LLC.
41824 * Originally Released Under LGPL - original licence link has changed is not relivant.
41827 * <script type="text/javascript">
41832 * @class Roo.form.NumberField
41833 * @extends Roo.form.TextField
41834 * Numeric text field that provides automatic keystroke filtering and numeric validation.
41836 * Creates a new NumberField
41837 * @param {Object} config Configuration options
41839 Roo.form.NumberField = function(config){
41840 Roo.form.NumberField.superclass.constructor.call(this, config);
41843 Roo.extend(Roo.form.NumberField, Roo.form.TextField, {
41845 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
41847 fieldClass: "x-form-field x-form-num-field",
41849 * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
41851 allowDecimals : true,
41853 * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
41855 decimalSeparator : ".",
41857 * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
41859 decimalPrecision : 2,
41861 * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
41863 allowNegative : true,
41865 * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
41867 minValue : Number.NEGATIVE_INFINITY,
41869 * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
41871 maxValue : Number.MAX_VALUE,
41873 * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
41875 minText : "The minimum value for this field is {0}",
41877 * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
41879 maxText : "The maximum value for this field is {0}",
41881 * @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
41882 * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
41884 nanText : "{0} is not a valid number",
41887 initEvents : function(){
41888 Roo.form.NumberField.superclass.initEvents.call(this);
41889 var allowed = "0123456789";
41890 if(this.allowDecimals){
41891 allowed += this.decimalSeparator;
41893 if(this.allowNegative){
41896 this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
41897 var keyPress = function(e){
41898 var k = e.getKey();
41899 if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
41902 var c = e.getCharCode();
41903 if(allowed.indexOf(String.fromCharCode(c)) === -1){
41907 this.el.on("keypress", keyPress, this);
41911 validateValue : function(value){
41912 if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
41915 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
41918 var num = this.parseValue(value);
41920 this.markInvalid(String.format(this.nanText, value));
41923 if(num < this.minValue){
41924 this.markInvalid(String.format(this.minText, this.minValue));
41927 if(num > this.maxValue){
41928 this.markInvalid(String.format(this.maxText, this.maxValue));
41934 getValue : function(){
41935 return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
41939 parseValue : function(value){
41940 value = parseFloat(String(value).replace(this.decimalSeparator, "."));
41941 return isNaN(value) ? '' : value;
41945 fixPrecision : function(value){
41946 var nan = isNaN(value);
41947 if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
41948 return nan ? '' : value;
41950 return parseFloat(value).toFixed(this.decimalPrecision);
41953 setValue : function(v){
41954 v = this.fixPrecision(v);
41955 Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
41959 decimalPrecisionFcn : function(v){
41960 return Math.floor(v);
41963 beforeBlur : function(){
41964 var v = this.parseValue(this.getRawValue());
41971 * Ext JS Library 1.1.1
41972 * Copyright(c) 2006-2007, Ext JS, LLC.
41974 * Originally Released Under LGPL - original licence link has changed is not relivant.
41977 * <script type="text/javascript">
41981 * @class Roo.form.DateField
41982 * @extends Roo.form.TriggerField
41983 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
41985 * Create a new DateField
41986 * @param {Object} config
41988 Roo.form.DateField = function(config)
41990 Roo.form.DateField.superclass.constructor.call(this, config);
41996 * Fires when a date is selected
41997 * @param {Roo.form.DateField} combo This combo box
41998 * @param {Date} date The date selected
42005 if(typeof this.minValue == "string") {
42006 this.minValue = this.parseDate(this.minValue);
42008 if(typeof this.maxValue == "string") {
42009 this.maxValue = this.parseDate(this.maxValue);
42011 this.ddMatch = null;
42012 if(this.disabledDates){
42013 var dd = this.disabledDates;
42015 for(var i = 0; i < dd.length; i++){
42017 if(i != dd.length-1) {
42021 this.ddMatch = new RegExp(re + ")");
42025 Roo.extend(Roo.form.DateField, Roo.form.TriggerField, {
42027 * @cfg {String} format
42028 * The default date format string which can be overriden for localization support. The format must be
42029 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
42033 * @cfg {String} altFormats
42034 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
42035 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
42037 altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
42039 * @cfg {Array} disabledDays
42040 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
42042 disabledDays : null,
42044 * @cfg {String} disabledDaysText
42045 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
42047 disabledDaysText : "Disabled",
42049 * @cfg {Array} disabledDates
42050 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
42051 * expression so they are very powerful. Some examples:
42053 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
42054 * <li>["03/08", "09/16"] would disable those days for every year</li>
42055 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
42056 * <li>["03/../2006"] would disable every day in March 2006</li>
42057 * <li>["^03"] would disable every day in every March</li>
42059 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
42060 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
42062 disabledDates : null,
42064 * @cfg {String} disabledDatesText
42065 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
42067 disabledDatesText : "Disabled",
42071 * @cfg {Date/String} zeroValue
42072 * if the date is less that this number, then the field is rendered as empty
42075 zeroValue : '1800-01-01',
42079 * @cfg {Date/String} minValue
42080 * The minimum allowed date. Can be either a Javascript date object or a string date in a
42081 * valid format (defaults to null).
42085 * @cfg {Date/String} maxValue
42086 * The maximum allowed date. Can be either a Javascript date object or a string date in a
42087 * valid format (defaults to null).
42091 * @cfg {String} minText
42092 * The error text to display when the date in the cell is before minValue (defaults to
42093 * 'The date in this field must be after {minValue}').
42095 minText : "The date in this field must be equal to or after {0}",
42097 * @cfg {String} maxText
42098 * The error text to display when the date in the cell is after maxValue (defaults to
42099 * 'The date in this field must be before {maxValue}').
42101 maxText : "The date in this field must be equal to or before {0}",
42103 * @cfg {String} invalidText
42104 * The error text to display when the date in the field is invalid (defaults to
42105 * '{value} is not a valid date - it must be in the format {format}').
42107 invalidText : "{0} is not a valid date - it must be in the format {1}",
42109 * @cfg {String} triggerClass
42110 * An additional CSS class used to style the trigger button. The trigger will always get the
42111 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
42112 * which displays a calendar icon).
42114 triggerClass : 'x-form-date-trigger',
42118 * @cfg {Boolean} useIso
42119 * if enabled, then the date field will use a hidden field to store the
42120 * real value as iso formated date. default (false)
42124 * @cfg {String/Object} autoCreate
42125 * A DomHelper element spec, or true for a default element spec (defaults to
42126 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
42129 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
42132 hiddenField: false,
42134 onRender : function(ct, position)
42136 Roo.form.DateField.superclass.onRender.call(this, ct, position);
42138 //this.el.dom.removeAttribute('name');
42139 Roo.log("Changing name?");
42140 this.el.dom.setAttribute('name', this.name + '____hidden___' );
42141 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
42143 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
42144 // prevent input submission
42145 this.hiddenName = this.name;
42152 validateValue : function(value)
42154 value = this.formatDate(value);
42155 if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
42156 Roo.log('super failed');
42159 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
42162 var svalue = value;
42163 value = this.parseDate(value);
42165 Roo.log('parse date failed' + svalue);
42166 this.markInvalid(String.format(this.invalidText, svalue, this.format));
42169 var time = value.getTime();
42170 if(this.minValue && time < this.minValue.getTime()){
42171 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
42174 if(this.maxValue && time > this.maxValue.getTime()){
42175 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
42178 if(this.disabledDays){
42179 var day = value.getDay();
42180 for(var i = 0; i < this.disabledDays.length; i++) {
42181 if(day === this.disabledDays[i]){
42182 this.markInvalid(this.disabledDaysText);
42187 var fvalue = this.formatDate(value);
42188 if(this.ddMatch && this.ddMatch.test(fvalue)){
42189 this.markInvalid(String.format(this.disabledDatesText, fvalue));
42196 // Provides logic to override the default TriggerField.validateBlur which just returns true
42197 validateBlur : function(){
42198 return !this.menu || !this.menu.isVisible();
42201 getName: function()
42203 // returns hidden if it's set..
42204 if (!this.rendered) {return ''};
42205 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
42210 * Returns the current date value of the date field.
42211 * @return {Date} The date value
42213 getValue : function(){
42215 return this.hiddenField ?
42216 this.hiddenField.value :
42217 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
42221 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
42222 * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
42223 * (the default format used is "m/d/y").
42226 //All of these calls set the same date value (May 4, 2006)
42228 //Pass a date object:
42229 var dt = new Date('5/4/06');
42230 dateField.setValue(dt);
42232 //Pass a date string (default format):
42233 dateField.setValue('5/4/06');
42235 //Pass a date string (custom format):
42236 dateField.format = 'Y-m-d';
42237 dateField.setValue('2006-5-4');
42239 * @param {String/Date} date The date or valid date string
42241 setValue : function(date){
42242 if (this.hiddenField) {
42243 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
42245 Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
42246 // make sure the value field is always stored as a date..
42247 this.value = this.parseDate(date);
42253 parseDate : function(value){
42255 if (value instanceof Date) {
42256 if (value < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
42263 if(!value || value instanceof Date){
42266 var v = Date.parseDate(value, this.format);
42267 if (!v && this.useIso) {
42268 v = Date.parseDate(value, 'Y-m-d');
42270 if(!v && this.altFormats){
42271 if(!this.altFormatsArray){
42272 this.altFormatsArray = this.altFormats.split("|");
42274 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
42275 v = Date.parseDate(value, this.altFormatsArray[i]);
42278 if (v < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
42285 formatDate : function(date, fmt){
42286 return (!date || !(date instanceof Date)) ?
42287 date : date.dateFormat(fmt || this.format);
42292 select: function(m, d){
42295 this.fireEvent('select', this, d);
42297 show : function(){ // retain focus styling
42301 this.focus.defer(10, this);
42302 var ml = this.menuListeners;
42303 this.menu.un("select", ml.select, this);
42304 this.menu.un("show", ml.show, this);
42305 this.menu.un("hide", ml.hide, this);
42310 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
42311 onTriggerClick : function(){
42315 if(this.menu == null){
42316 this.menu = new Roo.menu.DateMenu();
42318 Roo.apply(this.menu.picker, {
42319 showClear: this.allowBlank,
42320 minDate : this.minValue,
42321 maxDate : this.maxValue,
42322 disabledDatesRE : this.ddMatch,
42323 disabledDatesText : this.disabledDatesText,
42324 disabledDays : this.disabledDays,
42325 disabledDaysText : this.disabledDaysText,
42326 format : this.useIso ? 'Y-m-d' : this.format,
42327 minText : String.format(this.minText, this.formatDate(this.minValue)),
42328 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
42330 this.menu.on(Roo.apply({}, this.menuListeners, {
42333 this.menu.picker.setValue(this.getValue() || new Date());
42334 this.menu.show(this.el, "tl-bl?");
42337 beforeBlur : function(){
42338 var v = this.parseDate(this.getRawValue());
42348 isDirty : function() {
42349 if(this.disabled) {
42353 if(typeof(this.startValue) === 'undefined'){
42357 return String(this.getValue()) !== String(this.startValue);
42361 cleanLeadingSpace : function(e)
42368 * Ext JS Library 1.1.1
42369 * Copyright(c) 2006-2007, Ext JS, LLC.
42371 * Originally Released Under LGPL - original licence link has changed is not relivant.
42374 * <script type="text/javascript">
42378 * @class Roo.form.MonthField
42379 * @extends Roo.form.TriggerField
42380 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
42382 * Create a new MonthField
42383 * @param {Object} config
42385 Roo.form.MonthField = function(config){
42387 Roo.form.MonthField.superclass.constructor.call(this, config);
42393 * Fires when a date is selected
42394 * @param {Roo.form.MonthFieeld} combo This combo box
42395 * @param {Date} date The date selected
42402 if(typeof this.minValue == "string") {
42403 this.minValue = this.parseDate(this.minValue);
42405 if(typeof this.maxValue == "string") {
42406 this.maxValue = this.parseDate(this.maxValue);
42408 this.ddMatch = null;
42409 if(this.disabledDates){
42410 var dd = this.disabledDates;
42412 for(var i = 0; i < dd.length; i++){
42414 if(i != dd.length-1) {
42418 this.ddMatch = new RegExp(re + ")");
42422 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField, {
42424 * @cfg {String} format
42425 * The default date format string which can be overriden for localization support. The format must be
42426 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
42430 * @cfg {String} altFormats
42431 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
42432 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
42434 altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
42436 * @cfg {Array} disabledDays
42437 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
42439 disabledDays : [0,1,2,3,4,5,6],
42441 * @cfg {String} disabledDaysText
42442 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
42444 disabledDaysText : "Disabled",
42446 * @cfg {Array} disabledDates
42447 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
42448 * expression so they are very powerful. Some examples:
42450 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
42451 * <li>["03/08", "09/16"] would disable those days for every year</li>
42452 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
42453 * <li>["03/../2006"] would disable every day in March 2006</li>
42454 * <li>["^03"] would disable every day in every March</li>
42456 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
42457 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
42459 disabledDates : null,
42461 * @cfg {String} disabledDatesText
42462 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
42464 disabledDatesText : "Disabled",
42466 * @cfg {Date/String} minValue
42467 * The minimum allowed date. Can be either a Javascript date object or a string date in a
42468 * valid format (defaults to null).
42472 * @cfg {Date/String} maxValue
42473 * The maximum allowed date. Can be either a Javascript date object or a string date in a
42474 * valid format (defaults to null).
42478 * @cfg {String} minText
42479 * The error text to display when the date in the cell is before minValue (defaults to
42480 * 'The date in this field must be after {minValue}').
42482 minText : "The date in this field must be equal to or after {0}",
42484 * @cfg {String} maxTextf
42485 * The error text to display when the date in the cell is after maxValue (defaults to
42486 * 'The date in this field must be before {maxValue}').
42488 maxText : "The date in this field must be equal to or before {0}",
42490 * @cfg {String} invalidText
42491 * The error text to display when the date in the field is invalid (defaults to
42492 * '{value} is not a valid date - it must be in the format {format}').
42494 invalidText : "{0} is not a valid date - it must be in the format {1}",
42496 * @cfg {String} triggerClass
42497 * An additional CSS class used to style the trigger button. The trigger will always get the
42498 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
42499 * which displays a calendar icon).
42501 triggerClass : 'x-form-date-trigger',
42505 * @cfg {Boolean} useIso
42506 * if enabled, then the date field will use a hidden field to store the
42507 * real value as iso formated date. default (true)
42511 * @cfg {String/Object} autoCreate
42512 * A DomHelper element spec, or true for a default element spec (defaults to
42513 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
42516 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
42519 hiddenField: false,
42521 hideMonthPicker : false,
42523 onRender : function(ct, position)
42525 Roo.form.MonthField.superclass.onRender.call(this, ct, position);
42527 this.el.dom.removeAttribute('name');
42528 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
42530 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
42531 // prevent input submission
42532 this.hiddenName = this.name;
42539 validateValue : function(value)
42541 value = this.formatDate(value);
42542 if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
42545 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
42548 var svalue = value;
42549 value = this.parseDate(value);
42551 this.markInvalid(String.format(this.invalidText, svalue, this.format));
42554 var time = value.getTime();
42555 if(this.minValue && time < this.minValue.getTime()){
42556 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
42559 if(this.maxValue && time > this.maxValue.getTime()){
42560 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
42563 /*if(this.disabledDays){
42564 var day = value.getDay();
42565 for(var i = 0; i < this.disabledDays.length; i++) {
42566 if(day === this.disabledDays[i]){
42567 this.markInvalid(this.disabledDaysText);
42573 var fvalue = this.formatDate(value);
42574 /*if(this.ddMatch && this.ddMatch.test(fvalue)){
42575 this.markInvalid(String.format(this.disabledDatesText, fvalue));
42583 // Provides logic to override the default TriggerField.validateBlur which just returns true
42584 validateBlur : function(){
42585 return !this.menu || !this.menu.isVisible();
42589 * Returns the current date value of the date field.
42590 * @return {Date} The date value
42592 getValue : function(){
42596 return this.hiddenField ?
42597 this.hiddenField.value :
42598 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
42602 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
42603 * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
42604 * (the default format used is "m/d/y").
42607 //All of these calls set the same date value (May 4, 2006)
42609 //Pass a date object:
42610 var dt = new Date('5/4/06');
42611 monthField.setValue(dt);
42613 //Pass a date string (default format):
42614 monthField.setValue('5/4/06');
42616 //Pass a date string (custom format):
42617 monthField.format = 'Y-m-d';
42618 monthField.setValue('2006-5-4');
42620 * @param {String/Date} date The date or valid date string
42622 setValue : function(date){
42623 Roo.log('month setValue' + date);
42624 // can only be first of month..
42626 var val = this.parseDate(date);
42628 if (this.hiddenField) {
42629 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
42631 Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
42632 this.value = this.parseDate(date);
42636 parseDate : function(value){
42637 if(!value || value instanceof Date){
42638 value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
42641 var v = Date.parseDate(value, this.format);
42642 if (!v && this.useIso) {
42643 v = Date.parseDate(value, 'Y-m-d');
42647 v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
42651 if(!v && this.altFormats){
42652 if(!this.altFormatsArray){
42653 this.altFormatsArray = this.altFormats.split("|");
42655 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
42656 v = Date.parseDate(value, this.altFormatsArray[i]);
42663 formatDate : function(date, fmt){
42664 return (!date || !(date instanceof Date)) ?
42665 date : date.dateFormat(fmt || this.format);
42670 select: function(m, d){
42672 this.fireEvent('select', this, d);
42674 show : function(){ // retain focus styling
42678 this.focus.defer(10, this);
42679 var ml = this.menuListeners;
42680 this.menu.un("select", ml.select, this);
42681 this.menu.un("show", ml.show, this);
42682 this.menu.un("hide", ml.hide, this);
42686 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
42687 onTriggerClick : function(){
42691 if(this.menu == null){
42692 this.menu = new Roo.menu.DateMenu();
42696 Roo.apply(this.menu.picker, {
42698 showClear: this.allowBlank,
42699 minDate : this.minValue,
42700 maxDate : this.maxValue,
42701 disabledDatesRE : this.ddMatch,
42702 disabledDatesText : this.disabledDatesText,
42704 format : this.useIso ? 'Y-m-d' : this.format,
42705 minText : String.format(this.minText, this.formatDate(this.minValue)),
42706 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
42709 this.menu.on(Roo.apply({}, this.menuListeners, {
42717 // hide month picker get's called when we called by 'before hide';
42719 var ignorehide = true;
42720 p.hideMonthPicker = function(disableAnim){
42724 if(this.monthPicker){
42725 Roo.log("hideMonthPicker called");
42726 if(disableAnim === true){
42727 this.monthPicker.hide();
42729 this.monthPicker.slideOut('t', {duration:.2});
42730 p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
42731 p.fireEvent("select", this, this.value);
42737 Roo.log('picker set value');
42738 Roo.log(this.getValue());
42739 p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
42740 m.show(this.el, 'tl-bl?');
42741 ignorehide = false;
42742 // this will trigger hideMonthPicker..
42745 // hidden the day picker
42746 Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
42752 p.showMonthPicker.defer(100, p);
42758 beforeBlur : function(){
42759 var v = this.parseDate(this.getRawValue());
42765 /** @cfg {Boolean} grow @hide */
42766 /** @cfg {Number} growMin @hide */
42767 /** @cfg {Number} growMax @hide */
42774 * Ext JS Library 1.1.1
42775 * Copyright(c) 2006-2007, Ext JS, LLC.
42777 * Originally Released Under LGPL - original licence link has changed is not relivant.
42780 * <script type="text/javascript">
42785 * @class Roo.form.ComboBox
42786 * @extends Roo.form.TriggerField
42787 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
42789 * Create a new ComboBox.
42790 * @param {Object} config Configuration options
42792 Roo.form.ComboBox = function(config){
42793 Roo.form.ComboBox.superclass.constructor.call(this, config);
42797 * Fires when the dropdown list is expanded
42798 * @param {Roo.form.ComboBox} combo This combo box
42803 * Fires when the dropdown list is collapsed
42804 * @param {Roo.form.ComboBox} combo This combo box
42808 * @event beforeselect
42809 * Fires before a list item is selected. Return false to cancel the selection.
42810 * @param {Roo.form.ComboBox} combo This combo box
42811 * @param {Roo.data.Record} record The data record returned from the underlying store
42812 * @param {Number} index The index of the selected item in the dropdown list
42814 'beforeselect' : true,
42817 * Fires when a list item is selected
42818 * @param {Roo.form.ComboBox} combo This combo box
42819 * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
42820 * @param {Number} index The index of the selected item in the dropdown list
42824 * @event beforequery
42825 * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
42826 * The event object passed has these properties:
42827 * @param {Roo.form.ComboBox} combo This combo box
42828 * @param {String} query The query
42829 * @param {Boolean} forceAll true to force "all" query
42830 * @param {Boolean} cancel true to cancel the query
42831 * @param {Object} e The query event object
42833 'beforequery': true,
42836 * Fires when the 'add' icon is pressed (add a listener to enable add button)
42837 * @param {Roo.form.ComboBox} combo This combo box
42842 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
42843 * @param {Roo.form.ComboBox} combo This combo box
42844 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
42850 if(this.transform){
42851 this.allowDomMove = false;
42852 var s = Roo.getDom(this.transform);
42853 if(!this.hiddenName){
42854 this.hiddenName = s.name;
42857 this.mode = 'local';
42858 var d = [], opts = s.options;
42859 for(var i = 0, len = opts.length;i < len; i++){
42861 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
42863 this.value = value;
42865 d.push([value, o.text]);
42867 this.store = new Roo.data.SimpleStore({
42869 fields: ['value', 'text'],
42872 this.valueField = 'value';
42873 this.displayField = 'text';
42875 s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
42876 if(!this.lazyRender){
42877 this.target = true;
42878 this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
42879 s.parentNode.removeChild(s); // remove it
42880 this.render(this.el.parentNode);
42882 s.parentNode.removeChild(s); // remove it
42887 this.store = Roo.factory(this.store, Roo.data);
42890 this.selectedIndex = -1;
42891 if(this.mode == 'local'){
42892 if(config.queryDelay === undefined){
42893 this.queryDelay = 10;
42895 if(config.minChars === undefined){
42901 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
42903 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
42906 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
42907 * rendering into an Roo.Editor, defaults to false)
42910 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
42911 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
42914 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
42917 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
42918 * the dropdown list (defaults to undefined, with no header element)
42922 * @cfg {String/Roo.Template} tpl The template to use to render the output
42926 defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
42928 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
42930 listWidth: undefined,
42932 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
42933 * mode = 'remote' or 'text' if mode = 'local')
42935 displayField: undefined,
42937 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
42938 * mode = 'remote' or 'value' if mode = 'local').
42939 * Note: use of a valueField requires the user make a selection
42940 * in order for a value to be mapped.
42942 valueField: undefined,
42946 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
42947 * field's data value (defaults to the underlying DOM element's name)
42949 hiddenName: undefined,
42951 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
42955 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
42957 selectedClass: 'x-combo-selected',
42959 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
42960 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
42961 * which displays a downward arrow icon).
42963 triggerClass : 'x-form-arrow-trigger',
42965 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
42969 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
42970 * anchor positions (defaults to 'tl-bl')
42972 listAlign: 'tl-bl?',
42974 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
42978 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
42979 * query specified by the allQuery config option (defaults to 'query')
42981 triggerAction: 'query',
42983 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
42984 * (defaults to 4, does not apply if editable = false)
42988 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
42989 * delay (typeAheadDelay) if it matches a known value (defaults to false)
42993 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
42994 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
42998 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
42999 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
43003 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
43004 * when editable = true (defaults to false)
43006 selectOnFocus:false,
43008 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
43010 queryParam: 'query',
43012 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
43013 * when mode = 'remote' (defaults to 'Loading...')
43015 loadingText: 'Loading...',
43017 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
43021 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
43025 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
43026 * traditional select (defaults to true)
43030 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
43034 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
43038 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
43039 * listWidth has a higher value)
43043 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
43044 * allow the user to set arbitrary text into the field (defaults to false)
43046 forceSelection:false,
43048 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
43049 * if typeAhead = true (defaults to 250)
43051 typeAheadDelay : 250,
43053 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
43054 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
43056 valueNotFoundText : undefined,
43058 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
43060 blockFocus : false,
43063 * @cfg {Boolean} disableClear Disable showing of clear button.
43065 disableClear : false,
43067 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
43069 alwaysQuery : false,
43075 // element that contains real text value.. (when hidden is used..)
43078 onRender : function(ct, position)
43080 Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
43082 if(this.hiddenName){
43083 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
43085 this.hiddenField.value =
43086 this.hiddenValue !== undefined ? this.hiddenValue :
43087 this.value !== undefined ? this.value : '';
43089 // prevent input submission
43090 this.el.dom.removeAttribute('name');
43096 this.el.dom.setAttribute('autocomplete', 'off');
43099 var cls = 'x-combo-list';
43101 this.list = new Roo.Layer({
43102 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
43105 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
43106 this.list.setWidth(lw);
43107 this.list.swallowEvent('mousewheel');
43108 this.assetHeight = 0;
43111 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
43112 this.assetHeight += this.header.getHeight();
43115 this.innerList = this.list.createChild({cls:cls+'-inner'});
43116 this.innerList.on('mouseover', this.onViewOver, this);
43117 this.innerList.on('mousemove', this.onViewMove, this);
43118 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
43120 if(this.allowBlank && !this.pageSize && !this.disableClear){
43121 this.footer = this.list.createChild({cls:cls+'-ft'});
43122 this.pageTb = new Roo.Toolbar(this.footer);
43126 this.footer = this.list.createChild({cls:cls+'-ft'});
43127 this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
43128 {pageSize: this.pageSize});
43132 if (this.pageTb && this.allowBlank && !this.disableClear) {
43134 this.pageTb.add(new Roo.Toolbar.Fill(), {
43135 cls: 'x-btn-icon x-btn-clear',
43137 handler: function()
43140 _this.clearValue();
43141 _this.onSelect(false, -1);
43146 this.assetHeight += this.footer.getHeight();
43151 this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
43154 this.view = new Roo.View(this.innerList, this.tpl, {
43157 selectedClass: this.selectedClass
43160 this.view.on('click', this.onViewClick, this);
43162 this.store.on('beforeload', this.onBeforeLoad, this);
43163 this.store.on('load', this.onLoad, this);
43164 this.store.on('loadexception', this.onLoadException, this);
43166 if(this.resizable){
43167 this.resizer = new Roo.Resizable(this.list, {
43168 pinned:true, handles:'se'
43170 this.resizer.on('resize', function(r, w, h){
43171 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
43172 this.listWidth = w;
43173 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
43174 this.restrictHeight();
43176 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
43178 if(!this.editable){
43179 this.editable = true;
43180 this.setEditable(false);
43184 if (typeof(this.events.add.listeners) != 'undefined') {
43186 this.addicon = this.wrap.createChild(
43187 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });
43189 this.addicon.on('click', function(e) {
43190 this.fireEvent('add', this);
43193 if (typeof(this.events.edit.listeners) != 'undefined') {
43195 this.editicon = this.wrap.createChild(
43196 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });
43197 if (this.addicon) {
43198 this.editicon.setStyle('margin-left', '40px');
43200 this.editicon.on('click', function(e) {
43202 // we fire even if inothing is selected..
43203 this.fireEvent('edit', this, this.lastData );
43213 initEvents : function(){
43214 Roo.form.ComboBox.superclass.initEvents.call(this);
43216 this.keyNav = new Roo.KeyNav(this.el, {
43217 "up" : function(e){
43218 this.inKeyMode = true;
43222 "down" : function(e){
43223 if(!this.isExpanded()){
43224 this.onTriggerClick();
43226 this.inKeyMode = true;
43231 "enter" : function(e){
43232 this.onViewClick();
43236 "esc" : function(e){
43240 "tab" : function(e){
43241 this.onViewClick(false);
43242 this.fireEvent("specialkey", this, e);
43248 doRelay : function(foo, bar, hname){
43249 if(hname == 'down' || this.scope.isExpanded()){
43250 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
43257 this.queryDelay = Math.max(this.queryDelay || 10,
43258 this.mode == 'local' ? 10 : 250);
43259 this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
43260 if(this.typeAhead){
43261 this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
43263 if(this.editable !== false){
43264 this.el.on("keyup", this.onKeyUp, this);
43266 if(this.forceSelection){
43267 this.on('blur', this.doForce, this);
43271 onDestroy : function(){
43273 this.view.setStore(null);
43274 this.view.el.removeAllListeners();
43275 this.view.el.remove();
43276 this.view.purgeListeners();
43279 this.list.destroy();
43282 this.store.un('beforeload', this.onBeforeLoad, this);
43283 this.store.un('load', this.onLoad, this);
43284 this.store.un('loadexception', this.onLoadException, this);
43286 Roo.form.ComboBox.superclass.onDestroy.call(this);
43290 fireKey : function(e){
43291 if(e.isNavKeyPress() && !this.list.isVisible()){
43292 this.fireEvent("specialkey", this, e);
43297 onResize: function(w, h){
43298 Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
43300 if(typeof w != 'number'){
43301 // we do not handle it!?!?
43304 var tw = this.trigger.getWidth();
43305 tw += this.addicon ? this.addicon.getWidth() : 0;
43306 tw += this.editicon ? this.editicon.getWidth() : 0;
43308 this.el.setWidth( this.adjustWidth('input', x));
43310 this.trigger.setStyle('left', x+'px');
43312 if(this.list && this.listWidth === undefined){
43313 var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
43314 this.list.setWidth(lw);
43315 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
43323 * Allow or prevent the user from directly editing the field text. If false is passed,
43324 * the user will only be able to select from the items defined in the dropdown list. This method
43325 * is the runtime equivalent of setting the 'editable' config option at config time.
43326 * @param {Boolean} value True to allow the user to directly edit the field text
43328 setEditable : function(value){
43329 if(value == this.editable){
43332 this.editable = value;
43334 this.el.dom.setAttribute('readOnly', true);
43335 this.el.on('mousedown', this.onTriggerClick, this);
43336 this.el.addClass('x-combo-noedit');
43338 this.el.dom.setAttribute('readOnly', false);
43339 this.el.un('mousedown', this.onTriggerClick, this);
43340 this.el.removeClass('x-combo-noedit');
43345 onBeforeLoad : function(){
43346 if(!this.hasFocus){
43349 this.innerList.update(this.loadingText ?
43350 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
43351 this.restrictHeight();
43352 this.selectedIndex = -1;
43356 onLoad : function(){
43357 if(!this.hasFocus){
43360 if(this.store.getCount() > 0){
43362 this.restrictHeight();
43363 if(this.lastQuery == this.allQuery){
43365 this.el.dom.select();
43367 if(!this.selectByValue(this.value, true)){
43368 this.select(0, true);
43372 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
43373 this.taTask.delay(this.typeAheadDelay);
43377 this.onEmptyResults();
43382 onLoadException : function()
43385 Roo.log(this.store.reader.jsonData);
43386 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
43387 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
43393 onTypeAhead : function(){
43394 if(this.store.getCount() > 0){
43395 var r = this.store.getAt(0);
43396 var newValue = r.data[this.displayField];
43397 var len = newValue.length;
43398 var selStart = this.getRawValue().length;
43399 if(selStart != len){
43400 this.setRawValue(newValue);
43401 this.selectText(selStart, newValue.length);
43407 onSelect : function(record, index){
43408 if(this.fireEvent('beforeselect', this, record, index) !== false){
43409 this.setFromData(index > -1 ? record.data : false);
43411 this.fireEvent('select', this, record, index);
43416 * Returns the currently selected field value or empty string if no value is set.
43417 * @return {String} value The selected value
43419 getValue : function(){
43420 if(this.valueField){
43421 return typeof this.value != 'undefined' ? this.value : '';
43423 return Roo.form.ComboBox.superclass.getValue.call(this);
43427 * Clears any text/value currently set in the field
43429 clearValue : function(){
43430 if(this.hiddenField){
43431 this.hiddenField.value = '';
43434 this.setRawValue('');
43435 this.lastSelectionText = '';
43440 * Sets the specified value into the field. If the value finds a match, the corresponding record text
43441 * will be displayed in the field. If the value does not match the data value of an existing item,
43442 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
43443 * Otherwise the field will be blank (although the value will still be set).
43444 * @param {String} value The value to match
43446 setValue : function(v){
43448 if(this.valueField){
43449 var r = this.findRecord(this.valueField, v);
43451 text = r.data[this.displayField];
43452 }else if(this.valueNotFoundText !== undefined){
43453 text = this.valueNotFoundText;
43456 this.lastSelectionText = text;
43457 if(this.hiddenField){
43458 this.hiddenField.value = v;
43460 Roo.form.ComboBox.superclass.setValue.call(this, text);
43464 * @property {Object} the last set data for the element
43469 * Sets the value of the field based on a object which is related to the record format for the store.
43470 * @param {Object} value the value to set as. or false on reset?
43472 setFromData : function(o){
43473 var dv = ''; // display value
43474 var vv = ''; // value value..
43476 if (this.displayField) {
43477 dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
43479 // this is an error condition!!!
43480 Roo.log('no displayField value set for '+ (this.name ? this.name : this.id));
43483 if(this.valueField){
43484 vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
43486 if(this.hiddenField){
43487 this.hiddenField.value = vv;
43489 this.lastSelectionText = dv;
43490 Roo.form.ComboBox.superclass.setValue.call(this, dv);
43494 // no hidden field.. - we store the value in 'value', but still display
43495 // display field!!!!
43496 this.lastSelectionText = dv;
43497 Roo.form.ComboBox.superclass.setValue.call(this, dv);
43503 reset : function(){
43504 // overridden so that last data is reset..
43505 this.setValue(this.resetValue);
43506 this.originalValue = this.getValue();
43507 this.clearInvalid();
43508 this.lastData = false;
43510 this.view.clearSelections();
43514 findRecord : function(prop, value){
43516 if(this.store.getCount() > 0){
43517 this.store.each(function(r){
43518 if(r.data[prop] == value){
43528 getName: function()
43530 // returns hidden if it's set..
43531 if (!this.rendered) {return ''};
43532 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
43536 onViewMove : function(e, t){
43537 this.inKeyMode = false;
43541 onViewOver : function(e, t){
43542 if(this.inKeyMode){ // prevent key nav and mouse over conflicts
43545 var item = this.view.findItemFromChild(t);
43547 var index = this.view.indexOf(item);
43548 this.select(index, false);
43553 onViewClick : function(doFocus)
43555 var index = this.view.getSelectedIndexes()[0];
43556 var r = this.store.getAt(index);
43558 this.onSelect(r, index);
43560 if(doFocus !== false && !this.blockFocus){
43566 restrictHeight : function(){
43567 this.innerList.dom.style.height = '';
43568 var inner = this.innerList.dom;
43569 var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
43570 this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
43571 this.list.beginUpdate();
43572 this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
43573 this.list.alignTo(this.el, this.listAlign);
43574 this.list.endUpdate();
43578 onEmptyResults : function(){
43583 * Returns true if the dropdown list is expanded, else false.
43585 isExpanded : function(){
43586 return this.list.isVisible();
43590 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
43591 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
43592 * @param {String} value The data value of the item to select
43593 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
43594 * selected item if it is not currently in view (defaults to true)
43595 * @return {Boolean} True if the value matched an item in the list, else false
43597 selectByValue : function(v, scrollIntoView){
43598 if(v !== undefined && v !== null){
43599 var r = this.findRecord(this.valueField || this.displayField, v);
43601 this.select(this.store.indexOf(r), scrollIntoView);
43609 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
43610 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
43611 * @param {Number} index The zero-based index of the list item to select
43612 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
43613 * selected item if it is not currently in view (defaults to true)
43615 select : function(index, scrollIntoView){
43616 this.selectedIndex = index;
43617 this.view.select(index);
43618 if(scrollIntoView !== false){
43619 var el = this.view.getNode(index);
43621 this.innerList.scrollChildIntoView(el, false);
43627 selectNext : function(){
43628 var ct = this.store.getCount();
43630 if(this.selectedIndex == -1){
43632 }else if(this.selectedIndex < ct-1){
43633 this.select(this.selectedIndex+1);
43639 selectPrev : function(){
43640 var ct = this.store.getCount();
43642 if(this.selectedIndex == -1){
43644 }else if(this.selectedIndex != 0){
43645 this.select(this.selectedIndex-1);
43651 onKeyUp : function(e){
43652 if(this.editable !== false && !e.isSpecialKey()){
43653 this.lastKey = e.getKey();
43654 this.dqTask.delay(this.queryDelay);
43659 validateBlur : function(){
43660 return !this.list || !this.list.isVisible();
43664 initQuery : function(){
43665 this.doQuery(this.getRawValue());
43669 doForce : function(){
43670 if(this.el.dom.value.length > 0){
43671 this.el.dom.value =
43672 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
43678 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
43679 * query allowing the query action to be canceled if needed.
43680 * @param {String} query The SQL query to execute
43681 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
43682 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
43683 * saved in the current store (defaults to false)
43685 doQuery : function(q, forceAll){
43686 if(q === undefined || q === null){
43691 forceAll: forceAll,
43695 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
43699 forceAll = qe.forceAll;
43700 if(forceAll === true || (q.length >= this.minChars)){
43701 if(this.lastQuery != q || this.alwaysQuery){
43702 this.lastQuery = q;
43703 if(this.mode == 'local'){
43704 this.selectedIndex = -1;
43706 this.store.clearFilter();
43708 this.store.filter(this.displayField, q);
43712 this.store.baseParams[this.queryParam] = q;
43714 params: this.getParams(q)
43719 this.selectedIndex = -1;
43726 getParams : function(q){
43728 //p[this.queryParam] = q;
43731 p.limit = this.pageSize;
43737 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
43739 collapse : function(){
43740 if(!this.isExpanded()){
43744 Roo.get(document).un('mousedown', this.collapseIf, this);
43745 Roo.get(document).un('mousewheel', this.collapseIf, this);
43746 if (!this.editable) {
43747 Roo.get(document).un('keydown', this.listKeyPress, this);
43749 this.fireEvent('collapse', this);
43753 collapseIf : function(e){
43754 if(!e.within(this.wrap) && !e.within(this.list)){
43760 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
43762 expand : function(){
43763 if(this.isExpanded() || !this.hasFocus){
43766 this.list.alignTo(this.el, this.listAlign);
43768 Roo.get(document).on('mousedown', this.collapseIf, this);
43769 Roo.get(document).on('mousewheel', this.collapseIf, this);
43770 if (!this.editable) {
43771 Roo.get(document).on('keydown', this.listKeyPress, this);
43774 this.fireEvent('expand', this);
43778 // Implements the default empty TriggerField.onTriggerClick function
43779 onTriggerClick : function(){
43783 if(this.isExpanded()){
43785 if (!this.blockFocus) {
43790 this.hasFocus = true;
43791 if(this.triggerAction == 'all') {
43792 this.doQuery(this.allQuery, true);
43794 this.doQuery(this.getRawValue());
43796 if (!this.blockFocus) {
43801 listKeyPress : function(e)
43803 //Roo.log('listkeypress');
43804 // scroll to first matching element based on key pres..
43805 if (e.isSpecialKey()) {
43808 var k = String.fromCharCode(e.getKey()).toUpperCase();
43811 var csel = this.view.getSelectedNodes();
43812 var cselitem = false;
43814 var ix = this.view.indexOf(csel[0]);
43815 cselitem = this.store.getAt(ix);
43816 if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
43822 this.store.each(function(v) {
43824 // start at existing selection.
43825 if (cselitem.id == v.id) {
43831 if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
43832 match = this.store.indexOf(v);
43837 if (match === false) {
43838 return true; // no more action?
43841 this.view.select(match);
43842 var sn = Roo.get(this.view.getSelectedNodes()[0]);
43843 sn.scrollIntoView(sn.dom.parentNode, false);
43847 * @cfg {Boolean} grow
43851 * @cfg {Number} growMin
43855 * @cfg {Number} growMax
43863 * Copyright(c) 2010-2012, Roo J Solutions Limited
43870 * @class Roo.form.ComboBoxArray
43871 * @extends Roo.form.TextField
43872 * A facebook style adder... for lists of email / people / countries etc...
43873 * pick multiple items from a combo box, and shows each one.
43875 * Fred [x] Brian [x] [Pick another |v]
43878 * For this to work: it needs various extra information
43879 * - normal combo problay has
43881 * + displayField, valueField
43883 * For our purpose...
43886 * If we change from 'extends' to wrapping...
43893 * Create a new ComboBoxArray.
43894 * @param {Object} config Configuration options
43898 Roo.form.ComboBoxArray = function(config)
43902 * @event beforeremove
43903 * Fires before remove the value from the list
43904 * @param {Roo.form.ComboBoxArray} _self This combo box array
43905 * @param {Roo.form.ComboBoxArray.Item} item removed item
43907 'beforeremove' : true,
43910 * Fires when remove the value from the list
43911 * @param {Roo.form.ComboBoxArray} _self This combo box array
43912 * @param {Roo.form.ComboBoxArray.Item} item removed item
43919 Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
43921 this.items = new Roo.util.MixedCollection(false);
43923 // construct the child combo...
43933 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
43936 * @cfg {Roo.form.ComboBox} combo [required] The combo box that is wrapped
43941 // behavies liek a hiddne field
43942 inputType: 'hidden',
43944 * @cfg {Number} width The width of the box that displays the selected element
43951 * @cfg {String} name The name of the visable items on this form (eg. titles not ids)
43955 * @cfg {String} hiddenName The hidden name of the field, often contains an comma seperated list of names
43957 hiddenName : false,
43959 * @cfg {String} seperator The value seperator normally ','
43963 // private the array of items that are displayed..
43965 // private - the hidden field el.
43967 // private - the filed el..
43970 //validateValue : function() { return true; }, // all values are ok!
43971 //onAddClick: function() { },
43973 onRender : function(ct, position)
43976 // create the standard hidden element
43977 //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
43980 // give fake names to child combo;
43981 this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
43982 this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
43984 this.combo = Roo.factory(this.combo, Roo.form);
43985 this.combo.onRender(ct, position);
43986 if (typeof(this.combo.width) != 'undefined') {
43987 this.combo.onResize(this.combo.width,0);
43990 this.combo.initEvents();
43992 // assigned so form know we need to do this..
43993 this.store = this.combo.store;
43994 this.valueField = this.combo.valueField;
43995 this.displayField = this.combo.displayField ;
43998 this.combo.wrap.addClass('x-cbarray-grp');
44000 var cbwrap = this.combo.wrap.createChild(
44001 {tag: 'div', cls: 'x-cbarray-cb'},
44006 this.hiddenEl = this.combo.wrap.createChild({
44007 tag: 'input', type:'hidden' , name: this.hiddenName, value : ''
44009 this.el = this.combo.wrap.createChild({
44010 tag: 'input', type:'hidden' , name: this.name, value : ''
44012 // this.el.dom.removeAttribute("name");
44015 this.outerWrap = this.combo.wrap;
44016 this.wrap = cbwrap;
44018 this.outerWrap.setWidth(this.width);
44019 this.outerWrap.dom.removeChild(this.el.dom);
44021 this.wrap.dom.appendChild(this.el.dom);
44022 this.outerWrap.dom.removeChild(this.combo.trigger.dom);
44023 this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
44025 this.combo.trigger.setStyle('position','relative');
44026 this.combo.trigger.setStyle('left', '0px');
44027 this.combo.trigger.setStyle('top', '2px');
44029 this.combo.el.setStyle('vertical-align', 'text-bottom');
44031 //this.trigger.setStyle('vertical-align', 'top');
44033 // this should use the code from combo really... on('add' ....)
44037 this.adder = this.outerWrap.createChild(
44038 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});
44040 this.adder.on('click', function(e) {
44041 _t.fireEvent('adderclick', this, e);
44045 //this.adder.on('click', this.onAddClick, _t);
44048 this.combo.on('select', function(cb, rec, ix) {
44049 this.addItem(rec.data);
44052 cb.el.dom.value = '';
44053 //cb.lastData = rec.data;
44062 getName: function()
44064 // returns hidden if it's set..
44065 if (!this.rendered) {return ''};
44066 return this.hiddenName ? this.hiddenName : this.name;
44071 onResize: function(w, h){
44074 // not sure if this is needed..
44075 //this.combo.onResize(w,h);
44077 if(typeof w != 'number'){
44078 // we do not handle it!?!?
44081 var tw = this.combo.trigger.getWidth();
44082 tw += this.addicon ? this.addicon.getWidth() : 0;
44083 tw += this.editicon ? this.editicon.getWidth() : 0;
44085 this.combo.el.setWidth( this.combo.adjustWidth('input', x));
44087 this.combo.trigger.setStyle('left', '0px');
44089 if(this.list && this.listWidth === undefined){
44090 var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
44091 this.list.setWidth(lw);
44092 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
44099 addItem: function(rec)
44101 var valueField = this.combo.valueField;
44102 var displayField = this.combo.displayField;
44104 if (this.items.indexOfKey(rec[valueField]) > -1) {
44105 //console.log("GOT " + rec.data.id);
44109 var x = new Roo.form.ComboBoxArray.Item({
44110 //id : rec[this.idField],
44112 displayField : displayField ,
44113 tipField : displayField ,
44117 this.items.add(rec[valueField],x);
44118 // add it before the element..
44119 this.updateHiddenEl();
44120 x.render(this.outerWrap, this.wrap.dom);
44121 // add the image handler..
44124 updateHiddenEl : function()
44127 if (!this.hiddenEl) {
44131 var idField = this.combo.valueField;
44133 this.items.each(function(f) {
44134 ar.push(f.data[idField]);
44136 this.hiddenEl.dom.value = ar.join(this.seperator);
44142 this.items.clear();
44144 Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
44148 this.el.dom.value = '';
44149 if (this.hiddenEl) {
44150 this.hiddenEl.dom.value = '';
44154 getValue: function()
44156 return this.hiddenEl ? this.hiddenEl.dom.value : '';
44158 setValue: function(v) // not a valid action - must use addItems..
44163 if (this.store.isLocal && (typeof(v) == 'string')) {
44164 // then we can use the store to find the values..
44165 // comma seperated at present.. this needs to allow JSON based encoding..
44166 this.hiddenEl.value = v;
44168 Roo.each(v.split(this.seperator), function(k) {
44169 Roo.log("CHECK " + this.valueField + ',' + k);
44170 var li = this.store.query(this.valueField, k);
44175 add[this.valueField] = k;
44176 add[this.displayField] = li.item(0).data[this.displayField];
44182 if (typeof(v) == 'object' ) {
44183 // then let's assume it's an array of objects..
44184 Roo.each(v, function(l) {
44186 if (typeof(l) == 'string') {
44188 add[this.valueField] = l;
44189 add[this.displayField] = l
44198 setFromData: function(v)
44200 // this recieves an object, if setValues is called.
44202 this.el.dom.value = v[this.displayField];
44203 this.hiddenEl.dom.value = v[this.valueField];
44204 if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
44207 var kv = v[this.valueField];
44208 var dv = v[this.displayField];
44209 kv = typeof(kv) != 'string' ? '' : kv;
44210 dv = typeof(dv) != 'string' ? '' : dv;
44213 var keys = kv.split(this.seperator);
44214 var display = dv.split(this.seperator);
44215 for (var i = 0 ; i < keys.length; i++) {
44217 add[this.valueField] = keys[i];
44218 add[this.displayField] = display[i];
44226 * Validates the combox array value
44227 * @return {Boolean} True if the value is valid, else false
44229 validate : function(){
44230 if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
44231 this.clearInvalid();
44237 validateValue : function(value){
44238 return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
44246 isDirty : function() {
44247 if(this.disabled) {
44252 var d = Roo.decode(String(this.originalValue));
44254 return String(this.getValue()) !== String(this.originalValue);
44257 var originalValue = [];
44259 for (var i = 0; i < d.length; i++){
44260 originalValue.push(d[i][this.valueField]);
44263 return String(this.getValue()) !== String(originalValue.join(this.seperator));
44272 * @class Roo.form.ComboBoxArray.Item
44273 * @extends Roo.BoxComponent
44274 * A selected item in the list
44275 * Fred [x] Brian [x] [Pick another |v]
44278 * Create a new item.
44279 * @param {Object} config Configuration options
44282 Roo.form.ComboBoxArray.Item = function(config) {
44283 config.id = Roo.id();
44284 Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
44287 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
44290 displayField : false,
44294 defaultAutoCreate : {
44296 cls: 'x-cbarray-item',
44303 src : Roo.BLANK_IMAGE_URL ,
44311 onRender : function(ct, position)
44313 Roo.form.Field.superclass.onRender.call(this, ct, position);
44316 var cfg = this.getAutoCreate();
44317 this.el = ct.createChild(cfg, position);
44320 this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
44322 this.el.child('div').dom.innerHTML = this.cb.renderer ?
44323 this.cb.renderer(this.data) :
44324 String.format('{0}',this.data[this.displayField]);
44327 this.el.child('div').dom.setAttribute('qtip',
44328 String.format('{0}',this.data[this.tipField])
44331 this.el.child('img').on('click', this.remove, this);
44335 remove : function()
44337 if(this.cb.disabled){
44341 if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
44342 this.cb.items.remove(this);
44343 this.el.child('img').un('click', this.remove, this);
44345 this.cb.updateHiddenEl();
44347 this.cb.fireEvent('remove', this.cb, this);
44352 * RooJS Library 1.1.1
44353 * Copyright(c) 2008-2011 Alan Knowles
44360 * @class Roo.form.ComboNested
44361 * @extends Roo.form.ComboBox
44362 * A combobox for that allows selection of nested items in a list,
44377 * Create a new ComboNested
44378 * @param {Object} config Configuration options
44380 Roo.form.ComboNested = function(config){
44381 Roo.form.ComboCheck.superclass.constructor.call(this, config);
44382 // should verify some data...
44384 // hiddenName = required..
44385 // displayField = required
44386 // valudField == required
44387 var req= [ 'hiddenName', 'displayField', 'valueField' ];
44389 Roo.each(req, function(e) {
44390 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
44391 throw "Roo.form.ComboNested : missing value for: " + e;
44398 Roo.extend(Roo.form.ComboNested, Roo.form.ComboBox, {
44401 * @config {Number} max Number of columns to show
44406 list : null, // the outermost div..
44407 innerLists : null, // the
44411 loadingChildren : false,
44413 onRender : function(ct, position)
44415 Roo.form.ComboBox.superclass.onRender.call(this, ct, position); // skip parent call - got to above..
44417 if(this.hiddenName){
44418 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
44420 this.hiddenField.value =
44421 this.hiddenValue !== undefined ? this.hiddenValue :
44422 this.value !== undefined ? this.value : '';
44424 // prevent input submission
44425 this.el.dom.removeAttribute('name');
44431 this.el.dom.setAttribute('autocomplete', 'off');
44434 var cls = 'x-combo-list';
44436 this.list = new Roo.Layer({
44437 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
44440 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
44441 this.list.setWidth(lw);
44442 this.list.swallowEvent('mousewheel');
44443 this.assetHeight = 0;
44446 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
44447 this.assetHeight += this.header.getHeight();
44449 this.innerLists = [];
44452 for (var i =0 ; i < this.maxColumns; i++) {
44453 this.onRenderList( cls, i);
44456 // always needs footer, as we are going to have an 'OK' button.
44457 this.footer = this.list.createChild({cls:cls+'-ft'});
44458 this.pageTb = new Roo.Toolbar(this.footer);
44463 handler: function()
44469 if ( this.allowBlank && !this.disableClear) {
44471 this.pageTb.add(new Roo.Toolbar.Fill(), {
44472 cls: 'x-btn-icon x-btn-clear',
44474 handler: function()
44477 _this.clearValue();
44478 _this.onSelect(false, -1);
44483 this.assetHeight += this.footer.getHeight();
44487 onRenderList : function ( cls, i)
44490 var lw = Math.floor(
44491 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
44494 this.list.setWidth(lw); // default to '1'
44496 var il = this.innerLists[i] = this.list.createChild({cls:cls+'-inner'});
44497 //il.on('mouseover', this.onViewOver, this, { list: i });
44498 //il.on('mousemove', this.onViewMove, this, { list: i });
44500 il.setStyle({ 'overflow-x' : 'hidden'});
44503 this.tpl = new Roo.Template({
44504 html : '<div class="'+cls+'-item '+cls+'-item-{cn:this.isEmpty}">{' + this.displayField + '}</div>',
44505 isEmpty: function (value, allValues) {
44507 var dl = typeof(value.data) != 'undefined' ? value.data.length : value.length; ///json is a nested response..
44508 return dl ? 'has-children' : 'no-children'
44513 var store = this.store;
44515 store = new Roo.data.SimpleStore({
44516 //fields : this.store.reader.meta.fields,
44517 reader : this.store.reader,
44521 this.stores[i] = store;
44523 var view = this.views[i] = new Roo.View(
44529 selectedClass: this.selectedClass
44532 view.getEl().setWidth(lw);
44533 view.getEl().setStyle({
44534 position: i < 1 ? 'relative' : 'absolute',
44536 left: (i * lw ) + 'px',
44537 display : i > 0 ? 'none' : 'block'
44539 view.on('selectionchange', this.onSelectChange.createDelegate(this, {list : i }, true));
44540 view.on('dblclick', this.onDoubleClick.createDelegate(this, {list : i }, true));
44541 //view.on('click', this.onViewClick, this, { list : i });
44543 store.on('beforeload', this.onBeforeLoad, this);
44544 store.on('load', this.onLoad, this, { list : i});
44545 store.on('loadexception', this.onLoadException, this);
44547 // hide the other vies..
44553 restrictHeight : function()
44556 Roo.each(this.innerLists, function(il,i) {
44557 var el = this.views[i].getEl();
44558 el.dom.style.height = '';
44559 var inner = el.dom;
44560 var h = Math.max(il.clientHeight, il.offsetHeight, il.scrollHeight);
44561 // only adjust heights on other ones..
44562 mh = Math.max(h, mh);
44565 el.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
44566 il.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
44573 this.list.beginUpdate();
44574 this.list.setHeight(mh+this.list.getFrameWidth('tb')+this.assetHeight);
44575 this.list.alignTo(this.el, this.listAlign);
44576 this.list.endUpdate();
44581 // -- store handlers..
44583 onBeforeLoad : function()
44585 if(!this.hasFocus){
44588 this.innerLists[0].update(this.loadingText ?
44589 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
44590 this.restrictHeight();
44591 this.selectedIndex = -1;
44594 onLoad : function(a,b,c,d)
44596 if (!this.loadingChildren) {
44597 // then we are loading the top level. - hide the children
44598 for (var i = 1;i < this.views.length; i++) {
44599 this.views[i].getEl().setStyle({ display : 'none' });
44601 var lw = Math.floor(
44602 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
44605 this.list.setWidth(lw); // default to '1'
44609 if(!this.hasFocus){
44613 if(this.store.getCount() > 0) {
44615 this.restrictHeight();
44617 this.onEmptyResults();
44620 if (!this.loadingChildren) {
44621 this.selectActive();
44624 this.stores[1].loadData([]);
44625 this.stores[2].loadData([]);
44634 onLoadException : function()
44637 Roo.log(this.store.reader.jsonData);
44638 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
44639 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
44644 // no cleaning of leading spaces on blur here.
44645 cleanLeadingSpace : function(e) { },
44648 onSelectChange : function (view, sels, opts )
44650 var ix = view.getSelectedIndexes();
44652 if (opts.list > this.maxColumns - 2) {
44653 if (view.store.getCount()< 1) {
44654 this.views[opts.list ].getEl().setStyle({ display : 'none' });
44658 // used to clear ?? but if we are loading unselected
44659 this.setFromData(view.store.getAt(ix[0]).data);
44668 // this get's fired when trigger opens..
44669 // this.setFromData({});
44670 var str = this.stores[opts.list+1];
44671 str.data.clear(); // removeall wihtout the fire events..
44675 var rec = view.store.getAt(ix[0]);
44677 this.setFromData(rec.data);
44678 this.fireEvent('select', this, rec, ix[0]);
44680 var lw = Math.floor(
44682 (this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')
44683 ) / this.maxColumns
44685 this.loadingChildren = true;
44686 this.stores[opts.list+1].loadDataFromChildren( rec );
44687 this.loadingChildren = false;
44688 var dl = this.stores[opts.list+1]. getTotalCount();
44690 this.views[opts.list+1].getEl().setHeight( this.innerLists[0].getHeight());
44692 this.views[opts.list+1].getEl().setStyle({ display : dl ? 'block' : 'none' });
44693 for (var i = opts.list+2; i < this.views.length;i++) {
44694 this.views[i].getEl().setStyle({ display : 'none' });
44697 this.innerLists[opts.list+1].setHeight( this.innerLists[0].getHeight());
44698 this.list.setWidth(lw * (opts.list + (dl ? 2 : 1)));
44700 if (this.isLoading) {
44701 // this.selectActive(opts.list);
44709 onDoubleClick : function()
44711 this.collapse(); //??
44719 recordToStack : function(store, prop, value, stack)
44721 var cstore = new Roo.data.SimpleStore({
44722 //fields : this.store.reader.meta.fields, // we need array reader.. for
44723 reader : this.store.reader,
44727 var record = false;
44729 if(store.getCount() < 1){
44732 store.each(function(r){
44733 if(r.data[prop] == value){
44738 if (r.data.cn && r.data.cn.length) {
44739 cstore.loadDataFromChildren( r);
44740 var cret = _this.recordToStack(cstore, prop, value, stack);
44741 if (cret !== false) {
44750 if (record == false) {
44753 stack.unshift(srec);
44758 * find the stack of stores that match our value.
44763 selectActive : function ()
44765 // if store is not loaded, then we will need to wait for that to happen first.
44767 this.recordToStack(this.store, this.valueField, this.getValue(), stack);
44768 for (var i = 0; i < stack.length; i++ ) {
44769 this.views[i].select(stack[i].store.indexOf(stack[i]), false, false );
44781 * Ext JS Library 1.1.1
44782 * Copyright(c) 2006-2007, Ext JS, LLC.
44784 * Originally Released Under LGPL - original licence link has changed is not relivant.
44787 * <script type="text/javascript">
44790 * @class Roo.form.Checkbox
44791 * @extends Roo.form.Field
44792 * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
44794 * Creates a new Checkbox
44795 * @param {Object} config Configuration options
44797 Roo.form.Checkbox = function(config){
44798 Roo.form.Checkbox.superclass.constructor.call(this, config);
44802 * Fires when the checkbox is checked or unchecked.
44803 * @param {Roo.form.Checkbox} this This checkbox
44804 * @param {Boolean} checked The new checked value
44810 Roo.extend(Roo.form.Checkbox, Roo.form.Field, {
44812 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
44814 focusClass : undefined,
44816 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
44818 fieldClass: "x-form-field",
44820 * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
44824 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
44825 * {tag: "input", type: "checkbox", autocomplete: "off"})
44827 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
44829 * @cfg {String} boxLabel The text that appears beside the checkbox
44833 * @cfg {String} inputValue The value that should go into the generated input element's value attribute
44837 * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
44839 valueOff: '0', // value when not checked..
44841 actionMode : 'viewEl',
44844 itemCls : 'x-menu-check-item x-form-item',
44845 groupClass : 'x-menu-group-item',
44846 inputType : 'hidden',
44849 inSetChecked: false, // check that we are not calling self...
44851 inputElement: false, // real input element?
44852 basedOn: false, // ????
44854 isFormField: true, // not sure where this is needed!!!!
44856 onResize : function(){
44857 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
44858 if(!this.boxLabel){
44859 this.el.alignTo(this.wrap, 'c-c');
44863 initEvents : function(){
44864 Roo.form.Checkbox.superclass.initEvents.call(this);
44865 this.el.on("click", this.onClick, this);
44866 this.el.on("change", this.onClick, this);
44870 getResizeEl : function(){
44874 getPositionEl : function(){
44879 onRender : function(ct, position){
44880 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
44882 if(this.inputValue !== undefined){
44883 this.el.dom.value = this.inputValue;
44886 //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
44887 this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
44888 var viewEl = this.wrap.createChild({
44889 tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
44890 this.viewEl = viewEl;
44891 this.wrap.on('click', this.onClick, this);
44893 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
44894 this.el.on('propertychange', this.setFromHidden, this); //ie
44899 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
44900 // viewEl.on('click', this.onClick, this);
44902 //if(this.checked){
44903 this.setChecked(this.checked);
44905 //this.checked = this.el.dom;
44911 initValue : Roo.emptyFn,
44914 * Returns the checked state of the checkbox.
44915 * @return {Boolean} True if checked, else false
44917 getValue : function(){
44919 return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
44921 return this.valueOff;
44926 onClick : function(){
44927 if (this.disabled) {
44930 this.setChecked(!this.checked);
44932 //if(this.el.dom.checked != this.checked){
44933 // this.setValue(this.el.dom.checked);
44938 * Sets the checked state of the checkbox.
44939 * On is always based on a string comparison between inputValue and the param.
44940 * @param {Boolean/String} value - the value to set
44941 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
44943 setValue : function(v,suppressEvent){
44946 //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
44947 //if(this.el && this.el.dom){
44948 // this.el.dom.checked = this.checked;
44949 // this.el.dom.defaultChecked = this.checked;
44951 this.setChecked(String(v) === String(this.inputValue), suppressEvent);
44952 //this.fireEvent("check", this, this.checked);
44955 setChecked : function(state,suppressEvent)
44957 if (this.inSetChecked) {
44958 this.checked = state;
44964 this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
44966 this.checked = state;
44967 if(suppressEvent !== true){
44968 this.fireEvent('check', this, state);
44970 this.inSetChecked = true;
44971 this.el.dom.value = state ? this.inputValue : this.valueOff;
44972 this.inSetChecked = false;
44975 // handle setting of hidden value by some other method!!?!?
44976 setFromHidden: function()
44981 //console.log("SET FROM HIDDEN");
44982 //alert('setFrom hidden');
44983 this.setValue(this.el.dom.value);
44986 onDestroy : function()
44989 Roo.get(this.viewEl).remove();
44992 Roo.form.Checkbox.superclass.onDestroy.call(this);
44995 setBoxLabel : function(str)
44997 this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
45002 * Ext JS Library 1.1.1
45003 * Copyright(c) 2006-2007, Ext JS, LLC.
45005 * Originally Released Under LGPL - original licence link has changed is not relivant.
45008 * <script type="text/javascript">
45012 * @class Roo.form.Radio
45013 * @extends Roo.form.Checkbox
45014 * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
45015 * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
45017 * Creates a new Radio
45018 * @param {Object} config Configuration options
45020 Roo.form.Radio = function(){
45021 Roo.form.Radio.superclass.constructor.apply(this, arguments);
45023 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
45024 inputType: 'radio',
45027 * If this radio is part of a group, it will return the selected value
45030 getGroupValue : function(){
45031 return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
45035 onRender : function(ct, position){
45036 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
45038 if(this.inputValue !== undefined){
45039 this.el.dom.value = this.inputValue;
45042 this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
45043 //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
45044 //var viewEl = this.wrap.createChild({
45045 // tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
45046 //this.viewEl = viewEl;
45047 //this.wrap.on('click', this.onClick, this);
45049 //this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
45050 //this.el.on('propertychange', this.setFromHidden, this); //ie
45055 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
45056 // viewEl.on('click', this.onClick, this);
45059 this.el.dom.checked = 'checked' ;
45065 });Roo.rtf = {}; // namespace
45066 Roo.rtf.Hex = function(hex)
45070 Roo.rtf.Paragraph = function(opts)
45072 this.content = []; ///??? is that used?
45073 };Roo.rtf.Span = function(opts)
45075 this.value = opts.value;
45078 Roo.rtf.Group = function(parent)
45080 // we dont want to acutally store parent - it will make debug a nightmare..
45088 Roo.rtf.Group.prototype = {
45092 addContent : function(node) {
45093 // could set styles...
45094 this.content.push(node);
45096 addChild : function(cn)
45100 // only for images really...
45101 toDataURL : function()
45103 var mimetype = false;
45105 case this.content.filter(function(a) { return a.value == 'pngblip' } ).length > 0:
45106 mimetype = "image/png";
45108 case this.content.filter(function(a) { return a.value == 'jpegblip' } ).length > 0:
45109 mimetype = "image/jpeg";
45112 return 'about:blank'; // ?? error?
45116 var hexstring = this.content[this.content.length-1].value;
45118 return 'data:' + mimetype + ';base64,' + btoa(hexstring.match(/\w{2}/g).map(function(a) {
45119 return String.fromCharCode(parseInt(a, 16));
45124 // this looks like it's normally the {rtf{ .... }}
45125 Roo.rtf.Document = function()
45127 // we dont want to acutally store parent - it will make debug a nightmare..
45133 Roo.extend(Roo.rtf.Document, Roo.rtf.Group, {
45134 addChild : function(cn)
45138 case 'rtlch': // most content seems to be inside this??
45141 this.rtlch.push(cn);
45144 this[cn.type] = cn;
45149 getElementsByType : function(type)
45152 this._getElementsByType(type, ret, this.cn, 'rtf');
45155 _getElementsByType : function (type, ret, search_array, path)
45157 search_array.forEach(function(n,i) {
45158 if (n.type == type) {
45159 n.path = path + '/' + n.type + ':' + i;
45162 if (n.cn.length > 0) {
45163 this._getElementsByType(type, ret, n.cn, path + '/' + n.type+':'+i);
45170 Roo.rtf.Ctrl = function(opts)
45172 this.value = opts.value;
45173 this.param = opts.param;
45178 * based on this https://github.com/iarna/rtf-parser
45179 * it's really only designed to extract pict from pasted RTF
45183 * var images = new Roo.rtf.Parser().parse(a_string).filter(function(g) { return g.type == 'pict'; });
45192 Roo.rtf.Parser = function(text) {
45193 //super({objectMode: true})
45195 this.parserState = this.parseText;
45197 // these are for interpeter...
45199 ///this.parserState = this.parseTop
45200 this.groupStack = [];
45201 this.hexStore = [];
45204 this.groups = []; // where we put the return.
45206 for (var ii = 0; ii < text.length; ++ii) {
45209 if (text[ii] === '\n') {
45215 this.parserState(text[ii]);
45221 Roo.rtf.Parser.prototype = {
45222 text : '', // string being parsed..
45224 controlWordParam : '',
45228 groupStack : false,
45233 row : 1, // reportin?
45237 push : function (el)
45239 var m = 'cmd'+ el.type;
45240 if (typeof(this[m]) == 'undefined') {
45241 Roo.log('invalid cmd:' + el.type);
45247 flushHexStore : function()
45249 if (this.hexStore.length < 1) {
45252 var hexstr = this.hexStore.map(
45257 this.group.addContent( new Roo.rtf.Hex( hexstr ));
45260 this.hexStore.splice(0)
45264 cmdgroupstart : function()
45266 this.flushHexStore();
45268 this.groupStack.push(this.group);
45271 if (this.doc === false) {
45272 this.group = this.doc = new Roo.rtf.Document();
45276 this.group = new Roo.rtf.Group(this.group);
45278 cmdignorable : function()
45280 this.flushHexStore();
45281 this.group.ignorable = true;
45283 cmdendparagraph : function()
45285 this.flushHexStore();
45286 this.group.addContent(new Roo.rtf.Paragraph());
45288 cmdgroupend : function ()
45290 this.flushHexStore();
45291 var endingGroup = this.group;
45294 this.group = this.groupStack.pop();
45296 this.group.addChild(endingGroup);
45301 var doc = this.group || this.doc;
45302 //if (endingGroup instanceof FontTable) {
45303 // doc.fonts = endingGroup.table
45304 //} else if (endingGroup instanceof ColorTable) {
45305 // doc.colors = endingGroup.table
45306 //} else if (endingGroup !== this.doc && !endingGroup.get('ignorable')) {
45307 if (endingGroup.ignorable === false) {
45309 this.groups.push(endingGroup);
45310 // Roo.log( endingGroup );
45312 //Roo.each(endingGroup.content, function(item)) {
45313 // doc.addContent(item);
45315 //process.emit('debug', 'GROUP END', endingGroup.type, endingGroup.get('ignorable'))
45318 cmdtext : function (cmd)
45320 this.flushHexStore();
45321 if (!this.group) { // an RTF fragment, missing the {\rtf1 header
45322 //this.group = this.doc
45324 this.group.addContent(new Roo.rtf.Span(cmd));
45326 cmdcontrolword : function (cmd)
45328 this.flushHexStore();
45329 if (!this.group.type) {
45330 this.group.type = cmd.value;
45333 this.group.addContent(new Roo.rtf.Ctrl(cmd));
45334 // we actually don't care about ctrl words...
45337 var method = 'ctrl$' + cmd.value.replace(/-(.)/g, (_, char) => char.toUpperCase())
45338 if (this[method]) {
45339 this[method](cmd.param)
45341 if (!this.group.get('ignorable')) process.emit('debug', method, cmd.param)
45345 cmdhexchar : function(cmd) {
45346 this.hexStore.push(cmd);
45348 cmderror : function(cmd) {
45349 throw new Exception (cmd.value);
45354 if (this.text !== '\u0000') this.emitText()
45360 parseText : function(c)
45363 this.parserState = this.parseEscapes;
45364 } else if (c === '{') {
45365 this.emitStartGroup();
45366 } else if (c === '}') {
45367 this.emitEndGroup();
45368 } else if (c === '\x0A' || c === '\x0D') {
45369 // cr/lf are noise chars
45375 parseEscapes: function (c)
45377 if (c === '\\' || c === '{' || c === '}') {
45379 this.parserState = this.parseText;
45381 this.parserState = this.parseControlSymbol;
45382 this.parseControlSymbol(c);
45385 parseControlSymbol: function(c)
45388 this.text += '\u00a0'; // nbsp
45389 this.parserState = this.parseText
45390 } else if (c === '-') {
45391 this.text += '\u00ad'; // soft hyphen
45392 } else if (c === '_') {
45393 this.text += '\u2011'; // non-breaking hyphen
45394 } else if (c === '*') {
45395 this.emitIgnorable();
45396 this.parserState = this.parseText;
45397 } else if (c === "'") {
45398 this.parserState = this.parseHexChar;
45399 } else if (c === '|') { // formula cacter
45400 this.emitFormula();
45401 this.parserState = this.parseText;
45402 } else if (c === ':') { // subentry in an index entry
45403 this.emitIndexSubEntry();
45404 this.parserState = this.parseText;
45405 } else if (c === '\x0a') {
45406 this.emitEndParagraph();
45407 this.parserState = this.parseText;
45408 } else if (c === '\x0d') {
45409 this.emitEndParagraph();
45410 this.parserState = this.parseText;
45412 this.parserState = this.parseControlWord;
45413 this.parseControlWord(c);
45416 parseHexChar: function (c)
45418 if (/^[A-Fa-f0-9]$/.test(c)) {
45420 if (this.hexChar.length >= 2) {
45421 this.emitHexChar();
45422 this.parserState = this.parseText;
45426 this.emitError("Invalid character \"" + c + "\" in hex literal.");
45427 this.parserState = this.parseText;
45430 parseControlWord : function(c)
45433 this.emitControlWord();
45434 this.parserState = this.parseText;
45435 } else if (/^[-\d]$/.test(c)) {
45436 this.parserState = this.parseControlWordParam;
45437 this.controlWordParam += c;
45438 } else if (/^[A-Za-z]$/.test(c)) {
45439 this.controlWord += c;
45441 this.emitControlWord();
45442 this.parserState = this.parseText;
45446 parseControlWordParam : function (c) {
45447 if (/^\d$/.test(c)) {
45448 this.controlWordParam += c;
45449 } else if (c === ' ') {
45450 this.emitControlWord();
45451 this.parserState = this.parseText;
45453 this.emitControlWord();
45454 this.parserState = this.parseText;
45462 emitText : function () {
45463 if (this.text === '') {
45475 emitControlWord : function ()
45478 if (this.controlWord === '') {
45479 this.emitError('empty control word');
45482 type: 'controlword',
45483 value: this.controlWord,
45484 param: this.controlWordParam !== '' && Number(this.controlWordParam),
45490 this.controlWord = '';
45491 this.controlWordParam = '';
45493 emitStartGroup : function ()
45497 type: 'groupstart',
45503 emitEndGroup : function ()
45513 emitIgnorable : function ()
45523 emitHexChar : function ()
45528 value: this.hexChar,
45535 emitError : function (message)
45543 char: this.cpos //,
45544 //stack: new Error().stack
45547 emitEndParagraph : function () {
45550 type: 'endparagraph',
45558 Roo.htmleditor = {};
45561 * @class Roo.htmleditor.Filter
45562 * Base Class for filtering htmleditor stuff. - do not use this directly - extend it.
45563 * @cfg {DomElement} node The node to iterate and filter
45564 * @cfg {boolean|String|Array} tag Tags to replace
45566 * Create a new Filter.
45567 * @param {Object} config Configuration options
45572 Roo.htmleditor.Filter = function(cfg) {
45573 Roo.apply(this.cfg);
45574 // this does not actually call walk as it's really just a abstract class
45578 Roo.htmleditor.Filter.prototype = {
45584 // overrride to do replace comments.
45585 replaceComment : false,
45587 // overrride to do replace or do stuff with tags..
45588 replaceTag : false,
45590 walk : function(dom)
45592 Roo.each( Array.from(dom.childNodes), function( e ) {
45595 case e.nodeType == 8 && this.replaceComment !== false: // comment
45596 this.replaceComment(e);
45599 case e.nodeType != 1: //not a node.
45602 case this.tag === true: // everything
45603 case typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1: // array and it matches.
45604 case typeof(this.tag) == 'string' && this.tag == e.tagName: // array and it matches.
45605 if (this.replaceTag && false === this.replaceTag(e)) {
45608 if (e.hasChildNodes()) {
45613 default: // tags .. that do not match.
45614 if (e.hasChildNodes()) {
45625 * @class Roo.htmleditor.FilterAttributes
45626 * clean attributes and styles including http:// etc.. in attribute
45628 * Run a new Attribute Filter
45629 * @param {Object} config Configuration options
45631 Roo.htmleditor.FilterAttributes = function(cfg)
45633 Roo.apply(this, cfg);
45634 this.attrib_black = this.attrib_black || [];
45635 this.attrib_white = this.attrib_white || [];
45637 this.attrib_clean = this.attrib_clean || [];
45638 this.style_white = this.style_white || [];
45639 this.style_black = this.style_black || [];
45640 this.walk(cfg.node);
45643 Roo.extend(Roo.htmleditor.FilterAttributes, Roo.htmleditor.Filter,
45645 tag: true, // all tags
45647 attrib_black : false, // array
45648 attrib_clean : false,
45649 attrib_white : false,
45651 style_white : false,
45652 style_black : false,
45655 replaceTag : function(node)
45657 if (!node.attributes || !node.attributes.length) {
45661 for (var i = node.attributes.length-1; i > -1 ; i--) {
45662 var a = node.attributes[i];
45664 if (this.attrib_white.length && this.attrib_white.indexOf(a.name.toLowerCase()) < 0) {
45665 node.removeAttribute(a.name);
45671 if (a.name.toLowerCase().substr(0,2)=='on') {
45672 node.removeAttribute(a.name);
45677 if (this.attrib_black.indexOf(a.name.toLowerCase()) > -1) {
45678 node.removeAttribute(a.name);
45681 if (this.attrib_clean.indexOf(a.name.toLowerCase()) > -1) {
45682 this.cleanAttr(node,a.name,a.value); // fixme..
45685 if (a.name == 'style') {
45686 this.cleanStyle(node,a.name,a.value);
45689 /// clean up MS crap..
45690 // tecnically this should be a list of valid class'es..
45693 if (a.name == 'class') {
45694 if (a.value.match(/^Mso/)) {
45695 node.removeAttribute('class');
45698 if (a.value.match(/^body$/)) {
45699 node.removeAttribute('class');
45709 return true; // clean children
45712 cleanAttr: function(node, n,v)
45715 if (v.match(/^\./) || v.match(/^\//)) {
45718 if (v.match(/^(http|https):\/\//)
45719 || v.match(/^mailto:/)
45720 || v.match(/^ftp:/)
45721 || v.match(/^data:/)
45725 if (v.match(/^#/)) {
45728 if (v.match(/^\{/)) { // allow template editing.
45731 // Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
45732 node.removeAttribute(n);
45735 cleanStyle : function(node, n,v)
45737 if (v.match(/expression/)) { //XSS?? should we even bother..
45738 node.removeAttribute(n);
45742 var parts = v.split(/;/);
45745 Roo.each(parts, function(p) {
45746 p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
45750 var l = p.split(':').shift().replace(/\s+/g,'');
45751 l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
45753 if ( this.style_black.length && (this.style_black.indexOf(l) > -1 || this.style_black.indexOf(l.toLowerCase()) > -1)) {
45757 // only allow 'c whitelisted system attributes'
45758 if ( this.style_white.length && style_white.indexOf(l) < 0 && style_white.indexOf(l.toLowerCase()) < 0 ) {
45766 if (clean.length) {
45767 node.setAttribute(n, clean.join(';'));
45769 node.removeAttribute(n);
45778 * @class Roo.htmleditor.FilterBlack
45779 * remove blacklisted elements.
45781 * Run a new Blacklisted Filter
45782 * @param {Object} config Configuration options
45785 Roo.htmleditor.FilterBlack = function(cfg)
45787 Roo.apply(this, cfg);
45788 this.walk(cfg.node);
45791 Roo.extend(Roo.htmleditor.FilterBlack, Roo.htmleditor.Filter,
45793 tag : true, // all elements.
45795 replaceTag : function(n)
45797 n.parentNode.removeChild(n);
45801 * @class Roo.htmleditor.FilterComment
45804 * Run a new Comments Filter
45805 * @param {Object} config Configuration options
45807 Roo.htmleditor.FilterComment = function(cfg)
45809 this.walk(cfg.node);
45812 Roo.extend(Roo.htmleditor.FilterComment, Roo.htmleditor.Filter,
45815 replaceComment : function(n)
45817 n.parentNode.removeChild(n);
45820 * @class Roo.htmleditor.FilterKeepChildren
45821 * remove tags but keep children
45823 * Run a new Keep Children Filter
45824 * @param {Object} config Configuration options
45827 Roo.htmleditor.FilterKeepChildren = function(cfg)
45829 Roo.apply(this, cfg);
45830 if (this.tag === false) {
45831 return; // dont walk.. (you can use this to use this just to do a child removal on a single tag )
45833 this.walk(cfg.node);
45836 Roo.extend(Roo.htmleditor.FilterKeepChildren, Roo.htmleditor.FilterBlack,
45840 replaceTag : function(node)
45842 // walk children...
45844 var ar = Array.from(node.childNodes);
45846 for (var i = 0; i < ar.length; i++) {
45847 if (ar[i].nodeType == 1) {
45849 (typeof(this.tag) == 'object' && this.tag.indexOf(ar[i].tagName) > -1)
45850 || // array and it matches
45851 (typeof(this.tag) == 'string' && this.tag == ar[i].tagName)
45853 this.replaceTag(ar[i]); // child is blacklisted as well...
45858 ar = Array.from(node.childNodes);
45859 for (var i = 0; i < ar.length; i++) {
45861 node.removeChild(ar[i]);
45862 // what if we need to walk these???
45863 node.parentNode.insertBefore(ar[i], node);
45864 if (this.tag !== false) {
45869 node.parentNode.removeChild(node);
45870 return false; // don't walk children
45875 * @class Roo.htmleditor.FilterParagraph
45876 * paragraphs cause a nightmare for shared content - this filter is designed to be called ? at various points when editing
45877 * like on 'push' to remove the <p> tags and replace them with line breaks.
45879 * Run a new Paragraph Filter
45880 * @param {Object} config Configuration options
45883 Roo.htmleditor.FilterParagraph = function(cfg)
45885 // no need to apply config.
45886 this.walk(cfg.node);
45889 Roo.extend(Roo.htmleditor.FilterParagraph, Roo.htmleditor.Filter,
45896 replaceTag : function(node)
45899 if (node.childNodes.length == 1 &&
45900 node.childNodes[0].nodeType == 3 &&
45901 node.childNodes[0].textContent.trim().length < 1
45903 // remove and replace with '<BR>';
45904 node.parentNode.replaceChild(node.ownerDocument.createElement('BR'),node);
45905 return false; // no need to walk..
45907 var ar = Array.from(node.childNodes);
45908 for (var i = 0; i < ar.length; i++) {
45909 node.removeChild(ar[i]);
45910 // what if we need to walk these???
45911 node.parentNode.insertBefore(ar[i], node);
45913 // now what about this?
45917 node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
45918 node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
45919 node.parentNode.removeChild(node);
45926 * @class Roo.htmleditor.FilterSpan
45927 * filter span's with no attributes out..
45929 * Run a new Span Filter
45930 * @param {Object} config Configuration options
45933 Roo.htmleditor.FilterSpan = function(cfg)
45935 // no need to apply config.
45936 this.walk(cfg.node);
45939 Roo.extend(Roo.htmleditor.FilterSpan, Roo.htmleditor.FilterKeepChildren,
45945 replaceTag : function(node)
45947 if (node.attributes && node.attributes.length > 0) {
45948 return true; // walk if there are any.
45950 Roo.htmleditor.FilterKeepChildren.prototype.replaceTag.call(this, node);
45956 * @class Roo.htmleditor.FilterTableWidth
45957 try and remove table width data - as that frequently messes up other stuff.
45959 * was cleanTableWidths.
45961 * Quite often pasting from word etc.. results in tables with column and widths.
45962 * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
45965 * Run a new Table Filter
45966 * @param {Object} config Configuration options
45969 Roo.htmleditor.FilterTableWidth = function(cfg)
45971 // no need to apply config.
45972 this.tag = ['TABLE', 'TD', 'TR', 'TH', 'THEAD', 'TBODY' ];
45973 this.walk(cfg.node);
45976 Roo.extend(Roo.htmleditor.FilterTableWidth, Roo.htmleditor.Filter,
45981 replaceTag: function(node) {
45985 if (node.hasAttribute('width')) {
45986 node.removeAttribute('width');
45990 if (node.hasAttribute("style")) {
45993 var styles = node.getAttribute("style").split(";");
45995 Roo.each(styles, function(s) {
45996 if (!s.match(/:/)) {
45999 var kv = s.split(":");
46000 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
46003 // what ever is left... we allow.
46006 node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
46007 if (!nstyle.length) {
46008 node.removeAttribute('style');
46012 return true; // continue doing children..
46015 * @class Roo.htmleditor.FilterWord
46016 * try and clean up all the mess that Word generates.
46018 * This is the 'nice version' - see 'Heavy' that white lists a very short list of elements, and multi-filters
46021 * Run a new Span Filter
46022 * @param {Object} config Configuration options
46025 Roo.htmleditor.FilterWord = function(cfg)
46027 // no need to apply config.
46028 this.walk(cfg.node);
46031 Roo.extend(Roo.htmleditor.FilterWord, Roo.htmleditor.Filter,
46037 * Clean up MS wordisms...
46039 replaceTag : function(node)
46042 // no idea what this does - span with text, replaceds with just text.
46044 node.nodeName == 'SPAN' &&
46045 !node.hasAttributes() &&
46046 node.childNodes.length == 1 &&
46047 node.firstChild.nodeName == "#text"
46049 var textNode = node.firstChild;
46050 node.removeChild(textNode);
46051 if (node.getAttribute('lang') != 'zh-CN') { // do not space pad on chinese characters..
46052 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
46054 node.parentNode.insertBefore(textNode, node);
46055 if (node.getAttribute('lang') != 'zh-CN') { // do not space pad on chinese characters..
46056 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
46059 node.parentNode.removeChild(node);
46060 return false; // dont do chidren - we have remove our node - so no need to do chdhilren?
46065 if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
46066 node.parentNode.removeChild(node);
46067 return false; // dont do chidlren
46069 //Roo.log(node.tagName);
46070 // remove - but keep children..
46071 if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
46072 //Roo.log('-- removed');
46073 while (node.childNodes.length) {
46074 var cn = node.childNodes[0];
46075 node.removeChild(cn);
46076 node.parentNode.insertBefore(cn, node);
46077 // move node to parent - and clean it..
46078 this.replaceTag(cn);
46080 node.parentNode.removeChild(node);
46081 /// no need to iterate chidlren = it's got none..
46082 //this.iterateChildren(node, this.cleanWord);
46083 return false; // no need to iterate children.
46086 if (node.className.length) {
46088 var cn = node.className.split(/\W+/);
46090 Roo.each(cn, function(cls) {
46091 if (cls.match(/Mso[a-zA-Z]+/)) {
46096 node.className = cna.length ? cna.join(' ') : '';
46098 node.removeAttribute("class");
46102 if (node.hasAttribute("lang")) {
46103 node.removeAttribute("lang");
46106 if (node.hasAttribute("style")) {
46108 var styles = node.getAttribute("style").split(";");
46110 Roo.each(styles, function(s) {
46111 if (!s.match(/:/)) {
46114 var kv = s.split(":");
46115 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
46118 // what ever is left... we allow.
46121 node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
46122 if (!nstyle.length) {
46123 node.removeAttribute('style');
46126 return true; // do children
46133 * @class Roo.htmleditor.FilterStyleToTag
46134 * part of the word stuff... - certain 'styles' should be converted to tags.
46136 * font-weight: bold -> bold
46137 * ?? super / subscrit etc..
46140 * Run a new style to tag filter.
46141 * @param {Object} config Configuration options
46143 Roo.htmleditor.FilterStyleToTag = function(cfg)
46147 B : [ 'fontWeight' , 'bold'],
46148 I : [ 'fontStyle' , 'italic'],
46149 //pre : [ 'font-style' , 'italic'],
46150 // h1.. h6 ?? font-size?
46151 SUP : [ 'verticalAlign' , 'super' ],
46152 SUB : [ 'verticalAlign' , 'sub' ]
46157 Roo.apply(this, cfg);
46160 this.walk(cfg.node);
46167 Roo.extend(Roo.htmleditor.FilterStyleToTag, Roo.htmleditor.Filter,
46169 tag: true, // all tags
46174 replaceTag : function(node)
46178 if (node.getAttribute("style") === null) {
46182 for (var k in this.tags) {
46183 if (node.style[this.tags[k][0]] == this.tags[k][1]) {
46185 node.style.removeProperty(this.tags[k][0]);
46188 if (!inject.length) {
46191 var cn = Array.from(node.childNodes);
46193 Roo.each(inject, function(t) {
46194 var nc = node.ownerDocument.createElement(t);
46195 nn.appendChild(nc);
46198 for(var i = 0;i < cn.length;cn++) {
46199 node.removeChild(cn[i]);
46200 nn.appendChild(cn[i]);
46202 return true /// iterate thru
46206 * @class Roo.htmleditor.FilterLongBr
46207 * BR/BR/BR - keep a maximum of 2...
46209 * Run a new Long BR Filter
46210 * @param {Object} config Configuration options
46213 Roo.htmleditor.FilterLongBr = function(cfg)
46215 // no need to apply config.
46216 this.walk(cfg.node);
46219 Roo.extend(Roo.htmleditor.FilterLongBr, Roo.htmleditor.Filter,
46226 replaceTag : function(node)
46229 var ps = node.nextSibling;
46230 while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
46231 ps = ps.nextSibling;
46234 if (!ps && [ 'TD', 'TH', 'LI', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(node.parentNode.tagName) > -1) {
46235 node.parentNode.removeChild(node); // remove last BR inside one fo these tags
46239 if (!ps || ps.nodeType != 1) {
46243 if (!ps || ps.tagName != 'BR') {
46252 if (!node.previousSibling) {
46255 var ps = node.previousSibling;
46257 while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
46258 ps = ps.previousSibling;
46260 if (!ps || ps.nodeType != 1) {
46263 // if header or BR before.. then it's a candidate for removal.. - as we only want '2' of these..
46264 if (!ps || [ 'BR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(ps.tagName) < 0) {
46268 node.parentNode.removeChild(node); // remove me...
46270 return false; // no need to do children
46277 * @class Roo.htmleditor.FilterBlock
46278 * removes id / data-block and contenteditable that are associated with blocks
46279 * usage should be done on a cloned copy of the dom
46281 * Run a new Attribute Filter { node : xxxx }}
46282 * @param {Object} config Configuration options
46284 Roo.htmleditor.FilterBlock = function(cfg)
46286 Roo.apply(this, cfg);
46287 var qa = cfg.node.querySelectorAll;
46288 this.removeAttributes('data-block');
46289 this.removeAttributes('contenteditable');
46290 this.removeAttributes('id');
46294 Roo.apply(Roo.htmleditor.FilterBlock.prototype,
46296 node: true, // all tags
46299 removeAttributes : function(attr)
46301 var ar = this.node.querySelectorAll('*[' + attr + ']');
46302 for (var i =0;i<ar.length;i++) {
46303 ar[i].removeAttribute(attr);
46312 * This is based loosely on tinymce
46313 * @class Roo.htmleditor.TidySerializer
46314 * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
46316 * @method Serializer
46317 * @param {Object} settings Name/value settings object.
46321 Roo.htmleditor.TidySerializer = function(settings)
46323 Roo.apply(this, settings);
46325 this.writer = new Roo.htmleditor.TidyWriter(settings);
46330 Roo.htmleditor.TidySerializer.prototype = {
46333 * @param {boolean} inner do the inner of the node.
46340 * Serializes the specified node into a string.
46343 * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('<p>text</p>'));
46344 * @method serialize
46345 * @param {DomElement} node Node instance to serialize.
46346 * @return {String} String with HTML based on DOM tree.
46348 serialize : function(node) {
46350 // = settings.validate;
46351 var writer = this.writer;
46355 3: function(node) {
46357 writer.text(node.nodeValue, node);
46360 8: function(node) {
46361 writer.comment(node.nodeValue);
46363 // Processing instruction
46364 7: function(node) {
46365 writer.pi(node.name, node.nodeValue);
46368 10: function(node) {
46369 writer.doctype(node.nodeValue);
46372 4: function(node) {
46373 writer.cdata(node.nodeValue);
46375 // Document fragment
46376 11: function(node) {
46377 node = node.firstChild;
46383 node = node.nextSibling
46388 1 != node.nodeType || this.inner ? this.handlers[11](node) : this.walk(node);
46389 return writer.getContent();
46392 walk: function(node)
46394 var attrName, attrValue, sortedAttrs, i, l, elementRule,
46395 handler = this.handlers[node.nodeType];
46402 var name = node.nodeName;
46403 var isEmpty = node.childNodes.length < 1;
46405 var writer = this.writer;
46406 var attrs = node.attributes;
46409 writer.start(node.nodeName, attrs, isEmpty, node);
46413 node = node.firstChild;
46420 node = node.nextSibling;
46426 // Serialize element and treat all non elements as fragments
46431 * This is based loosely on tinymce
46432 * @class Roo.htmleditor.TidyWriter
46433 * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
46436 * - not tested much with 'PRE' formated elements.
46442 Roo.htmleditor.TidyWriter = function(settings)
46445 // indent, indentBefore, indentAfter, encode, htmlOutput, html = [];
46446 Roo.apply(this, settings);
46450 this.encode = Roo.htmleditor.TidyEntities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
46453 Roo.htmleditor.TidyWriter.prototype = {
46460 // part of state...
46464 last_inline : false,
46469 * Writes the a start element such as <p id="a">.
46472 * @param {String} name Name of the element.
46473 * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
46474 * @param {Boolean} empty Optional empty state if the tag should end like <br />.
46476 start: function(name, attrs, empty, node)
46478 var i, l, attr, value;
46480 // there are some situations where adding line break && indentation will not work. will not work.
46481 // <span / b / i ... formating?
46483 var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
46484 var in_pre = this.in_pre || Roo.htmleditor.TidyWriter.whitespace_elements.indexOf(name) > -1;
46486 var is_short = empty ? Roo.htmleditor.TidyWriter.shortend_elements.indexOf(name) > -1 : false;
46488 var add_lb = name == 'BR' ? false : in_inline;
46490 if (!add_lb && !this.in_pre && this.lastElementEndsWS()) {
46494 var indentstr = this.indentstr;
46496 // e_inline = elements that can be inline, but still allow \n before and after?
46497 // only 'BR' ??? any others?
46499 // ADD LINE BEFORE tage
46500 if (!this.in_pre) {
46503 if (name == 'BR') {
46505 } else if (this.lastElementEndsWS()) {
46508 // otherwise - no new line. (and dont indent.)
46519 this.html.push(indentstr + '<', name.toLowerCase());
46522 for (i = 0, l = attrs.length; i < l; i++) {
46524 this.html.push(' ', attr.name, '="', this.encode(attr.value, true), '"');
46530 this.html[this.html.length] = '/>';
46532 this.html[this.html.length] = '></' + name.toLowerCase() + '>';
46534 var e_inline = name == 'BR' ? false : this.in_inline;
46536 if (!e_inline && !this.in_pre) {
46543 this.html[this.html.length] = '>';
46545 // there is a special situation, where we need to turn on in_inline - if any of the imediate chidlren are one of these.
46547 if (!in_inline && !in_pre) {
46548 var cn = node.firstChild;
46550 if (Roo.htmleditor.TidyWriter.inline_elements.indexOf(cn.nodeName) > -1) {
46554 cn = cn.nextSibling;
46562 indentstr : in_pre ? '' : (this.indentstr + this.indent),
46564 in_inline : in_inline
46566 // add a line after if we are not in a
46568 if (!in_inline && !in_pre) {
46577 lastElementEndsWS : function()
46579 var value = this.html.length > 0 ? this.html[this.html.length-1] : false;
46580 if (value === false) {
46583 return value.match(/\s+$/);
46588 * Writes the a end element such as </p>.
46591 * @param {String} name Name of the element.
46593 end: function(name) {
46596 var indentstr = '';
46597 var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
46599 if (!this.in_pre && !in_inline) {
46601 indentstr = this.indentstr;
46603 this.html.push(indentstr + '</', name.toLowerCase(), '>');
46604 this.last_inline = in_inline;
46606 // pop the indent state..
46609 * Writes a text node.
46611 * In pre - we should not mess with the contents.
46615 * @param {String} text String to write out.
46616 * @param {Boolean} raw Optional raw state if true the contents wont get encoded.
46618 text: function(text, node)
46620 // if not in whitespace critical
46621 if (text.length < 1) {
46625 this.html[this.html.length] = text;
46629 if (this.in_inline) {
46630 text = text.replace(/\s+/g,' '); // all white space inc line breaks to a slingle' '
46632 text = text.replace(/\s+/,' '); // all white space to single white space
46635 // if next tag is '<BR>', then we can trim right..
46636 if (node.nextSibling &&
46637 node.nextSibling.nodeType == 1 &&
46638 node.nextSibling.nodeName == 'BR' )
46640 text = text.replace(/\s+$/g,'');
46642 // if previous tag was a BR, we can also trim..
46643 if (node.previousSibling &&
46644 node.previousSibling.nodeType == 1 &&
46645 node.previousSibling.nodeName == 'BR' )
46647 text = this.indentstr + text.replace(/^\s+/g,'');
46649 if (text.match(/\n/)) {
46650 text = text.replace(
46651 /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
46653 // remoeve the last whitespace / line break.
46654 text = text.replace(/\n\s+$/,'');
46656 // repace long lines
46660 this.html[this.html.length] = text;
46663 // see if previous element was a inline element.
46664 var indentstr = this.indentstr;
46666 text = text.replace(/\s+/g," "); // all whitespace into single white space.
46668 // should trim left?
46669 if (node.previousSibling &&
46670 node.previousSibling.nodeType == 1 &&
46671 Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.previousSibling.nodeName) > -1)
46677 text = text.replace(/^\s+/,''); // trim left
46680 // should trim right?
46681 if (node.nextSibling &&
46682 node.nextSibling.nodeType == 1 &&
46683 Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.nextSibling.nodeName) > -1)
46688 text = text.replace(/\s+$/,''); // trim right
46695 if (text.length < 1) {
46698 if (!text.match(/\n/)) {
46699 this.html.push(indentstr + text);
46703 text = this.indentstr + text.replace(
46704 /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
46706 // remoeve the last whitespace / line break.
46707 text = text.replace(/\s+$/,'');
46709 this.html.push(text);
46711 // split and indent..
46716 * Writes a cdata node such as <![CDATA[data]]>.
46719 * @param {String} text String to write out inside the cdata.
46721 cdata: function(text) {
46722 this.html.push('<![CDATA[', text, ']]>');
46725 * Writes a comment node such as <!-- Comment -->.
46728 * @param {String} text String to write out inside the comment.
46730 comment: function(text) {
46731 this.html.push('<!--', text, '-->');
46734 * Writes a PI node such as <?xml attr="value" ?>.
46737 * @param {String} name Name of the pi.
46738 * @param {String} text String to write out inside the pi.
46740 pi: function(name, text) {
46741 text ? this.html.push('<?', name, ' ', this.encode(text), '?>') : this.html.push('<?', name, '?>');
46742 this.indent != '' && this.html.push('\n');
46745 * Writes a doctype node such as <!DOCTYPE data>.
46748 * @param {String} text String to write out inside the doctype.
46750 doctype: function(text) {
46751 this.html.push('<!DOCTYPE', text, '>', this.indent != '' ? '\n' : '');
46754 * Resets the internal buffer if one wants to reuse the writer.
46758 reset: function() {
46759 this.html.length = 0;
46768 * Returns the contents that got serialized.
46770 * @method getContent
46771 * @return {String} HTML contents that got written down.
46773 getContent: function() {
46774 return this.html.join('').replace(/\n$/, '');
46777 pushState : function(cfg)
46779 this.state.push(cfg);
46780 Roo.apply(this, cfg);
46783 popState : function()
46785 if (this.state.length < 1) {
46786 return; // nothing to push
46793 if (this.state.length > 0) {
46794 cfg = this.state[this.state.length-1];
46796 Roo.apply(this, cfg);
46799 addLine: function()
46801 if (this.html.length < 1) {
46806 var value = this.html[this.html.length - 1];
46807 if (value.length > 0 && '\n' !== value) {
46808 this.html.push('\n');
46813 //'pre script noscript style textarea video audio iframe object code'
46814 // shortended... 'area base basefont br col frame hr img input isindex link meta param embed source wbr track');
46818 Roo.htmleditor.TidyWriter.inline_elements = [
46819 'SPAN','STRONG','B','EM','I','FONT','STRIKE','U','VAR',
46820 'CITE','DFN','CODE','MARK','Q','SUP','SUB','SAMP'
46822 Roo.htmleditor.TidyWriter.shortend_elements = [
46823 'AREA','BASE','BASEFONT','BR','COL','FRAME','HR','IMG','INPUT',
46824 'ISINDEX','LINK','','META','PARAM','EMBED','SOURCE','WBR','TRACK'
46827 Roo.htmleditor.TidyWriter.whitespace_elements = [
46828 'PRE','SCRIPT','NOSCRIPT','STYLE','TEXTAREA','VIDEO','AUDIO','IFRAME','OBJECT','CODE'
46830 * This is based loosely on tinymce
46831 * @class Roo.htmleditor.TidyEntities
46833 * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
46835 * Not 100% sure this is actually used or needed.
46838 Roo.htmleditor.TidyEntities = {
46841 * initialize data..
46843 init : function (){
46845 this.namedEntities = this.buildEntitiesLookup(this.namedEntitiesData, 32);
46850 buildEntitiesLookup: function(items, radix) {
46851 var i, chr, entity, lookup = {};
46855 items = typeof(items) == 'string' ? items.split(',') : items;
46856 radix = radix || 10;
46857 // Build entities lookup table
46858 for (i = 0; i < items.length; i += 2) {
46859 chr = String.fromCharCode(parseInt(items[i], radix));
46860 // Only add non base entities
46861 if (!this.baseEntities[chr]) {
46862 entity = '&' + items[i + 1] + ';';
46863 lookup[chr] = entity;
46864 lookup[entity] = chr;
46903 // Needs to be escaped since the YUI compressor would otherwise break the code
46910 // Reverse lookup table for raw entities
46911 reverseEntities : {
46919 attrsCharsRegExp : /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
46920 textCharsRegExp : /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
46921 rawCharsRegExp : /[<>&\"\']/g,
46922 entityRegExp : /&#([a-z0-9]+);?|&([a-z0-9]+);/gi,
46923 namedEntities : false,
46924 namedEntitiesData : [
47425 * Encodes the specified string using raw entities. This means only the required XML base entities will be encoded.
47427 * @method encodeRaw
47428 * @param {String} text Text to encode.
47429 * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
47430 * @return {String} Entity encoded text.
47432 encodeRaw: function(text, attr)
47435 return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
47436 return t.baseEntities[chr] || chr;
47440 * Encoded the specified text with both the attributes and text entities. This function will produce larger text contents
47441 * since it doesn't know if the context is within a attribute or text node. This was added for compatibility
47442 * and is exposed as the DOMUtils.encode function.
47444 * @method encodeAllRaw
47445 * @param {String} text Text to encode.
47446 * @return {String} Entity encoded text.
47448 encodeAllRaw: function(text) {
47450 return ('' + text).replace(this.rawCharsRegExp, function(chr) {
47451 return t.baseEntities[chr] || chr;
47455 * Encodes the specified string using numeric entities. The core entities will be
47456 * encoded as named ones but all non lower ascii characters will be encoded into numeric entities.
47458 * @method encodeNumeric
47459 * @param {String} text Text to encode.
47460 * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
47461 * @return {String} Entity encoded text.
47463 encodeNumeric: function(text, attr) {
47465 return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
47466 // Multi byte sequence convert it to a single entity
47467 if (chr.length > 1) {
47468 return '&#' + (1024 * (chr.charCodeAt(0) - 55296) + (chr.charCodeAt(1) - 56320) + 65536) + ';';
47470 return t.baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
47474 * Encodes the specified string using named entities. The core entities will be encoded
47475 * as named ones but all non lower ascii characters will be encoded into named entities.
47477 * @method encodeNamed
47478 * @param {String} text Text to encode.
47479 * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
47480 * @param {Object} entities Optional parameter with entities to use.
47481 * @return {String} Entity encoded text.
47483 encodeNamed: function(text, attr, entities) {
47485 entities = entities || this.namedEntities;
47486 return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
47487 return t.baseEntities[chr] || entities[chr] || chr;
47491 * Returns an encode function based on the name(s) and it's optional entities.
47493 * @method getEncodeFunc
47494 * @param {String} name Comma separated list of encoders for example named,numeric.
47495 * @param {String} entities Optional parameter with entities to use instead of the built in set.
47496 * @return {function} Encode function to be used.
47498 getEncodeFunc: function(name, entities) {
47499 entities = this.buildEntitiesLookup(entities) || this.namedEntities;
47501 function encodeNamedAndNumeric(text, attr) {
47502 return text.replace(attr ? t.attrsCharsRegExp : t.textCharsRegExp, function(chr) {
47503 return t.baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr;
47507 function encodeCustomNamed(text, attr) {
47508 return t.encodeNamed(text, attr, entities);
47510 // Replace + with , to be compatible with previous TinyMCE versions
47511 name = this.makeMap(name.replace(/\+/g, ','));
47512 // Named and numeric encoder
47513 if (name.named && name.numeric) {
47514 return this.encodeNamedAndNumeric;
47520 return encodeCustomNamed;
47522 return this.encodeNamed;
47525 if (name.numeric) {
47526 return this.encodeNumeric;
47529 return this.encodeRaw;
47532 * Decodes the specified string, this will replace entities with raw UTF characters.
47535 * @param {String} text Text to entity decode.
47536 * @return {String} Entity decoded string.
47538 decode: function(text)
47541 return text.replace(this.entityRegExp, function(all, numeric) {
47543 numeric = 'x' === numeric.charAt(0).toLowerCase() ? parseInt(numeric.substr(1), 16) : parseInt(numeric, 10);
47544 // Support upper UTF
47545 if (numeric > 65535) {
47547 return String.fromCharCode(55296 + (numeric >> 10), 56320 + (1023 & numeric));
47549 return t.asciiMap[numeric] || String.fromCharCode(numeric);
47551 return t.reverseEntities[all] || t.namedEntities[all] || t.nativeDecode(all);
47554 nativeDecode : function (text) {
47557 makeMap : function (items, delim, map) {
47559 items = items || [];
47560 delim = delim || ',';
47561 if (typeof items == "string") {
47562 items = items.split(delim);
47567 map[items[i]] = {};
47575 Roo.htmleditor.TidyEntities.init();
47577 * @class Roo.htmleditor.KeyEnter
47578 * Handle Enter press..
47579 * @cfg {Roo.HtmlEditorCore} core the editor.
47581 * Create a new Filter.
47582 * @param {Object} config Configuration options
47589 Roo.htmleditor.KeyEnter = function(cfg) {
47590 Roo.apply(this, cfg);
47591 // this does not actually call walk as it's really just a abstract class
47593 Roo.get(this.core.doc.body).on('keypress', this.keypress, this);
47596 //Roo.htmleditor.KeyEnter.i = 0;
47599 Roo.htmleditor.KeyEnter.prototype = {
47603 keypress : function(e)
47605 if (e.charCode != 13 && e.charCode != 10) {
47606 Roo.log([e.charCode,e]);
47609 e.preventDefault();
47610 // https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
47611 var doc = this.core.doc;
47615 var sel = this.core.getSelection();
47616 var range = sel.getRangeAt(0);
47617 var n = range.commonAncestorContainer;
47618 var pc = range.closest([ 'ol', 'ul']);
47619 var pli = range.closest('li');
47620 if (!pc || e.ctrlKey) {
47621 sel.insertNode('br', 'after');
47623 this.core.undoManager.addEvent();
47624 this.core.fireEditorEvent(e);
47628 // deal with <li> insetion
47629 if (pli.innerText.trim() == '' &&
47630 pli.previousSibling &&
47631 pli.previousSibling.nodeName == 'LI' &&
47632 pli.previousSibling.innerText.trim() == '') {
47633 pli.parentNode.removeChild(pli.previousSibling);
47634 sel.cursorAfter(pc);
47635 this.core.undoManager.addEvent();
47636 this.core.fireEditorEvent(e);
47640 var li = doc.createElement('LI');
47641 li.innerHTML = ' ';
47642 if (!pli || !pli.firstSibling) {
47643 pc.appendChild(li);
47645 pli.parentNode.insertBefore(li, pli.firstSibling);
47647 sel.cursorText (li.firstChild);
47649 this.core.undoManager.addEvent();
47650 this.core.fireEditorEvent(e);
47662 * @class Roo.htmleditor.Block
47663 * Base class for html editor blocks - do not use it directly .. extend it..
47664 * @cfg {DomElement} node The node to apply stuff to.
47665 * @cfg {String} friendly_name the name that appears in the context bar about this block
47666 * @cfg {Object} Context menu - see Roo.form.HtmlEditor.ToolbarContext
47669 * Create a new Filter.
47670 * @param {Object} config Configuration options
47673 Roo.htmleditor.Block = function(cfg)
47675 // do nothing .. should not be called really.
47678 * factory method to get the block from an element (using cache if necessary)
47680 * @param {HtmlElement} the dom element
47682 Roo.htmleditor.Block.factory = function(node)
47684 var cc = Roo.htmleditor.Block.cache;
47685 var id = Roo.get(node).id;
47686 if (typeof(cc[id]) != 'undefined' && (!cc[id].node || cc[id].node.closest('body'))) {
47687 Roo.htmleditor.Block.cache[id].readElement(node);
47688 return Roo.htmleditor.Block.cache[id];
47690 var db = node.getAttribute('data-block');
47692 db = node.nodeName.toLowerCase().toUpperCaseFirst();
47694 var cls = Roo.htmleditor['Block' + db];
47695 if (typeof(cls) == 'undefined') {
47696 //Roo.log(node.getAttribute('data-block'));
47697 Roo.log("OOps missing block : " + 'Block' + db);
47700 Roo.htmleditor.Block.cache[id] = new cls({ node: node });
47701 return Roo.htmleditor.Block.cache[id]; /// should trigger update element
47705 * initalize all Elements from content that are 'blockable'
47707 * @param the body element
47709 Roo.htmleditor.Block.initAll = function(body, type)
47711 if (typeof(type) == 'undefined') {
47712 var ia = Roo.htmleditor.Block.initAll;
47718 Roo.each(Roo.get(body).query(type), function(e) {
47719 Roo.htmleditor.Block.factory(e);
47722 // question goes here... do we need to clear out this cache sometimes?
47723 // or show we make it relivant to the htmleditor.
47724 Roo.htmleditor.Block.cache = {};
47726 Roo.htmleditor.Block.prototype = {
47730 // used by context menu
47731 friendly_name : 'Based Block',
47733 // text for button to delete this element
47734 deleteTitle : false,
47738 * Update a node with values from this object
47739 * @param {DomElement} node
47741 updateElement : function(node)
47743 Roo.DomHelper.update(node === undefined ? this.node : node, this.toObject());
47746 * convert to plain HTML for calling insertAtCursor..
47748 toHTML : function()
47750 return Roo.DomHelper.markup(this.toObject());
47753 * used by readEleemnt to extract data from a node
47754 * may need improving as it's pretty basic
47756 * @param {DomElement} node
47757 * @param {String} tag - tag to find, eg. IMG ?? might be better to use DomQuery ?
47758 * @param {String} attribute (use html - for contents, or style for using next param as style)
47759 * @param {String} style the style property - eg. text-align
47761 getVal : function(node, tag, attr, style)
47764 if (tag !== true && n.tagName != tag.toUpperCase()) {
47765 // in theory we could do figure[3] << 3rd figure? or some more complex search..?
47766 // but kiss for now.
47767 n = node.getElementsByTagName(tag).item(0);
47772 if (attr == 'html') {
47773 return n.innerHTML;
47775 if (attr == 'style') {
47776 return n.style[style];
47779 return n.hasAttribute(attr) ? n.getAttribute(attr) : '';
47783 * create a DomHelper friendly object - for use with
47784 * Roo.DomHelper.markup / overwrite / etc..
47787 toObject : function()
47792 * Read a node that has a 'data-block' property - and extract the values from it.
47793 * @param {DomElement} node - the node
47795 readElement : function(node)
47806 * @class Roo.htmleditor.BlockFigure
47807 * Block that has an image and a figcaption
47808 * @cfg {String} image_src the url for the image
47809 * @cfg {String} align (left|right) alignment for the block default left
47810 * @cfg {String} caption the text to appear below (and in the alt tag)
47811 * @cfg {String} caption_display (block|none) display or not the caption
47812 * @cfg {String|number} image_width the width of the image number or %?
47813 * @cfg {String|number} image_height the height of the image number or %?
47816 * Create a new Filter.
47817 * @param {Object} config Configuration options
47820 Roo.htmleditor.BlockFigure = function(cfg)
47823 this.readElement(cfg.node);
47824 this.updateElement(cfg.node);
47826 Roo.apply(this, cfg);
47828 Roo.extend(Roo.htmleditor.BlockFigure, Roo.htmleditor.Block, {
47835 caption_display : 'block',
47841 // margin: '2%', not used
47843 text_align: 'left', // (left|right) alignment for the text caption default left. - not used at present
47846 // used by context menu
47847 friendly_name : 'Image with caption',
47848 deleteTitle : "Delete Image and Caption",
47850 contextMenu : function(toolbar)
47853 var block = function() {
47854 return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
47858 var rooui = typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
47860 var syncValue = toolbar.editorcore.syncValue;
47866 xtype : 'TextItem',
47868 xns : rooui.Toolbar //Boostrap?
47872 text: 'Change Image URL',
47875 click: function (btn, state)
47879 Roo.MessageBox.show({
47880 title : "Image Source URL",
47881 msg : "Enter the url for the image",
47882 buttons: Roo.MessageBox.OKCANCEL,
47883 fn: function(btn, val){
47890 toolbar.editorcore.onEditorEvent();
47894 //multiline: multiline,
47896 value : b.image_src
47900 xns : rooui.Toolbar
47905 text: 'Change Link URL',
47908 click: function (btn, state)
47912 Roo.MessageBox.show({
47913 title : "Link URL",
47914 msg : "Enter the url for the link - leave blank to have no link",
47915 buttons: Roo.MessageBox.OKCANCEL,
47916 fn: function(btn, val){
47923 toolbar.editorcore.onEditorEvent();
47927 //multiline: multiline,
47933 xns : rooui.Toolbar
47937 text: 'Show Video URL',
47940 click: function (btn, state)
47942 Roo.MessageBox.alert("Video URL",
47943 block().video_url == '' ? 'This image is not linked ot a video' :
47944 'The image is linked to: <a target="_new" href="' + block().video_url + '">' + block().video_url + '</a>');
47947 xns : rooui.Toolbar
47952 xtype : 'TextItem',
47954 xns : rooui.Toolbar //Boostrap?
47957 xtype : 'ComboBox',
47958 allowBlank : false,
47959 displayField : 'val',
47962 triggerAction : 'all',
47964 valueField : 'val',
47968 select : function (combo, r, index)
47970 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
47972 b.width = r.get('val');
47975 toolbar.editorcore.onEditorEvent();
47980 xtype : 'SimpleStore',
47991 xtype : 'TextItem',
47993 xns : rooui.Toolbar //Boostrap?
47996 xtype : 'ComboBox',
47997 allowBlank : false,
47998 displayField : 'val',
48001 triggerAction : 'all',
48003 valueField : 'val',
48007 select : function (combo, r, index)
48009 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
48011 b.align = r.get('val');
48014 toolbar.editorcore.onEditorEvent();
48019 xtype : 'SimpleStore',
48033 text: 'Hide Caption',
48034 name : 'caption_display',
48036 enableToggle : true,
48037 setValue : function(v) {
48038 this.toggle(v == 'block' ? false : true);
48041 toggle: function (btn, state)
48044 b.caption_display = b.caption_display == 'block' ? 'none' : 'block';
48045 this.setText(b.caption_display == 'block' ? "Hide Caption" : "Show Caption");
48048 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
48049 toolbar.editorcore.onEditorEvent();
48052 xns : rooui.Toolbar
48058 * create a DomHelper friendly object - for use with
48059 * Roo.DomHelper.markup / overwrite / etc..
48061 toObject : function()
48063 var d = document.createElement('div');
48064 d.innerHTML = this.caption;
48066 var m = this.width == '50%' && this.align == 'center' ? '0 auto' : 0;
48070 contenteditable : 'false',
48071 src : this.image_src,
48072 alt : d.innerText.replace(/\n/g, " ").replace(/\s+/g, ' ').trim(), // removeHTML and reduce spaces..
48075 'max-width': '100%',
48082 '<div class="{0}" width="420" height="315" src="{1}" frameborder="0" allowfullscreen>' +
48084 '<img class="{0}-thumbnail" src="{3}/Images/{4}/{5}#image-{4}" />' +
48089 if (this.href.length > 0) {
48093 contenteditable : 'true',
48101 if (this.video_url.length > 0) {
48106 allowfullscreen : true,
48107 width : 420, // these are for video tricks - that we replace the outer
48109 src : this.video_url,
48118 'data-block' : 'Figure',
48119 contenteditable : 'false',
48122 float : this.align ,
48123 'max-width': this.width,
48131 align : this.align,
48139 'text-align': 'left',
48140 'margin-top' : '16px',
48141 'font-size' : '16px',
48142 'line-height' : '24px',
48143 display : this.caption_display
48145 cls : this.cls.length > 0 ? (this.cls + '-thumbnail' ) : '',
48148 // we can not rely on yahoo syndication to use CSS elements - so have to use '<i>' to encase stuff.
48150 contenteditable : true,
48151 html : this.caption
48161 readElement : function(node)
48163 // this should not really come from the link...
48164 this.video_url = this.getVal(node, 'div', 'src');
48165 this.cls = this.getVal(node, 'div', 'class');
48166 this.href = this.getVal(node, 'a', 'href');
48168 this.image_src = this.getVal(node, 'img', 'src');
48170 this.align = this.getVal(node, 'figure', 'align');
48171 this.caption = this.getVal(node, 'figcaption', 'html');
48173 if (this.caption.trim().match(/^<i[^>]*>/i)) {
48174 this.caption = this.caption.trim().replace(/^<i[^>]*>/i, '').replace(/^<\/i>$/i, '');
48176 //this.text_align = this.getVal(node, 'figcaption', 'style','text-align');
48177 this.width = this.getVal(node, 'figure', 'style', 'max-width');
48178 //this.margin = this.getVal(node, 'figure', 'style', 'margin');
48181 removeNode : function()
48198 * @class Roo.htmleditor.BlockTable
48199 * Block that manages a table
48202 * Create a new Filter.
48203 * @param {Object} config Configuration options
48206 Roo.htmleditor.BlockTable = function(cfg)
48209 this.readElement(cfg.node);
48210 this.updateElement(cfg.node);
48212 Roo.apply(this, cfg);
48215 for(var r = 0; r < this.no_row; r++) {
48217 for(var c = 0; c < this.no_col; c++) {
48218 this.rows[r][c] = this.emptyCell();
48225 Roo.extend(Roo.htmleditor.BlockTable, Roo.htmleditor.Block, {
48234 // used by context menu
48235 friendly_name : 'Table',
48236 deleteTitle : 'Delete Table',
48237 // context menu is drawn once..
48239 contextMenu : function(toolbar)
48242 var block = function() {
48243 return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
48247 var rooui = typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
48249 var syncValue = toolbar.editorcore.syncValue;
48255 xtype : 'TextItem',
48257 xns : rooui.Toolbar //Boostrap?
48260 xtype : 'ComboBox',
48261 allowBlank : false,
48262 displayField : 'val',
48265 triggerAction : 'all',
48267 valueField : 'val',
48271 select : function (combo, r, index)
48273 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
48275 b.width = r.get('val');
48278 toolbar.editorcore.onEditorEvent();
48283 xtype : 'SimpleStore',
48295 xtype : 'TextItem',
48296 text : "Columns: ",
48297 xns : rooui.Toolbar //Boostrap?
48304 click : function (_self, e)
48306 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
48307 block().removeColumn();
48309 toolbar.editorcore.onEditorEvent();
48312 xns : rooui.Toolbar
48318 click : function (_self, e)
48320 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
48321 block().addColumn();
48323 toolbar.editorcore.onEditorEvent();
48326 xns : rooui.Toolbar
48330 xtype : 'TextItem',
48332 xns : rooui.Toolbar //Boostrap?
48339 click : function (_self, e)
48341 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
48342 block().removeRow();
48344 toolbar.editorcore.onEditorEvent();
48347 xns : rooui.Toolbar
48353 click : function (_self, e)
48357 toolbar.editorcore.onEditorEvent();
48360 xns : rooui.Toolbar
48365 text: 'Reset Column Widths',
48368 click : function (_self, e)
48370 block().resetWidths();
48372 toolbar.editorcore.onEditorEvent();
48375 xns : rooui.Toolbar
48386 * create a DomHelper friendly object - for use with
48387 * Roo.DomHelper.markup / overwrite / etc..
48388 * ?? should it be called with option to hide all editing features?
48390 toObject : function()
48395 contenteditable : 'false', // this stops cell selection from picking the table.
48396 'data-block' : 'Table',
48399 border : 'solid 1px #000', // ??? hard coded?
48400 'border-collapse' : 'collapse'
48403 { tag : 'tbody' , cn : [] }
48407 // do we have a head = not really
48409 Roo.each(this.rows, function( row ) {
48414 border : 'solid 1px #000',
48420 ret.cn[0].cn.push(tr);
48421 // does the row have any properties? ?? height?
48423 Roo.each(row, function( cell ) {
48427 contenteditable : 'true',
48428 'data-block' : 'Td',
48432 if (cell.colspan > 1) {
48433 td.colspan = cell.colspan ;
48434 nc += cell.colspan;
48438 if (cell.rowspan > 1) {
48439 td.rowspan = cell.rowspan ;
48448 ncols = Math.max(nc, ncols);
48452 // add the header row..
48461 readElement : function(node)
48463 node = node ? node : this.node ;
48464 this.width = this.getVal(node, true, 'style', 'width') || '100%';
48468 var trs = Array.from(node.rows);
48469 trs.forEach(function(tr) {
48471 this.rows.push(row);
48475 Array.from(tr.cells).forEach(function(td) {
48478 colspan : td.hasAttribute('colspan') ? td.getAttribute('colspan')*1 : 1,
48479 rowspan : td.hasAttribute('rowspan') ? td.getAttribute('rowspan')*1 : 1,
48480 style : td.hasAttribute('style') ? td.getAttribute('style') : '',
48481 html : td.innerHTML
48483 no_column += add.colspan;
48490 this.no_col = Math.max(this.no_col, no_column);
48497 normalizeRows: function()
48501 this.rows.forEach(function(row) {
48504 row = this.normalizeRow(row);
48506 row.forEach(function(c) {
48507 while (typeof(ret[rid][cid]) != 'undefined') {
48510 if (typeof(ret[rid]) == 'undefined') {
48516 if (c.rowspan < 2) {
48520 for(var i = 1 ;i < c.rowspan; i++) {
48521 if (typeof(ret[rid+i]) == 'undefined') {
48524 ret[rid+i][cid] = c;
48532 normalizeRow: function(row)
48535 row.forEach(function(c) {
48536 if (c.colspan < 2) {
48540 for(var i =0 ;i < c.colspan; i++) {
48548 deleteColumn : function(sel)
48550 if (!sel || sel.type != 'col') {
48553 if (this.no_col < 2) {
48557 this.rows.forEach(function(row) {
48558 var cols = this.normalizeRow(row);
48559 var col = cols[sel.col];
48560 if (col.colspan > 1) {
48570 removeColumn : function()
48572 this.deleteColumn({
48574 col : this.no_col-1
48576 this.updateElement();
48580 addColumn : function()
48583 this.rows.forEach(function(row) {
48584 row.push(this.emptyCell());
48587 this.updateElement();
48590 deleteRow : function(sel)
48592 if (!sel || sel.type != 'row') {
48596 if (this.no_row < 2) {
48600 var rows = this.normalizeRows();
48603 rows[sel.row].forEach(function(col) {
48604 if (col.rowspan > 1) {
48607 col.remove = 1; // flage it as removed.
48612 this.rows.forEach(function(row) {
48614 row.forEach(function(c) {
48615 if (typeof(c.remove) == 'undefined') {
48620 if (newrow.length > 0) {
48624 this.rows = newrows;
48629 this.updateElement();
48632 removeRow : function()
48636 row : this.no_row-1
48642 addRow : function()
48646 for (var i = 0; i < this.no_col; i++ ) {
48648 row.push(this.emptyCell());
48651 this.rows.push(row);
48652 this.updateElement();
48656 // the default cell object... at present...
48657 emptyCell : function() {
48658 return (new Roo.htmleditor.BlockTd({})).toObject();
48663 removeNode : function()
48670 resetWidths : function()
48672 Array.from(this.node.getElementsByTagName('td')).forEach(function(n) {
48673 var nn = Roo.htmleditor.Block.factory(n);
48675 nn.updateElement(n);
48688 * since selections really work on the table cell, then editing really should work from there
48690 * The original plan was to support merging etc... - but that may not be needed yet..
48692 * So this simple version will support:
48694 * adjust the width +/-
48695 * reset the width...
48704 * @class Roo.htmleditor.BlockTable
48705 * Block that manages a table
48708 * Create a new Filter.
48709 * @param {Object} config Configuration options
48712 Roo.htmleditor.BlockTd = function(cfg)
48715 this.readElement(cfg.node);
48716 this.updateElement(cfg.node);
48718 Roo.apply(this, cfg);
48723 Roo.extend(Roo.htmleditor.BlockTd, Roo.htmleditor.Block, {
48728 textAlign : 'left',
48735 // used by context menu
48736 friendly_name : 'Table Cell',
48737 deleteTitle : false, // use our customer delete
48739 // context menu is drawn once..
48741 contextMenu : function(toolbar)
48744 var cell = function() {
48745 return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
48748 var table = function() {
48749 return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode.closest('table'));
48753 var saveSel = function()
48755 lr = toolbar.editorcore.getSelection().getRangeAt(0);
48757 var restoreSel = function()
48761 toolbar.editorcore.focus();
48762 var cr = toolbar.editorcore.getSelection();
48763 cr.removeAllRanges();
48765 toolbar.editorcore.onEditorEvent();
48766 }).defer(10, this);
48772 var rooui = typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
48774 var syncValue = toolbar.editorcore.syncValue;
48781 text : 'Edit Table',
48783 click : function() {
48784 var t = toolbar.tb.selectedNode.closest('table');
48785 toolbar.editorcore.selectNode(t);
48786 toolbar.editorcore.onEditorEvent();
48795 xtype : 'TextItem',
48796 text : "Column Width: ",
48797 xns : rooui.Toolbar
48804 click : function (_self, e)
48806 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
48807 cell().shrinkColumn();
48809 toolbar.editorcore.onEditorEvent();
48812 xns : rooui.Toolbar
48818 click : function (_self, e)
48820 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
48821 cell().growColumn();
48823 toolbar.editorcore.onEditorEvent();
48826 xns : rooui.Toolbar
48830 xtype : 'TextItem',
48831 text : "Vertical Align: ",
48832 xns : rooui.Toolbar //Boostrap?
48835 xtype : 'ComboBox',
48836 allowBlank : false,
48837 displayField : 'val',
48840 triggerAction : 'all',
48842 valueField : 'val',
48846 select : function (combo, r, index)
48848 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
48850 b.valign = r.get('val');
48853 toolbar.editorcore.onEditorEvent();
48858 xtype : 'SimpleStore',
48862 ['bottom'] // there are afew more...
48870 xtype : 'TextItem',
48871 text : "Merge Cells: ",
48872 xns : rooui.Toolbar
48881 click : function (_self, e)
48883 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
48884 cell().mergeRight();
48885 //block().growColumn();
48887 toolbar.editorcore.onEditorEvent();
48890 xns : rooui.Toolbar
48897 click : function (_self, e)
48899 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
48900 cell().mergeBelow();
48901 //block().growColumn();
48903 toolbar.editorcore.onEditorEvent();
48906 xns : rooui.Toolbar
48909 xtype : 'TextItem',
48911 xns : rooui.Toolbar
48919 click : function (_self, e)
48921 //toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
48924 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
48925 toolbar.editorcore.onEditorEvent();
48929 xns : rooui.Toolbar
48933 xns : rooui.Toolbar
48942 xns : rooui.Toolbar,
48951 click : function (_self, e)
48955 cell().deleteColumn();
48957 toolbar.editorcore.selectNode(t.node);
48958 toolbar.editorcore.onEditorEvent();
48967 click : function (_self, e)
48970 cell().deleteRow();
48973 toolbar.editorcore.selectNode(t.node);
48974 toolbar.editorcore.onEditorEvent();
48981 xtype : 'Separator',
48988 click : function (_self, e)
48991 var nn = t.node.nextSibling || t.node.previousSibling;
48992 t.node.parentNode.removeChild(t.node);
48994 toolbar.editorcore.selectNode(nn, true);
48996 toolbar.editorcore.onEditorEvent();
49006 // align... << fixme
49014 * create a DomHelper friendly object - for use with
49015 * Roo.DomHelper.markup / overwrite / etc..
49016 * ?? should it be called with option to hide all editing features?
49019 * create a DomHelper friendly object - for use with
49020 * Roo.DomHelper.markup / overwrite / etc..
49021 * ?? should it be called with option to hide all editing features?
49023 toObject : function()
49028 contenteditable : 'true', // this stops cell selection from picking the table.
49029 'data-block' : 'Td',
49030 valign : this.valign,
49032 'text-align' : this.textAlign,
49033 border : 'solid 1px rgb(0, 0, 0)', // ??? hard coded?
49034 'border-collapse' : 'collapse',
49035 padding : '6px', // 8 for desktop / 4 for mobile
49036 'vertical-align': this.valign
49040 if (this.width != '') {
49041 ret.width = this.width;
49042 ret.style.width = this.width;
49046 if (this.colspan > 1) {
49047 ret.colspan = this.colspan ;
49049 if (this.rowspan > 1) {
49050 ret.rowspan = this.rowspan ;
49059 readElement : function(node)
49061 node = node ? node : this.node ;
49062 this.width = node.style.width;
49063 this.colspan = Math.max(1,1*node.getAttribute('colspan'));
49064 this.rowspan = Math.max(1,1*node.getAttribute('rowspan'));
49065 this.html = node.innerHTML;
49070 // the default cell object... at present...
49071 emptyCell : function() {
49075 textAlign : 'left',
49076 html : " " // is this going to be editable now?
49081 removeNode : function()
49083 return this.node.closest('table');
49091 toTableArray : function()
49094 var tab = this.node.closest('tr').closest('table');
49095 Array.from(tab.rows).forEach(function(r, ri){
49099 this.colWidths = [];
49100 var all_auto = true;
49101 Array.from(tab.rows).forEach(function(r, ri){
49104 Array.from(r.cells).forEach(function(ce, ci){
49109 colspan : ce.colSpan,
49110 rowspan : ce.rowSpan
49112 if (ce.isEqualNode(this.node)) {
49115 // if we have been filled up by a row?
49116 if (typeof(ret[rn][cn]) != 'undefined') {
49117 while(typeof(ret[rn][cn]) != 'undefined') {
49123 if (typeof(this.colWidths[cn]) == 'undefined') {
49124 this.colWidths[cn] = ce.style.width;
49125 if (this.colWidths[cn] != '') {
49131 if (c.colspan < 2 && c.rowspan < 2 ) {
49136 for(var j = 0; j < c.rowspan; j++) {
49137 if (typeof(ret[rn+j]) == 'undefined') {
49138 continue; // we have a problem..
49141 for(var i = 0; i < c.colspan; i++) {
49142 ret[rn+j][cn+i] = c;
49151 // initalize widths.?
49152 // either all widths or no widths..
49154 this.colWidths[0] = false; // no widths flag.
49165 mergeRight: function()
49168 // get the contents of the next cell along..
49169 var tr = this.node.closest('tr');
49170 var i = Array.prototype.indexOf.call(tr.childNodes, this.node);
49171 if (i >= tr.childNodes.length - 1) {
49172 return; // no cells on right to merge with.
49174 var table = this.toTableArray();
49176 if (typeof(table[this.cellData.row][this.cellData.col+this.cellData.colspan]) == 'undefined') {
49177 return; // nothing right?
49179 var rc = table[this.cellData.row][this.cellData.col+this.cellData.colspan];
49180 // right cell - must be same rowspan and on the same row.
49181 if (rc.rowspan != this.cellData.rowspan || rc.row != this.cellData.row) {
49182 return; // right hand side is not same rowspan.
49187 this.node.innerHTML += ' ' + rc.cell.innerHTML;
49188 tr.removeChild(rc.cell);
49189 this.colspan += rc.colspan;
49190 this.node.setAttribute('colspan', this.colspan);
49195 mergeBelow : function()
49197 var table = this.toTableArray();
49198 if (typeof(table[this.cellData.row+this.cellData.rowspan]) == 'undefined') {
49199 return; // no row below
49201 if (typeof(table[this.cellData.row+this.cellData.rowspan][this.cellData.col]) == 'undefined') {
49202 return; // nothing right?
49204 var rc = table[this.cellData.row+this.cellData.rowspan][this.cellData.col];
49206 if (rc.colspan != this.cellData.colspan || rc.col != this.cellData.col) {
49207 return; // right hand side is not same rowspan.
49209 this.node.innerHTML = this.node.innerHTML + rc.cell.innerHTML ;
49210 rc.cell.parentNode.removeChild(rc.cell);
49211 this.rowspan += rc.rowspan;
49212 this.node.setAttribute('rowspan', this.rowspan);
49217 if (this.node.rowSpan < 2 && this.node.colSpan < 2) {
49220 var table = this.toTableArray();
49221 var cd = this.cellData;
49225 for(var r = cd.row; r < cd.row + cd.rowspan; r++) {
49229 for(var c = cd.col; c < cd.col + cd.colspan; c++) {
49230 if (r == cd.row && c == cd.col) {
49231 this.node.removeAttribute('rowspan');
49232 this.node.removeAttribute('colspan');
49236 var ntd = this.node.cloneNode(); // which col/row should be 0..
49237 ntd.removeAttribute('id'); //
49238 //ntd.style.width = '';
49239 ntd.innerHTML = '';
49240 table[r][c] = { cell : ntd, col : c, row: r , colspan : 1 , rowspan : 1 };
49244 this.redrawAllCells(table);
49252 redrawAllCells: function(table)
49256 var tab = this.node.closest('tr').closest('table');
49257 var ctr = tab.rows[0].parentNode;
49258 Array.from(tab.rows).forEach(function(r, ri){
49260 Array.from(r.cells).forEach(function(ce, ci){
49261 ce.parentNode.removeChild(ce);
49263 r.parentNode.removeChild(r);
49265 for(var r = 0 ; r < table.length; r++) {
49266 var re = tab.rows[r];
49268 var re = tab.ownerDocument.createElement('tr');
49269 ctr.appendChild(re);
49270 for(var c = 0 ; c < table[r].length; c++) {
49271 if (table[r][c].cell === false) {
49275 re.appendChild(table[r][c].cell);
49277 table[r][c].cell = false;
49282 updateWidths : function(table)
49284 for(var r = 0 ; r < table.length; r++) {
49286 for(var c = 0 ; c < table[r].length; c++) {
49287 if (table[r][c].cell === false) {
49291 if (this.colWidths[0] != false && table[r][c].colspan < 2) {
49292 var el = Roo.htmleditor.Block.factory(table[r][c].cell);
49293 el.width = Math.floor(this.colWidths[c]) +'%';
49294 el.updateElement(el.node);
49296 table[r][c].cell = false; // done
49300 normalizeWidths : function(table)
49303 if (this.colWidths[0] === false) {
49304 var nw = 100.0 / this.colWidths.length;
49305 this.colWidths.forEach(function(w,i) {
49306 this.colWidths[i] = nw;
49311 var t = 0, missing = [];
49313 this.colWidths.forEach(function(w,i) {
49315 this.colWidths[i] = this.colWidths[i] == '' ? 0 : (this.colWidths[i]+'').replace(/[^0-9]+/g,'')*1;
49316 var add = this.colWidths[i];
49325 var nc = this.colWidths.length;
49326 if (missing.length) {
49327 var mult = (nc - missing.length) / (1.0 * nc);
49329 var ew = (100 -t) / (1.0 * missing.length);
49330 this.colWidths.forEach(function(w,i) {
49332 this.colWidths[i] = w * mult;
49336 this.colWidths[i] = ew;
49338 // have to make up numbers..
49341 // now we should have all the widths..
49346 shrinkColumn : function()
49348 var table = this.toTableArray();
49349 this.normalizeWidths(table);
49350 var col = this.cellData.col;
49351 var nw = this.colWidths[col] * 0.8;
49355 var otherAdd = (this.colWidths[col] * 0.2) / (this.colWidths.length -1);
49356 this.colWidths.forEach(function(w,i) {
49358 this.colWidths[i] = nw;
49361 this.colWidths[i] += otherAdd
49363 this.updateWidths(table);
49366 growColumn : function()
49368 var table = this.toTableArray();
49369 this.normalizeWidths(table);
49370 var col = this.cellData.col;
49371 var nw = this.colWidths[col] * 1.2;
49375 var otherSub = (this.colWidths[col] * 0.2) / (this.colWidths.length -1);
49376 this.colWidths.forEach(function(w,i) {
49378 this.colWidths[i] = nw;
49381 this.colWidths[i] -= otherSub
49383 this.updateWidths(table);
49386 deleteRow : function()
49388 // delete this rows 'tr'
49389 // if any of the cells in this row have a rowspan > 1 && row!= this row..
49390 // then reduce the rowspan.
49391 var table = this.toTableArray();
49392 // this.cellData.row;
49393 for (var i =0;i< table[this.cellData.row].length ; i++) {
49394 var c = table[this.cellData.row][i];
49395 if (c.row != this.cellData.row) {
49398 c.cell.setAttribute('rowspan', c.rowspan);
49401 if (c.rowspan > 1) {
49403 c.cell.setAttribute('rowspan', c.rowspan);
49406 table.splice(this.cellData.row,1);
49407 this.redrawAllCells(table);
49410 deleteColumn : function()
49412 var table = this.toTableArray();
49414 for (var i =0;i< table.length ; i++) {
49415 var c = table[i][this.cellData.col];
49416 if (c.col != this.cellData.col) {
49417 table[i][this.cellData.col].colspan--;
49418 } else if (c.colspan > 1) {
49420 c.cell.setAttribute('colspan', c.colspan);
49422 table[i].splice(this.cellData.col,1);
49425 this.redrawAllCells(table);
49433 //<script type="text/javascript">
49436 * Based Ext JS Library 1.1.1
49437 * Copyright(c) 2006-2007, Ext JS, LLC.
49443 * @class Roo.HtmlEditorCore
49444 * @extends Roo.Component
49445 * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
49447 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
49450 Roo.HtmlEditorCore = function(config){
49453 Roo.HtmlEditorCore.superclass.constructor.call(this, config);
49458 * @event initialize
49459 * Fires when the editor is fully initialized (including the iframe)
49460 * @param {Roo.HtmlEditorCore} this
49465 * Fires when the editor is first receives the focus. Any insertion must wait
49466 * until after this event.
49467 * @param {Roo.HtmlEditorCore} this
49471 * @event beforesync
49472 * Fires before the textarea is updated with content from the editor iframe. Return false
49473 * to cancel the sync.
49474 * @param {Roo.HtmlEditorCore} this
49475 * @param {String} html
49479 * @event beforepush
49480 * Fires before the iframe editor is updated with content from the textarea. Return false
49481 * to cancel the push.
49482 * @param {Roo.HtmlEditorCore} this
49483 * @param {String} html
49488 * Fires when the textarea is updated with content from the editor iframe.
49489 * @param {Roo.HtmlEditorCore} this
49490 * @param {String} html
49495 * Fires when the iframe editor is updated with content from the textarea.
49496 * @param {Roo.HtmlEditorCore} this
49497 * @param {String} html
49502 * @event editorevent
49503 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
49504 * @param {Roo.HtmlEditorCore} this
49511 // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
49513 // defaults : white / black...
49514 this.applyBlacklists();
49521 Roo.extend(Roo.HtmlEditorCore, Roo.Component, {
49525 * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field
49531 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
49536 * @cfg {Number} height (in pixels)
49540 * @cfg {Number} width (in pixels)
49544 * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
49545 * if you are doing an email editor, this probably needs disabling, it's designed
49550 * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
49552 enableBlocks : true,
49554 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
49557 stylesheets: false,
49559 * @cfg {String} language default en - language of text (usefull for rtl languages)
49565 * @cfg {boolean} allowComments - default false - allow comments in HTML source
49566 * - by default they are stripped - if you are editing email you may need this.
49568 allowComments: false,
49572 // private properties
49573 validationEvent : false,
49575 initialized : false,
49577 sourceEditMode : false,
49578 onFocus : Roo.emptyFn,
49580 hideMode:'offsets',
49584 // blacklist + whitelisted elements..
49591 undoManager : false,
49593 * Protected method that will not generally be called directly. It
49594 * is called when the editor initializes the iframe with HTML contents. Override this method if you
49595 * want to change the initialization markup of the iframe (e.g. to add stylesheets).
49597 getDocMarkup : function(){
49601 // inherit styels from page...??
49602 if (this.stylesheets === false) {
49604 Roo.get(document.head).select('style').each(function(node) {
49605 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
49608 Roo.get(document.head).select('link').each(function(node) {
49609 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
49612 } else if (!this.stylesheets.length) {
49614 st = '<style type="text/css">' +
49615 'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
49618 for (var i in this.stylesheets) {
49619 if (typeof(this.stylesheets[i]) != 'string') {
49622 st += '<link rel="stylesheet" href="' + this.stylesheets[i] +'" type="text/css">';
49627 st += '<style type="text/css">' +
49628 'IMG { cursor: pointer } ' +
49631 st += '<meta name="google" content="notranslate">';
49633 var cls = 'notranslate roo-htmleditor-body';
49635 if(this.bodyCls.length){
49636 cls += ' ' + this.bodyCls;
49639 return '<html class="notranslate" translate="no"><head>' + st +
49640 //<style type="text/css">' +
49641 //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
49643 ' </head><body contenteditable="true" data-enable-grammerly="true" class="' + cls + '"></body></html>';
49647 onRender : function(ct, position)
49650 //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
49651 this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
49654 this.el.dom.style.border = '0 none';
49655 this.el.dom.setAttribute('tabIndex', -1);
49656 this.el.addClass('x-hidden hide');
49660 if(Roo.isIE){ // fix IE 1px bogus margin
49661 this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
49665 this.frameId = Roo.id();
49669 var iframe = this.owner.wrap.createChild({
49671 cls: 'form-control', // bootstrap..
49673 name: this.frameId,
49674 frameBorder : 'no',
49675 'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL : "javascript:false"
49680 this.iframe = iframe.dom;
49682 this.assignDocWin();
49684 this.doc.designMode = 'on';
49687 this.doc.write(this.getDocMarkup());
49691 var task = { // must defer to wait for browser to be ready
49693 //console.log("run task?" + this.doc.readyState);
49694 this.assignDocWin();
49695 if(this.doc.body || this.doc.readyState == 'complete'){
49697 this.doc.designMode="on";
49702 Roo.TaskMgr.stop(task);
49703 this.initEditor.defer(10, this);
49710 Roo.TaskMgr.start(task);
49715 onResize : function(w, h)
49717 Roo.log('resize: ' +w + ',' + h );
49718 //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
49722 if(typeof w == 'number'){
49724 this.iframe.style.width = w + 'px';
49726 if(typeof h == 'number'){
49728 this.iframe.style.height = h + 'px';
49730 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
49737 * Toggles the editor between standard and source edit mode.
49738 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
49740 toggleSourceEdit : function(sourceEditMode){
49742 this.sourceEditMode = sourceEditMode === true;
49744 if(this.sourceEditMode){
49746 Roo.get(this.iframe).addClass(['x-hidden','hide', 'd-none']); //FIXME - what's the BS styles for these
49749 Roo.get(this.iframe).removeClass(['x-hidden','hide', 'd-none']);
49750 //this.iframe.className = '';
49753 //this.setSize(this.owner.wrap.getSize());
49754 //this.fireEvent('editmodechange', this, this.sourceEditMode);
49761 * Protected method that will not generally be called directly. If you need/want
49762 * custom HTML cleanup, this is the method you should override.
49763 * @param {String} html The HTML to be cleaned
49764 * return {String} The cleaned HTML
49766 cleanHtml : function(html)
49768 html = String(html);
49769 if(html.length > 5){
49770 if(Roo.isSafari){ // strip safari nonsense
49771 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
49774 if(html == ' '){
49781 * HTML Editor -> Textarea
49782 * Protected method that will not generally be called directly. Syncs the contents
49783 * of the editor iframe with the textarea.
49785 syncValue : function()
49787 //Roo.log("HtmlEditorCore:syncValue (EDITOR->TEXT)");
49788 if(this.initialized){
49790 this.undoManager.addEvent();
49793 var bd = (this.doc.body || this.doc.documentElement);
49796 var sel = this.win.getSelection();
49798 var div = document.createElement('div');
49799 div.innerHTML = bd.innerHTML;
49800 var gtx = div.getElementsByClassName('gtx-trans-icon'); // google translate - really annoying and difficult to get rid of.
49801 if (gtx.length > 0) {
49802 var rm = gtx.item(0).parentNode;
49803 rm.parentNode.removeChild(rm);
49807 if (this.enableBlocks) {
49808 new Roo.htmleditor.FilterBlock({ node : div });
49811 var tidy = new Roo.htmleditor.TidySerializer({
49814 var html = tidy.serialize(div);
49818 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
49819 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
49821 html = '<div style="'+m[0]+'">' + html + '</div>';
49824 html = this.cleanHtml(html);
49825 // fix up the special chars.. normaly like back quotes in word...
49826 // however we do not want to do this with chinese..
49827 html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
49829 var cc = match.charCodeAt();
49831 // Get the character value, handling surrogate pairs
49832 if (match.length == 2) {
49833 // It's a surrogate pair, calculate the Unicode code point
49834 var high = match.charCodeAt(0) - 0xD800;
49835 var low = match.charCodeAt(1) - 0xDC00;
49836 cc = (high * 0x400) + low + 0x10000;
49838 (cc >= 0x4E00 && cc < 0xA000 ) ||
49839 (cc >= 0x3400 && cc < 0x4E00 ) ||
49840 (cc >= 0xf900 && cc < 0xfb00 )
49845 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
49846 return "&#" + cc + ";";
49853 if(this.owner.fireEvent('beforesync', this, html) !== false){
49854 this.el.dom.value = html;
49855 this.owner.fireEvent('sync', this, html);
49861 * TEXTAREA -> EDITABLE
49862 * Protected method that will not generally be called directly. Pushes the value of the textarea
49863 * into the iframe editor.
49865 pushValue : function()
49867 //Roo.log("HtmlEditorCore:pushValue (TEXT->EDITOR)");
49868 if(this.initialized){
49869 var v = this.el.dom.value.trim();
49872 if(this.owner.fireEvent('beforepush', this, v) !== false){
49873 var d = (this.doc.body || this.doc.documentElement);
49876 this.el.dom.value = d.innerHTML;
49877 this.owner.fireEvent('push', this, v);
49879 if (this.autoClean) {
49880 new Roo.htmleditor.FilterParagraph({node : this.doc.body}); // paragraphs
49881 new Roo.htmleditor.FilterSpan({node : this.doc.body}); // empty spans
49884 Roo.htmleditor.Block.initAll(this.doc.body);
49885 this.updateLanguage();
49887 var lc = this.doc.body.lastChild;
49888 if (lc && lc.nodeType == 1 && lc.getAttribute("contenteditable") == "false") {
49889 // add an extra line at the end.
49890 this.doc.body.appendChild(this.doc.createElement('br'));
49898 deferFocus : function(){
49899 this.focus.defer(10, this);
49903 focus : function(){
49904 if(this.win && !this.sourceEditMode){
49911 assignDocWin: function()
49913 var iframe = this.iframe;
49916 this.doc = iframe.contentWindow.document;
49917 this.win = iframe.contentWindow;
49919 // if (!Roo.get(this.frameId)) {
49922 // this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
49923 // this.win = Roo.get(this.frameId).dom.contentWindow;
49925 if (!Roo.get(this.frameId) && !iframe.contentDocument) {
49929 this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
49930 this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
49935 initEditor : function(){
49936 //console.log("INIT EDITOR");
49937 this.assignDocWin();
49941 this.doc.designMode="on";
49943 this.doc.write(this.getDocMarkup());
49946 var dbody = (this.doc.body || this.doc.documentElement);
49947 //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
49948 // this copies styles from the containing element into thsi one..
49949 // not sure why we need all of this..
49950 //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
49952 //var ss = this.el.getStyles( 'background-image', 'background-repeat');
49953 //ss['background-attachment'] = 'fixed'; // w3c
49954 dbody.bgProperties = 'fixed'; // ie
49955 dbody.setAttribute("translate", "no");
49957 //Roo.DomHelper.applyStyles(dbody, ss);
49958 Roo.EventManager.on(this.doc, {
49960 'mouseup': this.onEditorEvent,
49961 'dblclick': this.onEditorEvent,
49962 'click': this.onEditorEvent,
49963 'keyup': this.onEditorEvent,
49968 Roo.EventManager.on(this.doc, {
49969 'paste': this.onPasteEvent,
49973 Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
49976 if(Roo.isIE || Roo.isSafari || Roo.isOpera){
49977 Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
49979 this.initialized = true;
49982 // initialize special key events - enter
49983 new Roo.htmleditor.KeyEnter({core : this});
49987 this.owner.fireEvent('initialize', this);
49990 // this is to prevent a href clicks resulting in a redirect?
49992 onPasteEvent : function(e,v)
49994 // I think we better assume paste is going to be a dirty load of rubish from word..
49996 // even pasting into a 'email version' of this widget will have to clean up that mess.
49997 var cd = (e.browserEvent.clipboardData || window.clipboardData);
49999 // check what type of paste - if it's an image, then handle it differently.
50000 if (cd.files.length > 0) {
50002 var urlAPI = (window.createObjectURL && window) ||
50003 (window.URL && URL.revokeObjectURL && URL) ||
50004 (window.webkitURL && webkitURL);
50006 var url = urlAPI.createObjectURL( cd.files[0]);
50007 this.insertAtCursor('<img src=" + url + ">');
50011 var html = cd.getData('text/html'); // clipboard event
50012 var parser = new Roo.rtf.Parser(cd.getData('text/rtf'));
50013 var images = parser.doc ? parser.doc.getElementsByType('pict') : [];
50017 images = images.filter(function(g) { return !g.path.match(/^rtf\/(head|pgdsctbl|listtable)/); }) // ignore headers
50018 .map(function(g) { return g.toDataURL(); });
50021 html = this.cleanWordChars(html);
50023 var d = (new DOMParser().parseFromString(html, 'text/html')).body;
50026 var sn = this.getParentElement();
50027 // check if d contains a table, and prevent nesting??
50028 //Roo.log(d.getElementsByTagName('table'));
50030 //Roo.log(sn.closest('table'));
50031 if (d.getElementsByTagName('table').length && sn && sn.closest('table')) {
50032 e.preventDefault();
50033 this.insertAtCursor("You can not nest tables");
50034 //Roo.log("prevent?"); // fixme -
50038 if (images.length > 0) {
50039 Roo.each(d.getElementsByTagName('img'), function(img, i) {
50040 img.setAttribute('src', images[i]);
50043 if (this.autoClean) {
50044 new Roo.htmleditor.FilterStyleToTag({ node : d });
50045 new Roo.htmleditor.FilterAttributes({
50047 attrib_white : ['href', 'src', 'name', 'align'],
50048 attrib_clean : ['href', 'src' ]
50050 new Roo.htmleditor.FilterBlack({ node : d, tag : this.black});
50051 // should be fonts..
50052 new Roo.htmleditor.FilterKeepChildren({node : d, tag : [ 'FONT', 'O:P' ]} );
50053 new Roo.htmleditor.FilterParagraph({ node : d });
50054 new Roo.htmleditor.FilterSpan({ node : d });
50055 new Roo.htmleditor.FilterLongBr({ node : d });
50057 if (this.enableBlocks) {
50059 Array.from(d.getElementsByTagName('img')).forEach(function(img) {
50060 if (img.closest('figure')) { // assume!! that it's aready
50063 var fig = new Roo.htmleditor.BlockFigure({
50064 image_src : img.src
50066 fig.updateElement(img); // replace it..
50072 this.insertAtCursor(d.innerHTML.replace(/ /g,' '));
50073 if (this.enableBlocks) {
50074 Roo.htmleditor.Block.initAll(this.doc.body);
50078 e.preventDefault();
50080 // default behaveiour should be our local cleanup paste? (optional?)
50081 // for simple editor - we want to hammer the paste and get rid of everything... - so over-rideable..
50082 //this.owner.fireEvent('paste', e, v);
50085 onDestroy : function(){
50091 //for (var i =0; i < this.toolbars.length;i++) {
50092 // // fixme - ask toolbars for heights?
50093 // this.toolbars[i].onDestroy();
50096 //this.wrap.dom.innerHTML = '';
50097 //this.wrap.remove();
50102 onFirstFocus : function(){
50104 this.assignDocWin();
50105 this.undoManager = new Roo.lib.UndoManager(100,(this.doc.body || this.doc.documentElement));
50107 this.activated = true;
50110 if(Roo.isGecko){ // prevent silly gecko errors
50112 var s = this.win.getSelection();
50113 if(!s.focusNode || s.focusNode.nodeType != 3){
50114 var r = s.getRangeAt(0);
50115 r.selectNodeContents((this.doc.body || this.doc.documentElement));
50120 this.execCmd('useCSS', true);
50121 this.execCmd('styleWithCSS', false);
50124 this.owner.fireEvent('activate', this);
50128 adjustFont: function(btn){
50129 var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
50130 //if(Roo.isSafari){ // safari
50133 var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
50134 if(Roo.isSafari){ // safari
50135 var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
50136 v = (v < 10) ? 10 : v;
50137 v = (v > 48) ? 48 : v;
50138 v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
50143 v = Math.max(1, v+adjust);
50145 this.execCmd('FontSize', v );
50148 onEditorEvent : function(e)
50152 if (e && (e.ctrlKey || e.metaKey) && e.keyCode === 90) {
50153 return; // we do not handle this.. (undo manager does..)
50155 // in theory this detects if the last element is not a br, then we try and do that.
50156 // its so clicking in space at bottom triggers adding a br and moving the cursor.
50158 e.target.nodeName == 'BODY' &&
50159 e.type == "mouseup" &&
50160 this.doc.body.lastChild
50162 var lc = this.doc.body.lastChild;
50163 // gtx-trans is google translate plugin adding crap.
50164 while ((lc.nodeType == 3 && lc.nodeValue == '') || lc.id == 'gtx-trans') {
50165 lc = lc.previousSibling;
50167 if (lc.nodeType == 1 && lc.nodeName != 'BR') {
50168 // if last element is <BR> - then dont do anything.
50170 var ns = this.doc.createElement('br');
50171 this.doc.body.appendChild(ns);
50172 range = this.doc.createRange();
50173 range.setStartAfter(ns);
50174 range.collapse(true);
50175 var sel = this.win.getSelection();
50176 sel.removeAllRanges();
50177 sel.addRange(range);
50183 this.fireEditorEvent(e);
50184 // this.updateToolbar();
50185 this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
50188 fireEditorEvent: function(e)
50190 this.owner.fireEvent('editorevent', this, e);
50193 insertTag : function(tg)
50195 // could be a bit smarter... -> wrap the current selected tRoo..
50196 if (tg.toLowerCase() == 'span' ||
50197 tg.toLowerCase() == 'code' ||
50198 tg.toLowerCase() == 'sup' ||
50199 tg.toLowerCase() == 'sub'
50202 range = this.createRange(this.getSelection());
50203 var wrappingNode = this.doc.createElement(tg.toLowerCase());
50204 wrappingNode.appendChild(range.extractContents());
50205 range.insertNode(wrappingNode);
50212 this.execCmd("formatblock", tg);
50213 this.undoManager.addEvent();
50216 insertText : function(txt)
50220 var range = this.createRange();
50221 range.deleteContents();
50222 //alert(Sender.getAttribute('label'));
50224 range.insertNode(this.doc.createTextNode(txt));
50225 this.undoManager.addEvent();
50231 * Executes a Midas editor command on the editor document and performs necessary focus and
50232 * toolbar updates. <b>This should only be called after the editor is initialized.</b>
50233 * @param {String} cmd The Midas command
50234 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
50236 relayCmd : function(cmd, value)
50240 case 'justifyleft':
50241 case 'justifyright':
50242 case 'justifycenter':
50243 // if we are in a cell, then we will adjust the
50244 var n = this.getParentElement();
50245 var td = n.closest('td');
50247 var bl = Roo.htmleditor.Block.factory(td);
50248 bl.textAlign = cmd.replace('justify','');
50249 bl.updateElement();
50250 this.owner.fireEvent('editorevent', this);
50253 this.execCmd('styleWithCSS', true); //
50257 // if there is no selection, then we insert, and set the curson inside it..
50258 this.execCmd('styleWithCSS', false);
50268 this.execCmd(cmd, value);
50269 this.owner.fireEvent('editorevent', this);
50270 //this.updateToolbar();
50271 this.owner.deferFocus();
50275 * Executes a Midas editor command directly on the editor document.
50276 * For visual commands, you should use {@link #relayCmd} instead.
50277 * <b>This should only be called after the editor is initialized.</b>
50278 * @param {String} cmd The Midas command
50279 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
50281 execCmd : function(cmd, value){
50282 this.doc.execCommand(cmd, false, value === undefined ? null : value);
50289 * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
50291 * @param {String} text | dom node..
50293 insertAtCursor : function(text)
50296 if(!this.activated){
50300 if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
50304 // from jquery ui (MIT licenced)
50306 var win = this.win;
50308 if (win.getSelection && win.getSelection().getRangeAt) {
50310 // delete the existing?
50312 this.createRange(this.getSelection()).deleteContents();
50313 range = win.getSelection().getRangeAt(0);
50314 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
50315 range.insertNode(node);
50316 range = range.cloneRange();
50317 range.collapse(false);
50319 win.getSelection().removeAllRanges();
50320 win.getSelection().addRange(range);
50324 } else if (win.document.selection && win.document.selection.createRange) {
50325 // no firefox support
50326 var txt = typeof(text) == 'string' ? text : text.outerHTML;
50327 win.document.selection.createRange().pasteHTML(txt);
50330 // no firefox support
50331 var txt = typeof(text) == 'string' ? text : text.outerHTML;
50332 this.execCmd('InsertHTML', txt);
50340 mozKeyPress : function(e){
50342 var c = e.getCharCode(), cmd;
50345 c = String.fromCharCode(c).toLowerCase();
50359 // this.cleanUpPaste.defer(100, this);
50365 this.relayCmd(cmd);
50366 //this.win.focus();
50367 //this.execCmd(cmd);
50368 //this.deferFocus();
50369 e.preventDefault();
50377 fixKeys : function(){ // load time branching for fastest keydown performance
50381 return function(e){
50382 var k = e.getKey(), r;
50385 r = this.doc.selection.createRange();
50388 r.pasteHTML('    ');
50393 /// this is handled by Roo.htmleditor.KeyEnter
50396 r = this.doc.selection.createRange();
50398 var target = r.parentElement();
50399 if(!target || target.tagName.toLowerCase() != 'li'){
50401 r.pasteHTML('<br/>');
50408 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
50409 // this.cleanUpPaste.defer(100, this);
50415 }else if(Roo.isOpera){
50416 return function(e){
50417 var k = e.getKey();
50421 this.execCmd('InsertHTML','    ');
50425 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
50426 // this.cleanUpPaste.defer(100, this);
50431 }else if(Roo.isSafari){
50432 return function(e){
50433 var k = e.getKey();
50437 this.execCmd('InsertText','\t');
50441 this.mozKeyPress(e);
50443 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
50444 // this.cleanUpPaste.defer(100, this);
50452 getAllAncestors: function()
50454 var p = this.getSelectedNode();
50457 a.push(p); // push blank onto stack..
50458 p = this.getParentElement();
50462 while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
50466 a.push(this.doc.body);
50470 lastSelNode : false,
50473 getSelection : function()
50475 this.assignDocWin();
50476 return Roo.lib.Selection.wrap(Roo.isIE ? this.doc.selection : this.win.getSelection(), this.doc);
50479 * Select a dom node
50480 * @param {DomElement} node the node to select
50482 selectNode : function(node, collapse)
50484 var nodeRange = node.ownerDocument.createRange();
50486 nodeRange.selectNode(node);
50488 nodeRange.selectNodeContents(node);
50490 if (collapse === true) {
50491 nodeRange.collapse(true);
50494 var s = this.win.getSelection();
50495 s.removeAllRanges();
50496 s.addRange(nodeRange);
50499 getSelectedNode: function()
50501 // this may only work on Gecko!!!
50503 // should we cache this!!!!
50507 var range = this.createRange(this.getSelection()).cloneRange();
50510 var parent = range.parentElement();
50512 var testRange = range.duplicate();
50513 testRange.moveToElementText(parent);
50514 if (testRange.inRange(range)) {
50517 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
50520 parent = parent.parentElement;
50525 // is ancestor a text element.
50526 var ac = range.commonAncestorContainer;
50527 if (ac.nodeType == 3) {
50528 ac = ac.parentNode;
50531 var ar = ac.childNodes;
50534 var other_nodes = [];
50535 var has_other_nodes = false;
50536 for (var i=0;i<ar.length;i++) {
50537 if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ?
50540 // fullly contained node.
50542 if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
50547 // probably selected..
50548 if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
50549 other_nodes.push(ar[i]);
50553 if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0)) {
50558 has_other_nodes = true;
50560 if (!nodes.length && other_nodes.length) {
50561 nodes= other_nodes;
50563 if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
50571 createRange: function(sel)
50573 // this has strange effects when using with
50574 // top toolbar - not sure if it's a great idea.
50575 //this.editor.contentWindow.focus();
50576 if (typeof sel != "undefined") {
50578 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
50580 return this.doc.createRange();
50583 return this.doc.createRange();
50586 getParentElement: function()
50589 this.assignDocWin();
50590 var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
50592 var range = this.createRange(sel);
50595 var p = range.commonAncestorContainer;
50596 while (p.nodeType == 3) { // text node
50607 * Range intersection.. the hard stuff...
50611 * [ -- selected range --- ]
50615 * if end is before start or hits it. fail.
50616 * if start is after end or hits it fail.
50618 * if either hits (but other is outside. - then it's not
50624 // @see http://www.thismuchiknow.co.uk/?p=64.
50625 rangeIntersectsNode : function(range, node)
50627 var nodeRange = node.ownerDocument.createRange();
50629 nodeRange.selectNode(node);
50631 nodeRange.selectNodeContents(node);
50634 var rangeStartRange = range.cloneRange();
50635 rangeStartRange.collapse(true);
50637 var rangeEndRange = range.cloneRange();
50638 rangeEndRange.collapse(false);
50640 var nodeStartRange = nodeRange.cloneRange();
50641 nodeStartRange.collapse(true);
50643 var nodeEndRange = nodeRange.cloneRange();
50644 nodeEndRange.collapse(false);
50646 return rangeStartRange.compareBoundaryPoints(
50647 Range.START_TO_START, nodeEndRange) == -1 &&
50648 rangeEndRange.compareBoundaryPoints(
50649 Range.START_TO_START, nodeStartRange) == 1;
50653 rangeCompareNode : function(range, node)
50655 var nodeRange = node.ownerDocument.createRange();
50657 nodeRange.selectNode(node);
50659 nodeRange.selectNodeContents(node);
50663 range.collapse(true);
50665 nodeRange.collapse(true);
50667 var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
50668 var ee = range.compareBoundaryPoints( Range.END_TO_END, nodeRange);
50670 //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
50672 var nodeIsBefore = ss == 1;
50673 var nodeIsAfter = ee == -1;
50675 if (nodeIsBefore && nodeIsAfter) {
50678 if (!nodeIsBefore && nodeIsAfter) {
50679 return 1; //right trailed.
50682 if (nodeIsBefore && !nodeIsAfter) {
50683 return 2; // left trailed.
50689 cleanWordChars : function(input) {// change the chars to hex code
50692 [ 8211, "–" ],
50693 [ 8212, "—" ],
50701 var output = input;
50702 Roo.each(swapCodes, function(sw) {
50703 var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
50705 output = output.replace(swapper, sw[1]);
50715 cleanUpChild : function (node)
50718 new Roo.htmleditor.FilterComment({node : node});
50719 new Roo.htmleditor.FilterAttributes({
50721 attrib_black : this.ablack,
50722 attrib_clean : this.aclean,
50723 style_white : this.cwhite,
50724 style_black : this.cblack
50726 new Roo.htmleditor.FilterBlack({ node : node, tag : this.black});
50727 new Roo.htmleditor.FilterKeepChildren({node : node, tag : this.tag_remove} );
50733 * Clean up MS wordisms...
50734 * @deprecated - use filter directly
50736 cleanWord : function(node)
50738 new Roo.htmleditor.FilterWord({ node : node ? node : this.doc.body });
50745 * @deprecated - use filters
50747 cleanTableWidths : function(node)
50749 new Roo.htmleditor.FilterTableWidth({ node : node ? node : this.doc.body});
50756 applyBlacklists : function()
50758 var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white : [];
50759 var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black : [];
50761 this.aclean = typeof(this.owner.aclean) != 'undefined' && this.owner.aclean ? this.owner.aclean : Roo.HtmlEditorCore.aclean;
50762 this.ablack = typeof(this.owner.ablack) != 'undefined' && this.owner.ablack ? this.owner.ablack : Roo.HtmlEditorCore.ablack;
50763 this.tag_remove = typeof(this.owner.tag_remove) != 'undefined' && this.owner.tag_remove ? this.owner.tag_remove : Roo.HtmlEditorCore.tag_remove;
50767 Roo.each(Roo.HtmlEditorCore.white, function(tag) {
50768 if (b.indexOf(tag) > -1) {
50771 this.white.push(tag);
50775 Roo.each(w, function(tag) {
50776 if (b.indexOf(tag) > -1) {
50779 if (this.white.indexOf(tag) > -1) {
50782 this.white.push(tag);
50787 Roo.each(Roo.HtmlEditorCore.black, function(tag) {
50788 if (w.indexOf(tag) > -1) {
50791 this.black.push(tag);
50795 Roo.each(b, function(tag) {
50796 if (w.indexOf(tag) > -1) {
50799 if (this.black.indexOf(tag) > -1) {
50802 this.black.push(tag);
50807 w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite : [];
50808 b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack : [];
50812 Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
50813 if (b.indexOf(tag) > -1) {
50816 this.cwhite.push(tag);
50820 Roo.each(w, function(tag) {
50821 if (b.indexOf(tag) > -1) {
50824 if (this.cwhite.indexOf(tag) > -1) {
50827 this.cwhite.push(tag);
50832 Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
50833 if (w.indexOf(tag) > -1) {
50836 this.cblack.push(tag);
50840 Roo.each(b, function(tag) {
50841 if (w.indexOf(tag) > -1) {
50844 if (this.cblack.indexOf(tag) > -1) {
50847 this.cblack.push(tag);
50852 setStylesheets : function(stylesheets)
50854 if(typeof(stylesheets) == 'string'){
50855 Roo.get(this.iframe.contentDocument.head).createChild({
50857 rel : 'stylesheet',
50866 Roo.each(stylesheets, function(s) {
50871 Roo.get(_this.iframe.contentDocument.head).createChild({
50873 rel : 'stylesheet',
50883 updateLanguage : function()
50885 if (!this.iframe || !this.iframe.contentDocument) {
50888 Roo.get(this.iframe.contentDocument.body).attr("lang", this.language);
50892 removeStylesheets : function()
50896 Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
50901 setStyle : function(style)
50903 Roo.get(this.iframe.contentDocument.head).createChild({
50912 // hide stuff that is not compatible
50926 * @event specialkey
50930 * @cfg {String} fieldClass @hide
50933 * @cfg {String} focusClass @hide
50936 * @cfg {String} autoCreate @hide
50939 * @cfg {String} inputType @hide
50942 * @cfg {String} invalidClass @hide
50945 * @cfg {String} invalidText @hide
50948 * @cfg {String} msgFx @hide
50951 * @cfg {String} validateOnBlur @hide
50955 Roo.HtmlEditorCore.white = [
50956 'AREA', 'BR', 'IMG', 'INPUT', 'HR', 'WBR',
50958 'ADDRESS', 'BLOCKQUOTE', 'CENTER', 'DD', 'DIR', 'DIV',
50959 'DL', 'DT', 'H1', 'H2', 'H3', 'H4',
50960 'H5', 'H6', 'HR', 'ISINDEX', 'LISTING', 'MARQUEE',
50961 'MENU', 'MULTICOL', 'OL', 'P', 'PLAINTEXT', 'PRE',
50962 'TABLE', 'UL', 'XMP',
50964 'CAPTION', 'COL', 'COLGROUP', 'TBODY', 'TD', 'TFOOT', 'TH',
50967 'DIR', 'MENU', 'OL', 'UL', 'DL',
50973 Roo.HtmlEditorCore.black = [
50974 // 'embed', 'object', // enable - backend responsiblity to clean thiese
50976 'BASE', 'BASEFONT', 'BGSOUND', 'BLINK', 'BODY',
50977 'FRAME', 'FRAMESET', 'HEAD', 'HTML', 'ILAYER',
50978 'IFRAME', 'LAYER', 'LINK', 'META', 'OBJECT',
50979 'SCRIPT', 'STYLE' ,'TITLE', 'XML',
50980 //'FONT' // CLEAN LATER..
50981 'COLGROUP', 'COL' // messy tables.
50985 Roo.HtmlEditorCore.clean = [ // ?? needed???
50986 'SCRIPT', 'STYLE', 'TITLE', 'XML'
50988 Roo.HtmlEditorCore.tag_remove = [
50993 Roo.HtmlEditorCore.ablack = [
50997 Roo.HtmlEditorCore.aclean = [
50998 'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc'
51002 Roo.HtmlEditorCore.pwhite= [
51003 'http', 'https', 'mailto'
51006 // white listed style attributes.
51007 Roo.HtmlEditorCore.cwhite= [
51008 // 'text-align', /// default is to allow most things..
51014 // black listed style attributes.
51015 Roo.HtmlEditorCore.cblack= [
51016 // 'font-size' -- this can be set by the project
51022 //<script type="text/javascript">
51025 * Ext JS Library 1.1.1
51026 * Copyright(c) 2006-2007, Ext JS, LLC.
51032 Roo.form.HtmlEditor = function(config){
51036 Roo.form.HtmlEditor.superclass.constructor.call(this, config);
51038 if (!this.toolbars) {
51039 this.toolbars = [];
51041 this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
51047 * @class Roo.form.HtmlEditor
51048 * @extends Roo.form.Field
51049 * Provides a lightweight HTML Editor component.
51051 * This has been tested on Fireforx / Chrome.. IE may not be so great..
51053 * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
51054 * supported by this editor.</b><br/><br/>
51055 * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
51056 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
51058 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
51060 * @cfg {Boolean} clearUp
51064 * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
51069 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
51074 * @cfg {Number} height (in pixels)
51078 * @cfg {Number} width (in pixels)
51083 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets - this is usally a good idea rootURL + '/roojs1/css/undoreset.css', .
51086 stylesheets: false,
51090 * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
51095 * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
51101 * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
51106 * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
51111 * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
51113 allowComments: false,
51115 * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
51117 enableBlocks : true,
51120 * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
51121 * if you are doing an email editor, this probably needs disabling, it's designed
51125 * @cfg {string} bodyCls- default '' default classes to add to body of editable area - usually undoreset is a good start..
51129 * @cfg {String} language default en - language of text (usefull for rtl languages)
51138 // private properties
51139 validationEvent : false,
51141 initialized : false,
51144 onFocus : Roo.emptyFn,
51146 hideMode:'offsets',
51148 actionMode : 'container', // defaults to hiding it...
51150 defaultAutoCreate : { // modified by initCompnoent..
51152 style:"width:500px;height:300px;",
51153 autocomplete: "new-password"
51157 initComponent : function(){
51160 * @event initialize
51161 * Fires when the editor is fully initialized (including the iframe)
51162 * @param {HtmlEditor} this
51167 * Fires when the editor is first receives the focus. Any insertion must wait
51168 * until after this event.
51169 * @param {HtmlEditor} this
51173 * @event beforesync
51174 * Fires before the textarea is updated with content from the editor iframe. Return false
51175 * to cancel the sync.
51176 * @param {HtmlEditor} this
51177 * @param {String} html
51181 * @event beforepush
51182 * Fires before the iframe editor is updated with content from the textarea. Return false
51183 * to cancel the push.
51184 * @param {HtmlEditor} this
51185 * @param {String} html
51190 * Fires when the textarea is updated with content from the editor iframe.
51191 * @param {HtmlEditor} this
51192 * @param {String} html
51197 * Fires when the iframe editor is updated with content from the textarea.
51198 * @param {HtmlEditor} this
51199 * @param {String} html
51203 * @event editmodechange
51204 * Fires when the editor switches edit modes
51205 * @param {HtmlEditor} this
51206 * @param {Boolean} sourceEdit True if source edit, false if standard editing.
51208 editmodechange: true,
51210 * @event editorevent
51211 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
51212 * @param {HtmlEditor} this
51216 * @event firstfocus
51217 * Fires when on first focus - needed by toolbars..
51218 * @param {HtmlEditor} this
51223 * Auto save the htmlEditor value as a file into Events
51224 * @param {HtmlEditor} this
51228 * @event savedpreview
51229 * preview the saved version of htmlEditor
51230 * @param {HtmlEditor} this
51232 savedpreview: true,
51235 * @event stylesheetsclick
51236 * Fires when press the Sytlesheets button
51237 * @param {Roo.HtmlEditorCore} this
51239 stylesheetsclick: true,
51242 * Fires when press user pastes into the editor
51243 * @param {Roo.HtmlEditorCore} this
51247 this.defaultAutoCreate = {
51249 style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
51250 autocomplete: "new-password"
51255 * Protected method that will not generally be called directly. It
51256 * is called when the editor creates its toolbar. Override this method if you need to
51257 * add custom toolbar buttons.
51258 * @param {HtmlEditor} editor
51260 createToolbar : function(editor){
51261 Roo.log("create toolbars");
51262 if (!editor.toolbars || !editor.toolbars.length) {
51263 editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
51266 for (var i =0 ; i < editor.toolbars.length;i++) {
51267 editor.toolbars[i] = Roo.factory(
51268 typeof(editor.toolbars[i]) == 'string' ?
51269 { xtype: editor.toolbars[i]} : editor.toolbars[i],
51270 Roo.form.HtmlEditor);
51271 editor.toolbars[i].init(editor);
51277 * get the Context selected node
51278 * @returns {DomElement|boolean} selected node if active or false if none
51281 getSelectedNode : function()
51283 if (this.toolbars.length < 2 || !this.toolbars[1].tb) {
51286 return this.toolbars[1].tb.selectedNode;
51290 onRender : function(ct, position)
51293 Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
51295 this.wrap = this.el.wrap({
51296 cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
51299 this.editorcore.onRender(ct, position);
51301 if (this.resizable) {
51302 this.resizeEl = new Roo.Resizable(this.wrap, {
51306 minHeight : this.height,
51307 height: this.height,
51308 handles : this.resizable,
51311 resize : function(r, w, h) {
51312 _t.onResize(w,h); // -something
51318 this.createToolbar(this);
51322 this.setSize(this.wrap.getSize());
51324 if (this.resizeEl) {
51325 this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
51326 // should trigger onReize..
51329 this.keyNav = new Roo.KeyNav(this.el, {
51331 "tab" : function(e){
51332 e.preventDefault();
51334 var value = this.getValue();
51336 var start = this.el.dom.selectionStart;
51337 var end = this.el.dom.selectionEnd;
51341 this.setValue(value.substring(0, start) + "\t" + value.substring(end));
51342 this.el.dom.setSelectionRange(end + 1, end + 1);
51346 var f = value.substring(0, start).split("\t");
51348 if(f.pop().length != 0){
51352 this.setValue(f.join("\t") + value.substring(end));
51353 this.el.dom.setSelectionRange(start - 1, start - 1);
51357 "home" : function(e){
51358 e.preventDefault();
51360 var curr = this.el.dom.selectionStart;
51361 var lines = this.getValue().split("\n");
51368 this.el.dom.setSelectionRange(0, 0);
51374 for (var i = 0; i < lines.length;i++) {
51375 pos += lines[i].length;
51385 pos -= lines[i].length;
51391 this.el.dom.setSelectionRange(pos, pos);
51395 this.el.dom.selectionStart = pos;
51396 this.el.dom.selectionEnd = curr;
51399 "end" : function(e){
51400 e.preventDefault();
51402 var curr = this.el.dom.selectionStart;
51403 var lines = this.getValue().split("\n");
51410 this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
51416 for (var i = 0; i < lines.length;i++) {
51418 pos += lines[i].length;
51432 this.el.dom.setSelectionRange(pos, pos);
51436 this.el.dom.selectionStart = curr;
51437 this.el.dom.selectionEnd = pos;
51442 doRelay : function(foo, bar, hname){
51443 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
51449 // if(this.autosave && this.w){
51450 // this.autoSaveFn = setInterval(this.autosave, 1000);
51455 onResize : function(w, h)
51457 Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
51462 if(typeof w == 'number'){
51463 var aw = w - this.wrap.getFrameWidth('lr');
51464 this.el.setWidth(this.adjustWidth('textarea', aw));
51467 if(typeof h == 'number'){
51469 for (var i =0; i < this.toolbars.length;i++) {
51470 // fixme - ask toolbars for heights?
51471 tbh += this.toolbars[i].tb.el.getHeight();
51472 if (this.toolbars[i].footer) {
51473 tbh += this.toolbars[i].footer.el.getHeight();
51480 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
51481 ah -= 5; // knock a few pixes off for look..
51483 this.el.setHeight(this.adjustWidth('textarea', ah));
51487 Roo.log('onResize:' + [w,h,ew,eh].join(',') );
51488 this.editorcore.onResize(ew,eh);
51493 * Toggles the editor between standard and source edit mode.
51494 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
51496 toggleSourceEdit : function(sourceEditMode)
51498 this.editorcore.toggleSourceEdit(sourceEditMode);
51500 if(this.editorcore.sourceEditMode){
51501 Roo.log('editor - showing textarea');
51504 // Roo.log(this.syncValue());
51505 this.editorcore.syncValue();
51506 this.el.removeClass('x-hidden');
51507 this.el.dom.removeAttribute('tabIndex');
51509 this.el.dom.scrollTop = 0;
51512 for (var i = 0; i < this.toolbars.length; i++) {
51513 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
51514 this.toolbars[i].tb.hide();
51515 this.toolbars[i].footer.hide();
51520 Roo.log('editor - hiding textarea');
51522 // Roo.log(this.pushValue());
51523 this.editorcore.pushValue();
51525 this.el.addClass('x-hidden');
51526 this.el.dom.setAttribute('tabIndex', -1);
51528 for (var i = 0; i < this.toolbars.length; i++) {
51529 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
51530 this.toolbars[i].tb.show();
51531 this.toolbars[i].footer.show();
51535 //this.deferFocus();
51538 this.setSize(this.wrap.getSize());
51539 this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
51541 this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
51544 // private (for BoxComponent)
51545 adjustSize : Roo.BoxComponent.prototype.adjustSize,
51547 // private (for BoxComponent)
51548 getResizeEl : function(){
51552 // private (for BoxComponent)
51553 getPositionEl : function(){
51558 initEvents : function(){
51559 this.originalValue = this.getValue();
51563 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
51566 markInvalid : Roo.emptyFn,
51568 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
51571 clearInvalid : Roo.emptyFn,
51573 setValue : function(v){
51574 Roo.form.HtmlEditor.superclass.setValue.call(this, v);
51575 this.editorcore.pushValue();
51579 * update the language in the body - really done by core
51580 * @param {String} language - eg. en / ar / zh-CN etc..
51582 updateLanguage : function(lang)
51584 this.language = lang;
51585 this.editorcore.language = lang;
51586 this.editorcore.updateLanguage();
51590 deferFocus : function(){
51591 this.focus.defer(10, this);
51595 focus : function(){
51596 this.editorcore.focus();
51602 onDestroy : function(){
51608 for (var i =0; i < this.toolbars.length;i++) {
51609 // fixme - ask toolbars for heights?
51610 this.toolbars[i].onDestroy();
51613 this.wrap.dom.innerHTML = '';
51614 this.wrap.remove();
51619 onFirstFocus : function(){
51620 //Roo.log("onFirstFocus");
51621 this.editorcore.onFirstFocus();
51622 for (var i =0; i < this.toolbars.length;i++) {
51623 this.toolbars[i].onFirstFocus();
51629 syncValue : function()
51631 this.editorcore.syncValue();
51634 pushValue : function()
51636 this.editorcore.pushValue();
51639 setStylesheets : function(stylesheets)
51641 this.editorcore.setStylesheets(stylesheets);
51644 removeStylesheets : function()
51646 this.editorcore.removeStylesheets();
51650 // hide stuff that is not compatible
51664 * @event specialkey
51668 * @cfg {String} fieldClass @hide
51671 * @cfg {String} focusClass @hide
51674 * @cfg {String} autoCreate @hide
51677 * @cfg {String} inputType @hide
51680 * @cfg {String} invalidClass @hide
51683 * @cfg {String} invalidText @hide
51686 * @cfg {String} msgFx @hide
51689 * @cfg {String} validateOnBlur @hide
51695 * Ext JS Library 1.1.1
51696 * Copyright(c) 2006-2007, Ext JS, LLC.
51702 * @class Roo.form.HtmlEditor.ToolbarStandard
51707 new Roo.form.HtmlEditor({
51710 new Roo.form.HtmlEditorToolbar1({
51711 disable : { fonts: 1 , format: 1, ..., ... , ...],
51717 * @cfg {Object} disable List of elements to disable..
51718 * @cfg {Roo.Toolbar.Item|Roo.Toolbar.Button|Roo.Toolbar.SplitButton|Roo.form.Field} btns[] List of additional buttons.
51722 * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
51725 Roo.form.HtmlEditor.ToolbarStandard = function(config)
51728 Roo.apply(this, config);
51730 // default disabled, based on 'good practice'..
51731 this.disable = this.disable || {};
51732 Roo.applyIf(this.disable, {
51735 specialElements : true
51739 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
51740 // dont call parent... till later.
51743 Roo.form.HtmlEditor.ToolbarStandard.prototype = {
51750 editorcore : false,
51752 * @cfg {Object} disable List of toolbar elements to disable
51759 * @cfg {String} createLinkText The default text for the create link prompt
51761 createLinkText : 'Please enter the URL for the link:',
51763 * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
51765 defaultLinkValue : 'http:/'+'/',
51769 * @cfg {Array} fontFamilies An array of available font families
51787 // "á" , ?? a acute?
51792 "°" // , // degrees
51794 // "é" , // e ecute
51795 // "ú" , // u ecute?
51798 specialElements : [
51800 text: "Insert Table",
51803 ihtml : '<table><tr><td>Cell</td></tr></table>'
51807 text: "Insert Image",
51810 ihtml : '<img src="about:blank"/>'
51819 "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password",
51820 "input:submit", "input:button", "select", "textarea", "label" ],
51823 ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"],
51825 ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
51834 * @cfg {String} defaultFont default font to use.
51836 defaultFont: 'tahoma',
51838 fontSelect : false,
51841 formatCombo : false,
51843 init : function(editor)
51845 this.editor = editor;
51846 this.editorcore = editor.editorcore ? editor.editorcore : editor;
51847 var editorcore = this.editorcore;
51851 var fid = editorcore.frameId;
51853 function btn(id, toggle, handler){
51854 var xid = fid + '-'+ id ;
51858 cls : 'x-btn-icon x-edit-'+id,
51859 enableToggle:toggle !== false,
51860 scope: _t, // was editor...
51861 handler:handler||_t.relayBtnCmd,
51862 clickEvent:'mousedown',
51863 tooltip: etb.buttonTips[id] || undefined, ///tips ???
51870 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
51872 // stop form submits
51873 tb.el.on('click', function(e){
51874 e.preventDefault(); // what does this do?
51877 if(!this.disable.font) { // && !Roo.isSafari){
51878 /* why no safari for fonts
51879 editor.fontSelect = tb.el.createChild({
51882 cls:'x-font-select',
51883 html: this.createFontOptions()
51886 editor.fontSelect.on('change', function(){
51887 var font = editor.fontSelect.dom.value;
51888 editor.relayCmd('fontname', font);
51889 editor.deferFocus();
51893 editor.fontSelect.dom,
51899 if(!this.disable.formats){
51900 this.formatCombo = new Roo.form.ComboBox({
51901 store: new Roo.data.SimpleStore({
51904 data : this.formats // from states.js
51908 //autoCreate : {tag: "div", size: "20"},
51909 displayField:'tag',
51913 triggerAction: 'all',
51914 emptyText:'Add tag',
51915 selectOnFocus:true,
51918 'select': function(c, r, i) {
51919 editorcore.insertTag(r.get('tag'));
51925 tb.addField(this.formatCombo);
51929 if(!this.disable.format){
51934 btn('strikethrough')
51937 if(!this.disable.fontSize){
51942 btn('increasefontsize', false, editorcore.adjustFont),
51943 btn('decreasefontsize', false, editorcore.adjustFont)
51948 if(!this.disable.colors){
51951 id:editorcore.frameId +'-forecolor',
51952 cls:'x-btn-icon x-edit-forecolor',
51953 clickEvent:'mousedown',
51954 tooltip: this.buttonTips['forecolor'] || undefined,
51956 menu : new Roo.menu.ColorMenu({
51957 allowReselect: true,
51958 focus: Roo.emptyFn,
51961 selectHandler: function(cp, color){
51962 editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
51963 editor.deferFocus();
51966 clickEvent:'mousedown'
51969 id:editorcore.frameId +'backcolor',
51970 cls:'x-btn-icon x-edit-backcolor',
51971 clickEvent:'mousedown',
51972 tooltip: this.buttonTips['backcolor'] || undefined,
51974 menu : new Roo.menu.ColorMenu({
51975 focus: Roo.emptyFn,
51978 allowReselect: true,
51979 selectHandler: function(cp, color){
51981 editorcore.execCmd('useCSS', false);
51982 editorcore.execCmd('hilitecolor', color);
51983 editorcore.execCmd('useCSS', true);
51984 editor.deferFocus();
51986 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor',
51987 Roo.isSafari || Roo.isIE ? '#'+color : color);
51988 editor.deferFocus();
51992 clickEvent:'mousedown'
51997 // now add all the items...
52000 if(!this.disable.alignments){
52003 btn('justifyleft'),
52004 btn('justifycenter'),
52005 btn('justifyright')
52009 //if(!Roo.isSafari){
52010 if(!this.disable.links){
52013 btn('createlink', false, this.createLink) /// MOVE TO HERE?!!?!?!?!
52017 if(!this.disable.lists){
52020 btn('insertorderedlist'),
52021 btn('insertunorderedlist')
52024 if(!this.disable.sourceEdit){
52027 btn('sourceedit', true, function(btn){
52028 this.toggleSourceEdit(btn.pressed);
52035 // special menu.. - needs to be tidied up..
52036 if (!this.disable.special) {
52039 cls: 'x-edit-none',
52045 for (var i =0; i < this.specialChars.length; i++) {
52046 smenu.menu.items.push({
52048 html: this.specialChars[i],
52049 handler: function(a,b) {
52050 editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
52051 //editor.insertAtCursor(a.html);
52065 if (!this.disable.cleanStyles) {
52067 cls: 'x-btn-icon x-btn-clear',
52073 for (var i =0; i < this.cleanStyles.length; i++) {
52074 cmenu.menu.items.push({
52075 actiontype : this.cleanStyles[i],
52076 html: 'Remove ' + this.cleanStyles[i],
52077 handler: function(a,b) {
52080 var c = Roo.get(editorcore.doc.body);
52081 c.select('[style]').each(function(s) {
52082 s.dom.style.removeProperty(a.actiontype);
52084 editorcore.syncValue();
52089 cmenu.menu.items.push({
52090 actiontype : 'tablewidths',
52091 html: 'Remove Table Widths',
52092 handler: function(a,b) {
52093 editorcore.cleanTableWidths();
52094 editorcore.syncValue();
52098 cmenu.menu.items.push({
52099 actiontype : 'word',
52100 html: 'Remove MS Word Formating',
52101 handler: function(a,b) {
52102 editorcore.cleanWord();
52103 editorcore.syncValue();
52108 cmenu.menu.items.push({
52109 actiontype : 'all',
52110 html: 'Remove All Styles',
52111 handler: function(a,b) {
52113 var c = Roo.get(editorcore.doc.body);
52114 c.select('[style]').each(function(s) {
52115 s.dom.removeAttribute('style');
52117 editorcore.syncValue();
52122 cmenu.menu.items.push({
52123 actiontype : 'all',
52124 html: 'Remove All CSS Classes',
52125 handler: function(a,b) {
52127 var c = Roo.get(editorcore.doc.body);
52128 c.select('[class]').each(function(s) {
52129 s.dom.removeAttribute('class');
52131 editorcore.cleanWord();
52132 editorcore.syncValue();
52137 cmenu.menu.items.push({
52138 actiontype : 'tidy',
52139 html: 'Tidy HTML Source',
52140 handler: function(a,b) {
52141 new Roo.htmleditor.Tidy(editorcore.doc.body);
52142 editorcore.syncValue();
52151 if (!this.disable.specialElements) {
52154 cls: 'x-edit-none',
52159 for (var i =0; i < this.specialElements.length; i++) {
52160 semenu.menu.items.push(
52162 handler: function(a,b) {
52163 editor.insertAtCursor(this.ihtml);
52165 }, this.specialElements[i])
52177 for(var i =0; i< this.btns.length;i++) {
52178 var b = Roo.factory(this.btns[i],this.btns[i].xns || Roo.form);
52179 b.cls = 'x-edit-none';
52181 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
52182 b.cls += ' x-init-enable';
52185 b.scope = editorcore;
52193 // disable everything...
52195 this.tb.items.each(function(item){
52198 item.id != editorcore.frameId+ '-sourceedit' &&
52199 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
52205 this.rendered = true;
52207 // the all the btns;
52208 editor.on('editorevent', this.updateToolbar, this);
52209 // other toolbars need to implement this..
52210 //editor.on('editmodechange', this.updateToolbar, this);
52214 relayBtnCmd : function(btn) {
52215 this.editorcore.relayCmd(btn.cmd);
52217 // private used internally
52218 createLink : function(){
52219 //Roo.log("create link?");
52220 var ec = this.editorcore;
52221 var ar = ec.getAllAncestors();
52223 for(var i = 0;i< ar.length;i++) {
52224 if (ar[i] && ar[i].nodeName == 'A') {
52232 Roo.MessageBox.show({
52233 title : "Add / Edit Link URL",
52234 msg : "Enter the url for the link",
52235 buttons: Roo.MessageBox.OKCANCEL,
52236 fn: function(btn, url){
52240 if(url && url != 'http:/'+'/'){
52242 n.setAttribute('href', url);
52244 ec.relayCmd('createlink', url);
52250 //multiline: multiline,
52252 value : n ? n.getAttribute('href') : ''
52256 }).defer(100, this); // we have to defer this , otherwise the mouse click gives focus to the main window.
52262 * Protected method that will not generally be called directly. It triggers
52263 * a toolbar update by reading the markup state of the current selection in the editor.
52265 updateToolbar: function(){
52267 if(!this.editorcore.activated){
52268 this.editor.onFirstFocus();
52272 var btns = this.tb.items.map,
52273 doc = this.editorcore.doc,
52274 frameId = this.editorcore.frameId;
52276 if(!this.disable.font && !Roo.isSafari){
52278 var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
52279 if(name != this.fontSelect.dom.value){
52280 this.fontSelect.dom.value = name;
52284 if(!this.disable.format){
52285 btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
52286 btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
52287 btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
52288 btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
52290 if(!this.disable.alignments){
52291 btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
52292 btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
52293 btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
52295 if(!Roo.isSafari && !this.disable.lists){
52296 btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
52297 btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
52300 var ans = this.editorcore.getAllAncestors();
52301 if (this.formatCombo) {
52304 var store = this.formatCombo.store;
52305 this.formatCombo.setValue("");
52306 for (var i =0; i < ans.length;i++) {
52307 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
52309 this.formatCombo.setValue(ans[i].tagName.toLowerCase());
52317 // hides menus... - so this cant be on a menu...
52318 Roo.menu.MenuMgr.hideAll();
52320 //this.editorsyncValue();
52324 createFontOptions : function(){
52325 var buf = [], fs = this.fontFamilies, ff, lc;
52329 for(var i = 0, len = fs.length; i< len; i++){
52331 lc = ff.toLowerCase();
52333 '<option value="',lc,'" style="font-family:',ff,';"',
52334 (this.defaultFont == lc ? ' selected="true">' : '>'),
52339 return buf.join('');
52342 toggleSourceEdit : function(sourceEditMode){
52344 Roo.log("toolbar toogle");
52345 if(sourceEditMode === undefined){
52346 sourceEditMode = !this.sourceEditMode;
52348 this.sourceEditMode = sourceEditMode === true;
52349 var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
52350 // just toggle the button?
52351 if(btn.pressed !== this.sourceEditMode){
52352 btn.toggle(this.sourceEditMode);
52356 if(sourceEditMode){
52357 Roo.log("disabling buttons");
52358 this.tb.items.each(function(item){
52359 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
52365 Roo.log("enabling buttons");
52366 if(this.editorcore.initialized){
52367 this.tb.items.each(function(item){
52370 // initialize 'blocks'
52371 Roo.each(Roo.get(this.editorcore.doc.body).query('*[data-block]'), function(e) {
52372 Roo.htmleditor.Block.factory(e).updateElement(e);
52378 Roo.log("calling toggole on editor");
52379 // tell the editor that it's been pressed..
52380 this.editor.toggleSourceEdit(sourceEditMode);
52384 * Object collection of toolbar tooltips for the buttons in the editor. The key
52385 * is the command id associated with that button and the value is a valid QuickTips object.
52390 title: 'Bold (Ctrl+B)',
52391 text: 'Make the selected text bold.',
52392 cls: 'x-html-editor-tip'
52395 title: 'Italic (Ctrl+I)',
52396 text: 'Make the selected text italic.',
52397 cls: 'x-html-editor-tip'
52405 title: 'Bold (Ctrl+B)',
52406 text: 'Make the selected text bold.',
52407 cls: 'x-html-editor-tip'
52410 title: 'Italic (Ctrl+I)',
52411 text: 'Make the selected text italic.',
52412 cls: 'x-html-editor-tip'
52415 title: 'Underline (Ctrl+U)',
52416 text: 'Underline the selected text.',
52417 cls: 'x-html-editor-tip'
52420 title: 'Strikethrough',
52421 text: 'Strikethrough the selected text.',
52422 cls: 'x-html-editor-tip'
52424 increasefontsize : {
52425 title: 'Grow Text',
52426 text: 'Increase the font size.',
52427 cls: 'x-html-editor-tip'
52429 decreasefontsize : {
52430 title: 'Shrink Text',
52431 text: 'Decrease the font size.',
52432 cls: 'x-html-editor-tip'
52435 title: 'Text Highlight Color',
52436 text: 'Change the background color of the selected text.',
52437 cls: 'x-html-editor-tip'
52440 title: 'Font Color',
52441 text: 'Change the color of the selected text.',
52442 cls: 'x-html-editor-tip'
52445 title: 'Align Text Left',
52446 text: 'Align text to the left.',
52447 cls: 'x-html-editor-tip'
52450 title: 'Center Text',
52451 text: 'Center text in the editor.',
52452 cls: 'x-html-editor-tip'
52455 title: 'Align Text Right',
52456 text: 'Align text to the right.',
52457 cls: 'x-html-editor-tip'
52459 insertunorderedlist : {
52460 title: 'Bullet List',
52461 text: 'Start a bulleted list.',
52462 cls: 'x-html-editor-tip'
52464 insertorderedlist : {
52465 title: 'Numbered List',
52466 text: 'Start a numbered list.',
52467 cls: 'x-html-editor-tip'
52470 title: 'Hyperlink',
52471 text: 'Make the selected text a hyperlink.',
52472 cls: 'x-html-editor-tip'
52475 title: 'Source Edit',
52476 text: 'Switch to source editing mode.',
52477 cls: 'x-html-editor-tip'
52481 onDestroy : function(){
52484 this.tb.items.each(function(item){
52486 item.menu.removeAll();
52488 item.menu.el.destroy();
52496 onFirstFocus: function() {
52497 this.tb.items.each(function(item){
52506 // <script type="text/javascript">
52509 * Ext JS Library 1.1.1
52510 * Copyright(c) 2006-2007, Ext JS, LLC.
52517 * @class Roo.form.HtmlEditor.ToolbarContext
52522 new Roo.form.HtmlEditor({
52525 { xtype: 'ToolbarStandard', styles : {} }
52526 { xtype: 'ToolbarContext', disable : {} }
52532 * @config : {Object} disable List of elements to disable.. (not done yet.)
52533 * @config : {Object} styles Map of styles available.
52537 Roo.form.HtmlEditor.ToolbarContext = function(config)
52540 Roo.apply(this, config);
52541 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
52542 // dont call parent... till later.
52543 this.styles = this.styles || {};
52548 Roo.form.HtmlEditor.ToolbarContext.types = {
52563 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
52589 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
52660 name : 'selectoptions',
52666 // should we really allow this??
52667 // should this just be
52684 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
52685 Roo.form.HtmlEditor.ToolbarContext.stores = false;
52687 Roo.form.HtmlEditor.ToolbarContext.options = {
52689 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
52690 [ 'Courier New', 'Courier New'],
52691 [ 'Tahoma', 'Tahoma'],
52692 [ 'Times New Roman,serif', 'Times'],
52693 [ 'Verdana','Verdana' ]
52697 // fixme - these need to be configurable..
52700 //Roo.form.HtmlEditor.ToolbarContext.types
52703 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype, {
52710 editorcore : false,
52712 * @cfg {Object} disable List of toolbar elements to disable
52717 * @cfg {Object} styles List of styles
52718 * eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] }
52720 * These must be defined in the page, so they get rendered correctly..
52731 init : function(editor)
52733 this.editor = editor;
52734 this.editorcore = editor.editorcore ? editor.editorcore : editor;
52735 var editorcore = this.editorcore;
52737 var fid = editorcore.frameId;
52739 function btn(id, toggle, handler){
52740 var xid = fid + '-'+ id ;
52744 cls : 'x-btn-icon x-edit-'+id,
52745 enableToggle:toggle !== false,
52746 scope: editorcore, // was editor...
52747 handler:handler||editorcore.relayBtnCmd,
52748 clickEvent:'mousedown',
52749 tooltip: etb.buttonTips[id] || undefined, ///tips ???
52753 // create a new element.
52754 var wdiv = editor.wrap.createChild({
52756 }, editor.wrap.dom.firstChild.nextSibling, true);
52758 // can we do this more than once??
52760 // stop form submits
52763 // disable everything...
52764 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
52765 this.toolbars = {};
52766 // block toolbars are built in updateToolbar when needed.
52767 for (var i in ty) {
52769 this.toolbars[i] = this.buildToolbar(ty[i],i);
52771 this.tb = this.toolbars.BODY;
52773 this.buildFooter();
52774 this.footer.show();
52775 editor.on('hide', function( ) { this.footer.hide() }, this);
52776 editor.on('show', function( ) { this.footer.show() }, this);
52779 this.rendered = true;
52781 // the all the btns;
52782 editor.on('editorevent', this.updateToolbar, this);
52783 // other toolbars need to implement this..
52784 //editor.on('editmodechange', this.updateToolbar, this);
52790 * Protected method that will not generally be called directly. It triggers
52791 * a toolbar update by reading the markup state of the current selection in the editor.
52793 * Note you can force an update by calling on('editorevent', scope, false)
52795 updateToolbar: function(editor ,ev, sel)
52799 ev.stopEvent(); // se if we can stop this looping with mutiple events.
52803 // capture mouse up - this is handy for selecting images..
52804 // perhaps should go somewhere else...
52805 if(!this.editorcore.activated){
52806 this.editor.onFirstFocus();
52809 //Roo.log(ev ? ev.target : 'NOTARGET');
52812 // http://developer.yahoo.com/yui/docs/simple-editor.js.html
52813 // selectNode - might want to handle IE?
52818 (ev.type == 'mouseup' || ev.type == 'click' ) &&
52819 ev.target && ev.target.tagName != 'BODY' ) { // && ev.target.tagName == 'IMG') {
52820 // they have click on an image...
52821 // let's see if we can change the selection...
52824 // this triggers looping?
52825 //this.editorcore.selectNode(sel);
52829 // this forces an id..
52830 Array.from(this.editorcore.doc.body.querySelectorAll('.roo-ed-selection')).forEach(function(e) {
52831 e.classList.remove('roo-ed-selection');
52833 //Roo.select('.roo-ed-selection', false, this.editorcore.doc).removeClass('roo-ed-selection');
52834 //Roo.get(node).addClass('roo-ed-selection');
52836 //var updateFooter = sel ? false : true;
52839 var ans = this.editorcore.getAllAncestors();
52842 var ty = Roo.form.HtmlEditor.ToolbarContext.types;
52845 sel = ans.length ? (ans[0] ? ans[0] : ans[1]) : this.editorcore.doc.body;
52846 sel = sel ? sel : this.editorcore.doc.body;
52847 sel = sel.tagName.length ? sel : this.editorcore.doc.body;
52851 var tn = sel.tagName.toUpperCase();
52852 var lastSel = this.tb.selectedNode;
52853 this.tb.selectedNode = sel;
52854 var left_label = tn;
52856 // ok see if we are editing a block?
52859 // you are not actually selecting the block.
52860 if (sel && sel.hasAttribute('data-block')) {
52862 } else if (sel && sel.closest('[data-block]')) {
52864 db = sel.closest('[data-block]');
52865 //var cepar = sel.closest('[contenteditable=true]');
52866 //if (db && cepar && cepar.tagName != 'BODY') {
52867 // db = false; // we are inside an editable block.. = not sure how we are going to handle nested blocks!?
52873 //if (db && !sel.hasAttribute('contenteditable') && sel.getAttribute('contenteditable') != 'true' ) {
52874 if (db && this.editorcore.enableBlocks) {
52875 block = Roo.htmleditor.Block.factory(db);
52880 db.classList.length > 0 ? db.className + ' ' : ''
52881 ) + 'roo-ed-selection';
52883 // since we removed it earlier... its not there..
52884 tn = 'BLOCK.' + db.getAttribute('data-block');
52886 //this.editorcore.selectNode(db);
52887 if (typeof(this.toolbars[tn]) == 'undefined') {
52888 this.toolbars[tn] = this.buildToolbar( false ,tn ,block.friendly_name, block);
52890 this.toolbars[tn].selectedNode = db;
52891 left_label = block.friendly_name;
52892 ans = this.editorcore.getAllAncestors();
52900 if (this.tb.name == tn && lastSel == this.tb.selectedNode && ev !== false) {
52901 return; // no change?
52907 ///console.log("show: " + tn);
52908 this.tb = typeof(this.toolbars[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
52912 this.tb.items.first().el.innerHTML = left_label + ': ';
52915 // update attributes
52916 if (block && this.tb.fields) {
52918 this.tb.fields.each(function(e) {
52919 e.setValue(block[e.name]);
52923 } else if (this.tb.fields && this.tb.selectedNode) {
52924 this.tb.fields.each( function(e) {
52926 e.setValue(this.tb.selectedNode.style[e.stylename]);
52929 e.setValue(this.tb.selectedNode.getAttribute(e.attrname));
52931 this.updateToolbarStyles(this.tb.selectedNode);
52936 Roo.menu.MenuMgr.hideAll();
52941 // update the footer
52943 this.updateFooter(ans);
52947 updateToolbarStyles : function(sel)
52949 var hasStyles = false;
52950 for(var i in this.styles) {
52956 if (hasStyles && this.tb.hasStyles) {
52957 var st = this.tb.fields.item(0);
52959 st.store.removeAll();
52960 var cn = sel.className.split(/\s+/);
52963 if (this.styles['*']) {
52965 Roo.each(this.styles['*'], function(v) {
52966 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
52969 if (this.styles[tn]) {
52970 Roo.each(this.styles[tn], function(v) {
52971 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
52975 st.store.loadData(avs);
52982 updateFooter : function(ans)
52985 if (ans === false) {
52986 this.footDisp.dom.innerHTML = '';
52990 this.footerEls = ans.reverse();
52991 Roo.each(this.footerEls, function(a,i) {
52992 if (!a) { return; }
52993 html += html.length ? ' > ' : '';
52995 html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
53000 var sz = this.footDisp.up('td').getSize();
53001 this.footDisp.dom.style.width = (sz.width -10) + 'px';
53002 this.footDisp.dom.style.marginLeft = '5px';
53004 this.footDisp.dom.style.overflow = 'hidden';
53006 this.footDisp.dom.innerHTML = html;
53013 onDestroy : function(){
53016 this.tb.items.each(function(item){
53018 item.menu.removeAll();
53020 item.menu.el.destroy();
53028 onFirstFocus: function() {
53029 // need to do this for all the toolbars..
53030 this.tb.items.each(function(item){
53034 buildToolbar: function(tlist, nm, friendly_name, block)
53036 var editor = this.editor;
53037 var editorcore = this.editorcore;
53038 // create a new element.
53039 var wdiv = editor.wrap.createChild({
53041 }, editor.wrap.dom.firstChild.nextSibling, true);
53044 var tb = new Roo.Toolbar(wdiv);
53045 ///this.tb = tb; // << this sets the active toolbar..
53046 if (tlist === false && block) {
53047 tlist = block.contextMenu(this);
53050 tb.hasStyles = false;
53053 tb.add((typeof(friendly_name) == 'undefined' ? nm : friendly_name) + ": ");
53055 var styles = Array.from(this.styles);
53059 if (styles && styles.length) {
53060 tb.hasStyles = true;
53061 // this needs a multi-select checkbox...
53062 tb.addField( new Roo.form.ComboBox({
53063 store: new Roo.data.SimpleStore({
53065 fields: ['val', 'selected'],
53068 name : '-roo-edit-className',
53069 attrname : 'className',
53070 displayField: 'val',
53074 triggerAction: 'all',
53075 emptyText:'Select Style',
53076 selectOnFocus:true,
53079 'select': function(c, r, i) {
53080 // initial support only for on class per el..
53081 tb.selectedNode.className = r ? r.get('val') : '';
53082 editorcore.syncValue();
53089 var tbc = Roo.form.HtmlEditor.ToolbarContext;
53092 for (var i = 0; i < tlist.length; i++) {
53094 // newer versions will use xtype cfg to create menus.
53095 if (typeof(tlist[i].xtype) != 'undefined') {
53097 tb[typeof(tlist[i].name)== 'undefined' ? 'add' : 'addField'](Roo.factory(tlist[i]));
53103 var item = tlist[i];
53104 tb.add(item.title + ": ");
53107 //optname == used so you can configure the options available..
53108 var opts = item.opts ? item.opts : false;
53109 if (item.optname) { // use the b
53110 opts = Roo.form.HtmlEditor.ToolbarContext.options[item.optname];
53115 // opts == pulldown..
53116 tb.addField( new Roo.form.ComboBox({
53117 store: typeof(tbc.stores[i]) != 'undefined' ? Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
53119 fields: ['val', 'display'],
53122 name : '-roo-edit-' + tlist[i].name,
53124 attrname : tlist[i].name,
53125 stylename : item.style ? item.style : false,
53127 displayField: item.displayField ? item.displayField : 'val',
53128 valueField : 'val',
53130 mode: typeof(tbc.stores[tlist[i].name]) != 'undefined' ? 'remote' : 'local',
53132 triggerAction: 'all',
53133 emptyText:'Select',
53134 selectOnFocus:true,
53135 width: item.width ? item.width : 130,
53137 'select': function(c, r, i) {
53141 tb.selectedNode.style[c.stylename] = r.get('val');
53142 editorcore.syncValue();
53146 tb.selectedNode.removeAttribute(c.attrname);
53147 editorcore.syncValue();
53150 tb.selectedNode.setAttribute(c.attrname, r.get('val'));
53151 editorcore.syncValue();
53160 tb.addField( new Roo.form.TextField({
53163 //allowBlank:false,
53169 tb.addField( new Roo.form.TextField({
53170 name: '-roo-edit-' + tlist[i].name,
53171 attrname : tlist[i].name,
53177 'change' : function(f, nv, ov) {
53180 tb.selectedNode.setAttribute(f.attrname, nv);
53181 editorcore.syncValue();
53189 var show_delete = !block || block.deleteTitle !== false;
53191 show_delete = false;
53195 text: 'Stylesheets',
53198 click : function ()
53200 _this.editor.fireEvent('stylesheetsclick', _this.editor);
53209 text: block && block.deleteTitle ? block.deleteTitle : 'Remove Block or Formating', // remove the tag, and puts the children outside...
53212 click : function ()
53214 var sn = tb.selectedNode;
53216 sn = Roo.htmleditor.Block.factory(tb.selectedNode).removeNode();
53222 var stn = sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
53223 if (sn.hasAttribute('data-block')) {
53224 stn = sn.nextSibling || sn.previousSibling || sn.parentNode;
53225 sn.parentNode.removeChild(sn);
53227 } else if (sn && sn.tagName != 'BODY') {
53228 // remove and keep parents.
53229 a = new Roo.htmleditor.FilterKeepChildren({tag : false});
53234 var range = editorcore.createRange();
53236 range.setStart(stn,0);
53237 range.setEnd(stn,0);
53238 var selection = editorcore.getSelection();
53239 selection.removeAllRanges();
53240 selection.addRange(range);
53243 //_this.updateToolbar(null, null, pn);
53244 _this.updateToolbar(null, null, null);
53245 _this.updateFooter(false);
53256 tb.el.on('click', function(e){
53257 e.preventDefault(); // what does this do?
53259 tb.el.setVisibilityMode( Roo.Element.DISPLAY);
53262 // dont need to disable them... as they will get hidden
53267 buildFooter : function()
53270 var fel = this.editor.wrap.createChild();
53271 this.footer = new Roo.Toolbar(fel);
53272 // toolbar has scrolly on left / right?
53273 var footDisp= new Roo.Toolbar.Fill();
53279 handler : function() {
53280 _t.footDisp.scrollTo('left',0,true)
53284 this.footer.add( footDisp );
53289 handler : function() {
53291 _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
53295 var fel = Roo.get(footDisp.el);
53296 fel.addClass('x-editor-context');
53297 this.footDispWrap = fel;
53298 this.footDispWrap.overflow = 'hidden';
53300 this.footDisp = fel.createChild();
53301 this.footDispWrap.on('click', this.onContextClick, this)
53305 // when the footer contect changes
53306 onContextClick : function (ev,dom)
53308 ev.preventDefault();
53309 var cn = dom.className;
53311 if (!cn.match(/x-ed-loc-/)) {
53314 var n = cn.split('-').pop();
53315 var ans = this.footerEls;
53318 this.editorcore.selectNode(sel);
53321 this.updateToolbar(null, null, sel);
53338 * Ext JS Library 1.1.1
53339 * Copyright(c) 2006-2007, Ext JS, LLC.
53341 * Originally Released Under LGPL - original licence link has changed is not relivant.
53344 * <script type="text/javascript">
53348 * @class Roo.form.BasicForm
53349 * @extends Roo.util.Observable
53350 * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
53352 * @param {String/HTMLElement/Roo.Element} el The form element or its id
53353 * @param {Object} config Configuration options
53355 Roo.form.BasicForm = function(el, config){
53356 this.allItems = [];
53357 this.childForms = [];
53358 Roo.apply(this, config);
53360 * The Roo.form.Field items in this form.
53361 * @type MixedCollection
53365 this.items = new Roo.util.MixedCollection(false, function(o){
53366 return o.id || (o.id = Roo.id());
53370 * @event beforeaction
53371 * Fires before any action is performed. Return false to cancel the action.
53372 * @param {Form} this
53373 * @param {Action} action The action to be performed
53375 beforeaction: true,
53377 * @event actionfailed
53378 * Fires when an action fails.
53379 * @param {Form} this
53380 * @param {Action} action The action that failed
53382 actionfailed : true,
53384 * @event actioncomplete
53385 * Fires when an action is completed.
53386 * @param {Form} this
53387 * @param {Action} action The action that completed
53389 actioncomplete : true
53394 Roo.form.BasicForm.superclass.constructor.call(this);
53396 Roo.form.BasicForm.popover.apply();
53399 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
53401 * @cfg {String} method
53402 * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
53405 * @cfg {DataReader} reader
53406 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
53407 * This is optional as there is built-in support for processing JSON.
53410 * @cfg {DataReader} errorReader
53411 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
53412 * This is completely optional as there is built-in support for processing JSON.
53415 * @cfg {String} url
53416 * The URL to use for form actions if one isn't supplied in the action options.
53419 * @cfg {Boolean} fileUpload
53420 * Set to true if this form is a file upload.
53424 * @cfg {Object} baseParams
53425 * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
53430 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
53435 activeAction : null,
53438 * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
53439 * or setValues() data instead of when the form was first created.
53441 trackResetOnLoad : false,
53445 * childForms - used for multi-tab forms
53448 childForms : false,
53451 * allItems - full list of fields.
53457 * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
53458 * element by passing it or its id or mask the form itself by passing in true.
53461 waitMsgTarget : false,
53466 disableMask : false,
53469 * @cfg {Boolean} errorMask (true|false) default false
53474 * @cfg {Number} maskOffset Default 100
53479 initEl : function(el){
53480 this.el = Roo.get(el);
53481 this.id = this.el.id || Roo.id();
53482 this.el.on('submit', this.onSubmit, this);
53483 this.el.addClass('x-form');
53487 onSubmit : function(e){
53492 * Returns true if client-side validation on the form is successful.
53495 isValid : function(){
53497 var target = false;
53498 this.items.each(function(f){
53505 if(!target && f.el.isVisible(true)){
53510 if(this.errorMask && !valid){
53511 Roo.form.BasicForm.popover.mask(this, target);
53517 * Returns array of invalid form fields.
53521 invalidFields : function()
53524 this.items.each(function(f){
53537 * DEPRICATED Returns true if any fields in this form have changed since their original load.
53540 isDirty : function(){
53542 this.items.each(function(f){
53552 * Returns true if any fields in this form have changed since their original load. (New version)
53556 hasChanged : function()
53559 this.items.each(function(f){
53560 if(f.hasChanged()){
53569 * Resets all hasChanged to 'false' -
53570 * The old 'isDirty' used 'original value..' however this breaks reset() and a few other things.
53571 * So hasChanged storage is only to be used for this purpose
53574 resetHasChanged : function()
53576 this.items.each(function(f){
53577 f.resetHasChanged();
53584 * Performs a predefined action (submit or load) or custom actions you define on this form.
53585 * @param {String} actionName The name of the action type
53586 * @param {Object} options (optional) The options to pass to the action. All of the config options listed
53587 * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
53588 * accept other config options):
53590 Property Type Description
53591 ---------------- --------------- ----------------------------------------------------------------------------------
53592 url String The url for the action (defaults to the form's url)
53593 method String The form method to use (defaults to the form's method, or POST if not defined)
53594 params String/Object The params to pass (defaults to the form's baseParams, or none if not defined)
53595 clientValidation Boolean Applies to submit only. Pass true to call form.isValid() prior to posting to
53596 validate the form on the client (defaults to false)
53598 * @return {BasicForm} this
53600 doAction : function(action, options){
53601 if(typeof action == 'string'){
53602 action = new Roo.form.Action.ACTION_TYPES[action](this, options);
53604 if(this.fireEvent('beforeaction', this, action) !== false){
53605 this.beforeAction(action);
53606 action.run.defer(100, action);
53612 * Shortcut to do a submit action.
53613 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
53614 * @return {BasicForm} this
53616 submit : function(options){
53617 this.doAction('submit', options);
53622 * Shortcut to do a load action.
53623 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
53624 * @return {BasicForm} this
53626 load : function(options){
53627 this.doAction('load', options);
53632 * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
53633 * @param {Record} record The record to edit
53634 * @return {BasicForm} this
53636 updateRecord : function(record){
53637 record.beginEdit();
53638 var fs = record.fields;
53639 fs.each(function(f){
53640 var field = this.findField(f.name);
53642 record.set(f.name, field.getValue());
53650 * Loads an Roo.data.Record into this form.
53651 * @param {Record} record The record to load
53652 * @return {BasicForm} this
53654 loadRecord : function(record){
53655 this.setValues(record.data);
53660 beforeAction : function(action){
53661 var o = action.options;
53663 if(!this.disableMask) {
53664 if(this.waitMsgTarget === true){
53665 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
53666 }else if(this.waitMsgTarget){
53667 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
53668 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
53670 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
53678 afterAction : function(action, success){
53679 this.activeAction = null;
53680 var o = action.options;
53682 if(!this.disableMask) {
53683 if(this.waitMsgTarget === true){
53685 }else if(this.waitMsgTarget){
53686 this.waitMsgTarget.unmask();
53688 Roo.MessageBox.updateProgress(1);
53689 Roo.MessageBox.hide();
53697 Roo.callback(o.success, o.scope, [this, action]);
53698 this.fireEvent('actioncomplete', this, action);
53702 // failure condition..
53703 // we have a scenario where updates need confirming.
53704 // eg. if a locking scenario exists..
53705 // we look for { errors : { needs_confirm : true }} in the response.
53707 (typeof(action.result) != 'undefined') &&
53708 (typeof(action.result.errors) != 'undefined') &&
53709 (typeof(action.result.errors.needs_confirm) != 'undefined')
53712 Roo.MessageBox.confirm(
53713 "Change requires confirmation",
53714 action.result.errorMsg,
53719 _t.doAction('submit', { params : { _submit_confirmed : 1 } } );
53729 Roo.callback(o.failure, o.scope, [this, action]);
53730 // show an error message if no failed handler is set..
53731 if (!this.hasListener('actionfailed')) {
53732 Roo.MessageBox.alert("Error",
53733 (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
53734 action.result.errorMsg :
53735 "Saving Failed, please check your entries or try again"
53739 this.fireEvent('actionfailed', this, action);
53745 * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
53746 * @param {String} id The value to search for
53749 findField : function(id){
53750 var field = this.items.get(id);
53752 this.items.each(function(f){
53753 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
53759 return field || null;
53763 * Add a secondary form to this one,
53764 * Used to provide tabbed forms. One form is primary, with hidden values
53765 * which mirror the elements from the other forms.
53767 * @param {Roo.form.Form} form to add.
53770 addForm : function(form)
53773 if (this.childForms.indexOf(form) > -1) {
53777 this.childForms.push(form);
53779 Roo.each(form.allItems, function (fe) {
53781 n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
53782 if (this.findField(n)) { // already added..
53785 var add = new Roo.form.Hidden({
53788 add.render(this.el);
53795 * Mark fields in this form invalid in bulk.
53796 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
53797 * @return {BasicForm} this
53799 markInvalid : function(errors){
53800 if(errors instanceof Array){
53801 for(var i = 0, len = errors.length; i < len; i++){
53802 var fieldError = errors[i];
53803 var f = this.findField(fieldError.id);
53805 f.markInvalid(fieldError.msg);
53811 if(typeof errors[id] != 'function' && (field = this.findField(id))){
53812 field.markInvalid(errors[id]);
53816 Roo.each(this.childForms || [], function (f) {
53817 f.markInvalid(errors);
53824 * Set values for fields in this form in bulk.
53825 * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
53826 * @return {BasicForm} this
53828 setValues : function(values){
53829 if(values instanceof Array){ // array of objects
53830 for(var i = 0, len = values.length; i < len; i++){
53832 var f = this.findField(v.id);
53834 f.setValue(v.value);
53835 if(this.trackResetOnLoad){
53836 f.originalValue = f.getValue();
53840 }else{ // object hash
53843 if(typeof values[id] != 'function' && (field = this.findField(id))){
53845 if (field.setFromData &&
53846 field.valueField &&
53847 field.displayField &&
53848 // combos' with local stores can
53849 // be queried via setValue()
53850 // to set their value..
53851 (field.store && !field.store.isLocal)
53855 sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
53856 sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
53857 field.setFromData(sd);
53860 field.setValue(values[id]);
53864 if(this.trackResetOnLoad){
53865 field.originalValue = field.getValue();
53870 this.resetHasChanged();
53873 Roo.each(this.childForms || [], function (f) {
53874 f.setValues(values);
53875 f.resetHasChanged();
53882 * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
53883 * they are returned as an array.
53884 * @param {Boolean} asString
53887 getValues : function(asString)
53889 if (this.childForms) {
53890 // copy values from the child forms
53891 Roo.each(this.childForms, function (f) {
53892 this.setValues(f.getFieldValues()); // get the full set of data, as we might be copying comboboxes from external into this one.
53897 if (typeof(FormData) != 'undefined' && asString !== true) {
53898 // this relies on a 'recent' version of chrome apparently...
53900 var fd = (new FormData(this.el.dom)).entries();
53902 var ent = fd.next();
53903 while (!ent.done) {
53904 ret[ent.value[0]] = ent.value[1]; // not sure how this will handle duplicates..
53915 var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
53916 if(asString === true){
53919 return Roo.urlDecode(fs);
53923 * Returns the fields in this form as an object with key/value pairs.
53924 * This differs from getValues as it calls getValue on each child item, rather than using dom data.
53925 * Normally this will not return readOnly data
53926 * @param {Boolean} with_readonly return readonly field data.
53929 getFieldValues : function(with_readonly)
53931 if (this.childForms) {
53932 // copy values from the child forms
53933 // should this call getFieldValues - probably not as we do not currently copy
53934 // hidden fields when we generate..
53935 Roo.each(this.childForms, function (f) {
53936 this.setValues(f.getFieldValues());
53941 this.items.each(function(f){
53943 if (f.readOnly && with_readonly !== true) {
53944 return; // skip read only values. - this is in theory to stop 'old' values being copied over new ones
53945 // if a subform contains a copy of them.
53946 // if you have subforms with the same editable data, you will need to copy the data back
53950 if (!f.getName()) {
53953 var v = f.getValue();
53954 if (f.inputType =='radio') {
53955 if (typeof(ret[f.getName()]) == 'undefined') {
53956 ret[f.getName()] = ''; // empty..
53959 if (!f.el.dom.checked) {
53963 v = f.el.dom.value;
53967 // not sure if this supported any more..
53968 if ((typeof(v) == 'object') && f.getRawValue) {
53969 v = f.getRawValue() ; // dates..
53971 // combo boxes where name != hiddenName...
53972 if (f.name != f.getName()) {
53973 ret[f.name] = f.getRawValue();
53975 ret[f.getName()] = v;
53982 * Clears all invalid messages in this form.
53983 * @return {BasicForm} this
53985 clearInvalid : function(){
53986 this.items.each(function(f){
53990 Roo.each(this.childForms || [], function (f) {
53999 * Resets this form.
54000 * @return {BasicForm} this
54002 reset : function(){
54003 this.items.each(function(f){
54007 Roo.each(this.childForms || [], function (f) {
54010 this.resetHasChanged();
54016 * Add Roo.form components to this form.
54017 * @param {Field} field1
54018 * @param {Field} field2 (optional)
54019 * @param {Field} etc (optional)
54020 * @return {BasicForm} this
54023 this.items.addAll(Array.prototype.slice.call(arguments, 0));
54029 * Removes a field from the items collection (does NOT remove its markup).
54030 * @param {Field} field
54031 * @return {BasicForm} this
54033 remove : function(field){
54034 this.items.remove(field);
54039 * Looks at the fields in this form, checks them for an id attribute,
54040 * and calls applyTo on the existing dom element with that id.
54041 * @return {BasicForm} this
54043 render : function(){
54044 this.items.each(function(f){
54045 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
54053 * Calls {@link Ext#apply} for all fields in this form with the passed object.
54054 * @param {Object} values
54055 * @return {BasicForm} this
54057 applyToFields : function(o){
54058 this.items.each(function(f){
54065 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
54066 * @param {Object} values
54067 * @return {BasicForm} this
54069 applyIfToFields : function(o){
54070 this.items.each(function(f){
54078 Roo.BasicForm = Roo.form.BasicForm;
54080 Roo.apply(Roo.form.BasicForm, {
54094 intervalID : false,
54100 if(this.isApplied){
54105 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
54106 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
54107 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
54108 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
54111 this.maskEl.top.enableDisplayMode("block");
54112 this.maskEl.left.enableDisplayMode("block");
54113 this.maskEl.bottom.enableDisplayMode("block");
54114 this.maskEl.right.enableDisplayMode("block");
54116 Roo.get(document.body).on('click', function(){
54120 Roo.get(document.body).on('touchstart', function(){
54124 this.isApplied = true
54127 mask : function(form, target)
54131 this.target = target;
54133 if(!this.form.errorMask || !target.el){
54137 var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.x-layout-active-content', 100, true) || Roo.get(document.body);
54139 var ot = this.target.el.calcOffsetsTo(scrollable);
54141 var scrollTo = ot[1] - this.form.maskOffset;
54143 scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
54145 scrollable.scrollTo('top', scrollTo);
54147 var el = this.target.wrap || this.target.el;
54149 var box = el.getBox();
54151 this.maskEl.top.setStyle('position', 'absolute');
54152 this.maskEl.top.setStyle('z-index', 10000);
54153 this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
54154 this.maskEl.top.setLeft(0);
54155 this.maskEl.top.setTop(0);
54156 this.maskEl.top.show();
54158 this.maskEl.left.setStyle('position', 'absolute');
54159 this.maskEl.left.setStyle('z-index', 10000);
54160 this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
54161 this.maskEl.left.setLeft(0);
54162 this.maskEl.left.setTop(box.y - this.padding);
54163 this.maskEl.left.show();
54165 this.maskEl.bottom.setStyle('position', 'absolute');
54166 this.maskEl.bottom.setStyle('z-index', 10000);
54167 this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
54168 this.maskEl.bottom.setLeft(0);
54169 this.maskEl.bottom.setTop(box.bottom + this.padding);
54170 this.maskEl.bottom.show();
54172 this.maskEl.right.setStyle('position', 'absolute');
54173 this.maskEl.right.setStyle('z-index', 10000);
54174 this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
54175 this.maskEl.right.setLeft(box.right + this.padding);
54176 this.maskEl.right.setTop(box.y - this.padding);
54177 this.maskEl.right.show();
54179 this.intervalID = window.setInterval(function() {
54180 Roo.form.BasicForm.popover.unmask();
54183 window.onwheel = function(){ return false;};
54185 (function(){ this.isMasked = true; }).defer(500, this);
54189 unmask : function()
54191 if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
54195 this.maskEl.top.setStyle('position', 'absolute');
54196 this.maskEl.top.setSize(0, 0).setXY([0, 0]);
54197 this.maskEl.top.hide();
54199 this.maskEl.left.setStyle('position', 'absolute');
54200 this.maskEl.left.setSize(0, 0).setXY([0, 0]);
54201 this.maskEl.left.hide();
54203 this.maskEl.bottom.setStyle('position', 'absolute');
54204 this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
54205 this.maskEl.bottom.hide();
54207 this.maskEl.right.setStyle('position', 'absolute');
54208 this.maskEl.right.setSize(0, 0).setXY([0, 0]);
54209 this.maskEl.right.hide();
54211 window.onwheel = function(){ return true;};
54213 if(this.intervalID){
54214 window.clearInterval(this.intervalID);
54215 this.intervalID = false;
54218 this.isMasked = false;
54226 * Ext JS Library 1.1.1
54227 * Copyright(c) 2006-2007, Ext JS, LLC.
54229 * Originally Released Under LGPL - original licence link has changed is not relivant.
54232 * <script type="text/javascript">
54236 * @class Roo.form.Form
54237 * @extends Roo.form.BasicForm
54238 * @children Roo.form.Column Roo.form.FieldSet Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
54239 * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
54241 * @param {Object} config Configuration options
54243 Roo.form.Form = function(config){
54245 if (config.items) {
54246 xitems = config.items;
54247 delete config.items;
54251 Roo.form.Form.superclass.constructor.call(this, null, config);
54252 this.url = this.url || this.action;
54254 this.root = new Roo.form.Layout(Roo.applyIf({
54258 this.active = this.root;
54260 * Array of all the buttons that have been added to this form via {@link addButton}
54264 this.allItems = [];
54267 * @event clientvalidation
54268 * If the monitorValid config option is true, this event fires repetitively to notify of valid state
54269 * @param {Form} this
54270 * @param {Boolean} valid true if the form has passed client-side validation
54272 clientvalidation: true,
54275 * Fires when the form is rendered
54276 * @param {Roo.form.Form} form
54281 if (this.progressUrl) {
54282 // push a hidden field onto the list of fields..
54286 name : 'UPLOAD_IDENTIFIER'
54291 Roo.each(xitems, this.addxtype, this);
54295 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
54297 * @cfg {Roo.Button} buttons[] buttons at bottom of form
54301 * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
54304 * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
54307 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
54309 buttonAlign:'center',
54312 * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
54317 * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
54318 * This property cascades to child containers if not set.
54323 * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
54324 * fires a looping event with that state. This is required to bind buttons to the valid
54325 * state using the config value formBind:true on the button.
54327 monitorValid : false,
54330 * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
54335 * @cfg {String} progressUrl - Url to return progress data
54338 progressUrl : false,
54340 * @cfg {boolean|FormData} formData - true to use new 'FormData' post, or set to a new FormData({dom form}) Object, if
54341 * sending a formdata with extra parameters - eg uploaded elements.
54347 * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
54348 * fields are added and the column is closed. If no fields are passed the column remains open
54349 * until end() is called.
54350 * @param {Object} config The config to pass to the column
54351 * @param {Field} field1 (optional)
54352 * @param {Field} field2 (optional)
54353 * @param {Field} etc (optional)
54354 * @return Column The column container object
54356 column : function(c){
54357 var col = new Roo.form.Column(c);
54359 if(arguments.length > 1){ // duplicate code required because of Opera
54360 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
54367 * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
54368 * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
54369 * until end() is called.
54370 * @param {Object} config The config to pass to the fieldset
54371 * @param {Field} field1 (optional)
54372 * @param {Field} field2 (optional)
54373 * @param {Field} etc (optional)
54374 * @return FieldSet The fieldset container object
54376 fieldset : function(c){
54377 var fs = new Roo.form.FieldSet(c);
54379 if(arguments.length > 1){ // duplicate code required because of Opera
54380 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
54387 * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
54388 * fields are added and the container is closed. If no fields are passed the container remains open
54389 * until end() is called.
54390 * @param {Object} config The config to pass to the Layout
54391 * @param {Field} field1 (optional)
54392 * @param {Field} field2 (optional)
54393 * @param {Field} etc (optional)
54394 * @return Layout The container object
54396 container : function(c){
54397 var l = new Roo.form.Layout(c);
54399 if(arguments.length > 1){ // duplicate code required because of Opera
54400 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
54407 * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
54408 * @param {Object} container A Roo.form.Layout or subclass of Layout
54409 * @return {Form} this
54411 start : function(c){
54412 // cascade label info
54413 Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
54414 this.active.stack.push(c);
54415 c.ownerCt = this.active;
54421 * Closes the current open container
54422 * @return {Form} this
54425 if(this.active == this.root){
54428 this.active = this.active.ownerCt;
54433 * Add Roo.form components to the current open container (e.g. column, fieldset, etc.). Fields added via this method
54434 * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
54435 * as the label of the field.
54436 * @param {Field} field1
54437 * @param {Field} field2 (optional)
54438 * @param {Field} etc. (optional)
54439 * @return {Form} this
54442 this.active.stack.push.apply(this.active.stack, arguments);
54443 this.allItems.push.apply(this.allItems,arguments);
54445 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
54446 if(a[i].isFormField){
54451 Roo.form.Form.superclass.add.apply(this, r);
54461 * Find any element that has been added to a form, using it's ID or name
54462 * This can include framesets, columns etc. along with regular fields..
54463 * @param {String} id - id or name to find.
54465 * @return {Element} e - or false if nothing found.
54467 findbyId : function(id)
54473 Roo.each(this.allItems, function(f){
54474 if (f.id == id || f.name == id ){
54485 * Render this form into the passed container. This should only be called once!
54486 * @param {String/HTMLElement/Element} container The element this component should be rendered into
54487 * @return {Form} this
54489 render : function(ct)
54495 var o = this.autoCreate || {
54497 method : this.method || 'POST',
54498 id : this.id || Roo.id()
54500 this.initEl(ct.createChild(o));
54502 this.root.render(this.el);
54506 this.items.each(function(f){
54507 f.render('x-form-el-'+f.id);
54510 if(this.buttons.length > 0){
54511 // tables are required to maintain order and for correct IE layout
54512 var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
54513 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
54514 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
54516 var tr = tb.getElementsByTagName('tr')[0];
54517 for(var i = 0, len = this.buttons.length; i < len; i++) {
54518 var b = this.buttons[i];
54519 var td = document.createElement('td');
54520 td.className = 'x-form-btn-td';
54521 b.render(tr.appendChild(td));
54524 if(this.monitorValid){ // initialize after render
54525 this.startMonitoring();
54527 this.fireEvent('rendered', this);
54532 * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
54533 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
54534 * object or a valid Roo.DomHelper element config
54535 * @param {Function} handler The function called when the button is clicked
54536 * @param {Object} scope (optional) The scope of the handler function
54537 * @return {Roo.Button}
54539 addButton : function(config, handler, scope){
54543 minWidth: this.minButtonWidth,
54546 if(typeof config == "string"){
54549 Roo.apply(bc, config);
54551 var btn = new Roo.Button(null, bc);
54552 this.buttons.push(btn);
54557 * Adds a series of form elements (using the xtype property as the factory method.
54558 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
54559 * @param {Object} config
54562 addxtype : function()
54564 var ar = Array.prototype.slice.call(arguments, 0);
54566 for(var i = 0; i < ar.length; i++) {
54568 continue; // skip -- if this happends something invalid got sent, we
54569 // should ignore it, as basically that interface element will not show up
54570 // and that should be pretty obvious!!
54573 if (Roo.form[ar[i].xtype]) {
54575 var fe = Roo.factory(ar[i], Roo.form);
54581 fe.store.form = this;
54586 this.allItems.push(fe);
54587 if (fe.items && fe.addxtype) {
54588 fe.addxtype.apply(fe, fe.items);
54598 // console.log('adding ' + ar[i].xtype);
54600 if (ar[i].xtype == 'Button') {
54601 //console.log('adding button');
54602 //console.log(ar[i]);
54603 this.addButton(ar[i]);
54604 this.allItems.push(fe);
54608 if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
54609 alert('end is not supported on xtype any more, use items');
54611 // //console.log('adding end');
54619 * Starts monitoring of the valid state of this form. Usually this is done by passing the config
54620 * option "monitorValid"
54622 startMonitoring : function(){
54625 Roo.TaskMgr.start({
54626 run : this.bindHandler,
54627 interval : this.monitorPoll || 200,
54634 * Stops monitoring of the valid state of this form
54636 stopMonitoring : function(){
54637 this.bound = false;
54641 bindHandler : function(){
54643 return false; // stops binding
54646 this.items.each(function(f){
54647 if(!f.isValid(true)){
54652 for(var i = 0, len = this.buttons.length; i < len; i++){
54653 var btn = this.buttons[i];
54654 if(btn.formBind === true && btn.disabled === valid){
54655 btn.setDisabled(!valid);
54658 this.fireEvent('clientvalidation', this, valid);
54672 Roo.Form = Roo.form.Form;
54675 * Ext JS Library 1.1.1
54676 * Copyright(c) 2006-2007, Ext JS, LLC.
54678 * Originally Released Under LGPL - original licence link has changed is not relivant.
54681 * <script type="text/javascript">
54684 // as we use this in bootstrap.
54685 Roo.namespace('Roo.form');
54687 * @class Roo.form.Action
54688 * Internal Class used to handle form actions
54690 * @param {Roo.form.BasicForm} el The form element or its id
54691 * @param {Object} config Configuration options
54696 // define the action interface
54697 Roo.form.Action = function(form, options){
54699 this.options = options || {};
54702 * Client Validation Failed
54705 Roo.form.Action.CLIENT_INVALID = 'client';
54707 * Server Validation Failed
54710 Roo.form.Action.SERVER_INVALID = 'server';
54712 * Connect to Server Failed
54715 Roo.form.Action.CONNECT_FAILURE = 'connect';
54717 * Reading Data from Server Failed
54720 Roo.form.Action.LOAD_FAILURE = 'load';
54722 Roo.form.Action.prototype = {
54724 failureType : undefined,
54725 response : undefined,
54726 result : undefined,
54728 // interface method
54729 run : function(options){
54733 // interface method
54734 success : function(response){
54738 // interface method
54739 handleResponse : function(response){
54743 // default connection failure
54744 failure : function(response){
54746 this.response = response;
54747 this.failureType = Roo.form.Action.CONNECT_FAILURE;
54748 this.form.afterAction(this, false);
54751 processResponse : function(response){
54752 this.response = response;
54753 if(!response.responseText){
54756 this.result = this.handleResponse(response);
54757 return this.result;
54760 // utility functions used internally
54761 getUrl : function(appendParams){
54762 var url = this.options.url || this.form.url || this.form.el.dom.action;
54764 var p = this.getParams();
54766 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
54772 getMethod : function(){
54773 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
54776 getParams : function(){
54777 var bp = this.form.baseParams;
54778 var p = this.options.params;
54780 if(typeof p == "object"){
54781 p = Roo.urlEncode(Roo.applyIf(p, bp));
54782 }else if(typeof p == 'string' && bp){
54783 p += '&' + Roo.urlEncode(bp);
54786 p = Roo.urlEncode(bp);
54791 createCallback : function(){
54793 success: this.success,
54794 failure: this.failure,
54796 timeout: (this.form.timeout*1000),
54797 upload: this.form.fileUpload ? this.success : undefined
54802 Roo.form.Action.Submit = function(form, options){
54803 Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
54806 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
54809 haveProgress : false,
54810 uploadComplete : false,
54812 // uploadProgress indicator.
54813 uploadProgress : function()
54815 if (!this.form.progressUrl) {
54819 if (!this.haveProgress) {
54820 Roo.MessageBox.progress("Uploading", "Uploading");
54822 if (this.uploadComplete) {
54823 Roo.MessageBox.hide();
54827 this.haveProgress = true;
54829 var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
54831 var c = new Roo.data.Connection();
54833 url : this.form.progressUrl,
54838 success : function(req){
54839 //console.log(data);
54843 rdata = Roo.decode(req.responseText)
54845 Roo.log("Invalid data from server..");
54849 if (!rdata || !rdata.success) {
54851 Roo.MessageBox.alert(Roo.encode(rdata));
54854 var data = rdata.data;
54856 if (this.uploadComplete) {
54857 Roo.MessageBox.hide();
54862 Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
54863 Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
54866 this.uploadProgress.defer(2000,this);
54869 failure: function(data) {
54870 Roo.log('progress url failed ');
54881 // run get Values on the form, so it syncs any secondary forms.
54882 this.form.getValues();
54884 var o = this.options;
54885 var method = this.getMethod();
54886 var isPost = method == 'POST';
54887 if(o.clientValidation === false || this.form.isValid()){
54889 if (this.form.progressUrl) {
54890 this.form.findField('UPLOAD_IDENTIFIER').setValue(
54891 (new Date() * 1) + '' + Math.random());
54896 Roo.Ajax.request(Roo.apply(this.createCallback(), {
54897 form:this.form.el.dom,
54898 url:this.getUrl(!isPost),
54900 params:isPost ? this.getParams() : null,
54901 isUpload: this.form.fileUpload,
54902 formData : this.form.formData
54905 this.uploadProgress();
54907 }else if (o.clientValidation !== false){ // client validation failed
54908 this.failureType = Roo.form.Action.CLIENT_INVALID;
54909 this.form.afterAction(this, false);
54913 success : function(response)
54915 this.uploadComplete= true;
54916 if (this.haveProgress) {
54917 Roo.MessageBox.hide();
54921 var result = this.processResponse(response);
54922 if(result === true || result.success){
54923 this.form.afterAction(this, true);
54927 this.form.markInvalid(result.errors);
54928 this.failureType = Roo.form.Action.SERVER_INVALID;
54930 this.form.afterAction(this, false);
54932 failure : function(response)
54934 this.uploadComplete= true;
54935 if (this.haveProgress) {
54936 Roo.MessageBox.hide();
54939 this.response = response;
54940 this.failureType = Roo.form.Action.CONNECT_FAILURE;
54941 this.form.afterAction(this, false);
54944 handleResponse : function(response){
54945 if(this.form.errorReader){
54946 var rs = this.form.errorReader.read(response);
54949 for(var i = 0, len = rs.records.length; i < len; i++) {
54950 var r = rs.records[i];
54951 errors[i] = r.data;
54954 if(errors.length < 1){
54958 success : rs.success,
54964 ret = Roo.decode(response.responseText);
54968 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
54978 Roo.form.Action.Load = function(form, options){
54979 Roo.form.Action.Load.superclass.constructor.call(this, form, options);
54980 this.reader = this.form.reader;
54983 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
54988 Roo.Ajax.request(Roo.apply(
54989 this.createCallback(), {
54990 method:this.getMethod(),
54991 url:this.getUrl(false),
54992 params:this.getParams()
54996 success : function(response){
54998 var result = this.processResponse(response);
54999 if(result === true || !result.success || !result.data){
55000 this.failureType = Roo.form.Action.LOAD_FAILURE;
55001 this.form.afterAction(this, false);
55004 this.form.clearInvalid();
55005 this.form.setValues(result.data);
55006 this.form.afterAction(this, true);
55009 handleResponse : function(response){
55010 if(this.form.reader){
55011 var rs = this.form.reader.read(response);
55012 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
55014 success : rs.success,
55018 return Roo.decode(response.responseText);
55022 Roo.form.Action.ACTION_TYPES = {
55023 'load' : Roo.form.Action.Load,
55024 'submit' : Roo.form.Action.Submit
55027 * Ext JS Library 1.1.1
55028 * Copyright(c) 2006-2007, Ext JS, LLC.
55030 * Originally Released Under LGPL - original licence link has changed is not relivant.
55033 * <script type="text/javascript">
55037 * @class Roo.form.Layout
55038 * @extends Roo.Component
55039 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
55040 * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
55042 * @param {Object} config Configuration options
55044 Roo.form.Layout = function(config){
55046 if (config.items) {
55047 xitems = config.items;
55048 delete config.items;
55050 Roo.form.Layout.superclass.constructor.call(this, config);
55052 Roo.each(xitems, this.addxtype, this);
55056 Roo.extend(Roo.form.Layout, Roo.Component, {
55058 * @cfg {String/Object} autoCreate
55059 * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
55062 * @cfg {String/Object/Function} style
55063 * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
55064 * a function which returns such a specification.
55067 * @cfg {String} labelAlign
55068 * Valid values are "left," "top" and "right" (defaults to "left")
55071 * @cfg {Number} labelWidth
55072 * Fixed width in pixels of all field labels (defaults to undefined)
55075 * @cfg {Boolean} clear
55076 * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
55080 * @cfg {String} labelSeparator
55081 * The separator to use after field labels (defaults to ':')
55083 labelSeparator : ':',
55085 * @cfg {Boolean} hideLabels
55086 * True to suppress the display of field labels in this layout (defaults to false)
55088 hideLabels : false,
55091 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
55096 onRender : function(ct, position){
55097 if(this.el){ // from markup
55098 this.el = Roo.get(this.el);
55099 }else { // generate
55100 var cfg = this.getAutoCreate();
55101 this.el = ct.createChild(cfg, position);
55104 this.el.applyStyles(this.style);
55106 if(this.labelAlign){
55107 this.el.addClass('x-form-label-'+this.labelAlign);
55109 if(this.hideLabels){
55110 this.labelStyle = "display:none";
55111 this.elementStyle = "padding-left:0;";
55113 if(typeof this.labelWidth == 'number'){
55114 this.labelStyle = "width:"+this.labelWidth+"px;";
55115 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
55117 if(this.labelAlign == 'top'){
55118 this.labelStyle = "width:auto;";
55119 this.elementStyle = "padding-left:0;";
55122 var stack = this.stack;
55123 var slen = stack.length;
55125 if(!this.fieldTpl){
55126 var t = new Roo.Template(
55127 '<div class="x-form-item {5}">',
55128 '<label for="{0}" style="{2}">{1}{4}</label>',
55129 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
55131 '</div><div class="x-form-clear-left"></div>'
55133 t.disableFormats = true;
55135 Roo.form.Layout.prototype.fieldTpl = t;
55137 for(var i = 0; i < slen; i++) {
55138 if(stack[i].isFormField){
55139 this.renderField(stack[i]);
55141 this.renderComponent(stack[i]);
55146 this.el.createChild({cls:'x-form-clear'});
55151 renderField : function(f){
55152 f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
55155 f.labelStyle||this.labelStyle||'', //2
55156 this.elementStyle||'', //3
55157 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
55158 f.itemCls||this.itemCls||'' //5
55159 ], true).getPrevSibling());
55163 renderComponent : function(c){
55164 c.render(c.isLayout ? this.el : this.el.createChild());
55167 * Adds a object form elements (using the xtype property as the factory method.)
55168 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column
55169 * @param {Object} config
55171 addxtype : function(o)
55173 // create the lement.
55174 o.form = this.form;
55175 var fe = Roo.factory(o, Roo.form);
55176 this.form.allItems.push(fe);
55177 this.stack.push(fe);
55179 if (fe.isFormField) {
55180 this.form.items.add(fe);
55188 * @class Roo.form.Column
55189 * @extends Roo.form.Layout
55190 * @children Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
55191 * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
55193 * @param {Object} config Configuration options
55195 Roo.form.Column = function(config){
55196 Roo.form.Column.superclass.constructor.call(this, config);
55199 Roo.extend(Roo.form.Column, Roo.form.Layout, {
55201 * @cfg {Number/String} width
55202 * The fixed width of the column in pixels or CSS value (defaults to "auto")
55205 * @cfg {String/Object} autoCreate
55206 * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
55210 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
55213 onRender : function(ct, position){
55214 Roo.form.Column.superclass.onRender.call(this, ct, position);
55216 this.el.setWidth(this.width);
55223 * @class Roo.form.Row
55224 * @extends Roo.form.Layout
55225 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
55226 * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
55228 * @param {Object} config Configuration options
55232 Roo.form.Row = function(config){
55233 Roo.form.Row.superclass.constructor.call(this, config);
55236 Roo.extend(Roo.form.Row, Roo.form.Layout, {
55238 * @cfg {Number/String} width
55239 * The fixed width of the column in pixels or CSS value (defaults to "auto")
55242 * @cfg {Number/String} height
55243 * The fixed height of the column in pixels or CSS value (defaults to "auto")
55245 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
55249 onRender : function(ct, position){
55250 //console.log('row render');
55252 var t = new Roo.Template(
55253 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
55254 '<label for="{0}" style="{2}">{1}{4}</label>',
55255 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
55259 t.disableFormats = true;
55261 Roo.form.Layout.prototype.rowTpl = t;
55263 this.fieldTpl = this.rowTpl;
55265 //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
55266 var labelWidth = 100;
55268 if ((this.labelAlign != 'top')) {
55269 if (typeof this.labelWidth == 'number') {
55270 labelWidth = this.labelWidth
55272 this.padWidth = 20 + labelWidth;
55276 Roo.form.Column.superclass.onRender.call(this, ct, position);
55278 this.el.setWidth(this.width);
55281 this.el.setHeight(this.height);
55286 renderField : function(f){
55287 f.fieldEl = this.fieldTpl.append(this.el, [
55288 f.id, f.fieldLabel,
55289 f.labelStyle||this.labelStyle||'',
55290 this.elementStyle||'',
55291 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
55292 f.itemCls||this.itemCls||'',
55293 f.width ? f.width + this.padWidth : 160 + this.padWidth
55300 * @class Roo.form.FieldSet
55301 * @extends Roo.form.Layout
55302 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
55303 * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
55305 * @param {Object} config Configuration options
55307 Roo.form.FieldSet = function(config){
55308 Roo.form.FieldSet.superclass.constructor.call(this, config);
55311 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
55313 * @cfg {String} legend
55314 * The text to display as the legend for the FieldSet (defaults to '')
55317 * @cfg {String/Object} autoCreate
55318 * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
55322 defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
55325 onRender : function(ct, position){
55326 Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
55328 this.setLegend(this.legend);
55333 setLegend : function(text){
55335 this.el.child('legend').update(text);
55340 * Ext JS Library 1.1.1
55341 * Copyright(c) 2006-2007, Ext JS, LLC.
55343 * Originally Released Under LGPL - original licence link has changed is not relivant.
55346 * <script type="text/javascript">
55349 * @class Roo.form.VTypes
55350 * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
55353 Roo.form.VTypes = function(){
55354 // closure these in so they are only created once.
55355 var alpha = /^[a-zA-Z_]+$/;
55356 var alphanum = /^[a-zA-Z0-9_]+$/;
55357 var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
55358 var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
55360 // All these messages and functions are configurable
55363 * The function used to validate email addresses
55364 * @param {String} value The email address
55366 'email' : function(v){
55367 return email.test(v);
55370 * The error text to display when the email validation function returns false
55373 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
55375 * The keystroke filter mask to be applied on email input
55378 'emailMask' : /[a-z0-9_\.\-@]/i,
55381 * The function used to validate URLs
55382 * @param {String} value The URL
55384 'url' : function(v){
55385 return url.test(v);
55388 * The error text to display when the url validation function returns false
55391 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
55394 * The function used to validate alpha values
55395 * @param {String} value The value
55397 'alpha' : function(v){
55398 return alpha.test(v);
55401 * The error text to display when the alpha validation function returns false
55404 'alphaText' : 'This field should only contain letters and _',
55406 * The keystroke filter mask to be applied on alpha input
55409 'alphaMask' : /[a-z_]/i,
55412 * The function used to validate alphanumeric values
55413 * @param {String} value The value
55415 'alphanum' : function(v){
55416 return alphanum.test(v);
55419 * The error text to display when the alphanumeric validation function returns false
55422 'alphanumText' : 'This field should only contain letters, numbers and _',
55424 * The keystroke filter mask to be applied on alphanumeric input
55427 'alphanumMask' : /[a-z0-9_]/i
55429 }();//<script type="text/javascript">
55432 * @class Roo.form.FCKeditor
55433 * @extends Roo.form.TextArea
55434 * Wrapper around the FCKEditor http://www.fckeditor.net
55436 * Creates a new FCKeditor
55437 * @param {Object} config Configuration options
55439 Roo.form.FCKeditor = function(config){
55440 Roo.form.FCKeditor.superclass.constructor.call(this, config);
55443 * @event editorinit
55444 * Fired when the editor is initialized - you can add extra handlers here..
55445 * @param {FCKeditor} this
55446 * @param {Object} the FCK object.
55453 Roo.form.FCKeditor.editors = { };
55454 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
55456 //defaultAutoCreate : {
55457 // tag : "textarea",style : "width:100px;height:60px;" ,autocomplete : "off"
55461 * @cfg {Object} fck options - see fck manual for details.
55466 * @cfg {Object} fck toolbar set (Basic or Default)
55468 toolbarSet : 'Basic',
55470 * @cfg {Object} fck BasePath
55472 basePath : '/fckeditor/',
55480 onRender : function(ct, position)
55483 this.defaultAutoCreate = {
55485 style:"width:300px;height:60px;",
55486 autocomplete: "new-password"
55489 Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
55492 this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
55493 if(this.preventScrollbars){
55494 this.el.setStyle("overflow", "hidden");
55496 this.el.setHeight(this.growMin);
55499 //console.log('onrender' + this.getId() );
55500 Roo.form.FCKeditor.editors[this.getId()] = this;
55503 this.replaceTextarea() ;
55507 getEditor : function() {
55508 return this.fckEditor;
55511 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
55512 * @param {Mixed} value The value to set
55516 setValue : function(value)
55518 //console.log('setValue: ' + value);
55520 if(typeof(value) == 'undefined') { // not sure why this is happending...
55523 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
55525 //if(!this.el || !this.getEditor()) {
55526 // this.value = value;
55527 //this.setValue.defer(100,this,[value]);
55531 if(!this.getEditor()) {
55535 this.getEditor().SetData(value);
55542 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
55543 * @return {Mixed} value The field value
55545 getValue : function()
55548 if (this.frame && this.frame.dom.style.display == 'none') {
55549 return Roo.form.FCKeditor.superclass.getValue.call(this);
55552 if(!this.el || !this.getEditor()) {
55554 // this.getValue.defer(100,this);
55559 var value=this.getEditor().GetData();
55560 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
55561 return Roo.form.FCKeditor.superclass.getValue.call(this);
55567 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
55568 * @return {Mixed} value The field value
55570 getRawValue : function()
55572 if (this.frame && this.frame.dom.style.display == 'none') {
55573 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
55576 if(!this.el || !this.getEditor()) {
55577 //this.getRawValue.defer(100,this);
55584 var value=this.getEditor().GetData();
55585 Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
55586 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
55590 setSize : function(w,h) {
55594 //if (this.frame && this.frame.dom.style.display == 'none') {
55595 // Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
55598 //if(!this.el || !this.getEditor()) {
55599 // this.setSize.defer(100,this, [w,h]);
55605 Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
55607 this.frame.dom.setAttribute('width', w);
55608 this.frame.dom.setAttribute('height', h);
55609 this.frame.setSize(w,h);
55613 toggleSourceEdit : function(value) {
55617 this.el.dom.style.display = value ? '' : 'none';
55618 this.frame.dom.style.display = value ? 'none' : '';
55623 focus: function(tag)
55625 if (this.frame.dom.style.display == 'none') {
55626 return Roo.form.FCKeditor.superclass.focus.call(this);
55628 if(!this.el || !this.getEditor()) {
55629 this.focus.defer(100,this, [tag]);
55636 var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
55637 this.getEditor().Focus();
55639 if (!this.getEditor().Selection.GetSelection()) {
55640 this.focus.defer(100,this, [tag]);
55645 var r = this.getEditor().EditorDocument.createRange();
55646 r.setStart(tgs[0],0);
55647 r.setEnd(tgs[0],0);
55648 this.getEditor().Selection.GetSelection().removeAllRanges();
55649 this.getEditor().Selection.GetSelection().addRange(r);
55650 this.getEditor().Focus();
55657 replaceTextarea : function()
55659 if ( document.getElementById( this.getId() + '___Frame' ) ) {
55662 //if ( !this.checkBrowser || this._isCompatibleBrowser() )
55664 // We must check the elements firstly using the Id and then the name.
55665 var oTextarea = document.getElementById( this.getId() );
55667 var colElementsByName = document.getElementsByName( this.getId() ) ;
55669 oTextarea.style.display = 'none' ;
55671 if ( oTextarea.tabIndex ) {
55672 this.TabIndex = oTextarea.tabIndex ;
55675 this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
55676 this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
55677 this.frame = Roo.get(this.getId() + '___Frame')
55680 _getConfigHtml : function()
55684 for ( var o in this.fckconfig ) {
55685 sConfig += sConfig.length > 0 ? '&' : '';
55686 sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
55689 return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
55693 _getIFrameHtml : function()
55695 var sFile = 'fckeditor.html' ;
55696 /* no idea what this is about..
55699 if ( (/fcksource=true/i).test( window.top.location.search ) )
55700 sFile = 'fckeditor.original.html' ;
55705 var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
55706 sLink += this.toolbarSet ? ( '&Toolbar=' + this.toolbarSet) : '';
55709 var html = '<iframe id="' + this.getId() +
55710 '___Frame" src="' + sLink +
55711 '" width="' + this.width +
55712 '" height="' + this.height + '"' +
55713 (this.tabIndex ? ' tabindex="' + this.tabIndex + '"' :'' ) +
55714 ' frameborder="0" scrolling="no"></iframe>' ;
55719 _insertHtmlBefore : function( html, element )
55721 if ( element.insertAdjacentHTML ) {
55723 element.insertAdjacentHTML( 'beforeBegin', html ) ;
55725 var oRange = document.createRange() ;
55726 oRange.setStartBefore( element ) ;
55727 var oFragment = oRange.createContextualFragment( html );
55728 element.parentNode.insertBefore( oFragment, element ) ;
55741 //Roo.reg('fckeditor', Roo.form.FCKeditor);
55743 function FCKeditor_OnComplete(editorInstance){
55744 var f = Roo.form.FCKeditor.editors[editorInstance.Name];
55745 f.fckEditor = editorInstance;
55746 //console.log("loaded");
55747 f.fireEvent('editorinit', f, editorInstance);
55767 //<script type="text/javascript">
55769 * @class Roo.form.GridField
55770 * @extends Roo.form.Field
55771 * Embed a grid (or editable grid into a form)
55774 * This embeds a grid in a form, the value of the field should be the json encoded array of rows
55776 * xgrid.store = Roo.data.Store
55777 * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
55778 * xgrid.store.reader = Roo.data.JsonReader
55782 * Creates a new GridField
55783 * @param {Object} config Configuration options
55785 Roo.form.GridField = function(config){
55786 Roo.form.GridField.superclass.constructor.call(this, config);
55790 Roo.extend(Roo.form.GridField, Roo.form.Field, {
55792 * @cfg {Number} width - used to restrict width of grid..
55796 * @cfg {Number} height - used to restrict height of grid..
55800 * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
55806 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
55807 * {tag: "input", type: "checkbox", autocomplete: "off"})
55809 // defaultAutoCreate : { tag: 'div' },
55810 defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
55812 * @cfg {String} addTitle Text to include for adding a title.
55816 onResize : function(){
55817 Roo.form.Field.superclass.onResize.apply(this, arguments);
55820 initEvents : function(){
55821 // Roo.form.Checkbox.superclass.initEvents.call(this);
55822 // has no events...
55827 getResizeEl : function(){
55831 getPositionEl : function(){
55836 onRender : function(ct, position){
55838 this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
55839 var style = this.style;
55842 Roo.form.GridField.superclass.onRender.call(this, ct, position);
55843 this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
55844 this.viewEl = this.wrap.createChild({ tag: 'div' });
55846 this.viewEl.applyStyles(style);
55849 this.viewEl.setWidth(this.width);
55852 this.viewEl.setHeight(this.height);
55854 //if(this.inputValue !== undefined){
55855 //this.setValue(this.value);
55858 this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
55861 this.grid.render();
55862 this.grid.getDataSource().on('remove', this.refreshValue, this);
55863 this.grid.getDataSource().on('update', this.refreshValue, this);
55864 this.grid.on('afteredit', this.refreshValue, this);
55870 * Sets the value of the item.
55871 * @param {String} either an object or a string..
55873 setValue : function(v){
55875 v = v || []; // empty set..
55876 // this does not seem smart - it really only affects memoryproxy grids..
55877 if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
55878 var ds = this.grid.getDataSource();
55879 // assumes a json reader..
55881 data[ds.reader.meta.root ] = typeof(v) == 'string' ? Roo.decode(v) : v;
55882 ds.loadData( data);
55884 // clear selection so it does not get stale.
55885 if (this.grid.sm) {
55886 this.grid.sm.clearSelections();
55889 Roo.form.GridField.superclass.setValue.call(this, v);
55890 this.refreshValue();
55891 // should load data in the grid really....
55895 refreshValue: function() {
55897 this.grid.getDataSource().each(function(r) {
55900 this.el.dom.value = Roo.encode(val);
55908 * Ext JS Library 1.1.1
55909 * Copyright(c) 2006-2007, Ext JS, LLC.
55911 * Originally Released Under LGPL - original licence link has changed is not relivant.
55914 * <script type="text/javascript">
55917 * @class Roo.form.DisplayField
55918 * @extends Roo.form.Field
55919 * A generic Field to display non-editable data.
55920 * @cfg {Boolean} closable (true|false) default false
55922 * Creates a new Display Field item.
55923 * @param {Object} config Configuration options
55925 Roo.form.DisplayField = function(config){
55926 Roo.form.DisplayField.superclass.constructor.call(this, config);
55931 * Fires after the click the close btn
55932 * @param {Roo.form.DisplayField} this
55938 Roo.extend(Roo.form.DisplayField, Roo.form.TextField, {
55939 inputType: 'hidden',
55945 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
55947 focusClass : undefined,
55949 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
55951 fieldClass: 'x-form-field',
55954 * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
55956 valueRenderer: undefined,
55960 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
55961 * {tag: "input", type: "checkbox", autocomplete: "off"})
55964 // defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
55968 onResize : function(){
55969 Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
55973 initEvents : function(){
55974 // Roo.form.Checkbox.superclass.initEvents.call(this);
55975 // has no events...
55978 this.closeEl.on('click', this.onClose, this);
55984 getResizeEl : function(){
55988 getPositionEl : function(){
55993 onRender : function(ct, position){
55995 Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
55996 //if(this.inputValue !== undefined){
55997 this.wrap = this.el.wrap();
55999 this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
56002 this.closeEl = this.wrap.createChild({ tag: 'div', cls: 'x-dlg-close'});
56005 if (this.bodyStyle) {
56006 this.viewEl.applyStyles(this.bodyStyle);
56008 //this.viewEl.setStyle('padding', '2px');
56010 this.setValue(this.value);
56015 initValue : Roo.emptyFn,
56020 onClick : function(){
56025 * Sets the checked state of the checkbox.
56026 * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
56028 setValue : function(v){
56030 var html = this.valueRenderer ? this.valueRenderer(v) : String.format('{0}', v);
56031 // this might be called before we have a dom element..
56032 if (!this.viewEl) {
56035 this.viewEl.dom.innerHTML = html;
56036 Roo.form.DisplayField.superclass.setValue.call(this, v);
56040 onClose : function(e)
56042 e.preventDefault();
56044 this.fireEvent('close', this);
56053 * @class Roo.form.DayPicker
56054 * @extends Roo.form.Field
56055 * A Day picker show [M] [T] [W] ....
56057 * Creates a new Day Picker
56058 * @param {Object} config Configuration options
56060 Roo.form.DayPicker= function(config){
56061 Roo.form.DayPicker.superclass.constructor.call(this, config);
56065 Roo.extend(Roo.form.DayPicker, Roo.form.Field, {
56067 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
56069 focusClass : undefined,
56071 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
56073 fieldClass: "x-form-field",
56076 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
56077 * {tag: "input", type: "checkbox", autocomplete: "off"})
56079 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
56082 actionMode : 'viewEl',
56086 inputType : 'hidden',
56089 inputElement: false, // real input element?
56090 basedOn: false, // ????
56092 isFormField: true, // not sure where this is needed!!!!
56094 onResize : function(){
56095 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
56096 if(!this.boxLabel){
56097 this.el.alignTo(this.wrap, 'c-c');
56101 initEvents : function(){
56102 Roo.form.Checkbox.superclass.initEvents.call(this);
56103 this.el.on("click", this.onClick, this);
56104 this.el.on("change", this.onClick, this);
56108 getResizeEl : function(){
56112 getPositionEl : function(){
56118 onRender : function(ct, position){
56119 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
56121 this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
56123 var r1 = '<table><tr>';
56124 var r2 = '<tr class="x-form-daypick-icons">';
56125 for (var i=0; i < 7; i++) {
56126 r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
56127 r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL +'"></td>';
56130 var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
56131 viewEl.select('img').on('click', this.onClick, this);
56132 this.viewEl = viewEl;
56135 // this will not work on Chrome!!!
56136 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
56137 this.el.on('propertychange', this.setFromHidden, this); //ie
56145 initValue : Roo.emptyFn,
56148 * Returns the checked state of the checkbox.
56149 * @return {Boolean} True if checked, else false
56151 getValue : function(){
56152 return this.el.dom.value;
56157 onClick : function(e){
56158 //this.setChecked(!this.checked);
56159 Roo.get(e.target).toggleClass('x-menu-item-checked');
56160 this.refreshValue();
56161 //if(this.el.dom.checked != this.checked){
56162 // this.setValue(this.el.dom.checked);
56167 refreshValue : function()
56170 this.viewEl.select('img',true).each(function(e,i,n) {
56171 val += e.is(".x-menu-item-checked") ? String(n) : '';
56173 this.setValue(val, true);
56177 * Sets the checked state of the checkbox.
56178 * On is always based on a string comparison between inputValue and the param.
56179 * @param {Boolean/String} value - the value to set
56180 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
56182 setValue : function(v,suppressEvent){
56183 if (!this.el.dom) {
56186 var old = this.el.dom.value ;
56187 this.el.dom.value = v;
56188 if (suppressEvent) {
56192 // update display..
56193 this.viewEl.select('img',true).each(function(e,i,n) {
56195 var on = e.is(".x-menu-item-checked");
56196 var newv = v.indexOf(String(n)) > -1;
56198 e.toggleClass('x-menu-item-checked');
56204 this.fireEvent('change', this, v, old);
56209 // handle setting of hidden value by some other method!!?!?
56210 setFromHidden: function()
56215 //console.log("SET FROM HIDDEN");
56216 //alert('setFrom hidden');
56217 this.setValue(this.el.dom.value);
56220 onDestroy : function()
56223 Roo.get(this.viewEl).remove();
56226 Roo.form.DayPicker.superclass.onDestroy.call(this);
56230 * RooJS Library 1.1.1
56231 * Copyright(c) 2008-2011 Alan Knowles
56238 * @class Roo.form.ComboCheck
56239 * @extends Roo.form.ComboBox
56240 * A combobox for multiple select items.
56242 * FIXME - could do with a reset button..
56245 * Create a new ComboCheck
56246 * @param {Object} config Configuration options
56248 Roo.form.ComboCheck = function(config){
56249 Roo.form.ComboCheck.superclass.constructor.call(this, config);
56250 // should verify some data...
56252 // hiddenName = required..
56253 // displayField = required
56254 // valudField == required
56255 var req= [ 'hiddenName', 'displayField', 'valueField' ];
56257 Roo.each(req, function(e) {
56258 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
56259 throw "Roo.form.ComboCheck : missing value for: " + e;
56266 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
56271 selectedClass: 'x-menu-item-checked',
56274 onRender : function(ct, position){
56280 var cls = 'x-combo-list';
56283 this.tpl = new Roo.Template({
56284 html : '<div class="'+cls+'-item x-menu-check-item">' +
56285 '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' +
56286 '<span>{' + this.displayField + '}</span>' +
56293 Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
56294 this.view.singleSelect = false;
56295 this.view.multiSelect = true;
56296 this.view.toggleSelect = true;
56297 this.pageTb.add(new Roo.Toolbar.Fill(), {
56300 handler: function()
56307 onViewOver : function(e, t){
56313 onViewClick : function(doFocus,index){
56317 select: function () {
56318 //Roo.log("SELECT CALLED");
56321 selectByValue : function(xv, scrollIntoView){
56322 var ar = this.getValueArray();
56325 Roo.each(ar, function(v) {
56326 if(v === undefined || v === null){
56329 var r = this.findRecord(this.valueField, v);
56331 sels.push(this.store.indexOf(r))
56335 this.view.select(sels);
56341 onSelect : function(record, index){
56342 // Roo.log("onselect Called");
56343 // this is only called by the clear button now..
56344 this.view.clearSelections();
56345 this.setValue('[]');
56346 if (this.value != this.valueBefore) {
56347 this.fireEvent('change', this, this.value, this.valueBefore);
56348 this.valueBefore = this.value;
56351 getValueArray : function()
56356 //Roo.log(this.value);
56357 if (typeof(this.value) == 'undefined') {
56360 var ar = Roo.decode(this.value);
56361 return ar instanceof Array ? ar : []; //?? valid?
56364 Roo.log(e + "\nRoo.form.ComboCheck:getValueArray invalid data:" + this.getValue());
56369 expand : function ()
56372 Roo.form.ComboCheck.superclass.expand.call(this);
56373 this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
56374 //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
56379 collapse : function(){
56380 Roo.form.ComboCheck.superclass.collapse.call(this);
56381 var sl = this.view.getSelectedIndexes();
56382 var st = this.store;
56386 Roo.each(sl, function(i) {
56388 nv.push(r.get(this.valueField));
56390 this.setValue(Roo.encode(nv));
56391 if (this.value != this.valueBefore) {
56393 this.fireEvent('change', this, this.value, this.valueBefore);
56394 this.valueBefore = this.value;
56399 setValue : function(v){
56403 var vals = this.getValueArray();
56405 Roo.each(vals, function(k) {
56406 var r = this.findRecord(this.valueField, k);
56408 tv.push(r.data[this.displayField]);
56409 }else if(this.valueNotFoundText !== undefined){
56410 tv.push( this.valueNotFoundText );
56415 Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
56416 this.hiddenField.value = v;
56422 * Ext JS Library 1.1.1
56423 * Copyright(c) 2006-2007, Ext JS, LLC.
56425 * Originally Released Under LGPL - original licence link has changed is not relivant.
56428 * <script type="text/javascript">
56432 * @class Roo.form.Signature
56433 * @extends Roo.form.Field
56437 * @param {Object} config Configuration options
56440 Roo.form.Signature = function(config){
56441 Roo.form.Signature.superclass.constructor.call(this, config);
56443 this.addEvents({// not in used??
56446 * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
56447 * @param {Roo.form.Signature} combo This combo box
56452 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
56453 * @param {Roo.form.ComboBox} combo This combo box
56454 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
56460 Roo.extend(Roo.form.Signature, Roo.form.Field, {
56462 * @cfg {Object} labels Label to use when rendering a form.
56466 * confirm : "Confirm"
56471 confirm : "Confirm"
56474 * @cfg {Number} width The signature panel width (defaults to 300)
56478 * @cfg {Number} height The signature panel height (defaults to 100)
56482 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
56484 allowBlank : false,
56487 // {Object} signPanel The signature SVG panel element (defaults to {})
56489 // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
56490 isMouseDown : false,
56491 // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
56492 isConfirmed : false,
56493 // {String} signatureTmp SVG mapping string (defaults to empty string)
56497 defaultAutoCreate : { // modified by initCompnoent..
56503 onRender : function(ct, position){
56505 Roo.form.Signature.superclass.onRender.call(this, ct, position);
56507 this.wrap = this.el.wrap({
56508 cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
56511 this.createToolbar(this);
56512 this.signPanel = this.wrap.createChild({
56514 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
56518 this.svgID = Roo.id();
56519 this.svgEl = this.signPanel.createChild({
56520 xmlns : 'http://www.w3.org/2000/svg',
56522 id : this.svgID + "-svg",
56524 height: this.height,
56525 viewBox: '0 0 '+this.width+' '+this.height,
56529 id: this.svgID + "-svg-r",
56531 height: this.height,
56536 id: this.svgID + "-svg-l",
56538 y1: (this.height*0.8), // start set the line in 80% of height
56539 x2: this.width, // end
56540 y2: (this.height*0.8), // end set the line in 80% of height
56542 'stroke-width': "1",
56543 'stroke-dasharray': "3",
56544 'shape-rendering': "crispEdges",
56545 'pointer-events': "none"
56549 id: this.svgID + "-svg-p",
56551 'stroke-width': "3",
56553 'pointer-events': 'none'
56558 this.svgBox = this.svgEl.dom.getScreenCTM();
56560 createSVG : function(){
56561 var svg = this.signPanel;
56562 var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
56565 r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
56566 r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
56567 r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
56568 r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
56569 r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
56570 r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
56571 r.addEventListener('touchend', function(e) { return t.up(e); }, false);
56574 isTouchEvent : function(e){
56575 return e.type.match(/^touch/);
56577 getCoords : function (e) {
56578 var pt = this.svgEl.dom.createSVGPoint();
56581 if (this.isTouchEvent(e)) {
56582 pt.x = e.targetTouches[0].clientX;
56583 pt.y = e.targetTouches[0].clientY;
56585 var a = this.svgEl.dom.getScreenCTM();
56586 var b = a.inverse();
56587 var mx = pt.matrixTransform(b);
56588 return mx.x + ',' + mx.y;
56590 //mouse event headler
56591 down : function (e) {
56592 this.signatureTmp += 'M' + this.getCoords(e) + ' ';
56593 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
56595 this.isMouseDown = true;
56597 e.preventDefault();
56599 move : function (e) {
56600 if (this.isMouseDown) {
56601 this.signatureTmp += 'L' + this.getCoords(e) + ' ';
56602 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
56605 e.preventDefault();
56607 up : function (e) {
56608 this.isMouseDown = false;
56609 var sp = this.signatureTmp.split(' ');
56612 if(!sp[sp.length-2].match(/^L/)){
56616 this.signatureTmp = sp.join(" ");
56619 if(this.getValue() != this.signatureTmp){
56620 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
56621 this.isConfirmed = false;
56623 e.preventDefault();
56627 * Protected method that will not generally be called directly. It
56628 * is called when the editor creates its toolbar. Override this method if you need to
56629 * add custom toolbar buttons.
56630 * @param {HtmlEditor} editor
56632 createToolbar : function(editor){
56633 function btn(id, toggle, handler){
56634 var xid = fid + '-'+ id ;
56638 cls : 'x-btn-icon x-edit-'+id,
56639 enableToggle:toggle !== false,
56640 scope: editor, // was editor...
56641 handler:handler||editor.relayBtnCmd,
56642 clickEvent:'mousedown',
56643 tooltip: etb.buttonTips[id] || undefined, ///tips ???
56649 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
56653 cls : ' x-signature-btn x-signature-'+id,
56654 scope: editor, // was editor...
56655 handler: this.reset,
56656 clickEvent:'mousedown',
56657 text: this.labels.clear
56664 cls : ' x-signature-btn x-signature-'+id,
56665 scope: editor, // was editor...
56666 handler: this.confirmHandler,
56667 clickEvent:'mousedown',
56668 text: this.labels.confirm
56675 * when user is clicked confirm then show this image.....
56677 * @return {String} Image Data URI
56679 getImageDataURI : function(){
56680 var svg = this.svgEl.dom.parentNode.innerHTML;
56681 var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
56686 * @return {Boolean} this.isConfirmed
56688 getConfirmed : function(){
56689 return this.isConfirmed;
56693 * @return {Number} this.width
56695 getWidth : function(){
56700 * @return {Number} this.height
56702 getHeight : function(){
56703 return this.height;
56706 getSignature : function(){
56707 return this.signatureTmp;
56710 reset : function(){
56711 this.signatureTmp = '';
56712 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
56713 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
56714 this.isConfirmed = false;
56715 Roo.form.Signature.superclass.reset.call(this);
56717 setSignature : function(s){
56718 this.signatureTmp = s;
56719 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
56720 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
56722 this.isConfirmed = false;
56723 Roo.form.Signature.superclass.reset.call(this);
56726 // Roo.log(this.signPanel.dom.contentWindow.up())
56729 setConfirmed : function(){
56733 // Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
56736 confirmHandler : function(){
56737 if(!this.getSignature()){
56741 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
56742 this.setValue(this.getSignature());
56743 this.isConfirmed = true;
56745 this.fireEvent('confirm', this);
56748 // Subclasses should provide the validation implementation by overriding this
56749 validateValue : function(value){
56750 if(this.allowBlank){
56754 if(this.isConfirmed){
56761 * Ext JS Library 1.1.1
56762 * Copyright(c) 2006-2007, Ext JS, LLC.
56764 * Originally Released Under LGPL - original licence link has changed is not relivant.
56767 * <script type="text/javascript">
56772 * @class Roo.form.ComboBox
56773 * @extends Roo.form.TriggerField
56774 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
56776 * Create a new ComboBox.
56777 * @param {Object} config Configuration options
56779 Roo.form.Select = function(config){
56780 Roo.form.Select.superclass.constructor.call(this, config);
56784 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
56786 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
56789 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
56790 * rendering into an Roo.Editor, defaults to false)
56793 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
56794 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
56797 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
56800 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
56801 * the dropdown list (defaults to undefined, with no header element)
56805 * @cfg {String/Roo.Template} tpl The template to use to render the output
56809 defaultAutoCreate : {tag: "select" },
56811 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
56813 listWidth: undefined,
56815 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
56816 * mode = 'remote' or 'text' if mode = 'local')
56818 displayField: undefined,
56820 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
56821 * mode = 'remote' or 'value' if mode = 'local').
56822 * Note: use of a valueField requires the user make a selection
56823 * in order for a value to be mapped.
56825 valueField: undefined,
56829 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
56830 * field's data value (defaults to the underlying DOM element's name)
56832 hiddenName: undefined,
56834 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
56838 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
56840 selectedClass: 'x-combo-selected',
56842 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
56843 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
56844 * which displays a downward arrow icon).
56846 triggerClass : 'x-form-arrow-trigger',
56848 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
56852 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
56853 * anchor positions (defaults to 'tl-bl')
56855 listAlign: 'tl-bl?',
56857 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
56861 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
56862 * query specified by the allQuery config option (defaults to 'query')
56864 triggerAction: 'query',
56866 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
56867 * (defaults to 4, does not apply if editable = false)
56871 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
56872 * delay (typeAheadDelay) if it matches a known value (defaults to false)
56876 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
56877 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
56881 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
56882 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
56886 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
56887 * when editable = true (defaults to false)
56889 selectOnFocus:false,
56891 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
56893 queryParam: 'query',
56895 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
56896 * when mode = 'remote' (defaults to 'Loading...')
56898 loadingText: 'Loading...',
56900 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
56904 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
56908 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
56909 * traditional select (defaults to true)
56913 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
56917 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
56921 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
56922 * listWidth has a higher value)
56926 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
56927 * allow the user to set arbitrary text into the field (defaults to false)
56929 forceSelection:false,
56931 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
56932 * if typeAhead = true (defaults to 250)
56934 typeAheadDelay : 250,
56936 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
56937 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
56939 valueNotFoundText : undefined,
56942 * @cfg {String} defaultValue The value displayed after loading the store.
56947 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
56949 blockFocus : false,
56952 * @cfg {Boolean} disableClear Disable showing of clear button.
56954 disableClear : false,
56956 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
56958 alwaysQuery : false,
56964 // element that contains real text value.. (when hidden is used..)
56967 onRender : function(ct, position){
56968 Roo.form.Field.prototype.onRender.call(this, ct, position);
56971 this.store.on('beforeload', this.onBeforeLoad, this);
56972 this.store.on('load', this.onLoad, this);
56973 this.store.on('loadexception', this.onLoadException, this);
56974 this.store.load({});
56982 initEvents : function(){
56983 //Roo.form.ComboBox.superclass.initEvents.call(this);
56987 onDestroy : function(){
56990 this.store.un('beforeload', this.onBeforeLoad, this);
56991 this.store.un('load', this.onLoad, this);
56992 this.store.un('loadexception', this.onLoadException, this);
56994 //Roo.form.ComboBox.superclass.onDestroy.call(this);
56998 fireKey : function(e){
56999 if(e.isNavKeyPress() && !this.list.isVisible()){
57000 this.fireEvent("specialkey", this, e);
57005 onResize: function(w, h){
57013 * Allow or prevent the user from directly editing the field text. If false is passed,
57014 * the user will only be able to select from the items defined in the dropdown list. This method
57015 * is the runtime equivalent of setting the 'editable' config option at config time.
57016 * @param {Boolean} value True to allow the user to directly edit the field text
57018 setEditable : function(value){
57023 onBeforeLoad : function(){
57025 Roo.log("Select before load");
57028 this.innerList.update(this.loadingText ?
57029 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
57030 //this.restrictHeight();
57031 this.selectedIndex = -1;
57035 onLoad : function(){
57038 var dom = this.el.dom;
57039 dom.innerHTML = '';
57040 var od = dom.ownerDocument;
57042 if (this.emptyText) {
57043 var op = od.createElement('option');
57044 op.setAttribute('value', '');
57045 op.innerHTML = String.format('{0}', this.emptyText);
57046 dom.appendChild(op);
57048 if(this.store.getCount() > 0){
57050 var vf = this.valueField;
57051 var df = this.displayField;
57052 this.store.data.each(function(r) {
57053 // which colmsn to use... testing - cdoe / title..
57054 var op = od.createElement('option');
57055 op.setAttribute('value', r.data[vf]);
57056 op.innerHTML = String.format('{0}', r.data[df]);
57057 dom.appendChild(op);
57059 if (typeof(this.defaultValue != 'undefined')) {
57060 this.setValue(this.defaultValue);
57065 //this.onEmptyResults();
57070 onLoadException : function()
57072 dom.innerHTML = '';
57074 Roo.log("Select on load exception");
57078 Roo.log(this.store.reader.jsonData);
57079 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
57080 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
57086 onTypeAhead : function(){
57091 onSelect : function(record, index){
57092 Roo.log('on select?');
57094 if(this.fireEvent('beforeselect', this, record, index) !== false){
57095 this.setFromData(index > -1 ? record.data : false);
57097 this.fireEvent('select', this, record, index);
57102 * Returns the currently selected field value or empty string if no value is set.
57103 * @return {String} value The selected value
57105 getValue : function(){
57106 var dom = this.el.dom;
57107 this.value = dom.options[dom.selectedIndex].value;
57113 * Clears any text/value currently set in the field
57115 clearValue : function(){
57117 this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
57122 * Sets the specified value into the field. If the value finds a match, the corresponding record text
57123 * will be displayed in the field. If the value does not match the data value of an existing item,
57124 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
57125 * Otherwise the field will be blank (although the value will still be set).
57126 * @param {String} value The value to match
57128 setValue : function(v){
57129 var d = this.el.dom;
57130 for (var i =0; i < d.options.length;i++) {
57131 if (v == d.options[i].value) {
57132 d.selectedIndex = i;
57140 * @property {Object} the last set data for the element
57145 * Sets the value of the field based on a object which is related to the record format for the store.
57146 * @param {Object} value the value to set as. or false on reset?
57148 setFromData : function(o){
57149 Roo.log('setfrom data?');
57155 reset : function(){
57159 findRecord : function(prop, value){
57164 if(this.store.getCount() > 0){
57165 this.store.each(function(r){
57166 if(r.data[prop] == value){
57176 getName: function()
57178 // returns hidden if it's set..
57179 if (!this.rendered) {return ''};
57180 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
57188 onEmptyResults : function(){
57189 Roo.log('empty results');
57194 * Returns true if the dropdown list is expanded, else false.
57196 isExpanded : function(){
57201 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
57202 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
57203 * @param {String} value The data value of the item to select
57204 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
57205 * selected item if it is not currently in view (defaults to true)
57206 * @return {Boolean} True if the value matched an item in the list, else false
57208 selectByValue : function(v, scrollIntoView){
57209 Roo.log('select By Value');
57212 if(v !== undefined && v !== null){
57213 var r = this.findRecord(this.valueField || this.displayField, v);
57215 this.select(this.store.indexOf(r), scrollIntoView);
57223 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
57224 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
57225 * @param {Number} index The zero-based index of the list item to select
57226 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
57227 * selected item if it is not currently in view (defaults to true)
57229 select : function(index, scrollIntoView){
57230 Roo.log('select ');
57233 this.selectedIndex = index;
57234 this.view.select(index);
57235 if(scrollIntoView !== false){
57236 var el = this.view.getNode(index);
57238 this.innerList.scrollChildIntoView(el, false);
57246 validateBlur : function(){
57253 initQuery : function(){
57254 this.doQuery(this.getRawValue());
57258 doForce : function(){
57259 if(this.el.dom.value.length > 0){
57260 this.el.dom.value =
57261 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
57267 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
57268 * query allowing the query action to be canceled if needed.
57269 * @param {String} query The SQL query to execute
57270 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
57271 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
57272 * saved in the current store (defaults to false)
57274 doQuery : function(q, forceAll){
57276 Roo.log('doQuery?');
57277 if(q === undefined || q === null){
57282 forceAll: forceAll,
57286 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
57290 forceAll = qe.forceAll;
57291 if(forceAll === true || (q.length >= this.minChars)){
57292 if(this.lastQuery != q || this.alwaysQuery){
57293 this.lastQuery = q;
57294 if(this.mode == 'local'){
57295 this.selectedIndex = -1;
57297 this.store.clearFilter();
57299 this.store.filter(this.displayField, q);
57303 this.store.baseParams[this.queryParam] = q;
57305 params: this.getParams(q)
57310 this.selectedIndex = -1;
57317 getParams : function(q){
57319 //p[this.queryParam] = q;
57322 p.limit = this.pageSize;
57328 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
57330 collapse : function(){
57335 collapseIf : function(e){
57340 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
57342 expand : function(){
57350 * @cfg {Boolean} grow
57354 * @cfg {Number} growMin
57358 * @cfg {Number} growMax
57366 setWidth : function()
57370 getResizeEl : function(){
57373 });//<script type="text/javasscript">
57377 * @class Roo.DDView
57378 * A DnD enabled version of Roo.View.
57379 * @param {Element/String} container The Element in which to create the View.
57380 * @param {String} tpl The template string used to create the markup for each element of the View
57381 * @param {Object} config The configuration properties. These include all the config options of
57382 * {@link Roo.View} plus some specific to this class.<br>
57384 * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
57385 * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
57387 * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
57388 .x-view-drag-insert-above {
57389 border-top:1px dotted #3366cc;
57391 .x-view-drag-insert-below {
57392 border-bottom:1px dotted #3366cc;
57398 Roo.DDView = function(container, tpl, config) {
57399 Roo.DDView.superclass.constructor.apply(this, arguments);
57400 this.getEl().setStyle("outline", "0px none");
57401 this.getEl().unselectable();
57402 if (this.dragGroup) {
57403 this.setDraggable(this.dragGroup.split(","));
57405 if (this.dropGroup) {
57406 this.setDroppable(this.dropGroup.split(","));
57408 if (this.deletable) {
57409 this.setDeletable();
57411 this.isDirtyFlag = false;
57417 Roo.extend(Roo.DDView, Roo.View, {
57418 /** @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
57419 /** @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
57420 /** @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
57421 /** @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
57425 reset: Roo.emptyFn,
57427 clearInvalid: Roo.form.Field.prototype.clearInvalid,
57429 validate: function() {
57433 destroy: function() {
57434 this.purgeListeners();
57435 this.getEl.removeAllListeners();
57436 this.getEl().remove();
57437 if (this.dragZone) {
57438 if (this.dragZone.destroy) {
57439 this.dragZone.destroy();
57442 if (this.dropZone) {
57443 if (this.dropZone.destroy) {
57444 this.dropZone.destroy();
57449 /** Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
57450 getName: function() {
57454 /** Loads the View from a JSON string representing the Records to put into the Store. */
57455 setValue: function(v) {
57457 throw "DDView.setValue(). DDView must be constructed with a valid Store";
57460 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
57461 this.store.proxy = new Roo.data.MemoryProxy(data);
57465 /** @return {String} a parenthesised list of the ids of the Records in the View. */
57466 getValue: function() {
57468 this.store.each(function(rec) {
57469 result += rec.id + ',';
57471 return result.substr(0, result.length - 1) + ')';
57474 getIds: function() {
57475 var i = 0, result = new Array(this.store.getCount());
57476 this.store.each(function(rec) {
57477 result[i++] = rec.id;
57482 isDirty: function() {
57483 return this.isDirtyFlag;
57487 * Part of the Roo.dd.DropZone interface. If no target node is found, the
57488 * whole Element becomes the target, and this causes the drop gesture to append.
57490 getTargetFromEvent : function(e) {
57491 var target = e.getTarget();
57492 while ((target !== null) && (target.parentNode != this.el.dom)) {
57493 target = target.parentNode;
57496 target = this.el.dom.lastChild || this.el.dom;
57502 * Create the drag data which consists of an object which has the property "ddel" as
57503 * the drag proxy element.
57505 getDragData : function(e) {
57506 var target = this.findItemFromChild(e.getTarget());
57508 this.handleSelection(e);
57509 var selNodes = this.getSelectedNodes();
57512 copy: this.copy || (this.allowCopy && e.ctrlKey),
57516 var selectedIndices = this.getSelectedIndexes();
57517 for (var i = 0; i < selectedIndices.length; i++) {
57518 dragData.records.push(this.store.getAt(selectedIndices[i]));
57520 if (selNodes.length == 1) {
57521 dragData.ddel = target.cloneNode(true); // the div element
57523 var div = document.createElement('div'); // create the multi element drag "ghost"
57524 div.className = 'multi-proxy';
57525 for (var i = 0, len = selNodes.length; i < len; i++) {
57526 div.appendChild(selNodes[i].cloneNode(true));
57528 dragData.ddel = div;
57530 //console.log(dragData)
57531 //console.log(dragData.ddel.innerHTML)
57534 //console.log('nodragData')
57538 /** Specify to which ddGroup items in this DDView may be dragged. */
57539 setDraggable: function(ddGroup) {
57540 if (ddGroup instanceof Array) {
57541 Roo.each(ddGroup, this.setDraggable, this);
57544 if (this.dragZone) {
57545 this.dragZone.addToGroup(ddGroup);
57547 this.dragZone = new Roo.dd.DragZone(this.getEl(), {
57548 containerScroll: true,
57552 // Draggability implies selection. DragZone's mousedown selects the element.
57553 if (!this.multiSelect) { this.singleSelect = true; }
57555 // Wire the DragZone's handlers up to methods in *this*
57556 this.dragZone.getDragData = this.getDragData.createDelegate(this);
57560 /** Specify from which ddGroup this DDView accepts drops. */
57561 setDroppable: function(ddGroup) {
57562 if (ddGroup instanceof Array) {
57563 Roo.each(ddGroup, this.setDroppable, this);
57566 if (this.dropZone) {
57567 this.dropZone.addToGroup(ddGroup);
57569 this.dropZone = new Roo.dd.DropZone(this.getEl(), {
57570 containerScroll: true,
57574 // Wire the DropZone's handlers up to methods in *this*
57575 this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
57576 this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
57577 this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
57578 this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
57579 this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
57583 /** Decide whether to drop above or below a View node. */
57584 getDropPoint : function(e, n, dd){
57585 if (n == this.el.dom) { return "above"; }
57586 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
57587 var c = t + (b - t) / 2;
57588 var y = Roo.lib.Event.getPageY(e);
57596 onNodeEnter : function(n, dd, e, data){
57600 onNodeOver : function(n, dd, e, data){
57601 var pt = this.getDropPoint(e, n, dd);
57602 // set the insert point style on the target node
57603 var dragElClass = this.dropNotAllowed;
57606 if (pt == "above"){
57607 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
57608 targetElClass = "x-view-drag-insert-above";
57610 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
57611 targetElClass = "x-view-drag-insert-below";
57613 if (this.lastInsertClass != targetElClass){
57614 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
57615 this.lastInsertClass = targetElClass;
57618 return dragElClass;
57621 onNodeOut : function(n, dd, e, data){
57622 this.removeDropIndicators(n);
57625 onNodeDrop : function(n, dd, e, data){
57626 if (this.fireEvent("drop", this, n, dd, e, data) === false) {
57629 var pt = this.getDropPoint(e, n, dd);
57630 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
57631 if (pt == "below") { insertAt++; }
57632 for (var i = 0; i < data.records.length; i++) {
57633 var r = data.records[i];
57634 var dup = this.store.getById(r.id);
57635 if (dup && (dd != this.dragZone)) {
57636 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
57639 this.store.insert(insertAt++, r.copy());
57641 data.source.isDirtyFlag = true;
57643 this.store.insert(insertAt++, r);
57645 this.isDirtyFlag = true;
57648 this.dragZone.cachedTarget = null;
57652 removeDropIndicators : function(n){
57654 Roo.fly(n).removeClass([
57655 "x-view-drag-insert-above",
57656 "x-view-drag-insert-below"]);
57657 this.lastInsertClass = "_noclass";
57662 * Utility method. Add a delete option to the DDView's context menu.
57663 * @param {String} imageUrl The URL of the "delete" icon image.
57665 setDeletable: function(imageUrl) {
57666 if (!this.singleSelect && !this.multiSelect) {
57667 this.singleSelect = true;
57669 var c = this.getContextMenu();
57670 this.contextMenu.on("itemclick", function(item) {
57673 this.remove(this.getSelectedIndexes());
57677 this.contextMenu.add({
57684 /** Return the context menu for this DDView. */
57685 getContextMenu: function() {
57686 if (!this.contextMenu) {
57687 // Create the View's context menu
57688 this.contextMenu = new Roo.menu.Menu({
57689 id: this.id + "-contextmenu"
57691 this.el.on("contextmenu", this.showContextMenu, this);
57693 return this.contextMenu;
57696 disableContextMenu: function() {
57697 if (this.contextMenu) {
57698 this.el.un("contextmenu", this.showContextMenu, this);
57702 showContextMenu: function(e, item) {
57703 item = this.findItemFromChild(e.getTarget());
57706 this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
57707 this.contextMenu.showAt(e.getXY());
57712 * Remove {@link Roo.data.Record}s at the specified indices.
57713 * @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
57715 remove: function(selectedIndices) {
57716 selectedIndices = [].concat(selectedIndices);
57717 for (var i = 0; i < selectedIndices.length; i++) {
57718 var rec = this.store.getAt(selectedIndices[i]);
57719 this.store.remove(rec);
57724 * Double click fires the event, but also, if this is draggable, and there is only one other
57725 * related DropZone, it transfers the selected node.
57727 onDblClick : function(e){
57728 var item = this.findItemFromChild(e.getTarget());
57730 if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
57733 if (this.dragGroup) {
57734 var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
57735 while (targets.indexOf(this.dropZone) > -1) {
57736 targets.remove(this.dropZone);
57738 if (targets.length == 1) {
57739 this.dragZone.cachedTarget = null;
57740 var el = Roo.get(targets[0].getEl());
57741 var box = el.getBox(true);
57742 targets[0].onNodeDrop(el.dom, {
57744 xy: [box.x, box.y + box.height - 1]
57745 }, null, this.getDragData(e));
57751 handleSelection: function(e) {
57752 this.dragZone.cachedTarget = null;
57753 var item = this.findItemFromChild(e.getTarget());
57755 this.clearSelections(true);
57758 if (item && (this.multiSelect || this.singleSelect)){
57759 if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
57760 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
57761 }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
57762 this.unselect(item);
57764 this.select(item, this.multiSelect && e.ctrlKey);
57765 this.lastSelection = item;
57770 onItemClick : function(item, index, e){
57771 if(this.fireEvent("beforeclick", this, index, item, e) === false){
57777 unselect : function(nodeInfo, suppressEvent){
57778 var node = this.getNode(nodeInfo);
57779 if(node && this.isSelected(node)){
57780 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
57781 Roo.fly(node).removeClass(this.selectedClass);
57782 this.selections.remove(node);
57783 if(!suppressEvent){
57784 this.fireEvent("selectionchange", this, this.selections);
57792 * Ext JS Library 1.1.1
57793 * Copyright(c) 2006-2007, Ext JS, LLC.
57795 * Originally Released Under LGPL - original licence link has changed is not relivant.
57798 * <script type="text/javascript">
57802 * @class Roo.LayoutManager
57803 * @extends Roo.util.Observable
57804 * Base class for layout managers.
57806 Roo.LayoutManager = function(container, config){
57807 Roo.LayoutManager.superclass.constructor.call(this);
57808 this.el = Roo.get(container);
57809 // ie scrollbar fix
57810 if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
57811 document.body.scroll = "no";
57812 }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
57813 this.el.position('relative');
57815 this.id = this.el.id;
57816 this.el.addClass("x-layout-container");
57817 /** false to disable window resize monitoring @type Boolean */
57818 this.monitorWindowResize = true;
57823 * Fires when a layout is performed.
57824 * @param {Roo.LayoutManager} this
57828 * @event regionresized
57829 * Fires when the user resizes a region.
57830 * @param {Roo.LayoutRegion} region The resized region
57831 * @param {Number} newSize The new size (width for east/west, height for north/south)
57833 "regionresized" : true,
57835 * @event regioncollapsed
57836 * Fires when a region is collapsed.
57837 * @param {Roo.LayoutRegion} region The collapsed region
57839 "regioncollapsed" : true,
57841 * @event regionexpanded
57842 * Fires when a region is expanded.
57843 * @param {Roo.LayoutRegion} region The expanded region
57845 "regionexpanded" : true
57847 this.updating = false;
57848 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
57851 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
57853 * Returns true if this layout is currently being updated
57854 * @return {Boolean}
57856 isUpdating : function(){
57857 return this.updating;
57861 * Suspend the LayoutManager from doing auto-layouts while
57862 * making multiple add or remove calls
57864 beginUpdate : function(){
57865 this.updating = true;
57869 * Restore auto-layouts and optionally disable the manager from performing a layout
57870 * @param {Boolean} noLayout true to disable a layout update
57872 endUpdate : function(noLayout){
57873 this.updating = false;
57879 layout: function(){
57883 onRegionResized : function(region, newSize){
57884 this.fireEvent("regionresized", region, newSize);
57888 onRegionCollapsed : function(region){
57889 this.fireEvent("regioncollapsed", region);
57892 onRegionExpanded : function(region){
57893 this.fireEvent("regionexpanded", region);
57897 * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
57898 * performs box-model adjustments.
57899 * @return {Object} The size as an object {width: (the width), height: (the height)}
57901 getViewSize : function(){
57903 if(this.el.dom != document.body){
57904 size = this.el.getSize();
57906 size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
57908 size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
57909 size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
57914 * Returns the Element this layout is bound to.
57915 * @return {Roo.Element}
57917 getEl : function(){
57922 * Returns the specified region.
57923 * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
57924 * @return {Roo.LayoutRegion}
57926 getRegion : function(target){
57927 return this.regions[target.toLowerCase()];
57930 onWindowResize : function(){
57931 if(this.monitorWindowResize){
57937 * Ext JS Library 1.1.1
57938 * Copyright(c) 2006-2007, Ext JS, LLC.
57940 * Originally Released Under LGPL - original licence link has changed is not relivant.
57943 * <script type="text/javascript">
57946 * @class Roo.BorderLayout
57947 * @extends Roo.LayoutManager
57948 * @children Roo.ContentPanel
57949 * This class represents a common layout manager used in desktop applications. For screenshots and more details,
57950 * please see: <br><br>
57951 * <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>
57952 * <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>
57955 var layout = new Roo.BorderLayout(document.body, {
57989 preferredTabWidth: 150
57994 var CP = Roo.ContentPanel;
57996 layout.beginUpdate();
57997 layout.add("north", new CP("north", "North"));
57998 layout.add("south", new CP("south", {title: "South", closable: true}));
57999 layout.add("west", new CP("west", {title: "West"}));
58000 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
58001 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
58002 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
58003 layout.getRegion("center").showPanel("center1");
58004 layout.endUpdate();
58007 <b>The container the layout is rendered into can be either the body element or any other element.
58008 If it is not the body element, the container needs to either be an absolute positioned element,
58009 or you will need to add "position:relative" to the css of the container. You will also need to specify
58010 the container size if it is not the body element.</b>
58013 * Create a new BorderLayout
58014 * @param {String/HTMLElement/Element} container The container this layout is bound to
58015 * @param {Object} config Configuration options
58017 Roo.BorderLayout = function(container, config){
58018 config = config || {};
58019 Roo.BorderLayout.superclass.constructor.call(this, container, config);
58020 this.factory = config.factory || Roo.BorderLayout.RegionFactory;
58021 for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
58022 var target = this.factory.validRegions[i];
58023 if(config[target]){
58024 this.addRegion(target, config[target]);
58029 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
58032 * @cfg {Roo.LayoutRegion} east
58035 * @cfg {Roo.LayoutRegion} west
58038 * @cfg {Roo.LayoutRegion} north
58041 * @cfg {Roo.LayoutRegion} south
58044 * @cfg {Roo.LayoutRegion} center
58047 * Creates and adds a new region if it doesn't already exist.
58048 * @param {String} target The target region key (north, south, east, west or center).
58049 * @param {Object} config The regions config object
58050 * @return {BorderLayoutRegion} The new region
58052 addRegion : function(target, config){
58053 if(!this.regions[target]){
58054 var r = this.factory.create(target, this, config);
58055 this.bindRegion(target, r);
58057 return this.regions[target];
58061 bindRegion : function(name, r){
58062 this.regions[name] = r;
58063 r.on("visibilitychange", this.layout, this);
58064 r.on("paneladded", this.layout, this);
58065 r.on("panelremoved", this.layout, this);
58066 r.on("invalidated", this.layout, this);
58067 r.on("resized", this.onRegionResized, this);
58068 r.on("collapsed", this.onRegionCollapsed, this);
58069 r.on("expanded", this.onRegionExpanded, this);
58073 * Performs a layout update.
58075 layout : function(){
58076 if(this.updating) {
58079 var size = this.getViewSize();
58080 var w = size.width;
58081 var h = size.height;
58086 //var x = 0, y = 0;
58088 var rs = this.regions;
58089 var north = rs["north"];
58090 var south = rs["south"];
58091 var west = rs["west"];
58092 var east = rs["east"];
58093 var center = rs["center"];
58094 //if(this.hideOnLayout){ // not supported anymore
58095 //c.el.setStyle("display", "none");
58097 if(north && north.isVisible()){
58098 var b = north.getBox();
58099 var m = north.getMargins();
58100 b.width = w - (m.left+m.right);
58103 centerY = b.height + b.y + m.bottom;
58104 centerH -= centerY;
58105 north.updateBox(this.safeBox(b));
58107 if(south && south.isVisible()){
58108 var b = south.getBox();
58109 var m = south.getMargins();
58110 b.width = w - (m.left+m.right);
58112 var totalHeight = (b.height + m.top + m.bottom);
58113 b.y = h - totalHeight + m.top;
58114 centerH -= totalHeight;
58115 south.updateBox(this.safeBox(b));
58117 if(west && west.isVisible()){
58118 var b = west.getBox();
58119 var m = west.getMargins();
58120 b.height = centerH - (m.top+m.bottom);
58122 b.y = centerY + m.top;
58123 var totalWidth = (b.width + m.left + m.right);
58124 centerX += totalWidth;
58125 centerW -= totalWidth;
58126 west.updateBox(this.safeBox(b));
58128 if(east && east.isVisible()){
58129 var b = east.getBox();
58130 var m = east.getMargins();
58131 b.height = centerH - (m.top+m.bottom);
58132 var totalWidth = (b.width + m.left + m.right);
58133 b.x = w - totalWidth + m.left;
58134 b.y = centerY + m.top;
58135 centerW -= totalWidth;
58136 east.updateBox(this.safeBox(b));
58139 var m = center.getMargins();
58141 x: centerX + m.left,
58142 y: centerY + m.top,
58143 width: centerW - (m.left+m.right),
58144 height: centerH - (m.top+m.bottom)
58146 //if(this.hideOnLayout){
58147 //center.el.setStyle("display", "block");
58149 center.updateBox(this.safeBox(centerBox));
58152 this.fireEvent("layout", this);
58156 safeBox : function(box){
58157 box.width = Math.max(0, box.width);
58158 box.height = Math.max(0, box.height);
58163 * Adds a ContentPanel (or subclass) to this layout.
58164 * @param {String} target The target region key (north, south, east, west or center).
58165 * @param {Roo.ContentPanel} panel The panel to add
58166 * @return {Roo.ContentPanel} The added panel
58168 add : function(target, panel){
58170 target = target.toLowerCase();
58171 return this.regions[target].add(panel);
58175 * Remove a ContentPanel (or subclass) to this layout.
58176 * @param {String} target The target region key (north, south, east, west or center).
58177 * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
58178 * @return {Roo.ContentPanel} The removed panel
58180 remove : function(target, panel){
58181 target = target.toLowerCase();
58182 return this.regions[target].remove(panel);
58186 * Searches all regions for a panel with the specified id
58187 * @param {String} panelId
58188 * @return {Roo.ContentPanel} The panel or null if it wasn't found
58190 findPanel : function(panelId){
58191 var rs = this.regions;
58192 for(var target in rs){
58193 if(typeof rs[target] != "function"){
58194 var p = rs[target].getPanel(panelId);
58204 * Searches all regions for a panel with the specified id and activates (shows) it.
58205 * @param {String/ContentPanel} panelId The panels id or the panel itself
58206 * @return {Roo.ContentPanel} The shown panel or null
58208 showPanel : function(panelId) {
58209 var rs = this.regions;
58210 for(var target in rs){
58211 var r = rs[target];
58212 if(typeof r != "function"){
58213 if(r.hasPanel(panelId)){
58214 return r.showPanel(panelId);
58222 * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
58223 * @param {Roo.state.Provider} provider (optional) An alternate state provider
58225 restoreState : function(provider){
58227 provider = Roo.state.Manager;
58229 var sm = new Roo.LayoutStateManager();
58230 sm.init(this, provider);
58234 * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object. This config
58235 * object should contain properties for each region to add ContentPanels to, and each property's value should be
58236 * a valid ContentPanel config object. Example:
58238 // Create the main layout
58239 var layout = new Roo.BorderLayout('main-ct', {
58250 // Create and add multiple ContentPanels at once via configs
58253 id: 'source-files',
58255 title:'Ext Source Files',
58268 * @param {Object} regions An object containing ContentPanel configs by region name
58270 batchAdd : function(regions){
58271 this.beginUpdate();
58272 for(var rname in regions){
58273 var lr = this.regions[rname];
58275 this.addTypedPanels(lr, regions[rname]);
58282 addTypedPanels : function(lr, ps){
58283 if(typeof ps == 'string'){
58284 lr.add(new Roo.ContentPanel(ps));
58286 else if(ps instanceof Array){
58287 for(var i =0, len = ps.length; i < len; i++){
58288 this.addTypedPanels(lr, ps[i]);
58291 else if(!ps.events){ // raw config?
58293 delete ps.el; // prevent conflict
58294 lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
58296 else { // panel object assumed!
58301 * Adds a xtype elements to the layout.
58305 xtype : 'ContentPanel',
58312 xtype : 'NestedLayoutPanel',
58318 items : [ ... list of content panels or nested layout panels.. ]
58322 * @param {Object} cfg Xtype definition of item to add.
58324 addxtype : function(cfg)
58326 // basically accepts a pannel...
58327 // can accept a layout region..!?!?
58328 //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
58330 if (!cfg.xtype.match(/Panel$/)) {
58335 if (typeof(cfg.region) == 'undefined') {
58336 Roo.log("Failed to add Panel, region was not set");
58340 var region = cfg.region;
58346 xitems = cfg.items;
58353 case 'ContentPanel': // ContentPanel (el, cfg)
58354 case 'ScrollPanel': // ContentPanel (el, cfg)
58356 if(cfg.autoCreate) {
58357 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
58359 var el = this.el.createChild();
58360 ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
58363 this.add(region, ret);
58367 case 'TreePanel': // our new panel!
58368 cfg.el = this.el.createChild();
58369 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
58370 this.add(region, ret);
58373 case 'NestedLayoutPanel':
58374 // create a new Layout (which is a Border Layout...
58375 var el = this.el.createChild();
58376 var clayout = cfg.layout;
58378 clayout.items = clayout.items || [];
58379 // replace this exitems with the clayout ones..
58380 xitems = clayout.items;
58383 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
58384 cfg.background = false;
58386 var layout = new Roo.BorderLayout(el, clayout);
58388 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
58389 //console.log('adding nested layout panel ' + cfg.toSource());
58390 this.add(region, ret);
58391 nb = {}; /// find first...
58396 // needs grid and region
58398 //var el = this.getRegion(region).el.createChild();
58399 var el = this.el.createChild();
58400 // create the grid first...
58402 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
58404 if (region == 'center' && this.active ) {
58405 cfg.background = false;
58407 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
58409 this.add(region, ret);
58410 if (cfg.background) {
58411 ret.on('activate', function(gp) {
58412 if (!gp.grid.rendered) {
58427 if (typeof(Roo[cfg.xtype]) != 'undefined') {
58429 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
58430 this.add(region, ret);
58433 alert("Can not add '" + cfg.xtype + "' to BorderLayout");
58437 // GridPanel (grid, cfg)
58440 this.beginUpdate();
58444 Roo.each(xitems, function(i) {
58445 region = nb && i.region ? i.region : false;
58447 var add = ret.addxtype(i);
58450 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
58451 if (!i.background) {
58452 abn[region] = nb[region] ;
58459 // make the last non-background panel active..
58460 //if (nb) { Roo.log(abn); }
58463 for(var r in abn) {
58464 region = this.getRegion(r);
58466 // tried using nb[r], but it does not work..
58468 region.showPanel(abn[r]);
58479 * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
58480 * the beginUpdate and endUpdate calls internally. The key to this method is the <b>panels</b> property that can be
58481 * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
58482 * during creation. The following code is equivalent to the constructor-based example at the beginning of this class:
58485 var CP = Roo.ContentPanel;
58487 var layout = Roo.BorderLayout.create({
58491 panels: [new CP("north", "North")]
58500 panels: [new CP("west", {title: "West"})]
58509 panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
58518 panels: [new CP("south", {title: "South", closable: true})]
58525 preferredTabWidth: 150,
58527 new CP("center1", {title: "Close Me", closable: true}),
58528 new CP("center2", {title: "Center Panel", closable: false})
58533 layout.getRegion("center").showPanel("center1");
58538 Roo.BorderLayout.create = function(config, targetEl){
58539 var layout = new Roo.BorderLayout(targetEl || document.body, config);
58540 layout.beginUpdate();
58541 var regions = Roo.BorderLayout.RegionFactory.validRegions;
58542 for(var j = 0, jlen = regions.length; j < jlen; j++){
58543 var lr = regions[j];
58544 if(layout.regions[lr] && config[lr].panels){
58545 var r = layout.regions[lr];
58546 var ps = config[lr].panels;
58547 layout.addTypedPanels(r, ps);
58550 layout.endUpdate();
58555 Roo.BorderLayout.RegionFactory = {
58557 validRegions : ["north","south","east","west","center"],
58560 create : function(target, mgr, config){
58561 target = target.toLowerCase();
58562 if(config.lightweight || config.basic){
58563 return new Roo.BasicLayoutRegion(mgr, config, target);
58567 return new Roo.NorthLayoutRegion(mgr, config);
58569 return new Roo.SouthLayoutRegion(mgr, config);
58571 return new Roo.EastLayoutRegion(mgr, config);
58573 return new Roo.WestLayoutRegion(mgr, config);
58575 return new Roo.CenterLayoutRegion(mgr, config);
58577 throw 'Layout region "'+target+'" not supported.';
58581 * Ext JS Library 1.1.1
58582 * Copyright(c) 2006-2007, Ext JS, LLC.
58584 * Originally Released Under LGPL - original licence link has changed is not relivant.
58587 * <script type="text/javascript">
58591 * @class Roo.BasicLayoutRegion
58592 * @extends Roo.util.Observable
58593 * This class represents a lightweight region in a layout manager. This region does not move dom nodes
58594 * and does not have a titlebar, tabs or any other features. All it does is size and position
58595 * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
58597 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
58599 this.position = pos;
58602 * @scope Roo.BasicLayoutRegion
58606 * @event beforeremove
58607 * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
58608 * @param {Roo.LayoutRegion} this
58609 * @param {Roo.ContentPanel} panel The panel
58610 * @param {Object} e The cancel event object
58612 "beforeremove" : true,
58614 * @event invalidated
58615 * Fires when the layout for this region is changed.
58616 * @param {Roo.LayoutRegion} this
58618 "invalidated" : true,
58620 * @event visibilitychange
58621 * Fires when this region is shown or hidden
58622 * @param {Roo.LayoutRegion} this
58623 * @param {Boolean} visibility true or false
58625 "visibilitychange" : true,
58627 * @event paneladded
58628 * Fires when a panel is added.
58629 * @param {Roo.LayoutRegion} this
58630 * @param {Roo.ContentPanel} panel The panel
58632 "paneladded" : true,
58634 * @event panelremoved
58635 * Fires when a panel is removed.
58636 * @param {Roo.LayoutRegion} this
58637 * @param {Roo.ContentPanel} panel The panel
58639 "panelremoved" : true,
58641 * @event beforecollapse
58642 * Fires when this region before collapse.
58643 * @param {Roo.LayoutRegion} this
58645 "beforecollapse" : true,
58648 * Fires when this region is collapsed.
58649 * @param {Roo.LayoutRegion} this
58651 "collapsed" : true,
58654 * Fires when this region is expanded.
58655 * @param {Roo.LayoutRegion} this
58660 * Fires when this region is slid into view.
58661 * @param {Roo.LayoutRegion} this
58663 "slideshow" : true,
58666 * Fires when this region slides out of view.
58667 * @param {Roo.LayoutRegion} this
58669 "slidehide" : true,
58671 * @event panelactivated
58672 * Fires when a panel is activated.
58673 * @param {Roo.LayoutRegion} this
58674 * @param {Roo.ContentPanel} panel The activated panel
58676 "panelactivated" : true,
58679 * Fires when the user resizes this region.
58680 * @param {Roo.LayoutRegion} this
58681 * @param {Number} newSize The new size (width for east/west, height for north/south)
58685 /** A collection of panels in this region. @type Roo.util.MixedCollection */
58686 this.panels = new Roo.util.MixedCollection();
58687 this.panels.getKey = this.getPanelId.createDelegate(this);
58689 this.activePanel = null;
58690 // ensure listeners are added...
58692 if (config.listeners || config.events) {
58693 Roo.BasicLayoutRegion.superclass.constructor.call(this, {
58694 listeners : config.listeners || {},
58695 events : config.events || {}
58699 if(skipConfig !== true){
58700 this.applyConfig(config);
58704 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
58705 getPanelId : function(p){
58709 applyConfig : function(config){
58710 this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
58711 this.config = config;
58716 * Resizes the region to the specified size. For vertical regions (west, east) this adjusts
58717 * the width, for horizontal (north, south) the height.
58718 * @param {Number} newSize The new width or height
58720 resizeTo : function(newSize){
58721 var el = this.el ? this.el :
58722 (this.activePanel ? this.activePanel.getEl() : null);
58724 switch(this.position){
58727 el.setWidth(newSize);
58728 this.fireEvent("resized", this, newSize);
58732 el.setHeight(newSize);
58733 this.fireEvent("resized", this, newSize);
58739 getBox : function(){
58740 return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
58743 getMargins : function(){
58744 return this.margins;
58747 updateBox : function(box){
58749 var el = this.activePanel.getEl();
58750 el.dom.style.left = box.x + "px";
58751 el.dom.style.top = box.y + "px";
58752 this.activePanel.setSize(box.width, box.height);
58756 * Returns the container element for this region.
58757 * @return {Roo.Element}
58759 getEl : function(){
58760 return this.activePanel;
58764 * Returns true if this region is currently visible.
58765 * @return {Boolean}
58767 isVisible : function(){
58768 return this.activePanel ? true : false;
58771 setActivePanel : function(panel){
58772 panel = this.getPanel(panel);
58773 if(this.activePanel && this.activePanel != panel){
58774 this.activePanel.setActiveState(false);
58775 this.activePanel.getEl().setLeftTop(-10000,-10000);
58777 this.activePanel = panel;
58778 panel.setActiveState(true);
58780 panel.setSize(this.box.width, this.box.height);
58782 this.fireEvent("panelactivated", this, panel);
58783 this.fireEvent("invalidated");
58787 * Show the specified panel.
58788 * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
58789 * @return {Roo.ContentPanel} The shown panel or null
58791 showPanel : function(panel){
58792 if(panel = this.getPanel(panel)){
58793 this.setActivePanel(panel);
58799 * Get the active panel for this region.
58800 * @return {Roo.ContentPanel} The active panel or null
58802 getActivePanel : function(){
58803 return this.activePanel;
58807 * Add the passed ContentPanel(s)
58808 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
58809 * @return {Roo.ContentPanel} The panel added (if only one was added)
58811 add : function(panel){
58812 if(arguments.length > 1){
58813 for(var i = 0, len = arguments.length; i < len; i++) {
58814 this.add(arguments[i]);
58818 if(this.hasPanel(panel)){
58819 this.showPanel(panel);
58822 var el = panel.getEl();
58823 if(el.dom.parentNode != this.mgr.el.dom){
58824 this.mgr.el.dom.appendChild(el.dom);
58826 if(panel.setRegion){
58827 panel.setRegion(this);
58829 this.panels.add(panel);
58830 el.setStyle("position", "absolute");
58831 if(!panel.background){
58832 this.setActivePanel(panel);
58833 if(this.config.initialSize && this.panels.getCount()==1){
58834 this.resizeTo(this.config.initialSize);
58837 this.fireEvent("paneladded", this, panel);
58842 * Returns true if the panel is in this region.
58843 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
58844 * @return {Boolean}
58846 hasPanel : function(panel){
58847 if(typeof panel == "object"){ // must be panel obj
58848 panel = panel.getId();
58850 return this.getPanel(panel) ? true : false;
58854 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
58855 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
58856 * @param {Boolean} preservePanel Overrides the config preservePanel option
58857 * @return {Roo.ContentPanel} The panel that was removed
58859 remove : function(panel, preservePanel){
58860 panel = this.getPanel(panel);
58865 this.fireEvent("beforeremove", this, panel, e);
58866 if(e.cancel === true){
58869 var panelId = panel.getId();
58870 this.panels.removeKey(panelId);
58875 * Returns the panel specified or null if it's not in this region.
58876 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
58877 * @return {Roo.ContentPanel}
58879 getPanel : function(id){
58880 if(typeof id == "object"){ // must be panel obj
58883 return this.panels.get(id);
58887 * Returns this regions position (north/south/east/west/center).
58890 getPosition: function(){
58891 return this.position;
58895 * Ext JS Library 1.1.1
58896 * Copyright(c) 2006-2007, Ext JS, LLC.
58898 * Originally Released Under LGPL - original licence link has changed is not relivant.
58901 * <script type="text/javascript">
58905 * @class Roo.LayoutRegion
58906 * @extends Roo.BasicLayoutRegion
58907 * This class represents a region in a layout manager.
58908 * @cfg {Boolean} collapsible False to disable collapsing (defaults to true)
58909 * @cfg {Boolean} collapsed True to set the initial display to collapsed (defaults to false)
58910 * @cfg {Boolean} floatable False to disable floating (defaults to true)
58911 * @cfg {Object} margins Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
58912 * @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})
58913 * @cfg {String} tabPosition (top|bottom) "top" or "bottom" (defaults to "bottom")
58914 * @cfg {String} collapsedTitle Optional string message to display in the collapsed block of a north or south region
58915 * @cfg {Boolean} alwaysShowTabs True to always display tabs even when there is only 1 panel (defaults to false)
58916 * @cfg {Boolean} autoScroll True to enable overflow scrolling (defaults to false)
58917 * @cfg {Boolean} titlebar True to display a title bar (defaults to true)
58918 * @cfg {String} title The title for the region (overrides panel titles)
58919 * @cfg {Boolean} animate True to animate expand/collapse (defaults to false)
58920 * @cfg {Boolean} autoHide False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
58921 * @cfg {Boolean} preservePanels True to preserve removed panels so they can be readded later (defaults to false)
58922 * @cfg {Boolean} closeOnTab True to place the close icon on the tabs instead of the region titlebar (defaults to false)
58923 * @cfg {Boolean} hideTabs True to hide the tab strip (defaults to false)
58924 * @cfg {Boolean} resizeTabs True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
58925 * the space available, similar to FireFox 1.5 tabs (defaults to false)
58926 * @cfg {Number} minTabWidth The minimum tab width (defaults to 40)
58927 * @cfg {Number} preferredTabWidth The preferred tab width (defaults to 150)
58928 * @cfg {Boolean} showPin True to show a pin button
58929 * @cfg {Boolean} hidden True to start the region hidden (defaults to false)
58930 * @cfg {Boolean} hideWhenEmpty True to hide the region when it has no panels
58931 * @cfg {Boolean} disableTabTips True to disable tab tooltips
58932 * @cfg {Number} width For East/West panels
58933 * @cfg {Number} height For North/South panels
58934 * @cfg {Boolean} split To show the splitter
58935 * @cfg {Boolean} toolbar xtype configuration for a toolbar - shows on right of tabbar
58937 Roo.LayoutRegion = function(mgr, config, pos){
58938 Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
58939 var dh = Roo.DomHelper;
58940 /** This region's container element
58941 * @type Roo.Element */
58942 this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
58943 /** This region's title element
58944 * @type Roo.Element */
58946 this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
58947 {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: " "},
58948 {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
58950 this.titleEl.enableDisplayMode();
58951 /** This region's title text element
58952 * @type HTMLElement */
58953 this.titleTextEl = this.titleEl.dom.firstChild;
58954 this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
58955 this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
58956 this.closeBtn.enableDisplayMode();
58957 this.closeBtn.on("click", this.closeClicked, this);
58958 this.closeBtn.hide();
58960 this.createBody(config);
58961 this.visible = true;
58962 this.collapsed = false;
58964 if(config.hideWhenEmpty){
58966 this.on("paneladded", this.validateVisibility, this);
58967 this.on("panelremoved", this.validateVisibility, this);
58969 this.applyConfig(config);
58972 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
58974 createBody : function(){
58975 /** This region's body element
58976 * @type Roo.Element */
58977 this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
58980 applyConfig : function(c){
58981 if(c.collapsible && this.position != "center" && !this.collapsedEl){
58982 var dh = Roo.DomHelper;
58983 if(c.titlebar !== false){
58984 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
58985 this.collapseBtn.on("click", this.collapse, this);
58986 this.collapseBtn.enableDisplayMode();
58988 if(c.showPin === true || this.showPin){
58989 this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
58990 this.stickBtn.enableDisplayMode();
58991 this.stickBtn.on("click", this.expand, this);
58992 this.stickBtn.hide();
58995 /** This region's collapsed element
58996 * @type Roo.Element */
58997 this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
58998 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
59000 if(c.floatable !== false){
59001 this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
59002 this.collapsedEl.on("click", this.collapseClick, this);
59005 if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
59006 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
59007 id: "message", unselectable: "on", style:{"float":"left"}});
59008 this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
59010 this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
59011 this.expandBtn.on("click", this.expand, this);
59013 if(this.collapseBtn){
59014 this.collapseBtn.setVisible(c.collapsible == true);
59016 this.cmargins = c.cmargins || this.cmargins ||
59017 (this.position == "west" || this.position == "east" ?
59018 {top: 0, left: 2, right:2, bottom: 0} :
59019 {top: 2, left: 0, right:0, bottom: 2});
59020 this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
59021 this.bottomTabs = c.tabPosition != "top";
59022 this.autoScroll = c.autoScroll || false;
59023 if(this.autoScroll){
59024 this.bodyEl.setStyle("overflow", "auto");
59026 this.bodyEl.setStyle("overflow", "hidden");
59028 //if(c.titlebar !== false){
59029 if((!c.titlebar && !c.title) || c.titlebar === false){
59030 this.titleEl.hide();
59032 this.titleEl.show();
59034 this.titleTextEl.innerHTML = c.title;
59038 this.duration = c.duration || .30;
59039 this.slideDuration = c.slideDuration || .45;
59042 this.collapse(true);
59049 * Returns true if this region is currently visible.
59050 * @return {Boolean}
59052 isVisible : function(){
59053 return this.visible;
59057 * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
59058 * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&#160;")
59060 setCollapsedTitle : function(title){
59061 title = title || " ";
59062 if(this.collapsedTitleTextEl){
59063 this.collapsedTitleTextEl.innerHTML = title;
59067 getBox : function(){
59069 if(!this.collapsed){
59070 b = this.el.getBox(false, true);
59072 b = this.collapsedEl.getBox(false, true);
59077 getMargins : function(){
59078 return this.collapsed ? this.cmargins : this.margins;
59081 highlight : function(){
59082 this.el.addClass("x-layout-panel-dragover");
59085 unhighlight : function(){
59086 this.el.removeClass("x-layout-panel-dragover");
59089 updateBox : function(box){
59091 if(!this.collapsed){
59092 this.el.dom.style.left = box.x + "px";
59093 this.el.dom.style.top = box.y + "px";
59094 this.updateBody(box.width, box.height);
59096 this.collapsedEl.dom.style.left = box.x + "px";
59097 this.collapsedEl.dom.style.top = box.y + "px";
59098 this.collapsedEl.setSize(box.width, box.height);
59101 this.tabs.autoSizeTabs();
59105 updateBody : function(w, h){
59107 this.el.setWidth(w);
59108 w -= this.el.getBorderWidth("rl");
59109 if(this.config.adjustments){
59110 w += this.config.adjustments[0];
59114 this.el.setHeight(h);
59115 h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
59116 h -= this.el.getBorderWidth("tb");
59117 if(this.config.adjustments){
59118 h += this.config.adjustments[1];
59120 this.bodyEl.setHeight(h);
59122 h = this.tabs.syncHeight(h);
59125 if(this.panelSize){
59126 w = w !== null ? w : this.panelSize.width;
59127 h = h !== null ? h : this.panelSize.height;
59129 if(this.activePanel){
59130 var el = this.activePanel.getEl();
59131 w = w !== null ? w : el.getWidth();
59132 h = h !== null ? h : el.getHeight();
59133 this.panelSize = {width: w, height: h};
59134 this.activePanel.setSize(w, h);
59136 if(Roo.isIE && this.tabs){
59137 this.tabs.el.repaint();
59142 * Returns the container element for this region.
59143 * @return {Roo.Element}
59145 getEl : function(){
59150 * Hides this region.
59153 if(!this.collapsed){
59154 this.el.dom.style.left = "-2000px";
59157 this.collapsedEl.dom.style.left = "-2000px";
59158 this.collapsedEl.hide();
59160 this.visible = false;
59161 this.fireEvent("visibilitychange", this, false);
59165 * Shows this region if it was previously hidden.
59168 if(!this.collapsed){
59171 this.collapsedEl.show();
59173 this.visible = true;
59174 this.fireEvent("visibilitychange", this, true);
59177 closeClicked : function(){
59178 if(this.activePanel){
59179 this.remove(this.activePanel);
59183 collapseClick : function(e){
59185 e.stopPropagation();
59188 e.stopPropagation();
59194 * Collapses this region.
59195 * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
59197 collapse : function(skipAnim, skipCheck){
59198 if(this.collapsed) {
59202 if(skipCheck || this.fireEvent("beforecollapse", this) != false){
59204 this.collapsed = true;
59206 this.split.el.hide();
59208 if(this.config.animate && skipAnim !== true){
59209 this.fireEvent("invalidated", this);
59210 this.animateCollapse();
59212 this.el.setLocation(-20000,-20000);
59214 this.collapsedEl.show();
59215 this.fireEvent("collapsed", this);
59216 this.fireEvent("invalidated", this);
59222 animateCollapse : function(){
59227 * Expands this region if it was previously collapsed.
59228 * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
59229 * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
59231 expand : function(e, skipAnim){
59233 e.stopPropagation();
59235 if(!this.collapsed || this.el.hasActiveFx()) {
59239 this.afterSlideIn();
59242 this.collapsed = false;
59243 if(this.config.animate && skipAnim !== true){
59244 this.animateExpand();
59248 this.split.el.show();
59250 this.collapsedEl.setLocation(-2000,-2000);
59251 this.collapsedEl.hide();
59252 this.fireEvent("invalidated", this);
59253 this.fireEvent("expanded", this);
59257 animateExpand : function(){
59261 initTabs : function()
59263 this.bodyEl.setStyle("overflow", "hidden");
59264 var ts = new Roo.TabPanel(
59267 tabPosition: this.bottomTabs ? 'bottom' : 'top',
59268 disableTooltips: this.config.disableTabTips,
59269 toolbar : this.config.toolbar
59272 if(this.config.hideTabs){
59273 ts.stripWrap.setDisplayed(false);
59276 ts.resizeTabs = this.config.resizeTabs === true;
59277 ts.minTabWidth = this.config.minTabWidth || 40;
59278 ts.maxTabWidth = this.config.maxTabWidth || 250;
59279 ts.preferredTabWidth = this.config.preferredTabWidth || 150;
59280 ts.monitorResize = false;
59281 ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
59282 ts.bodyEl.addClass('x-layout-tabs-body');
59283 this.panels.each(this.initPanelAsTab, this);
59286 initPanelAsTab : function(panel){
59287 var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
59288 this.config.closeOnTab && panel.isClosable());
59289 if(panel.tabTip !== undefined){
59290 ti.setTooltip(panel.tabTip);
59292 ti.on("activate", function(){
59293 this.setActivePanel(panel);
59295 if(this.config.closeOnTab){
59296 ti.on("beforeclose", function(t, e){
59298 this.remove(panel);
59304 updatePanelTitle : function(panel, title){
59305 if(this.activePanel == panel){
59306 this.updateTitle(title);
59309 var ti = this.tabs.getTab(panel.getEl().id);
59311 if(panel.tabTip !== undefined){
59312 ti.setTooltip(panel.tabTip);
59317 updateTitle : function(title){
59318 if(this.titleTextEl && !this.config.title){
59319 this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : " ");
59323 setActivePanel : function(panel){
59324 panel = this.getPanel(panel);
59325 if(this.activePanel && this.activePanel != panel){
59326 this.activePanel.setActiveState(false);
59328 this.activePanel = panel;
59329 panel.setActiveState(true);
59330 if(this.panelSize){
59331 panel.setSize(this.panelSize.width, this.panelSize.height);
59334 this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
59336 this.updateTitle(panel.getTitle());
59338 this.fireEvent("invalidated", this);
59340 this.fireEvent("panelactivated", this, panel);
59344 * Shows the specified panel.
59345 * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
59346 * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
59348 showPanel : function(panel)
59350 panel = this.getPanel(panel);
59353 var tab = this.tabs.getTab(panel.getEl().id);
59354 if(tab.isHidden()){
59355 this.tabs.unhideTab(tab.id);
59359 this.setActivePanel(panel);
59366 * Get the active panel for this region.
59367 * @return {Roo.ContentPanel} The active panel or null
59369 getActivePanel : function(){
59370 return this.activePanel;
59373 validateVisibility : function(){
59374 if(this.panels.getCount() < 1){
59375 this.updateTitle(" ");
59376 this.closeBtn.hide();
59379 if(!this.isVisible()){
59386 * Adds the passed ContentPanel(s) to this region.
59387 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
59388 * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
59390 add : function(panel){
59391 if(arguments.length > 1){
59392 for(var i = 0, len = arguments.length; i < len; i++) {
59393 this.add(arguments[i]);
59397 if(this.hasPanel(panel)){
59398 this.showPanel(panel);
59401 panel.setRegion(this);
59402 this.panels.add(panel);
59403 if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
59404 this.bodyEl.dom.appendChild(panel.getEl().dom);
59405 if(panel.background !== true){
59406 this.setActivePanel(panel);
59408 this.fireEvent("paneladded", this, panel);
59414 this.initPanelAsTab(panel);
59416 if(panel.background !== true){
59417 this.tabs.activate(panel.getEl().id);
59419 this.fireEvent("paneladded", this, panel);
59424 * Hides the tab for the specified panel.
59425 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
59427 hidePanel : function(panel){
59428 if(this.tabs && (panel = this.getPanel(panel))){
59429 this.tabs.hideTab(panel.getEl().id);
59434 * Unhides the tab for a previously hidden panel.
59435 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
59437 unhidePanel : function(panel){
59438 if(this.tabs && (panel = this.getPanel(panel))){
59439 this.tabs.unhideTab(panel.getEl().id);
59443 clearPanels : function(){
59444 while(this.panels.getCount() > 0){
59445 this.remove(this.panels.first());
59450 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
59451 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
59452 * @param {Boolean} preservePanel Overrides the config preservePanel option
59453 * @return {Roo.ContentPanel} The panel that was removed
59455 remove : function(panel, preservePanel){
59456 panel = this.getPanel(panel);
59461 this.fireEvent("beforeremove", this, panel, e);
59462 if(e.cancel === true){
59465 preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
59466 var panelId = panel.getId();
59467 this.panels.removeKey(panelId);
59469 document.body.appendChild(panel.getEl().dom);
59472 this.tabs.removeTab(panel.getEl().id);
59473 }else if (!preservePanel){
59474 this.bodyEl.dom.removeChild(panel.getEl().dom);
59476 if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
59477 var p = this.panels.first();
59478 var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
59479 tempEl.appendChild(p.getEl().dom);
59480 this.bodyEl.update("");
59481 this.bodyEl.dom.appendChild(p.getEl().dom);
59483 this.updateTitle(p.getTitle());
59485 this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
59486 this.setActivePanel(p);
59488 panel.setRegion(null);
59489 if(this.activePanel == panel){
59490 this.activePanel = null;
59492 if(this.config.autoDestroy !== false && preservePanel !== true){
59493 try{panel.destroy();}catch(e){}
59495 this.fireEvent("panelremoved", this, panel);
59500 * Returns the TabPanel component used by this region
59501 * @return {Roo.TabPanel}
59503 getTabs : function(){
59507 createTool : function(parentEl, className){
59508 var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
59509 children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: " "}]}, true);
59510 btn.addClassOnOver("x-layout-tools-button-over");
59515 * Ext JS Library 1.1.1
59516 * Copyright(c) 2006-2007, Ext JS, LLC.
59518 * Originally Released Under LGPL - original licence link has changed is not relivant.
59521 * <script type="text/javascript">
59527 * @class Roo.SplitLayoutRegion
59528 * @extends Roo.LayoutRegion
59529 * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
59531 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
59532 this.cursor = cursor;
59533 Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
59536 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
59537 splitTip : "Drag to resize.",
59538 collapsibleSplitTip : "Drag to resize. Double click to hide.",
59539 useSplitTips : false,
59541 applyConfig : function(config){
59542 Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
59545 var splitEl = Roo.DomHelper.append(this.mgr.el.dom,
59546 {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: " "});
59547 /** The SplitBar for this region
59548 * @type Roo.SplitBar */
59549 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
59550 this.split.on("moved", this.onSplitMove, this);
59551 this.split.useShim = config.useShim === true;
59552 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
59553 if(this.useSplitTips){
59554 this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
59556 if(config.collapsible){
59557 this.split.el.on("dblclick", this.collapse, this);
59560 if(typeof config.minSize != "undefined"){
59561 this.split.minSize = config.minSize;
59563 if(typeof config.maxSize != "undefined"){
59564 this.split.maxSize = config.maxSize;
59566 if(config.hideWhenEmpty || config.hidden || config.collapsed){
59567 this.hideSplitter();
59572 getHMaxSize : function(){
59573 var cmax = this.config.maxSize || 10000;
59574 var center = this.mgr.getRegion("center");
59575 return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
59578 getVMaxSize : function(){
59579 var cmax = this.config.maxSize || 10000;
59580 var center = this.mgr.getRegion("center");
59581 return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
59584 onSplitMove : function(split, newSize){
59585 this.fireEvent("resized", this, newSize);
59589 * Returns the {@link Roo.SplitBar} for this region.
59590 * @return {Roo.SplitBar}
59592 getSplitBar : function(){
59597 this.hideSplitter();
59598 Roo.SplitLayoutRegion.superclass.hide.call(this);
59601 hideSplitter : function(){
59603 this.split.el.setLocation(-2000,-2000);
59604 this.split.el.hide();
59610 this.split.el.show();
59612 Roo.SplitLayoutRegion.superclass.show.call(this);
59615 beforeSlide: function(){
59616 if(Roo.isGecko){// firefox overflow auto bug workaround
59617 this.bodyEl.clip();
59619 this.tabs.bodyEl.clip();
59621 if(this.activePanel){
59622 this.activePanel.getEl().clip();
59624 if(this.activePanel.beforeSlide){
59625 this.activePanel.beforeSlide();
59631 afterSlide : function(){
59632 if(Roo.isGecko){// firefox overflow auto bug workaround
59633 this.bodyEl.unclip();
59635 this.tabs.bodyEl.unclip();
59637 if(this.activePanel){
59638 this.activePanel.getEl().unclip();
59639 if(this.activePanel.afterSlide){
59640 this.activePanel.afterSlide();
59646 initAutoHide : function(){
59647 if(this.autoHide !== false){
59648 if(!this.autoHideHd){
59649 var st = new Roo.util.DelayedTask(this.slideIn, this);
59650 this.autoHideHd = {
59651 "mouseout": function(e){
59652 if(!e.within(this.el, true)){
59656 "mouseover" : function(e){
59662 this.el.on(this.autoHideHd);
59666 clearAutoHide : function(){
59667 if(this.autoHide !== false){
59668 this.el.un("mouseout", this.autoHideHd.mouseout);
59669 this.el.un("mouseover", this.autoHideHd.mouseover);
59673 clearMonitor : function(){
59674 Roo.get(document).un("click", this.slideInIf, this);
59677 // these names are backwards but not changed for compat
59678 slideOut : function(){
59679 if(this.isSlid || this.el.hasActiveFx()){
59682 this.isSlid = true;
59683 if(this.collapseBtn){
59684 this.collapseBtn.hide();
59686 this.closeBtnState = this.closeBtn.getStyle('display');
59687 this.closeBtn.hide();
59689 this.stickBtn.show();
59692 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
59693 this.beforeSlide();
59694 this.el.setStyle("z-index", 10001);
59695 this.el.slideIn(this.getSlideAnchor(), {
59696 callback: function(){
59698 this.initAutoHide();
59699 Roo.get(document).on("click", this.slideInIf, this);
59700 this.fireEvent("slideshow", this);
59707 afterSlideIn : function(){
59708 this.clearAutoHide();
59709 this.isSlid = false;
59710 this.clearMonitor();
59711 this.el.setStyle("z-index", "");
59712 if(this.collapseBtn){
59713 this.collapseBtn.show();
59715 this.closeBtn.setStyle('display', this.closeBtnState);
59717 this.stickBtn.hide();
59719 this.fireEvent("slidehide", this);
59722 slideIn : function(cb){
59723 if(!this.isSlid || this.el.hasActiveFx()){
59727 this.isSlid = false;
59728 this.beforeSlide();
59729 this.el.slideOut(this.getSlideAnchor(), {
59730 callback: function(){
59731 this.el.setLeftTop(-10000, -10000);
59733 this.afterSlideIn();
59741 slideInIf : function(e){
59742 if(!e.within(this.el)){
59747 animateCollapse : function(){
59748 this.beforeSlide();
59749 this.el.setStyle("z-index", 20000);
59750 var anchor = this.getSlideAnchor();
59751 this.el.slideOut(anchor, {
59752 callback : function(){
59753 this.el.setStyle("z-index", "");
59754 this.collapsedEl.slideIn(anchor, {duration:.3});
59756 this.el.setLocation(-10000,-10000);
59758 this.fireEvent("collapsed", this);
59765 animateExpand : function(){
59766 this.beforeSlide();
59767 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
59768 this.el.setStyle("z-index", 20000);
59769 this.collapsedEl.hide({
59772 this.el.slideIn(this.getSlideAnchor(), {
59773 callback : function(){
59774 this.el.setStyle("z-index", "");
59777 this.split.el.show();
59779 this.fireEvent("invalidated", this);
59780 this.fireEvent("expanded", this);
59808 getAnchor : function(){
59809 return this.anchors[this.position];
59812 getCollapseAnchor : function(){
59813 return this.canchors[this.position];
59816 getSlideAnchor : function(){
59817 return this.sanchors[this.position];
59820 getAlignAdj : function(){
59821 var cm = this.cmargins;
59822 switch(this.position){
59838 getExpandAdj : function(){
59839 var c = this.collapsedEl, cm = this.cmargins;
59840 switch(this.position){
59842 return [-(cm.right+c.getWidth()+cm.left), 0];
59845 return [cm.right+c.getWidth()+cm.left, 0];
59848 return [0, -(cm.top+cm.bottom+c.getHeight())];
59851 return [0, cm.top+cm.bottom+c.getHeight()];
59857 * Ext JS Library 1.1.1
59858 * Copyright(c) 2006-2007, Ext JS, LLC.
59860 * Originally Released Under LGPL - original licence link has changed is not relivant.
59863 * <script type="text/javascript">
59866 * These classes are private internal classes
59868 Roo.CenterLayoutRegion = function(mgr, config){
59869 Roo.LayoutRegion.call(this, mgr, config, "center");
59870 this.visible = true;
59871 this.minWidth = config.minWidth || 20;
59872 this.minHeight = config.minHeight || 20;
59875 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
59877 // center panel can't be hidden
59881 // center panel can't be hidden
59884 getMinWidth: function(){
59885 return this.minWidth;
59888 getMinHeight: function(){
59889 return this.minHeight;
59894 Roo.NorthLayoutRegion = function(mgr, config){
59895 Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
59897 this.split.placement = Roo.SplitBar.TOP;
59898 this.split.orientation = Roo.SplitBar.VERTICAL;
59899 this.split.el.addClass("x-layout-split-v");
59901 var size = config.initialSize || config.height;
59902 if(typeof size != "undefined"){
59903 this.el.setHeight(size);
59906 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
59907 orientation: Roo.SplitBar.VERTICAL,
59908 getBox : function(){
59909 if(this.collapsed){
59910 return this.collapsedEl.getBox();
59912 var box = this.el.getBox();
59914 box.height += this.split.el.getHeight();
59919 updateBox : function(box){
59920 if(this.split && !this.collapsed){
59921 box.height -= this.split.el.getHeight();
59922 this.split.el.setLeft(box.x);
59923 this.split.el.setTop(box.y+box.height);
59924 this.split.el.setWidth(box.width);
59926 if(this.collapsed){
59927 this.updateBody(box.width, null);
59929 Roo.LayoutRegion.prototype.updateBox.call(this, box);
59933 Roo.SouthLayoutRegion = function(mgr, config){
59934 Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
59936 this.split.placement = Roo.SplitBar.BOTTOM;
59937 this.split.orientation = Roo.SplitBar.VERTICAL;
59938 this.split.el.addClass("x-layout-split-v");
59940 var size = config.initialSize || config.height;
59941 if(typeof size != "undefined"){
59942 this.el.setHeight(size);
59945 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
59946 orientation: Roo.SplitBar.VERTICAL,
59947 getBox : function(){
59948 if(this.collapsed){
59949 return this.collapsedEl.getBox();
59951 var box = this.el.getBox();
59953 var sh = this.split.el.getHeight();
59960 updateBox : function(box){
59961 if(this.split && !this.collapsed){
59962 var sh = this.split.el.getHeight();
59965 this.split.el.setLeft(box.x);
59966 this.split.el.setTop(box.y-sh);
59967 this.split.el.setWidth(box.width);
59969 if(this.collapsed){
59970 this.updateBody(box.width, null);
59972 Roo.LayoutRegion.prototype.updateBox.call(this, box);
59976 Roo.EastLayoutRegion = function(mgr, config){
59977 Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
59979 this.split.placement = Roo.SplitBar.RIGHT;
59980 this.split.orientation = Roo.SplitBar.HORIZONTAL;
59981 this.split.el.addClass("x-layout-split-h");
59983 var size = config.initialSize || config.width;
59984 if(typeof size != "undefined"){
59985 this.el.setWidth(size);
59988 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
59989 orientation: Roo.SplitBar.HORIZONTAL,
59990 getBox : function(){
59991 if(this.collapsed){
59992 return this.collapsedEl.getBox();
59994 var box = this.el.getBox();
59996 var sw = this.split.el.getWidth();
60003 updateBox : function(box){
60004 if(this.split && !this.collapsed){
60005 var sw = this.split.el.getWidth();
60007 this.split.el.setLeft(box.x);
60008 this.split.el.setTop(box.y);
60009 this.split.el.setHeight(box.height);
60012 if(this.collapsed){
60013 this.updateBody(null, box.height);
60015 Roo.LayoutRegion.prototype.updateBox.call(this, box);
60019 Roo.WestLayoutRegion = function(mgr, config){
60020 Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
60022 this.split.placement = Roo.SplitBar.LEFT;
60023 this.split.orientation = Roo.SplitBar.HORIZONTAL;
60024 this.split.el.addClass("x-layout-split-h");
60026 var size = config.initialSize || config.width;
60027 if(typeof size != "undefined"){
60028 this.el.setWidth(size);
60031 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
60032 orientation: Roo.SplitBar.HORIZONTAL,
60033 getBox : function(){
60034 if(this.collapsed){
60035 return this.collapsedEl.getBox();
60037 var box = this.el.getBox();
60039 box.width += this.split.el.getWidth();
60044 updateBox : function(box){
60045 if(this.split && !this.collapsed){
60046 var sw = this.split.el.getWidth();
60048 this.split.el.setLeft(box.x+box.width);
60049 this.split.el.setTop(box.y);
60050 this.split.el.setHeight(box.height);
60052 if(this.collapsed){
60053 this.updateBody(null, box.height);
60055 Roo.LayoutRegion.prototype.updateBox.call(this, box);
60060 * Ext JS Library 1.1.1
60061 * Copyright(c) 2006-2007, Ext JS, LLC.
60063 * Originally Released Under LGPL - original licence link has changed is not relivant.
60066 * <script type="text/javascript">
60071 * Private internal class for reading and applying state
60073 Roo.LayoutStateManager = function(layout){
60074 // default empty state
60083 Roo.LayoutStateManager.prototype = {
60084 init : function(layout, provider){
60085 this.provider = provider;
60086 var state = provider.get(layout.id+"-layout-state");
60088 var wasUpdating = layout.isUpdating();
60090 layout.beginUpdate();
60092 for(var key in state){
60093 if(typeof state[key] != "function"){
60094 var rstate = state[key];
60095 var r = layout.getRegion(key);
60098 r.resizeTo(rstate.size);
60100 if(rstate.collapsed == true){
60103 r.expand(null, true);
60109 layout.endUpdate();
60111 this.state = state;
60113 this.layout = layout;
60114 layout.on("regionresized", this.onRegionResized, this);
60115 layout.on("regioncollapsed", this.onRegionCollapsed, this);
60116 layout.on("regionexpanded", this.onRegionExpanded, this);
60119 storeState : function(){
60120 this.provider.set(this.layout.id+"-layout-state", this.state);
60123 onRegionResized : function(region, newSize){
60124 this.state[region.getPosition()].size = newSize;
60128 onRegionCollapsed : function(region){
60129 this.state[region.getPosition()].collapsed = true;
60133 onRegionExpanded : function(region){
60134 this.state[region.getPosition()].collapsed = false;
60139 * Ext JS Library 1.1.1
60140 * Copyright(c) 2006-2007, Ext JS, LLC.
60142 * Originally Released Under LGPL - original licence link has changed is not relivant.
60145 * <script type="text/javascript">
60148 * @class Roo.ContentPanel
60149 * @extends Roo.util.Observable
60150 * @children Roo.form.Form Roo.JsonView Roo.View
60151 * @parent Roo.BorderLayout Roo.LayoutDialog builder
60152 * A basic ContentPanel element.
60153 * @cfg {Boolean} fitToFrame True for this panel to adjust its size to fit when the region resizes (defaults to false)
60154 * @cfg {Boolean} fitContainer When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container (defaults to false)
60155 * @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
60156 * @cfg {Boolean} closable True if the panel can be closed/removed
60157 * @cfg {Boolean} background True if the panel should not be activated when it is added (defaults to false)
60158 * @cfg {String|HTMLElement|Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
60159 * @cfg {Roo.Toolbar} toolbar A toolbar for this panel
60160 * @cfg {Boolean} autoScroll True to scroll overflow in this panel (use with {@link #fitToFrame})
60161 * @cfg {String} title The title for this panel
60162 * @cfg {Array} adjustments Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
60163 * @cfg {String} url Calls {@link #setUrl} with this value
60164 * @cfg {String} region (center|north|south|east|west) [required] which region to put this panel on (when used with xtype constructors)
60165 * @cfg {String|Object} params When used with {@link #url}, calls {@link #setUrl} with this value
60166 * @cfg {Boolean} loadOnce When used with {@link #url}, calls {@link #setUrl} with this value
60167 * @cfg {String} content Raw content to fill content panel with (uses setContent on construction.)
60168 * @cfg {String} style Extra style to add to the content panel
60169 * @cfg {Roo.menu.Menu} menu popup menu
60172 * Create a new ContentPanel.
60173 * @param {String/HTMLElement/Roo.Element} el The container element for this panel
60174 * @param {String/Object} config A string to set only the title or a config object
60175 * @param {String} content (optional) Set the HTML content for this panel
60176 * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
60178 Roo.ContentPanel = function(el, config, content){
60182 if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
60186 if (config && config.parentLayout) {
60187 el = config.parentLayout.el.createChild();
60190 if(el.autoCreate){ // xtype is available if this is called from factory
60194 this.el = Roo.get(el);
60195 if(!this.el && config && config.autoCreate){
60196 if(typeof config.autoCreate == "object"){
60197 if(!config.autoCreate.id){
60198 config.autoCreate.id = config.id||el;
60200 this.el = Roo.DomHelper.append(document.body,
60201 config.autoCreate, true);
60203 this.el = Roo.DomHelper.append(document.body,
60204 {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
60209 this.closable = false;
60210 this.loaded = false;
60211 this.active = false;
60212 if(typeof config == "string"){
60213 this.title = config;
60215 Roo.apply(this, config);
60218 if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
60219 this.wrapEl = this.el.wrap();
60220 this.toolbar.container = this.el.insertSibling(false, 'before');
60221 this.toolbar = new Roo.Toolbar(this.toolbar);
60224 // xtype created footer. - not sure if will work as we normally have to render first..
60225 if (this.footer && !this.footer.el && this.footer.xtype) {
60226 if (!this.wrapEl) {
60227 this.wrapEl = this.el.wrap();
60230 this.footer.container = this.wrapEl.createChild();
60232 this.footer = Roo.factory(this.footer, Roo);
60237 this.resizeEl = Roo.get(this.resizeEl, true);
60239 this.resizeEl = this.el;
60241 // handle view.xtype
60249 * Fires when this panel is activated.
60250 * @param {Roo.ContentPanel} this
60254 * @event deactivate
60255 * Fires when this panel is activated.
60256 * @param {Roo.ContentPanel} this
60258 "deactivate" : true,
60262 * Fires when this panel is resized if fitToFrame is true.
60263 * @param {Roo.ContentPanel} this
60264 * @param {Number} width The width after any component adjustments
60265 * @param {Number} height The height after any component adjustments
60271 * Fires when this tab is created
60272 * @param {Roo.ContentPanel} this
60282 if(this.autoScroll){
60283 this.resizeEl.setStyle("overflow", "auto");
60285 // fix randome scrolling
60286 this.el.on('scroll', function() {
60287 Roo.log('fix random scolling');
60288 this.scrollTo('top',0);
60291 content = content || this.content;
60293 this.setContent(content);
60295 if(config && config.url){
60296 this.setUrl(this.url, this.params, this.loadOnce);
60301 Roo.ContentPanel.superclass.constructor.call(this);
60303 if (this.view && typeof(this.view.xtype) != 'undefined') {
60304 this.view.el = this.el.appendChild(document.createElement("div"));
60305 this.view = Roo.factory(this.view);
60306 this.view.render && this.view.render(false, '');
60310 this.fireEvent('render', this);
60313 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
60315 setRegion : function(region){
60316 this.region = region;
60318 this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
60320 this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
60325 * Returns the toolbar for this Panel if one was configured.
60326 * @return {Roo.Toolbar}
60328 getToolbar : function(){
60329 return this.toolbar;
60332 setActiveState : function(active){
60333 this.active = active;
60335 this.fireEvent("deactivate", this);
60337 this.fireEvent("activate", this);
60341 * Updates this panel's element
60342 * @param {String} content The new content
60343 * @param {Boolean} loadScripts (optional) true to look for and process scripts
60345 setContent : function(content, loadScripts){
60346 this.el.update(content, loadScripts);
60349 ignoreResize : function(w, h){
60350 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
60353 this.lastSize = {width: w, height: h};
60358 * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
60359 * @return {Roo.UpdateManager} The UpdateManager
60361 getUpdateManager : function(){
60362 return this.el.getUpdateManager();
60365 * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
60366 * @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:
60369 url: "your-url.php",
60370 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
60371 callback: yourFunction,
60372 scope: yourObject, //(optional scope)
60375 text: "Loading...",
60380 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
60381 * 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.
60382 * @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}
60383 * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
60384 * @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.
60385 * @return {Roo.ContentPanel} this
60388 var um = this.el.getUpdateManager();
60389 um.update.apply(um, arguments);
60395 * 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.
60396 * @param {String/Function} url The URL to load the content from or a function to call to get the URL
60397 * @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)
60398 * @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)
60399 * @return {Roo.UpdateManager} The UpdateManager
60401 setUrl : function(url, params, loadOnce){
60402 if(this.refreshDelegate){
60403 this.removeListener("activate", this.refreshDelegate);
60405 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
60406 this.on("activate", this.refreshDelegate);
60407 return this.el.getUpdateManager();
60410 _handleRefresh : function(url, params, loadOnce){
60411 if(!loadOnce || !this.loaded){
60412 var updater = this.el.getUpdateManager();
60413 updater.update(url, params, this._setLoaded.createDelegate(this));
60417 _setLoaded : function(){
60418 this.loaded = true;
60422 * Returns this panel's id
60425 getId : function(){
60430 * Returns this panel's element - used by regiosn to add.
60431 * @return {Roo.Element}
60433 getEl : function(){
60434 return this.wrapEl || this.el;
60437 adjustForComponents : function(width, height)
60439 //Roo.log('adjustForComponents ');
60440 if(this.resizeEl != this.el){
60441 width -= this.el.getFrameWidth('lr');
60442 height -= this.el.getFrameWidth('tb');
60445 var te = this.toolbar.getEl();
60446 height -= te.getHeight();
60447 te.setWidth(width);
60450 var te = this.footer.getEl();
60451 //Roo.log("footer:" + te.getHeight());
60453 height -= te.getHeight();
60454 te.setWidth(width);
60458 if(this.adjustments){
60459 width += this.adjustments[0];
60460 height += this.adjustments[1];
60462 return {"width": width, "height": height};
60465 setSize : function(width, height){
60466 if(this.fitToFrame && !this.ignoreResize(width, height)){
60467 if(this.fitContainer && this.resizeEl != this.el){
60468 this.el.setSize(width, height);
60470 var size = this.adjustForComponents(width, height);
60471 this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
60472 this.fireEvent('resize', this, size.width, size.height);
60477 * Returns this panel's title
60480 getTitle : function(){
60485 * Set this panel's title
60486 * @param {String} title
60488 setTitle : function(title){
60489 this.title = title;
60491 this.region.updatePanelTitle(this, title);
60496 * Returns true is this panel was configured to be closable
60497 * @return {Boolean}
60499 isClosable : function(){
60500 return this.closable;
60503 beforeSlide : function(){
60505 this.resizeEl.clip();
60508 afterSlide : function(){
60510 this.resizeEl.unclip();
60514 * Force a content refresh from the URL specified in the {@link #setUrl} method.
60515 * Will fail silently if the {@link #setUrl} method has not been called.
60516 * This does not activate the panel, just updates its content.
60518 refresh : function(){
60519 if(this.refreshDelegate){
60520 this.loaded = false;
60521 this.refreshDelegate();
60526 * Destroys this panel
60528 destroy : function(){
60529 this.el.removeAllListeners();
60530 var tempEl = document.createElement("span");
60531 tempEl.appendChild(this.el.dom);
60532 tempEl.innerHTML = "";
60538 * form - if the content panel contains a form - this is a reference to it.
60539 * @type {Roo.form.Form}
60543 * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
60544 * This contains a reference to it.
60550 * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
60560 * @param {Object} cfg Xtype definition of item to add.
60563 addxtype : function(cfg) {
60565 if (cfg.xtype.match(/^Form$/)) {
60568 //if (this.footer) {
60569 // el = this.footer.container.insertSibling(false, 'before');
60571 el = this.el.createChild();
60574 this.form = new Roo.form.Form(cfg);
60577 if ( this.form.allItems.length) {
60578 this.form.render(el.dom);
60582 // should only have one of theses..
60583 if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
60584 // views.. should not be just added - used named prop 'view''
60586 cfg.el = this.el.appendChild(document.createElement("div"));
60589 var ret = new Roo.factory(cfg);
60591 ret.render && ret.render(false, ''); // render blank..
60600 * @class Roo.GridPanel
60601 * @extends Roo.ContentPanel
60602 * @parent Roo.BorderLayout Roo.LayoutDialog builder
60604 * Create a new GridPanel.
60605 * @cfg {Roo.grid.Grid} grid The grid for this panel
60607 Roo.GridPanel = function(grid, config){
60609 // universal ctor...
60610 if (typeof(grid.grid) != 'undefined') {
60612 grid = config.grid;
60614 this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
60615 {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
60617 this.wrapper.dom.appendChild(grid.getGridEl().dom);
60619 Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
60622 this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
60624 // xtype created footer. - not sure if will work as we normally have to render first..
60625 if (this.footer && !this.footer.el && this.footer.xtype) {
60627 this.footer.container = this.grid.getView().getFooterPanel(true);
60628 this.footer.dataSource = this.grid.dataSource;
60629 this.footer = Roo.factory(this.footer, Roo);
60633 grid.monitorWindowResize = false; // turn off autosizing
60634 grid.autoHeight = false;
60635 grid.autoWidth = false;
60637 this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
60640 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
60641 getId : function(){
60642 return this.grid.id;
60646 * Returns the grid for this panel
60647 * @return {Roo.grid.Grid}
60649 getGrid : function(){
60653 setSize : function(width, height){
60654 if(!this.ignoreResize(width, height)){
60655 var grid = this.grid;
60656 var size = this.adjustForComponents(width, height);
60657 grid.getGridEl().setSize(size.width, size.height);
60662 beforeSlide : function(){
60663 this.grid.getView().scroller.clip();
60666 afterSlide : function(){
60667 this.grid.getView().scroller.unclip();
60670 destroy : function(){
60671 this.grid.destroy();
60673 Roo.GridPanel.superclass.destroy.call(this);
60679 * @class Roo.NestedLayoutPanel
60680 * @extends Roo.ContentPanel
60681 * @parent Roo.BorderLayout Roo.LayoutDialog builder
60682 * @cfg Roo.BorderLayout} layout [required] The layout for this panel
60686 * Create a new NestedLayoutPanel.
60689 * @param {Roo.BorderLayout} layout [required] The layout for this panel
60690 * @param {String/Object} config A string to set only the title or a config object
60692 Roo.NestedLayoutPanel = function(layout, config)
60694 // construct with only one argument..
60695 /* FIXME - implement nicer consturctors
60696 if (layout.layout) {
60698 layout = config.layout;
60699 delete config.layout;
60701 if (layout.xtype && !layout.getEl) {
60702 // then layout needs constructing..
60703 layout = Roo.factory(layout, Roo);
60708 Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
60710 layout.monitorWindowResize = false; // turn off autosizing
60711 this.layout = layout;
60712 this.layout.getEl().addClass("x-layout-nested-layout");
60719 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
60721 setSize : function(width, height){
60722 if(!this.ignoreResize(width, height)){
60723 var size = this.adjustForComponents(width, height);
60724 var el = this.layout.getEl();
60725 el.setSize(size.width, size.height);
60726 var touch = el.dom.offsetWidth;
60727 this.layout.layout();
60728 // ie requires a double layout on the first pass
60729 if(Roo.isIE && !this.initialized){
60730 this.initialized = true;
60731 this.layout.layout();
60736 // activate all subpanels if not currently active..
60738 setActiveState : function(active){
60739 this.active = active;
60741 this.fireEvent("deactivate", this);
60745 this.fireEvent("activate", this);
60746 // not sure if this should happen before or after..
60747 if (!this.layout) {
60748 return; // should not happen..
60751 for (var r in this.layout.regions) {
60752 reg = this.layout.getRegion(r);
60753 if (reg.getActivePanel()) {
60754 //reg.showPanel(reg.getActivePanel()); // force it to activate..
60755 reg.setActivePanel(reg.getActivePanel());
60758 if (!reg.panels.length) {
60761 reg.showPanel(reg.getPanel(0));
60770 * Returns the nested BorderLayout for this panel
60771 * @return {Roo.BorderLayout}
60773 getLayout : function(){
60774 return this.layout;
60778 * Adds a xtype elements to the layout of the nested panel
60782 xtype : 'ContentPanel',
60789 xtype : 'NestedLayoutPanel',
60795 items : [ ... list of content panels or nested layout panels.. ]
60799 * @param {Object} cfg Xtype definition of item to add.
60801 addxtype : function(cfg) {
60802 return this.layout.addxtype(cfg);
60807 Roo.ScrollPanel = function(el, config, content){
60808 config = config || {};
60809 config.fitToFrame = true;
60810 Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
60812 this.el.dom.style.overflow = "hidden";
60813 var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
60814 this.el.removeClass("x-layout-inactive-content");
60815 this.el.on("mousewheel", this.onWheel, this);
60817 var up = wrap.createChild({cls: "x-scroller-up", html: " "}, this.el.dom);
60818 var down = wrap.createChild({cls: "x-scroller-down", html: " "});
60819 up.unselectable(); down.unselectable();
60820 up.on("click", this.scrollUp, this);
60821 down.on("click", this.scrollDown, this);
60822 up.addClassOnOver("x-scroller-btn-over");
60823 down.addClassOnOver("x-scroller-btn-over");
60824 up.addClassOnClick("x-scroller-btn-click");
60825 down.addClassOnClick("x-scroller-btn-click");
60826 this.adjustments = [0, -(up.getHeight() + down.getHeight())];
60828 this.resizeEl = this.el;
60829 this.el = wrap; this.up = up; this.down = down;
60832 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
60834 wheelIncrement : 5,
60835 scrollUp : function(){
60836 this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
60839 scrollDown : function(){
60840 this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
60843 afterScroll : function(){
60844 var el = this.resizeEl;
60845 var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
60846 this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
60847 this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
60850 setSize : function(){
60851 Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
60852 this.afterScroll();
60855 onWheel : function(e){
60856 var d = e.getWheelDelta();
60857 this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
60858 this.afterScroll();
60862 setContent : function(content, loadScripts){
60863 this.resizeEl.update(content, loadScripts);
60871 * @class Roo.TreePanel
60872 * @extends Roo.ContentPanel
60873 * @parent Roo.BorderLayout Roo.LayoutDialog builder
60874 * Treepanel component
60877 * Create a new TreePanel. - defaults to fit/scoll contents.
60878 * @param {String/Object} config A string to set only the panel's title, or a config object
60880 Roo.TreePanel = function(config){
60881 var el = config.el;
60882 var tree = config.tree;
60883 delete config.tree;
60884 delete config.el; // hopefull!
60886 // wrapper for IE7 strict & safari scroll issue
60888 var treeEl = el.createChild();
60889 config.resizeEl = treeEl;
60893 Roo.TreePanel.superclass.constructor.call(this, el, config);
60896 this.tree = new Roo.tree.TreePanel(treeEl , tree);
60897 //console.log(tree);
60898 this.on('activate', function()
60900 if (this.tree.rendered) {
60903 //console.log('render tree');
60904 this.tree.render();
60906 // this should not be needed.. - it's actually the 'el' that resizes?
60907 // actuall it breaks the containerScroll - dragging nodes auto scroll at top
60909 //this.on('resize', function (cp, w, h) {
60910 // this.tree.innerCt.setWidth(w);
60911 // this.tree.innerCt.setHeight(h);
60912 // //this.tree.innerCt.setStyle('overflow-y', 'auto');
60919 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {
60923 * @cfg {Roo.tree.TreePanel} tree [required] The tree TreePanel, with config etc.
60941 * Ext JS Library 1.1.1
60942 * Copyright(c) 2006-2007, Ext JS, LLC.
60944 * Originally Released Under LGPL - original licence link has changed is not relivant.
60947 * <script type="text/javascript">
60952 * @class Roo.ReaderLayout
60953 * @extends Roo.BorderLayout
60954 * This is a pre-built layout that represents a classic, 5-pane application. It consists of a header, a primary
60955 * center region containing two nested regions (a top one for a list view and one for item preview below),
60956 * and regions on either side that can be used for navigation, application commands, informational displays, etc.
60957 * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
60958 * expedites the setup of the overall layout and regions for this common application style.
60961 var reader = new Roo.ReaderLayout();
60962 var CP = Roo.ContentPanel; // shortcut for adding
60964 reader.beginUpdate();
60965 reader.add("north", new CP("north", "North"));
60966 reader.add("west", new CP("west", {title: "West"}));
60967 reader.add("east", new CP("east", {title: "East"}));
60969 reader.regions.listView.add(new CP("listView", "List"));
60970 reader.regions.preview.add(new CP("preview", "Preview"));
60971 reader.endUpdate();
60974 * Create a new ReaderLayout
60975 * @param {Object} config Configuration options
60976 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
60977 * document.body if omitted)
60979 Roo.ReaderLayout = function(config, renderTo){
60980 var c = config || {size:{}};
60981 Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
60982 north: c.north !== false ? Roo.apply({
60986 }, c.north) : false,
60987 west: c.west !== false ? Roo.apply({
60995 margins:{left:5,right:0,bottom:5,top:5},
60996 cmargins:{left:5,right:5,bottom:5,top:5}
60997 }, c.west) : false,
60998 east: c.east !== false ? Roo.apply({
61006 margins:{left:0,right:5,bottom:5,top:5},
61007 cmargins:{left:5,right:5,bottom:5,top:5}
61008 }, c.east) : false,
61009 center: Roo.apply({
61010 tabPosition: 'top',
61014 margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
61018 this.el.addClass('x-reader');
61020 this.beginUpdate();
61022 var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
61023 south: c.preview !== false ? Roo.apply({
61030 cmargins:{top:5,left:0, right:0, bottom:0}
61031 }, c.preview) : false,
61032 center: Roo.apply({
61038 this.add('center', new Roo.NestedLayoutPanel(inner,
61039 Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
61043 this.regions.preview = inner.getRegion('south');
61044 this.regions.listView = inner.getRegion('center');
61047 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
61049 * Ext JS Library 1.1.1
61050 * Copyright(c) 2006-2007, Ext JS, LLC.
61052 * Originally Released Under LGPL - original licence link has changed is not relivant.
61055 * <script type="text/javascript">
61059 * @class Roo.grid.Grid
61060 * @extends Roo.util.Observable
61061 * This class represents the primary interface of a component based grid control.
61062 * <br><br>Usage:<pre><code>
61063 var grid = new Roo.grid.Grid("my-container-id", {
61066 selModel: mySelectionModel,
61067 autoSizeColumns: true,
61068 monitorWindowResize: false,
61069 trackMouseOver: true
61074 * <b>Common Problems:</b><br/>
61075 * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
61076 * element will correct this<br/>
61077 * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
61078 * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
61079 * are unpredictable.<br/>
61080 * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
61081 * grid to calculate dimensions/offsets.<br/>
61083 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
61084 * The container MUST have some type of size defined for the grid to fill. The container will be
61085 * automatically set to position relative if it isn't already.
61086 * @param {Object} config A config object that sets properties on this grid.
61088 Roo.grid.Grid = function(container, config){
61089 // initialize the container
61090 this.container = Roo.get(container);
61091 this.container.update("");
61092 this.container.setStyle("overflow", "hidden");
61093 this.container.addClass('x-grid-container');
61095 this.id = this.container.id;
61097 Roo.apply(this, config);
61098 // check and correct shorthanded configs
61100 this.dataSource = this.ds;
61104 this.colModel = this.cm;
61108 this.selModel = this.sm;
61112 if (this.selModel) {
61113 this.selModel = Roo.factory(this.selModel, Roo.grid);
61114 this.sm = this.selModel;
61115 this.sm.xmodule = this.xmodule || false;
61117 if (typeof(this.colModel.config) == 'undefined') {
61118 this.colModel = new Roo.grid.ColumnModel(this.colModel);
61119 this.cm = this.colModel;
61120 this.cm.xmodule = this.xmodule || false;
61122 if (this.dataSource) {
61123 this.dataSource= Roo.factory(this.dataSource, Roo.data);
61124 this.ds = this.dataSource;
61125 this.ds.xmodule = this.xmodule || false;
61132 this.container.setWidth(this.width);
61136 this.container.setHeight(this.height);
61143 * The raw click event for the entire grid.
61144 * @param {Roo.EventObject} e
61149 * The raw dblclick event for the entire grid.
61150 * @param {Roo.EventObject} e
61154 * @event contextmenu
61155 * The raw contextmenu event for the entire grid.
61156 * @param {Roo.EventObject} e
61158 "contextmenu" : true,
61161 * The raw mousedown event for the entire grid.
61162 * @param {Roo.EventObject} e
61164 "mousedown" : true,
61167 * The raw mouseup event for the entire grid.
61168 * @param {Roo.EventObject} e
61173 * The raw mouseover event for the entire grid.
61174 * @param {Roo.EventObject} e
61176 "mouseover" : true,
61179 * The raw mouseout event for the entire grid.
61180 * @param {Roo.EventObject} e
61185 * The raw keypress event for the entire grid.
61186 * @param {Roo.EventObject} e
61191 * The raw keydown event for the entire grid.
61192 * @param {Roo.EventObject} e
61200 * Fires when a cell is clicked
61201 * @param {Grid} this
61202 * @param {Number} rowIndex
61203 * @param {Number} columnIndex
61204 * @param {Roo.EventObject} e
61206 "cellclick" : true,
61208 * @event celldblclick
61209 * Fires when a cell is double clicked
61210 * @param {Grid} this
61211 * @param {Number} rowIndex
61212 * @param {Number} columnIndex
61213 * @param {Roo.EventObject} e
61215 "celldblclick" : true,
61218 * Fires when a row is clicked
61219 * @param {Grid} this
61220 * @param {Number} rowIndex
61221 * @param {Roo.EventObject} e
61225 * @event rowdblclick
61226 * Fires when a row is double clicked
61227 * @param {Grid} this
61228 * @param {Number} rowIndex
61229 * @param {Roo.EventObject} e
61231 "rowdblclick" : true,
61233 * @event headerclick
61234 * Fires when a header is clicked
61235 * @param {Grid} this
61236 * @param {Number} columnIndex
61237 * @param {Roo.EventObject} e
61239 "headerclick" : true,
61241 * @event headerdblclick
61242 * Fires when a header cell is double clicked
61243 * @param {Grid} this
61244 * @param {Number} columnIndex
61245 * @param {Roo.EventObject} e
61247 "headerdblclick" : true,
61249 * @event rowcontextmenu
61250 * Fires when a row is right clicked
61251 * @param {Grid} this
61252 * @param {Number} rowIndex
61253 * @param {Roo.EventObject} e
61255 "rowcontextmenu" : true,
61257 * @event cellcontextmenu
61258 * Fires when a cell is right clicked
61259 * @param {Grid} this
61260 * @param {Number} rowIndex
61261 * @param {Number} cellIndex
61262 * @param {Roo.EventObject} e
61264 "cellcontextmenu" : true,
61266 * @event headercontextmenu
61267 * Fires when a header is right clicked
61268 * @param {Grid} this
61269 * @param {Number} columnIndex
61270 * @param {Roo.EventObject} e
61272 "headercontextmenu" : true,
61274 * @event bodyscroll
61275 * Fires when the body element is scrolled
61276 * @param {Number} scrollLeft
61277 * @param {Number} scrollTop
61279 "bodyscroll" : true,
61281 * @event columnresize
61282 * Fires when the user resizes a column
61283 * @param {Number} columnIndex
61284 * @param {Number} newSize
61286 "columnresize" : true,
61288 * @event columnmove
61289 * Fires when the user moves a column
61290 * @param {Number} oldIndex
61291 * @param {Number} newIndex
61293 "columnmove" : true,
61296 * Fires when row(s) start being dragged
61297 * @param {Grid} this
61298 * @param {Roo.GridDD} dd The drag drop object
61299 * @param {event} e The raw browser event
61301 "startdrag" : true,
61304 * Fires when a drag operation is complete
61305 * @param {Grid} this
61306 * @param {Roo.GridDD} dd The drag drop object
61307 * @param {event} e The raw browser event
61312 * Fires when dragged row(s) are dropped on a valid DD target
61313 * @param {Grid} this
61314 * @param {Roo.GridDD} dd The drag drop object
61315 * @param {String} targetId The target drag drop object
61316 * @param {event} e The raw browser event
61321 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
61322 * @param {Grid} this
61323 * @param {Roo.GridDD} dd The drag drop object
61324 * @param {String} targetId The target drag drop object
61325 * @param {event} e The raw browser event
61330 * Fires when the dragged row(s) first cross another DD target while being dragged
61331 * @param {Grid} this
61332 * @param {Roo.GridDD} dd The drag drop object
61333 * @param {String} targetId The target drag drop object
61334 * @param {event} e The raw browser event
61336 "dragenter" : true,
61339 * Fires when the dragged row(s) leave another DD target while being dragged
61340 * @param {Grid} this
61341 * @param {Roo.GridDD} dd The drag drop object
61342 * @param {String} targetId The target drag drop object
61343 * @param {event} e The raw browser event
61348 * Fires when a row is rendered, so you can change add a style to it.
61349 * @param {GridView} gridview The grid view
61350 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
61356 * Fires when the grid is rendered
61357 * @param {Grid} grid
61362 Roo.grid.Grid.superclass.constructor.call(this);
61364 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
61367 * @cfg {Roo.grid.AbstractSelectionModel} sm The selection Model (default = Roo.grid.RowSelectionModel)
61370 * @cfg {Roo.grid.GridView} view The view that renders the grid (default = Roo.grid.GridView)
61373 * @cfg {Roo.grid.ColumnModel} cm[] The columns of the grid
61376 * @cfg {Roo.grid.Store} ds The data store for the grid
61379 * @cfg {Roo.Toolbar} toolbar a toolbar for buttons etc.
61382 * @cfg {String} ddGroup - drag drop group.
61385 * @cfg {String} dragGroup - drag group (?? not sure if needed.)
61389 * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
61391 minColumnWidth : 25,
61394 * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
61395 * <b>on initial render.</b> It is more efficient to explicitly size the columns
61396 * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option. Default is false.
61398 autoSizeColumns : false,
61401 * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
61403 autoSizeHeaders : true,
61406 * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
61408 monitorWindowResize : true,
61411 * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
61412 * rows measured to get a columns size. Default is 0 (all rows).
61414 maxRowsToMeasure : 0,
61417 * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
61419 trackMouseOver : true,
61422 * @cfg {Boolean} enableDrag True to enable drag of rows. Default is false. (double check if this is needed?)
61425 * @cfg {Boolean} enableDrop True to enable drop of elements. Default is false. (double check if this is needed?)
61429 * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
61431 enableDragDrop : false,
61434 * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
61436 enableColumnMove : true,
61439 * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
61441 enableColumnHide : true,
61444 * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
61446 enableRowHeightSync : false,
61449 * @cfg {Boolean} stripeRows True to stripe the rows. Default is true.
61454 * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
61456 autoHeight : false,
61459 * @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.
61461 autoExpandColumn : false,
61464 * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
61467 autoExpandMin : 50,
61470 * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
61472 autoExpandMax : 1000,
61475 * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
61480 * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
61484 * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
61488 * @cfg {boolean} sortColMenu Sort the column order menu when it shows (usefull for long lists..) default false
61490 sortColMenu : false,
61496 * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
61497 * of a fixed width. Default is false.
61500 * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
61505 * @cfg {String} ddText Configures the text is the drag proxy (defaults to "%0 selected row(s)").
61506 * %0 is replaced with the number of selected rows.
61508 ddText : "{0} selected row{1}",
61512 * Called once after all setup has been completed and the grid is ready to be rendered.
61513 * @return {Roo.grid.Grid} this
61515 render : function()
61517 var c = this.container;
61518 // try to detect autoHeight/width mode
61519 if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
61520 this.autoHeight = true;
61522 var view = this.getView();
61525 c.on("click", this.onClick, this);
61526 c.on("dblclick", this.onDblClick, this);
61527 c.on("contextmenu", this.onContextMenu, this);
61528 c.on("keydown", this.onKeyDown, this);
61530 c.on("touchstart", this.onTouchStart, this);
61533 this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
61535 this.getSelectionModel().init(this);
61540 this.loadMask = new Roo.LoadMask(this.container,
61541 Roo.apply({store:this.dataSource}, this.loadMask));
61545 if (this.toolbar && this.toolbar.xtype) {
61546 this.toolbar.container = this.getView().getHeaderPanel(true);
61547 this.toolbar = new Roo.Toolbar(this.toolbar);
61549 if (this.footer && this.footer.xtype) {
61550 this.footer.dataSource = this.getDataSource();
61551 this.footer.container = this.getView().getFooterPanel(true);
61552 this.footer = Roo.factory(this.footer, Roo);
61554 if (this.dropTarget && this.dropTarget.xtype) {
61555 delete this.dropTarget.xtype;
61556 this.dropTarget = new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
61560 this.rendered = true;
61561 this.fireEvent('render', this);
61566 * Reconfigures the grid to use a different Store and Column Model.
61567 * The View will be bound to the new objects and refreshed.
61568 * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
61569 * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
61571 reconfigure : function(dataSource, colModel){
61573 this.loadMask.destroy();
61574 this.loadMask = new Roo.LoadMask(this.container,
61575 Roo.apply({store:dataSource}, this.loadMask));
61577 this.view.bind(dataSource, colModel);
61578 this.dataSource = dataSource;
61579 this.colModel = colModel;
61580 this.view.refresh(true);
61584 * Add's a column, default at the end..
61586 * @param {int} position to add (default end)
61587 * @param {Array} of objects of column configuration see {@link Roo.grid.ColumnModel}
61589 addColumns : function(pos, ar)
61592 for (var i =0;i< ar.length;i++) {
61594 cfg.id = typeof(cfg.id) == 'undefined' ? Roo.id() : cfg.id; // don't normally use this..
61595 this.cm.lookup[cfg.id] = cfg;
61599 if (typeof(pos) == 'undefined' || pos >= this.cm.config.length) {
61600 pos = this.cm.config.length; //this.cm.config.push(cfg);
61602 pos = Math.max(0,pos);
61605 this.cm.config.splice.apply(this.cm.config, ar);
61609 this.view.generateRules(this.cm);
61610 this.view.refresh(true);
61618 onKeyDown : function(e){
61619 this.fireEvent("keydown", e);
61623 * Destroy this grid.
61624 * @param {Boolean} removeEl True to remove the element
61626 destroy : function(removeEl, keepListeners){
61628 this.loadMask.destroy();
61630 var c = this.container;
61631 c.removeAllListeners();
61632 this.view.destroy();
61633 this.colModel.purgeListeners();
61634 if(!keepListeners){
61635 this.purgeListeners();
61638 if(removeEl === true){
61644 processEvent : function(name, e){
61645 // does this fire select???
61646 //Roo.log('grid:processEvent ' + name);
61648 if (name != 'touchstart' ) {
61649 this.fireEvent(name, e);
61652 var t = e.getTarget();
61654 var header = v.findHeaderIndex(t);
61655 if(header !== false){
61656 var ename = name == 'touchstart' ? 'click' : name;
61658 this.fireEvent("header" + ename, this, header, e);
61660 var row = v.findRowIndex(t);
61661 var cell = v.findCellIndex(t);
61662 if (name == 'touchstart') {
61663 // first touch is always a click.
61664 // hopefull this happens after selection is updated.?
61667 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
61668 var cs = this.selModel.getSelectedCell();
61669 if (row == cs[0] && cell == cs[1]){
61673 if (typeof(this.selModel.getSelections) != 'undefined') {
61674 var cs = this.selModel.getSelections();
61675 var ds = this.dataSource;
61676 if (cs.length == 1 && ds.getAt(row) == cs[0]){
61687 this.fireEvent("row" + name, this, row, e);
61688 if(cell !== false){
61689 this.fireEvent("cell" + name, this, row, cell, e);
61696 onClick : function(e){
61697 this.processEvent("click", e);
61700 onTouchStart : function(e){
61701 this.processEvent("touchstart", e);
61705 onContextMenu : function(e, t){
61706 this.processEvent("contextmenu", e);
61710 onDblClick : function(e){
61711 this.processEvent("dblclick", e);
61715 walkCells : function(row, col, step, fn, scope){
61716 var cm = this.colModel, clen = cm.getColumnCount();
61717 var ds = this.dataSource, rlen = ds.getCount(), first = true;
61729 if(fn.call(scope || this, row, col, cm) === true){
61747 if(fn.call(scope || this, row, col, cm) === true){
61759 getSelections : function(){
61760 return this.selModel.getSelections();
61764 * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
61765 * but if manual update is required this method will initiate it.
61767 autoSize : function(){
61769 this.view.layout();
61770 if(this.view.adjustForScroll){
61771 this.view.adjustForScroll();
61777 * Returns the grid's underlying element.
61778 * @return {Element} The element
61780 getGridEl : function(){
61781 return this.container;
61784 // private for compatibility, overridden by editor grid
61785 stopEditing : function(){},
61788 * Returns the grid's SelectionModel.
61789 * @return {SelectionModel}
61791 getSelectionModel : function(){
61792 if(!this.selModel){
61793 this.selModel = new Roo.grid.RowSelectionModel();
61795 return this.selModel;
61799 * Returns the grid's DataSource.
61800 * @return {DataSource}
61802 getDataSource : function(){
61803 return this.dataSource;
61807 * Returns the grid's ColumnModel.
61808 * @return {ColumnModel}
61810 getColumnModel : function(){
61811 return this.colModel;
61815 * Returns the grid's GridView object.
61816 * @return {GridView}
61818 getView : function(){
61820 this.view = new Roo.grid.GridView(this.viewConfig);
61821 this.relayEvents(this.view, [
61822 "beforerowremoved", "beforerowsinserted",
61823 "beforerefresh", "rowremoved",
61824 "rowsinserted", "rowupdated" ,"refresh"
61830 * Called to get grid's drag proxy text, by default returns this.ddText.
61831 * Override this to put something different in the dragged text.
61834 getDragDropText : function(){
61835 var count = this.selModel.getCount();
61836 return String.format(this.ddText, count, count == 1 ? '' : 's');
61841 * Ext JS Library 1.1.1
61842 * Copyright(c) 2006-2007, Ext JS, LLC.
61844 * Originally Released Under LGPL - original licence link has changed is not relivant.
61847 * <script type="text/javascript">
61850 * @class Roo.grid.AbstractGridView
61851 * @extends Roo.util.Observable
61853 * Abstract base class for grid Views
61856 Roo.grid.AbstractGridView = function(){
61860 "beforerowremoved" : true,
61861 "beforerowsinserted" : true,
61862 "beforerefresh" : true,
61863 "rowremoved" : true,
61864 "rowsinserted" : true,
61865 "rowupdated" : true,
61868 Roo.grid.AbstractGridView.superclass.constructor.call(this);
61871 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
61872 rowClass : "x-grid-row",
61873 cellClass : "x-grid-cell",
61874 tdClass : "x-grid-td",
61875 hdClass : "x-grid-hd",
61876 splitClass : "x-grid-hd-split",
61878 init: function(grid){
61880 var cid = this.grid.getGridEl().id;
61881 this.colSelector = "#" + cid + " ." + this.cellClass + "-";
61882 this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
61883 this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
61884 this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
61887 getColumnRenderers : function(){
61888 var renderers = [];
61889 var cm = this.grid.colModel;
61890 var colCount = cm.getColumnCount();
61891 for(var i = 0; i < colCount; i++){
61892 renderers[i] = cm.getRenderer(i);
61897 getColumnIds : function(){
61899 var cm = this.grid.colModel;
61900 var colCount = cm.getColumnCount();
61901 for(var i = 0; i < colCount; i++){
61902 ids[i] = cm.getColumnId(i);
61907 getDataIndexes : function(){
61908 if(!this.indexMap){
61909 this.indexMap = this.buildIndexMap();
61911 return this.indexMap.colToData;
61914 getColumnIndexByDataIndex : function(dataIndex){
61915 if(!this.indexMap){
61916 this.indexMap = this.buildIndexMap();
61918 return this.indexMap.dataToCol[dataIndex];
61922 * Set a css style for a column dynamically.
61923 * @param {Number} colIndex The index of the column
61924 * @param {String} name The css property name
61925 * @param {String} value The css value
61927 setCSSStyle : function(colIndex, name, value){
61928 var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
61929 Roo.util.CSS.updateRule(selector, name, value);
61932 generateRules : function(cm){
61933 var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
61934 Roo.util.CSS.removeStyleSheet(rulesId);
61935 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
61936 var cid = cm.getColumnId(i);
61937 ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
61938 this.tdSelector, cid, " {\n}\n",
61939 this.hdSelector, cid, " {\n}\n",
61940 this.splitSelector, cid, " {\n}\n");
61942 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
61946 * Ext JS Library 1.1.1
61947 * Copyright(c) 2006-2007, Ext JS, LLC.
61949 * Originally Released Under LGPL - original licence link has changed is not relivant.
61952 * <script type="text/javascript">
61956 // This is a support class used internally by the Grid components
61957 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
61959 this.view = grid.getView();
61960 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
61961 Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
61963 this.setHandleElId(Roo.id(hd));
61964 this.setOuterHandleElId(Roo.id(hd2));
61966 this.scroll = false;
61968 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
61970 getDragData : function(e){
61971 var t = Roo.lib.Event.getTarget(e);
61972 var h = this.view.findHeaderCell(t);
61974 return {ddel: h.firstChild, header:h};
61979 onInitDrag : function(e){
61980 this.view.headersDisabled = true;
61981 var clone = this.dragData.ddel.cloneNode(true);
61982 clone.id = Roo.id();
61983 clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
61984 this.proxy.update(clone);
61988 afterValidDrop : function(){
61990 setTimeout(function(){
61991 v.headersDisabled = false;
61995 afterInvalidDrop : function(){
61997 setTimeout(function(){
61998 v.headersDisabled = false;
62004 * Ext JS Library 1.1.1
62005 * Copyright(c) 2006-2007, Ext JS, LLC.
62007 * Originally Released Under LGPL - original licence link has changed is not relivant.
62010 * <script type="text/javascript">
62013 // This is a support class used internally by the Grid components
62014 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
62016 this.view = grid.getView();
62017 // split the proxies so they don't interfere with mouse events
62018 this.proxyTop = Roo.DomHelper.append(document.body, {
62019 cls:"col-move-top", html:" "
62021 this.proxyBottom = Roo.DomHelper.append(document.body, {
62022 cls:"col-move-bottom", html:" "
62024 this.proxyTop.hide = this.proxyBottom.hide = function(){
62025 this.setLeftTop(-100,-100);
62026 this.setStyle("visibility", "hidden");
62028 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
62029 // temporarily disabled
62030 //Roo.dd.ScrollManager.register(this.view.scroller.dom);
62031 Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
62033 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
62034 proxyOffsets : [-4, -9],
62035 fly: Roo.Element.fly,
62037 getTargetFromEvent : function(e){
62038 var t = Roo.lib.Event.getTarget(e);
62039 var cindex = this.view.findCellIndex(t);
62040 if(cindex !== false){
62041 return this.view.getHeaderCell(cindex);
62046 nextVisible : function(h){
62047 var v = this.view, cm = this.grid.colModel;
62050 if(!cm.isHidden(v.getCellIndex(h))){
62058 prevVisible : function(h){
62059 var v = this.view, cm = this.grid.colModel;
62062 if(!cm.isHidden(v.getCellIndex(h))){
62070 positionIndicator : function(h, n, e){
62071 var x = Roo.lib.Event.getPageX(e);
62072 var r = Roo.lib.Dom.getRegion(n.firstChild);
62073 var px, pt, py = r.top + this.proxyOffsets[1];
62074 if((r.right - x) <= (r.right-r.left)/2){
62075 px = r.right+this.view.borderWidth;
62081 var oldIndex = this.view.getCellIndex(h);
62082 var newIndex = this.view.getCellIndex(n);
62084 if(this.grid.colModel.isFixed(newIndex)){
62088 var locked = this.grid.colModel.isLocked(newIndex);
62093 if(oldIndex < newIndex){
62096 if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
62099 px += this.proxyOffsets[0];
62100 this.proxyTop.setLeftTop(px, py);
62101 this.proxyTop.show();
62102 if(!this.bottomOffset){
62103 this.bottomOffset = this.view.mainHd.getHeight();
62105 this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
62106 this.proxyBottom.show();
62110 onNodeEnter : function(n, dd, e, data){
62111 if(data.header != n){
62112 this.positionIndicator(data.header, n, e);
62116 onNodeOver : function(n, dd, e, data){
62117 var result = false;
62118 if(data.header != n){
62119 result = this.positionIndicator(data.header, n, e);
62122 this.proxyTop.hide();
62123 this.proxyBottom.hide();
62125 return result ? this.dropAllowed : this.dropNotAllowed;
62128 onNodeOut : function(n, dd, e, data){
62129 this.proxyTop.hide();
62130 this.proxyBottom.hide();
62133 onNodeDrop : function(n, dd, e, data){
62134 var h = data.header;
62136 var cm = this.grid.colModel;
62137 var x = Roo.lib.Event.getPageX(e);
62138 var r = Roo.lib.Dom.getRegion(n.firstChild);
62139 var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
62140 var oldIndex = this.view.getCellIndex(h);
62141 var newIndex = this.view.getCellIndex(n);
62142 var locked = cm.isLocked(newIndex);
62146 if(oldIndex < newIndex){
62149 if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
62152 cm.setLocked(oldIndex, locked, true);
62153 cm.moveColumn(oldIndex, newIndex);
62154 this.grid.fireEvent("columnmove", oldIndex, newIndex);
62162 * Ext JS Library 1.1.1
62163 * Copyright(c) 2006-2007, Ext JS, LLC.
62165 * Originally Released Under LGPL - original licence link has changed is not relivant.
62168 * <script type="text/javascript">
62172 * @class Roo.grid.GridView
62173 * @extends Roo.util.Observable
62176 * @param {Object} config
62178 Roo.grid.GridView = function(config){
62179 Roo.grid.GridView.superclass.constructor.call(this);
62182 Roo.apply(this, config);
62185 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
62187 unselectable : 'unselectable="on"',
62188 unselectableCls : 'x-unselectable',
62191 rowClass : "x-grid-row",
62193 cellClass : "x-grid-col",
62195 tdClass : "x-grid-td",
62197 hdClass : "x-grid-hd",
62199 splitClass : "x-grid-split",
62201 sortClasses : ["sort-asc", "sort-desc"],
62203 enableMoveAnim : false,
62207 dh : Roo.DomHelper,
62209 fly : Roo.Element.fly,
62211 css : Roo.util.CSS,
62217 scrollIncrement : 22,
62219 cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
62221 findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
62223 bind : function(ds, cm){
62225 this.ds.un("load", this.onLoad, this);
62226 this.ds.un("datachanged", this.onDataChange, this);
62227 this.ds.un("add", this.onAdd, this);
62228 this.ds.un("remove", this.onRemove, this);
62229 this.ds.un("update", this.onUpdate, this);
62230 this.ds.un("clear", this.onClear, this);
62233 ds.on("load", this.onLoad, this);
62234 ds.on("datachanged", this.onDataChange, this);
62235 ds.on("add", this.onAdd, this);
62236 ds.on("remove", this.onRemove, this);
62237 ds.on("update", this.onUpdate, this);
62238 ds.on("clear", this.onClear, this);
62243 this.cm.un("widthchange", this.onColWidthChange, this);
62244 this.cm.un("headerchange", this.onHeaderChange, this);
62245 this.cm.un("hiddenchange", this.onHiddenChange, this);
62246 this.cm.un("columnmoved", this.onColumnMove, this);
62247 this.cm.un("columnlockchange", this.onColumnLock, this);
62250 this.generateRules(cm);
62251 cm.on("widthchange", this.onColWidthChange, this);
62252 cm.on("headerchange", this.onHeaderChange, this);
62253 cm.on("hiddenchange", this.onHiddenChange, this);
62254 cm.on("columnmoved", this.onColumnMove, this);
62255 cm.on("columnlockchange", this.onColumnLock, this);
62260 init: function(grid){
62261 Roo.grid.GridView.superclass.init.call(this, grid);
62263 this.bind(grid.dataSource, grid.colModel);
62265 grid.on("headerclick", this.handleHeaderClick, this);
62267 if(grid.trackMouseOver){
62268 grid.on("mouseover", this.onRowOver, this);
62269 grid.on("mouseout", this.onRowOut, this);
62271 grid.cancelTextSelection = function(){};
62272 this.gridId = grid.id;
62274 var tpls = this.templates || {};
62277 tpls.master = new Roo.Template(
62278 '<div class="x-grid" hidefocus="true">',
62279 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
62280 '<div class="x-grid-topbar"></div>',
62281 '<div class="x-grid-scroller"><div></div></div>',
62282 '<div class="x-grid-locked">',
62283 '<div class="x-grid-header">{lockedHeader}</div>',
62284 '<div class="x-grid-body">{lockedBody}</div>',
62286 '<div class="x-grid-viewport">',
62287 '<div class="x-grid-header">{header}</div>',
62288 '<div class="x-grid-body">{body}</div>',
62290 '<div class="x-grid-bottombar"></div>',
62292 '<div class="x-grid-resize-proxy"> </div>',
62295 tpls.master.disableformats = true;
62299 tpls.header = new Roo.Template(
62300 '<table border="0" cellspacing="0" cellpadding="0">',
62301 '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
62304 tpls.header.disableformats = true;
62306 tpls.header.compile();
62309 tpls.hcell = new Roo.Template(
62310 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
62311 '<div class="x-grid-hd-text ' + this.unselectableCls + '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
62314 tpls.hcell.disableFormats = true;
62316 tpls.hcell.compile();
62319 tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
62320 this.unselectableCls + '" ' + this.unselectable +'> </div>');
62321 tpls.hsplit.disableFormats = true;
62323 tpls.hsplit.compile();
62326 tpls.body = new Roo.Template(
62327 '<table border="0" cellspacing="0" cellpadding="0">',
62328 "<tbody>{rows}</tbody>",
62331 tpls.body.disableFormats = true;
62333 tpls.body.compile();
62336 tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
62337 tpls.row.disableFormats = true;
62339 tpls.row.compile();
62342 tpls.cell = new Roo.Template(
62343 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
62344 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
62345 this.unselectableCls + '" ' + this.unselectable +'" {attr}>{value}</div></div>',
62348 tpls.cell.disableFormats = true;
62350 tpls.cell.compile();
62352 this.templates = tpls;
62355 // remap these for backwards compat
62356 onColWidthChange : function(){
62357 this.updateColumns.apply(this, arguments);
62359 onHeaderChange : function(){
62360 this.updateHeaders.apply(this, arguments);
62362 onHiddenChange : function(){
62363 this.handleHiddenChange.apply(this, arguments);
62365 onColumnMove : function(){
62366 this.handleColumnMove.apply(this, arguments);
62368 onColumnLock : function(){
62369 this.handleLockChange.apply(this, arguments);
62372 onDataChange : function(){
62374 this.updateHeaderSortState();
62377 onClear : function(){
62381 onUpdate : function(ds, record){
62382 this.refreshRow(record);
62385 refreshRow : function(record){
62386 var ds = this.ds, index;
62387 if(typeof record == 'number'){
62389 record = ds.getAt(index);
62391 index = ds.indexOf(record);
62393 this.insertRows(ds, index, index, true);
62394 this.onRemove(ds, record, index+1, true);
62395 this.syncRowHeights(index, index);
62397 this.fireEvent("rowupdated", this, index, record);
62400 onAdd : function(ds, records, index){
62401 this.insertRows(ds, index, index + (records.length-1));
62404 onRemove : function(ds, record, index, isUpdate){
62405 if(isUpdate !== true){
62406 this.fireEvent("beforerowremoved", this, index, record);
62408 var bt = this.getBodyTable(), lt = this.getLockedTable();
62409 if(bt.rows[index]){
62410 bt.firstChild.removeChild(bt.rows[index]);
62412 if(lt.rows[index]){
62413 lt.firstChild.removeChild(lt.rows[index]);
62415 if(isUpdate !== true){
62416 this.stripeRows(index);
62417 this.syncRowHeights(index, index);
62419 this.fireEvent("rowremoved", this, index, record);
62423 onLoad : function(){
62424 this.scrollToTop();
62428 * Scrolls the grid to the top
62430 scrollToTop : function(){
62432 this.scroller.dom.scrollTop = 0;
62438 * Gets a panel in the header of the grid that can be used for toolbars etc.
62439 * After modifying the contents of this panel a call to grid.autoSize() may be
62440 * required to register any changes in size.
62441 * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
62442 * @return Roo.Element
62444 getHeaderPanel : function(doShow){
62446 this.headerPanel.show();
62448 return this.headerPanel;
62452 * Gets a panel in the footer of the grid that can be used for toolbars etc.
62453 * After modifying the contents of this panel a call to grid.autoSize() may be
62454 * required to register any changes in size.
62455 * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
62456 * @return Roo.Element
62458 getFooterPanel : function(doShow){
62460 this.footerPanel.show();
62462 return this.footerPanel;
62465 initElements : function(){
62466 var E = Roo.Element;
62467 var el = this.grid.getGridEl().dom.firstChild;
62468 var cs = el.childNodes;
62470 this.el = new E(el);
62472 this.focusEl = new E(el.firstChild);
62473 this.focusEl.swallowEvent("click", true);
62475 this.headerPanel = new E(cs[1]);
62476 this.headerPanel.enableDisplayMode("block");
62478 this.scroller = new E(cs[2]);
62479 this.scrollSizer = new E(this.scroller.dom.firstChild);
62481 this.lockedWrap = new E(cs[3]);
62482 this.lockedHd = new E(this.lockedWrap.dom.firstChild);
62483 this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
62485 this.mainWrap = new E(cs[4]);
62486 this.mainHd = new E(this.mainWrap.dom.firstChild);
62487 this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
62489 this.footerPanel = new E(cs[5]);
62490 this.footerPanel.enableDisplayMode("block");
62492 this.resizeProxy = new E(cs[6]);
62494 this.headerSelector = String.format(
62495 '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
62496 this.lockedHd.id, this.mainHd.id
62499 this.splitterSelector = String.format(
62500 '#{0} div.x-grid-split, #{1} div.x-grid-split',
62501 this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
62504 idToCssName : function(s)
62506 return s.replace(/[^a-z0-9]+/ig, '-');
62509 getHeaderCell : function(index){
62510 return Roo.DomQuery.select(this.headerSelector)[index];
62513 getHeaderCellMeasure : function(index){
62514 return this.getHeaderCell(index).firstChild;
62517 getHeaderCellText : function(index){
62518 return this.getHeaderCell(index).firstChild.firstChild;
62521 getLockedTable : function(){
62522 return this.lockedBody.dom.firstChild;
62525 getBodyTable : function(){
62526 return this.mainBody.dom.firstChild;
62529 getLockedRow : function(index){
62530 return this.getLockedTable().rows[index];
62533 getRow : function(index){
62534 return this.getBodyTable().rows[index];
62537 getRowComposite : function(index){
62539 this.rowEl = new Roo.CompositeElementLite();
62541 var els = [], lrow, mrow;
62542 if(lrow = this.getLockedRow(index)){
62545 if(mrow = this.getRow(index)){
62548 this.rowEl.elements = els;
62552 * Gets the 'td' of the cell
62554 * @param {Integer} rowIndex row to select
62555 * @param {Integer} colIndex column to select
62559 getCell : function(rowIndex, colIndex){
62560 var locked = this.cm.getLockedCount();
62562 if(colIndex < locked){
62563 source = this.lockedBody.dom.firstChild;
62565 source = this.mainBody.dom.firstChild;
62566 colIndex -= locked;
62568 return source.rows[rowIndex].childNodes[colIndex];
62571 getCellText : function(rowIndex, colIndex){
62572 return this.getCell(rowIndex, colIndex).firstChild.firstChild;
62575 getCellBox : function(cell){
62576 var b = this.fly(cell).getBox();
62577 if(Roo.isOpera){ // opera fails to report the Y
62578 b.y = cell.offsetTop + this.mainBody.getY();
62583 getCellIndex : function(cell){
62584 var id = String(cell.className).match(this.cellRE);
62586 return parseInt(id[1], 10);
62591 findHeaderIndex : function(n){
62592 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
62593 return r ? this.getCellIndex(r) : false;
62596 findHeaderCell : function(n){
62597 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
62598 return r ? r : false;
62601 findRowIndex : function(n){
62605 var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
62606 return r ? r.rowIndex : false;
62609 findCellIndex : function(node){
62610 var stop = this.el.dom;
62611 while(node && node != stop){
62612 if(this.findRE.test(node.className)){
62613 return this.getCellIndex(node);
62615 node = node.parentNode;
62620 getColumnId : function(index){
62621 return this.cm.getColumnId(index);
62624 getSplitters : function()
62626 if(this.splitterSelector){
62627 return Roo.DomQuery.select(this.splitterSelector);
62633 getSplitter : function(index){
62634 return this.getSplitters()[index];
62637 onRowOver : function(e, t){
62639 if((row = this.findRowIndex(t)) !== false){
62640 this.getRowComposite(row).addClass("x-grid-row-over");
62644 onRowOut : function(e, t){
62646 if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
62647 this.getRowComposite(row).removeClass("x-grid-row-over");
62651 renderHeaders : function(){
62653 var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
62654 var cb = [], lb = [], sb = [], lsb = [], p = {};
62655 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
62656 p.cellId = "x-grid-hd-0-" + i;
62657 p.splitId = "x-grid-csplit-0-" + i;
62658 p.id = cm.getColumnId(i);
62659 p.value = cm.getColumnHeader(i) || "";
62660 p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</) ? '' : p.value || "";
62661 p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
62662 if(!cm.isLocked(i)){
62663 cb[cb.length] = ct.apply(p);
62664 sb[sb.length] = st.apply(p);
62666 lb[lb.length] = ct.apply(p);
62667 lsb[lsb.length] = st.apply(p);
62670 return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
62671 ht.apply({cells: cb.join(""), splits:sb.join("")})];
62674 updateHeaders : function(){
62675 var html = this.renderHeaders();
62676 this.lockedHd.update(html[0]);
62677 this.mainHd.update(html[1]);
62681 * Focuses the specified row.
62682 * @param {Number} row The row index
62684 focusRow : function(row)
62686 //Roo.log('GridView.focusRow');
62687 var x = this.scroller.dom.scrollLeft;
62688 this.focusCell(row, 0, false);
62689 this.scroller.dom.scrollLeft = x;
62693 * Focuses the specified cell.
62694 * @param {Number} row The row index
62695 * @param {Number} col The column index
62696 * @param {Boolean} hscroll false to disable horizontal scrolling
62698 focusCell : function(row, col, hscroll)
62700 //Roo.log('GridView.focusCell');
62701 var el = this.ensureVisible(row, col, hscroll);
62702 this.focusEl.alignTo(el, "tl-tl");
62704 this.focusEl.focus();
62706 this.focusEl.focus.defer(1, this.focusEl);
62711 * Scrolls the specified cell into view
62712 * @param {Number} row The row index
62713 * @param {Number} col The column index
62714 * @param {Boolean} hscroll false to disable horizontal scrolling
62716 ensureVisible : function(row, col, hscroll)
62718 //Roo.log('GridView.ensureVisible,' + row + ',' + col);
62719 //return null; //disable for testing.
62720 if(typeof row != "number"){
62721 row = row.rowIndex;
62723 if(row < 0 && row >= this.ds.getCount()){
62726 col = (col !== undefined ? col : 0);
62727 var cm = this.grid.colModel;
62728 while(cm.isHidden(col)){
62732 var el = this.getCell(row, col);
62736 var c = this.scroller.dom;
62738 var ctop = parseInt(el.offsetTop, 10);
62739 var cleft = parseInt(el.offsetLeft, 10);
62740 var cbot = ctop + el.offsetHeight;
62741 var cright = cleft + el.offsetWidth;
62743 var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
62744 var stop = parseInt(c.scrollTop, 10);
62745 var sleft = parseInt(c.scrollLeft, 10);
62746 var sbot = stop + ch;
62747 var sright = sleft + c.clientWidth;
62749 Roo.log('GridView.ensureVisible:' +
62751 ' c.clientHeight:' + c.clientHeight +
62752 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
62760 c.scrollTop = ctop;
62761 //Roo.log("set scrolltop to ctop DISABLE?");
62762 }else if(cbot > sbot){
62763 //Roo.log("set scrolltop to cbot-ch");
62764 c.scrollTop = cbot-ch;
62767 if(hscroll !== false){
62769 c.scrollLeft = cleft;
62770 }else if(cright > sright){
62771 c.scrollLeft = cright-c.clientWidth;
62778 updateColumns : function(){
62779 this.grid.stopEditing();
62780 var cm = this.grid.colModel, colIds = this.getColumnIds();
62781 //var totalWidth = cm.getTotalWidth();
62783 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
62784 //if(cm.isHidden(i)) continue;
62785 var w = cm.getColumnWidth(i);
62786 this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
62787 this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
62789 this.updateSplitters();
62792 generateRules : function(cm){
62793 var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
62794 Roo.util.CSS.removeStyleSheet(rulesId);
62795 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
62796 var cid = cm.getColumnId(i);
62798 if(cm.config[i].align){
62799 align = 'text-align:'+cm.config[i].align+';';
62802 if(cm.isHidden(i)){
62803 hidden = 'display:none;';
62805 var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
62807 this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
62808 this.hdSelector, cid, " {\n", align, width, "}\n",
62809 this.tdSelector, cid, " {\n",hidden,"\n}\n",
62810 this.splitSelector, cid, " {\n", hidden , "\n}\n");
62812 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
62815 updateSplitters : function(){
62816 var cm = this.cm, s = this.getSplitters();
62817 if(s){ // splitters not created yet
62818 var pos = 0, locked = true;
62819 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
62820 if(cm.isHidden(i)) {
62823 var w = cm.getColumnWidth(i); // make sure it's a number
62824 if(!cm.isLocked(i) && locked){
62829 s[i].style.left = (pos-this.splitOffset) + "px";
62834 handleHiddenChange : function(colModel, colIndex, hidden){
62836 this.hideColumn(colIndex);
62838 this.unhideColumn(colIndex);
62842 hideColumn : function(colIndex){
62843 var cid = this.getColumnId(colIndex);
62844 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
62845 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
62847 this.updateHeaders();
62849 this.updateSplitters();
62853 unhideColumn : function(colIndex){
62854 var cid = this.getColumnId(colIndex);
62855 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
62856 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
62859 this.updateHeaders();
62861 this.updateSplitters();
62865 insertRows : function(dm, firstRow, lastRow, isUpdate){
62866 if(firstRow == 0 && lastRow == dm.getCount()-1){
62870 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
62872 var s = this.getScrollState();
62873 var markup = this.renderRows(firstRow, lastRow);
62874 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
62875 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
62876 this.restoreScroll(s);
62878 this.fireEvent("rowsinserted", this, firstRow, lastRow);
62879 this.syncRowHeights(firstRow, lastRow);
62880 this.stripeRows(firstRow);
62886 bufferRows : function(markup, target, index){
62887 var before = null, trows = target.rows, tbody = target.tBodies[0];
62888 if(index < trows.length){
62889 before = trows[index];
62891 var b = document.createElement("div");
62892 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
62893 var rows = b.firstChild.rows;
62894 for(var i = 0, len = rows.length; i < len; i++){
62896 tbody.insertBefore(rows[0], before);
62898 tbody.appendChild(rows[0]);
62905 deleteRows : function(dm, firstRow, lastRow){
62906 if(dm.getRowCount()<1){
62907 this.fireEvent("beforerefresh", this);
62908 this.mainBody.update("");
62909 this.lockedBody.update("");
62910 this.fireEvent("refresh", this);
62912 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
62913 var bt = this.getBodyTable();
62914 var tbody = bt.firstChild;
62915 var rows = bt.rows;
62916 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
62917 tbody.removeChild(rows[firstRow]);
62919 this.stripeRows(firstRow);
62920 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
62924 updateRows : function(dataSource, firstRow, lastRow){
62925 var s = this.getScrollState();
62927 this.restoreScroll(s);
62930 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
62934 this.updateHeaderSortState();
62937 getScrollState : function(){
62939 var sb = this.scroller.dom;
62940 return {left: sb.scrollLeft, top: sb.scrollTop};
62943 stripeRows : function(startRow){
62944 if(!this.grid.stripeRows || this.ds.getCount() < 1){
62947 startRow = startRow || 0;
62948 var rows = this.getBodyTable().rows;
62949 var lrows = this.getLockedTable().rows;
62950 var cls = ' x-grid-row-alt ';
62951 for(var i = startRow, len = rows.length; i < len; i++){
62952 var row = rows[i], lrow = lrows[i];
62953 var isAlt = ((i+1) % 2 == 0);
62954 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
62955 if(isAlt == hasAlt){
62959 row.className += " x-grid-row-alt";
62961 row.className = row.className.replace("x-grid-row-alt", "");
62964 lrow.className = row.className;
62969 restoreScroll : function(state){
62970 //Roo.log('GridView.restoreScroll');
62971 var sb = this.scroller.dom;
62972 sb.scrollLeft = state.left;
62973 sb.scrollTop = state.top;
62977 syncScroll : function(){
62978 //Roo.log('GridView.syncScroll');
62979 var sb = this.scroller.dom;
62980 var sh = this.mainHd.dom;
62981 var bs = this.mainBody.dom;
62982 var lv = this.lockedBody.dom;
62983 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
62984 lv.scrollTop = bs.scrollTop = sb.scrollTop;
62987 handleScroll : function(e){
62989 var sb = this.scroller.dom;
62990 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
62994 handleWheel : function(e){
62995 var d = e.getWheelDelta();
62996 this.scroller.dom.scrollTop -= d*22;
62997 // set this here to prevent jumpy scrolling on large tables
62998 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
63002 renderRows : function(startRow, endRow){
63003 // pull in all the crap needed to render rows
63004 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
63005 var colCount = cm.getColumnCount();
63007 if(ds.getCount() < 1){
63011 // build a map for all the columns
63013 for(var i = 0; i < colCount; i++){
63014 var name = cm.getDataIndex(i);
63016 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
63017 renderer : cm.getRenderer(i),
63018 id : cm.getColumnId(i),
63019 locked : cm.isLocked(i),
63020 has_editor : cm.isCellEditable(i)
63024 startRow = startRow || 0;
63025 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
63027 // records to render
63028 var rs = ds.getRange(startRow, endRow);
63030 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
63033 // As much as I hate to duplicate code, this was branched because FireFox really hates
63034 // [].join("") on strings. The performance difference was substantial enough to
63035 // branch this function
63036 doRender : Roo.isGecko ?
63037 function(cs, rs, ds, startRow, colCount, stripe){
63038 var ts = this.templates, ct = ts.cell, rt = ts.row;
63040 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
63042 var hasListener = this.grid.hasListener('rowclass');
63044 for(var j = 0, len = rs.length; j < len; j++){
63045 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
63046 for(var i = 0; i < colCount; i++){
63048 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
63050 p.css = p.attr = "";
63051 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
63052 if(p.value == undefined || p.value === "") {
63053 p.value = " ";
63056 p.css += ' x-grid-editable-cell';
63058 if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
63059 p.css += ' x-grid-dirty-cell';
63061 var markup = ct.apply(p);
63069 if(stripe && ((rowIndex+1) % 2 == 0)){
63070 alt.push("x-grid-row-alt")
63073 alt.push( " x-grid-dirty-row");
63076 if(this.getRowClass){
63077 alt.push(this.getRowClass(r, rowIndex));
63083 rowIndex : rowIndex,
63086 this.grid.fireEvent('rowclass', this, rowcfg);
63087 alt.push(rowcfg.rowClass);
63089 rp.alt = alt.join(" ");
63090 lbuf+= rt.apply(rp);
63092 buf+= rt.apply(rp);
63094 return [lbuf, buf];
63096 function(cs, rs, ds, startRow, colCount, stripe){
63097 var ts = this.templates, ct = ts.cell, rt = ts.row;
63099 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
63100 var hasListener = this.grid.hasListener('rowclass');
63103 for(var j = 0, len = rs.length; j < len; j++){
63104 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
63105 for(var i = 0; i < colCount; i++){
63107 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
63109 p.css = p.attr = "";
63110 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
63111 if(p.value == undefined || p.value === "") {
63112 p.value = " ";
63116 p.css += ' x-grid-editable-cell';
63118 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
63119 p.css += ' x-grid-dirty-cell'
63122 var markup = ct.apply(p);
63124 cb[cb.length] = markup;
63126 lcb[lcb.length] = markup;
63130 if(stripe && ((rowIndex+1) % 2 == 0)){
63131 alt.push( "x-grid-row-alt");
63134 alt.push(" x-grid-dirty-row");
63137 if(this.getRowClass){
63138 alt.push( this.getRowClass(r, rowIndex));
63144 rowIndex : rowIndex,
63147 this.grid.fireEvent('rowclass', this, rowcfg);
63148 alt.push(rowcfg.rowClass);
63151 rp.alt = alt.join(" ");
63152 rp.cells = lcb.join("");
63153 lbuf[lbuf.length] = rt.apply(rp);
63154 rp.cells = cb.join("");
63155 buf[buf.length] = rt.apply(rp);
63157 return [lbuf.join(""), buf.join("")];
63160 renderBody : function(){
63161 var markup = this.renderRows();
63162 var bt = this.templates.body;
63163 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
63167 * Refreshes the grid
63168 * @param {Boolean} headersToo
63170 refresh : function(headersToo){
63171 this.fireEvent("beforerefresh", this);
63172 this.grid.stopEditing();
63173 var result = this.renderBody();
63174 this.lockedBody.update(result[0]);
63175 this.mainBody.update(result[1]);
63176 if(headersToo === true){
63177 this.updateHeaders();
63178 this.updateColumns();
63179 this.updateSplitters();
63180 this.updateHeaderSortState();
63182 this.syncRowHeights();
63184 this.fireEvent("refresh", this);
63187 handleColumnMove : function(cm, oldIndex, newIndex){
63188 this.indexMap = null;
63189 var s = this.getScrollState();
63190 this.refresh(true);
63191 this.restoreScroll(s);
63192 this.afterMove(newIndex);
63195 afterMove : function(colIndex){
63196 if(this.enableMoveAnim && Roo.enableFx){
63197 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
63199 // if multisort - fix sortOrder, and reload..
63200 if (this.grid.dataSource.multiSort) {
63201 // the we can call sort again..
63202 var dm = this.grid.dataSource;
63203 var cm = this.grid.colModel;
63205 for(var i = 0; i < cm.config.length; i++ ) {
63207 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
63208 continue; // dont' bother, it's not in sort list or being set.
63211 so.push(cm.config[i].dataIndex);
63214 dm.load(dm.lastOptions);
63221 updateCell : function(dm, rowIndex, dataIndex){
63222 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
63223 if(typeof colIndex == "undefined"){ // not present in grid
63226 var cm = this.grid.colModel;
63227 var cell = this.getCell(rowIndex, colIndex);
63228 var cellText = this.getCellText(rowIndex, colIndex);
63231 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
63232 id : cm.getColumnId(colIndex),
63233 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
63235 var renderer = cm.getRenderer(colIndex);
63236 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
63237 if(typeof val == "undefined" || val === "") {
63240 cellText.innerHTML = val;
63241 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
63242 this.syncRowHeights(rowIndex, rowIndex);
63245 calcColumnWidth : function(colIndex, maxRowsToMeasure){
63247 if(this.grid.autoSizeHeaders){
63248 var h = this.getHeaderCellMeasure(colIndex);
63249 maxWidth = Math.max(maxWidth, h.scrollWidth);
63252 if(this.cm.isLocked(colIndex)){
63253 tb = this.getLockedTable();
63256 tb = this.getBodyTable();
63257 index = colIndex - this.cm.getLockedCount();
63260 var rows = tb.rows;
63261 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
63262 for(var i = 0; i < stopIndex; i++){
63263 var cell = rows[i].childNodes[index].firstChild;
63264 maxWidth = Math.max(maxWidth, cell.scrollWidth);
63267 return maxWidth + /*margin for error in IE*/ 5;
63270 * Autofit a column to its content.
63271 * @param {Number} colIndex
63272 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
63274 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
63275 if(this.cm.isHidden(colIndex)){
63276 return; // can't calc a hidden column
63279 var cid = this.cm.getColumnId(colIndex);
63280 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
63281 if(this.grid.autoSizeHeaders){
63282 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
63285 var newWidth = this.calcColumnWidth(colIndex);
63286 this.cm.setColumnWidth(colIndex,
63287 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
63288 if(!suppressEvent){
63289 this.grid.fireEvent("columnresize", colIndex, newWidth);
63294 * Autofits all columns to their content and then expands to fit any extra space in the grid
63296 autoSizeColumns : function(){
63297 var cm = this.grid.colModel;
63298 var colCount = cm.getColumnCount();
63299 for(var i = 0; i < colCount; i++){
63300 this.autoSizeColumn(i, true, true);
63302 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
63305 this.updateColumns();
63311 * Autofits all columns to the grid's width proportionate with their current size
63312 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
63314 fitColumns : function(reserveScrollSpace){
63315 var cm = this.grid.colModel;
63316 var colCount = cm.getColumnCount();
63320 for (i = 0; i < colCount; i++){
63321 if(!cm.isHidden(i) && !cm.isFixed(i)){
63322 w = cm.getColumnWidth(i);
63328 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
63329 if(reserveScrollSpace){
63332 var frac = (avail - cm.getTotalWidth())/width;
63333 while (cols.length){
63336 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
63338 this.updateColumns();
63342 onRowSelect : function(rowIndex){
63343 var row = this.getRowComposite(rowIndex);
63344 row.addClass("x-grid-row-selected");
63347 onRowDeselect : function(rowIndex){
63348 var row = this.getRowComposite(rowIndex);
63349 row.removeClass("x-grid-row-selected");
63352 onCellSelect : function(row, col){
63353 var cell = this.getCell(row, col);
63355 Roo.fly(cell).addClass("x-grid-cell-selected");
63359 onCellDeselect : function(row, col){
63360 var cell = this.getCell(row, col);
63362 Roo.fly(cell).removeClass("x-grid-cell-selected");
63366 updateHeaderSortState : function(){
63368 // sort state can be single { field: xxx, direction : yyy}
63369 // or { xxx=>ASC , yyy : DESC ..... }
63372 if (!this.ds.multiSort) {
63373 var state = this.ds.getSortState();
63377 mstate[state.field] = state.direction;
63378 // FIXME... - this is not used here.. but might be elsewhere..
63379 this.sortState = state;
63382 mstate = this.ds.sortToggle;
63384 //remove existing sort classes..
63386 var sc = this.sortClasses;
63387 var hds = this.el.select(this.headerSelector).removeClass(sc);
63389 for(var f in mstate) {
63391 var sortColumn = this.cm.findColumnIndex(f);
63393 if(sortColumn != -1){
63394 var sortDir = mstate[f];
63395 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
63404 handleHeaderClick : function(g, index,e){
63406 Roo.log("header click");
63409 // touch events on header are handled by context
63410 this.handleHdCtx(g,index,e);
63415 if(this.headersDisabled){
63418 var dm = g.dataSource, cm = g.colModel;
63419 if(!cm.isSortable(index)){
63424 if (dm.multiSort) {
63425 // update the sortOrder
63427 for(var i = 0; i < cm.config.length; i++ ) {
63429 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
63430 continue; // dont' bother, it's not in sort list or being set.
63433 so.push(cm.config[i].dataIndex);
63439 dm.sort(cm.getDataIndex(index));
63443 destroy : function(){
63445 this.colMenu.removeAll();
63446 Roo.menu.MenuMgr.unregister(this.colMenu);
63447 this.colMenu.getEl().remove();
63448 delete this.colMenu;
63451 this.hmenu.removeAll();
63452 Roo.menu.MenuMgr.unregister(this.hmenu);
63453 this.hmenu.getEl().remove();
63456 if(this.grid.enableColumnMove){
63457 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
63459 for(var dd in dds){
63460 if(!dds[dd].config.isTarget && dds[dd].dragElId){
63461 var elid = dds[dd].dragElId;
63463 Roo.get(elid).remove();
63464 } else if(dds[dd].config.isTarget){
63465 dds[dd].proxyTop.remove();
63466 dds[dd].proxyBottom.remove();
63469 if(Roo.dd.DDM.locationCache[dd]){
63470 delete Roo.dd.DDM.locationCache[dd];
63473 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
63476 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
63477 this.bind(null, null);
63478 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
63481 handleLockChange : function(){
63482 this.refresh(true);
63485 onDenyColumnLock : function(){
63489 onDenyColumnHide : function(){
63493 handleHdMenuClick : function(item){
63494 var index = this.hdCtxIndex;
63495 var cm = this.cm, ds = this.ds;
63498 ds.sort(cm.getDataIndex(index), "ASC");
63501 ds.sort(cm.getDataIndex(index), "DESC");
63504 var lc = cm.getLockedCount();
63505 if(cm.getColumnCount(true) <= lc+1){
63506 this.onDenyColumnLock();
63510 cm.setLocked(index, true, true);
63511 cm.moveColumn(index, lc);
63512 this.grid.fireEvent("columnmove", index, lc);
63514 cm.setLocked(index, true);
63518 var lc = cm.getLockedCount();
63519 if((lc-1) != index){
63520 cm.setLocked(index, false, true);
63521 cm.moveColumn(index, lc-1);
63522 this.grid.fireEvent("columnmove", index, lc-1);
63524 cm.setLocked(index, false);
63527 case 'wider': // used to expand cols on touch..
63529 var cw = cm.getColumnWidth(index);
63530 cw += (item.id == 'wider' ? 1 : -1) * 50;
63531 cw = Math.max(0, cw);
63532 cw = Math.min(cw,4000);
63533 cm.setColumnWidth(index, cw);
63537 index = cm.getIndexById(item.id.substr(4));
63539 if(item.checked && cm.getColumnCount(true) <= 1){
63540 this.onDenyColumnHide();
63543 cm.setHidden(index, item.checked);
63549 beforeColMenuShow : function(){
63550 var cm = this.cm, colCount = cm.getColumnCount();
63551 this.colMenu.removeAll();
63554 for(var i = 0; i < colCount; i++){
63556 id: "col-"+cm.getColumnId(i),
63557 text: cm.getColumnHeader(i),
63558 checked: !cm.isHidden(i),
63563 if (this.grid.sortColMenu) {
63564 items.sort(function(a,b) {
63565 if (a.text == b.text) {
63568 return a.text.toUpperCase() > b.text.toUpperCase() ? 1 : -1;
63572 for(var i = 0; i < colCount; i++){
63573 this.colMenu.add(new Roo.menu.CheckItem(items[i]));
63577 handleHdCtx : function(g, index, e){
63579 var hd = this.getHeaderCell(index);
63580 this.hdCtxIndex = index;
63581 var ms = this.hmenu.items, cm = this.cm;
63582 ms.get("asc").setDisabled(!cm.isSortable(index));
63583 ms.get("desc").setDisabled(!cm.isSortable(index));
63584 if(this.grid.enableColLock !== false){
63585 ms.get("lock").setDisabled(cm.isLocked(index));
63586 ms.get("unlock").setDisabled(!cm.isLocked(index));
63588 this.hmenu.show(hd, "tl-bl");
63591 handleHdOver : function(e){
63592 var hd = this.findHeaderCell(e.getTarget());
63593 if(hd && !this.headersDisabled){
63594 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
63595 this.fly(hd).addClass("x-grid-hd-over");
63600 handleHdOut : function(e){
63601 var hd = this.findHeaderCell(e.getTarget());
63603 this.fly(hd).removeClass("x-grid-hd-over");
63607 handleSplitDblClick : function(e, t){
63608 var i = this.getCellIndex(t);
63609 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
63610 this.autoSizeColumn(i, true);
63615 render : function(){
63618 var colCount = cm.getColumnCount();
63620 if(this.grid.monitorWindowResize === true){
63621 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
63623 var header = this.renderHeaders();
63624 var body = this.templates.body.apply({rows:""});
63625 var html = this.templates.master.apply({
63628 lockedHeader: header[0],
63632 //this.updateColumns();
63634 this.grid.getGridEl().dom.innerHTML = html;
63636 this.initElements();
63638 // a kludge to fix the random scolling effect in webkit
63639 this.el.on("scroll", function() {
63640 this.el.dom.scrollTop=0; // hopefully not recursive..
63643 this.scroller.on("scroll", this.handleScroll, this);
63644 this.lockedBody.on("mousewheel", this.handleWheel, this);
63645 this.mainBody.on("mousewheel", this.handleWheel, this);
63647 this.mainHd.on("mouseover", this.handleHdOver, this);
63648 this.mainHd.on("mouseout", this.handleHdOut, this);
63649 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
63650 {delegate: "."+this.splitClass});
63652 this.lockedHd.on("mouseover", this.handleHdOver, this);
63653 this.lockedHd.on("mouseout", this.handleHdOut, this);
63654 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
63655 {delegate: "."+this.splitClass});
63657 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
63658 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
63661 this.updateSplitters();
63663 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
63664 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
63665 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
63668 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
63669 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
63671 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
63672 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
63674 if(this.grid.enableColLock !== false){
63675 this.hmenu.add('-',
63676 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
63677 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
63681 this.hmenu.add('-',
63682 {id:"wider", text: this.columnsWiderText},
63683 {id:"narrow", text: this.columnsNarrowText }
63689 if(this.grid.enableColumnHide !== false){
63691 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
63692 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
63693 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
63695 this.hmenu.add('-',
63696 {id:"columns", text: this.columnsText, menu: this.colMenu}
63699 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
63701 this.grid.on("headercontextmenu", this.handleHdCtx, this);
63704 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
63705 this.dd = new Roo.grid.GridDragZone(this.grid, {
63706 ddGroup : this.grid.ddGroup || 'GridDD'
63712 for(var i = 0; i < colCount; i++){
63713 if(cm.isHidden(i)){
63714 this.hideColumn(i);
63716 if(cm.config[i].align){
63717 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
63718 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
63722 this.updateHeaderSortState();
63724 this.beforeInitialResize();
63727 // two part rendering gives faster view to the user
63728 this.renderPhase2.defer(1, this);
63731 renderPhase2 : function(){
63732 // render the rows now
63734 if(this.grid.autoSizeColumns){
63735 this.autoSizeColumns();
63739 beforeInitialResize : function(){
63743 onColumnSplitterMoved : function(i, w){
63744 this.userResized = true;
63745 var cm = this.grid.colModel;
63746 cm.setColumnWidth(i, w, true);
63747 var cid = cm.getColumnId(i);
63748 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
63749 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
63750 this.updateSplitters();
63752 this.grid.fireEvent("columnresize", i, w);
63755 syncRowHeights : function(startIndex, endIndex){
63756 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
63757 startIndex = startIndex || 0;
63758 var mrows = this.getBodyTable().rows;
63759 var lrows = this.getLockedTable().rows;
63760 var len = mrows.length-1;
63761 endIndex = Math.min(endIndex || len, len);
63762 for(var i = startIndex; i <= endIndex; i++){
63763 var m = mrows[i], l = lrows[i];
63764 var h = Math.max(m.offsetHeight, l.offsetHeight);
63765 m.style.height = l.style.height = h + "px";
63770 layout : function(initialRender, is2ndPass)
63773 var auto = g.autoHeight;
63774 var scrollOffset = 16;
63775 var c = g.getGridEl(), cm = this.cm,
63776 expandCol = g.autoExpandColumn,
63778 //c.beginMeasure();
63780 if(!c.dom.offsetWidth){ // display:none?
63782 this.lockedWrap.show();
63783 this.mainWrap.show();
63788 var hasLock = this.cm.isLocked(0);
63790 var tbh = this.headerPanel.getHeight();
63791 var bbh = this.footerPanel.getHeight();
63794 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
63795 var newHeight = ch + c.getBorderWidth("tb");
63797 newHeight = Math.min(g.maxHeight, newHeight);
63799 c.setHeight(newHeight);
63803 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
63806 var s = this.scroller;
63808 var csize = c.getSize(true);
63810 this.el.setSize(csize.width, csize.height);
63812 this.headerPanel.setWidth(csize.width);
63813 this.footerPanel.setWidth(csize.width);
63815 var hdHeight = this.mainHd.getHeight();
63816 var vw = csize.width;
63817 var vh = csize.height - (tbh + bbh);
63821 var bt = this.getBodyTable();
63823 if(cm.getLockedCount() == cm.config.length){
63824 bt = this.getLockedTable();
63827 var ltWidth = hasLock ?
63828 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
63830 var scrollHeight = bt.offsetHeight;
63831 var scrollWidth = ltWidth + bt.offsetWidth;
63832 var vscroll = false, hscroll = false;
63834 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
63836 var lw = this.lockedWrap, mw = this.mainWrap;
63837 var lb = this.lockedBody, mb = this.mainBody;
63839 setTimeout(function(){
63840 var t = s.dom.offsetTop;
63841 var w = s.dom.clientWidth,
63842 h = s.dom.clientHeight;
63845 lw.setSize(ltWidth, h);
63847 mw.setLeftTop(ltWidth, t);
63848 mw.setSize(w-ltWidth, h);
63850 lb.setHeight(h-hdHeight);
63851 mb.setHeight(h-hdHeight);
63853 if(is2ndPass !== true && !gv.userResized && expandCol){
63854 // high speed resize without full column calculation
63856 var ci = cm.getIndexById(expandCol);
63858 ci = cm.findColumnIndex(expandCol);
63860 ci = Math.max(0, ci); // make sure it's got at least the first col.
63861 var expandId = cm.getColumnId(ci);
63862 var tw = cm.getTotalWidth(false);
63863 var currentWidth = cm.getColumnWidth(ci);
63864 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
63865 if(currentWidth != cw){
63866 cm.setColumnWidth(ci, cw, true);
63867 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
63868 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
63869 gv.updateSplitters();
63870 gv.layout(false, true);
63882 onWindowResize : function(){
63883 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
63889 appendFooter : function(parentEl){
63893 sortAscText : "Sort Ascending",
63894 sortDescText : "Sort Descending",
63895 lockText : "Lock Column",
63896 unlockText : "Unlock Column",
63897 columnsText : "Columns",
63899 columnsWiderText : "Wider",
63900 columnsNarrowText : "Thinner"
63904 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
63905 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
63906 this.proxy.el.addClass('x-grid3-col-dd');
63909 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
63910 handleMouseDown : function(e){
63914 callHandleMouseDown : function(e){
63915 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
63920 * Ext JS Library 1.1.1
63921 * Copyright(c) 2006-2007, Ext JS, LLC.
63923 * Originally Released Under LGPL - original licence link has changed is not relivant.
63926 * <script type="text/javascript">
63929 * @extends Roo.dd.DDProxy
63930 * @class Roo.grid.SplitDragZone
63931 * Support for Column Header resizing
63933 * @param {Object} config
63936 // This is a support class used internally by the Grid components
63937 Roo.grid.SplitDragZone = function(grid, hd, hd2){
63939 this.view = grid.getView();
63940 this.proxy = this.view.resizeProxy;
63941 Roo.grid.SplitDragZone.superclass.constructor.call(
63944 "gridSplitters" + this.grid.getGridEl().id, // SGROUP
63946 dragElId : Roo.id(this.proxy.dom),
63951 this.setHandleElId(Roo.id(hd));
63952 if (hd2 !== false) {
63953 this.setOuterHandleElId(Roo.id(hd2));
63956 this.scroll = false;
63958 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
63959 fly: Roo.Element.fly,
63961 b4StartDrag : function(x, y){
63962 this.view.headersDisabled = true;
63963 var h = this.view.mainWrap ? this.view.mainWrap.getHeight() : (
63964 this.view.headEl.getHeight() + this.view.bodyEl.getHeight()
63966 this.proxy.setHeight(h);
63968 // for old system colWidth really stored the actual width?
63969 // in bootstrap we tried using xs/ms/etc.. to do % sizing?
63970 // which in reality did not work.. - it worked only for fixed sizes
63971 // for resizable we need to use actual sizes.
63972 var w = this.cm.getColumnWidth(this.cellIndex);
63973 if (!this.view.mainWrap) {
63975 w = this.view.getHeaderIndex(this.cellIndex).getWidth();
63980 // this was w-this.grid.minColumnWidth;
63981 // doesnt really make sense? - w = thie curren width or the rendered one?
63982 var minw = Math.max(w-this.grid.minColumnWidth, 0);
63983 this.resetConstraints();
63984 this.setXConstraint(minw, 1000);
63985 this.setYConstraint(0, 0);
63986 this.minX = x - minw;
63987 this.maxX = x + 1000;
63989 if (!this.view.mainWrap) { // this is Bootstrap code..
63990 this.getDragEl().style.display='block';
63993 Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
63997 handleMouseDown : function(e){
63998 ev = Roo.EventObject.setEvent(e);
63999 var t = this.fly(ev.getTarget());
64000 if(t.hasClass("x-grid-split")){
64001 this.cellIndex = this.view.getCellIndex(t.dom);
64002 this.split = t.dom;
64003 this.cm = this.grid.colModel;
64004 if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
64005 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
64010 endDrag : function(e){
64011 this.view.headersDisabled = false;
64012 var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
64013 var diff = endX - this.startPos;
64015 var w = this.cm.getColumnWidth(this.cellIndex);
64016 if (!this.view.mainWrap) {
64019 this.view.onColumnSplitterMoved(this.cellIndex, w+diff);
64022 autoOffset : function(){
64023 this.setDelta(0,0);
64027 * Ext JS Library 1.1.1
64028 * Copyright(c) 2006-2007, Ext JS, LLC.
64030 * Originally Released Under LGPL - original licence link has changed is not relivant.
64033 * <script type="text/javascript">
64037 // This is a support class used internally by the Grid components
64038 Roo.grid.GridDragZone = function(grid, config){
64039 this.view = grid.getView();
64040 Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
64041 if(this.view.lockedBody){
64042 this.setHandleElId(Roo.id(this.view.mainBody.dom));
64043 this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
64045 this.scroll = false;
64047 this.ddel = document.createElement('div');
64048 this.ddel.className = 'x-grid-dd-wrap';
64051 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
64052 ddGroup : "GridDD",
64054 getDragData : function(e){
64055 var t = Roo.lib.Event.getTarget(e);
64056 var rowIndex = this.view.findRowIndex(t);
64057 var sm = this.grid.selModel;
64059 //Roo.log(rowIndex);
64061 if (sm.getSelectedCell) {
64062 // cell selection..
64063 if (!sm.getSelectedCell()) {
64066 if (rowIndex != sm.getSelectedCell()[0]) {
64071 if (sm.getSelections && sm.getSelections().length < 1) {
64076 // before it used to all dragging of unseleted... - now we dont do that.
64077 if(rowIndex !== false){
64082 //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
64084 //if(!sm.isSelected(rowIndex) || e.hasModifier()){
64087 if (e.hasModifier()){
64088 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
64091 Roo.log("getDragData");
64096 rowIndex: rowIndex,
64097 selections: sm.getSelections ? sm.getSelections() : (
64098 sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : [])
64105 onInitDrag : function(e){
64106 var data = this.dragData;
64107 this.ddel.innerHTML = this.grid.getDragDropText();
64108 this.proxy.update(this.ddel);
64109 // fire start drag?
64112 afterRepair : function(){
64113 this.dragging = false;
64116 getRepairXY : function(e, data){
64120 onEndDrag : function(data, e){
64124 onValidDrop : function(dd, e, id){
64129 beforeInvalidDrop : function(e, id){
64134 * Ext JS Library 1.1.1
64135 * Copyright(c) 2006-2007, Ext JS, LLC.
64137 * Originally Released Under LGPL - original licence link has changed is not relivant.
64140 * <script type="text/javascript">
64145 * @class Roo.grid.ColumnModel
64146 * @extends Roo.util.Observable
64147 * This is the default implementation of a ColumnModel used by the Grid. It defines
64148 * the columns in the grid.
64151 var colModel = new Roo.grid.ColumnModel([
64152 {header: "Ticker", width: 60, sortable: true, locked: true},
64153 {header: "Company Name", width: 150, sortable: true},
64154 {header: "Market Cap.", width: 100, sortable: true},
64155 {header: "$ Sales", width: 100, sortable: true, renderer: money},
64156 {header: "Employees", width: 100, sortable: true, resizable: false}
64161 * The config options listed for this class are options which may appear in each
64162 * individual column definition.
64163 * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
64165 * @param {Object} config An Array of column config objects. See this class's
64166 * config objects for details.
64168 Roo.grid.ColumnModel = function(config){
64170 * The config passed into the constructor
64172 this.config = []; //config;
64175 // if no id, create one
64176 // if the column does not have a dataIndex mapping,
64177 // map it to the order it is in the config
64178 for(var i = 0, len = config.length; i < len; i++){
64179 this.addColumn(config[i]);
64184 * The width of columns which have no width specified (defaults to 100)
64187 this.defaultWidth = 100;
64190 * Default sortable of columns which have no sortable specified (defaults to false)
64193 this.defaultSortable = false;
64197 * @event widthchange
64198 * Fires when the width of a column changes.
64199 * @param {ColumnModel} this
64200 * @param {Number} columnIndex The column index
64201 * @param {Number} newWidth The new width
64203 "widthchange": true,
64205 * @event headerchange
64206 * Fires when the text of a header changes.
64207 * @param {ColumnModel} this
64208 * @param {Number} columnIndex The column index
64209 * @param {Number} newText The new header text
64211 "headerchange": true,
64213 * @event hiddenchange
64214 * Fires when a column is hidden or "unhidden".
64215 * @param {ColumnModel} this
64216 * @param {Number} columnIndex The column index
64217 * @param {Boolean} hidden true if hidden, false otherwise
64219 "hiddenchange": true,
64221 * @event columnmoved
64222 * Fires when a column is moved.
64223 * @param {ColumnModel} this
64224 * @param {Number} oldIndex
64225 * @param {Number} newIndex
64227 "columnmoved" : true,
64229 * @event columlockchange
64230 * Fires when a column's locked state is changed
64231 * @param {ColumnModel} this
64232 * @param {Number} colIndex
64233 * @param {Boolean} locked true if locked
64235 "columnlockchange" : true
64237 Roo.grid.ColumnModel.superclass.constructor.call(this);
64239 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
64241 * @cfg {String} header The header text to display in the Grid view.
64244 * @cfg {String} xsHeader Header at Bootsrap Extra Small width (default for all)
64247 * @cfg {String} smHeader Header at Bootsrap Small width
64250 * @cfg {String} mdHeader Header at Bootsrap Medium width
64253 * @cfg {String} lgHeader Header at Bootsrap Large width
64256 * @cfg {String} xlHeader Header at Bootsrap extra Large width
64259 * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
64260 * {@link Roo.data.Record} definition from which to draw the column's value. If not
64261 * specified, the column's index is used as an index into the Record's data Array.
64264 * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
64265 * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
64268 * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
64269 * Defaults to the value of the {@link #defaultSortable} property.
64270 * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
64273 * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid. Defaults to false.
64276 * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed. Defaults to false.
64279 * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
64282 * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
64285 * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
64286 * given the cell's data value. See {@link #setRenderer}. If not specified, the
64287 * default renderer returns the escaped data value. If an object is returned (bootstrap only)
64288 * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
64291 * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor
64294 * @cfg {String} align (Optional) Set the CSS text-align property of the column. Defaults to undefined.
64297 * @cfg {String} valign (Optional) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc). Defaults to undefined.
64300 * @cfg {String} cursor (Optional)
64303 * @cfg {String} tooltip (Optional)
64306 * @cfg {Number} xs (Optional) can be '0' for hidden at this size (number less than 12)
64309 * @cfg {Number} sm (Optional) can be '0' for hidden at this size (number less than 12)
64312 * @cfg {Number} md (Optional) can be '0' for hidden at this size (number less than 12)
64315 * @cfg {Number} lg (Optional) can be '0' for hidden at this size (number less than 12)
64318 * @cfg {Number} xl (Optional) can be '0' for hidden at this size (number less than 12)
64321 * Returns the id of the column at the specified index.
64322 * @param {Number} index The column index
64323 * @return {String} the id
64325 getColumnId : function(index){
64326 return this.config[index].id;
64330 * Returns the column for a specified id.
64331 * @param {String} id The column id
64332 * @return {Object} the column
64334 getColumnById : function(id){
64335 return this.lookup[id];
64340 * Returns the column Object for a specified dataIndex.
64341 * @param {String} dataIndex The column dataIndex
64342 * @return {Object|Boolean} the column or false if not found
64344 getColumnByDataIndex: function(dataIndex){
64345 var index = this.findColumnIndex(dataIndex);
64346 return index > -1 ? this.config[index] : false;
64350 * Returns the index for a specified column id.
64351 * @param {String} id The column id
64352 * @return {Number} the index, or -1 if not found
64354 getIndexById : function(id){
64355 for(var i = 0, len = this.config.length; i < len; i++){
64356 if(this.config[i].id == id){
64364 * Returns the index for a specified column dataIndex.
64365 * @param {String} dataIndex The column dataIndex
64366 * @return {Number} the index, or -1 if not found
64369 findColumnIndex : function(dataIndex){
64370 for(var i = 0, len = this.config.length; i < len; i++){
64371 if(this.config[i].dataIndex == dataIndex){
64379 moveColumn : function(oldIndex, newIndex){
64380 var c = this.config[oldIndex];
64381 this.config.splice(oldIndex, 1);
64382 this.config.splice(newIndex, 0, c);
64383 this.dataMap = null;
64384 this.fireEvent("columnmoved", this, oldIndex, newIndex);
64387 isLocked : function(colIndex){
64388 return this.config[colIndex].locked === true;
64391 setLocked : function(colIndex, value, suppressEvent){
64392 if(this.isLocked(colIndex) == value){
64395 this.config[colIndex].locked = value;
64396 if(!suppressEvent){
64397 this.fireEvent("columnlockchange", this, colIndex, value);
64401 getTotalLockedWidth : function(){
64402 var totalWidth = 0;
64403 for(var i = 0; i < this.config.length; i++){
64404 if(this.isLocked(i) && !this.isHidden(i)){
64405 this.totalWidth += this.getColumnWidth(i);
64411 getLockedCount : function(){
64412 for(var i = 0, len = this.config.length; i < len; i++){
64413 if(!this.isLocked(i)){
64418 return this.config.length;
64422 * Returns the number of columns.
64425 getColumnCount : function(visibleOnly){
64426 if(visibleOnly === true){
64428 for(var i = 0, len = this.config.length; i < len; i++){
64429 if(!this.isHidden(i)){
64435 return this.config.length;
64439 * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
64440 * @param {Function} fn
64441 * @param {Object} scope (optional)
64442 * @return {Array} result
64444 getColumnsBy : function(fn, scope){
64446 for(var i = 0, len = this.config.length; i < len; i++){
64447 var c = this.config[i];
64448 if(fn.call(scope||this, c, i) === true){
64456 * Returns true if the specified column is sortable.
64457 * @param {Number} col The column index
64458 * @return {Boolean}
64460 isSortable : function(col){
64461 if(typeof this.config[col].sortable == "undefined"){
64462 return this.defaultSortable;
64464 return this.config[col].sortable;
64468 * Returns the rendering (formatting) function defined for the column.
64469 * @param {Number} col The column index.
64470 * @return {Function} The function used to render the cell. See {@link #setRenderer}.
64472 getRenderer : function(col){
64473 if(!this.config[col].renderer){
64474 return Roo.grid.ColumnModel.defaultRenderer;
64476 return this.config[col].renderer;
64480 * Sets the rendering (formatting) function for a column.
64481 * @param {Number} col The column index
64482 * @param {Function} fn The function to use to process the cell's raw data
64483 * to return HTML markup for the grid view. The render function is called with
64484 * the following parameters:<ul>
64485 * <li>Data value.</li>
64486 * <li>Cell metadata. An object in which you may set the following attributes:<ul>
64487 * <li>css A CSS style string to apply to the table cell.</li>
64488 * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
64489 * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
64490 * <li>Row index</li>
64491 * <li>Column index</li>
64492 * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
64494 setRenderer : function(col, fn){
64495 this.config[col].renderer = fn;
64499 * Returns the width for the specified column.
64500 * @param {Number} col The column index
64501 * @param (optional) {String} gridSize bootstrap width size.
64504 getColumnWidth : function(col, gridSize)
64506 var cfg = this.config[col];
64508 if (typeof(gridSize) == 'undefined') {
64509 return cfg.width * 1 || this.defaultWidth;
64511 if (gridSize === false) { // if we set it..
64512 return cfg.width || false;
64514 var sizes = ['xl', 'lg', 'md', 'sm', 'xs'];
64516 for(var i = sizes.indexOf(gridSize); i < sizes.length; i++) {
64517 if (typeof(cfg[ sizes[i] ] ) == 'undefined') {
64520 return cfg[ sizes[i] ];
64527 * Sets the width for a column.
64528 * @param {Number} col The column index
64529 * @param {Number} width The new width
64531 setColumnWidth : function(col, width, suppressEvent){
64532 this.config[col].width = width;
64533 this.totalWidth = null;
64534 if(!suppressEvent){
64535 this.fireEvent("widthchange", this, col, width);
64540 * Returns the total width of all columns.
64541 * @param {Boolean} includeHidden True to include hidden column widths
64544 getTotalWidth : function(includeHidden){
64545 if(!this.totalWidth){
64546 this.totalWidth = 0;
64547 for(var i = 0, len = this.config.length; i < len; i++){
64548 if(includeHidden || !this.isHidden(i)){
64549 this.totalWidth += this.getColumnWidth(i);
64553 return this.totalWidth;
64557 * Returns the header for the specified column.
64558 * @param {Number} col The column index
64561 getColumnHeader : function(col){
64562 return this.config[col].header;
64566 * Sets the header for a column.
64567 * @param {Number} col The column index
64568 * @param {String} header The new header
64570 setColumnHeader : function(col, header){
64571 this.config[col].header = header;
64572 this.fireEvent("headerchange", this, col, header);
64576 * Returns the tooltip for the specified column.
64577 * @param {Number} col The column index
64580 getColumnTooltip : function(col){
64581 return this.config[col].tooltip;
64584 * Sets the tooltip for a column.
64585 * @param {Number} col The column index
64586 * @param {String} tooltip The new tooltip
64588 setColumnTooltip : function(col, tooltip){
64589 this.config[col].tooltip = tooltip;
64593 * Returns the dataIndex for the specified column.
64594 * @param {Number} col The column index
64597 getDataIndex : function(col){
64598 return this.config[col].dataIndex;
64602 * Sets the dataIndex for a column.
64603 * @param {Number} col The column index
64604 * @param {Number} dataIndex The new dataIndex
64606 setDataIndex : function(col, dataIndex){
64607 this.config[col].dataIndex = dataIndex;
64613 * Returns true if the cell is editable.
64614 * @param {Number} colIndex The column index
64615 * @param {Number} rowIndex The row index - this is nto actually used..?
64616 * @return {Boolean}
64618 isCellEditable : function(colIndex, rowIndex){
64619 return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
64623 * Returns the editor defined for the cell/column.
64624 * return false or null to disable editing.
64625 * @param {Number} colIndex The column index
64626 * @param {Number} rowIndex The row index
64629 getCellEditor : function(colIndex, rowIndex){
64630 return this.config[colIndex].editor;
64634 * Sets if a column is editable.
64635 * @param {Number} col The column index
64636 * @param {Boolean} editable True if the column is editable
64638 setEditable : function(col, editable){
64639 this.config[col].editable = editable;
64644 * Returns true if the column is hidden.
64645 * @param {Number} colIndex The column index
64646 * @return {Boolean}
64648 isHidden : function(colIndex){
64649 return this.config[colIndex].hidden;
64654 * Returns true if the column width cannot be changed
64656 isFixed : function(colIndex){
64657 return this.config[colIndex].fixed;
64661 * Returns true if the column can be resized
64662 * @return {Boolean}
64664 isResizable : function(colIndex){
64665 return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
64668 * Sets if a column is hidden.
64669 * @param {Number} colIndex The column index
64670 * @param {Boolean} hidden True if the column is hidden
64672 setHidden : function(colIndex, hidden){
64673 this.config[colIndex].hidden = hidden;
64674 this.totalWidth = null;
64675 this.fireEvent("hiddenchange", this, colIndex, hidden);
64679 * Sets the editor for a column.
64680 * @param {Number} col The column index
64681 * @param {Object} editor The editor object
64683 setEditor : function(col, editor){
64684 this.config[col].editor = editor;
64687 * Add a column (experimental...) - defaults to adding to the end..
64688 * @param {Object} config
64690 addColumn : function(c)
64693 var i = this.config.length;
64694 this.config[i] = c;
64696 if(typeof c.dataIndex == "undefined"){
64699 if(typeof c.renderer == "string"){
64700 c.renderer = Roo.util.Format[c.renderer];
64702 if(typeof c.id == "undefined"){
64705 if(c.editor && c.editor.xtype){
64706 c.editor = Roo.factory(c.editor, Roo.grid);
64708 if(c.editor && c.editor.isFormField){
64709 c.editor = new Roo.grid.GridEditor(c.editor);
64711 this.lookup[c.id] = c;
64716 Roo.grid.ColumnModel.defaultRenderer = function(value)
64718 if(typeof value == "object") {
64721 if(typeof value == "string" && value.length < 1){
64725 return String.format("{0}", value);
64728 // Alias for backwards compatibility
64729 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
64732 * Ext JS Library 1.1.1
64733 * Copyright(c) 2006-2007, Ext JS, LLC.
64735 * Originally Released Under LGPL - original licence link has changed is not relivant.
64738 * <script type="text/javascript">
64742 * @class Roo.grid.AbstractSelectionModel
64743 * @extends Roo.util.Observable
64745 * Abstract base class for grid SelectionModels. It provides the interface that should be
64746 * implemented by descendant classes. This class should not be directly instantiated.
64749 Roo.grid.AbstractSelectionModel = function(){
64750 this.locked = false;
64751 Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
64754 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable, {
64755 /** @ignore Called by the grid automatically. Do not call directly. */
64756 init : function(grid){
64762 * Locks the selections.
64765 this.locked = true;
64769 * Unlocks the selections.
64771 unlock : function(){
64772 this.locked = false;
64776 * Returns true if the selections are locked.
64777 * @return {Boolean}
64779 isLocked : function(){
64780 return this.locked;
64784 * Ext JS Library 1.1.1
64785 * Copyright(c) 2006-2007, Ext JS, LLC.
64787 * Originally Released Under LGPL - original licence link has changed is not relivant.
64790 * <script type="text/javascript">
64793 * @extends Roo.grid.AbstractSelectionModel
64794 * @class Roo.grid.RowSelectionModel
64795 * The default SelectionModel used by {@link Roo.grid.Grid}.
64796 * It supports multiple selections and keyboard selection/navigation.
64798 * @param {Object} config
64800 Roo.grid.RowSelectionModel = function(config){
64801 Roo.apply(this, config);
64802 this.selections = new Roo.util.MixedCollection(false, function(o){
64807 this.lastActive = false;
64811 * @event selectionchange
64812 * Fires when the selection changes
64813 * @param {SelectionModel} this
64815 "selectionchange" : true,
64817 * @event afterselectionchange
64818 * Fires after the selection changes (eg. by key press or clicking)
64819 * @param {SelectionModel} this
64821 "afterselectionchange" : true,
64823 * @event beforerowselect
64824 * Fires when a row is selected being selected, return false to cancel.
64825 * @param {SelectionModel} this
64826 * @param {Number} rowIndex The selected index
64827 * @param {Boolean} keepExisting False if other selections will be cleared
64829 "beforerowselect" : true,
64832 * Fires when a row is selected.
64833 * @param {SelectionModel} this
64834 * @param {Number} rowIndex The selected index
64835 * @param {Roo.data.Record} r The record
64837 "rowselect" : true,
64839 * @event rowdeselect
64840 * Fires when a row is deselected.
64841 * @param {SelectionModel} this
64842 * @param {Number} rowIndex The selected index
64844 "rowdeselect" : true
64846 Roo.grid.RowSelectionModel.superclass.constructor.call(this);
64847 this.locked = false;
64850 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel, {
64852 * @cfg {Boolean} singleSelect
64853 * True to allow selection of only one row at a time (defaults to false)
64855 singleSelect : false,
64858 initEvents : function(){
64860 if(!this.grid.enableDragDrop && !this.grid.enableDrag){
64861 this.grid.on("mousedown", this.handleMouseDown, this);
64862 }else{ // allow click to work like normal
64863 this.grid.on("rowclick", this.handleDragableRowClick, this);
64865 // bootstrap does not have a view..
64866 var view = this.grid.view ? this.grid.view : this.grid;
64867 this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
64868 "up" : function(e){
64870 this.selectPrevious(e.shiftKey);
64871 }else if(this.last !== false && this.lastActive !== false){
64872 var last = this.last;
64873 this.selectRange(this.last, this.lastActive-1);
64874 view.focusRow(this.lastActive);
64875 if(last !== false){
64879 this.selectFirstRow();
64881 this.fireEvent("afterselectionchange", this);
64883 "down" : function(e){
64885 this.selectNext(e.shiftKey);
64886 }else if(this.last !== false && this.lastActive !== false){
64887 var last = this.last;
64888 this.selectRange(this.last, this.lastActive+1);
64889 view.focusRow(this.lastActive);
64890 if(last !== false){
64894 this.selectFirstRow();
64896 this.fireEvent("afterselectionchange", this);
64902 view.on("refresh", this.onRefresh, this);
64903 view.on("rowupdated", this.onRowUpdated, this);
64904 view.on("rowremoved", this.onRemove, this);
64908 onRefresh : function(){
64909 var ds = this.grid.ds, i, v = this.grid.view;
64910 var s = this.selections;
64911 s.each(function(r){
64912 if((i = ds.indexOfId(r.id)) != -1){
64914 s.add(ds.getAt(i)); // updating the selection relate data
64922 onRemove : function(v, index, r){
64923 this.selections.remove(r);
64927 onRowUpdated : function(v, index, r){
64928 if(this.isSelected(r)){
64929 v.onRowSelect(index);
64935 * @param {Array} records The records to select
64936 * @param {Boolean} keepExisting (optional) True to keep existing selections
64938 selectRecords : function(records, keepExisting){
64940 this.clearSelections();
64942 var ds = this.grid.ds;
64943 for(var i = 0, len = records.length; i < len; i++){
64944 this.selectRow(ds.indexOf(records[i]), true);
64949 * Gets the number of selected rows.
64952 getCount : function(){
64953 return this.selections.length;
64957 * Selects the first row in the grid.
64959 selectFirstRow : function(){
64964 * Select the last row.
64965 * @param {Boolean} keepExisting (optional) True to keep existing selections
64967 selectLastRow : function(keepExisting){
64968 this.selectRow(this.grid.ds.getCount() - 1, keepExisting);
64972 * Selects the row immediately following the last selected row.
64973 * @param {Boolean} keepExisting (optional) True to keep existing selections
64975 selectNext : function(keepExisting){
64976 if(this.last !== false && (this.last+1) < this.grid.ds.getCount()){
64977 this.selectRow(this.last+1, keepExisting);
64978 var view = this.grid.view ? this.grid.view : this.grid;
64979 view.focusRow(this.last);
64984 * Selects the row that precedes the last selected row.
64985 * @param {Boolean} keepExisting (optional) True to keep existing selections
64987 selectPrevious : function(keepExisting){
64989 this.selectRow(this.last-1, keepExisting);
64990 var view = this.grid.view ? this.grid.view : this.grid;
64991 view.focusRow(this.last);
64996 * Returns the selected records
64997 * @return {Array} Array of selected records
64999 getSelections : function(){
65000 return [].concat(this.selections.items);
65004 * Returns the first selected record.
65007 getSelected : function(){
65008 return this.selections.itemAt(0);
65013 * Clears all selections.
65015 clearSelections : function(fast){
65020 var ds = this.grid.ds;
65021 var s = this.selections;
65022 s.each(function(r){
65023 this.deselectRow(ds.indexOfId(r.id));
65027 this.selections.clear();
65034 * Selects all rows.
65036 selectAll : function(){
65040 this.selections.clear();
65041 for(var i = 0, len = this.grid.ds.getCount(); i < len; i++){
65042 this.selectRow(i, true);
65047 * Returns True if there is a selection.
65048 * @return {Boolean}
65050 hasSelection : function(){
65051 return this.selections.length > 0;
65055 * Returns True if the specified row is selected.
65056 * @param {Number/Record} record The record or index of the record to check
65057 * @return {Boolean}
65059 isSelected : function(index){
65060 var r = typeof index == "number" ? this.grid.ds.getAt(index) : index;
65061 return (r && this.selections.key(r.id) ? true : false);
65065 * Returns True if the specified record id is selected.
65066 * @param {String} id The id of record to check
65067 * @return {Boolean}
65069 isIdSelected : function(id){
65070 return (this.selections.key(id) ? true : false);
65074 handleMouseDown : function(e, t)
65076 var view = this.grid.view ? this.grid.view : this.grid;
65078 if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
65081 if(e.shiftKey && this.last !== false){
65082 var last = this.last;
65083 this.selectRange(last, rowIndex, e.ctrlKey);
65084 this.last = last; // reset the last
65085 view.focusRow(rowIndex);
65087 var isSelected = this.isSelected(rowIndex);
65088 if(e.button !== 0 && isSelected){
65089 view.focusRow(rowIndex);
65090 }else if(e.ctrlKey && isSelected){
65091 this.deselectRow(rowIndex);
65092 }else if(!isSelected){
65093 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
65094 view.focusRow(rowIndex);
65097 this.fireEvent("afterselectionchange", this);
65100 handleDragableRowClick : function(grid, rowIndex, e)
65102 if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
65103 this.selectRow(rowIndex, false);
65104 var view = this.grid.view ? this.grid.view : this.grid;
65105 view.focusRow(rowIndex);
65106 this.fireEvent("afterselectionchange", this);
65111 * Selects multiple rows.
65112 * @param {Array} rows Array of the indexes of the row to select
65113 * @param {Boolean} keepExisting (optional) True to keep existing selections
65115 selectRows : function(rows, keepExisting){
65117 this.clearSelections();
65119 for(var i = 0, len = rows.length; i < len; i++){
65120 this.selectRow(rows[i], true);
65125 * Selects a range of rows. All rows in between startRow and endRow are also selected.
65126 * @param {Number} startRow The index of the first row in the range
65127 * @param {Number} endRow The index of the last row in the range
65128 * @param {Boolean} keepExisting (optional) True to retain existing selections
65130 selectRange : function(startRow, endRow, keepExisting){
65135 this.clearSelections();
65137 if(startRow <= endRow){
65138 for(var i = startRow; i <= endRow; i++){
65139 this.selectRow(i, true);
65142 for(var i = startRow; i >= endRow; i--){
65143 this.selectRow(i, true);
65149 * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
65150 * @param {Number} startRow The index of the first row in the range
65151 * @param {Number} endRow The index of the last row in the range
65153 deselectRange : function(startRow, endRow, preventViewNotify){
65157 for(var i = startRow; i <= endRow; i++){
65158 this.deselectRow(i, preventViewNotify);
65164 * @param {Number} row The index of the row to select
65165 * @param {Boolean} keepExisting (optional) True to keep existing selections
65167 selectRow : function(index, keepExisting, preventViewNotify){
65168 if(this.locked || (index < 0 || index >= this.grid.ds.getCount())) {
65171 if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
65172 if(!keepExisting || this.singleSelect){
65173 this.clearSelections();
65175 var r = this.grid.ds.getAt(index);
65176 this.selections.add(r);
65177 this.last = this.lastActive = index;
65178 if(!preventViewNotify){
65179 var view = this.grid.view ? this.grid.view : this.grid;
65180 view.onRowSelect(index);
65182 this.fireEvent("rowselect", this, index, r);
65183 this.fireEvent("selectionchange", this);
65189 * @param {Number} row The index of the row to deselect
65191 deselectRow : function(index, preventViewNotify){
65195 if(this.last == index){
65198 if(this.lastActive == index){
65199 this.lastActive = false;
65201 var r = this.grid.ds.getAt(index);
65202 this.selections.remove(r);
65203 if(!preventViewNotify){
65204 var view = this.grid.view ? this.grid.view : this.grid;
65205 view.onRowDeselect(index);
65207 this.fireEvent("rowdeselect", this, index);
65208 this.fireEvent("selectionchange", this);
65212 restoreLast : function(){
65214 this.last = this._last;
65219 acceptsNav : function(row, col, cm){
65220 return !cm.isHidden(col) && cm.isCellEditable(col, row);
65224 onEditorKey : function(field, e){
65225 var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
65230 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
65232 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
65234 }else if(k == e.ENTER && !e.ctrlKey){
65238 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
65240 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
65242 }else if(k == e.ESC){
65246 g.startEditing(newCell[0], newCell[1]);
65251 * Ext JS Library 1.1.1
65252 * Copyright(c) 2006-2007, Ext JS, LLC.
65254 * Originally Released Under LGPL - original licence link has changed is not relivant.
65257 * <script type="text/javascript">
65260 * @class Roo.grid.CellSelectionModel
65261 * @extends Roo.grid.AbstractSelectionModel
65262 * This class provides the basic implementation for cell selection in a grid.
65264 * @param {Object} config The object containing the configuration of this model.
65265 * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
65267 Roo.grid.CellSelectionModel = function(config){
65268 Roo.apply(this, config);
65270 this.selection = null;
65274 * @event beforerowselect
65275 * Fires before a cell is selected.
65276 * @param {SelectionModel} this
65277 * @param {Number} rowIndex The selected row index
65278 * @param {Number} colIndex The selected cell index
65280 "beforecellselect" : true,
65282 * @event cellselect
65283 * Fires when a cell is selected.
65284 * @param {SelectionModel} this
65285 * @param {Number} rowIndex The selected row index
65286 * @param {Number} colIndex The selected cell index
65288 "cellselect" : true,
65290 * @event selectionchange
65291 * Fires when the active selection changes.
65292 * @param {SelectionModel} this
65293 * @param {Object} selection null for no selection or an object (o) with two properties
65295 <li>o.record: the record object for the row the selection is in</li>
65296 <li>o.cell: An array of [rowIndex, columnIndex]</li>
65299 "selectionchange" : true,
65302 * Fires when the tab (or enter) was pressed on the last editable cell
65303 * You can use this to trigger add new row.
65304 * @param {SelectionModel} this
65308 * @event beforeeditnext
65309 * Fires before the next editable sell is made active
65310 * You can use this to skip to another cell or fire the tabend
65311 * if you set cell to false
65312 * @param {Object} eventdata object : { cell : [ row, col ] }
65314 "beforeeditnext" : true
65316 Roo.grid.CellSelectionModel.superclass.constructor.call(this);
65319 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel, {
65321 enter_is_tab: false,
65324 initEvents : function(){
65325 this.grid.on("mousedown", this.handleMouseDown, this);
65326 this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
65327 var view = this.grid.view;
65328 view.on("refresh", this.onViewChange, this);
65329 view.on("rowupdated", this.onRowUpdated, this);
65330 view.on("beforerowremoved", this.clearSelections, this);
65331 view.on("beforerowsinserted", this.clearSelections, this);
65332 if(this.grid.isEditor){
65333 this.grid.on("beforeedit", this.beforeEdit, this);
65338 beforeEdit : function(e){
65339 this.select(e.row, e.column, false, true, e.record);
65343 onRowUpdated : function(v, index, r){
65344 if(this.selection && this.selection.record == r){
65345 v.onCellSelect(index, this.selection.cell[1]);
65350 onViewChange : function(){
65351 this.clearSelections(true);
65355 * Returns the currently selected cell,.
65356 * @return {Array} The selected cell (row, column) or null if none selected.
65358 getSelectedCell : function(){
65359 return this.selection ? this.selection.cell : null;
65363 * Clears all selections.
65364 * @param {Boolean} true to prevent the gridview from being notified about the change.
65366 clearSelections : function(preventNotify){
65367 var s = this.selection;
65369 if(preventNotify !== true){
65370 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
65372 this.selection = null;
65373 this.fireEvent("selectionchange", this, null);
65378 * Returns true if there is a selection.
65379 * @return {Boolean}
65381 hasSelection : function(){
65382 return this.selection ? true : false;
65386 handleMouseDown : function(e, t){
65387 var v = this.grid.getView();
65388 if(this.isLocked()){
65391 var row = v.findRowIndex(t);
65392 var cell = v.findCellIndex(t);
65393 if(row !== false && cell !== false){
65394 this.select(row, cell);
65400 * @param {Number} rowIndex
65401 * @param {Number} collIndex
65403 select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
65404 if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
65405 this.clearSelections();
65406 r = r || this.grid.dataSource.getAt(rowIndex);
65409 cell : [rowIndex, colIndex]
65411 if(!preventViewNotify){
65412 var v = this.grid.getView();
65413 v.onCellSelect(rowIndex, colIndex);
65414 if(preventFocus !== true){
65415 v.focusCell(rowIndex, colIndex);
65418 this.fireEvent("cellselect", this, rowIndex, colIndex);
65419 this.fireEvent("selectionchange", this, this.selection);
65424 isSelectable : function(rowIndex, colIndex, cm){
65425 return !cm.isHidden(colIndex);
65429 handleKeyDown : function(e){
65430 //Roo.log('Cell Sel Model handleKeyDown');
65431 if(!e.isNavKeyPress()){
65434 var g = this.grid, s = this.selection;
65437 var cell = g.walkCells(0, 0, 1, this.isSelectable, this);
65439 this.select(cell[0], cell[1]);
65444 var walk = function(row, col, step){
65445 return g.walkCells(row, col, step, sm.isSelectable, sm);
65447 var k = e.getKey(), r = s.cell[0], c = s.cell[1];
65454 // handled by onEditorKey
65455 if (g.isEditor && g.editing) {
65459 newCell = walk(r, c-1, -1);
65461 newCell = walk(r, c+1, 1);
65466 newCell = walk(r+1, c, 1);
65470 newCell = walk(r-1, c, -1);
65474 newCell = walk(r, c+1, 1);
65478 newCell = walk(r, c-1, -1);
65483 if(g.isEditor && !g.editing){
65484 g.startEditing(r, c);
65493 this.select(newCell[0], newCell[1]);
65499 acceptsNav : function(row, col, cm){
65500 return !cm.isHidden(col) && cm.isCellEditable(col, row);
65504 * @param {Number} field (not used) - as it's normally used as a listener
65505 * @param {Number} e - event - fake it by using
65507 * var e = Roo.EventObjectImpl.prototype;
65508 * e.keyCode = e.TAB
65512 onEditorKey : function(field, e){
65514 var k = e.getKey(),
65517 ed = g.activeEditor,
65519 ///Roo.log('onEditorKey' + k);
65522 if (this.enter_is_tab && k == e.ENTER) {
65528 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
65530 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
65536 } else if(k == e.ENTER && !e.ctrlKey){
65539 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
65541 } else if(k == e.ESC){
65546 var ecall = { cell : newCell, forward : forward };
65547 this.fireEvent('beforeeditnext', ecall );
65548 newCell = ecall.cell;
65549 forward = ecall.forward;
65553 //Roo.log('next cell after edit');
65554 g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
65555 } else if (forward) {
65556 // tabbed past last
65557 this.fireEvent.defer(100, this, ['tabend',this]);
65562 * Ext JS Library 1.1.1
65563 * Copyright(c) 2006-2007, Ext JS, LLC.
65565 * Originally Released Under LGPL - original licence link has changed is not relivant.
65568 * <script type="text/javascript">
65572 * @class Roo.grid.EditorGrid
65573 * @extends Roo.grid.Grid
65574 * Class for creating and editable grid.
65575 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
65576 * The container MUST have some type of size defined for the grid to fill. The container will be
65577 * automatically set to position relative if it isn't already.
65578 * @param {Object} dataSource The data model to bind to
65579 * @param {Object} colModel The column model with info about this grid's columns
65581 Roo.grid.EditorGrid = function(container, config){
65582 Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
65583 this.getGridEl().addClass("xedit-grid");
65585 if(!this.selModel){
65586 this.selModel = new Roo.grid.CellSelectionModel();
65589 this.activeEditor = null;
65593 * @event beforeedit
65594 * Fires before cell editing is triggered. The edit event object has the following properties <br />
65595 * <ul style="padding:5px;padding-left:16px;">
65596 * <li>grid - This grid</li>
65597 * <li>record - The record being edited</li>
65598 * <li>field - The field name being edited</li>
65599 * <li>value - The value for the field being edited.</li>
65600 * <li>row - The grid row index</li>
65601 * <li>column - The grid column index</li>
65602 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
65604 * @param {Object} e An edit event (see above for description)
65606 "beforeedit" : true,
65609 * Fires after a cell is edited. <br />
65610 * <ul style="padding:5px;padding-left:16px;">
65611 * <li>grid - This grid</li>
65612 * <li>record - The record being edited</li>
65613 * <li>field - The field name being edited</li>
65614 * <li>value - The value being set</li>
65615 * <li>originalValue - The original value for the field, before the edit.</li>
65616 * <li>row - The grid row index</li>
65617 * <li>column - The grid column index</li>
65619 * @param {Object} e An edit event (see above for description)
65621 "afteredit" : true,
65623 * @event validateedit
65624 * Fires after a cell is edited, but before the value is set in the record.
65625 * You can use this to modify the value being set in the field, Return false
65626 * to cancel the change. The edit event object has the following properties <br />
65627 * <ul style="padding:5px;padding-left:16px;">
65628 * <li>editor - This editor</li>
65629 * <li>grid - This grid</li>
65630 * <li>record - The record being edited</li>
65631 * <li>field - The field name being edited</li>
65632 * <li>value - The value being set</li>
65633 * <li>originalValue - The original value for the field, before the edit.</li>
65634 * <li>row - The grid row index</li>
65635 * <li>column - The grid column index</li>
65636 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
65638 * @param {Object} e An edit event (see above for description)
65640 "validateedit" : true
65642 this.on("bodyscroll", this.stopEditing, this);
65643 this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick, this);
65646 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
65648 * @cfg {Number} clicksToEdit
65649 * The number of clicks on a cell required to display the cell's editor (defaults to 2)
65656 trackMouseOver: false, // causes very odd FF errors
65658 onCellDblClick : function(g, row, col){
65659 this.startEditing(row, col);
65662 onEditComplete : function(ed, value, startValue){
65663 this.editing = false;
65664 this.activeEditor = null;
65665 ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
65667 var field = this.colModel.getDataIndex(ed.col);
65672 originalValue: startValue,
65679 var cell = Roo.get(this.view.getCell(ed.row,ed.col));
65682 if(String(value) !== String(startValue)){
65684 if(this.fireEvent("validateedit", e) !== false && !e.cancel){
65685 r.set(field, e.value);
65686 // if we are dealing with a combo box..
65687 // then we also set the 'name' colum to be the displayField
65688 if (ed.field.displayField && ed.field.name) {
65689 r.set(ed.field.name, ed.field.el.dom.value);
65692 delete e.cancel; //?? why!!!
65693 this.fireEvent("afteredit", e);
65696 this.fireEvent("afteredit", e); // always fire it!
65698 this.view.focusCell(ed.row, ed.col);
65702 * Starts editing the specified for the specified row/column
65703 * @param {Number} rowIndex
65704 * @param {Number} colIndex
65706 startEditing : function(row, col){
65707 this.stopEditing();
65708 if(this.colModel.isCellEditable(col, row)){
65709 this.view.ensureVisible(row, col, true);
65711 var r = this.dataSource.getAt(row);
65712 var field = this.colModel.getDataIndex(col);
65713 var cell = Roo.get(this.view.getCell(row,col));
65718 value: r.data[field],
65723 if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
65724 this.editing = true;
65725 var ed = this.colModel.getCellEditor(col, row);
65731 ed.render(ed.parentEl || document.body);
65737 (function(){ // complex but required for focus issues in safari, ie and opera
65741 ed.on("complete", this.onEditComplete, this, {single: true});
65742 ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
65743 this.activeEditor = ed;
65744 var v = r.data[field];
65745 ed.startEdit(this.view.getCell(row, col), v);
65746 // combo's with 'displayField and name set
65747 if (ed.field.displayField && ed.field.name) {
65748 ed.field.el.dom.value = r.data[ed.field.name];
65752 }).defer(50, this);
65758 * Stops any active editing
65760 stopEditing : function(){
65761 if(this.activeEditor){
65762 this.activeEditor.completeEdit();
65764 this.activeEditor = null;
65768 * Called to get grid's drag proxy text, by default returns this.ddText.
65771 getDragDropText : function(){
65772 var count = this.selModel.getSelectedCell() ? 1 : 0;
65773 return String.format(this.ddText, count, count == 1 ? '' : 's');
65778 * Ext JS Library 1.1.1
65779 * Copyright(c) 2006-2007, Ext JS, LLC.
65781 * Originally Released Under LGPL - original licence link has changed is not relivant.
65784 * <script type="text/javascript">
65787 // private - not really -- you end up using it !
65788 // This is a support class used internally by the Grid components
65791 * @class Roo.grid.GridEditor
65792 * @extends Roo.Editor
65793 * Class for creating and editable grid elements.
65794 * @param {Object} config any settings (must include field)
65796 Roo.grid.GridEditor = function(field, config){
65797 if (!config && field.field) {
65799 field = Roo.factory(config.field, Roo.form);
65801 Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
65802 field.monitorTab = false;
65805 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
65808 * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
65811 alignment: "tl-tl",
65814 cls: "x-small-editor x-grid-editor",
65819 * Ext JS Library 1.1.1
65820 * Copyright(c) 2006-2007, Ext JS, LLC.
65822 * Originally Released Under LGPL - original licence link has changed is not relivant.
65825 * <script type="text/javascript">
65830 Roo.grid.PropertyRecord = Roo.data.Record.create([
65831 {name:'name',type:'string'}, 'value'
65835 Roo.grid.PropertyStore = function(grid, source){
65837 this.store = new Roo.data.Store({
65838 recordType : Roo.grid.PropertyRecord
65840 this.store.on('update', this.onUpdate, this);
65842 this.setSource(source);
65844 Roo.grid.PropertyStore.superclass.constructor.call(this);
65849 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
65850 setSource : function(o){
65852 this.store.removeAll();
65855 if(this.isEditableValue(o[k])){
65856 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
65859 this.store.loadRecords({records: data}, {}, true);
65862 onUpdate : function(ds, record, type){
65863 if(type == Roo.data.Record.EDIT){
65864 var v = record.data['value'];
65865 var oldValue = record.modified['value'];
65866 if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
65867 this.source[record.id] = v;
65869 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
65876 getProperty : function(row){
65877 return this.store.getAt(row);
65880 isEditableValue: function(val){
65881 if(val && val instanceof Date){
65883 }else if(typeof val == 'object' || typeof val == 'function'){
65889 setValue : function(prop, value){
65890 this.source[prop] = value;
65891 this.store.getById(prop).set('value', value);
65894 getSource : function(){
65895 return this.source;
65899 Roo.grid.PropertyColumnModel = function(grid, store){
65902 g.PropertyColumnModel.superclass.constructor.call(this, [
65903 {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
65904 {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
65906 this.store = store;
65907 this.bselect = Roo.DomHelper.append(document.body, {
65908 tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
65909 {tag: 'option', value: 'true', html: 'true'},
65910 {tag: 'option', value: 'false', html: 'false'}
65913 Roo.id(this.bselect);
65916 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
65917 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
65918 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
65919 'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
65920 'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
65922 this.renderCellDelegate = this.renderCell.createDelegate(this);
65923 this.renderPropDelegate = this.renderProp.createDelegate(this);
65926 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
65930 valueText : 'Value',
65932 dateFormat : 'm/j/Y',
65935 renderDate : function(dateVal){
65936 return dateVal.dateFormat(this.dateFormat);
65939 renderBool : function(bVal){
65940 return bVal ? 'true' : 'false';
65943 isCellEditable : function(colIndex, rowIndex){
65944 return colIndex == 1;
65947 getRenderer : function(col){
65949 this.renderCellDelegate : this.renderPropDelegate;
65952 renderProp : function(v){
65953 return this.getPropertyName(v);
65956 renderCell : function(val){
65958 if(val instanceof Date){
65959 rv = this.renderDate(val);
65960 }else if(typeof val == 'boolean'){
65961 rv = this.renderBool(val);
65963 return Roo.util.Format.htmlEncode(rv);
65966 getPropertyName : function(name){
65967 var pn = this.grid.propertyNames;
65968 return pn && pn[name] ? pn[name] : name;
65971 getCellEditor : function(colIndex, rowIndex){
65972 var p = this.store.getProperty(rowIndex);
65973 var n = p.data['name'], val = p.data['value'];
65975 if(typeof(this.grid.customEditors[n]) == 'string'){
65976 return this.editors[this.grid.customEditors[n]];
65978 if(typeof(this.grid.customEditors[n]) != 'undefined'){
65979 return this.grid.customEditors[n];
65981 if(val instanceof Date){
65982 return this.editors['date'];
65983 }else if(typeof val == 'number'){
65984 return this.editors['number'];
65985 }else if(typeof val == 'boolean'){
65986 return this.editors['boolean'];
65988 return this.editors['string'];
65994 * @class Roo.grid.PropertyGrid
65995 * @extends Roo.grid.EditorGrid
65996 * This class represents the interface of a component based property grid control.
65997 * <br><br>Usage:<pre><code>
65998 var grid = new Roo.grid.PropertyGrid("my-container-id", {
66006 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
66007 * The container MUST have some type of size defined for the grid to fill. The container will be
66008 * automatically set to position relative if it isn't already.
66009 * @param {Object} config A config object that sets properties on this grid.
66011 Roo.grid.PropertyGrid = function(container, config){
66012 config = config || {};
66013 var store = new Roo.grid.PropertyStore(this);
66014 this.store = store;
66015 var cm = new Roo.grid.PropertyColumnModel(this, store);
66016 store.store.sort('name', 'ASC');
66017 Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
66020 enableColLock:false,
66021 enableColumnMove:false,
66023 trackMouseOver: false,
66026 this.getGridEl().addClass('x-props-grid');
66027 this.lastEditRow = null;
66028 this.on('columnresize', this.onColumnResize, this);
66031 * @event beforepropertychange
66032 * Fires before a property changes (return false to stop?)
66033 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
66034 * @param {String} id Record Id
66035 * @param {String} newval New Value
66036 * @param {String} oldval Old Value
66038 "beforepropertychange": true,
66040 * @event propertychange
66041 * Fires after a property changes
66042 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
66043 * @param {String} id Record Id
66044 * @param {String} newval New Value
66045 * @param {String} oldval Old Value
66047 "propertychange": true
66049 this.customEditors = this.customEditors || {};
66051 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
66054 * @cfg {Object} customEditors map of colnames=> custom editors.
66055 * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
66056 * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
66057 * false disables editing of the field.
66061 * @cfg {Object} propertyNames map of property Names to their displayed value
66064 render : function(){
66065 Roo.grid.PropertyGrid.superclass.render.call(this);
66066 this.autoSize.defer(100, this);
66069 autoSize : function(){
66070 Roo.grid.PropertyGrid.superclass.autoSize.call(this);
66072 this.view.fitColumns();
66076 onColumnResize : function(){
66077 this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
66081 * Sets the data for the Grid
66082 * accepts a Key => Value object of all the elements avaiable.
66083 * @param {Object} data to appear in grid.
66085 setSource : function(source){
66086 this.store.setSource(source);
66090 * Gets all the data from the grid.
66091 * @return {Object} data data stored in grid
66093 getSource : function(){
66094 return this.store.getSource();
66103 * @class Roo.grid.Calendar
66104 * @extends Roo.grid.Grid
66105 * This class extends the Grid to provide a calendar widget
66106 * <br><br>Usage:<pre><code>
66107 var grid = new Roo.grid.Calendar("my-container-id", {
66110 selModel: mySelectionModel,
66111 autoSizeColumns: true,
66112 monitorWindowResize: false,
66113 trackMouseOver: true
66114 eventstore : real data store..
66120 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
66121 * The container MUST have some type of size defined for the grid to fill. The container will be
66122 * automatically set to position relative if it isn't already.
66123 * @param {Object} config A config object that sets properties on this grid.
66125 Roo.grid.Calendar = function(container, config){
66126 // initialize the container
66127 this.container = Roo.get(container);
66128 this.container.update("");
66129 this.container.setStyle("overflow", "hidden");
66130 this.container.addClass('x-grid-container');
66132 this.id = this.container.id;
66134 Roo.apply(this, config);
66135 // check and correct shorthanded configs
66139 for (var r = 0;r < 6;r++) {
66142 for (var c =0;c < 7;c++) {
66146 if (this.eventStore) {
66147 this.eventStore= Roo.factory(this.eventStore, Roo.data);
66148 this.eventStore.on('load',this.onLoad, this);
66149 this.eventStore.on('beforeload',this.clearEvents, this);
66153 this.dataSource = new Roo.data.Store({
66154 proxy: new Roo.data.MemoryProxy(rows),
66155 reader: new Roo.data.ArrayReader({}, [
66156 'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
66159 this.dataSource.load();
66160 this.ds = this.dataSource;
66161 this.ds.xmodule = this.xmodule || false;
66164 var cellRender = function(v,x,r)
66166 return String.format(
66167 '<div class="fc-day fc-widget-content"><div>' +
66168 '<div class="fc-event-container"></div>' +
66169 '<div class="fc-day-number">{0}</div>'+
66171 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
66172 '</div></div>', v);
66177 this.colModel = new Roo.grid.ColumnModel( [
66179 xtype: 'ColumnModel',
66181 dataIndex : 'weekday0',
66183 renderer : cellRender
66186 xtype: 'ColumnModel',
66188 dataIndex : 'weekday1',
66190 renderer : cellRender
66193 xtype: 'ColumnModel',
66195 dataIndex : 'weekday2',
66196 header : 'Tuesday',
66197 renderer : cellRender
66200 xtype: 'ColumnModel',
66202 dataIndex : 'weekday3',
66203 header : 'Wednesday',
66204 renderer : cellRender
66207 xtype: 'ColumnModel',
66209 dataIndex : 'weekday4',
66210 header : 'Thursday',
66211 renderer : cellRender
66214 xtype: 'ColumnModel',
66216 dataIndex : 'weekday5',
66218 renderer : cellRender
66221 xtype: 'ColumnModel',
66223 dataIndex : 'weekday6',
66224 header : 'Saturday',
66225 renderer : cellRender
66228 this.cm = this.colModel;
66229 this.cm.xmodule = this.xmodule || false;
66233 //this.selModel = new Roo.grid.CellSelectionModel();
66234 //this.sm = this.selModel;
66235 //this.selModel.init(this);
66239 this.container.setWidth(this.width);
66243 this.container.setHeight(this.height);
66250 * The raw click event for the entire grid.
66251 * @param {Roo.EventObject} e
66256 * The raw dblclick event for the entire grid.
66257 * @param {Roo.EventObject} e
66261 * @event contextmenu
66262 * The raw contextmenu event for the entire grid.
66263 * @param {Roo.EventObject} e
66265 "contextmenu" : true,
66268 * The raw mousedown event for the entire grid.
66269 * @param {Roo.EventObject} e
66271 "mousedown" : true,
66274 * The raw mouseup event for the entire grid.
66275 * @param {Roo.EventObject} e
66280 * The raw mouseover event for the entire grid.
66281 * @param {Roo.EventObject} e
66283 "mouseover" : true,
66286 * The raw mouseout event for the entire grid.
66287 * @param {Roo.EventObject} e
66292 * The raw keypress event for the entire grid.
66293 * @param {Roo.EventObject} e
66298 * The raw keydown event for the entire grid.
66299 * @param {Roo.EventObject} e
66307 * Fires when a cell is clicked
66308 * @param {Grid} this
66309 * @param {Number} rowIndex
66310 * @param {Number} columnIndex
66311 * @param {Roo.EventObject} e
66313 "cellclick" : true,
66315 * @event celldblclick
66316 * Fires when a cell is double clicked
66317 * @param {Grid} this
66318 * @param {Number} rowIndex
66319 * @param {Number} columnIndex
66320 * @param {Roo.EventObject} e
66322 "celldblclick" : true,
66325 * Fires when a row is clicked
66326 * @param {Grid} this
66327 * @param {Number} rowIndex
66328 * @param {Roo.EventObject} e
66332 * @event rowdblclick
66333 * Fires when a row is double clicked
66334 * @param {Grid} this
66335 * @param {Number} rowIndex
66336 * @param {Roo.EventObject} e
66338 "rowdblclick" : true,
66340 * @event headerclick
66341 * Fires when a header is clicked
66342 * @param {Grid} this
66343 * @param {Number} columnIndex
66344 * @param {Roo.EventObject} e
66346 "headerclick" : true,
66348 * @event headerdblclick
66349 * Fires when a header cell is double clicked
66350 * @param {Grid} this
66351 * @param {Number} columnIndex
66352 * @param {Roo.EventObject} e
66354 "headerdblclick" : true,
66356 * @event rowcontextmenu
66357 * Fires when a row is right clicked
66358 * @param {Grid} this
66359 * @param {Number} rowIndex
66360 * @param {Roo.EventObject} e
66362 "rowcontextmenu" : true,
66364 * @event cellcontextmenu
66365 * Fires when a cell is right clicked
66366 * @param {Grid} this
66367 * @param {Number} rowIndex
66368 * @param {Number} cellIndex
66369 * @param {Roo.EventObject} e
66371 "cellcontextmenu" : true,
66373 * @event headercontextmenu
66374 * Fires when a header is right clicked
66375 * @param {Grid} this
66376 * @param {Number} columnIndex
66377 * @param {Roo.EventObject} e
66379 "headercontextmenu" : true,
66381 * @event bodyscroll
66382 * Fires when the body element is scrolled
66383 * @param {Number} scrollLeft
66384 * @param {Number} scrollTop
66386 "bodyscroll" : true,
66388 * @event columnresize
66389 * Fires when the user resizes a column
66390 * @param {Number} columnIndex
66391 * @param {Number} newSize
66393 "columnresize" : true,
66395 * @event columnmove
66396 * Fires when the user moves a column
66397 * @param {Number} oldIndex
66398 * @param {Number} newIndex
66400 "columnmove" : true,
66403 * Fires when row(s) start being dragged
66404 * @param {Grid} this
66405 * @param {Roo.GridDD} dd The drag drop object
66406 * @param {event} e The raw browser event
66408 "startdrag" : true,
66411 * Fires when a drag operation is complete
66412 * @param {Grid} this
66413 * @param {Roo.GridDD} dd The drag drop object
66414 * @param {event} e The raw browser event
66419 * Fires when dragged row(s) are dropped on a valid DD target
66420 * @param {Grid} this
66421 * @param {Roo.GridDD} dd The drag drop object
66422 * @param {String} targetId The target drag drop object
66423 * @param {event} e The raw browser event
66428 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
66429 * @param {Grid} this
66430 * @param {Roo.GridDD} dd The drag drop object
66431 * @param {String} targetId The target drag drop object
66432 * @param {event} e The raw browser event
66437 * Fires when the dragged row(s) first cross another DD target while being dragged
66438 * @param {Grid} this
66439 * @param {Roo.GridDD} dd The drag drop object
66440 * @param {String} targetId The target drag drop object
66441 * @param {event} e The raw browser event
66443 "dragenter" : true,
66446 * Fires when the dragged row(s) leave another DD target while being dragged
66447 * @param {Grid} this
66448 * @param {Roo.GridDD} dd The drag drop object
66449 * @param {String} targetId The target drag drop object
66450 * @param {event} e The raw browser event
66455 * Fires when a row is rendered, so you can change add a style to it.
66456 * @param {GridView} gridview The grid view
66457 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
66463 * Fires when the grid is rendered
66464 * @param {Grid} grid
66469 * Fires when a date is selected
66470 * @param {DatePicker} this
66471 * @param {Date} date The selected date
66475 * @event monthchange
66476 * Fires when the displayed month changes
66477 * @param {DatePicker} this
66478 * @param {Date} date The selected month
66480 'monthchange': true,
66482 * @event evententer
66483 * Fires when mouse over an event
66484 * @param {Calendar} this
66485 * @param {event} Event
66487 'evententer': true,
66489 * @event eventleave
66490 * Fires when the mouse leaves an
66491 * @param {Calendar} this
66494 'eventleave': true,
66496 * @event eventclick
66497 * Fires when the mouse click an
66498 * @param {Calendar} this
66501 'eventclick': true,
66503 * @event eventrender
66504 * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
66505 * @param {Calendar} this
66506 * @param {data} data to be modified
66508 'eventrender': true
66512 Roo.grid.Grid.superclass.constructor.call(this);
66513 this.on('render', function() {
66514 this.view.el.addClass('x-grid-cal');
66516 (function() { this.setDate(new Date()); }).defer(100,this); //default today..
66520 if (!Roo.grid.Calendar.style) {
66521 Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
66524 '.x-grid-cal .x-grid-col' : {
66525 height: 'auto !important',
66526 'vertical-align': 'top'
66528 '.x-grid-cal .fc-event-hori' : {
66539 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
66541 * @cfg {Store} eventStore The store that loads events.
66546 activeDate : false,
66549 monitorWindowResize : false,
66552 resizeColumns : function() {
66553 var col = (this.view.el.getWidth() / 7) - 3;
66554 // loop through cols, and setWidth
66555 for(var i =0 ; i < 7 ; i++){
66556 this.cm.setColumnWidth(i, col);
66559 setDate :function(date) {
66561 Roo.log('setDate?');
66563 this.resizeColumns();
66564 var vd = this.activeDate;
66565 this.activeDate = date;
66566 // if(vd && this.el){
66567 // var t = date.getTime();
66568 // if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
66569 // Roo.log('using add remove');
66571 // this.fireEvent('monthchange', this, date);
66573 // this.cells.removeClass("fc-state-highlight");
66574 // this.cells.each(function(c){
66575 // if(c.dateValue == t){
66576 // c.addClass("fc-state-highlight");
66577 // setTimeout(function(){
66578 // try{c.dom.firstChild.focus();}catch(e){}
66588 var days = date.getDaysInMonth();
66590 var firstOfMonth = date.getFirstDateOfMonth();
66591 var startingPos = firstOfMonth.getDay()-this.startDay;
66593 if(startingPos < this.startDay){
66597 var pm = date.add(Date.MONTH, -1);
66598 var prevStart = pm.getDaysInMonth()-startingPos;
66602 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
66604 this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
66605 //this.cells.addClassOnOver('fc-state-hover');
66607 var cells = this.cells.elements;
66608 var textEls = this.textNodes;
66610 //Roo.each(cells, function(cell){
66611 // cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
66614 days += startingPos;
66616 // convert everything to numbers so it's fast
66617 var day = 86400000;
66618 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
66621 //Roo.log(prevStart);
66623 var today = new Date().clearTime().getTime();
66624 var sel = date.clearTime().getTime();
66625 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
66626 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
66627 var ddMatch = this.disabledDatesRE;
66628 var ddText = this.disabledDatesText;
66629 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
66630 var ddaysText = this.disabledDaysText;
66631 var format = this.format;
66633 var setCellClass = function(cal, cell){
66635 //Roo.log('set Cell Class');
66637 var t = d.getTime();
66642 cell.dateValue = t;
66644 cell.className += " fc-today";
66645 cell.className += " fc-state-highlight";
66646 cell.title = cal.todayText;
66649 // disable highlight in other month..
66650 cell.className += " fc-state-highlight";
66655 //cell.className = " fc-state-disabled";
66656 cell.title = cal.minText;
66660 //cell.className = " fc-state-disabled";
66661 cell.title = cal.maxText;
66665 if(ddays.indexOf(d.getDay()) != -1){
66666 // cell.title = ddaysText;
66667 // cell.className = " fc-state-disabled";
66670 if(ddMatch && format){
66671 var fvalue = d.dateFormat(format);
66672 if(ddMatch.test(fvalue)){
66673 cell.title = ddText.replace("%0", fvalue);
66674 cell.className = " fc-state-disabled";
66678 if (!cell.initialClassName) {
66679 cell.initialClassName = cell.dom.className;
66682 cell.dom.className = cell.initialClassName + ' ' + cell.className;
66687 for(; i < startingPos; i++) {
66688 cells[i].dayName = (++prevStart);
66689 Roo.log(textEls[i]);
66690 d.setDate(d.getDate()+1);
66692 //cells[i].className = "fc-past fc-other-month";
66693 setCellClass(this, cells[i]);
66698 for(; i < days; i++){
66699 intDay = i - startingPos + 1;
66700 cells[i].dayName = (intDay);
66701 d.setDate(d.getDate()+1);
66703 cells[i].className = ''; // "x-date-active";
66704 setCellClass(this, cells[i]);
66708 for(; i < 42; i++) {
66709 //textEls[i].innerHTML = (++extraDays);
66711 d.setDate(d.getDate()+1);
66712 cells[i].dayName = (++extraDays);
66713 cells[i].className = "fc-future fc-other-month";
66714 setCellClass(this, cells[i]);
66717 //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
66719 var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
66721 // this will cause all the cells to mis
66724 for (var r = 0;r < 6;r++) {
66725 for (var c =0;c < 7;c++) {
66726 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
66730 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
66731 for(i=0;i<cells.length;i++) {
66733 this.cells.elements[i].dayName = cells[i].dayName ;
66734 this.cells.elements[i].className = cells[i].className;
66735 this.cells.elements[i].initialClassName = cells[i].initialClassName ;
66736 this.cells.elements[i].title = cells[i].title ;
66737 this.cells.elements[i].dateValue = cells[i].dateValue ;
66743 //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
66744 //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
66746 ////if(totalRows != 6){
66747 //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
66748 // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
66751 this.fireEvent('monthchange', this, date);
66756 * Returns the grid's SelectionModel.
66757 * @return {SelectionModel}
66759 getSelectionModel : function(){
66760 if(!this.selModel){
66761 this.selModel = new Roo.grid.CellSelectionModel();
66763 return this.selModel;
66767 this.eventStore.load()
66773 findCell : function(dt) {
66774 dt = dt.clearTime().getTime();
66776 this.cells.each(function(c){
66777 //Roo.log("check " +c.dateValue + '?=' + dt);
66778 if(c.dateValue == dt){
66788 findCells : function(rec) {
66789 var s = rec.data.start_dt.clone().clearTime().getTime();
66791 var e= rec.data.end_dt.clone().clearTime().getTime();
66794 this.cells.each(function(c){
66795 ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
66797 if(c.dateValue > e){
66800 if(c.dateValue < s){
66809 findBestRow: function(cells)
66813 for (var i =0 ; i < cells.length;i++) {
66814 ret = Math.max(cells[i].rows || 0,ret);
66821 addItem : function(rec)
66823 // look for vertical location slot in
66824 var cells = this.findCells(rec);
66826 rec.row = this.findBestRow(cells);
66828 // work out the location.
66832 for(var i =0; i < cells.length; i++) {
66840 if (crow.start.getY() == cells[i].getY()) {
66842 crow.end = cells[i];
66858 for (var i = 0; i < cells.length;i++) {
66859 cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
66866 clearEvents: function() {
66868 if (!this.eventStore.getCount()) {
66871 // reset number of rows in cells.
66872 Roo.each(this.cells.elements, function(c){
66876 this.eventStore.each(function(e) {
66877 this.clearEvent(e);
66882 clearEvent : function(ev)
66885 Roo.each(ev.els, function(el) {
66886 el.un('mouseenter' ,this.onEventEnter, this);
66887 el.un('mouseleave' ,this.onEventLeave, this);
66895 renderEvent : function(ev,ctr) {
66897 ctr = this.view.el.select('.fc-event-container',true).first();
66901 this.clearEvent(ev);
66907 var cells = ev.cells;
66908 var rows = ev.rows;
66909 this.fireEvent('eventrender', this, ev);
66911 for(var i =0; i < rows.length; i++) {
66915 cls += ' fc-event-start';
66917 if ((i+1) == rows.length) {
66918 cls += ' fc-event-end';
66921 //Roo.log(ev.data);
66922 // how many rows should it span..
66923 var cg = this.eventTmpl.append(ctr,Roo.apply({
66926 }, ev.data) , true);
66929 cg.on('mouseenter' ,this.onEventEnter, this, ev);
66930 cg.on('mouseleave' ,this.onEventLeave, this, ev);
66931 cg.on('click', this.onEventClick, this, ev);
66935 var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
66936 var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
66939 cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);
66940 cg.setWidth(ebox.right - sbox.x -2);
66944 renderEvents: function()
66946 // first make sure there is enough space..
66948 if (!this.eventTmpl) {
66949 this.eventTmpl = new Roo.Template(
66950 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}" style="position: absolute" unselectable="on">' +
66951 '<div class="fc-event-inner">' +
66952 '<span class="fc-event-time">{time}</span>' +
66953 '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
66955 '<div class="ui-resizable-heandle ui-resizable-e"> </div>' +
66963 this.cells.each(function(c) {
66964 //Roo.log(c.select('.fc-day-content div',true).first());
66965 c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
66968 var ctr = this.view.el.select('.fc-event-container',true).first();
66971 this.eventStore.each(function(ev){
66973 this.renderEvent(ev);
66977 this.view.layout();
66981 onEventEnter: function (e, el,event,d) {
66982 this.fireEvent('evententer', this, el, event);
66985 onEventLeave: function (e, el,event,d) {
66986 this.fireEvent('eventleave', this, el, event);
66989 onEventClick: function (e, el,event,d) {
66990 this.fireEvent('eventclick', this, el, event);
66993 onMonthChange: function () {
66997 onLoad: function () {
66999 //Roo.log('calendar onload');
67001 if(this.eventStore.getCount() > 0){
67005 this.eventStore.each(function(d){
67010 if (typeof(add.end_dt) == 'undefined') {
67011 Roo.log("Missing End time in calendar data: ");
67015 if (typeof(add.start_dt) == 'undefined') {
67016 Roo.log("Missing Start time in calendar data: ");
67020 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
67021 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
67022 add.id = add.id || d.id;
67023 add.title = add.title || '??';
67031 this.renderEvents();
67041 render : function ()
67045 if (!this.view.el.hasClass('course-timesheet')) {
67046 this.view.el.addClass('course-timesheet');
67048 if (this.tsStyle) {
67053 Roo.log(_this.grid.view.el.getWidth());
67056 this.tsStyle = Roo.util.CSS.createStyleSheet({
67057 '.course-timesheet .x-grid-row' : {
67060 '.x-grid-row td' : {
67061 'vertical-align' : 0
67063 '.course-edit-link' : {
67065 'text-overflow' : 'ellipsis',
67066 'overflow' : 'hidden',
67067 'white-space' : 'nowrap',
67068 'cursor' : 'pointer'
67073 '.de-act-sup-link' : {
67074 'color' : 'purple',
67075 'text-decoration' : 'line-through'
67079 'text-decoration' : 'line-through'
67081 '.course-timesheet .course-highlight' : {
67082 'border-top-style': 'dashed !important',
67083 'border-bottom-bottom': 'dashed !important'
67085 '.course-timesheet .course-item' : {
67086 'font-family' : 'tahoma, arial, helvetica',
67087 'font-size' : '11px',
67088 'overflow' : 'hidden',
67089 'padding-left' : '10px',
67090 'padding-right' : '10px',
67091 'padding-top' : '10px'
67099 monitorWindowResize : false,
67100 cellrenderer : function(v,x,r)
67105 xtype: 'CellSelectionModel',
67112 beforeload : function (_self, options)
67114 options.params = options.params || {};
67115 options.params._month = _this.monthField.getValue();
67116 options.params.limit = 9999;
67117 options.params['sort'] = 'when_dt';
67118 options.params['dir'] = 'ASC';
67119 this.proxy.loadResponse = this.loadResponse;
67121 //this.addColumns();
67123 load : function (_self, records, options)
67125 _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
67126 // if you click on the translation.. you can edit it...
67127 var el = Roo.get(this);
67128 var id = el.dom.getAttribute('data-id');
67129 var d = el.dom.getAttribute('data-date');
67130 var t = el.dom.getAttribute('data-time');
67131 //var id = this.child('span').dom.textContent;
67134 Pman.Dialog.CourseCalendar.show({
67138 productitem_active : id ? 1 : 0
67140 _this.grid.ds.load({});
67145 _this.panel.fireEvent('resize', [ '', '' ]);
67148 loadResponse : function(o, success, response){
67149 // this is overridden on before load..
67151 Roo.log("our code?");
67152 //Roo.log(success);
67153 //Roo.log(response)
67154 delete this.activeRequest;
67156 this.fireEvent("loadexception", this, o, response);
67157 o.request.callback.call(o.request.scope, null, o.request.arg, false);
67162 result = o.reader.read(response);
67164 Roo.log("load exception?");
67165 this.fireEvent("loadexception", this, o, response, e);
67166 o.request.callback.call(o.request.scope, null, o.request.arg, false);
67169 Roo.log("ready...");
67170 // loop through result.records;
67171 // and set this.tdate[date] = [] << array of records..
67173 Roo.each(result.records, function(r){
67175 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
67176 _this.tdata[r.data.when_dt.format('j')] = [];
67178 _this.tdata[r.data.when_dt.format('j')].push(r.data);
67181 //Roo.log(_this.tdata);
67183 result.records = [];
67184 result.totalRecords = 6;
67186 // let's generate some duumy records for the rows.
67187 //var st = _this.dateField.getValue();
67189 // work out monday..
67190 //st = st.add(Date.DAY, -1 * st.format('w'));
67192 var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
67194 var firstOfMonth = date.getFirstDayOfMonth();
67195 var days = date.getDaysInMonth();
67197 var firstAdded = false;
67198 for (var i = 0; i < result.totalRecords ; i++) {
67199 //var d= st.add(Date.DAY, i);
67202 for(var w = 0 ; w < 7 ; w++){
67203 if(!firstAdded && firstOfMonth != w){
67210 var dd = (d > 0 && d < 10) ? "0"+d : d;
67211 row['weekday'+w] = String.format(
67212 '<span style="font-size: 16px;"><b>{0}</b></span>'+
67213 '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
67215 date.format('Y-m-')+dd
67218 if(typeof(_this.tdata[d]) != 'undefined'){
67219 Roo.each(_this.tdata[d], function(r){
67223 var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
67224 if(r.parent_id*1>0){
67225 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
67228 if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
67229 deactive = 'de-act-link';
67232 row['weekday'+w] += String.format(
67233 '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
67235 r.product_id_name, //1
67236 r.when_dt.format('h:ia'), //2
67246 // only do this if something added..
67248 result.records.push(_this.grid.dataSource.reader.newRow(row));
67252 // push it twice. (second one with an hour..
67256 this.fireEvent("load", this, o, o.request.arg);
67257 o.request.callback.call(o.request.scope, result, o.request.arg, true);
67259 sortInfo : {field: 'when_dt', direction : 'ASC' },
67261 xtype: 'HttpProxy',
67264 url : baseURL + '/Roo/Shop_course.php'
67267 xtype: 'JsonReader',
67284 'name': 'parent_id',
67288 'name': 'product_id',
67292 'name': 'productitem_id',
67310 click : function (_self, e)
67312 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
67313 sd.setMonth(sd.getMonth()-1);
67314 _this.monthField.setValue(sd.format('Y-m-d'));
67315 _this.grid.ds.load({});
67321 xtype: 'Separator',
67325 xtype: 'MonthField',
67328 render : function (_self)
67330 _this.monthField = _self;
67331 // _this.monthField.set today
67333 select : function (combo, date)
67335 _this.grid.ds.load({});
67338 value : (function() { return new Date(); })()
67341 xtype: 'Separator',
67347 text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
67357 click : function (_self, e)
67359 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
67360 sd.setMonth(sd.getMonth()+1);
67361 _this.monthField.setValue(sd.format('Y-m-d'));
67362 _this.grid.ds.load({});
67375 * Ext JS Library 1.1.1
67376 * Copyright(c) 2006-2007, Ext JS, LLC.
67378 * Originally Released Under LGPL - original licence link has changed is not relivant.
67381 * <script type="text/javascript">
67385 * @class Roo.LoadMask
67386 * A simple utility class for generically masking elements while loading data. If the element being masked has
67387 * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
67388 * process and the mask element will be cached for reuse. For all other elements, this mask will replace the
67389 * element's UpdateManager load indicator and will be destroyed after the initial load.
67391 * Create a new LoadMask
67392 * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
67393 * @param {Object} config The config object
67395 Roo.LoadMask = function(el, config){
67396 this.el = Roo.get(el);
67397 Roo.apply(this, config);
67399 this.store.on('beforeload', this.onBeforeLoad, this);
67400 this.store.on('load', this.onLoad, this);
67401 this.store.on('loadexception', this.onLoadException, this);
67402 this.removeMask = false;
67404 var um = this.el.getUpdateManager();
67405 um.showLoadIndicator = false; // disable the default indicator
67406 um.on('beforeupdate', this.onBeforeLoad, this);
67407 um.on('update', this.onLoad, this);
67408 um.on('failure', this.onLoad, this);
67409 this.removeMask = true;
67413 Roo.LoadMask.prototype = {
67415 * @cfg {Boolean} removeMask
67416 * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
67417 * False to persist the mask element reference for multiple uses (e.g., for paged data widgets). Defaults to false.
67419 removeMask : false,
67421 * @cfg {String} msg
67422 * The text to display in a centered loading message box (defaults to 'Loading...')
67424 msg : 'Loading...',
67426 * @cfg {String} msgCls
67427 * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
67429 msgCls : 'x-mask-loading',
67432 * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
67438 * Disables the mask to prevent it from being displayed
67440 disable : function(){
67441 this.disabled = true;
67445 * Enables the mask so that it can be displayed
67447 enable : function(){
67448 this.disabled = false;
67451 onLoadException : function()
67453 Roo.log(arguments);
67455 if (typeof(arguments[3]) != 'undefined') {
67456 Roo.MessageBox.alert("Error loading",arguments[3]);
67460 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
67461 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
67468 (function() { this.el.unmask(this.removeMask); }).defer(50, this);
67471 onLoad : function()
67473 (function() { this.el.unmask(this.removeMask); }).defer(50, this);
67477 onBeforeLoad : function(){
67478 if(!this.disabled){
67479 (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
67484 destroy : function(){
67486 this.store.un('beforeload', this.onBeforeLoad, this);
67487 this.store.un('load', this.onLoad, this);
67488 this.store.un('loadexception', this.onLoadException, this);
67490 var um = this.el.getUpdateManager();
67491 um.un('beforeupdate', this.onBeforeLoad, this);
67492 um.un('update', this.onLoad, this);
67493 um.un('failure', this.onLoad, this);
67498 * Ext JS Library 1.1.1
67499 * Copyright(c) 2006-2007, Ext JS, LLC.
67501 * Originally Released Under LGPL - original licence link has changed is not relivant.
67504 * <script type="text/javascript">
67509 * @class Roo.XTemplate
67510 * @extends Roo.Template
67511 * Provides a template that can have nested templates for loops or conditionals. The syntax is:
67513 var t = new Roo.XTemplate(
67514 '<select name="{name}">',
67515 '<tpl for="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
67519 // then append, applying the master template values
67522 * Supported features:
67527 {a_variable} - output encoded.
67528 {a_variable.format:("Y-m-d")} - call a method on the variable
67529 {a_variable:raw} - unencoded output
67530 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
67531 {a_variable:this.method_on_template(...)} - call a method on the template object.
67536 <tpl for="a_variable or condition.."></tpl>
67537 <tpl if="a_variable or condition"></tpl>
67538 <tpl exec="some javascript"></tpl>
67539 <tpl name="named_template"></tpl> (experimental)
67541 <tpl for="."></tpl> - just iterate the property..
67542 <tpl for=".."></tpl> - iterates with the parent (probably the template)
67546 Roo.XTemplate = function()
67548 Roo.XTemplate.superclass.constructor.apply(this, arguments);
67555 Roo.extend(Roo.XTemplate, Roo.Template, {
67558 * The various sub templates
67563 * basic tag replacing syntax
67566 * // you can fake an object call by doing this
67570 re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
67573 * compile the template
67575 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
67578 compile: function()
67582 s = ['<tpl>', s, '</tpl>'].join('');
67584 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
67585 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
67586 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
67587 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
67588 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
67593 while(true == !!(m = s.match(re))){
67594 var forMatch = m[0].match(nameRe),
67595 ifMatch = m[0].match(ifRe),
67596 execMatch = m[0].match(execRe),
67597 namedMatch = m[0].match(namedRe),
67602 name = forMatch && forMatch[1] ? forMatch[1] : '';
67605 // if - puts fn into test..
67606 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
67608 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
67613 // exec - calls a function... returns empty if true is returned.
67614 exp = execMatch && execMatch[1] ? execMatch[1] : null;
67616 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
67624 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
67625 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
67626 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
67629 var uid = namedMatch ? namedMatch[1] : id;
67633 id: namedMatch ? namedMatch[1] : id,
67640 s = s.replace(m[0], '');
67642 s = s.replace(m[0], '{xtpl'+ id + '}');
67647 for(var i = tpls.length-1; i >= 0; --i){
67648 this.compileTpl(tpls[i]);
67649 this.tpls[tpls[i].id] = tpls[i];
67651 this.master = tpls[tpls.length-1];
67655 * same as applyTemplate, except it's done to one of the subTemplates
67656 * when using named templates, you can do:
67658 * var str = pl.applySubTemplate('your-name', values);
67661 * @param {Number} id of the template
67662 * @param {Object} values to apply to template
67663 * @param {Object} parent (normaly the instance of this object)
67665 applySubTemplate : function(id, values, parent)
67669 var t = this.tpls[id];
67673 if(t.test && !t.test.call(this, values, parent)){
67677 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
67678 Roo.log(e.toString());
67684 if(t.exec && t.exec.call(this, values, parent)){
67688 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
67689 Roo.log(e.toString());
67694 var vs = t.target ? t.target.call(this, values, parent) : values;
67695 parent = t.target ? values : parent;
67696 if(t.target && vs instanceof Array){
67698 for(var i = 0, len = vs.length; i < len; i++){
67699 buf[buf.length] = t.compiled.call(this, vs[i], parent);
67701 return buf.join('');
67703 return t.compiled.call(this, vs, parent);
67705 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
67706 Roo.log(e.toString());
67707 Roo.log(t.compiled);
67712 compileTpl : function(tpl)
67714 var fm = Roo.util.Format;
67715 var useF = this.disableFormats !== true;
67716 var sep = Roo.isGecko ? "+" : ",";
67717 var undef = function(str) {
67718 Roo.log("Property not found :" + str);
67722 var fn = function(m, name, format, args)
67724 //Roo.log(arguments);
67725 args = args ? args.replace(/\\'/g,"'") : args;
67726 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
67727 if (typeof(format) == 'undefined') {
67728 format= 'htmlEncode';
67730 if (format == 'raw' ) {
67734 if(name.substr(0, 4) == 'xtpl'){
67735 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
67738 // build an array of options to determine if value is undefined..
67740 // basically get 'xxxx.yyyy' then do
67741 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
67742 // (function () { Roo.log("Property not found"); return ''; })() :
67747 Roo.each(name.split('.'), function(st) {
67748 lookfor += (lookfor.length ? '.': '') + st;
67749 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
67752 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
67755 if(format && useF){
67757 args = args ? ',' + args : "";
67759 if(format.substr(0, 5) != "this."){
67760 format = "fm." + format + '(';
67762 format = 'this.call("'+ format.substr(5) + '", ';
67766 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
67770 // called with xxyx.yuu:(test,test)
67772 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
67774 // raw.. - :raw modifier..
67775 return "'"+ sep + udef_st + name + ")"+sep+"'";
67779 // branched to use + in gecko and [].join() in others
67781 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
67782 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
67785 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
67786 body.push(tpl.body.replace(/(\r\n|\n)/g,
67787 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
67788 body.push("'].join('');};};");
67789 body = body.join('');
67792 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
67794 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
67800 applyTemplate : function(values){
67801 return this.master.compiled.call(this, values, {});
67802 //var s = this.subs;
67805 apply : function(){
67806 return this.applyTemplate.apply(this, arguments);
67811 Roo.XTemplate.from = function(el){
67812 el = Roo.getDom(el);
67813 return new Roo.XTemplate(el.value || el.innerHTML);