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">
14 * @class Roo.data.SortTypes
16 * Defines the default sorting (casting?) comparison functions used when sorting data.
18 Roo.data.SortTypes = {
20 * Default sort that does nothing
21 * @param {Mixed} s The value being converted
22 * @return {Mixed} The comparison value
29 * The regular expression used to strip tags
33 stripTagsRE : /<\/?[^>]+>/gi,
36 * Strips all HTML tags to sort on text only
37 * @param {Mixed} s The value being converted
38 * @return {String} The comparison value
41 return String(s).replace(this.stripTagsRE, "");
45 * Strips all HTML tags to sort on text only - Case insensitive
46 * @param {Mixed} s The value being converted
47 * @return {String} The comparison value
49 asUCText : function(s){
50 return String(s).toUpperCase().replace(this.stripTagsRE, "");
54 * Case insensitive string
55 * @param {Mixed} s The value being converted
56 * @return {String} The comparison value
58 asUCString : function(s) {
59 return String(s).toUpperCase();
64 * @param {Mixed} s The value being converted
65 * @return {Number} The comparison value
67 asDate : function(s) {
71 if(s instanceof Date){
74 return Date.parse(String(s));
79 * @param {Mixed} s The value being converted
80 * @return {Float} The comparison value
82 asFloat : function(s) {
83 var val = parseFloat(String(s).replace(/,/g, ""));
92 * @param {Mixed} s The value being converted
93 * @return {Number} The comparison value
96 var val = parseInt(String(s).replace(/,/g, ""));
104 * Ext JS Library 1.1.1
105 * Copyright(c) 2006-2007, Ext JS, LLC.
107 * Originally Released Under LGPL - original licence link has changed is not relivant.
110 * <script type="text/javascript">
114 * @class Roo.data.Record
115 * Instances of this class encapsulate both record <em>definition</em> information, and record
116 * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
117 * to access Records cached in an {@link Roo.data.Store} object.<br>
119 * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
120 * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
123 * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
125 * This constructor should not be used to create Record objects. Instead, use the constructor generated by
126 * {@link #create}. The parameters are the same.
127 * @param {Array} data An associative Array of data values keyed by the field name.
128 * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
129 * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
130 * not specified an integer id is generated.
132 Roo.data.Record = function(data, id){
133 this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
138 * Generate a constructor for a specific record layout.
139 * @param {Array} o An Array of field definition objects which specify field names, and optionally,
140 * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
141 * Each field definition object may contain the following properties: <ul>
142 * <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,
143 * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
144 * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
145 * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
146 * is being used, then this is a string containing the javascript expression to reference the data relative to
147 * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
148 * to the data item relative to the record element. If the mapping expression is the same as the field name,
149 * this may be omitted.</p></li>
150 * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
151 * <ul><li>auto (Default, implies no conversion)</li>
156 * <li>date</li></ul></p></li>
157 * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
158 * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
159 * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
160 * by the Reader into an object that will be stored in the Record. It is passed the
161 * following parameters:<ul>
162 * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
164 * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
166 * <br>usage:<br><pre><code>
167 var TopicRecord = Roo.data.Record.create(
168 {name: 'title', mapping: 'topic_title'},
169 {name: 'author', mapping: 'username'},
170 {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
171 {name: 'lastPost', mapping: 'post_time', type: 'date'},
172 {name: 'lastPoster', mapping: 'user2'},
173 {name: 'excerpt', mapping: 'post_text'}
176 var myNewRecord = new TopicRecord({
177 title: 'Do my job please',
180 lastPost: new Date(),
181 lastPoster: 'Animal',
182 excerpt: 'No way dude!'
184 myStore.add(myNewRecord);
189 Roo.data.Record.create = function(o){
191 f.superclass.constructor.apply(this, arguments);
193 Roo.extend(f, Roo.data.Record);
195 p.fields = new Roo.util.MixedCollection(false, function(field){
198 for(var i = 0, len = o.length; i < len; i++){
199 p.fields.add(new Roo.data.Field(o[i]));
201 f.getField = function(name){
202 return p.fields.get(name);
207 Roo.data.Record.AUTO_ID = 1000;
208 Roo.data.Record.EDIT = 'edit';
209 Roo.data.Record.REJECT = 'reject';
210 Roo.data.Record.COMMIT = 'commit';
212 Roo.data.Record.prototype = {
214 * Readonly flag - true if this record has been modified.
223 join : function(store){
228 * Set the named field to the specified value.
229 * @param {String} name The name of the field to set.
230 * @param {Object} value The value to set the field to.
232 set : function(name, value){
233 if(this.data[name] == value){
240 if(typeof this.modified[name] == 'undefined'){
241 this.modified[name] = this.data[name];
243 this.data[name] = value;
244 if(!this.editing && this.store){
245 this.store.afterEdit(this);
250 * Get the value of the named field.
251 * @param {String} name The name of the field to get the value of.
252 * @return {Object} The value of the field.
254 get : function(name){
255 return this.data[name];
259 beginEdit : function(){
265 cancelEdit : function(){
266 this.editing = false;
267 delete this.modified;
271 endEdit : function(){
272 this.editing = false;
273 if(this.dirty && this.store){
274 this.store.afterEdit(this);
279 * Usually called by the {@link Roo.data.Store} which owns the Record.
280 * Rejects all changes made to the Record since either creation, or the last commit operation.
281 * Modified fields are reverted to their original values.
283 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
284 * of reject operations.
287 var m = this.modified;
289 if(typeof m[n] != "function"){
294 delete this.modified;
295 this.editing = false;
297 this.store.afterReject(this);
302 * Usually called by the {@link Roo.data.Store} which owns the Record.
303 * Commits all changes made to the Record since either creation, or the last commit operation.
305 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
306 * of commit operations.
310 delete this.modified;
311 this.editing = false;
313 this.store.afterCommit(this);
318 hasError : function(){
319 return this.error != null;
323 clearError : function(){
328 * Creates a copy of this record.
329 * @param {String} id (optional) A new record id if you don't want to use this record's id
332 copy : function(newId) {
333 return new this.constructor(Roo.apply({}, this.data), newId || this.id);
337 * Ext JS Library 1.1.1
338 * Copyright(c) 2006-2007, Ext JS, LLC.
340 * Originally Released Under LGPL - original licence link has changed is not relivant.
343 * <script type="text/javascript">
349 * @class Roo.data.Store
350 * @extends Roo.util.Observable
351 * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
352 * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
354 * 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
355 * has no knowledge of the format of the data returned by the Proxy.<br>
357 * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
358 * instances from the data object. These records are cached and made available through accessor functions.
360 * Creates a new Store.
361 * @param {Object} config A config object containing the objects needed for the Store to access data,
362 * and read the data into Records.
364 Roo.data.Store = function(config){
365 this.data = new Roo.util.MixedCollection(false);
366 this.data.getKey = function(o){
369 this.baseParams = {};
376 "multisort" : "_multisort"
379 if(config && config.data){
380 this.inlineData = config.data;
384 Roo.apply(this, config);
386 if(this.reader){ // reader passed
387 this.reader = Roo.factory(this.reader, Roo.data);
388 this.reader.xmodule = this.xmodule || false;
389 if(!this.recordType){
390 this.recordType = this.reader.recordType;
392 if(this.reader.onMetaChange){
393 this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
398 this.fields = this.recordType.prototype.fields;
405 * Fires when the data cache has changed, and a widget which is using this Store
406 * as a Record cache should refresh its view.
407 * @param {Store} this
412 * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
413 * @param {Store} this
414 * @param {Object} meta The JSON metadata
419 * Fires when Records have been added to the Store
420 * @param {Store} this
421 * @param {Roo.data.Record[]} records The array of Records added
422 * @param {Number} index The index at which the record(s) were added
427 * Fires when a Record has been removed from the Store
428 * @param {Store} this
429 * @param {Roo.data.Record} record The Record that was removed
430 * @param {Number} index The index at which the record was removed
435 * Fires when a Record has been updated
436 * @param {Store} this
437 * @param {Roo.data.Record} record The Record that was updated
438 * @param {String} operation The update operation being performed. Value may be one of:
441 Roo.data.Record.REJECT
442 Roo.data.Record.COMMIT
448 * Fires when the data cache has been cleared.
449 * @param {Store} this
454 * Fires before a request is made for a new data object. If the beforeload handler returns false
455 * the load action will be canceled.
456 * @param {Store} this
457 * @param {Object} options The loading options that were specified (see {@link #load} for details)
461 * @event beforeloadadd
462 * Fires after a new set of Records has been loaded.
463 * @param {Store} this
464 * @param {Roo.data.Record[]} records The Records that were loaded
465 * @param {Object} options The loading options that were specified (see {@link #load} for details)
467 beforeloadadd : true,
470 * Fires after a new set of Records has been loaded, before they are added to the store.
471 * @param {Store} this
472 * @param {Roo.data.Record[]} records The Records that were loaded
473 * @param {Object} options The loading options that were specified (see {@link #load} for details)
474 * @params {Object} return from reader
478 * @event loadexception
479 * Fires if an exception occurs in the Proxy during loading.
480 * Called with the signature of the Proxy's "loadexception" event.
481 * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
484 * @param {Object} ret return data from JsonData.reader() - success, totalRecords, records
485 * @param {Object} opts - load Options
486 * @param {Object} jsonData from your request (normally this contains the Exception)
492 this.proxy = Roo.factory(this.proxy, Roo.data);
493 this.proxy.xmodule = this.xmodule || false;
494 this.relayEvents(this.proxy, ["loadexception"]);
496 this.sortToggle = {};
497 this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
499 Roo.data.Store.superclass.constructor.call(this);
502 this.loadData(this.inlineData);
503 delete this.inlineData;
507 Roo.extend(Roo.data.Store, Roo.util.Observable, {
509 * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
510 * without a remote query - used by combo/forms at present.
514 * @cfg {Roo.data.DataProxy} proxy [required] The Proxy object which provides access to a data object.
517 * @cfg {Array} data Inline data to be loaded when the store is initialized.
520 * @cfg {Roo.data.DataReader} reader [required] The Reader object which processes the data object and returns
521 * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
524 * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
525 * on any HTTP request
528 * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
531 * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
535 * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
536 * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
541 * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
542 * loaded or when a record is removed. (defaults to false).
544 pruneModifiedRecords : false,
550 * Add Records to the Store and fires the add event.
551 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
553 add : function(records){
554 records = [].concat(records);
555 for(var i = 0, len = records.length; i < len; i++){
556 records[i].join(this);
558 var index = this.data.length;
559 this.data.addAll(records);
560 this.fireEvent("add", this, records, index);
564 * Remove a Record from the Store and fires the remove event.
565 * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
567 remove : function(record){
568 var index = this.data.indexOf(record);
569 this.data.removeAt(index);
571 if(this.pruneModifiedRecords){
572 this.modified.remove(record);
574 this.fireEvent("remove", this, record, index);
578 * Remove all Records from the Store and fires the clear event.
580 removeAll : function(){
582 if(this.pruneModifiedRecords){
585 this.fireEvent("clear", this);
589 * Inserts Records to the Store at the given index and fires the add event.
590 * @param {Number} index The start index at which to insert the passed Records.
591 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
593 insert : function(index, records){
594 records = [].concat(records);
595 for(var i = 0, len = records.length; i < len; i++){
596 this.data.insert(index, records[i]);
597 records[i].join(this);
599 this.fireEvent("add", this, records, index);
603 * Get the index within the cache of the passed Record.
604 * @param {Roo.data.Record} record The Roo.data.Record object to to find.
605 * @return {Number} The index of the passed Record. Returns -1 if not found.
607 indexOf : function(record){
608 return this.data.indexOf(record);
612 * Get the index within the cache of the Record with the passed id.
613 * @param {String} id The id of the Record to find.
614 * @return {Number} The index of the Record. Returns -1 if not found.
616 indexOfId : function(id){
617 return this.data.indexOfKey(id);
621 * Get the Record with the specified id.
622 * @param {String} id The id of the Record to find.
623 * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
625 getById : function(id){
626 return this.data.key(id);
630 * Get the Record at the specified index.
631 * @param {Number} index The index of the Record to find.
632 * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
634 getAt : function(index){
635 return this.data.itemAt(index);
639 * Returns a range of Records between specified indices.
640 * @param {Number} startIndex (optional) The starting index (defaults to 0)
641 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
642 * @return {Roo.data.Record[]} An array of Records
644 getRange : function(start, end){
645 return this.data.getRange(start, end);
649 storeOptions : function(o){
650 o = Roo.apply({}, o);
653 this.lastOptions = o;
657 * Loads the Record cache from the configured Proxy using the configured Reader.
659 * If using remote paging, then the first load call must specify the <em>start</em>
660 * and <em>limit</em> properties in the options.params property to establish the initial
661 * position within the dataset, and the number of Records to cache on each read from the Proxy.
663 * <strong>It is important to note that for remote data sources, loading is asynchronous,
664 * and this call will return before the new data has been loaded. Perform any post-processing
665 * in a callback function, or in a "load" event handler.</strong>
667 * @param {Object} options An object containing properties which control loading options:<ul>
668 * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
669 * <li>params.data {Object} if you are using a MemoryProxy / JsonReader, use this as the data to load stuff..
672 data : data, // array of key=>value data like JsonReader
679 * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
680 * passed the following arguments:<ul>
681 * <li>r : Roo.data.Record[]</li>
682 * <li>options: Options object from the load call</li>
683 * <li>success: Boolean success indicator</li></ul></li>
684 * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
685 * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
688 load : function(options){
689 options = options || {};
690 if(this.fireEvent("beforeload", this, options) !== false){
691 this.storeOptions(options);
692 var p = Roo.apply(options.params || {}, this.baseParams);
693 // if meta was not loaded from remote source.. try requesting it.
694 if (!this.reader.metaFromRemote) {
697 if(this.sortInfo && this.remoteSort){
698 var pn = this.paramNames;
699 p[pn["sort"]] = this.sortInfo.field;
700 p[pn["dir"]] = this.sortInfo.direction;
702 if (this.multiSort) {
703 var pn = this.paramNames;
704 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
707 this.proxy.load(p, this.reader, this.loadRecords, this, options);
712 * Reloads the Record cache from the configured Proxy using the configured Reader and
713 * the options from the last load operation performed.
714 * @param {Object} options (optional) An object containing properties which may override the options
715 * used in the last load operation. See {@link #load} for details (defaults to null, in which case
716 * the most recently used options are reused).
718 reload : function(options){
719 this.load(Roo.applyIf(options||{}, this.lastOptions));
723 // Called as a callback by the Reader during a load operation.
724 loadRecords : function(o, options, success){
727 if(success !== false){
728 this.fireEvent("load", this, [], options, o);
730 if(options.callback){
731 options.callback.call(options.scope || this, [], options, false);
735 // if data returned failure - throw an exception.
736 if (o.success === false) {
737 // show a message if no listener is registered.
738 if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
739 Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
741 // loadmask wil be hooked into this..
742 this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
745 var r = o.records, t = o.totalRecords || r.length;
747 this.fireEvent("beforeloadadd", this, r, options, o);
749 if(!options || options.add !== true){
750 if(this.pruneModifiedRecords){
753 for(var i = 0, len = r.length; i < len; i++){
757 this.data = this.snapshot;
758 delete this.snapshot;
762 this.totalLength = t;
764 this.fireEvent("datachanged", this);
766 this.totalLength = Math.max(t, this.data.length+r.length);
770 if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
772 var e = new Roo.data.Record({});
774 e.set(this.parent.displayField, this.parent.emptyTitle);
775 e.set(this.parent.valueField, '');
780 this.fireEvent("load", this, r, options, o);
781 if(options.callback){
782 options.callback.call(options.scope || this, r, options, true);
788 * Loads data from a passed data block. A Reader which understands the format of the data
789 * must have been configured in the constructor.
790 * @param {Object} data The data block from which to read the Records. The format of the data expected
791 * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
792 * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
794 loadData : function(o, append){
795 var r = this.reader.readRecords(o);
796 this.loadRecords(r, {add: append}, true);
800 * using 'cn' the nested child reader read the child array into it's child stores.
801 * @param {Object} rec The record with a 'children array
803 loadDataFromChildren : function(rec)
805 this.loadData(this.reader.toLoadData(rec));
810 * Gets the number of cached records.
812 * <em>If using paging, this may not be the total size of the dataset. If the data object
813 * used by the Reader contains the dataset size, then the getTotalCount() function returns
814 * the data set size</em>
816 getCount : function(){
817 return this.data.length || 0;
821 * Gets the total number of records in the dataset as returned by the server.
823 * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
824 * the dataset size</em>
826 getTotalCount : function(){
827 return this.totalLength || 0;
831 * Returns the sort state of the Store as an object with two properties:
833 field {String} The name of the field by which the Records are sorted
834 direction {String} The sort order, "ASC" or "DESC"
837 getSortState : function(){
838 return this.sortInfo;
842 applySort : function(){
843 if(this.sortInfo && !this.remoteSort){
844 var s = this.sortInfo, f = s.field;
845 var st = this.fields.get(f).sortType;
846 var fn = function(r1, r2){
847 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
848 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
850 this.data.sort(s.direction, fn);
851 if(this.snapshot && this.snapshot != this.data){
852 this.snapshot.sort(s.direction, fn);
858 * Sets the default sort column and order to be used by the next load operation.
859 * @param {String} fieldName The name of the field to sort by.
860 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
862 setDefaultSort : function(field, dir){
863 this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
868 * If remote sorting is used, the sort is performed on the server, and the cache is
869 * reloaded. If local sorting is used, the cache is sorted internally.
870 * @param {String} fieldName The name of the field to sort by.
871 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
873 sort : function(fieldName, dir){
874 var f = this.fields.get(fieldName);
876 this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
878 if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
879 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
884 this.sortToggle[f.name] = dir;
885 this.sortInfo = {field: f.name, direction: dir};
886 if(!this.remoteSort){
888 this.fireEvent("datachanged", this);
890 this.load(this.lastOptions);
895 * Calls the specified function for each of the Records in the cache.
896 * @param {Function} fn The function to call. The Record is passed as the first parameter.
897 * Returning <em>false</em> aborts and exits the iteration.
898 * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
900 each : function(fn, scope){
901 this.data.each(fn, scope);
905 * Gets all records modified since the last commit. Modified records are persisted across load operations
906 * (e.g., during paging).
907 * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
909 getModifiedRecords : function(){
910 return this.modified;
914 createFilterFn : function(property, value, anyMatch){
915 if(!value.exec){ // not a regex
916 value = String(value);
917 if(value.length == 0){
920 value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
923 return value.test(r.data[property]);
928 * Sums the value of <i>property</i> for each record between start and end and returns the result.
929 * @param {String} property A field on your records
930 * @param {Number} start The record index to start at (defaults to 0)
931 * @param {Number} end The last record index to include (defaults to length - 1)
932 * @return {Number} The sum
934 sum : function(property, start, end){
935 var rs = this.data.items, v = 0;
937 end = (end || end === 0) ? end : rs.length-1;
939 for(var i = start; i <= end; i++){
940 v += (rs[i].data[property] || 0);
946 * Filter the records by a specified property.
947 * @param {String} field A field on your records
948 * @param {String/RegExp} value Either a string that the field
949 * should start with or a RegExp to test against the field
950 * @param {Boolean} anyMatch True to match any part not just the beginning
952 filter : function(property, value, anyMatch){
953 var fn = this.createFilterFn(property, value, anyMatch);
954 return fn ? this.filterBy(fn) : this.clearFilter();
958 * Filter by a function. The specified function will be called with each
959 * record in this data source. If the function returns true the record is included,
960 * otherwise it is filtered.
961 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
962 * @param {Object} scope (optional) The scope of the function (defaults to this)
964 filterBy : function(fn, scope){
965 this.snapshot = this.snapshot || this.data;
966 this.data = this.queryBy(fn, scope||this);
967 this.fireEvent("datachanged", this);
971 * Query the records by a specified property.
972 * @param {String} field A field on your records
973 * @param {String/RegExp} value Either a string that the field
974 * should start with or a RegExp to test against the field
975 * @param {Boolean} anyMatch True to match any part not just the beginning
976 * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
978 query : function(property, value, anyMatch){
979 var fn = this.createFilterFn(property, value, anyMatch);
980 return fn ? this.queryBy(fn) : this.data.clone();
984 * Query by a function. The specified function will be called with each
985 * record in this data source. If the function returns true the record is included
987 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
988 * @param {Object} scope (optional) The scope of the function (defaults to this)
989 @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
991 queryBy : function(fn, scope){
992 var data = this.snapshot || this.data;
993 return data.filterBy(fn, scope||this);
997 * Collects unique values for a particular dataIndex from this store.
998 * @param {String} dataIndex The property to collect
999 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
1000 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
1001 * @return {Array} An array of the unique values
1003 collect : function(dataIndex, allowNull, bypassFilter){
1004 var d = (bypassFilter === true && this.snapshot) ?
1005 this.snapshot.items : this.data.items;
1006 var v, sv, r = [], l = {};
1007 for(var i = 0, len = d.length; i < len; i++){
1008 v = d[i].data[dataIndex];
1010 if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
1019 * Revert to a view of the Record cache with no filtering applied.
1020 * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
1022 clearFilter : function(suppressEvent){
1023 if(this.snapshot && this.snapshot != this.data){
1024 this.data = this.snapshot;
1025 delete this.snapshot;
1026 if(suppressEvent !== true){
1027 this.fireEvent("datachanged", this);
1033 afterEdit : function(record){
1034 if(this.modified.indexOf(record) == -1){
1035 this.modified.push(record);
1037 this.fireEvent("update", this, record, Roo.data.Record.EDIT);
1041 afterReject : function(record){
1042 this.modified.remove(record);
1043 this.fireEvent("update", this, record, Roo.data.Record.REJECT);
1047 afterCommit : function(record){
1048 this.modified.remove(record);
1049 this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
1053 * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
1054 * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
1056 commitChanges : function(){
1057 var m = this.modified.slice(0);
1059 for(var i = 0, len = m.length; i < len; i++){
1065 * Cancel outstanding changes on all changed records.
1067 rejectChanges : function(){
1068 var m = this.modified.slice(0);
1070 for(var i = 0, len = m.length; i < len; i++){
1075 onMetaChange : function(meta, rtype, o){
1076 this.recordType = rtype;
1077 this.fields = rtype.prototype.fields;
1078 delete this.snapshot;
1079 this.sortInfo = meta.sortInfo || this.sortInfo;
1081 this.fireEvent('metachange', this, this.reader.meta);
1084 moveIndex : function(data, type)
1086 var index = this.indexOf(data);
1088 var newIndex = index + type;
1092 this.insert(newIndex, data);
1097 * Ext JS Library 1.1.1
1098 * Copyright(c) 2006-2007, Ext JS, LLC.
1100 * Originally Released Under LGPL - original licence link has changed is not relivant.
1103 * <script type="text/javascript">
1107 * @class Roo.data.SimpleStore
1108 * @extends Roo.data.Store
1109 * Small helper class to make creating Stores from Array data easier.
1110 * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
1111 * @cfg {Array} fields An array of field definition objects, or field name strings.
1112 * @cfg {Object} an existing reader (eg. copied from another store)
1113 * @cfg {Array} data The multi-dimensional array of data
1114 * @cfg {Roo.data.DataProxy} proxy [not-required]
1115 * @cfg {Roo.data.Reader} reader [not-required]
1117 * @param {Object} config
1119 Roo.data.SimpleStore = function(config)
1121 Roo.data.SimpleStore.superclass.constructor.call(this, {
1123 reader: typeof(config.reader) != 'undefined' ? config.reader : new Roo.data.ArrayReader({
1126 Roo.data.Record.create(config.fields)
1128 proxy : new Roo.data.MemoryProxy(config.data)
1132 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
1134 * Ext JS Library 1.1.1
1135 * Copyright(c) 2006-2007, Ext JS, LLC.
1137 * Originally Released Under LGPL - original licence link has changed is not relivant.
1140 * <script type="text/javascript">
1145 * @extends Roo.data.Store
1146 * @class Roo.data.JsonStore
1147 * Small helper class to make creating Stores for JSON data easier. <br/>
1149 var store = new Roo.data.JsonStore({
1150 url: 'get-images.php',
1152 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
1155 * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
1156 * JsonReader and HttpProxy (unless inline data is provided).</b>
1157 * @cfg {Array} fields An array of field definition objects, or field name strings.
1159 * @param {Object} config
1161 Roo.data.JsonStore = function(c){
1162 Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
1163 proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
1164 reader: new Roo.data.JsonReader(c, c.fields)
1167 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
1169 * Ext JS Library 1.1.1
1170 * Copyright(c) 2006-2007, Ext JS, LLC.
1172 * Originally Released Under LGPL - original licence link has changed is not relivant.
1175 * <script type="text/javascript">
1179 Roo.data.Field = function(config){
1180 if(typeof config == "string"){
1181 config = {name: config};
1183 Roo.apply(this, config);
1189 var st = Roo.data.SortTypes;
1190 // named sortTypes are supported, here we look them up
1191 if(typeof this.sortType == "string"){
1192 this.sortType = st[this.sortType];
1195 // set default sortType for strings and dates
1199 this.sortType = st.asUCString;
1202 this.sortType = st.asDate;
1205 this.sortType = st.none;
1210 var stripRe = /[\$,%]/g;
1212 // prebuilt conversion function for this field, instead of
1213 // switching every time we're reading a value
1215 var cv, dateFormat = this.dateFormat;
1220 cv = function(v){ return v; };
1223 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
1227 return v !== undefined && v !== null && v !== '' ?
1228 parseInt(String(v).replace(stripRe, ""), 10) : '';
1233 return v !== undefined && v !== null && v !== '' ?
1234 parseFloat(String(v).replace(stripRe, ""), 10) : '';
1239 cv = function(v){ return v === true || v === "true" || v == 1; };
1246 if(v instanceof Date){
1250 if(dateFormat == "timestamp"){
1251 return new Date(v*1000);
1253 return Date.parseDate(v, dateFormat);
1255 var parsed = Date.parse(v);
1256 return parsed ? new Date(parsed) : null;
1265 Roo.data.Field.prototype = {
1273 * Ext JS Library 1.1.1
1274 * Copyright(c) 2006-2007, Ext JS, LLC.
1276 * Originally Released Under LGPL - original licence link has changed is not relivant.
1279 * <script type="text/javascript">
1282 // Base class for reading structured data from a data source. This class is intended to be
1283 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
1286 * @class Roo.data.DataReader
1288 * Base class for reading structured data from a data source. This class is intended to be
1289 * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
1292 Roo.data.DataReader = function(meta, recordType){
1296 this.recordType = recordType instanceof Array ?
1297 Roo.data.Record.create(recordType) : recordType;
1300 Roo.data.DataReader.prototype = {
1303 readerType : 'Data',
1305 * Create an empty record
1306 * @param {Object} data (optional) - overlay some values
1307 * @return {Roo.data.Record} record created.
1309 newRow : function(d) {
1311 this.recordType.prototype.fields.each(function(c) {
1313 case 'int' : da[c.name] = 0; break;
1314 case 'date' : da[c.name] = new Date(); break;
1315 case 'float' : da[c.name] = 0.0; break;
1316 case 'boolean' : da[c.name] = false; break;
1317 default : da[c.name] = ""; break;
1321 return new this.recordType(Roo.apply(da, d));
1327 * Ext JS Library 1.1.1
1328 * Copyright(c) 2006-2007, Ext JS, LLC.
1330 * Originally Released Under LGPL - original licence link has changed is not relivant.
1333 * <script type="text/javascript">
1337 * @class Roo.data.DataProxy
1338 * @extends Roo.util.Observable
1340 * This class is an abstract base class for implementations which provide retrieval of
1341 * unformatted data objects.<br>
1343 * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
1344 * (of the appropriate type which knows how to parse the data object) to provide a block of
1345 * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
1347 * Custom implementations must implement the load method as described in
1348 * {@link Roo.data.HttpProxy#load}.
1350 Roo.data.DataProxy = function(){
1354 * Fires before a network request is made to retrieve a data object.
1355 * @param {Object} This DataProxy object.
1356 * @param {Object} params The params parameter to the load function.
1361 * Fires before the load method's callback is called.
1362 * @param {Object} This DataProxy object.
1363 * @param {Object} o The data object.
1364 * @param {Object} arg The callback argument object passed to the load function.
1368 * @event loadexception
1369 * Fires if an Exception occurs during data retrieval.
1370 * @param {Object} This DataProxy object.
1371 * @param {Object} o The data object.
1372 * @param {Object} arg The callback argument object passed to the load function.
1373 * @param {Object} e The Exception.
1375 loadexception : true
1377 Roo.data.DataProxy.superclass.constructor.call(this);
1380 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
1383 * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
1387 * Ext JS Library 1.1.1
1388 * Copyright(c) 2006-2007, Ext JS, LLC.
1390 * Originally Released Under LGPL - original licence link has changed is not relivant.
1393 * <script type="text/javascript">
1396 * @class Roo.data.MemoryProxy
1397 * @extends Roo.data.DataProxy
1398 * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
1399 * to the Reader when its load method is called.
1401 * @param {Object} config A config object containing the objects needed for the Store to access data,
1403 Roo.data.MemoryProxy = function(config){
1405 if (typeof(config) != 'undefined' && typeof(config.data) != 'undefined') {
1408 Roo.data.MemoryProxy.superclass.constructor.call(this);
1412 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
1415 * @cfg {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
1418 * Load data from the requested source (in this case an in-memory
1419 * data object passed to the constructor), read the data object into
1420 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
1421 * process that block using the passed callback.
1422 * @param {Object} params This parameter is not used by the MemoryProxy class.
1423 * @param {Roo.data.DataReader} reader The Reader object which converts the data
1424 * object into a block of Roo.data.Records.
1425 * @param {Function} callback The function into which to pass the block of Roo.data.records.
1426 * The function must be passed <ul>
1427 * <li>The Record block object</li>
1428 * <li>The "arg" argument from the load function</li>
1429 * <li>A boolean success indicator</li>
1431 * @param {Object} scope The scope in which to call the callback
1432 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1434 load : function(params, reader, callback, scope, arg){
1435 params = params || {};
1438 result = reader.readRecords(params.data ? params.data :this.data);
1440 this.fireEvent("loadexception", this, arg, null, e);
1441 callback.call(scope, null, arg, false);
1444 callback.call(scope, result, arg, true);
1448 update : function(params, records){
1453 * Ext JS Library 1.1.1
1454 * Copyright(c) 2006-2007, Ext JS, LLC.
1456 * Originally Released Under LGPL - original licence link has changed is not relivant.
1459 * <script type="text/javascript">
1462 * @class Roo.data.HttpProxy
1463 * @extends Roo.data.DataProxy
1464 * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
1465 * configured to reference a certain URL.<br><br>
1467 * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
1468 * from which the running page was served.<br><br>
1470 * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
1472 * Be aware that to enable the browser to parse an XML document, the server must set
1473 * the Content-Type header in the HTTP response to "text/xml".
1475 * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
1476 * an {@link Roo.data.Connection} object. If a Connection config is passed, the singleton {@link Roo.Ajax} object
1477 * will be used to make the request.
1479 Roo.data.HttpProxy = function(conn){
1480 Roo.data.HttpProxy.superclass.constructor.call(this);
1481 // is conn a conn config or a real conn?
1483 this.useAjax = !conn || !conn.events;
1487 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
1488 // thse are take from connection...
1491 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
1494 * @cfg {Object} extraParams An object containing properties which are used as
1495 * extra parameters to each request made by this object. (defaults to undefined)
1498 * @cfg {Object} defaultHeaders An object containing request headers which are added
1499 * to each request made by this object. (defaults to undefined)
1502 * @cfg {String} method (GET|POST) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
1505 * @cfg {Number} timeout The timeout in milliseconds to be used for requests. (defaults to 30000)
1508 * @cfg {Boolean} autoAbort Whether this request should abort any pending requests. (defaults to false)
1514 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
1518 * Return the {@link Roo.data.Connection} object being used by this Proxy.
1519 * @return {Connection} The Connection object. This object may be used to subscribe to events on
1520 * a finer-grained basis than the DataProxy events.
1522 getConnection : function(){
1523 return this.useAjax ? Roo.Ajax : this.conn;
1527 * Load data from the configured {@link Roo.data.Connection}, read the data object into
1528 * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
1529 * process that block using the passed callback.
1530 * @param {Object} params An object containing properties which are to be used as HTTP parameters
1531 * for the request to the remote server.
1532 * @param {Roo.data.DataReader} reader The Reader object which converts the data
1533 * object into a block of Roo.data.Records.
1534 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
1535 * The function must be passed <ul>
1536 * <li>The Record block object</li>
1537 * <li>The "arg" argument from the load function</li>
1538 * <li>A boolean success indicator</li>
1540 * @param {Object} scope The scope in which to call the callback
1541 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1543 load : function(params, reader, callback, scope, arg){
1544 if(this.fireEvent("beforeload", this, params) !== false){
1546 params : params || {},
1548 callback : callback,
1553 callback : this.loadResponse,
1557 Roo.applyIf(o, this.conn);
1558 if(this.activeRequest){
1559 Roo.Ajax.abort(this.activeRequest);
1561 this.activeRequest = Roo.Ajax.request(o);
1563 this.conn.request(o);
1566 callback.call(scope||this, null, arg, false);
1571 loadResponse : function(o, success, response){
1572 delete this.activeRequest;
1574 this.fireEvent("loadexception", this, o, response);
1575 o.request.callback.call(o.request.scope, null, o.request.arg, false);
1580 result = o.reader.read(response);
1583 o.raw = { errorMsg : response.responseText };
1584 this.fireEvent("loadexception", this, o, response, e);
1585 o.request.callback.call(o.request.scope, o, o.request.arg, false);
1589 this.fireEvent("load", this, o, o.request.arg);
1590 o.request.callback.call(o.request.scope, result, o.request.arg, true);
1594 update : function(dataSet){
1599 updateResponse : function(dataSet){
1604 * Ext JS Library 1.1.1
1605 * Copyright(c) 2006-2007, Ext JS, LLC.
1607 * Originally Released Under LGPL - original licence link has changed is not relivant.
1610 * <script type="text/javascript">
1614 * @class Roo.data.ScriptTagProxy
1615 * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
1616 * other than the originating domain of the running page.<br><br>
1618 * <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
1619 * of the running page, you must use this class, rather than DataProxy.</em><br><br>
1621 * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
1622 * source code that is used as the source inside a <script> tag.<br><br>
1624 * In order for the browser to process the returned data, the server must wrap the data object
1625 * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
1626 * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
1627 * depending on whether the callback name was passed:
1630 boolean scriptTag = false;
1631 String cb = request.getParameter("callback");
1634 response.setContentType("text/javascript");
1636 response.setContentType("application/x-json");
1638 Writer out = response.getWriter();
1640 out.write(cb + "(");
1642 out.print(dataBlock.toJsonString());
1649 * @param {Object} config A configuration object.
1651 Roo.data.ScriptTagProxy = function(config){
1652 Roo.data.ScriptTagProxy.superclass.constructor.call(this);
1653 Roo.apply(this, config);
1654 this.head = document.getElementsByTagName("head")[0];
1657 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
1659 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
1661 * @cfg {String} url The URL from which to request the data object.
1664 * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
1668 * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
1669 * the server the name of the callback function set up by the load call to process the returned data object.
1670 * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
1671 * javascript output which calls this named function passing the data object as its only parameter.
1673 callbackParam : "callback",
1675 * @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
1676 * name to the request.
1681 * Load data from the configured URL, read the data object into
1682 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
1683 * process that block using the passed callback.
1684 * @param {Object} params An object containing properties which are to be used as HTTP parameters
1685 * for the request to the remote server.
1686 * @param {Roo.data.DataReader} reader The Reader object which converts the data
1687 * object into a block of Roo.data.Records.
1688 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
1689 * The function must be passed <ul>
1690 * <li>The Record block object</li>
1691 * <li>The "arg" argument from the load function</li>
1692 * <li>A boolean success indicator</li>
1694 * @param {Object} scope The scope in which to call the callback
1695 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1697 load : function(params, reader, callback, scope, arg){
1698 if(this.fireEvent("beforeload", this, params) !== false){
1700 var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
1703 url += (url.indexOf("?") != -1 ? "&" : "?") + p;
1705 url += "&_dc=" + (new Date().getTime());
1707 var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
1710 cb : "stcCallback"+transId,
1711 scriptId : "stcScript"+transId,
1715 callback : callback,
1721 window[trans.cb] = function(o){
1722 conn.handleResponse(o, trans);
1725 url += String.format("&{0}={1}", this.callbackParam, trans.cb);
1727 if(this.autoAbort !== false){
1731 trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
1733 var script = document.createElement("script");
1734 script.setAttribute("src", url);
1735 script.setAttribute("type", "text/javascript");
1736 script.setAttribute("id", trans.scriptId);
1737 this.head.appendChild(script);
1741 callback.call(scope||this, null, arg, false);
1746 isLoading : function(){
1747 return this.trans ? true : false;
1751 * Abort the current server request.
1754 if(this.isLoading()){
1755 this.destroyTrans(this.trans);
1760 destroyTrans : function(trans, isLoaded){
1761 this.head.removeChild(document.getElementById(trans.scriptId));
1762 clearTimeout(trans.timeoutId);
1764 window[trans.cb] = undefined;
1766 delete window[trans.cb];
1769 // if hasn't been loaded, wait for load to remove it to prevent script error
1770 window[trans.cb] = function(){
1771 window[trans.cb] = undefined;
1773 delete window[trans.cb];
1780 handleResponse : function(o, trans){
1782 this.destroyTrans(trans, true);
1785 result = trans.reader.readRecords(o);
1787 this.fireEvent("loadexception", this, o, trans.arg, e);
1788 trans.callback.call(trans.scope||window, null, trans.arg, false);
1791 this.fireEvent("load", this, o, trans.arg);
1792 trans.callback.call(trans.scope||window, result, trans.arg, true);
1796 handleFailure : function(trans){
1798 this.destroyTrans(trans, false);
1799 this.fireEvent("loadexception", this, null, trans.arg);
1800 trans.callback.call(trans.scope||window, null, trans.arg, false);
1804 * Ext JS Library 1.1.1
1805 * Copyright(c) 2006-2007, Ext JS, LLC.
1807 * Originally Released Under LGPL - original licence link has changed is not relivant.
1810 * <script type="text/javascript">
1814 * @class Roo.data.JsonReader
1815 * @extends Roo.data.DataReader
1816 * Data reader class to create an Array of Roo.data.Record objects from a JSON response
1817 * based on mappings in a provided Roo.data.Record constructor.
1819 * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
1820 * in the reply previously.
1825 var RecordDef = Roo.data.Record.create([
1826 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
1827 {name: 'occupation'} // This field will use "occupation" as the mapping.
1829 var myReader = new Roo.data.JsonReader({
1830 totalProperty: "results", // The property which contains the total dataset size (optional)
1831 root: "rows", // The property which contains an Array of row objects
1832 id: "id" // The property within each row object that provides an ID for the record (optional)
1836 * This would consume a JSON file like this:
1838 { 'results': 2, 'rows': [
1839 { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
1840 { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
1843 * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
1844 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
1845 * paged from the remote server.
1846 * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
1847 * @cfg {String} root name of the property which contains the Array of row objects.
1848 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
1849 * @cfg {Array} fields Array of field definition objects
1851 * Create a new JsonReader
1852 * @param {Object} meta Metadata configuration options
1853 * @param {Object} recordType Either an Array of field definition objects,
1854 * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
1856 Roo.data.JsonReader = function(meta, recordType){
1859 // set some defaults:
1861 totalProperty: 'total',
1862 successProperty : 'success',
1867 Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
1869 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
1871 readerType : 'Json',
1874 * @prop {Boolean} metaFromRemote - if the meta data was loaded from the remote source.
1875 * Used by Store query builder to append _requestMeta to params.
1878 metaFromRemote : false,
1880 * This method is only used by a DataProxy which has retrieved data from a remote server.
1881 * @param {Object} response The XHR object which contains the JSON data in its responseText.
1882 * @return {Object} data A data block which is used by an Roo.data.Store object as
1883 * a cache of Roo.data.Records.
1885 read : function(response){
1886 var json = response.responseText;
1888 var o = /* eval:var:o */ eval("("+json+")");
1890 throw {message: "JsonReader.read: Json object not found"};
1896 this.metaFromRemote = true;
1897 this.meta = o.metaData;
1898 this.recordType = Roo.data.Record.create(o.metaData.fields);
1899 this.onMetaChange(this.meta, this.recordType, o);
1901 return this.readRecords(o);
1904 // private function a store will implement
1905 onMetaChange : function(meta, recordType, o){
1912 simpleAccess: function(obj, subsc) {
1919 getJsonAccessor: function(){
1921 return function(expr) {
1923 return(re.test(expr))
1924 ? new Function("obj", "return obj." + expr)
1934 * Create a data block containing Roo.data.Records from an XML document.
1935 * @param {Object} o An object which contains an Array of row objects in the property specified
1936 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
1937 * which contains the total size of the dataset.
1938 * @return {Object} data A data block which is used by an Roo.data.Store object as
1939 * a cache of Roo.data.Records.
1941 readRecords : function(o){
1943 * After any data loads, the raw JSON data is available for further custom processing.
1947 var s = this.meta, Record = this.recordType,
1948 f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
1950 // Generate extraction functions for the totalProperty, the root, the id, and for each field
1952 if(s.totalProperty) {
1953 this.getTotal = this.getJsonAccessor(s.totalProperty);
1955 if(s.successProperty) {
1956 this.getSuccess = this.getJsonAccessor(s.successProperty);
1958 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
1960 var g = this.getJsonAccessor(s.id);
1961 this.getId = function(rec) {
1963 return (r === undefined || r === "") ? null : r;
1966 this.getId = function(){return null;};
1969 for(var jj = 0; jj < fl; jj++){
1971 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
1972 this.ef[jj] = this.getJsonAccessor(map);
1976 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
1977 if(s.totalProperty){
1978 var vt = parseInt(this.getTotal(o), 10);
1983 if(s.successProperty){
1984 var vs = this.getSuccess(o);
1985 if(vs === false || vs === 'false'){
1990 for(var i = 0; i < c; i++){
1993 var id = this.getId(n);
1994 for(var j = 0; j < fl; j++){
1996 var v = this.ef[j](n);
1998 Roo.log('missing convert for ' + f.name);
2002 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
2006 raw : { errorMsg : "JSON Reader Error: fields or metadata not available to create Record" },
2012 var record = new Record(values, id);
2014 records[i] = record;
2020 totalRecords : totalRecords
2023 // used when loading children.. @see loadDataFromChildren
2024 toLoadData: function(rec)
2026 // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
2027 var data = typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
2028 return { data : data, total : data.length };
2033 * Ext JS Library 1.1.1
2034 * Copyright(c) 2006-2007, Ext JS, LLC.
2036 * Originally Released Under LGPL - original licence link has changed is not relivant.
2039 * <script type="text/javascript">
2043 * @class Roo.data.XmlReader
2044 * @extends Roo.data.DataReader
2045 * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
2046 * based on mappings in a provided Roo.data.Record constructor.<br><br>
2048 * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
2049 * header in the HTTP response must be set to "text/xml".</em>
2053 var RecordDef = Roo.data.Record.create([
2054 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
2055 {name: 'occupation'} // This field will use "occupation" as the mapping.
2057 var myReader = new Roo.data.XmlReader({
2058 totalRecords: "results", // The element which contains the total dataset size (optional)
2059 record: "row", // The repeated element which contains row information
2060 id: "id" // The element within the row that provides an ID for the record (optional)
2064 * This would consume an XML file like this:
2068 <results>2</results>
2071 <name>Bill</name>
2072 <occupation>Gardener</occupation>
2076 <name>Ben</name>
2077 <occupation>Horticulturalist</occupation>
2081 * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
2082 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
2083 * paged from the remote server.
2084 * @cfg {String} record The DomQuery path to the repeated element which contains record information.
2085 * @cfg {String} success The DomQuery path to the success attribute used by forms.
2086 * @cfg {String} id The DomQuery path relative from the record element to the element that contains
2087 * a record identifier value.
2089 * Create a new XmlReader
2090 * @param {Object} meta Metadata configuration options
2091 * @param {Mixed} recordType The definition of the data record type to produce. This can be either a valid
2092 * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
2093 * Roo.data.Record.create. See the {@link Roo.data.Record} class for more details.
2095 Roo.data.XmlReader = function(meta, recordType){
2097 Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
2099 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
2104 * This method is only used by a DataProxy which has retrieved data from a remote server.
2105 * @param {Object} response The XHR object which contains the parsed XML document. The response is expected
2106 * to contain a method called 'responseXML' that returns an XML document object.
2107 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
2108 * a cache of Roo.data.Records.
2110 read : function(response){
2111 var doc = response.responseXML;
2113 throw {message: "XmlReader.read: XML Document not available"};
2115 return this.readRecords(doc);
2119 * Create a data block containing Roo.data.Records from an XML document.
2120 * @param {Object} doc A parsed XML document.
2121 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
2122 * a cache of Roo.data.Records.
2124 readRecords : function(doc){
2126 * After any data loads/reads, the raw XML Document is available for further custom processing.
2130 var root = doc.documentElement || doc;
2131 var q = Roo.DomQuery;
2132 var recordType = this.recordType, fields = recordType.prototype.fields;
2133 var sid = this.meta.id;
2134 var totalRecords = 0, success = true;
2135 if(this.meta.totalRecords){
2136 totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
2139 if(this.meta.success){
2140 var sv = q.selectValue(this.meta.success, root, true);
2141 success = sv !== false && sv !== 'false';
2144 var ns = q.select(this.meta.record, root);
2145 for(var i = 0, len = ns.length; i < len; i++) {
2148 var id = sid ? q.selectValue(sid, n) : undefined;
2149 for(var j = 0, jlen = fields.length; j < jlen; j++){
2150 var f = fields.items[j];
2151 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
2155 var record = new recordType(values, id);
2157 records[records.length] = record;
2163 totalRecords : totalRecords || records.length
2168 * Ext JS Library 1.1.1
2169 * Copyright(c) 2006-2007, Ext JS, LLC.
2171 * Originally Released Under LGPL - original licence link has changed is not relivant.
2174 * <script type="text/javascript">
2178 * @class Roo.data.ArrayReader
2179 * @extends Roo.data.DataReader
2180 * Data reader class to create an Array of Roo.data.Record objects from an Array.
2181 * Each element of that Array represents a row of data fields. The
2182 * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
2183 * of the field definition if it exists, or the field's ordinal position in the definition.<br>
2187 var RecordDef = Roo.data.Record.create([
2188 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
2189 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
2191 var myReader = new Roo.data.ArrayReader({
2192 id: 0 // The subscript within row Array that provides an ID for the Record (optional)
2196 * This would consume an Array like this:
2198 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
2202 * Create a new JsonReader
2203 * @param {Object} meta Metadata configuration options.
2204 * @param {Object|Array} recordType Either an Array of field definition objects
2206 * @cfg {Array} fields Array of field definition objects
2207 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
2208 * as specified to {@link Roo.data.Record#create},
2209 * or an {@link Roo.data.Record} object
2212 * created using {@link Roo.data.Record#create}.
2214 Roo.data.ArrayReader = function(meta, recordType)
2216 Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
2219 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
2222 * Create a data block containing Roo.data.Records from an XML document.
2223 * @param {Object} o An Array of row objects which represents the dataset.
2224 * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
2225 * a cache of Roo.data.Records.
2227 readRecords : function(o)
2229 var sid = this.meta ? this.meta.id : null;
2230 var recordType = this.recordType, fields = recordType.prototype.fields;
2233 for(var i = 0; i < root.length; i++){
2236 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
2237 for(var j = 0, jlen = fields.length; j < jlen; j++){
2238 var f = fields.items[j];
2239 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
2240 var v = n[k] !== undefined ? n[k] : f.defaultValue;
2244 var record = new recordType(values, id);
2246 records[records.length] = record;
2250 totalRecords : records.length
2253 // used when loading children.. @see loadDataFromChildren
2254 toLoadData: function(rec)
2256 // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
2257 return typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
2264 * Ext JS Library 1.1.1
2265 * Copyright(c) 2006-2007, Ext JS, LLC.
2267 * Originally Released Under LGPL - original licence link has changed is not relivant.
2270 * <script type="text/javascript">
2275 * @class Roo.data.Tree
2276 * @extends Roo.util.Observable
2277 * Represents a tree data structure and bubbles all the events for its nodes. The nodes
2278 * in the tree have most standard DOM functionality.
2280 * @param {Node} root (optional) The root node
2282 Roo.data.Tree = function(root){
2285 * The root node for this tree
2290 this.setRootNode(root);
2295 * Fires when a new child node is appended to a node in this tree.
2296 * @param {Tree} tree The owner tree
2297 * @param {Node} parent The parent node
2298 * @param {Node} node The newly appended node
2299 * @param {Number} index The index of the newly appended node
2304 * Fires when a child node is removed from a node in this tree.
2305 * @param {Tree} tree The owner tree
2306 * @param {Node} parent The parent node
2307 * @param {Node} node The child node removed
2312 * Fires when a node is moved to a new location in the tree
2313 * @param {Tree} tree The owner tree
2314 * @param {Node} node The node moved
2315 * @param {Node} oldParent The old parent of this node
2316 * @param {Node} newParent The new parent of this node
2317 * @param {Number} index The index it was moved to
2322 * Fires when a new child node is inserted in a node in this tree.
2323 * @param {Tree} tree The owner tree
2324 * @param {Node} parent The parent node
2325 * @param {Node} node The child node inserted
2326 * @param {Node} refNode The child node the node was inserted before
2330 * @event beforeappend
2331 * Fires before a new child is appended to a node in this tree, return false to cancel the append.
2332 * @param {Tree} tree The owner tree
2333 * @param {Node} parent The parent node
2334 * @param {Node} node The child node to be appended
2336 "beforeappend" : true,
2338 * @event beforeremove
2339 * Fires before a child is removed from a node in this tree, return false to cancel the remove.
2340 * @param {Tree} tree The owner tree
2341 * @param {Node} parent The parent node
2342 * @param {Node} node The child node to be removed
2344 "beforeremove" : true,
2347 * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
2348 * @param {Tree} tree The owner tree
2349 * @param {Node} node The node being moved
2350 * @param {Node} oldParent The parent of the node
2351 * @param {Node} newParent The new parent the node is moving to
2352 * @param {Number} index The index it is being moved to
2354 "beforemove" : true,
2356 * @event beforeinsert
2357 * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
2358 * @param {Tree} tree The owner tree
2359 * @param {Node} parent The parent node
2360 * @param {Node} node The child node to be inserted
2361 * @param {Node} refNode The child node the node is being inserted before
2363 "beforeinsert" : true
2366 Roo.data.Tree.superclass.constructor.call(this);
2369 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
2372 proxyNodeEvent : function(){
2373 return this.fireEvent.apply(this, arguments);
2377 * Returns the root node for this tree.
2380 getRootNode : function(){
2385 * Sets the root node for this tree.
2386 * @param {Node} node
2389 setRootNode : function(node){
2391 node.ownerTree = this;
2393 this.registerNode(node);
2398 * Gets a node in this tree by its id.
2399 * @param {String} id
2402 getNodeById : function(id){
2403 return this.nodeHash[id];
2406 registerNode : function(node){
2407 this.nodeHash[node.id] = node;
2410 unregisterNode : function(node){
2411 delete this.nodeHash[node.id];
2414 toString : function(){
2415 return "[Tree"+(this.id?" "+this.id:"")+"]";
2420 * @class Roo.data.Node
2421 * @extends Roo.util.Observable
2422 * @cfg {Boolean} leaf true if this node is a leaf and does not have children
2423 * @cfg {String} id The id for this node. If one is not specified, one is generated.
2425 * @param {Object} attributes The attributes/config for the node
2427 Roo.data.Node = function(attributes){
2429 * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
2432 this.attributes = attributes || {};
2433 this.leaf = this.attributes.leaf;
2435 * The node id. @type String
2437 this.id = this.attributes.id;
2439 this.id = Roo.id(null, "ynode-");
2440 this.attributes.id = this.id;
2445 * All child nodes of this node. @type Array
2447 this.childNodes = [];
2448 if(!this.childNodes.indexOf){ // indexOf is a must
2449 this.childNodes.indexOf = function(o){
2450 for(var i = 0, len = this.length; i < len; i++){
2459 * The parent node for this node. @type Node
2461 this.parentNode = null;
2463 * The first direct child node of this node, or null if this node has no child nodes. @type Node
2465 this.firstChild = null;
2467 * The last direct child node of this node, or null if this node has no child nodes. @type Node
2469 this.lastChild = null;
2471 * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
2473 this.previousSibling = null;
2475 * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
2477 this.nextSibling = null;
2482 * Fires when a new child node is appended
2483 * @param {Tree} tree The owner tree
2484 * @param {Node} this This node
2485 * @param {Node} node The newly appended node
2486 * @param {Number} index The index of the newly appended node
2491 * Fires when a child node is removed
2492 * @param {Tree} tree The owner tree
2493 * @param {Node} this This node
2494 * @param {Node} node The removed node
2499 * Fires when this node is moved to a new location in the tree
2500 * @param {Tree} tree The owner tree
2501 * @param {Node} this This node
2502 * @param {Node} oldParent The old parent of this node
2503 * @param {Node} newParent The new parent of this node
2504 * @param {Number} index The index it was moved to
2509 * Fires when a new child node is inserted.
2510 * @param {Tree} tree The owner tree
2511 * @param {Node} this This node
2512 * @param {Node} node The child node inserted
2513 * @param {Node} refNode The child node the node was inserted before
2517 * @event beforeappend
2518 * Fires before a new child is appended, return false to cancel the append.
2519 * @param {Tree} tree The owner tree
2520 * @param {Node} this This node
2521 * @param {Node} node The child node to be appended
2523 "beforeappend" : true,
2525 * @event beforeremove
2526 * Fires before a child is removed, return false to cancel the remove.
2527 * @param {Tree} tree The owner tree
2528 * @param {Node} this This node
2529 * @param {Node} node The child node to be removed
2531 "beforeremove" : true,
2534 * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
2535 * @param {Tree} tree The owner tree
2536 * @param {Node} this This node
2537 * @param {Node} oldParent The parent of this node
2538 * @param {Node} newParent The new parent this node is moving to
2539 * @param {Number} index The index it is being moved to
2541 "beforemove" : true,
2543 * @event beforeinsert
2544 * Fires before a new child is inserted, return false to cancel the insert.
2545 * @param {Tree} tree The owner tree
2546 * @param {Node} this This node
2547 * @param {Node} node The child node to be inserted
2548 * @param {Node} refNode The child node the node is being inserted before
2550 "beforeinsert" : true
2552 this.listeners = this.attributes.listeners;
2553 Roo.data.Node.superclass.constructor.call(this);
2556 Roo.extend(Roo.data.Node, Roo.util.Observable, {
2557 fireEvent : function(evtName){
2558 // first do standard event for this node
2559 if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
2562 // then bubble it up to the tree if the event wasn't cancelled
2563 var ot = this.getOwnerTree();
2565 if(ot.proxyNodeEvent.apply(ot, arguments) === false){
2573 * Returns true if this node is a leaf
2576 isLeaf : function(){
2577 return this.leaf === true;
2581 setFirstChild : function(node){
2582 this.firstChild = node;
2586 setLastChild : function(node){
2587 this.lastChild = node;
2592 * Returns true if this node is the last child of its parent
2595 isLast : function(){
2596 return (!this.parentNode ? true : this.parentNode.lastChild == this);
2600 * Returns true if this node is the first child of its parent
2603 isFirst : function(){
2604 return (!this.parentNode ? true : this.parentNode.firstChild == this);
2607 hasChildNodes : function(){
2608 return !this.isLeaf() && this.childNodes.length > 0;
2612 * Insert node(s) as the last child node of this node.
2613 * @param {Node/Array} node The node or Array of nodes to append
2614 * @return {Node} The appended node if single append, or null if an array was passed
2616 appendChild : function(node){
2618 if(node instanceof Array){
2620 }else if(arguments.length > 1){
2624 // if passed an array or multiple args do them one by one
2626 for(var i = 0, len = multi.length; i < len; i++) {
2627 this.appendChild(multi[i]);
2630 if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
2633 var index = this.childNodes.length;
2634 var oldParent = node.parentNode;
2635 // it's a move, make sure we move it cleanly
2637 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
2640 oldParent.removeChild(node);
2643 index = this.childNodes.length;
2645 this.setFirstChild(node);
2647 this.childNodes.push(node);
2648 node.parentNode = this;
2649 var ps = this.childNodes[index-1];
2651 node.previousSibling = ps;
2652 ps.nextSibling = node;
2654 node.previousSibling = null;
2656 node.nextSibling = null;
2657 this.setLastChild(node);
2658 node.setOwnerTree(this.getOwnerTree());
2659 this.fireEvent("append", this.ownerTree, this, node, index);
2660 if(this.ownerTree) {
2661 this.ownerTree.fireEvent("appendnode", this, node, index);
2664 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
2671 * Removes a child node from this node.
2672 * @param {Node} node The node to remove
2673 * @return {Node} The removed node
2675 removeChild : function(node){
2676 var index = this.childNodes.indexOf(node);
2680 if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
2684 // remove it from childNodes collection
2685 this.childNodes.splice(index, 1);
2688 if(node.previousSibling){
2689 node.previousSibling.nextSibling = node.nextSibling;
2691 if(node.nextSibling){
2692 node.nextSibling.previousSibling = node.previousSibling;
2695 // update child refs
2696 if(this.firstChild == node){
2697 this.setFirstChild(node.nextSibling);
2699 if(this.lastChild == node){
2700 this.setLastChild(node.previousSibling);
2703 node.setOwnerTree(null);
2704 // clear any references from the node
2705 node.parentNode = null;
2706 node.previousSibling = null;
2707 node.nextSibling = null;
2708 this.fireEvent("remove", this.ownerTree, this, node);
2713 * Inserts the first node before the second node in this nodes childNodes collection.
2714 * @param {Node} node The node to insert
2715 * @param {Node} refNode The node to insert before (if null the node is appended)
2716 * @return {Node} The inserted node
2718 insertBefore : function(node, refNode){
2719 if(!refNode){ // like standard Dom, refNode can be null for append
2720 return this.appendChild(node);
2723 if(node == refNode){
2727 if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
2730 var index = this.childNodes.indexOf(refNode);
2731 var oldParent = node.parentNode;
2732 var refIndex = index;
2734 // when moving internally, indexes will change after remove
2735 if(oldParent == this && this.childNodes.indexOf(node) < index){
2739 // it's a move, make sure we move it cleanly
2741 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
2744 oldParent.removeChild(node);
2747 this.setFirstChild(node);
2749 this.childNodes.splice(refIndex, 0, node);
2750 node.parentNode = this;
2751 var ps = this.childNodes[refIndex-1];
2753 node.previousSibling = ps;
2754 ps.nextSibling = node;
2756 node.previousSibling = null;
2758 node.nextSibling = refNode;
2759 refNode.previousSibling = node;
2760 node.setOwnerTree(this.getOwnerTree());
2761 this.fireEvent("insert", this.ownerTree, this, node, refNode);
2763 node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
2769 * Returns the child node at the specified index.
2770 * @param {Number} index
2773 item : function(index){
2774 return this.childNodes[index];
2778 * Replaces one child node in this node with another.
2779 * @param {Node} newChild The replacement node
2780 * @param {Node} oldChild The node to replace
2781 * @return {Node} The replaced node
2783 replaceChild : function(newChild, oldChild){
2784 this.insertBefore(newChild, oldChild);
2785 this.removeChild(oldChild);
2790 * Returns the index of a child node
2791 * @param {Node} node
2792 * @return {Number} The index of the node or -1 if it was not found
2794 indexOf : function(child){
2795 return this.childNodes.indexOf(child);
2799 * Returns the tree this node is in.
2802 getOwnerTree : function(){
2803 // if it doesn't have one, look for one
2804 if(!this.ownerTree){
2808 this.ownerTree = p.ownerTree;
2814 return this.ownerTree;
2818 * Returns depth of this node (the root node has a depth of 0)
2821 getDepth : function(){
2824 while(p.parentNode){
2832 setOwnerTree : function(tree){
2833 // if it's move, we need to update everyone
2834 if(tree != this.ownerTree){
2836 this.ownerTree.unregisterNode(this);
2838 this.ownerTree = tree;
2839 var cs = this.childNodes;
2840 for(var i = 0, len = cs.length; i < len; i++) {
2841 cs[i].setOwnerTree(tree);
2844 tree.registerNode(this);
2850 * Returns the path for this node. The path can be used to expand or select this node programmatically.
2851 * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
2852 * @return {String} The path
2854 getPath : function(attr){
2855 attr = attr || "id";
2856 var p = this.parentNode;
2857 var b = [this.attributes[attr]];
2859 b.unshift(p.attributes[attr]);
2862 var sep = this.getOwnerTree().pathSeparator;
2863 return sep + b.join(sep);
2867 * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
2868 * function call will be the scope provided or the current node. The arguments to the function
2869 * will be the args provided or the current node. If the function returns false at any point,
2870 * the bubble is stopped.
2871 * @param {Function} fn The function to call
2872 * @param {Object} scope (optional) The scope of the function (defaults to current node)
2873 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2875 bubble : function(fn, scope, args){
2878 if(fn.call(scope || p, args || p) === false){
2886 * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
2887 * function call will be the scope provided or the current node. The arguments to the function
2888 * will be the args provided or the current node. If the function returns false at any point,
2889 * the cascade is stopped on that branch.
2890 * @param {Function} fn The function to call
2891 * @param {Object} scope (optional) The scope of the function (defaults to current node)
2892 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2894 cascade : function(fn, scope, args){
2895 if(fn.call(scope || this, args || this) !== false){
2896 var cs = this.childNodes;
2897 for(var i = 0, len = cs.length; i < len; i++) {
2898 cs[i].cascade(fn, scope, args);
2904 * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
2905 * function call will be the scope provided or the current node. The arguments to the function
2906 * will be the args provided or the current node. If the function returns false at any point,
2907 * the iteration stops.
2908 * @param {Function} fn The function to call
2909 * @param {Object} scope (optional) The scope of the function (defaults to current node)
2910 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2912 eachChild : function(fn, scope, args){
2913 var cs = this.childNodes;
2914 for(var i = 0, len = cs.length; i < len; i++) {
2915 if(fn.call(scope || this, args || cs[i]) === false){
2922 * Finds the first child that has the attribute with the specified value.
2923 * @param {String} attribute The attribute name
2924 * @param {Mixed} value The value to search for
2925 * @return {Node} The found child or null if none was found
2927 findChild : function(attribute, value){
2928 var cs = this.childNodes;
2929 for(var i = 0, len = cs.length; i < len; i++) {
2930 if(cs[i].attributes[attribute] == value){
2938 * Finds the first child by a custom function. The child matches if the function passed
2940 * @param {Function} fn
2941 * @param {Object} scope (optional)
2942 * @return {Node} The found child or null if none was found
2944 findChildBy : function(fn, scope){
2945 var cs = this.childNodes;
2946 for(var i = 0, len = cs.length; i < len; i++) {
2947 if(fn.call(scope||cs[i], cs[i]) === true){
2955 * Sorts this nodes children using the supplied sort function
2956 * @param {Function} fn
2957 * @param {Object} scope (optional)
2959 sort : function(fn, scope){
2960 var cs = this.childNodes;
2961 var len = cs.length;
2963 var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
2965 for(var i = 0; i < len; i++){
2967 n.previousSibling = cs[i-1];
2968 n.nextSibling = cs[i+1];
2970 this.setFirstChild(n);
2973 this.setLastChild(n);
2980 * Returns true if this node is an ancestor (at any point) of the passed node.
2981 * @param {Node} node
2984 contains : function(node){
2985 return node.isAncestor(this);
2989 * Returns true if the passed node is an ancestor (at any point) of this node.
2990 * @param {Node} node
2993 isAncestor : function(node){
2994 var p = this.parentNode;
3004 toString : function(){
3005 return "[Node"+(this.id?" "+this.id:"")+"]";
3009 * Ext JS Library 1.1.1
3010 * Copyright(c) 2006-2007, Ext JS, LLC.
3012 * Originally Released Under LGPL - original licence link has changed is not relivant.
3015 * <script type="text/javascript">
3021 * Simple class that can provide a shadow effect for any element. Note that the element MUST be absolutely positioned,
3022 * and the shadow does not provide any shimming. This should be used only in simple cases -- for more advanced
3023 * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
3025 * Create a new Shadow
3026 * @param {Object} config The config object
3028 Roo.Shadow = function(config){
3029 Roo.apply(this, config);
3030 if(typeof this.mode != "string"){
3031 this.mode = this.defaultMode;
3033 var o = this.offset, a = {h: 0};
3034 var rad = Math.floor(this.offset/2);
3035 switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
3041 a.l -= this.offset + rad;
3042 a.t -= this.offset + rad;
3053 a.l -= (this.offset - rad);
3054 a.t -= this.offset + rad;
3056 a.w -= (this.offset - rad)*2;
3067 a.l -= (this.offset - rad);
3068 a.t -= (this.offset - rad);
3070 a.w -= (this.offset + rad + 1);
3071 a.h -= (this.offset + rad);
3080 Roo.Shadow.prototype = {
3082 * @cfg {String} mode
3083 * The shadow display mode. Supports the following options:<br />
3084 * sides: Shadow displays on both sides and bottom only<br />
3085 * frame: Shadow displays equally on all four sides<br />
3086 * drop: Traditional bottom-right drop shadow (default)
3090 * @cfg {String} offset
3091 * The number of pixels to offset the shadow from the element (defaults to 4)
3096 defaultMode: "drop",
3099 * Displays the shadow under the target element
3100 * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
3102 show : function(target){
3103 target = Roo.get(target);
3105 this.el = Roo.Shadow.Pool.pull();
3106 if(this.el.dom.nextSibling != target.dom){
3107 this.el.insertBefore(target);
3110 this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
3112 this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
3115 target.getLeft(true),
3116 target.getTop(true),
3120 this.el.dom.style.display = "block";
3124 * Returns true if the shadow is visible, else false
3126 isVisible : function(){
3127 return this.el ? true : false;
3131 * Direct alignment when values are already available. Show must be called at least once before
3132 * calling this method to ensure it is initialized.
3133 * @param {Number} left The target element left position
3134 * @param {Number} top The target element top position
3135 * @param {Number} width The target element width
3136 * @param {Number} height The target element height
3138 realign : function(l, t, w, h){
3142 var a = this.adjusts, d = this.el.dom, s = d.style;
3144 s.left = (l+a.l)+"px";
3145 s.top = (t+a.t)+"px";
3146 var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
3148 if(s.width != sws || s.height != shs){
3152 var cn = d.childNodes;
3153 var sww = Math.max(0, (sw-12))+"px";
3154 cn[0].childNodes[1].style.width = sww;
3155 cn[1].childNodes[1].style.width = sww;
3156 cn[2].childNodes[1].style.width = sww;
3157 cn[1].style.height = Math.max(0, (sh-12))+"px";
3167 this.el.dom.style.display = "none";
3168 Roo.Shadow.Pool.push(this.el);
3174 * Adjust the z-index of this shadow
3175 * @param {Number} zindex The new z-index
3177 setZIndex : function(z){
3180 this.el.setStyle("z-index", z);
3185 // Private utility class that manages the internal Shadow cache
3186 Roo.Shadow.Pool = function(){
3188 var markup = Roo.isIE ?
3189 '<div class="x-ie-shadow"></div>' :
3190 '<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>';
3195 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
3196 sh.autoBoxAdjust = false;
3201 push : function(sh){
3207 * Ext JS Library 1.1.1
3208 * Copyright(c) 2006-2007, Ext JS, LLC.
3210 * Originally Released Under LGPL - original licence link has changed is not relivant.
3213 * <script type="text/javascript">
3218 * @class Roo.SplitBar
3219 * @extends Roo.util.Observable
3220 * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
3224 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
3225 Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
3226 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
3227 split.minSize = 100;
3228 split.maxSize = 600;
3229 split.animate = true;
3230 split.on('moved', splitterMoved);
3233 * Create a new SplitBar
3234 * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar.
3235 * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged
3236 * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
3237 * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or
3238 Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
3239 position of the SplitBar).
3241 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
3244 this.el = Roo.get(dragElement, true);
3245 this.el.dom.unselectable = "on";
3247 this.resizingEl = Roo.get(resizingElement, true);
3251 * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
3252 * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
3255 this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
3258 * The minimum size of the resizing element. (Defaults to 0)
3264 * The maximum size of the resizing element. (Defaults to 2000)
3267 this.maxSize = 2000;
3270 * Whether to animate the transition to the new size
3273 this.animate = false;
3276 * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
3279 this.useShim = false;
3286 this.proxy = Roo.SplitBar.createProxy(this.orientation);
3288 this.proxy = Roo.get(existingProxy).dom;
3291 this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
3294 this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
3297 this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
3300 this.dragSpecs = {};
3303 * @private The adapter to use to positon and resize elements
3305 this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
3306 this.adapter.init(this);
3308 if(this.orientation == Roo.SplitBar.HORIZONTAL){
3310 this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
3311 this.el.addClass("x-splitbar-h");
3314 this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
3315 this.el.addClass("x-splitbar-v");
3321 * Fires when the splitter is moved (alias for {@link #event-moved})
3322 * @param {Roo.SplitBar} this
3323 * @param {Number} newSize the new width or height
3328 * Fires when the splitter is moved
3329 * @param {Roo.SplitBar} this
3330 * @param {Number} newSize the new width or height
3334 * @event beforeresize
3335 * Fires before the splitter is dragged
3336 * @param {Roo.SplitBar} this
3338 "beforeresize" : true,
3340 "beforeapply" : true
3343 Roo.util.Observable.call(this);
3346 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
3347 onStartProxyDrag : function(x, y){
3348 this.fireEvent("beforeresize", this);
3350 var o = Roo.DomHelper.insertFirst(document.body, {cls: "x-drag-overlay", html: " "}, true);
3352 o.enableDisplayMode("block");
3353 // all splitbars share the same overlay
3354 Roo.SplitBar.prototype.overlay = o;
3356 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
3357 this.overlay.show();
3358 Roo.get(this.proxy).setDisplayed("block");
3359 var size = this.adapter.getElementSize(this);
3360 this.activeMinSize = this.getMinimumSize();;
3361 this.activeMaxSize = this.getMaximumSize();;
3362 var c1 = size - this.activeMinSize;
3363 var c2 = Math.max(this.activeMaxSize - size, 0);
3364 if(this.orientation == Roo.SplitBar.HORIZONTAL){
3365 this.dd.resetConstraints();
3366 this.dd.setXConstraint(
3367 this.placement == Roo.SplitBar.LEFT ? c1 : c2,
3368 this.placement == Roo.SplitBar.LEFT ? c2 : c1
3370 this.dd.setYConstraint(0, 0);
3372 this.dd.resetConstraints();
3373 this.dd.setXConstraint(0, 0);
3374 this.dd.setYConstraint(
3375 this.placement == Roo.SplitBar.TOP ? c1 : c2,
3376 this.placement == Roo.SplitBar.TOP ? c2 : c1
3379 this.dragSpecs.startSize = size;
3380 this.dragSpecs.startPoint = [x, y];
3381 Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
3385 * @private Called after the drag operation by the DDProxy
3387 onEndProxyDrag : function(e){
3388 Roo.get(this.proxy).setDisplayed(false);
3389 var endPoint = Roo.lib.Event.getXY(e);
3391 this.overlay.hide();
3394 if(this.orientation == Roo.SplitBar.HORIZONTAL){
3395 newSize = this.dragSpecs.startSize +
3396 (this.placement == Roo.SplitBar.LEFT ?
3397 endPoint[0] - this.dragSpecs.startPoint[0] :
3398 this.dragSpecs.startPoint[0] - endPoint[0]
3401 newSize = this.dragSpecs.startSize +
3402 (this.placement == Roo.SplitBar.TOP ?
3403 endPoint[1] - this.dragSpecs.startPoint[1] :
3404 this.dragSpecs.startPoint[1] - endPoint[1]
3407 newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
3408 if(newSize != this.dragSpecs.startSize){
3409 if(this.fireEvent('beforeapply', this, newSize) !== false){
3410 this.adapter.setElementSize(this, newSize);
3411 this.fireEvent("moved", this, newSize);
3412 this.fireEvent("resize", this, newSize);
3418 * Get the adapter this SplitBar uses
3419 * @return The adapter object
3421 getAdapter : function(){
3422 return this.adapter;
3426 * Set the adapter this SplitBar uses
3427 * @param {Object} adapter A SplitBar adapter object
3429 setAdapter : function(adapter){
3430 this.adapter = adapter;
3431 this.adapter.init(this);
3435 * Gets the minimum size for the resizing element
3436 * @return {Number} The minimum size
3438 getMinimumSize : function(){
3439 return this.minSize;
3443 * Sets the minimum size for the resizing element
3444 * @param {Number} minSize The minimum size
3446 setMinimumSize : function(minSize){
3447 this.minSize = minSize;
3451 * Gets the maximum size for the resizing element
3452 * @return {Number} The maximum size
3454 getMaximumSize : function(){
3455 return this.maxSize;
3459 * Sets the maximum size for the resizing element
3460 * @param {Number} maxSize The maximum size
3462 setMaximumSize : function(maxSize){
3463 this.maxSize = maxSize;
3467 * Sets the initialize size for the resizing element
3468 * @param {Number} size The initial size
3470 setCurrentSize : function(size){
3471 var oldAnimate = this.animate;
3472 this.animate = false;
3473 this.adapter.setElementSize(this, size);
3474 this.animate = oldAnimate;
3478 * Destroy this splitbar.
3479 * @param {Boolean} removeEl True to remove the element
3481 destroy : function(removeEl){
3486 this.proxy.parentNode.removeChild(this.proxy);
3494 * @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.
3496 Roo.SplitBar.createProxy = function(dir){
3497 var proxy = new Roo.Element(document.createElement("div"));
3498 proxy.unselectable();
3499 var cls = 'x-splitbar-proxy';
3500 proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
3501 document.body.appendChild(proxy.dom);
3506 * @class Roo.SplitBar.BasicLayoutAdapter
3507 * Default Adapter. It assumes the splitter and resizing element are not positioned
3508 * elements and only gets/sets the width of the element. Generally used for table based layouts.
3510 Roo.SplitBar.BasicLayoutAdapter = function(){
3513 Roo.SplitBar.BasicLayoutAdapter.prototype = {
3514 // do nothing for now
3519 * Called before drag operations to get the current size of the resizing element.
3520 * @param {Roo.SplitBar} s The SplitBar using this adapter
3522 getElementSize : function(s){
3523 if(s.orientation == Roo.SplitBar.HORIZONTAL){
3524 return s.resizingEl.getWidth();
3526 return s.resizingEl.getHeight();
3531 * Called after drag operations to set the size of the resizing element.
3532 * @param {Roo.SplitBar} s The SplitBar using this adapter
3533 * @param {Number} newSize The new size to set
3534 * @param {Function} onComplete A function to be invoked when resizing is complete
3536 setElementSize : function(s, newSize, onComplete){
3537 if(s.orientation == Roo.SplitBar.HORIZONTAL){
3539 s.resizingEl.setWidth(newSize);
3541 onComplete(s, newSize);
3544 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
3549 s.resizingEl.setHeight(newSize);
3551 onComplete(s, newSize);
3554 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
3561 *@class Roo.SplitBar.AbsoluteLayoutAdapter
3562 * @extends Roo.SplitBar.BasicLayoutAdapter
3563 * Adapter that moves the splitter element to align with the resized sizing element.
3564 * Used with an absolute positioned SplitBar.
3565 * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
3566 * document.body, make sure you assign an id to the body element.
3568 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
3569 this.basic = new Roo.SplitBar.BasicLayoutAdapter();
3570 this.container = Roo.get(container);
3573 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
3578 getElementSize : function(s){
3579 return this.basic.getElementSize(s);
3582 setElementSize : function(s, newSize, onComplete){
3583 this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
3586 moveSplitter : function(s){
3587 var yes = Roo.SplitBar;
3588 switch(s.placement){
3590 s.el.setX(s.resizingEl.getRight());
3593 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
3596 s.el.setY(s.resizingEl.getBottom());
3599 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
3606 * Orientation constant - Create a vertical SplitBar
3610 Roo.SplitBar.VERTICAL = 1;
3613 * Orientation constant - Create a horizontal SplitBar
3617 Roo.SplitBar.HORIZONTAL = 2;
3620 * Placement constant - The resizing element is to the left of the splitter element
3624 Roo.SplitBar.LEFT = 1;
3627 * Placement constant - The resizing element is to the right of the splitter element
3631 Roo.SplitBar.RIGHT = 2;
3634 * Placement constant - The resizing element is positioned above the splitter element
3638 Roo.SplitBar.TOP = 3;
3641 * Placement constant - The resizing element is positioned under splitter element
3645 Roo.SplitBar.BOTTOM = 4;
3648 * Ext JS Library 1.1.1
3649 * Copyright(c) 2006-2007, Ext JS, LLC.
3651 * Originally Released Under LGPL - original licence link has changed is not relivant.
3654 * <script type="text/javascript">
3659 * @extends Roo.util.Observable
3660 * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template.
3661 * This class also supports single and multi selection modes. <br>
3662 * Create a data model bound view:
3664 var store = new Roo.data.Store(...);
3666 var view = new Roo.View({
3668 tpl : '<div id="{0}">{2} - {1}</div>', // auto create template
3671 selectedClass: "ydataview-selected",
3675 // listen for node click?
3676 view.on("click", function(vw, index, node, e){
3677 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
3681 dataModel.load("foobar.xml");
3683 For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
3685 * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
3686 * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
3688 * Note: old style constructor is still suported (container, template, config)
3692 * @param {Object} config The config object
3695 Roo.View = function(config, depreciated_tpl, depreciated_config){
3697 this.parent = false;
3699 if (typeof(depreciated_tpl) == 'undefined') {
3700 // new way.. - universal constructor.
3701 Roo.apply(this, config);
3702 this.el = Roo.get(this.el);
3705 this.el = Roo.get(config);
3706 this.tpl = depreciated_tpl;
3707 Roo.apply(this, depreciated_config);
3709 this.wrapEl = this.el.wrap().wrap();
3710 ///this.el = this.wrapEla.appendChild(document.createElement("div"));
3713 if(typeof(this.tpl) == "string"){
3714 this.tpl = new Roo.Template(this.tpl);
3716 // support xtype ctors..
3717 this.tpl = new Roo.factory(this.tpl, Roo);
3726 * @event beforeclick
3727 * Fires before a click is processed. Returns false to cancel the default action.
3728 * @param {Roo.View} this
3729 * @param {Number} index The index of the target node
3730 * @param {HTMLElement} node The target node
3731 * @param {Roo.EventObject} e The raw event object
3733 "beforeclick" : true,
3736 * Fires when a template node is clicked.
3737 * @param {Roo.View} this
3738 * @param {Number} index The index of the target node
3739 * @param {HTMLElement} node The target node
3740 * @param {Roo.EventObject} e The raw event object
3745 * Fires when a template node is double clicked.
3746 * @param {Roo.View} this
3747 * @param {Number} index The index of the target node
3748 * @param {HTMLElement} node The target node
3749 * @param {Roo.EventObject} e The raw event object
3753 * @event contextmenu
3754 * Fires when a template node is right clicked.
3755 * @param {Roo.View} this
3756 * @param {Number} index The index of the target node
3757 * @param {HTMLElement} node The target node
3758 * @param {Roo.EventObject} e The raw event object
3760 "contextmenu" : true,
3762 * @event selectionchange
3763 * Fires when the selected nodes change.
3764 * @param {Roo.View} this
3765 * @param {Array} selections Array of the selected nodes
3767 "selectionchange" : true,
3770 * @event beforeselect
3771 * Fires before a selection is made. If any handlers return false, the selection is cancelled.
3772 * @param {Roo.View} this
3773 * @param {HTMLElement} node The node to be selected
3774 * @param {Array} selections Array of currently selected nodes
3776 "beforeselect" : true,
3778 * @event preparedata
3779 * Fires on every row to render, to allow you to change the data.
3780 * @param {Roo.View} this
3781 * @param {Object} data to be rendered (change this)
3783 "preparedata" : true
3791 "click": this.onClick,
3792 "dblclick": this.onDblClick,
3793 "contextmenu": this.onContextMenu,
3797 this.selections = [];
3799 this.cmp = new Roo.CompositeElementLite([]);
3801 this.store = Roo.factory(this.store, Roo.data);
3802 this.setStore(this.store, true);
3805 if ( this.footer && this.footer.xtype) {
3807 var fctr = this.wrapEl.appendChild(document.createElement("div"));
3809 this.footer.dataSource = this.store;
3810 this.footer.container = fctr;
3811 this.footer = Roo.factory(this.footer, Roo);
3812 fctr.insertFirst(this.el);
3814 // this is a bit insane - as the paging toolbar seems to detach the el..
3815 // dom.parentNode.parentNode.parentNode
3816 // they get detached?
3820 Roo.View.superclass.constructor.call(this);
3825 Roo.extend(Roo.View, Roo.util.Observable, {
3828 * @cfg {Roo.data.Store} store Data store to load data from.
3833 * @cfg {String|Roo.Element} el The container element.
3838 * @cfg {String|Roo.Template} tpl The template used by this View
3842 * @cfg {String} dataName the named area of the template to use as the data area
3843 * Works with domtemplates roo-name="name"
3847 * @cfg {String} selectedClass The css class to add to selected nodes
3849 selectedClass : "x-view-selected",
3851 * @cfg {String} emptyText The empty text to show when nothing is loaded.
3856 * @cfg {String} text to display on mask (default Loading)
3860 * @cfg {Boolean} multiSelect Allow multiple selection
3862 multiSelect : false,
3864 * @cfg {Boolean} singleSelect Allow single selection
3866 singleSelect: false,
3869 * @cfg {Boolean} toggleSelect - selecting
3871 toggleSelect : false,
3874 * @cfg {Boolean} tickable - selecting
3879 * Returns the element this view is bound to.
3880 * @return {Roo.Element}
3889 * Refreshes the view. - called by datachanged on the store. - do not call directly.
3891 refresh : function(){
3892 //Roo.log('refresh');
3895 // if we are using something like 'domtemplate', then
3896 // the what gets used is:
3897 // t.applySubtemplate(NAME, data, wrapping data..)
3898 // the outer template then get' applied with
3899 // the store 'extra data'
3900 // and the body get's added to the
3901 // roo-name="data" node?
3902 // <span class='roo-tpl-{name}'></span> ?????
3906 this.clearSelections();
3909 var records = this.store.getRange();
3910 if(records.length < 1) {
3912 // is this valid?? = should it render a template??
3914 this.el.update(this.emptyText);
3918 if (this.dataName) {
3919 this.el.update(t.apply(this.store.meta)); //????
3920 el = this.el.child('.roo-tpl-' + this.dataName);
3923 for(var i = 0, len = records.length; i < len; i++){
3924 var data = this.prepareData(records[i].data, i, records[i]);
3925 this.fireEvent("preparedata", this, data, i, records[i]);
3927 var d = Roo.apply({}, data);
3930 Roo.apply(d, {'roo-id' : Roo.id()});
3934 Roo.each(this.parent.item, function(item){
3935 if(item[_this.parent.valueField] != data[_this.parent.valueField]){
3938 Roo.apply(d, {'roo-data-checked' : 'checked'});
3942 html[html.length] = Roo.util.Format.trim(
3944 t.applySubtemplate(this.dataName, d, this.store.meta) :
3951 el.update(html.join(""));
3952 this.nodes = el.dom.childNodes;
3953 this.updateIndexes(0);
3958 * Function to override to reformat the data that is sent to
3959 * the template for each node.
3960 * DEPRICATED - use the preparedata event handler.
3961 * @param {Array/Object} data The raw data (array of colData for a data model bound view or
3962 * a JSON object for an UpdateManager bound view).
3964 prepareData : function(data, index, record)
3966 this.fireEvent("preparedata", this, data, index, record);
3970 onUpdate : function(ds, record){
3971 // Roo.log('on update');
3972 this.clearSelections();
3973 var index = this.store.indexOf(record);
3974 var n = this.nodes[index];
3975 this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
3976 n.parentNode.removeChild(n);
3977 this.updateIndexes(index, index);
3983 onAdd : function(ds, records, index)
3985 //Roo.log(['on Add', ds, records, index] );
3986 this.clearSelections();
3987 if(this.nodes.length == 0){
3991 var n = this.nodes[index];
3992 for(var i = 0, len = records.length; i < len; i++){
3993 var d = this.prepareData(records[i].data, i, records[i]);
3995 this.tpl.insertBefore(n, d);
3998 this.tpl.append(this.el, d);
4001 this.updateIndexes(index);
4004 onRemove : function(ds, record, index){
4005 // Roo.log('onRemove');
4006 this.clearSelections();
4007 var el = this.dataName ?
4008 this.el.child('.roo-tpl-' + this.dataName) :
4011 el.dom.removeChild(this.nodes[index]);
4012 this.updateIndexes(index);
4016 * Refresh an individual node.
4017 * @param {Number} index
4019 refreshNode : function(index){
4020 this.onUpdate(this.store, this.store.getAt(index));
4023 updateIndexes : function(startIndex, endIndex){
4024 var ns = this.nodes;
4025 startIndex = startIndex || 0;
4026 endIndex = endIndex || ns.length - 1;
4027 for(var i = startIndex; i <= endIndex; i++){
4028 ns[i].nodeIndex = i;
4033 * Changes the data store this view uses and refresh the view.
4034 * @param {Store} store
4036 setStore : function(store, initial){
4037 if(!initial && this.store){
4038 this.store.un("datachanged", this.refresh);
4039 this.store.un("add", this.onAdd);
4040 this.store.un("remove", this.onRemove);
4041 this.store.un("update", this.onUpdate);
4042 this.store.un("clear", this.refresh);
4043 this.store.un("beforeload", this.onBeforeLoad);
4044 this.store.un("load", this.onLoad);
4045 this.store.un("loadexception", this.onLoad);
4049 store.on("datachanged", this.refresh, this);
4050 store.on("add", this.onAdd, this);
4051 store.on("remove", this.onRemove, this);
4052 store.on("update", this.onUpdate, this);
4053 store.on("clear", this.refresh, this);
4054 store.on("beforeload", this.onBeforeLoad, this);
4055 store.on("load", this.onLoad, this);
4056 store.on("loadexception", this.onLoad, this);
4064 * onbeforeLoad - masks the loading area.
4067 onBeforeLoad : function(store,opts)
4069 //Roo.log('onBeforeLoad');
4073 this.el.mask(this.mask ? this.mask : "Loading" );
4075 onLoad : function ()
4082 * Returns the template node the passed child belongs to or null if it doesn't belong to one.
4083 * @param {HTMLElement} node
4084 * @return {HTMLElement} The template node
4086 findItemFromChild : function(node){
4087 var el = this.dataName ?
4088 this.el.child('.roo-tpl-' + this.dataName,true) :
4091 if(!node || node.parentNode == el){
4094 var p = node.parentNode;
4095 while(p && p != el){
4096 if(p.parentNode == el){
4105 onClick : function(e){
4106 var item = this.findItemFromChild(e.getTarget());
4108 var index = this.indexOf(item);
4109 if(this.onItemClick(item, index, e) !== false){
4110 this.fireEvent("click", this, index, item, e);
4113 this.clearSelections();
4118 onContextMenu : function(e){
4119 var item = this.findItemFromChild(e.getTarget());
4121 this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
4126 onDblClick : function(e){
4127 var item = this.findItemFromChild(e.getTarget());
4129 this.fireEvent("dblclick", this, this.indexOf(item), item, e);
4133 onItemClick : function(item, index, e)
4135 if(this.fireEvent("beforeclick", this, index, item, e) === false){
4138 if (this.toggleSelect) {
4139 var m = this.isSelected(item) ? 'unselect' : 'select';
4142 _t[m](item, true, false);
4145 if(this.multiSelect || this.singleSelect){
4146 if(this.multiSelect && e.shiftKey && this.lastSelection){
4147 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
4149 this.select(item, this.multiSelect && e.ctrlKey);
4150 this.lastSelection = item;
4162 * Get the number of selected nodes.
4165 getSelectionCount : function(){
4166 return this.selections.length;
4170 * Get the currently selected nodes.
4171 * @return {Array} An array of HTMLElements
4173 getSelectedNodes : function(){
4174 return this.selections;
4178 * Get the indexes of the selected nodes.
4181 getSelectedIndexes : function(){
4182 var indexes = [], s = this.selections;
4183 for(var i = 0, len = s.length; i < len; i++){
4184 indexes.push(s[i].nodeIndex);
4190 * Clear all selections
4191 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
4193 clearSelections : function(suppressEvent){
4194 if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
4195 this.cmp.elements = this.selections;
4196 this.cmp.removeClass(this.selectedClass);
4197 this.selections = [];
4199 this.fireEvent("selectionchange", this, this.selections);
4205 * Returns true if the passed node is selected
4206 * @param {HTMLElement/Number} node The node or node index
4209 isSelected : function(node){
4210 var s = this.selections;
4214 node = this.getNode(node);
4215 return s.indexOf(node) !== -1;
4220 * @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
4221 * @param {Boolean} keepExisting (optional) true to keep existing selections
4222 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
4224 select : function(nodeInfo, keepExisting, suppressEvent){
4225 if(nodeInfo instanceof Array){
4227 this.clearSelections(true);
4229 for(var i = 0, len = nodeInfo.length; i < len; i++){
4230 this.select(nodeInfo[i], true, true);
4234 var node = this.getNode(nodeInfo);
4235 if(!node || this.isSelected(node)){
4236 return; // already selected.
4239 this.clearSelections(true);
4242 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
4243 Roo.fly(node).addClass(this.selectedClass);
4244 this.selections.push(node);
4246 this.fireEvent("selectionchange", this, this.selections);
4254 * @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
4255 * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
4256 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
4258 unselect : function(nodeInfo, keepExisting, suppressEvent)
4260 if(nodeInfo instanceof Array){
4261 Roo.each(this.selections, function(s) {
4262 this.unselect(s, nodeInfo);
4266 var node = this.getNode(nodeInfo);
4267 if(!node || !this.isSelected(node)){
4268 //Roo.log("not selected");
4269 return; // not selected.
4273 Roo.each(this.selections, function(s) {
4275 Roo.fly(node).removeClass(this.selectedClass);
4282 this.selections= ns;
4283 this.fireEvent("selectionchange", this, this.selections);
4287 * Gets a template node.
4288 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
4289 * @return {HTMLElement} The node or null if it wasn't found
4291 getNode : function(nodeInfo){
4292 if(typeof nodeInfo == "string"){
4293 return document.getElementById(nodeInfo);
4294 }else if(typeof nodeInfo == "number"){
4295 return this.nodes[nodeInfo];
4301 * Gets a range template nodes.
4302 * @param {Number} startIndex
4303 * @param {Number} endIndex
4304 * @return {Array} An array of nodes
4306 getNodes : function(start, end){
4307 var ns = this.nodes;
4309 end = typeof end == "undefined" ? ns.length - 1 : end;
4312 for(var i = start; i <= end; i++){
4316 for(var i = start; i >= end; i--){
4324 * Finds the index of the passed node
4325 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
4326 * @return {Number} The index of the node or -1
4328 indexOf : function(node){
4329 node = this.getNode(node);
4330 if(typeof node.nodeIndex == "number"){
4331 return node.nodeIndex;
4333 var ns = this.nodes;
4334 for(var i = 0, len = ns.length; i < len; i++){
4344 * Ext JS Library 1.1.1
4345 * Copyright(c) 2006-2007, Ext JS, LLC.
4347 * Originally Released Under LGPL - original licence link has changed is not relivant.
4350 * <script type="text/javascript">
4354 * @class Roo.JsonView
4356 * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
4358 var view = new Roo.JsonView({
4359 container: "my-element",
4360 tpl: '<div id="{id}">{foo} - {bar}</div>', // auto create template
4365 // listen for node click?
4366 view.on("click", function(vw, index, node, e){
4367 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
4370 // direct load of JSON data
4371 view.load("foobar.php");
4373 // Example from my blog list
4374 var tpl = new Roo.Template(
4375 '<div class="entry">' +
4376 '<a class="entry-title" href="{link}">{title}</a>' +
4377 "<h4>{date} by {author} | {comments} Comments</h4>{description}" +
4378 "</div><hr />"
4381 var moreView = new Roo.JsonView({
4382 container : "entry-list",
4386 moreView.on("beforerender", this.sortEntries, this);
4388 url: "/blog/get-posts.php",
4389 params: "allposts=true",
4390 text: "Loading Blog Entries..."
4394 * Note: old code is supported with arguments : (container, template, config)
4398 * Create a new JsonView
4400 * @param {Object} config The config object
4403 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
4406 Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
4408 var um = this.el.getUpdateManager();
4409 um.setRenderer(this);
4410 um.on("update", this.onLoad, this);
4411 um.on("failure", this.onLoadException, this);
4414 * @event beforerender
4415 * Fires before rendering of the downloaded JSON data.
4416 * @param {Roo.JsonView} this
4417 * @param {Object} data The JSON data loaded
4421 * Fires when data is loaded.
4422 * @param {Roo.JsonView} this
4423 * @param {Object} data The JSON data loaded
4424 * @param {Object} response The raw Connect response object
4427 * @event loadexception
4428 * Fires when loading fails.
4429 * @param {Roo.JsonView} this
4430 * @param {Object} response The raw Connect response object
4433 'beforerender' : true,
4435 'loadexception' : true
4438 Roo.extend(Roo.JsonView, Roo.View, {
4440 * @type {String} The root property in the loaded JSON object that contains the data
4445 * Refreshes the view.
4447 refresh : function(){
4448 this.clearSelections();
4451 var o = this.jsonData;
4452 if(o && o.length > 0){
4453 for(var i = 0, len = o.length; i < len; i++){
4454 var data = this.prepareData(o[i], i, o);
4455 html[html.length] = this.tpl.apply(data);
4458 html.push(this.emptyText);
4460 this.el.update(html.join(""));
4461 this.nodes = this.el.dom.childNodes;
4462 this.updateIndexes(0);
4466 * 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.
4467 * @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:
4470 url: "your-url.php",
4471 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
4472 callback: yourFunction,
4473 scope: yourObject, //(optional scope)
4481 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
4482 * 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.
4483 * @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}
4484 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
4485 * @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.
4488 var um = this.el.getUpdateManager();
4489 um.update.apply(um, arguments);
4492 // note - render is a standard framework call...
4493 // using it for the response is really flaky... - it's called by UpdateManager normally, except when called by the XComponent/addXtype.
4494 render : function(el, response){
4496 this.clearSelections();
4500 if (response != '') {
4501 o = Roo.util.JSON.decode(response.responseText);
4504 o = o[this.jsonRoot];
4510 * The current JSON data or null
4513 this.beforeRender();
4518 * Get the number of records in the current JSON dataset
4521 getCount : function(){
4522 return this.jsonData ? this.jsonData.length : 0;
4526 * Returns the JSON object for the specified node(s)
4527 * @param {HTMLElement/Array} node The node or an array of nodes
4528 * @return {Object/Array} If you pass in an array, you get an array back, otherwise
4529 * you get the JSON object for the node
4531 getNodeData : function(node){
4532 if(node instanceof Array){
4534 for(var i = 0, len = node.length; i < len; i++){
4535 data.push(this.getNodeData(node[i]));
4539 return this.jsonData[this.indexOf(node)] || null;
4542 beforeRender : function(){
4543 this.snapshot = this.jsonData;
4545 this.sort.apply(this, this.sortInfo);
4547 this.fireEvent("beforerender", this, this.jsonData);
4550 onLoad : function(el, o){
4551 this.fireEvent("load", this, this.jsonData, o);
4554 onLoadException : function(el, o){
4555 this.fireEvent("loadexception", this, o);
4559 * Filter the data by a specific property.
4560 * @param {String} property A property on your JSON objects
4561 * @param {String/RegExp} value Either string that the property values
4562 * should start with, or a RegExp to test against the property
4564 filter : function(property, value){
4567 var ss = this.snapshot;
4568 if(typeof value == "string"){
4569 var vlen = value.length;
4574 value = value.toLowerCase();
4575 for(var i = 0, len = ss.length; i < len; i++){
4577 if(o[property].substr(0, vlen).toLowerCase() == value){
4581 } else if(value.exec){ // regex?
4582 for(var i = 0, len = ss.length; i < len; i++){
4584 if(value.test(o[property])){
4591 this.jsonData = data;
4597 * Filter by a function. The passed function will be called with each
4598 * object in the current dataset. If the function returns true the value is kept,
4599 * otherwise it is filtered.
4600 * @param {Function} fn
4601 * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
4603 filterBy : function(fn, scope){
4606 var ss = this.snapshot;
4607 for(var i = 0, len = ss.length; i < len; i++){
4609 if(fn.call(scope || this, o)){
4613 this.jsonData = data;
4619 * Clears the current filter.
4621 clearFilter : function(){
4622 if(this.snapshot && this.jsonData != this.snapshot){
4623 this.jsonData = this.snapshot;
4630 * Sorts the data for this view and refreshes it.
4631 * @param {String} property A property on your JSON objects to sort on
4632 * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
4633 * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
4635 sort : function(property, dir, sortType){
4636 this.sortInfo = Array.prototype.slice.call(arguments, 0);
4639 var dsc = dir && dir.toLowerCase() == "desc";
4640 var f = function(o1, o2){
4641 var v1 = sortType ? sortType(o1[p]) : o1[p];
4642 var v2 = sortType ? sortType(o2[p]) : o2[p];
4645 return dsc ? +1 : -1;
4647 return dsc ? -1 : +1;
4652 this.jsonData.sort(f);
4654 if(this.jsonData != this.snapshot){
4655 this.snapshot.sort(f);
4661 * Ext JS Library 1.1.1
4662 * Copyright(c) 2006-2007, Ext JS, LLC.
4664 * Originally Released Under LGPL - original licence link has changed is not relivant.
4667 * <script type="text/javascript">
4672 * @class Roo.ColorPalette
4673 * @extends Roo.Component
4674 * Simple color palette class for choosing colors. The palette can be rendered to any container.<br />
4675 * Here's an example of typical usage:
4677 var cp = new Roo.ColorPalette({value:'993300'}); // initial selected color
4678 cp.render('my-div');
4680 cp.on('select', function(palette, selColor){
4681 // do something with selColor
4685 * Create a new ColorPalette
4686 * @param {Object} config The config object
4688 Roo.ColorPalette = function(config){
4689 Roo.ColorPalette.superclass.constructor.call(this, config);
4693 * Fires when a color is selected
4694 * @param {ColorPalette} this
4695 * @param {String} color The 6-digit color hex code (without the # symbol)
4701 this.on("select", this.handler, this.scope, true);
4704 Roo.extend(Roo.ColorPalette, Roo.Component, {
4706 * @cfg {String} itemCls
4707 * The CSS class to apply to the containing element (defaults to "x-color-palette")
4709 itemCls : "x-color-palette",
4711 * @cfg {String} value
4712 * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol). Note that
4713 * the hex codes are case-sensitive.
4718 ctype: "Roo.ColorPalette",
4721 * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
4723 allowReselect : false,
4726 * <p>An array of 6-digit color hex code strings (without the # symbol). This array can contain any number
4727 * of colors, and each hex code should be unique. The width of the palette is controlled via CSS by adjusting
4728 * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
4729 * of colors with the width setting until the box is symmetrical.</p>
4730 * <p>You can override individual colors if needed:</p>
4732 var cp = new Roo.ColorPalette();
4733 cp.colors[0] = "FF0000"; // change the first box to red
4736 Or you can provide a custom array of your own for complete control:
4738 var cp = new Roo.ColorPalette();
4739 cp.colors = ["000000", "993300", "333300"];
4744 "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
4745 "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
4746 "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
4747 "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
4748 "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
4752 onRender : function(container, position){
4753 var t = new Roo.MasterTemplate(
4754 '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on"> </span></em></a></tpl>'
4756 var c = this.colors;
4757 for(var i = 0, len = c.length; i < len; i++){
4760 var el = document.createElement("div");
4761 el.className = this.itemCls;
4763 container.dom.insertBefore(el, position);
4764 this.el = Roo.get(el);
4765 this.el.on(this.clickEvent, this.handleClick, this, {delegate: "a"});
4766 if(this.clickEvent != 'click'){
4767 this.el.on('click', Roo.emptyFn, this, {delegate: "a", preventDefault:true});
4772 afterRender : function(){
4773 Roo.ColorPalette.superclass.afterRender.call(this);
4782 handleClick : function(e, t){
4785 var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
4786 this.select(c.toUpperCase());
4791 * Selects the specified color in the palette (fires the select event)
4792 * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
4794 select : function(color){
4795 color = color.replace("#", "");
4796 if(color != this.value || this.allowReselect){
4799 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
4801 el.child("a.color-"+color).addClass("x-color-palette-sel");
4803 this.fireEvent("select", this, color);
4808 * Ext JS Library 1.1.1
4809 * Copyright(c) 2006-2007, Ext JS, LLC.
4811 * Originally Released Under LGPL - original licence link has changed is not relivant.
4814 * <script type="text/javascript">
4818 * @class Roo.DatePicker
4819 * @extends Roo.Component
4820 * Simple date picker class.
4822 * Create a new DatePicker
4823 * @param {Object} config The config object
4825 Roo.DatePicker = function(config){
4826 Roo.DatePicker.superclass.constructor.call(this, config);
4828 this.value = config && config.value ?
4829 config.value.clearTime() : new Date().clearTime();
4834 * Fires when a date is selected
4835 * @param {DatePicker} this
4836 * @param {Date} date The selected date
4840 * @event monthchange
4841 * Fires when the displayed month changes
4842 * @param {DatePicker} this
4843 * @param {Date} date The selected month
4849 this.on("select", this.handler, this.scope || this);
4851 // build the disabledDatesRE
4852 if(!this.disabledDatesRE && this.disabledDates){
4853 var dd = this.disabledDates;
4855 for(var i = 0; i < dd.length; i++){
4857 if(i != dd.length-1) {
4861 this.disabledDatesRE = new RegExp(re + ")");
4865 Roo.extend(Roo.DatePicker, Roo.Component, {
4867 * @cfg {String} todayText
4868 * The text to display on the button that selects the current date (defaults to "Today")
4870 todayText : "Today",
4872 * @cfg {String} okText
4873 * The text to display on the ok button
4875 okText : " OK ", //   to give the user extra clicking room
4877 * @cfg {String} cancelText
4878 * The text to display on the cancel button
4880 cancelText : "Cancel",
4882 * @cfg {String} todayTip
4883 * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
4885 todayTip : "{0} (Spacebar)",
4887 * @cfg {Date} minDate
4888 * Minimum allowable date (JavaScript date object, defaults to null)
4892 * @cfg {Date} maxDate
4893 * Maximum allowable date (JavaScript date object, defaults to null)
4897 * @cfg {String} minText
4898 * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
4900 minText : "This date is before the minimum date",
4902 * @cfg {String} maxText
4903 * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
4905 maxText : "This date is after the maximum date",
4907 * @cfg {String} format
4908 * The default date format string which can be overriden for localization support. The format must be
4909 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
4913 * @cfg {Array} disabledDays
4914 * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
4916 disabledDays : null,
4918 * @cfg {String} disabledDaysText
4919 * The tooltip to display when the date falls on a disabled day (defaults to "")
4921 disabledDaysText : "",
4923 * @cfg {RegExp} disabledDatesRE
4924 * JavaScript regular expression used to disable a pattern of dates (defaults to null)
4926 disabledDatesRE : null,
4928 * @cfg {String} disabledDatesText
4929 * The tooltip text to display when the date falls on a disabled date (defaults to "")
4931 disabledDatesText : "",
4933 * @cfg {Boolean} constrainToViewport
4934 * True to constrain the date picker to the viewport (defaults to true)
4936 constrainToViewport : true,
4938 * @cfg {Array} monthNames
4939 * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
4941 monthNames : Date.monthNames,
4943 * @cfg {Array} dayNames
4944 * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
4946 dayNames : Date.dayNames,
4948 * @cfg {String} nextText
4949 * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
4951 nextText: 'Next Month (Control+Right)',
4953 * @cfg {String} prevText
4954 * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
4956 prevText: 'Previous Month (Control+Left)',
4958 * @cfg {String} monthYearText
4959 * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
4961 monthYearText: 'Choose a month (Control+Up/Down to move years)',
4963 * @cfg {Number} startDay
4964 * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
4968 * @cfg {Bool} showClear
4969 * Show a clear button (usefull for date form elements that can be blank.)
4975 * Sets the value of the date field
4976 * @param {Date} value The date to set
4978 setValue : function(value){
4979 var old = this.value;
4981 if (typeof(value) == 'string') {
4983 value = Date.parseDate(value, this.format);
4989 this.value = value.clearTime(true);
4991 this.update(this.value);
4996 * Gets the current selected value of the date field
4997 * @return {Date} The selected date
4999 getValue : function(){
5006 this.update(this.activeDate);
5011 onRender : function(container, position){
5014 '<table cellspacing="0">',
5015 '<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>',
5016 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
5017 var dn = this.dayNames;
5018 for(var i = 0; i < 7; i++){
5019 var d = this.startDay+i;
5023 m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
5025 m[m.length] = "</tr></thead><tbody><tr>";
5026 for(var i = 0; i < 42; i++) {
5027 if(i % 7 == 0 && i != 0){
5028 m[m.length] = "</tr><tr>";
5030 m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
5032 m[m.length] = '</tr></tbody></table></td></tr><tr>'+
5033 '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
5035 var el = document.createElement("div");
5036 el.className = "x-date-picker";
5037 el.innerHTML = m.join("");
5039 container.dom.insertBefore(el, position);
5041 this.el = Roo.get(el);
5042 this.eventEl = Roo.get(el.firstChild);
5044 new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
5045 handler: this.showPrevMonth,
5047 preventDefault:true,
5051 new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
5052 handler: this.showNextMonth,
5054 preventDefault:true,
5058 this.eventEl.on("mousewheel", this.handleMouseWheel, this);
5060 this.monthPicker = this.el.down('div.x-date-mp');
5061 this.monthPicker.enableDisplayMode('block');
5063 var kn = new Roo.KeyNav(this.eventEl, {
5064 "left" : function(e){
5066 this.showPrevMonth() :
5067 this.update(this.activeDate.add("d", -1));
5070 "right" : function(e){
5072 this.showNextMonth() :
5073 this.update(this.activeDate.add("d", 1));
5078 this.showNextYear() :
5079 this.update(this.activeDate.add("d", -7));
5082 "down" : function(e){
5084 this.showPrevYear() :
5085 this.update(this.activeDate.add("d", 7));
5088 "pageUp" : function(e){
5089 this.showNextMonth();
5092 "pageDown" : function(e){
5093 this.showPrevMonth();
5096 "enter" : function(e){
5097 e.stopPropagation();
5104 this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"});
5106 this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday, this);
5108 this.el.unselectable();
5110 this.cells = this.el.select("table.x-date-inner tbody td");
5111 this.textNodes = this.el.query("table.x-date-inner tbody span");
5113 this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
5115 tooltip: this.monthYearText
5118 this.mbtn.on('click', this.showMonthPicker, this);
5119 this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
5122 var today = (new Date()).dateFormat(this.format);
5124 var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
5125 if (this.showClear) {
5126 baseTb.add( new Roo.Toolbar.Fill());
5129 text: String.format(this.todayText, today),
5130 tooltip: String.format(this.todayTip, today),
5131 handler: this.selectToday,
5135 //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
5138 if (this.showClear) {
5140 baseTb.add( new Roo.Toolbar.Fill());
5143 cls: 'x-btn-icon x-btn-clear',
5144 handler: function() {
5146 this.fireEvent("select", this, '');
5156 this.update(this.value);
5159 createMonthPicker : function(){
5160 if(!this.monthPicker.dom.firstChild){
5161 var buf = ['<table border="0" cellspacing="0">'];
5162 for(var i = 0; i < 6; i++){
5164 '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
5165 '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
5167 '<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>' :
5168 '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
5172 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
5174 '</button><button type="button" class="x-date-mp-cancel">',
5176 '</button></td></tr>',
5179 this.monthPicker.update(buf.join(''));
5180 this.monthPicker.on('click', this.onMonthClick, this);
5181 this.monthPicker.on('dblclick', this.onMonthDblClick, this);
5183 this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
5184 this.mpYears = this.monthPicker.select('td.x-date-mp-year');
5186 this.mpMonths.each(function(m, a, i){
5189 m.dom.xmonth = 5 + Math.round(i * .5);
5191 m.dom.xmonth = Math.round((i-1) * .5);
5197 showMonthPicker : function(){
5198 this.createMonthPicker();
5199 var size = this.el.getSize();
5200 this.monthPicker.setSize(size);
5201 this.monthPicker.child('table').setSize(size);
5203 this.mpSelMonth = (this.activeDate || this.value).getMonth();
5204 this.updateMPMonth(this.mpSelMonth);
5205 this.mpSelYear = (this.activeDate || this.value).getFullYear();
5206 this.updateMPYear(this.mpSelYear);
5208 this.monthPicker.slideIn('t', {duration:.2});
5211 updateMPYear : function(y){
5213 var ys = this.mpYears.elements;
5214 for(var i = 1; i <= 10; i++){
5215 var td = ys[i-1], y2;
5217 y2 = y + Math.round(i * .5);
5218 td.firstChild.innerHTML = y2;
5221 y2 = y - (5-Math.round(i * .5));
5222 td.firstChild.innerHTML = y2;
5225 this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
5229 updateMPMonth : function(sm){
5230 this.mpMonths.each(function(m, a, i){
5231 m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
5235 selectMPMonth: function(m){
5239 onMonthClick : function(e, t){
5241 var el = new Roo.Element(t), pn;
5242 if(el.is('button.x-date-mp-cancel')){
5243 this.hideMonthPicker();
5245 else if(el.is('button.x-date-mp-ok')){
5246 this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
5247 this.hideMonthPicker();
5249 else if(pn = el.up('td.x-date-mp-month', 2)){
5250 this.mpMonths.removeClass('x-date-mp-sel');
5251 pn.addClass('x-date-mp-sel');
5252 this.mpSelMonth = pn.dom.xmonth;
5254 else if(pn = el.up('td.x-date-mp-year', 2)){
5255 this.mpYears.removeClass('x-date-mp-sel');
5256 pn.addClass('x-date-mp-sel');
5257 this.mpSelYear = pn.dom.xyear;
5259 else if(el.is('a.x-date-mp-prev')){
5260 this.updateMPYear(this.mpyear-10);
5262 else if(el.is('a.x-date-mp-next')){
5263 this.updateMPYear(this.mpyear+10);
5267 onMonthDblClick : function(e, t){
5269 var el = new Roo.Element(t), pn;
5270 if(pn = el.up('td.x-date-mp-month', 2)){
5271 this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
5272 this.hideMonthPicker();
5274 else if(pn = el.up('td.x-date-mp-year', 2)){
5275 this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
5276 this.hideMonthPicker();
5280 hideMonthPicker : function(disableAnim){
5281 if(this.monthPicker){
5282 if(disableAnim === true){
5283 this.monthPicker.hide();
5285 this.monthPicker.slideOut('t', {duration:.2});
5291 showPrevMonth : function(e){
5292 this.update(this.activeDate.add("mo", -1));
5296 showNextMonth : function(e){
5297 this.update(this.activeDate.add("mo", 1));
5301 showPrevYear : function(){
5302 this.update(this.activeDate.add("y", -1));
5306 showNextYear : function(){
5307 this.update(this.activeDate.add("y", 1));
5311 handleMouseWheel : function(e){
5312 var delta = e.getWheelDelta();
5314 this.showPrevMonth();
5316 } else if(delta < 0){
5317 this.showNextMonth();
5323 handleDateClick : function(e, t){
5325 if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
5326 this.setValue(new Date(t.dateValue));
5327 this.fireEvent("select", this, this.value);
5332 selectToday : function(){
5333 this.setValue(new Date().clearTime());
5334 this.fireEvent("select", this, this.value);
5338 update : function(date)
5340 var vd = this.activeDate;
5341 this.activeDate = date;
5343 var t = date.getTime();
5344 if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
5345 this.cells.removeClass("x-date-selected");
5346 this.cells.each(function(c){
5347 if(c.dom.firstChild.dateValue == t){
5348 c.addClass("x-date-selected");
5349 setTimeout(function(){
5350 try{c.dom.firstChild.focus();}catch(e){}
5359 var days = date.getDaysInMonth();
5360 var firstOfMonth = date.getFirstDateOfMonth();
5361 var startingPos = firstOfMonth.getDay()-this.startDay;
5363 if(startingPos <= this.startDay){
5367 var pm = date.add("mo", -1);
5368 var prevStart = pm.getDaysInMonth()-startingPos;
5370 var cells = this.cells.elements;
5371 var textEls = this.textNodes;
5372 days += startingPos;
5374 // convert everything to numbers so it's fast
5376 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
5377 var today = new Date().clearTime().getTime();
5378 var sel = date.clearTime().getTime();
5379 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
5380 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
5381 var ddMatch = this.disabledDatesRE;
5382 var ddText = this.disabledDatesText;
5383 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
5384 var ddaysText = this.disabledDaysText;
5385 var format = this.format;
5387 var setCellClass = function(cal, cell){
5389 var t = d.getTime();
5390 cell.firstChild.dateValue = t;
5392 cell.className += " x-date-today";
5393 cell.title = cal.todayText;
5396 cell.className += " x-date-selected";
5397 setTimeout(function(){
5398 try{cell.firstChild.focus();}catch(e){}
5403 cell.className = " x-date-disabled";
5404 cell.title = cal.minText;
5408 cell.className = " x-date-disabled";
5409 cell.title = cal.maxText;
5413 if(ddays.indexOf(d.getDay()) != -1){
5414 cell.title = ddaysText;
5415 cell.className = " x-date-disabled";
5418 if(ddMatch && format){
5419 var fvalue = d.dateFormat(format);
5420 if(ddMatch.test(fvalue)){
5421 cell.title = ddText.replace("%0", fvalue);
5422 cell.className = " x-date-disabled";
5428 for(; i < startingPos; i++) {
5429 textEls[i].innerHTML = (++prevStart);
5430 d.setDate(d.getDate()+1);
5431 cells[i].className = "x-date-prevday";
5432 setCellClass(this, cells[i]);
5434 for(; i < days; i++){
5435 intDay = i - startingPos + 1;
5436 textEls[i].innerHTML = (intDay);
5437 d.setDate(d.getDate()+1);
5438 cells[i].className = "x-date-active";
5439 setCellClass(this, cells[i]);
5442 for(; i < 42; i++) {
5443 textEls[i].innerHTML = (++extraDays);
5444 d.setDate(d.getDate()+1);
5445 cells[i].className = "x-date-nextday";
5446 setCellClass(this, cells[i]);
5449 this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
5450 this.fireEvent('monthchange', this, date);
5452 if(!this.internalRender){
5453 var main = this.el.dom.firstChild;
5454 var w = main.offsetWidth;
5455 this.el.setWidth(w + this.el.getBorderWidth("lr"));
5456 Roo.fly(main).setWidth(w);
5457 this.internalRender = true;
5458 // opera does not respect the auto grow header center column
5459 // then, after it gets a width opera refuses to recalculate
5460 // without a second pass
5461 if(Roo.isOpera && !this.secondPass){
5462 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
5463 this.secondPass = true;
5464 this.update.defer(10, this, [date]);
5476 * @class Roo.panel.Cropbox
5477 * @extends Roo.BoxComponent
5478 * Panel Cropbox class
5479 * @cfg {String} emptyText show when image has been loaded
5480 * @cfg {String} rotateNotify show when image too small to rotate
5481 * @cfg {Number} errorTimeout default 3000
5482 * @cfg {Number} minWidth default 300
5483 * @cfg {Number} minHeight default 300
5484 * @cfg {Number} outputMaxWidth default 1200
5485 * @cfg {Number} windowSize default 300
5486 * @cfg {Array} buttons default ['rotateLeft', 'pictureBtn', 'rotateRight']
5487 * @cfg {Boolean} isDocument (true|false) default false
5488 * @cfg {String} url action url
5489 * @cfg {String} paramName default 'imageUpload'
5490 * @cfg {String} method default POST
5491 * @cfg {Boolean} loadMask (true|false) default true
5492 * @cfg {Boolean} loadingText default 'Loading...'
5495 * Create a new Cropbox
5496 * @param {Object} config The config object
5499 Roo.panel.Cropbox = function(config){
5500 Roo.panel.Cropbox.superclass.constructor.call(this, config);
5504 * @event beforeselectfile
5505 * Fire before select file
5506 * @param {Roo.panel.Cropbox} this
5508 "beforeselectfile" : true,
5511 * Fire after initEvent
5512 * @param {Roo.panel.Cropbox} this
5517 * Fire after initEvent
5518 * @param {Roo.panel.Cropbox} this
5519 * @param {String} data
5524 * Fire when preparing the file data
5525 * @param {Roo.panel.Cropbox} this
5526 * @param {Object} file
5531 * Fire when get exception
5532 * @param {Roo.panel.Cropbox} this
5533 * @param {XMLHttpRequest} xhr
5537 * @event beforeloadcanvas
5538 * Fire before load the canvas
5539 * @param {Roo.panel.Cropbox} this
5540 * @param {String} src
5542 "beforeloadcanvas" : true,
5545 * Fire when trash image
5546 * @param {Roo.panel.Cropbox} this
5551 * Fire when download the image
5552 * @param {Roo.panel.Cropbox} this
5556 * @event footerbuttonclick
5557 * Fire when footerbuttonclick
5558 * @param {Roo.panel.Cropbox} this
5559 * @param {String} type
5561 "footerbuttonclick" : true,
5565 * @param {Roo.panel.Cropbox} this
5570 * Fire when rotate the image
5571 * @param {Roo.panel.Cropbox} this
5572 * @param {String} pos
5577 * Fire when inspect the file
5578 * @param {Roo.panel.Cropbox} this
5579 * @param {Object} file
5584 * Fire when xhr upload the file
5585 * @param {Roo.panel.Cropbox} this
5586 * @param {Object} data
5591 * Fire when arrange the file data
5592 * @param {Roo.panel.Cropbox} this
5593 * @param {Object} formData
5598 * Fire after load the canvas
5599 * @param {Roo.panel.Cropbox}
5600 * @param {Object} imgEl
5605 this.buttons = this.buttons || Roo.panel.Cropbox.footer.STANDARD;
5608 Roo.extend(Roo.panel.Cropbox, Roo.Component, {
5610 emptyText : 'Click to upload image',
5611 rotateNotify : 'Image is too small to rotate',
5612 errorTimeout : 3000,
5623 outputMaxWidth : 1200,
5628 cropType : 'image/jpeg',
5630 canvasLoaded : false,
5633 paramName : 'imageUpload',
5635 loadingText : 'Loading...',
5638 getAutoCreate : function()
5642 cls : 'roo-upload-cropbox',
5646 cls : 'roo-upload-cropbox-selector',
5651 cls : 'roo-upload-cropbox-body',
5652 style : 'cursor:pointer',
5656 cls : 'roo-upload-cropbox-preview'
5660 cls : 'roo-upload-cropbox-thumb'
5664 cls : 'roo-upload-cropbox-empty-notify',
5665 html : this.emptyText
5669 cls : 'roo-upload-cropbox-error-notify alert alert-danger',
5670 html : this.rotateNotify
5676 cls : 'roo-upload-cropbox-footer',
5679 cls : 'btn-group btn-group-justified roo-upload-cropbox-btn-group',
5689 onRender : function(ct, position)
5691 Roo.panel.Cropbox.superclass.onRender.call(this, ct, position);
5694 if (this.el.attr('xtype')) {
5695 this.el.attr('xtypex', this.el.attr('xtype'));
5696 this.el.dom.removeAttribute('xtype');
5702 var cfg = Roo.apply({}, this.getAutoCreate());
5704 cfg.id = this.id || Roo.id();
5707 cfg.cls = (typeof(cfg.cls) == 'undefined' ? this.cls : cfg.cls) + ' ' + this.cls;
5710 if (this.style) { // fixme needs to support more complex style data.
5711 cfg.style = (typeof(cfg.style) == 'undefined' ? this.style : cfg.style) + '; ' + this.style;
5714 this.el = ct.createChild(cfg, position);
5719 if (this.buttons.length) {
5721 Roo.each(this.buttons, function(bb) {
5723 var btn = this.el.select('.roo-upload-cropbox-footer div.roo-upload-cropbox-btn-group').first().createChild(bb);
5725 btn.on('click', this.onFooterButtonClick.createDelegate(this, [bb.action], true));
5731 this.maskEl = this.el;
5735 initEvents : function()
5737 this.urlAPI = (window.createObjectURL && window) ||
5738 (window.URL && URL.revokeObjectURL && URL) ||
5739 (window.webkitURL && webkitURL);
5741 this.bodyEl = this.el.select('.roo-upload-cropbox-body', true).first();
5742 this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
5744 this.selectorEl = this.el.select('.roo-upload-cropbox-selector', true).first();
5745 this.selectorEl.hide();
5747 this.previewEl = this.el.select('.roo-upload-cropbox-preview', true).first();
5748 this.previewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
5750 this.thumbEl = this.el.select('.roo-upload-cropbox-thumb', true).first();
5751 this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
5752 this.thumbEl.hide();
5754 this.notifyEl = this.el.select('.roo-upload-cropbox-empty-notify', true).first();
5755 this.notifyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
5757 this.errorEl = this.el.select('.roo-upload-cropbox-error-notify', true).first();
5758 this.errorEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
5759 this.errorEl.hide();
5761 this.footerEl = this.el.select('.roo-upload-cropbox-footer', true).first();
5762 this.footerEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
5763 this.footerEl.hide();
5765 this.setThumbBoxSize();
5771 this.fireEvent('initial', this);
5778 window.addEventListener("resize", function() { _this.resize(); } );
5780 this.bodyEl.on('click', this.beforeSelectFile, this);
5783 this.bodyEl.on('touchstart', this.onTouchStart, this);
5784 this.bodyEl.on('touchmove', this.onTouchMove, this);
5785 this.bodyEl.on('touchend', this.onTouchEnd, this);
5789 this.bodyEl.on('mousedown', this.onMouseDown, this);
5790 this.bodyEl.on('mousemove', this.onMouseMove, this);
5791 var mousewheel = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel';
5792 this.bodyEl.on(mousewheel, this.onMouseWheel, this);
5793 Roo.get(document).on('mouseup', this.onMouseUp, this);
5796 this.selectorEl.on('change', this.onFileSelected, this);
5804 this.baseRotate = 1;
5805 this.dragable = false;
5806 this.pinching = false;
5809 this.cropData = false;
5810 this.notifyEl.dom.innerHTML = this.emptyText;
5812 // this.selectorEl.dom.value = '';
5818 if(this.fireEvent('resize', this) != false){
5819 this.setThumbBoxPosition();
5820 this.setCanvasPosition();
5824 onFooterButtonClick : function(e, el, o, type)
5827 case 'rotate-left' :
5828 this.onRotateLeft(e);
5830 case 'rotate-right' :
5831 this.onRotateRight(e);
5834 this.beforeSelectFile(e);
5852 this.fireEvent('footerbuttonclick', this, type);
5855 beforeSelectFile : function(e)
5859 if(this.fireEvent('beforeselectfile', this) != false){
5860 this.selectorEl.dom.click();
5864 onFileSelected : function(e)
5868 if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
5872 var file = this.selectorEl.dom.files[0];
5874 if(this.fireEvent('inspect', this, file) != false){
5882 this.fireEvent('trash', this);
5885 download : function(e)
5887 this.fireEvent('download', this);
5890 center : function(e)
5892 this.setCanvasPosition();
5895 loadCanvas : function(src)
5897 if(this.fireEvent('beforeloadcanvas', this, src) != false){
5901 this.imageEl = document.createElement('img');
5905 this.imageEl.addEventListener("load", function(){ _this.onLoadCanvas(); });
5907 this.imageEl.src = src;
5911 onLoadCanvas : function()
5913 this.imageEl.OriginWidth = this.imageEl.naturalWidth || this.imageEl.width;
5914 this.imageEl.OriginHeight = this.imageEl.naturalHeight || this.imageEl.height;
5916 if(this.fireEvent('loadcanvas', this, this.imageEl) != false){
5918 this.bodyEl.un('click', this.beforeSelectFile, this);
5920 this.notifyEl.hide();
5921 this.thumbEl.show();
5922 this.footerEl.show();
5924 this.baseRotateLevel();
5926 if(this.isDocument){
5927 this.setThumbBoxSize();
5930 this.setThumbBoxPosition();
5932 this.baseScaleLevel();
5938 this.canvasLoaded = true;
5943 this.maskEl.unmask();
5948 setCanvasPosition : function(center = true)
5954 var newCenterLeft = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
5955 var newCenterTop = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
5958 this.previewEl.setLeft(newCenterLeft);
5959 this.previewEl.setTop(newCenterTop);
5964 var oldScaleLevel = this.baseScale * Math.pow(1.02, this.startScale);
5965 var oldCanvasWidth = Math.floor(this.imageEl.OriginWidth * oldScaleLevel);
5966 var oldCanvasHeight = Math.floor(this.imageEl.OriginHeight * oldScaleLevel);
5968 var oldCenterLeft = Math.ceil((this.bodyEl.getWidth() - oldCanvasWidth) / 2);
5969 var oldCenterTop = Math.ceil((this.bodyEl.getHeight() - oldCanvasHeight) / 2);
5971 var leftDiff = newCenterLeft - oldCenterLeft;
5972 var topDiff = newCenterTop - oldCenterTop;
5974 var newPreviewLeft = this.previewEl.getLeft(true) + leftDiff;
5975 var newPreviewTop = this.previewEl.getTop(true) + topDiff;
5977 this.previewEl.setLeft(newPreviewLeft);
5978 this.previewEl.setTop(newPreviewTop);
5982 onMouseDown : function(e)
5986 this.dragable = true;
5987 this.pinching = false;
5989 if(this.isDocument && (this.canvasEl.width < this.thumbEl.getWidth() || this.canvasEl.height < this.thumbEl.getHeight())){
5990 this.dragable = false;
5994 this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
5995 this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
5999 onMouseMove : function(e)
6003 if(!this.canvasLoaded){
6007 if (!this.dragable){
6011 var maxPaddingLeft = this.canvasEl.width / 0.9 * 0.05;
6012 var maxPaddingTop = maxPaddingLeft * this.minHeight / this.minWidth;
6014 if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight <= this.minWidth / this.minHeight)) {
6015 maxPaddingLeft = (this.canvasEl.height * this.minWidth / this.minHeight - this.canvasEl.width) / 2 + maxPaddingLeft;
6018 if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight >= this.minWidth / this.minHeight)) {
6019 maxPaddingTop = (this.canvasEl.width * this.minHeight / this.minWidth - this.canvasEl.height) / 2 + maxPaddingTop;
6022 var minX = Math.ceil(this.thumbEl.getLeft(true) + this.thumbEl.getWidth() - this.canvasEl.width - maxPaddingLeft);
6023 var minY = Math.ceil(this.thumbEl.getTop(true) + this.thumbEl.getHeight() - this.canvasEl.height - maxPaddingTop);
6025 var maxX = Math.ceil(this.thumbEl.getLeft(true) + maxPaddingLeft);
6026 var maxY = Math.ceil(this.thumbEl.getTop(true) + maxPaddingTop);
6040 var x = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
6041 var y = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
6043 x = x - this.mouseX;
6044 y = y - this.mouseY;
6046 var bgX = Math.ceil(x + this.previewEl.getLeft(true));
6047 var bgY = Math.ceil(y + this.previewEl.getTop(true));
6049 bgX = (bgX < minX) ? minX : ((bgX > maxX) ? maxX : bgX);
6050 bgY = (bgY < minY) ? minY : ((bgY > maxY) ? maxY : bgY);
6052 this.previewEl.setLeft(bgX);
6053 this.previewEl.setTop(bgY);
6055 this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
6056 this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
6059 onMouseUp : function(e)
6063 this.dragable = false;
6066 onMouseWheel : function(e)
6070 this.startScale = this.scale;
6071 this.scale = (e.getWheelDelta() > 0) ? (this.scale + 1) : (this.scale - 1);
6073 if(!this.zoomable()){
6074 this.scale = this.startScale;
6084 zoomable : function()
6086 var minScale = this.thumbEl.getWidth() / this.minWidth;
6088 if(this.minWidth < this.minHeight){
6089 minScale = this.thumbEl.getHeight() / this.minHeight;
6092 var width = Math.ceil(this.imageEl.OriginWidth * this.getScaleLevel() / minScale);
6093 var height = Math.ceil(this.imageEl.OriginHeight * this.getScaleLevel() / minScale);
6095 var maxWidth = this.imageEl.OriginWidth;
6096 var maxHeight = this.imageEl.OriginHeight;
6099 var newCanvasWidth = Math.floor(this.imageEl.OriginWidth * this.getScaleLevel());
6100 var newCanvasHeight = Math.floor(this.imageEl.OriginHeight * this.getScaleLevel());
6102 var oldCenterLeft = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
6103 var oldCenterTop = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
6105 var newCenterLeft = Math.ceil((this.bodyEl.getWidth() - newCanvasWidth) / 2);
6106 var newCenterTop = Math.ceil((this.bodyEl.getHeight() - newCanvasHeight) / 2);
6108 var leftDiff = newCenterLeft - oldCenterLeft;
6109 var topDiff = newCenterTop - oldCenterTop;
6111 var newPreviewLeft = this.previewEl.getLeft(true) + leftDiff;
6112 var newPreviewTop = this.previewEl.getTop(true) + topDiff;
6114 var paddingLeft = newPreviewLeft - this.thumbEl.getLeft(true);
6115 var paddingTop = newPreviewTop - this.thumbEl.getTop(true);
6117 var paddingRight = this.thumbEl.getLeft(true) + this.thumbEl.getWidth() - newCanvasWidth - newPreviewLeft;
6118 var paddingBottom = this.thumbEl.getTop(true) + this.thumbEl.getHeight() - newCanvasHeight - newPreviewTop;
6120 var maxPaddingLeft = newCanvasWidth / 0.9 * 0.05;
6121 var maxPaddingTop = maxPaddingLeft * this.minHeight / this.minWidth;
6123 if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight <= this.minWidth / this.minHeight)) {
6124 maxPaddingLeft = (newCanvasHeight * this.minWidth / this.minHeight - newCanvasWidth) / 2 + maxPaddingLeft;
6127 if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight >= this.minWidth / this.minHeight)) {
6128 maxPaddingTop = (newCanvasWidth * this.minHeight / this.minWidth - newCanvasHeight) / 2 + maxPaddingTop;
6133 (this.rotate == 0 || this.rotate == 180) &&
6135 width > this.imageEl.OriginWidth ||
6136 height > this.imageEl.OriginHeight ||
6137 (width < this.minWidth && height < this.minHeight)
6145 (this.rotate == 90 || this.rotate == 270) &&
6147 width > this.imageEl.OriginWidth ||
6148 height > this.imageEl.OriginHeight ||
6149 (width < this.minHeight && height < this.minWidth)
6157 (this.rotate == 0 || this.rotate == 180) &&
6160 paddingLeft > maxPaddingLeft ||
6161 paddingRight > maxPaddingLeft ||
6162 paddingTop > maxPaddingTop ||
6163 paddingBottom > maxPaddingTop ||
6174 (this.rotate == 90 || this.rotate == 270) &&
6176 width < this.minHeight ||
6177 width > this.imageEl.OriginWidth ||
6178 height < this.minWidth ||
6179 height > this.imageEl.OriginHeight
6189 onRotateLeft : function(e)
6191 if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
6193 var minScale = this.thumbEl.getWidth() / this.minWidth;
6195 var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
6196 var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
6198 this.startScale = this.scale;
6200 while (this.getScaleLevel() < minScale){
6202 this.scale = this.scale + 1;
6204 if(!this.zoomable()){
6209 Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
6210 Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
6215 this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
6222 this.scale = this.startScale;
6224 this.onRotateFail();
6229 this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
6231 if(this.isDocument){
6232 this.setThumbBoxSize();
6233 this.setThumbBoxPosition();
6234 this.setCanvasPosition();
6239 this.fireEvent('rotate', this, 'left');
6243 onRotateRight : function(e)
6245 if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
6247 var minScale = this.thumbEl.getWidth() / this.minWidth;
6249 var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
6250 var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
6252 this.startScale = this.scale;
6254 while (this.getScaleLevel() < minScale){
6256 this.scale = this.scale + 1;
6258 if(!this.zoomable()){
6263 Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
6264 Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
6269 this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
6276 this.scale = this.startScale;
6278 this.onRotateFail();
6283 this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
6285 if(this.isDocument){
6286 this.setThumbBoxSize();
6287 this.setThumbBoxPosition();
6288 this.setCanvasPosition();
6293 this.fireEvent('rotate', this, 'right');
6296 onRotateFail : function()
6298 this.errorEl.show(true);
6302 (function() { _this.errorEl.hide(true); }).defer(this.errorTimeout);
6307 this.previewEl.dom.innerHTML = '';
6309 var canvasEl = document.createElement("canvas");
6311 var contextEl = canvasEl.getContext("2d");
6313 canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
6314 canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
6315 var center = this.imageEl.OriginWidth / 2;
6317 if(this.imageEl.OriginWidth < this.imageEl.OriginHeight){
6318 canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
6319 canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
6320 center = this.imageEl.OriginHeight / 2;
6323 contextEl.scale(this.getScaleLevel(), this.getScaleLevel());
6325 contextEl.translate(center, center);
6326 contextEl.rotate(this.rotate * Math.PI / 180);
6328 contextEl.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
6330 this.canvasEl = document.createElement("canvas");
6332 this.contextEl = this.canvasEl.getContext("2d");
6334 switch (this.rotate) {
6337 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
6338 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
6340 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6345 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
6346 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
6348 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
6349 this.contextEl.drawImage(canvasEl, Math.abs(this.canvasEl.width - this.canvasEl.height), 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6353 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6358 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
6359 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
6361 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
6362 this.contextEl.drawImage(canvasEl, 0, Math.abs(this.canvasEl.width - this.canvasEl.height), this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6366 this.contextEl.drawImage(canvasEl, Math.abs(this.canvasEl.width - this.canvasEl.height), 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6371 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
6372 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
6374 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
6375 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6379 this.contextEl.drawImage(canvasEl, 0, Math.abs(this.canvasEl.width - this.canvasEl.height), this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6386 this.previewEl.appendChild(this.canvasEl);
6388 this.setCanvasPosition(false);
6393 if(!this.canvasLoaded){
6397 var imageCanvas = document.createElement("canvas");
6399 var imageContext = imageCanvas.getContext("2d");
6401 imageCanvas.width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
6402 imageCanvas.height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
6404 var center = imageCanvas.width / 2;
6406 imageContext.translate(center, center);
6408 imageContext.rotate(this.rotate * Math.PI / 180);
6410 imageContext.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
6412 var canvas = document.createElement("canvas");
6414 var context = canvas.getContext("2d");
6416 canvas.width = this.thumbEl.getWidth() / this.getScaleLevel();
6418 canvas.height = this.thumbEl.getHeight() / this.getScaleLevel();
6420 switch (this.rotate) {
6423 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
6424 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
6426 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
6427 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
6429 var sx = this.thumbEl.getLeft(true) - this.previewEl.getLeft(true);
6430 var sy = this.thumbEl.getTop(true) - this.previewEl.getTop(true);
6432 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
6433 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
6435 if(canvas.width > this.outputMaxWidth) {
6436 var scale = this.outputMaxWidth / canvas.width;
6437 canvas.width = canvas.width * scale;
6438 canvas.height = canvas.height * scale;
6439 context.scale(scale, scale);
6442 context.fillStyle = 'white';
6443 context.fillRect(0, 0, this.thumbEl.getWidth() / this.getScaleLevel(), this.thumbEl.getHeight() / this.getScaleLevel());
6446 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
6451 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
6452 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
6454 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
6455 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
6457 var targetWidth = this.minWidth - 2 * x;
6458 var targetHeight = this.minHeight - 2 * y;
6462 if((x == 0 && y == 0) || (x == 0 && y > 0)){
6463 scale = targetWidth / width;
6466 if(x > 0 && y == 0){
6467 scale = targetHeight / height;
6471 scale = targetWidth / width;
6474 scale = targetHeight / height;
6478 context.scale(scale, scale);
6480 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
6481 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
6483 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
6484 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
6486 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
6488 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
6493 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
6494 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
6496 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
6497 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
6499 var targetWidth = this.minWidth - 2 * x;
6500 var targetHeight = this.minHeight - 2 * y;
6504 if((x == 0 && y == 0) || (x == 0 && y > 0)){
6505 scale = targetWidth / width;
6508 if(x > 0 && y == 0){
6509 scale = targetHeight / height;
6513 scale = targetWidth / width;
6516 scale = targetHeight / height;
6520 context.scale(scale, scale);
6522 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
6523 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
6525 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
6526 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
6528 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
6529 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
6531 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
6536 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
6537 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
6539 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
6540 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
6542 var targetWidth = this.minWidth - 2 * x;
6543 var targetHeight = this.minHeight - 2 * y;
6547 if((x == 0 && y == 0) || (x == 0 && y > 0)){
6548 scale = targetWidth / width;
6551 if(x > 0 && y == 0){
6552 scale = targetHeight / height;
6556 scale = targetWidth / width;
6559 scale = targetHeight / height;
6563 context.scale(scale, scale);
6564 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
6565 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
6567 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
6568 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
6570 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
6572 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
6579 this.cropData = canvas.toDataURL(this.cropType);
6581 if(this.fireEvent('crop', this, this.cropData) !== false){
6582 this.process(this.file, this.cropData);
6589 setThumbBoxSize : function()
6593 if(this.isDocument && typeof(this.imageEl) != 'undefined'){
6594 width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.max(this.minWidth, this.minHeight) : Math.min(this.minWidth, this.minHeight);
6595 height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.min(this.minWidth, this.minHeight) : Math.max(this.minWidth, this.minHeight);
6597 this.minWidth = width;
6598 this.minHeight = height;
6600 if(this.rotate == 90 || this.rotate == 270){
6601 this.minWidth = height;
6602 this.minHeight = width;
6606 height = this.windowSize;
6607 width = Math.ceil(this.minWidth * height / this.minHeight);
6609 if(this.minWidth > this.minHeight){
6610 width = this.windowSize;
6611 height = Math.ceil(this.minHeight * width / this.minWidth);
6614 this.thumbEl.setStyle({
6615 width : width + 'px',
6616 height : height + 'px'
6623 setThumbBoxPosition : function()
6625 var x = Math.ceil((this.bodyEl.getWidth() - this.thumbEl.getWidth()) / 2 );
6626 var y = Math.ceil((this.bodyEl.getHeight() - this.thumbEl.getHeight()) / 2);
6628 this.thumbEl.setLeft(x);
6629 this.thumbEl.setTop(y);
6633 baseRotateLevel : function()
6635 this.baseRotate = 1;
6638 typeof(this.exif) != 'undefined' &&
6639 typeof(this.exif[Roo.panel.Cropbox['tags']['Orientation']]) != 'undefined' &&
6640 [1, 3, 6, 8].indexOf(this.exif[Roo.panel.Cropbox['tags']['Orientation']]) != -1
6642 this.baseRotate = this.exif[Roo.panel.Cropbox['tags']['Orientation']];
6645 this.rotate = Roo.panel.Cropbox['Orientation'][this.baseRotate];
6649 baseScaleLevel : function()
6653 if(this.isDocument){
6655 if(this.baseRotate == 6 || this.baseRotate == 8){
6657 height = this.thumbEl.getHeight();
6658 this.baseScale = height / this.imageEl.OriginWidth;
6660 if(this.imageEl.OriginHeight * this.baseScale > this.thumbEl.getWidth()){
6661 width = this.thumbEl.getWidth();
6662 this.baseScale = width / this.imageEl.OriginHeight;
6668 height = this.thumbEl.getHeight();
6669 this.baseScale = height / this.imageEl.OriginHeight;
6671 if(this.imageEl.OriginWidth * this.baseScale > this.thumbEl.getWidth()){
6672 width = this.thumbEl.getWidth();
6673 this.baseScale = width / this.imageEl.OriginWidth;
6679 if(this.baseRotate == 6 || this.baseRotate == 8){
6681 width = this.thumbEl.getHeight();
6682 this.baseScale = width / this.imageEl.OriginHeight;
6684 if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getWidth()){
6685 height = this.thumbEl.getWidth();
6686 this.baseScale = height / this.imageEl.OriginHeight;
6689 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
6690 height = this.thumbEl.getWidth();
6691 this.baseScale = height / this.imageEl.OriginHeight;
6693 if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getHeight()){
6694 width = this.thumbEl.getHeight();
6695 this.baseScale = width / this.imageEl.OriginWidth;
6702 width = this.thumbEl.getWidth();
6703 this.baseScale = width / this.imageEl.OriginWidth;
6705 if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getHeight()){
6706 height = this.thumbEl.getHeight();
6707 this.baseScale = height / this.imageEl.OriginHeight;
6710 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
6712 height = this.thumbEl.getHeight();
6713 this.baseScale = height / this.imageEl.OriginHeight;
6715 if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getWidth()){
6716 width = this.thumbEl.getWidth();
6717 this.baseScale = width / this.imageEl.OriginWidth;
6722 if(this.imageEl.OriginWidth < this.minWidth || this.imageEl.OriginHeight < this.minHeight) {
6723 this.baseScale = width / this.minWidth;
6729 getScaleLevel : function()
6731 return this.baseScale * Math.pow(1.02, this.scale);
6734 onTouchStart : function(e)
6736 if(!this.canvasLoaded){
6737 this.beforeSelectFile(e);
6741 var touches = e.browserEvent.touches;
6747 if(touches.length == 1){
6748 this.onMouseDown(e);
6752 if(touches.length != 2){
6758 for(var i = 0, finger; finger = touches[i]; i++){
6759 coords.push(finger.pageX, finger.pageY);
6762 var x = Math.pow(coords[0] - coords[2], 2);
6763 var y = Math.pow(coords[1] - coords[3], 2);
6765 this.startDistance = Math.sqrt(x + y);
6767 this.startScale = this.scale;
6769 this.pinching = true;
6770 this.dragable = false;
6774 onTouchMove : function(e)
6776 if(!this.pinching && !this.dragable){
6780 var touches = e.browserEvent.touches;
6787 this.onMouseMove(e);
6793 for(var i = 0, finger; finger = touches[i]; i++){
6794 coords.push(finger.pageX, finger.pageY);
6797 var x = Math.pow(coords[0] - coords[2], 2);
6798 var y = Math.pow(coords[1] - coords[3], 2);
6800 this.endDistance = Math.sqrt(x + y);
6802 this.scale = this.startScale + Math.floor(Math.log(this.endDistance / this.startDistance) / Math.log(1.1));
6804 if(!this.zoomable()){
6805 this.scale = this.startScale;
6813 onTouchEnd : function(e)
6815 this.pinching = false;
6816 this.dragable = false;
6820 process : function(file, crop)
6823 this.maskEl.mask(this.loadingText);
6826 this.xhr = new XMLHttpRequest();
6828 file.xhr = this.xhr;
6830 this.xhr.open(this.method, this.url, true);
6833 "Accept": "application/json",
6834 "Cache-Control": "no-cache",
6835 "X-Requested-With": "XMLHttpRequest"
6838 for (var headerName in headers) {
6839 var headerValue = headers[headerName];
6841 this.xhr.setRequestHeader(headerName, headerValue);
6847 this.xhr.onload = function()
6849 _this.xhrOnLoad(_this.xhr);
6852 this.xhr.onerror = function()
6854 _this.xhrOnError(_this.xhr);
6857 var formData = new FormData();
6859 formData.append('returnHTML', 'NO');
6862 formData.append('crop', crop);
6863 var blobBin = atob(crop.split(',')[1]);
6865 for(var i = 0; i < blobBin.length; i++) {
6866 array.push(blobBin.charCodeAt(i));
6868 var croppedFile =new Blob([new Uint8Array(array)], {type: this.cropType});
6869 formData.append(this.paramName, croppedFile, file.name);
6872 if(typeof(file.filename) != 'undefined'){
6873 formData.append('filename', file.filename);
6876 if(typeof(file.mimetype) != 'undefined'){
6877 formData.append('mimetype', file.mimetype);
6880 if(this.fireEvent('arrange', this, formData) != false){
6881 this.xhr.send(formData);
6885 xhrOnLoad : function(xhr)
6888 this.maskEl.unmask();
6891 if (xhr.readyState !== 4) {
6892 this.fireEvent('exception', this, xhr);
6896 var response = Roo.decode(xhr.responseText);
6898 if(!response.success){
6899 this.fireEvent('exception', this, xhr);
6903 var response = Roo.decode(xhr.responseText);
6905 this.fireEvent('upload', this, response);
6909 xhrOnError : function()
6912 this.maskEl.unmask();
6915 Roo.log('xhr on error');
6917 var response = Roo.decode(xhr.responseText);
6923 prepare : function(file)
6926 this.maskEl.mask(this.loadingText);
6932 if(typeof(file) === 'string'){
6933 this.loadCanvas(file);
6937 if(!file || !this.urlAPI){
6942 if(typeof(file.type) != 'undefined' && file.type.length != 0) {
6943 this.cropType = file.type;
6948 if(this.fireEvent('prepare', this, this.file) != false){
6950 var reader = new FileReader();
6952 reader.onload = function (e) {
6953 if (e.target.error) {
6954 Roo.log(e.target.error);
6958 var buffer = e.target.result,
6959 dataView = new DataView(buffer),
6961 maxOffset = dataView.byteLength - 4,
6965 if (dataView.getUint16(0) === 0xffd8) {
6966 while (offset < maxOffset) {
6967 markerBytes = dataView.getUint16(offset);
6969 if ((markerBytes >= 0xffe0 && markerBytes <= 0xffef) || markerBytes === 0xfffe) {
6970 markerLength = dataView.getUint16(offset + 2) + 2;
6971 if (offset + markerLength > dataView.byteLength) {
6972 Roo.log('Invalid meta data: Invalid segment size.');
6976 if(markerBytes == 0xffe1){
6977 _this.parseExifData(
6984 offset += markerLength;
6994 var url = _this.urlAPI.createObjectURL(_this.file);
6996 _this.loadCanvas(url);
7001 reader.readAsArrayBuffer(this.file);
7007 parseExifData : function(dataView, offset, length)
7009 var tiffOffset = offset + 10,
7013 if (dataView.getUint32(offset + 4) !== 0x45786966) {
7014 // No Exif data, might be XMP data instead
7018 // Check for the ASCII code for "Exif" (0x45786966):
7019 if (dataView.getUint32(offset + 4) !== 0x45786966) {
7020 // No Exif data, might be XMP data instead
7023 if (tiffOffset + 8 > dataView.byteLength) {
7024 Roo.log('Invalid Exif data: Invalid segment size.');
7027 // Check for the two null bytes:
7028 if (dataView.getUint16(offset + 8) !== 0x0000) {
7029 Roo.log('Invalid Exif data: Missing byte alignment offset.');
7032 // Check the byte alignment:
7033 switch (dataView.getUint16(tiffOffset)) {
7035 littleEndian = true;
7038 littleEndian = false;
7041 Roo.log('Invalid Exif data: Invalid byte alignment marker.');
7044 // Check for the TIFF tag marker (0x002A):
7045 if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) {
7046 Roo.log('Invalid Exif data: Missing TIFF marker.');
7049 // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
7050 dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
7055 tiffOffset + dirOffset,
7060 parseExifTags : function(dataView, tiffOffset, dirOffset, littleEndian)
7065 if (dirOffset + 6 > dataView.byteLength) {
7066 Roo.log('Invalid Exif data: Invalid directory offset.');
7069 tagsNumber = dataView.getUint16(dirOffset, littleEndian);
7070 dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
7071 if (dirEndOffset + 4 > dataView.byteLength) {
7072 Roo.log('Invalid Exif data: Invalid directory size.');
7075 for (i = 0; i < tagsNumber; i += 1) {
7079 dirOffset + 2 + 12 * i, // tag offset
7083 // Return the offset to the next directory:
7084 return dataView.getUint32(dirEndOffset, littleEndian);
7087 parseExifTag : function (dataView, tiffOffset, offset, littleEndian)
7089 var tag = dataView.getUint16(offset, littleEndian);
7091 this.exif[tag] = this.getExifValue(
7095 dataView.getUint16(offset + 2, littleEndian), // tag type
7096 dataView.getUint32(offset + 4, littleEndian), // tag length
7101 getExifValue : function (dataView, tiffOffset, offset, type, length, littleEndian)
7103 var tagType = Roo.panel.Cropbox.exifTagTypes[type],
7112 Roo.log('Invalid Exif data: Invalid tag type.');
7116 tagSize = tagType.size * length;
7117 // Determine if the value is contained in the dataOffset bytes,
7118 // or if the value at the dataOffset is a pointer to the actual data:
7119 dataOffset = tagSize > 4 ?
7120 tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8);
7121 if (dataOffset + tagSize > dataView.byteLength) {
7122 Roo.log('Invalid Exif data: Invalid data offset.');
7126 return tagType.getValue(dataView, dataOffset, littleEndian);
7129 for (i = 0; i < length; i += 1) {
7130 values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian);
7133 if (tagType.ascii) {
7135 // Concatenate the chars:
7136 for (i = 0; i < values.length; i += 1) {
7138 // Ignore the terminating NULL byte(s):
7139 if (c === '\u0000') {
7151 Roo.apply(Roo.panel.Cropbox, {
7153 'Orientation': 0x0112
7159 3: 180, //'bottom-right',
7160 // 4: 'bottom-left',
7162 6: 90, //'right-top',
7163 // 7: 'right-bottom',
7164 8: 270 //'left-bottom'
7168 // byte, 8-bit unsigned int:
7170 getValue: function (dataView, dataOffset) {
7171 return dataView.getUint8(dataOffset);
7175 // ascii, 8-bit byte:
7177 getValue: function (dataView, dataOffset) {
7178 return String.fromCharCode(dataView.getUint8(dataOffset));
7183 // short, 16 bit int:
7185 getValue: function (dataView, dataOffset, littleEndian) {
7186 return dataView.getUint16(dataOffset, littleEndian);
7190 // long, 32 bit int:
7192 getValue: function (dataView, dataOffset, littleEndian) {
7193 return dataView.getUint32(dataOffset, littleEndian);
7197 // rational = two long values, first is numerator, second is denominator:
7199 getValue: function (dataView, dataOffset, littleEndian) {
7200 return dataView.getUint32(dataOffset, littleEndian) /
7201 dataView.getUint32(dataOffset + 4, littleEndian);
7205 // slong, 32 bit signed int:
7207 getValue: function (dataView, dataOffset, littleEndian) {
7208 return dataView.getInt32(dataOffset, littleEndian);
7212 // srational, two slongs, first is numerator, second is denominator:
7214 getValue: function (dataView, dataOffset, littleEndian) {
7215 return dataView.getInt32(dataOffset, littleEndian) /
7216 dataView.getInt32(dataOffset + 4, littleEndian);
7226 cls : 'btn-group roo-upload-cropbox-rotate-left',
7227 action : 'rotate-left',
7231 cls : 'btn btn-default',
7232 html : '<i class="fa fa-undo"></i>'
7238 cls : 'btn-group roo-upload-cropbox-picture',
7243 cls : 'btn btn-default',
7244 html : '<i class="fa fa-picture-o"></i>'
7250 cls : 'btn-group roo-upload-cropbox-rotate-right',
7251 action : 'rotate-right',
7255 cls : 'btn btn-default',
7256 html : '<i class="fa fa-repeat"></i>'
7264 cls : 'btn-group roo-upload-cropbox-rotate-left',
7265 action : 'rotate-left',
7269 cls : 'btn btn-default',
7270 html : '<i class="fa fa-undo"></i>'
7276 cls : 'btn-group roo-upload-cropbox-download',
7277 action : 'download',
7281 cls : 'btn btn-default',
7282 html : '<i class="fa fa-download"></i>'
7288 cls : 'btn-group roo-upload-cropbox-crop',
7293 cls : 'btn btn-default',
7294 html : '<i class="fa fa-crop"></i>'
7300 cls : 'btn-group roo-upload-cropbox-trash',
7305 cls : 'btn btn-default',
7306 html : '<i class="fa fa-trash"></i>'
7312 cls : 'btn-group roo-upload-cropbox-rotate-right',
7313 action : 'rotate-right',
7317 cls : 'btn btn-default',
7318 html : '<i class="fa fa-repeat"></i>'
7326 cls : 'btn-group roo-upload-cropbox-rotate-left',
7327 action : 'rotate-left',
7331 cls : 'btn btn-default',
7332 html : '<i class="fa fa-undo"></i>'
7338 cls : 'btn-group roo-upload-cropbox-rotate-right',
7339 action : 'rotate-right',
7343 cls : 'btn btn-default',
7344 html : '<i class="fa fa-repeat"></i>'
7352 cls : 'btn-group roo-upload-cropbox-center',
7357 cls : 'btn btn-default',
7367 * Ext JS Library 1.1.1
7368 * Copyright(c) 2006-2007, Ext JS, LLC.
7370 * Originally Released Under LGPL - original licence link has changed is not relivant.
7373 * <script type="text/javascript">
7376 * @class Roo.panel.Tab
7377 * @extends Roo.util.Observable
7378 * A lightweight tab container.
7382 // basic tabs 1, built from existing content
7383 var tabs = new Roo.panel.Tab("tabs1");
7384 tabs.addTab("script", "View Script");
7385 tabs.addTab("markup", "View Markup");
7386 tabs.activate("script");
7388 // more advanced tabs, built from javascript
7389 var jtabs = new Roo.panel.Tab("jtabs");
7390 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
7392 // set up the UpdateManager
7393 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
7394 var updater = tab2.getUpdateManager();
7395 updater.setDefaultUrl("ajax1.htm");
7396 tab2.on('activate', updater.refresh, updater, true);
7398 // Use setUrl for Ajax loading
7399 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
7400 tab3.setUrl("ajax2.htm", null, true);
7403 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
7406 jtabs.activate("jtabs-1");
7409 * Create a new TabPanel.
7410 * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
7411 * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
7413 Roo.panel.Tab = function(container, config){
7415 * The container element for this TabPanel.
7418 this.el = Roo.get(container, true);
7420 if(typeof config == "boolean"){
7421 this.tabPosition = config ? "bottom" : "top";
7423 Roo.apply(this, config);
7426 if(this.tabPosition == "bottom"){
7427 this.bodyEl = Roo.get(this.createBody(this.el.dom));
7428 this.el.addClass("x-tabs-bottom");
7430 this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
7431 this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
7432 this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
7434 Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
7436 if(this.tabPosition != "bottom"){
7437 /** The body element that contains {@link Roo.panel.TabItem} bodies. +
7440 this.bodyEl = Roo.get(this.createBody(this.el.dom));
7441 this.el.addClass("x-tabs-top");
7445 this.bodyEl.setStyle("position", "relative");
7448 this.activateDelegate = this.activate.createDelegate(this);
7453 * Fires when the active tab changes
7454 * @param {Roo.panel.Tab} this
7455 * @param {Roo.panel.TabItem} activePanel The new active tab
7459 * @event beforetabchange
7460 * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
7461 * @param {Roo.panel.Tab} this
7462 * @param {Object} e Set cancel to true on this object to cancel the tab change
7463 * @param {Roo.panel.TabItem} tab The tab being changed to
7465 "beforetabchange" : true
7468 Roo.EventManager.onWindowResize(this.onResize, this);
7469 this.cpad = this.el.getPadding("lr");
7470 this.hiddenCount = 0;
7473 // toolbar on the tabbar support...
7475 var tcfg = this.toolbar;
7476 tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');
7477 this.toolbar = new Roo.Toolbar(tcfg);
7479 var tbl = tcfg.container.child('table', true);
7480 tbl.setAttribute('width', '100%');
7487 Roo.panel.Tab.superclass.constructor.call(this);
7490 Roo.extend(Roo.panel.Tab, Roo.util.Observable, {
7492 *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
7494 tabPosition : "top",
7496 *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
7498 currentTabWidth : 0,
7500 *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
7504 *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
7508 *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
7510 preferredTabWidth : 175,
7512 *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
7516 *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
7518 monitorResize : true,
7520 *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar.
7525 * Creates a new {@link Roo.panel.TabItem} by looking for an existing element with the provided id -- if it's not found it creates one.
7526 * @param {String} id The id of the div to use <b>or create</b>
7527 * @param {String} text The text for the tab
7528 * @param {String} content (optional) Content to put in the TabPanelItem body
7529 * @param {Boolean} closable (optional) True to create a close icon on the tab
7530 * @return {Roo.panel.TabItem} The created TabPanelItem
7532 addTab : function(id, text, content, closable){
7533 var item = new Roo.panel.TabItem(this, id, text, closable);
7534 this.addTabItem(item);
7536 item.setContent(content);
7542 * Returns the {@link Roo.panel.TabItem} with the specified id/index
7543 * @param {String/Number} id The id or index of the TabPanelItem to fetch.
7544 * @return {Roo.panel.TabItem}
7546 getTab : function(id){
7547 return this.items[id];
7551 * Hides the {@link Roo.panel.TabItem} with the specified id/index
7552 * @param {String/Number} id The id or index of the TabPanelItem to hide.
7554 hideTab : function(id){
7555 var t = this.items[id];
7559 this.autoSizeTabs();
7564 * "Unhides" the {@link Roo.panel.TabItem} with the specified id/index.
7565 * @param {String/Number} id The id or index of the TabPanelItem to unhide.
7567 unhideTab : function(id){
7568 var t = this.items[id];
7572 this.autoSizeTabs();
7577 * Adds an existing {@link Roo.panel.TabItem}.
7578 * @param {Roo.panel.TabItem} item The TabPanelItem to add
7580 addTabItem : function(item){
7581 this.items[item.id] = item;
7582 this.items.push(item);
7583 if(this.resizeTabs){
7584 item.setWidth(this.currentTabWidth || this.preferredTabWidth);
7585 this.autoSizeTabs();
7592 * Removes a {@link Roo.panel.TabItem}.
7593 * @param {String/Number} id The id or index of the TabPanelItem to remove.
7595 removeTab : function(id){
7596 var items = this.items;
7597 var tab = items[id];
7598 if(!tab) { return; }
7599 var index = items.indexOf(tab);
7600 if(this.active == tab && items.length > 1){
7601 var newTab = this.getNextAvailable(index);
7606 this.stripEl.dom.removeChild(tab.pnode.dom);
7607 if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
7608 this.bodyEl.dom.removeChild(tab.bodyEl.dom);
7610 items.splice(index, 1);
7611 delete this.items[tab.id];
7612 tab.fireEvent("close", tab);
7613 tab.purgeListeners();
7614 this.autoSizeTabs();
7617 getNextAvailable : function(start){
7618 var items = this.items;
7620 // look for a next tab that will slide over to
7621 // replace the one being removed
7622 while(index < items.length){
7623 var item = items[++index];
7624 if(item && !item.isHidden()){
7628 // if one isn't found select the previous tab (on the left)
7631 var item = items[--index];
7632 if(item && !item.isHidden()){
7640 * Disables a {@link Roo.panel.TabItem}. It cannot be the active tab, if it is this call is ignored.
7641 * @param {String/Number} id The id or index of the TabPanelItem to disable.
7643 disableTab : function(id){
7644 var tab = this.items[id];
7645 if(tab && this.active != tab){
7651 * Enables a {@link Roo.panel.TabItem} that is disabled.
7652 * @param {String/Number} id The id or index of the TabPanelItem to enable.
7654 enableTab : function(id){
7655 var tab = this.items[id];
7660 * Activates a {@link Roo.panel.TabItem}. The currently active one will be deactivated.
7661 * @param {String/Number} id The id or index of the TabPanelItem to activate.
7662 * @return {Roo.panel.TabItem} The TabPanelItem.
7664 activate : function(id){
7665 var tab = this.items[id];
7669 if(tab == this.active || tab.disabled){
7673 this.fireEvent("beforetabchange", this, e, tab);
7674 if(e.cancel !== true && !tab.disabled){
7678 this.active = this.items[id];
7680 this.fireEvent("tabchange", this, this.active);
7686 * Gets the active {@link Roo.panel.TabItem}.
7687 * @return {Roo.panel.TabItem} The active TabPanelItem or null if none are active.
7689 getActiveTab : function(){
7694 * Updates the tab body element to fit the height of the container element
7695 * for overflow scrolling
7696 * @param {Number} targetHeight (optional) Override the starting height from the elements height
7698 syncHeight : function(targetHeight){
7699 var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
7700 var bm = this.bodyEl.getMargins();
7701 var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
7702 this.bodyEl.setHeight(newHeight);
7706 onResize : function(){
7707 if(this.monitorResize){
7708 this.autoSizeTabs();
7713 * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
7715 beginUpdate : function(){
7716 this.updating = true;
7720 * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
7722 endUpdate : function(){
7723 this.updating = false;
7724 this.autoSizeTabs();
7728 * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
7730 autoSizeTabs : function(){
7731 var count = this.items.length;
7732 var vcount = count - this.hiddenCount;
7733 if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
7736 var w = Math.max(this.el.getWidth() - this.cpad, 10);
7737 var availWidth = Math.floor(w / vcount);
7738 var b = this.stripBody;
7739 if(b.getWidth() > w){
7740 var tabs = this.items;
7741 this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
7742 if(availWidth < this.minTabWidth){
7743 /*if(!this.sleft){ // incomplete scrolling code
7744 this.createScrollButtons();
7747 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
7750 if(this.currentTabWidth < this.preferredTabWidth){
7751 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
7757 * Returns the number of tabs in this TabPanel.
7760 getCount : function(){
7761 return this.items.length;
7765 * Resizes all the tabs to the passed width
7766 * @param {Number} The new width
7768 setTabWidth : function(width){
7769 this.currentTabWidth = width;
7770 for(var i = 0, len = this.items.length; i < len; i++) {
7771 if(!this.items[i].isHidden()) {
7772 this.items[i].setWidth(width);
7778 * Destroys this TabPanel
7779 * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
7781 destroy : function(removeEl){
7782 Roo.EventManager.removeResizeListener(this.onResize, this);
7783 for(var i = 0, len = this.items.length; i < len; i++){
7784 this.items[i].purgeListeners();
7786 if(removeEl === true){
7795 Roo.panel.Tab.prototype.createStripList = function(strip){
7796 // div wrapper for retard IE
7797 // returns the "tr" element.
7798 strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
7799 '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
7800 '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
7801 return strip.firstChild.firstChild.firstChild.firstChild;
7804 Roo.panel.Tab.prototype.createBody = function(container){
7805 var body = document.createElement("div");
7806 Roo.id(body, "tab-body");
7807 Roo.fly(body).addClass("x-tabs-body");
7808 container.appendChild(body);
7812 Roo.panel.Tab.prototype.createItemBody = function(bodyEl, id){
7813 var body = Roo.getDom(id);
7815 body = document.createElement("div");
7818 Roo.fly(body).addClass("x-tabs-item-body");
7819 bodyEl.insertBefore(body, bodyEl.firstChild);
7823 Roo.panel.Tab.prototype.createStripElements = function(stripEl, text, closable){
7824 var td = document.createElement("td");
7825 stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
7826 //stripEl.appendChild(td);
7828 td.className = "x-tabs-closable";
7830 this.closeTpl = new Roo.Template(
7831 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
7832 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
7833 '<div unselectable="on" class="close-icon"> </div></em></span></a>'
7836 var el = this.closeTpl.overwrite(td, {"text": text});
7837 var close = el.getElementsByTagName("div")[0];
7838 var inner = el.getElementsByTagName("em")[0];
7839 return {"el": el, "close": close, "inner": inner};
7842 this.tabTpl = new Roo.Template(
7843 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
7844 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
7847 var el = this.tabTpl.overwrite(td, {"text": text});
7848 var inner = el.getElementsByTagName("em")[0];
7849 return {"el": el, "inner": inner};
7852 * @class Roo.panel.TabItem
7853 * @extends Roo.util.Observable
7854 * Represents an individual item (tab plus body) in a TabPanel.
7855 * @param {Roo.panel.Tab} tabPanel The {@link Roo.panel.Tab} this TabPanelItem belongs to
7856 * @param {String} id The id of this TabPanelItem
7857 * @param {String} text The text for the tab of this TabPanelItem
7858 * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
7860 Roo.panel.TabItem = function(tabPanel, id, text, closable){
7862 * The {@link Roo.panel.Tab} this TabPanelItem belongs to
7863 * @type Roo.panel.Tab
7865 this.tabPanel = tabPanel;
7867 * The id for this TabPanelItem
7872 this.disabled = false;
7876 this.loaded = false;
7877 this.closable = closable;
7880 * The body element for this TabPanelItem.
7883 this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
7884 this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
7885 this.bodyEl.setStyle("display", "block");
7886 this.bodyEl.setStyle("zoom", "1");
7889 var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
7891 this.el = Roo.get(els.el, true);
7892 this.inner = Roo.get(els.inner, true);
7893 this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
7894 this.pnode = Roo.get(els.el.parentNode, true);
7895 this.el.on("mousedown", this.onTabMouseDown, this);
7896 this.el.on("click", this.onTabClick, this);
7899 var c = Roo.get(els.close, true);
7900 c.dom.title = this.closeText;
7901 c.addClassOnOver("close-over");
7902 c.on("click", this.closeClick, this);
7908 * Fires when this tab becomes the active tab.
7909 * @param {Roo.panel.Tab} tabPanel The parent TabPanel
7910 * @param {Roo.panel.TabItem} this
7914 * @event beforeclose
7915 * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
7916 * @param {Roo.panel.TabItem} this
7917 * @param {Object} e Set cancel to true on this object to cancel the close.
7919 "beforeclose": true,
7922 * Fires when this tab is closed.
7923 * @param {Roo.panel.TabItem} this
7928 * Fires when this tab is no longer the active tab.
7929 * @param {Roo.panel.Tab} tabPanel The parent TabPanel
7930 * @param {Roo.panel.TabItem} this
7934 this.hidden = false;
7936 Roo.panel.TabItem.superclass.constructor.call(this);
7939 Roo.extend(Roo.panel.TabItem, Roo.util.Observable, {
7940 purgeListeners : function(){
7941 Roo.util.Observable.prototype.purgeListeners.call(this);
7942 this.el.removeAllListeners();
7945 * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
7948 this.pnode.addClass("on");
7951 this.tabPanel.stripWrap.repaint();
7953 this.fireEvent("activate", this.tabPanel, this);
7957 * Returns true if this tab is the active tab.
7960 isActive : function(){
7961 return this.tabPanel.getActiveTab() == this;
7965 * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
7968 this.pnode.removeClass("on");
7970 this.fireEvent("deactivate", this.tabPanel, this);
7973 hideAction : function(){
7975 this.bodyEl.setStyle("position", "absolute");
7976 this.bodyEl.setLeft("-20000px");
7977 this.bodyEl.setTop("-20000px");
7980 showAction : function(){
7981 this.bodyEl.setStyle("position", "relative");
7982 this.bodyEl.setTop("");
7983 this.bodyEl.setLeft("");
7988 * Set the tooltip for the tab.
7989 * @param {String} tooltip The tab's tooltip
7991 setTooltip : function(text){
7992 if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
7993 this.textEl.dom.qtip = text;
7994 this.textEl.dom.removeAttribute('title');
7996 this.textEl.dom.title = text;
8000 onTabClick : function(e){
8002 this.tabPanel.activate(this.id);
8005 onTabMouseDown : function(e){
8007 this.tabPanel.activate(this.id);
8010 getWidth : function(){
8011 return this.inner.getWidth();
8014 setWidth : function(width){
8015 var iwidth = width - this.pnode.getPadding("lr");
8016 this.inner.setWidth(iwidth);
8017 this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
8018 this.pnode.setWidth(width);
8022 * Show or hide the tab
8023 * @param {Boolean} hidden True to hide or false to show.
8025 setHidden : function(hidden){
8026 this.hidden = hidden;
8027 this.pnode.setStyle("display", hidden ? "none" : "");
8031 * Returns true if this tab is "hidden"
8034 isHidden : function(){
8039 * Returns the text for this tab
8042 getText : function(){
8046 autoSize : function(){
8047 //this.el.beginMeasure();
8048 this.textEl.setWidth(1);
8050 * #2804 [new] Tabs in Roojs
8051 * increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
8053 this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
8054 //this.el.endMeasure();
8058 * Sets the text for the tab (Note: this also sets the tooltip text)
8059 * @param {String} text The tab's text and tooltip
8061 setText : function(text){
8063 this.textEl.update(text);
8064 this.setTooltip(text);
8065 if(!this.tabPanel.resizeTabs){
8070 * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
8072 activate : function(){
8073 this.tabPanel.activate(this.id);
8077 * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
8079 disable : function(){
8080 if(this.tabPanel.active != this){
8081 this.disabled = true;
8082 this.pnode.addClass("disabled");
8087 * Enables this TabPanelItem if it was previously disabled.
8089 enable : function(){
8090 this.disabled = false;
8091 this.pnode.removeClass("disabled");
8095 * Sets the content for this TabPanelItem.
8096 * @param {String} content The content
8097 * @param {Boolean} loadScripts true to look for and load scripts
8099 setContent : function(content, loadScripts){
8100 this.bodyEl.update(content, loadScripts);
8104 * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
8105 * @return {Roo.UpdateManager} The UpdateManager
8107 getUpdateManager : function(){
8108 return this.bodyEl.getUpdateManager();
8112 * Set a URL to be used to load the content for this TabPanelItem.
8113 * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
8114 * @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)
8115 * @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)
8116 * @return {Roo.UpdateManager} The UpdateManager
8118 setUrl : function(url, params, loadOnce){
8119 if(this.refreshDelegate){
8120 this.un('activate', this.refreshDelegate);
8122 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
8123 this.on("activate", this.refreshDelegate);
8124 return this.bodyEl.getUpdateManager();
8128 _handleRefresh : function(url, params, loadOnce){
8129 if(!loadOnce || !this.loaded){
8130 var updater = this.bodyEl.getUpdateManager();
8131 updater.update(url, params, this._setLoaded.createDelegate(this));
8136 * Forces a content refresh from the URL specified in the {@link #setUrl} method.
8137 * Will fail silently if the setUrl method has not been called.
8138 * This does not activate the panel, just updates its content.
8140 refresh : function(){
8141 if(this.refreshDelegate){
8142 this.loaded = false;
8143 this.refreshDelegate();
8148 _setLoaded : function(){
8153 closeClick : function(e){
8156 this.fireEvent("beforeclose", this, o);
8157 if(o.cancel !== true){
8158 this.tabPanel.removeTab(this.id);
8162 * The text displayed in the tooltip for the close icon.
8165 closeText : "Close this tab"
8169 Roo.panel.Tab.prototype.createStrip = function(container){
8170 var strip = document.createElement("div");
8171 strip.className = "x-tabs-wrap";
8172 container.appendChild(strip);
8176 * Ext JS Library 1.1.1
8177 * Copyright(c) 2006-2007, Ext JS, LLC.
8179 * Originally Released Under LGPL - original licence link has changed is not relivant.
8182 * <script type="text/javascript">
8187 * @extends Roo.util.Observable
8188 * Simple Button class
8189 * @cfg {String} text The button text
8190 * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
8191 * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
8192 * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
8193 * @cfg {Object} scope The scope of the handler
8194 * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
8195 * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
8196 * @cfg {Boolean} hidden True to start hidden (defaults to false)
8197 * @cfg {Boolean} disabled True to start disabled (defaults to false)
8198 * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
8199 * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
8200 applies if enableToggle = true)
8201 * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
8202 * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
8203 an {@link Roo.util.ClickRepeater} config object (defaults to false).
8205 * Create a new button
8206 * @param {Object} config The config object
8208 Roo.Button = function(renderTo, config)
8212 renderTo = config.renderTo || false;
8215 Roo.apply(this, config);
8219 * Fires when this button is clicked
8220 * @param {Button} this
8221 * @param {EventObject} e The click event
8226 * Fires when the "pressed" state of this button changes (only if enableToggle = true)
8227 * @param {Button} this
8228 * @param {Boolean} pressed
8233 * Fires when the mouse hovers over the button
8234 * @param {Button} this
8235 * @param {Event} e The event object
8240 * Fires when the mouse exits the button
8241 * @param {Button} this
8242 * @param {Event} e The event object
8247 * Fires when the button is rendered
8248 * @param {Button} this
8253 this.menu = Roo.menu.MenuMgr.get(this.menu);
8255 // register listeners first!! - so render can be captured..
8256 Roo.util.Observable.call(this);
8258 this.render(renderTo);
8264 Roo.extend(Roo.Button, Roo.util.Observable, {
8270 * Read-only. True if this button is hidden
8275 * Read-only. True if this button is disabled
8280 * Read-only. True if this button is pressed (only if enableToggle = true)
8286 * @cfg {Number} tabIndex
8287 * The DOM tabIndex for this button (defaults to undefined)
8289 tabIndex : undefined,
8292 * @cfg {Boolean} enableToggle
8293 * True to enable pressed/not pressed toggling (defaults to false)
8295 enableToggle: false,
8297 * @cfg {Roo.menu.Menu} menu
8298 * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
8302 * @cfg {String} menuAlign
8303 * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
8305 menuAlign : "tl-bl?",
8308 * @cfg {String} iconCls
8309 * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
8311 iconCls : undefined,
8313 * @cfg {String} type
8314 * The button's type, corresponding to the DOM input element type attribute. Either "submit," "reset" or "button" (default).
8319 menuClassTarget: 'tr',
8322 * @cfg {String} clickEvent
8323 * The type of event to map to the button's event handler (defaults to 'click')
8325 clickEvent : 'click',
8328 * @cfg {Boolean} handleMouseEvents
8329 * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
8331 handleMouseEvents : true,
8334 * @cfg {String} tooltipType
8335 * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
8337 tooltipType : 'qtip',
8341 * A CSS class to apply to the button's main element.
8345 * @cfg {Roo.Template} template (Optional)
8346 * An {@link Roo.Template} with which to create the Button's main element. This Template must
8347 * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
8348 * require code modifications if required elements (e.g. a button) aren't present.
8352 render : function(renderTo){
8354 if(this.hideParent){
8355 this.parentEl = Roo.get(renderTo);
8359 if(!Roo.Button.buttonTemplate){
8360 // hideous table template
8361 Roo.Button.buttonTemplate = new Roo.Template(
8362 '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
8363 '<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>',
8364 "</tr></tbody></table>");
8366 this.template = Roo.Button.buttonTemplate;
8368 btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
8369 var btnEl = btn.child("button:first");
8370 btnEl.on('focus', this.onFocus, this);
8371 btnEl.on('blur', this.onBlur, this);
8373 btn.addClass(this.cls);
8376 btnEl.setStyle('background-image', 'url(' +this.icon +')');
8379 btnEl.addClass(this.iconCls);
8381 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
8384 if(this.tabIndex !== undefined){
8385 btnEl.dom.tabIndex = this.tabIndex;
8388 if(typeof this.tooltip == 'object'){
8389 Roo.QuickTips.tips(Roo.apply({
8393 btnEl.dom[this.tooltipType] = this.tooltip;
8397 btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
8401 this.el.dom.id = this.el.id = this.id;
8404 this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
8405 this.menu.on("show", this.onMenuShow, this);
8406 this.menu.on("hide", this.onMenuHide, this);
8408 btn.addClass("x-btn");
8409 if(Roo.isIE && !Roo.isIE7){
8410 this.autoWidth.defer(1, this);
8414 if(this.handleMouseEvents){
8415 btn.on("mouseover", this.onMouseOver, this);
8416 btn.on("mouseout", this.onMouseOut, this);
8417 btn.on("mousedown", this.onMouseDown, this);
8419 btn.on(this.clickEvent, this.onClick, this);
8420 //btn.on("mouseup", this.onMouseUp, this);
8427 Roo.ButtonToggleMgr.register(this);
8429 this.el.addClass("x-btn-pressed");
8432 var repeater = new Roo.util.ClickRepeater(btn,
8433 typeof this.repeat == "object" ? this.repeat : {}
8435 repeater.on("click", this.onClick, this);
8438 this.fireEvent('render', this);
8442 * Returns the button's underlying element
8443 * @return {Roo.Element} The element
8450 * Destroys this Button and removes any listeners.
8452 destroy : function(){
8453 Roo.ButtonToggleMgr.unregister(this);
8454 this.el.removeAllListeners();
8455 this.purgeListeners();
8460 autoWidth : function(){
8462 this.el.setWidth("auto");
8463 if(Roo.isIE7 && Roo.isStrict){
8464 var ib = this.el.child('button');
8465 if(ib && ib.getWidth() > 20){
8467 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
8472 this.el.beginMeasure();
8474 if(this.el.getWidth() < this.minWidth){
8475 this.el.setWidth(this.minWidth);
8478 this.el.endMeasure();
8485 * Assigns this button's click handler
8486 * @param {Function} handler The function to call when the button is clicked
8487 * @param {Object} scope (optional) Scope for the function passed in
8489 setHandler : function(handler, scope){
8490 this.handler = handler;
8495 * Sets this button's text
8496 * @param {String} text The button text
8498 setText : function(text){
8501 this.el.child("td.x-btn-center button.x-btn-text").update(text);
8507 * Gets the text for this button
8508 * @return {String} The button text
8510 getText : function(){
8518 this.hidden = false;
8520 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
8530 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
8535 * Convenience function for boolean show/hide
8536 * @param {Boolean} visible True to show, false to hide
8538 setVisible: function(visible){
8546 * Similar to toggle, but does not trigger event.
8547 * @param {Boolean} state [required] Force a particular state
8549 setPressed : function(state)
8551 if(state != this.pressed){
8553 this.el.addClass("x-btn-pressed");
8554 this.pressed = true;
8556 this.el.removeClass("x-btn-pressed");
8557 this.pressed = false;
8563 * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
8564 * @param {Boolean} state (optional) Force a particular state
8566 toggle : function(state){
8567 state = state === undefined ? !this.pressed : state;
8568 if(state != this.pressed){
8570 this.el.addClass("x-btn-pressed");
8571 this.pressed = true;
8572 this.fireEvent("toggle", this, true);
8574 this.el.removeClass("x-btn-pressed");
8575 this.pressed = false;
8576 this.fireEvent("toggle", this, false);
8578 if(this.toggleHandler){
8579 this.toggleHandler.call(this.scope || this, this, state);
8590 this.el.child('button:first').focus();
8594 * Disable this button
8596 disable : function(){
8598 this.el.addClass("x-btn-disabled");
8600 this.disabled = true;
8604 * Enable this button
8606 enable : function(){
8608 this.el.removeClass("x-btn-disabled");
8610 this.disabled = false;
8614 * Convenience function for boolean enable/disable
8615 * @param {Boolean} enabled True to enable, false to disable
8617 setDisabled : function(v){
8618 this[v !== true ? "enable" : "disable"]();
8622 onClick : function(e)
8631 if(this.enableToggle){
8634 if(this.menu && !this.menu.isVisible()){
8635 this.menu.show(this.el, this.menuAlign);
8637 this.fireEvent("click", this, e);
8639 this.el.removeClass("x-btn-over");
8640 this.handler.call(this.scope || this, this, e);
8645 onMouseOver : function(e){
8647 this.el.addClass("x-btn-over");
8648 this.fireEvent('mouseover', this, e);
8652 onMouseOut : function(e){
8653 if(!e.within(this.el, true)){
8654 this.el.removeClass("x-btn-over");
8655 this.fireEvent('mouseout', this, e);
8659 onFocus : function(e){
8661 this.el.addClass("x-btn-focus");
8665 onBlur : function(e){
8666 this.el.removeClass("x-btn-focus");
8669 onMouseDown : function(e){
8670 if(!this.disabled && e.button == 0){
8671 this.el.addClass("x-btn-click");
8672 Roo.get(document).on('mouseup', this.onMouseUp, this);
8676 onMouseUp : function(e){
8678 this.el.removeClass("x-btn-click");
8679 Roo.get(document).un('mouseup', this.onMouseUp, this);
8683 onMenuShow : function(e){
8684 this.el.addClass("x-btn-menu-active");
8687 onMenuHide : function(e){
8688 this.el.removeClass("x-btn-menu-active");
8692 // Private utility class used by Button
8693 Roo.ButtonToggleMgr = function(){
8696 function toggleGroup(btn, state){
8698 var g = groups[btn.toggleGroup];
8699 for(var i = 0, l = g.length; i < l; i++){
8708 register : function(btn){
8709 if(!btn.toggleGroup){
8712 var g = groups[btn.toggleGroup];
8714 g = groups[btn.toggleGroup] = [];
8717 btn.on("toggle", toggleGroup);
8720 unregister : function(btn){
8721 if(!btn.toggleGroup){
8724 var g = groups[btn.toggleGroup];
8727 btn.un("toggle", toggleGroup);
8733 * Ext JS Library 1.1.1
8734 * Copyright(c) 2006-2007, Ext JS, LLC.
8736 * Originally Released Under LGPL - original licence link has changed is not relivant.
8739 * <script type="text/javascript">
8743 * @class Roo.SplitButton
8744 * @extends Roo.Button
8745 * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
8746 * click event of the button. Typically this would be used to display a dropdown menu that provides additional
8747 * options to the primary button action, but any custom handler can provide the arrowclick implementation.
8748 * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
8749 * @cfg {String} arrowTooltip The title attribute of the arrow
8751 * Create a new menu button
8752 * @param {String/HTMLElement/Element} renderTo The element to append the button to
8753 * @param {Object} config The config object
8755 Roo.SplitButton = function(renderTo, config){
8756 Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
8759 * Fires when this button's arrow is clicked
8760 * @param {SplitButton} this
8761 * @param {EventObject} e The click event
8763 this.addEvents({"arrowclick":true});
8766 Roo.extend(Roo.SplitButton, Roo.Button, {
8767 render : function(renderTo){
8768 // this is one sweet looking template!
8769 var tpl = new Roo.Template(
8770 '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
8771 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
8772 '<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>',
8773 "</tbody></table></td><td>",
8774 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
8775 '<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>',
8776 "</tbody></table></td></tr></table>"
8778 var btn = tpl.append(renderTo, [this.text, this.type], true);
8779 var btnEl = btn.child("button");
8781 btn.addClass(this.cls);
8784 btnEl.setStyle('background-image', 'url(' +this.icon +')');
8787 btnEl.addClass(this.iconCls);
8789 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
8793 if(this.handleMouseEvents){
8794 btn.on("mouseover", this.onMouseOver, this);
8795 btn.on("mouseout", this.onMouseOut, this);
8796 btn.on("mousedown", this.onMouseDown, this);
8797 btn.on("mouseup", this.onMouseUp, this);
8799 btn.on(this.clickEvent, this.onClick, this);
8801 if(typeof this.tooltip == 'object'){
8802 Roo.QuickTips.tips(Roo.apply({
8806 btnEl.dom[this.tooltipType] = this.tooltip;
8809 if(this.arrowTooltip){
8810 btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
8819 this.el.addClass("x-btn-pressed");
8821 if(Roo.isIE && !Roo.isIE7){
8822 this.autoWidth.defer(1, this);
8827 this.menu.on("show", this.onMenuShow, this);
8828 this.menu.on("hide", this.onMenuHide, this);
8830 this.fireEvent('render', this);
8834 autoWidth : function(){
8836 var tbl = this.el.child("table:first");
8837 var tbl2 = this.el.child("table:last");
8838 this.el.setWidth("auto");
8839 tbl.setWidth("auto");
8840 if(Roo.isIE7 && Roo.isStrict){
8841 var ib = this.el.child('button:first');
8842 if(ib && ib.getWidth() > 20){
8844 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
8849 this.el.beginMeasure();
8851 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
8852 tbl.setWidth(this.minWidth-tbl2.getWidth());
8855 this.el.endMeasure();
8858 this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
8862 * Sets this button's click handler
8863 * @param {Function} handler The function to call when the button is clicked
8864 * @param {Object} scope (optional) Scope for the function passed above
8866 setHandler : function(handler, scope){
8867 this.handler = handler;
8872 * Sets this button's arrow click handler
8873 * @param {Function} handler The function to call when the arrow is clicked
8874 * @param {Object} scope (optional) Scope for the function passed above
8876 setArrowHandler : function(handler, scope){
8877 this.arrowHandler = handler;
8886 this.el.child("button:first").focus();
8891 onClick : function(e){
8894 if(e.getTarget(".x-btn-menu-arrow-wrap")){
8895 if(this.menu && !this.menu.isVisible()){
8896 this.menu.show(this.el, this.menuAlign);
8898 this.fireEvent("arrowclick", this, e);
8899 if(this.arrowHandler){
8900 this.arrowHandler.call(this.scope || this, this, e);
8903 this.fireEvent("click", this, e);
8905 this.handler.call(this.scope || this, this, e);
8911 onMouseDown : function(e){
8913 Roo.fly(e.getTarget("table")).addClass("x-btn-click");
8917 onMouseUp : function(e){
8918 Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
8924 Roo.MenuButton = Roo.SplitButton;/*
8926 * Ext JS Library 1.1.1
8927 * Copyright(c) 2006-2007, Ext JS, LLC.
8929 * Originally Released Under LGPL - original licence link has changed is not relivant.
8932 * <script type="text/javascript">
8936 * @class Roo.Toolbar
8937 * @children Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
8938 * Basic Toolbar class.
8940 * Creates a new Toolbar
8941 * @param {Object} container The config object
8943 Roo.Toolbar = function(container, buttons, config)
8945 /// old consturctor format still supported..
8946 if(container instanceof Array){ // omit the container for later rendering
8947 buttons = container;
8951 if (typeof(container) == 'object' && container.xtype) {
8953 container = config.container;
8954 buttons = config.buttons || []; // not really - use items!!
8957 if (config && config.items) {
8958 xitems = config.items;
8959 delete config.items;
8961 Roo.apply(this, config);
8962 this.buttons = buttons;
8965 this.render(container);
8967 this.xitems = xitems;
8968 Roo.each(xitems, function(b) {
8974 Roo.Toolbar.prototype = {
8976 * @cfg {Array} items
8977 * array of button configs or elements to add (will be converted to a MixedCollection)
8981 * @cfg {String/HTMLElement/Element} container
8982 * The id or element that will contain the toolbar
8985 render : function(ct){
8986 this.el = Roo.get(ct);
8988 this.el.addClass(this.cls);
8990 // using a table allows for vertical alignment
8991 // 100% width is needed by Safari...
8992 this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
8993 this.tr = this.el.child("tr", true);
8995 this.items = new Roo.util.MixedCollection(false, function(o){
8996 return o.id || ("item" + (++autoId));
8999 this.add.apply(this, this.buttons);
9000 delete this.buttons;
9005 * Adds element(s) to the toolbar -- this function takes a variable number of
9006 * arguments of mixed type and adds them to the toolbar.
9007 * @param {Mixed} arg1 The following types of arguments are all valid:<br />
9009 * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
9010 * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
9011 * <li>Field: Any form field (equivalent to {@link #addField})</li>
9012 * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
9013 * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
9014 * Note that there are a few special strings that are treated differently as explained nRoo.</li>
9015 * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
9016 * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
9017 * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
9019 * @param {Mixed} arg2
9020 * @param {Mixed} etc.
9023 var a = arguments, l = a.length;
9024 for(var i = 0; i < l; i++){
9029 _add : function(el) {
9032 el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
9035 if (el.applyTo){ // some kind of form field
9036 return this.addField(el);
9038 if (el.render){ // some kind of Toolbar.Item
9039 return this.addItem(el);
9041 if (typeof el == "string"){ // string
9042 if(el == "separator" || el == "-"){
9043 return this.addSeparator();
9046 return this.addSpacer();
9049 return this.addFill();
9051 return this.addText(el);
9054 if(el.tagName){ // element
9055 return this.addElement(el);
9057 if(typeof el == "object"){ // must be button config?
9058 return this.addButton(el);
9066 * Add an Xtype element
9067 * @param {Object} xtype Xtype Object
9068 * @return {Object} created Object
9070 addxtype : function(e){
9075 * Returns the Element for this toolbar.
9076 * @return {Roo.Element}
9084 * @return {Roo.Toolbar.Item} The separator item
9086 addSeparator : function(){
9087 return this.addItem(new Roo.Toolbar.Separator());
9091 * Adds a spacer element
9092 * @return {Roo.Toolbar.Spacer} The spacer item
9094 addSpacer : function(){
9095 return this.addItem(new Roo.Toolbar.Spacer());
9099 * Adds a fill element that forces subsequent additions to the right side of the toolbar
9100 * @return {Roo.Toolbar.Fill} The fill item
9102 addFill : function(){
9103 return this.addItem(new Roo.Toolbar.Fill());
9107 * Adds any standard HTML element to the toolbar
9108 * @param {String/HTMLElement/Element} el The element or id of the element to add
9109 * @return {Roo.Toolbar.Item} The element's item
9111 addElement : function(el){
9112 return this.addItem(new Roo.Toolbar.Item(el));
9115 * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
9116 * @type Roo.util.MixedCollection
9121 * Adds any Toolbar.Item or subclass
9122 * @param {Roo.Toolbar.Item} item
9123 * @return {Roo.Toolbar.Item} The item
9125 addItem : function(item){
9126 var td = this.nextBlock();
9128 this.items.add(item);
9133 * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
9134 * @param {Object/Array} config A button config or array of configs
9135 * @return {Roo.Toolbar.Button/Array}
9137 addButton : function(config){
9138 if(config instanceof Array){
9140 for(var i = 0, len = config.length; i < len; i++) {
9141 buttons.push(this.addButton(config[i]));
9146 if(!(config instanceof Roo.Toolbar.Button)){
9148 new Roo.Toolbar.SplitButton(config) :
9149 new Roo.Toolbar.Button(config);
9151 var td = this.nextBlock();
9158 * Adds text to the toolbar
9159 * @param {String} text The text to add
9160 * @return {Roo.Toolbar.Item} The element's item
9162 addText : function(text){
9163 return this.addItem(new Roo.Toolbar.TextItem(text));
9167 * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
9168 * @param {Number} index The index where the item is to be inserted
9169 * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
9170 * @return {Roo.Toolbar.Button/Item}
9172 insertButton : function(index, item){
9173 if(item instanceof Array){
9175 for(var i = 0, len = item.length; i < len; i++) {
9176 buttons.push(this.insertButton(index + i, item[i]));
9180 if (!(item instanceof Roo.Toolbar.Button)){
9181 item = new Roo.Toolbar.Button(item);
9183 var td = document.createElement("td");
9184 this.tr.insertBefore(td, this.tr.childNodes[index]);
9186 this.items.insert(index, item);
9191 * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
9192 * @param {Object} config
9193 * @return {Roo.Toolbar.Item} The element's item
9195 addDom : function(config, returnEl){
9196 var td = this.nextBlock();
9197 Roo.DomHelper.overwrite(td, config);
9198 var ti = new Roo.Toolbar.Item(td.firstChild);
9205 * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
9206 * @type Roo.util.MixedCollection
9211 * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
9212 * Note: the field should not have been rendered yet. For a field that has already been
9213 * rendered, use {@link #addElement}.
9214 * @param {Roo.form.Field} field
9215 * @return {Roo.ToolbarItem}
9219 addField : function(field) {
9222 this.fields = new Roo.util.MixedCollection(false, function(o){
9223 return o.id || ("item" + (++autoId));
9228 var td = this.nextBlock();
9230 var ti = new Roo.Toolbar.Item(td.firstChild);
9233 this.fields.add(field);
9244 this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
9245 this.el.child('div').hide();
9253 this.el.child('div').show();
9257 nextBlock : function(){
9258 var td = document.createElement("td");
9259 this.tr.appendChild(td);
9264 destroy : function(){
9265 if(this.items){ // rendered?
9266 Roo.destroy.apply(Roo, this.items.items);
9268 if(this.fields){ // rendered?
9269 Roo.destroy.apply(Roo, this.fields.items);
9271 Roo.Element.uncache(this.el, this.tr);
9276 * @class Roo.Toolbar.Item
9277 * The base class that other classes should extend in order to get some basic common toolbar item functionality.
9279 * Creates a new Item
9280 * @param {HTMLElement} el
9282 Roo.Toolbar.Item = function(el){
9284 if (typeof (el.xtype) != 'undefined') {
9289 this.el = Roo.getDom(el);
9290 this.id = Roo.id(this.el);
9291 this.hidden = false;
9296 * Fires when the button is rendered
9297 * @param {Button} this
9301 Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
9303 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
9304 //Roo.Toolbar.Item.prototype = {
9307 * Get this item's HTML Element
9308 * @return {HTMLElement}
9315 render : function(td){
9318 td.appendChild(this.el);
9320 this.fireEvent('render', this);
9324 * Removes and destroys this item.
9326 destroy : function(){
9327 this.td.parentNode.removeChild(this.td);
9334 this.hidden = false;
9335 this.td.style.display = "";
9343 this.td.style.display = "none";
9347 * Convenience function for boolean show/hide.
9348 * @param {Boolean} visible true to show/false to hide
9350 setVisible: function(visible){
9359 * Try to focus this item.
9362 Roo.fly(this.el).focus();
9366 * Disables this item.
9368 disable : function(){
9369 Roo.fly(this.td).addClass("x-item-disabled");
9370 this.disabled = true;
9371 this.el.disabled = true;
9375 * Enables this item.
9377 enable : function(){
9378 Roo.fly(this.td).removeClass("x-item-disabled");
9379 this.disabled = false;
9380 this.el.disabled = false;
9386 * @class Roo.Toolbar.Separator
9387 * @extends Roo.Toolbar.Item
9388 * A simple toolbar separator class
9390 * Creates a new Separator
9392 Roo.Toolbar.Separator = function(cfg){
9394 var s = document.createElement("span");
9395 s.className = "ytb-sep";
9400 Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
9402 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
9404 disable:Roo.emptyFn,
9409 * @class Roo.Toolbar.Spacer
9410 * @extends Roo.Toolbar.Item
9411 * A simple element that adds extra horizontal space to a toolbar.
9413 * Creates a new Spacer
9415 Roo.Toolbar.Spacer = function(cfg){
9416 var s = document.createElement("div");
9417 s.className = "ytb-spacer";
9421 Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
9423 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
9425 disable:Roo.emptyFn,
9430 * @class Roo.Toolbar.Fill
9431 * @extends Roo.Toolbar.Spacer
9432 * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
9434 * Creates a new Spacer
9436 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
9438 render : function(td){
9439 td.style.width = '100%';
9440 Roo.Toolbar.Fill.superclass.render.call(this, td);
9445 * @class Roo.Toolbar.TextItem
9446 * @extends Roo.Toolbar.Item
9447 * A simple class that renders text directly into a toolbar.
9449 * Creates a new TextItem
9450 * @cfg {string} text
9452 Roo.Toolbar.TextItem = function(cfg){
9453 var text = cfg || "";
9454 if (typeof(cfg) == 'object') {
9455 text = cfg.text || "";
9459 var s = document.createElement("span");
9460 s.className = "ytb-text";
9466 Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg || s);
9468 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
9472 disable:Roo.emptyFn,
9478 this.hidden = false;
9479 this.el.style.display = "";
9487 this.el.style.display = "none";
9493 * @class Roo.Toolbar.Button
9494 * @extends Roo.Button
9495 * A button that renders into a toolbar.
9497 * Creates a new Button
9498 * @param {Object} config A standard {@link Roo.Button} config object
9500 Roo.Toolbar.Button = function(config){
9501 Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
9503 Roo.extend(Roo.Toolbar.Button, Roo.Button,
9507 render : function(td){
9509 Roo.Toolbar.Button.superclass.render.call(this, td);
9513 * Removes and destroys this button
9515 destroy : function(){
9516 Roo.Toolbar.Button.superclass.destroy.call(this);
9517 this.td.parentNode.removeChild(this.td);
9524 this.hidden = false;
9525 this.td.style.display = "";
9533 this.td.style.display = "none";
9537 * Disables this item
9539 disable : function(){
9540 Roo.fly(this.td).addClass("x-item-disabled");
9541 this.disabled = true;
9547 enable : function(){
9548 Roo.fly(this.td).removeClass("x-item-disabled");
9549 this.disabled = false;
9553 Roo.ToolbarButton = Roo.Toolbar.Button;
9556 * @class Roo.Toolbar.SplitButton
9557 * @extends Roo.SplitButton
9558 * A menu button that renders into a toolbar.
9560 * Creates a new SplitButton
9561 * @param {Object} config A standard {@link Roo.SplitButton} config object
9563 Roo.Toolbar.SplitButton = function(config){
9564 Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
9566 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
9567 render : function(td){
9569 Roo.Toolbar.SplitButton.superclass.render.call(this, td);
9573 * Removes and destroys this button
9575 destroy : function(){
9576 Roo.Toolbar.SplitButton.superclass.destroy.call(this);
9577 this.td.parentNode.removeChild(this.td);
9584 this.hidden = false;
9585 this.td.style.display = "";
9593 this.td.style.display = "none";
9598 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
9600 * Ext JS Library 1.1.1
9601 * Copyright(c) 2006-2007, Ext JS, LLC.
9603 * Originally Released Under LGPL - original licence link has changed is not relivant.
9606 * <script type="text/javascript">
9610 * @class Roo.PagingToolbar
9611 * @extends Roo.Toolbar
9612 * @children Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
9613 * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
9615 * Create a new PagingToolbar
9616 * @param {Object} config The config object
9618 Roo.PagingToolbar = function(el, ds, config)
9620 // old args format still supported... - xtype is prefered..
9621 if (typeof(el) == 'object' && el.xtype) {
9622 // created from xtype...
9625 el = config.container;
9629 items = config.items;
9633 Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
9636 this.renderButtons(this.el);
9639 // supprot items array.
9641 Roo.each(items, function(e) {
9642 this.add(Roo.factory(e));
9647 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
9650 * @cfg {String/HTMLElement/Element} container
9651 * container The id or element that will contain the toolbar
9654 * @cfg {Boolean} displayInfo
9655 * True to display the displayMsg (defaults to false)
9660 * @cfg {Number} pageSize
9661 * The number of records to display per page (defaults to 20)
9665 * @cfg {String} displayMsg
9666 * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
9668 displayMsg : 'Displaying {0} - {1} of {2}',
9670 * @cfg {String} emptyMsg
9671 * The message to display when no records are found (defaults to "No data to display")
9673 emptyMsg : 'No data to display',
9675 * Customizable piece of the default paging text (defaults to "Page")
9678 beforePageText : "Page",
9680 * Customizable piece of the default paging text (defaults to "of %0")
9683 afterPageText : "of {0}",
9685 * Customizable piece of the default paging text (defaults to "First Page")
9688 firstText : "First Page",
9690 * Customizable piece of the default paging text (defaults to "Previous Page")
9693 prevText : "Previous Page",
9695 * Customizable piece of the default paging text (defaults to "Next Page")
9698 nextText : "Next Page",
9700 * Customizable piece of the default paging text (defaults to "Last Page")
9703 lastText : "Last Page",
9705 * Customizable piece of the default paging text (defaults to "Refresh")
9708 refreshText : "Refresh",
9711 renderButtons : function(el){
9712 Roo.PagingToolbar.superclass.render.call(this, el);
9713 this.first = this.addButton({
9714 tooltip: this.firstText,
9715 cls: "x-btn-icon x-grid-page-first",
9717 handler: this.onClick.createDelegate(this, ["first"])
9719 this.prev = this.addButton({
9720 tooltip: this.prevText,
9721 cls: "x-btn-icon x-grid-page-prev",
9723 handler: this.onClick.createDelegate(this, ["prev"])
9725 //this.addSeparator();
9726 this.add(this.beforePageText);
9727 this.field = Roo.get(this.addDom({
9732 cls: "x-grid-page-number"
9734 this.field.on("keydown", this.onPagingKeydown, this);
9735 this.field.on("focus", function(){this.dom.select();});
9736 this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
9737 this.field.setHeight(18);
9738 //this.addSeparator();
9739 this.next = this.addButton({
9740 tooltip: this.nextText,
9741 cls: "x-btn-icon x-grid-page-next",
9743 handler: this.onClick.createDelegate(this, ["next"])
9745 this.last = this.addButton({
9746 tooltip: this.lastText,
9747 cls: "x-btn-icon x-grid-page-last",
9749 handler: this.onClick.createDelegate(this, ["last"])
9751 //this.addSeparator();
9752 this.loading = this.addButton({
9753 tooltip: this.refreshText,
9754 cls: "x-btn-icon x-grid-loading",
9755 handler: this.onClick.createDelegate(this, ["refresh"])
9758 if(this.displayInfo){
9759 this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
9764 updateInfo : function(){
9766 var count = this.ds.getCount();
9767 var msg = count == 0 ?
9771 this.cursor+1, this.cursor+count, this.ds.getTotalCount()
9773 this.displayEl.update(msg);
9778 onLoad : function(ds, r, o){
9779 this.cursor = o.params ? o.params.start : 0;
9780 var d = this.getPageData(), ap = d.activePage, ps = d.pages;
9782 this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
9783 this.field.dom.value = ap;
9784 this.first.setDisabled(ap == 1);
9785 this.prev.setDisabled(ap == 1);
9786 this.next.setDisabled(ap == ps);
9787 this.last.setDisabled(ap == ps);
9788 this.loading.enable();
9793 getPageData : function(){
9794 var total = this.ds.getTotalCount();
9797 activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
9798 pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
9803 onLoadError : function(){
9804 this.loading.enable();
9808 onPagingKeydown : function(e){
9810 var d = this.getPageData();
9812 var v = this.field.dom.value, pageNum;
9813 if(!v || isNaN(pageNum = parseInt(v, 10))){
9814 this.field.dom.value = d.activePage;
9817 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
9818 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
9821 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))
9823 var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
9824 this.field.dom.value = pageNum;
9825 this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
9828 else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
9830 var v = this.field.dom.value, pageNum;
9831 var increment = (e.shiftKey) ? 10 : 1;
9832 if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
9835 if(!v || isNaN(pageNum = parseInt(v, 10))) {
9836 this.field.dom.value = d.activePage;
9839 else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
9841 this.field.dom.value = parseInt(v, 10) + increment;
9842 pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
9843 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
9850 beforeLoad : function(){
9852 this.loading.disable();
9856 * event that occurs when you click on the navigation buttons - can be used to trigger load of a grid.
9857 * @param {String} which (first|prev|next|last|refresh) which button to press.
9861 onClick : function(which){
9865 ds.load({params:{start: 0, limit: this.pageSize}});
9868 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
9871 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
9874 var total = ds.getTotalCount();
9875 var extra = total % this.pageSize;
9876 var lastStart = extra ? (total - extra) : total-this.pageSize;
9877 ds.load({params:{start: lastStart, limit: this.pageSize}});
9880 ds.load({params:{start: this.cursor, limit: this.pageSize}});
9886 * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
9887 * @param {Roo.data.Store} store The data store to unbind
9889 unbind : function(ds){
9890 ds.un("beforeload", this.beforeLoad, this);
9891 ds.un("load", this.onLoad, this);
9892 ds.un("loadexception", this.onLoadError, this);
9893 ds.un("remove", this.updateInfo, this);
9894 ds.un("add", this.updateInfo, this);
9895 this.ds = undefined;
9899 * Binds the paging toolbar to the specified {@link Roo.data.Store}
9900 * @param {Roo.data.Store} store The data store to bind
9902 bind : function(ds){
9903 ds.on("beforeload", this.beforeLoad, this);
9904 ds.on("load", this.onLoad, this);
9905 ds.on("loadexception", this.onLoadError, this);
9906 ds.on("remove", this.updateInfo, this);
9907 ds.on("add", this.updateInfo, this);
9912 * Ext JS Library 1.1.1
9913 * Copyright(c) 2006-2007, Ext JS, LLC.
9915 * Originally Released Under LGPL - original licence link has changed is not relivant.
9918 * <script type="text/javascript">
9922 * @class Roo.Resizable
9923 * @extends Roo.util.Observable
9924 * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
9925 * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
9926 * 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
9927 * the element will be wrapped for you automatically.</p>
9928 * <p>Here is the list of valid resize handles:</p>
9931 ------ -------------------
9940 'hd' horizontal drag
9943 * <p>Here's an example showing the creation of a typical Resizable:</p>
9945 var resizer = new Roo.Resizable("element-id", {
9953 resizer.on("resize", myHandler);
9955 * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
9956 * resizer.east.setDisplayed(false);</p>
9957 * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
9958 * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
9959 * resize operation's new size (defaults to [0, 0])
9960 * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
9961 * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
9962 * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
9963 * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
9964 * @cfg {Boolean} enabled False to disable resizing (defaults to true)
9965 * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
9966 * @cfg {Number} width The width of the element in pixels (defaults to null)
9967 * @cfg {Number} height The height of the element in pixels (defaults to null)
9968 * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
9969 * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
9970 * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
9971 * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
9972 * @cfg {Boolean} multiDirectional <b>Deprecated</b>. The old style of adding multi-direction resize handles, deprecated
9973 * in favor of the handles config option (defaults to false)
9974 * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
9975 * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
9976 * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
9977 * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
9978 * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
9979 * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
9980 * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
9981 * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
9982 * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
9983 * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
9984 * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
9986 * Create a new resizable component
9987 * @param {String/HTMLElement/Roo.Element} el The id or element to resize
9988 * @param {Object} config configuration options
9990 Roo.Resizable = function(el, config)
9992 this.el = Roo.get(el);
9994 if(config && config.wrap){
9995 config.resizeChild = this.el;
9996 this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
9997 this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
9998 this.el.setStyle("overflow", "hidden");
9999 this.el.setPositioning(config.resizeChild.getPositioning());
10000 config.resizeChild.clearPositioning();
10001 if(!config.width || !config.height){
10002 var csize = config.resizeChild.getSize();
10003 this.el.setSize(csize.width, csize.height);
10005 if(config.pinned && !config.adjustments){
10006 config.adjustments = "auto";
10010 this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
10011 this.proxy.unselectable();
10012 this.proxy.enableDisplayMode('block');
10014 Roo.apply(this, config);
10017 this.disableTrackOver = true;
10018 this.el.addClass("x-resizable-pinned");
10020 // if the element isn't positioned, make it relative
10021 var position = this.el.getStyle("position");
10022 if(position != "absolute" && position != "fixed"){
10023 this.el.setStyle("position", "relative");
10025 if(!this.handles){ // no handles passed, must be legacy style
10026 this.handles = 's,e,se';
10027 if(this.multiDirectional){
10028 this.handles += ',n,w';
10031 if(this.handles == "all"){
10032 this.handles = "n s e w ne nw se sw";
10034 var hs = this.handles.split(/\s*?[,;]\s*?| /);
10035 var ps = Roo.Resizable.positions;
10036 for(var i = 0, len = hs.length; i < len; i++){
10037 if(hs[i] && ps[hs[i]]){
10038 var pos = ps[hs[i]];
10039 this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
10043 this.corner = this.southeast;
10045 // updateBox = the box can move..
10046 if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
10047 this.updateBox = true;
10050 this.activeHandle = null;
10052 if(this.resizeChild){
10053 if(typeof this.resizeChild == "boolean"){
10054 this.resizeChild = Roo.get(this.el.dom.firstChild, true);
10056 this.resizeChild = Roo.get(this.resizeChild, true);
10060 if(this.adjustments == "auto"){
10061 var rc = this.resizeChild;
10062 var hw = this.west, he = this.east, hn = this.north, hs = this.south;
10063 if(rc && (hw || hn)){
10064 rc.position("relative");
10065 rc.setLeft(hw ? hw.el.getWidth() : 0);
10066 rc.setTop(hn ? hn.el.getHeight() : 0);
10068 this.adjustments = [
10069 (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
10070 (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
10074 if(this.draggable){
10075 this.dd = this.dynamic ?
10076 this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
10077 this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
10083 * @event beforeresize
10084 * Fired before resize is allowed. Set enabled to false to cancel resize.
10085 * @param {Roo.Resizable} this
10086 * @param {Roo.EventObject} e The mousedown event
10088 "beforeresize" : true,
10091 * Fired a resizing.
10092 * @param {Roo.Resizable} this
10093 * @param {Number} x The new x position
10094 * @param {Number} y The new y position
10095 * @param {Number} w The new w width
10096 * @param {Number} h The new h hight
10097 * @param {Roo.EventObject} e The mouseup event
10102 * Fired after a resize.
10103 * @param {Roo.Resizable} this
10104 * @param {Number} width The new width
10105 * @param {Number} height The new height
10106 * @param {Roo.EventObject} e The mouseup event
10111 if(this.width !== null && this.height !== null){
10112 this.resizeTo(this.width, this.height);
10114 this.updateChildSize();
10117 this.el.dom.style.zoom = 1;
10119 Roo.Resizable.superclass.constructor.call(this);
10122 Roo.extend(Roo.Resizable, Roo.util.Observable, {
10123 resizeChild : false,
10124 adjustments : [0, 0],
10134 multiDirectional : false,
10135 disableTrackOver : false,
10136 easing : 'easeOutStrong',
10137 widthIncrement : 0,
10138 heightIncrement : 0,
10142 preserveRatio : false,
10143 transparent: false,
10149 * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
10151 constrainTo: undefined,
10153 * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
10155 resizeRegion: undefined,
10159 * Perform a manual resize
10160 * @param {Number} width
10161 * @param {Number} height
10163 resizeTo : function(width, height){
10164 this.el.setSize(width, height);
10165 this.updateChildSize();
10166 this.fireEvent("resize", this, width, height, null);
10170 startSizing : function(e, handle){
10171 this.fireEvent("beforeresize", this, e);
10172 if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
10175 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: " "});
10176 this.overlay.unselectable();
10177 this.overlay.enableDisplayMode("block");
10178 this.overlay.on("mousemove", this.onMouseMove, this);
10179 this.overlay.on("mouseup", this.onMouseUp, this);
10181 this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
10183 this.resizing = true;
10184 this.startBox = this.el.getBox();
10185 this.startPoint = e.getXY();
10186 this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
10187 (this.startBox.y + this.startBox.height) - this.startPoint[1]];
10189 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
10190 this.overlay.show();
10192 if(this.constrainTo) {
10193 var ct = Roo.get(this.constrainTo);
10194 this.resizeRegion = ct.getRegion().adjust(
10195 ct.getFrameWidth('t'),
10196 ct.getFrameWidth('l'),
10197 -ct.getFrameWidth('b'),
10198 -ct.getFrameWidth('r')
10202 this.proxy.setStyle('visibility', 'hidden'); // workaround display none
10204 this.proxy.setBox(this.startBox);
10206 this.proxy.setStyle('visibility', 'visible');
10212 onMouseDown : function(handle, e){
10215 this.activeHandle = handle;
10216 this.startSizing(e, handle);
10221 onMouseUp : function(e){
10222 var size = this.resizeElement();
10223 this.resizing = false;
10225 this.overlay.hide();
10227 this.fireEvent("resize", this, size.width, size.height, e);
10231 updateChildSize : function(){
10233 if(this.resizeChild){
10235 var child = this.resizeChild;
10236 var adj = this.adjustments;
10237 if(el.dom.offsetWidth){
10238 var b = el.getSize(true);
10239 child.setSize(b.width+adj[0], b.height+adj[1]);
10241 // Second call here for IE
10242 // The first call enables instant resizing and
10243 // the second call corrects scroll bars if they
10246 setTimeout(function(){
10247 if(el.dom.offsetWidth){
10248 var b = el.getSize(true);
10249 child.setSize(b.width+adj[0], b.height+adj[1]);
10257 snap : function(value, inc, min){
10258 if(!inc || !value) {
10261 var newValue = value;
10262 var m = value % inc;
10265 newValue = value + (inc-m);
10267 newValue = value - m;
10270 return Math.max(min, newValue);
10274 resizeElement : function(){
10275 var box = this.proxy.getBox();
10276 if(this.updateBox){
10277 this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
10279 this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
10281 this.updateChildSize();
10289 constrain : function(v, diff, m, mx){
10292 }else if(v - diff > mx){
10299 onMouseMove : function(e){
10302 try{// try catch so if something goes wrong the user doesn't get hung
10304 if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
10308 //var curXY = this.startPoint;
10309 var curSize = this.curSize || this.startBox;
10310 var x = this.startBox.x, y = this.startBox.y;
10311 var ox = x, oy = y;
10312 var w = curSize.width, h = curSize.height;
10313 var ow = w, oh = h;
10314 var mw = this.minWidth, mh = this.minHeight;
10315 var mxw = this.maxWidth, mxh = this.maxHeight;
10316 var wi = this.widthIncrement;
10317 var hi = this.heightIncrement;
10319 var eventXY = e.getXY();
10320 var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
10321 var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
10323 var pos = this.activeHandle.position;
10328 w = Math.min(Math.max(mw, w), mxw);
10333 h = Math.min(Math.max(mh, h), mxh);
10338 w = Math.min(Math.max(mw, w), mxw);
10339 h = Math.min(Math.max(mh, h), mxh);
10342 diffY = this.constrain(h, diffY, mh, mxh);
10349 var adiffX = Math.abs(diffX);
10350 var sub = (adiffX % wi); // how much
10351 if (sub > (wi/2)) { // far enough to snap
10352 diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
10354 // remove difference..
10355 diffX = (diffX > 0) ? diffX-sub : diffX+sub;
10359 x = Math.max(this.minX, x);
10362 diffX = this.constrain(w, diffX, mw, mxw);
10368 w = Math.min(Math.max(mw, w), mxw);
10369 diffY = this.constrain(h, diffY, mh, mxh);
10374 diffX = this.constrain(w, diffX, mw, mxw);
10375 diffY = this.constrain(h, diffY, mh, mxh);
10382 diffX = this.constrain(w, diffX, mw, mxw);
10384 h = Math.min(Math.max(mh, h), mxh);
10390 var sw = this.snap(w, wi, mw);
10391 var sh = this.snap(h, hi, mh);
10392 if(sw != w || sh != h){
10415 if(this.preserveRatio){
10420 h = Math.min(Math.max(mh, h), mxh);
10425 w = Math.min(Math.max(mw, w), mxw);
10430 w = Math.min(Math.max(mw, w), mxw);
10436 w = Math.min(Math.max(mw, w), mxw);
10442 h = Math.min(Math.max(mh, h), mxh);
10450 h = Math.min(Math.max(mh, h), mxh);
10460 h = Math.min(Math.max(mh, h), mxh);
10468 if (pos == 'hdrag') {
10471 this.proxy.setBounds(x, y, w, h);
10473 this.resizeElement();
10477 this.fireEvent("resizing", this, x, y, w, h, e);
10481 handleOver : function(){
10483 this.el.addClass("x-resizable-over");
10488 handleOut : function(){
10489 if(!this.resizing){
10490 this.el.removeClass("x-resizable-over");
10495 * Returns the element this component is bound to.
10496 * @return {Roo.Element}
10498 getEl : function(){
10503 * Returns the resizeChild element (or null).
10504 * @return {Roo.Element}
10506 getResizeChild : function(){
10507 return this.resizeChild;
10509 groupHandler : function()
10514 * Destroys this resizable. If the element was wrapped and
10515 * removeEl is not true then the element remains.
10516 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
10518 destroy : function(removeEl){
10519 this.proxy.remove();
10521 this.overlay.removeAllListeners();
10522 this.overlay.remove();
10524 var ps = Roo.Resizable.positions;
10526 if(typeof ps[k] != "function" && this[ps[k]]){
10527 var h = this[ps[k]];
10528 h.el.removeAllListeners();
10533 this.el.update("");
10540 // hash to map config positions to true positions
10541 Roo.Resizable.positions = {
10542 n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast",
10547 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
10549 // only initialize the template if resizable is used
10550 var tpl = Roo.DomHelper.createTemplate(
10551 {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
10554 Roo.Resizable.Handle.prototype.tpl = tpl;
10556 this.position = pos;
10558 // show north drag fro topdra
10559 var handlepos = pos == 'hdrag' ? 'north' : pos;
10561 this.el = this.tpl.append(rz.el.dom, [handlepos], true);
10562 if (pos == 'hdrag') {
10563 this.el.setStyle('cursor', 'pointer');
10565 this.el.unselectable();
10567 this.el.setOpacity(0);
10569 this.el.on("mousedown", this.onMouseDown, this);
10570 if(!disableTrackOver){
10571 this.el.on("mouseover", this.onMouseOver, this);
10572 this.el.on("mouseout", this.onMouseOut, this);
10577 Roo.Resizable.Handle.prototype = {
10578 afterResize : function(rz){
10583 onMouseDown : function(e){
10584 this.rz.onMouseDown(this, e);
10587 onMouseOver : function(e){
10588 this.rz.handleOver(this, e);
10591 onMouseOut : function(e){
10592 this.rz.handleOut(this, e);
10596 * Ext JS Library 1.1.1
10597 * Copyright(c) 2006-2007, Ext JS, LLC.
10599 * Originally Released Under LGPL - original licence link has changed is not relivant.
10602 * <script type="text/javascript">
10606 * @class Roo.Editor
10607 * @extends Roo.Component
10608 * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
10610 * Create a new Editor
10611 * @param {Roo.form.Field} field The Field object (or descendant)
10612 * @param {Object} config The config object
10614 Roo.Editor = function(field, config){
10615 Roo.Editor.superclass.constructor.call(this, config);
10616 this.field = field;
10619 * @event beforestartedit
10620 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
10621 * false from the handler of this event.
10622 * @param {Editor} this
10623 * @param {Roo.Element} boundEl The underlying element bound to this editor
10624 * @param {Mixed} value The field value being set
10626 "beforestartedit" : true,
10629 * Fires when this editor is displayed
10630 * @param {Roo.Element} boundEl The underlying element bound to this editor
10631 * @param {Mixed} value The starting field value
10633 "startedit" : true,
10635 * @event beforecomplete
10636 * Fires after a change has been made to the field, but before the change is reflected in the underlying
10637 * field. Saving the change to the field can be canceled by returning false from the handler of this event.
10638 * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
10639 * event will not fire since no edit actually occurred.
10640 * @param {Editor} this
10641 * @param {Mixed} value The current field value
10642 * @param {Mixed} startValue The original field value
10644 "beforecomplete" : true,
10647 * Fires after editing is complete and any changed value has been written to the underlying field.
10648 * @param {Editor} this
10649 * @param {Mixed} value The current field value
10650 * @param {Mixed} startValue The original field value
10654 * @event specialkey
10655 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
10656 * {@link Roo.EventObject#getKey} to determine which key was pressed.
10657 * @param {Roo.form.Field} this
10658 * @param {Roo.EventObject} e The event object
10660 "specialkey" : true
10664 Roo.extend(Roo.Editor, Roo.Component, {
10666 * @cfg {Boolean/String} autosize
10667 * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
10668 * or "height" to adopt the height only (defaults to false)
10671 * @cfg {Boolean} revertInvalid
10672 * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
10673 * validation fails (defaults to true)
10676 * @cfg {Boolean} ignoreNoChange
10677 * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
10678 * the value has not changed (defaults to false). Applies only to string values - edits for other data types
10679 * will never be ignored.
10682 * @cfg {Boolean} hideEl
10683 * False to keep the bound element visible while the editor is displayed (defaults to true)
10686 * @cfg {Mixed} value
10687 * The data value of the underlying field (defaults to "")
10691 * @cfg {String} alignment
10692 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
10696 * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
10697 * for bottom-right shadow (defaults to "frame")
10701 * @cfg {Boolean} constrain True to constrain the editor to the viewport
10705 * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
10707 completeOnEnter : false,
10709 * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
10711 cancelOnEsc : false,
10713 * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
10718 onRender : function(ct, position){
10719 this.el = new Roo.Layer({
10720 shadow: this.shadow,
10726 constrain: this.constrain
10728 this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
10729 if(this.field.msgTarget != 'title'){
10730 this.field.msgTarget = 'qtip';
10732 this.field.render(this.el);
10734 this.field.el.dom.setAttribute('autocomplete', 'off');
10736 this.field.on("specialkey", this.onSpecialKey, this);
10737 if(this.swallowKeys){
10738 this.field.el.swallowEvent(['keydown','keypress']);
10741 this.field.on("blur", this.onBlur, this);
10742 if(this.field.grow){
10743 this.field.on("autosize", this.el.sync, this.el, {delay:1});
10747 onSpecialKey : function(field, e)
10749 //Roo.log('editor onSpecialKey');
10750 if(this.completeOnEnter && e.getKey() == e.ENTER){
10752 this.completeEdit();
10755 // do not fire special key otherwise it might hide close the editor...
10756 if(e.getKey() == e.ENTER){
10759 if(this.cancelOnEsc && e.getKey() == e.ESC){
10763 this.fireEvent('specialkey', field, e);
10768 * Starts the editing process and shows the editor.
10769 * @param {String/HTMLElement/Element} el The element to edit
10770 * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
10771 * to the innerHTML of el.
10773 startEdit : function(el, value){
10775 this.completeEdit();
10777 this.boundEl = Roo.get(el);
10778 var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
10779 if(!this.rendered){
10780 this.render(this.parentEl || document.body);
10782 if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
10785 this.startValue = v;
10786 this.field.setValue(v);
10788 var sz = this.boundEl.getSize();
10789 switch(this.autoSize){
10791 this.setSize(sz.width, "");
10794 this.setSize("", sz.height);
10797 this.setSize(sz.width, sz.height);
10800 this.el.alignTo(this.boundEl, this.alignment);
10801 this.editing = true;
10803 Roo.QuickTips.disable();
10809 * Sets the height and width of this editor.
10810 * @param {Number} width The new width
10811 * @param {Number} height The new height
10813 setSize : function(w, h){
10814 this.field.setSize(w, h);
10821 * Realigns the editor to the bound field based on the current alignment config value.
10823 realign : function(){
10824 this.el.alignTo(this.boundEl, this.alignment);
10828 * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
10829 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
10831 completeEdit : function(remainVisible){
10835 var v = this.getValue();
10836 if(this.revertInvalid !== false && !this.field.isValid()){
10837 v = this.startValue;
10838 this.cancelEdit(true);
10840 if(String(v) === String(this.startValue) && this.ignoreNoChange){
10841 this.editing = false;
10845 if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
10846 this.editing = false;
10847 if(this.updateEl && this.boundEl){
10848 this.boundEl.update(v);
10850 if(remainVisible !== true){
10853 this.fireEvent("complete", this, v, this.startValue);
10858 onShow : function(){
10860 if(this.hideEl !== false){
10861 this.boundEl.hide();
10864 if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
10865 this.fixIEFocus = true;
10866 this.deferredFocus.defer(50, this);
10868 this.field.focus();
10870 this.fireEvent("startedit", this.boundEl, this.startValue);
10873 deferredFocus : function(){
10875 this.field.focus();
10880 * Cancels the editing process and hides the editor without persisting any changes. The field value will be
10881 * reverted to the original starting value.
10882 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
10883 * cancel (defaults to false)
10885 cancelEdit : function(remainVisible){
10887 this.setValue(this.startValue);
10888 if(remainVisible !== true){
10895 onBlur : function(){
10896 if(this.allowBlur !== true && this.editing){
10897 this.completeEdit();
10902 onHide : function(){
10904 this.completeEdit();
10908 if(this.field.collapse){
10909 this.field.collapse();
10912 if(this.hideEl !== false){
10913 this.boundEl.show();
10916 Roo.QuickTips.enable();
10921 * Sets the data value of the editor
10922 * @param {Mixed} value Any valid value supported by the underlying field
10924 setValue : function(v){
10925 this.field.setValue(v);
10929 * Gets the data value of the editor
10930 * @return {Mixed} The data value
10932 getValue : function(){
10933 return this.field.getValue();
10937 * Ext JS Library 1.1.1
10938 * Copyright(c) 2006-2007, Ext JS, LLC.
10940 * Originally Released Under LGPL - original licence link has changed is not relivant.
10943 * <script type="text/javascript">
10947 * @class Roo.BasicDialog
10948 * @extends Roo.util.Observable
10949 * @parent none builder
10950 * Lightweight Dialog Class. The code below shows the creation of a typical dialog using existing HTML markup:
10952 var dlg = new Roo.BasicDialog("my-dlg", {
10961 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
10962 dlg.addButton('OK', dlg.hide, dlg); // Could call a save function instead of hiding
10963 dlg.addButton('Cancel', dlg.hide, dlg);
10966 <b>A Dialog should always be a direct child of the body element.</b>
10967 * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
10968 * @cfg {String} title Default text to display in the title bar (defaults to null)
10969 * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
10970 * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
10971 * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
10972 * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
10973 * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
10974 * (defaults to null with no animation)
10975 * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
10976 * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
10977 * property for valid values (defaults to 'all')
10978 * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
10979 * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
10980 * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
10981 * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
10982 * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
10983 * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
10984 * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
10985 * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
10986 * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
10987 * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
10988 * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
10989 * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
10990 * draggable = true (defaults to false)
10991 * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
10992 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
10993 * shadow (defaults to false)
10994 * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
10995 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
10996 * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
10997 * @cfg {Array} buttons Array of buttons
10998 * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
11000 * Create a new BasicDialog.
11001 * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
11002 * @param {Object} config Configuration options
11004 Roo.BasicDialog = function(el, config){
11005 this.el = Roo.get(el);
11006 var dh = Roo.DomHelper;
11007 if(!this.el && config && config.autoCreate){
11008 if(typeof config.autoCreate == "object"){
11009 if(!config.autoCreate.id){
11010 config.autoCreate.id = el;
11012 this.el = dh.append(document.body,
11013 config.autoCreate, true);
11015 this.el = dh.append(document.body,
11016 {tag: "div", id: el, style:'visibility:hidden;'}, true);
11020 el.setDisplayed(true);
11021 el.hide = this.hideAction;
11023 el.addClass("x-dlg");
11025 Roo.apply(this, config);
11027 this.proxy = el.createProxy("x-dlg-proxy");
11028 this.proxy.hide = this.hideAction;
11029 this.proxy.setOpacity(.5);
11033 el.setWidth(config.width);
11036 el.setHeight(config.height);
11038 this.size = el.getSize();
11039 if(typeof config.x != "undefined" && typeof config.y != "undefined"){
11040 this.xy = [config.x,config.y];
11042 this.xy = el.getCenterXY(true);
11044 /** The header element @type Roo.Element */
11045 this.header = el.child("> .x-dlg-hd");
11046 /** The body element @type Roo.Element */
11047 this.body = el.child("> .x-dlg-bd");
11048 /** The footer element @type Roo.Element */
11049 this.footer = el.child("> .x-dlg-ft");
11052 this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
11055 this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
11058 this.header.unselectable();
11060 this.header.update(this.title);
11062 // this element allows the dialog to be focused for keyboard event
11063 this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
11064 this.focusEl.swallowEvent("click", true);
11066 this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
11068 // wrap the body and footer for special rendering
11069 this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
11071 this.bwrap.dom.appendChild(this.footer.dom);
11074 this.bg = this.el.createChild({
11075 tag: "div", cls:"x-dlg-bg",
11076 html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
11078 this.centerBg = this.bg.child("div.x-dlg-bg-center");
11081 if(this.autoScroll !== false && !this.autoTabs){
11082 this.body.setStyle("overflow", "auto");
11085 this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
11087 if(this.closable !== false){
11088 this.el.addClass("x-dlg-closable");
11089 this.close = this.toolbox.createChild({cls:"x-dlg-close"});
11090 this.close.on("click", this.closeClick, this);
11091 this.close.addClassOnOver("x-dlg-close-over");
11093 if(this.collapsible !== false){
11094 this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
11095 this.collapseBtn.on("click", this.collapseClick, this);
11096 this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
11097 this.header.on("dblclick", this.collapseClick, this);
11099 if(this.resizable !== false){
11100 this.el.addClass("x-dlg-resizable");
11101 this.resizer = new Roo.Resizable(el, {
11102 minWidth: this.minWidth || 80,
11103 minHeight:this.minHeight || 80,
11104 handles: this.resizeHandles || "all",
11107 this.resizer.on("beforeresize", this.beforeResize, this);
11108 this.resizer.on("resize", this.onResize, this);
11110 if(this.draggable !== false){
11111 el.addClass("x-dlg-draggable");
11112 if (!this.proxyDrag) {
11113 var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
11116 var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
11118 dd.setHandleElId(this.header.id);
11119 dd.endDrag = this.endMove.createDelegate(this);
11120 dd.startDrag = this.startMove.createDelegate(this);
11121 dd.onDrag = this.onDrag.createDelegate(this);
11126 this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
11127 this.mask.enableDisplayMode("block");
11129 this.el.addClass("x-dlg-modal");
11132 this.shadow = new Roo.Shadow({
11133 mode : typeof this.shadow == "string" ? this.shadow : "sides",
11134 offset : this.shadowOffset
11137 this.shadowOffset = 0;
11139 if(Roo.useShims && this.shim !== false){
11140 this.shim = this.el.createShim();
11141 this.shim.hide = this.hideAction;
11149 if (this.buttons) {
11150 var bts= this.buttons;
11152 Roo.each(bts, function(b) {
11161 * Fires when a key is pressed
11162 * @param {Roo.BasicDialog} this
11163 * @param {Roo.EventObject} e
11168 * Fires when this dialog is moved by the user.
11169 * @param {Roo.BasicDialog} this
11170 * @param {Number} x The new page X
11171 * @param {Number} y The new page Y
11176 * Fires when this dialog is resized by the user.
11177 * @param {Roo.BasicDialog} this
11178 * @param {Number} width The new width
11179 * @param {Number} height The new height
11183 * @event beforehide
11184 * Fires before this dialog is hidden.
11185 * @param {Roo.BasicDialog} this
11187 "beforehide" : true,
11190 * Fires when this dialog is hidden.
11191 * @param {Roo.BasicDialog} this
11195 * @event beforeshow
11196 * Fires before this dialog is shown.
11197 * @param {Roo.BasicDialog} this
11199 "beforeshow" : true,
11202 * Fires when this dialog is shown.
11203 * @param {Roo.BasicDialog} this
11207 el.on("keydown", this.onKeyDown, this);
11208 el.on("mousedown", this.toFront, this);
11209 Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
11211 Roo.DialogManager.register(this);
11212 Roo.BasicDialog.superclass.constructor.call(this);
11215 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
11216 shadowOffset: Roo.isIE ? 6 : 5,
11219 minButtonWidth: 75,
11220 defaultButton: null,
11221 buttonAlign: "right",
11226 * Sets the dialog title text
11227 * @param {String} text The title text to display
11228 * @return {Roo.BasicDialog} this
11230 setTitle : function(text){
11231 this.header.update(text);
11236 closeClick : function(){
11241 collapseClick : function(){
11242 this[this.collapsed ? "expand" : "collapse"]();
11246 * Collapses the dialog to its minimized state (only the title bar is visible).
11247 * Equivalent to the user clicking the collapse dialog button.
11249 collapse : function(){
11250 if(!this.collapsed){
11251 this.collapsed = true;
11252 this.el.addClass("x-dlg-collapsed");
11253 this.restoreHeight = this.el.getHeight();
11254 this.resizeTo(this.el.getWidth(), this.header.getHeight());
11259 * Expands a collapsed dialog back to its normal state. Equivalent to the user
11260 * clicking the expand dialog button.
11262 expand : function(){
11263 if(this.collapsed){
11264 this.collapsed = false;
11265 this.el.removeClass("x-dlg-collapsed");
11266 this.resizeTo(this.el.getWidth(), this.restoreHeight);
11271 * Reinitializes the tabs component, clearing out old tabs and finding new ones.
11272 * @return {Roo.panel.Tab} The tabs component
11274 initTabs : function(){
11275 var tabs = this.getTabs();
11276 while(tabs.getTab(0)){
11279 this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
11281 tabs.addTab(Roo.id(dom), dom.title);
11289 beforeResize : function(){
11290 this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
11294 onResize : function(){
11295 this.refreshSize();
11296 this.syncBodyHeight();
11297 this.adjustAssets();
11299 this.fireEvent("resize", this, this.size.width, this.size.height);
11303 onKeyDown : function(e){
11304 if(this.isVisible()){
11305 this.fireEvent("keydown", this, e);
11310 * Resizes the dialog.
11311 * @param {Number} width
11312 * @param {Number} height
11313 * @return {Roo.BasicDialog} this
11315 resizeTo : function(width, height){
11316 this.el.setSize(width, height);
11317 this.size = {width: width, height: height};
11318 this.syncBodyHeight();
11319 if(this.fixedcenter){
11322 if(this.isVisible()){
11323 this.constrainXY();
11324 this.adjustAssets();
11326 this.fireEvent("resize", this, width, height);
11332 * Resizes the dialog to fit the specified content size.
11333 * @param {Number} width
11334 * @param {Number} height
11335 * @return {Roo.BasicDialog} this
11337 setContentSize : function(w, h){
11338 h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
11339 w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
11340 //if(!this.el.isBorderBox()){
11341 h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
11342 w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
11345 h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
11346 w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
11348 this.resizeTo(w, h);
11353 * Adds a key listener for when this dialog is displayed. This allows you to hook in a function that will be
11354 * executed in response to a particular key being pressed while the dialog is active.
11355 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
11356 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
11357 * @param {Function} fn The function to call
11358 * @param {Object} scope (optional) The scope of the function
11359 * @return {Roo.BasicDialog} this
11361 addKeyListener : function(key, fn, scope){
11362 var keyCode, shift, ctrl, alt;
11363 if(typeof key == "object" && !(key instanceof Array)){
11364 keyCode = key["key"];
11365 shift = key["shift"];
11366 ctrl = key["ctrl"];
11371 var handler = function(dlg, e){
11372 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
11373 var k = e.getKey();
11374 if(keyCode instanceof Array){
11375 for(var i = 0, len = keyCode.length; i < len; i++){
11376 if(keyCode[i] == k){
11377 fn.call(scope || window, dlg, k, e);
11383 fn.call(scope || window, dlg, k, e);
11388 this.on("keydown", handler);
11393 * Returns the panel.Tab component (creates it if it doesn't exist).
11394 * Note: If you wish to simply check for the existence of tabs without creating them,
11395 * check for a null 'tabs' property.
11396 * @return {Roo.panel.Tab} The tabs component
11398 getTabs : function(){
11400 this.el.addClass("x-dlg-auto-tabs");
11401 this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
11402 this.tabs = new Roo.panel.Tab(this.body.dom, this.tabPosition == "bottom");
11408 * Adds a button to the footer section of the dialog.
11409 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
11410 * object or a valid Roo.DomHelper element config
11411 * @param {Function} handler The function called when the button is clicked
11412 * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
11413 * @return {Roo.Button} The new button
11415 addButton : function(config, handler, scope){
11416 var dh = Roo.DomHelper;
11418 this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
11420 if(!this.btnContainer){
11421 var tb = this.footer.createChild({
11423 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
11424 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
11426 this.btnContainer = tb.firstChild.firstChild.firstChild;
11431 minWidth: this.minButtonWidth,
11434 if(typeof config == "string"){
11435 bconfig.text = config;
11438 bconfig.dhconfig = config;
11440 Roo.apply(bconfig, config);
11444 if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
11445 bconfig.position = Math.max(0, bconfig.position);
11446 fc = this.btnContainer.childNodes[bconfig.position];
11449 var btn = new Roo.Button(
11451 this.btnContainer.insertBefore(document.createElement("td"),fc)
11452 : this.btnContainer.appendChild(document.createElement("td")),
11453 //Roo.get(this.btnContainer).createChild( { tag: 'td'}, fc ),
11456 this.syncBodyHeight();
11459 * Array of all the buttons that have been added to this dialog via addButton
11464 this.buttons.push(btn);
11469 * Sets the default button to be focused when the dialog is displayed.
11470 * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
11471 * @return {Roo.BasicDialog} this
11473 setDefaultButton : function(btn){
11474 this.defaultButton = btn;
11479 getHeaderFooterHeight : function(safe){
11482 height += this.header.getHeight();
11485 var fm = this.footer.getMargins();
11486 height += (this.footer.getHeight()+fm.top+fm.bottom);
11488 height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
11489 height += this.centerBg.getPadding("tb");
11494 syncBodyHeight : function()
11496 var bd = this.body, // the text
11497 cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
11499 var height = this.size.height - this.getHeaderFooterHeight(false);
11500 bd.setHeight(height-bd.getMargins("tb"));
11501 var hh = this.header.getHeight();
11502 var h = this.size.height-hh;
11505 bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
11506 bw.setHeight(h-cb.getPadding("tb"));
11508 bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
11509 bd.setWidth(bw.getWidth(true));
11511 this.tabs.syncHeight();
11513 this.tabs.el.repaint();
11519 * Restores the previous state of the dialog if Roo.state is configured.
11520 * @return {Roo.BasicDialog} this
11522 restoreState : function(){
11523 var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
11524 if(box && box.width){
11525 this.xy = [box.x, box.y];
11526 this.resizeTo(box.width, box.height);
11532 beforeShow : function(){
11534 if(this.fixedcenter){
11535 this.xy = this.el.getCenterXY(true);
11538 Roo.get(document.body).addClass("x-body-masked");
11539 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
11542 this.constrainXY();
11546 animShow : function(){
11547 var b = Roo.get(this.animateTarget).getBox();
11548 this.proxy.setSize(b.width, b.height);
11549 this.proxy.setLocation(b.x, b.y);
11551 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
11552 true, .35, this.showEl.createDelegate(this));
11556 * Shows the dialog.
11557 * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
11558 * @return {Roo.BasicDialog} this
11560 show : function(animateTarget){
11561 if (this.fireEvent("beforeshow", this) === false){
11564 if(this.syncHeightBeforeShow){
11565 this.syncBodyHeight();
11566 }else if(this.firstShow){
11567 this.firstShow = false;
11568 this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
11570 this.animateTarget = animateTarget || this.animateTarget;
11571 if(!this.el.isVisible()){
11573 if(this.animateTarget && Roo.get(this.animateTarget)){
11583 showEl : function(){
11585 this.el.setXY(this.xy);
11587 this.adjustAssets(true);
11590 // IE peekaboo bug - fix found by Dave Fenwick
11594 this.fireEvent("show", this);
11598 * Focuses the dialog. If a defaultButton is set, it will receive focus, otherwise the
11599 * dialog itself will receive focus.
11601 focus : function(){
11602 if(this.defaultButton){
11603 this.defaultButton.focus();
11605 this.focusEl.focus();
11610 constrainXY : function(){
11611 if(this.constraintoviewport !== false){
11612 if(!this.viewSize){
11613 if(this.container){
11614 var s = this.container.getSize();
11615 this.viewSize = [s.width, s.height];
11617 this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
11620 var s = Roo.get(this.container||document).getScroll();
11622 var x = this.xy[0], y = this.xy[1];
11623 var w = this.size.width, h = this.size.height;
11624 var vw = this.viewSize[0], vh = this.viewSize[1];
11625 // only move it if it needs it
11627 // first validate right/bottom
11628 if(x + w > vw+s.left){
11632 if(y + h > vh+s.top){
11636 // then make sure top/left isn't negative
11648 if(this.isVisible()){
11649 this.el.setLocation(x, y);
11650 this.adjustAssets();
11657 onDrag : function(){
11658 if(!this.proxyDrag){
11659 this.xy = this.el.getXY();
11660 this.adjustAssets();
11665 adjustAssets : function(doShow){
11666 var x = this.xy[0], y = this.xy[1];
11667 var w = this.size.width, h = this.size.height;
11668 if(doShow === true){
11670 this.shadow.show(this.el);
11676 if(this.shadow && this.shadow.isVisible()){
11677 this.shadow.show(this.el);
11679 if(this.shim && this.shim.isVisible()){
11680 this.shim.setBounds(x, y, w, h);
11685 adjustViewport : function(w, h){
11687 w = Roo.lib.Dom.getViewWidth();
11688 h = Roo.lib.Dom.getViewHeight();
11691 this.viewSize = [w, h];
11692 if(this.modal && this.mask.isVisible()){
11693 this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
11694 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
11696 if(this.isVisible()){
11697 this.constrainXY();
11702 * Destroys this dialog and all its supporting elements (including any tabs, shim,
11703 * shadow, proxy, mask, etc.) Also removes all event listeners.
11704 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
11706 destroy : function(removeEl){
11707 if(this.isVisible()){
11708 this.animateTarget = null;
11711 Roo.EventManager.removeResizeListener(this.adjustViewport, this);
11713 this.tabs.destroy(removeEl);
11726 for(var i = 0, len = this.buttons.length; i < len; i++){
11727 this.buttons[i].destroy();
11730 this.el.removeAllListeners();
11731 if(removeEl === true){
11732 this.el.update("");
11735 Roo.DialogManager.unregister(this);
11739 startMove : function(){
11740 if(this.proxyDrag){
11743 if(this.constraintoviewport !== false){
11744 this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
11749 endMove : function(){
11750 if(!this.proxyDrag){
11751 Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
11753 Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
11756 this.refreshSize();
11757 this.adjustAssets();
11759 this.fireEvent("move", this, this.xy[0], this.xy[1]);
11763 * Brings this dialog to the front of any other visible dialogs
11764 * @return {Roo.BasicDialog} this
11766 toFront : function(){
11767 Roo.DialogManager.bringToFront(this);
11772 * Sends this dialog to the back (under) of any other visible dialogs
11773 * @return {Roo.BasicDialog} this
11775 toBack : function(){
11776 Roo.DialogManager.sendToBack(this);
11781 * Centers this dialog in the viewport
11782 * @return {Roo.BasicDialog} this
11784 center : function(){
11785 var xy = this.el.getCenterXY(true);
11786 this.moveTo(xy[0], xy[1]);
11791 * Moves the dialog's top-left corner to the specified point
11792 * @param {Number} x
11793 * @param {Number} y
11794 * @return {Roo.BasicDialog} this
11796 moveTo : function(x, y){
11798 if(this.isVisible()){
11799 this.el.setXY(this.xy);
11800 this.adjustAssets();
11806 * Aligns the dialog to the specified element
11807 * @param {String/HTMLElement/Roo.Element} element The element to align to.
11808 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
11809 * @param {Array} offsets (optional) Offset the positioning by [x, y]
11810 * @return {Roo.BasicDialog} this
11812 alignTo : function(element, position, offsets){
11813 this.xy = this.el.getAlignToXY(element, position, offsets);
11814 if(this.isVisible()){
11815 this.el.setXY(this.xy);
11816 this.adjustAssets();
11822 * Anchors an element to another element and realigns it when the window is resized.
11823 * @param {String/HTMLElement/Roo.Element} element The element to align to.
11824 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
11825 * @param {Array} offsets (optional) Offset the positioning by [x, y]
11826 * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
11827 * is a number, it is used as the buffer delay (defaults to 50ms).
11828 * @return {Roo.BasicDialog} this
11830 anchorTo : function(el, alignment, offsets, monitorScroll){
11831 var action = function(){
11832 this.alignTo(el, alignment, offsets);
11834 Roo.EventManager.onWindowResize(action, this);
11835 var tm = typeof monitorScroll;
11836 if(tm != 'undefined'){
11837 Roo.EventManager.on(window, 'scroll', action, this,
11838 {buffer: tm == 'number' ? monitorScroll : 50});
11845 * Returns true if the dialog is visible
11846 * @return {Boolean}
11848 isVisible : function(){
11849 return this.el.isVisible();
11853 animHide : function(callback){
11854 var b = Roo.get(this.animateTarget).getBox();
11856 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
11858 this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
11859 this.hideEl.createDelegate(this, [callback]));
11863 * Hides the dialog.
11864 * @param {Function} callback (optional) Function to call when the dialog is hidden
11865 * @return {Roo.BasicDialog} this
11867 hide : function(callback){
11868 if (this.fireEvent("beforehide", this) === false){
11872 this.shadow.hide();
11877 // sometimes animateTarget seems to get set.. causing problems...
11878 // this just double checks..
11879 if(this.animateTarget && Roo.get(this.animateTarget)) {
11880 this.animHide(callback);
11883 this.hideEl(callback);
11889 hideEl : function(callback){
11893 Roo.get(document.body).removeClass("x-body-masked");
11895 this.fireEvent("hide", this);
11896 if(typeof callback == "function"){
11902 hideAction : function(){
11903 this.setLeft("-10000px");
11904 this.setTop("-10000px");
11905 this.setStyle("visibility", "hidden");
11909 refreshSize : function(){
11910 this.size = this.el.getSize();
11911 this.xy = this.el.getXY();
11912 Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
11916 // z-index is managed by the DialogManager and may be overwritten at any time
11917 setZIndex : function(index){
11919 this.mask.setStyle("z-index", index);
11922 this.shim.setStyle("z-index", ++index);
11925 this.shadow.setZIndex(++index);
11927 this.el.setStyle("z-index", ++index);
11929 this.proxy.setStyle("z-index", ++index);
11932 this.resizer.proxy.setStyle("z-index", ++index);
11935 this.lastZIndex = index;
11939 * Returns the element for this dialog
11940 * @return {Roo.Element} The underlying dialog Element
11942 getEl : function(){
11948 * @class Roo.DialogManager
11949 * Provides global access to BasicDialogs that have been created and
11950 * support for z-indexing (layering) multiple open dialogs.
11952 Roo.DialogManager = function(){
11954 var accessList = [];
11958 var sortDialogs = function(d1, d2){
11959 return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
11963 var orderDialogs = function(){
11964 accessList.sort(sortDialogs);
11965 var seed = Roo.DialogManager.zseed;
11966 for(var i = 0, len = accessList.length; i < len; i++){
11967 var dlg = accessList[i];
11969 dlg.setZIndex(seed + (i*10));
11976 * The starting z-index for BasicDialogs (defaults to 9000)
11977 * @type Number The z-index value
11982 register : function(dlg){
11983 list[dlg.id] = dlg;
11984 accessList.push(dlg);
11988 unregister : function(dlg){
11989 delete list[dlg.id];
11992 if(!accessList.indexOf){
11993 for( i = 0, len = accessList.length; i < len; i++){
11994 if(accessList[i] == dlg){
11995 accessList.splice(i, 1);
12000 i = accessList.indexOf(dlg);
12002 accessList.splice(i, 1);
12008 * Gets a registered dialog by id
12009 * @param {String/Object} id The id of the dialog or a dialog
12010 * @return {Roo.BasicDialog} this
12012 get : function(id){
12013 return typeof id == "object" ? id : list[id];
12017 * Brings the specified dialog to the front
12018 * @param {String/Object} dlg The id of the dialog or a dialog
12019 * @return {Roo.BasicDialog} this
12021 bringToFront : function(dlg){
12022 dlg = this.get(dlg);
12025 dlg._lastAccess = new Date().getTime();
12032 * Sends the specified dialog to the back
12033 * @param {String/Object} dlg The id of the dialog or a dialog
12034 * @return {Roo.BasicDialog} this
12036 sendToBack : function(dlg){
12037 dlg = this.get(dlg);
12038 dlg._lastAccess = -(new Date().getTime());
12044 * Hides all dialogs
12046 hideAll : function(){
12047 for(var id in list){
12048 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
12057 * @class Roo.LayoutDialog
12058 * @extends Roo.BasicDialog
12059 * @children Roo.panel.Content
12060 * @parent builder none
12061 * Dialog which provides adjustments for working with a layout in a Dialog.
12062 * Add your necessary layout config options to the dialog's config.<br>
12063 * Example usage (including a nested layout):
12066 dialog = new Roo.LayoutDialog("download-dlg", {
12075 // layout config merges with the dialog config
12077 tabPosition: "top",
12078 alwaysShowTabs: true
12081 dialog.addKeyListener(27, dialog.hide, dialog);
12082 dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
12083 dialog.addButton("Build It!", this.getDownload, this);
12085 // we can even add nested layouts
12086 var innerLayout = new Roo.layout.Border("dl-inner", {
12096 innerLayout.beginUpdate();
12097 innerLayout.add("east", new Roo.panel.Content("dl-details"));
12098 innerLayout.add("center", new Roo.panel.Content("selection-panel"));
12099 innerLayout.endUpdate(true);
12101 var layout = dialog.getLayout();
12102 layout.beginUpdate();
12103 layout.add("center", new Roo.panel.Content("standard-panel",
12104 {title: "Download the Source", fitToFrame:true}));
12105 layout.add("center", new Roo.panel.NestedLayout(innerLayout,
12106 {title: "Build your own roo.js"}));
12107 layout.getRegion("center").showPanel(sp);
12108 layout.endUpdate();
12112 * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
12113 * @param {Object} config configuration options
12115 Roo.LayoutDialog = function(el, cfg){
12118 if (typeof(cfg) == 'undefined') {
12119 config = Roo.apply({}, el);
12120 // not sure why we use documentElement here.. - it should always be body.
12121 // IE7 borks horribly if we use documentElement.
12122 // webkit also does not like documentElement - it creates a body element...
12123 el = Roo.get( document.body || document.documentElement ).createChild();
12124 //config.autoCreate = true;
12128 config.autoTabs = false;
12129 Roo.LayoutDialog.superclass.constructor.call(this, el, config);
12130 this.body.setStyle({overflow:"hidden", position:"relative"});
12131 this.layout = new Roo.layout.Border(this.body.dom, config);
12132 this.layout.monitorWindowResize = false;
12133 this.el.addClass("x-dlg-auto-layout");
12134 // fix case when center region overwrites center function
12135 this.center = Roo.BasicDialog.prototype.center;
12136 this.on("show", this.layout.layout, this.layout, true);
12137 if (config.items) {
12138 var xitems = config.items;
12139 delete config.items;
12140 Roo.each(xitems, this.addxtype, this);
12145 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
12149 * @cfg {Roo.layout.Region} east
12152 * @cfg {Roo.layout.Region} west
12155 * @cfg {Roo.layout.Region} south
12158 * @cfg {Roo.layout.Region} north
12161 * @cfg {Roo.layout.Region} center
12164 * @cfg {Roo.Button} buttons[] Bottom buttons..
12169 * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
12172 endUpdate : function(){
12173 this.layout.endUpdate();
12177 * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
12180 beginUpdate : function(){
12181 this.layout.beginUpdate();
12185 * Get the BorderLayout for this dialog
12186 * @return {Roo.layout.Border}
12188 getLayout : function(){
12189 return this.layout;
12192 showEl : function(){
12193 Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
12195 this.layout.layout();
12200 // Use the syncHeightBeforeShow config option to control this automatically
12201 syncBodyHeight : function(){
12202 Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
12203 if(this.layout){this.layout.layout();}
12207 * Add an xtype element (actually adds to the layout.)
12208 * @return {Object} xdata xtype object data.
12211 addxtype : function(c) {
12212 return this.layout.addxtype(c);
12216 * Ext JS Library 1.1.1
12217 * Copyright(c) 2006-2007, Ext JS, LLC.
12219 * Originally Released Under LGPL - original licence link has changed is not relivant.
12222 * <script type="text/javascript">
12226 * @class Roo.MessageBox
12228 * Utility class for generating different styles of message boxes. The alias Roo.Msg can also be used.
12232 Roo.Msg.alert('Status', 'Changes saved successfully.');
12234 // Prompt for user data:
12235 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
12237 // process text value...
12241 // Show a dialog using config options:
12243 title:'Save Changes?',
12244 msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
12245 buttons: Roo.Msg.YESNOCANCEL,
12252 Roo.MessageBox = function(){
12253 var dlg, opt, mask, waitTimer;
12254 var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
12255 var buttons, activeTextEl, bwidth;
12258 var handleButton = function(button){
12260 Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
12264 var handleHide = function(){
12265 if(opt && opt.cls){
12266 dlg.el.removeClass(opt.cls);
12269 Roo.TaskMgr.stop(waitTimer);
12275 var updateButtons = function(b){
12278 buttons["ok"].hide();
12279 buttons["cancel"].hide();
12280 buttons["yes"].hide();
12281 buttons["no"].hide();
12282 dlg.footer.dom.style.display = 'none';
12285 dlg.footer.dom.style.display = '';
12286 for(var k in buttons){
12287 if(typeof buttons[k] != "function"){
12290 buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
12291 width += buttons[k].el.getWidth()+15;
12301 var handleEsc = function(d, k, e){
12302 if(opt && opt.closable !== false){
12312 * Returns a reference to the underlying {@link Roo.BasicDialog} element
12313 * @return {Roo.BasicDialog} The BasicDialog element
12315 getDialog : function(){
12317 dlg = new Roo.BasicDialog("x-msg-box", {
12322 constraintoviewport:false,
12324 collapsible : false,
12327 width:400, height:100,
12328 buttonAlign:"center",
12329 closeClick : function(){
12330 if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
12331 handleButton("no");
12333 handleButton("cancel");
12338 dlg.on("hide", handleHide);
12340 dlg.addKeyListener(27, handleEsc);
12342 var bt = this.buttonText;
12343 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
12344 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
12345 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
12346 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
12347 bodyEl = dlg.body.createChild({
12349 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>'
12351 msgEl = bodyEl.dom.firstChild;
12352 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
12353 textboxEl.enableDisplayMode();
12354 textboxEl.addKeyListener([10,13], function(){
12355 if(dlg.isVisible() && opt && opt.buttons){
12356 if(opt.buttons.ok){
12357 handleButton("ok");
12358 }else if(opt.buttons.yes){
12359 handleButton("yes");
12363 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
12364 textareaEl.enableDisplayMode();
12365 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
12366 progressEl.enableDisplayMode();
12367 var pf = progressEl.dom.firstChild;
12369 pp = Roo.get(pf.firstChild);
12370 pp.setHeight(pf.offsetHeight);
12378 * Updates the message box body text
12379 * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
12380 * the XHTML-compliant non-breaking space character '&#160;')
12381 * @return {Roo.MessageBox} This message box
12383 updateText : function(text){
12384 if(!dlg.isVisible() && !opt.width){
12385 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
12387 msgEl.innerHTML = text || ' ';
12389 var cw = Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
12390 //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
12392 Math.min(opt.width || cw , this.maxWidth),
12393 Math.max(opt.minWidth || this.minWidth, bwidth)
12396 activeTextEl.setWidth(w);
12398 if(dlg.isVisible()){
12399 dlg.fixedcenter = false;
12401 // to big, make it scroll. = But as usual stupid IE does not support
12404 if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
12405 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
12406 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
12408 bodyEl.dom.style.height = '';
12409 bodyEl.dom.style.overflowY = '';
12412 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
12414 bodyEl.dom.style.overflowX = '';
12417 dlg.setContentSize(w, bodyEl.getHeight());
12418 if(dlg.isVisible()){
12419 dlg.fixedcenter = true;
12425 * Updates a progress-style message box's text and progress bar. Only relevant on message boxes
12426 * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
12427 * @param {Number} value Any number between 0 and 1 (e.g., .5)
12428 * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
12429 * @return {Roo.MessageBox} This message box
12431 updateProgress : function(value, text){
12433 this.updateText(text);
12435 if (pp) { // weird bug on my firefox - for some reason this is not defined
12436 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
12442 * Returns true if the message box is currently displayed
12443 * @return {Boolean} True if the message box is visible, else false
12445 isVisible : function(){
12446 return dlg && dlg.isVisible();
12450 * Hides the message box if it is displayed
12453 if(this.isVisible()){
12459 * Displays a new message box, or reinitializes an existing message box, based on the config options
12460 * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
12461 * The following config object properties are supported:
12463 Property Type Description
12464 ---------- --------------- ------------------------------------------------------------------------------------
12465 animEl String/Element An id or Element from which the message box should animate as it opens and
12466 closes (defaults to undefined)
12467 buttons Object/Boolean A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
12468 cancel:'Bar'}), or false to not show any buttons (defaults to false)
12469 closable Boolean False to hide the top-right close button (defaults to true). Note that
12470 progress and wait dialogs will ignore this property and always hide the
12471 close button as they can only be closed programmatically.
12472 cls String A custom CSS class to apply to the message box element
12473 defaultTextHeight Number The default height in pixels of the message box's multiline textarea if
12474 displayed (defaults to 75)
12475 fn Function A callback function to execute after closing the dialog. The arguments to the
12476 function will be btn (the name of the button that was clicked, if applicable,
12477 e.g. "ok"), and text (the value of the active text field, if applicable).
12478 Progress and wait dialogs will ignore this option since they do not respond to
12479 user actions and can only be closed programmatically, so any required function
12480 should be called by the same code after it closes the dialog.
12481 icon String A CSS class that provides a background image to be used as an icon for
12482 the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
12483 maxWidth Number The maximum width in pixels of the message box (defaults to 600)
12484 minWidth Number The minimum width in pixels of the message box (defaults to 100)
12485 modal Boolean False to allow user interaction with the page while the message box is
12486 displayed (defaults to true)
12487 msg String A string that will replace the existing message box body text (defaults
12488 to the XHTML-compliant non-breaking space character ' ')
12489 multiline Boolean True to prompt the user to enter multi-line text (defaults to false)
12490 progress Boolean True to display a progress bar (defaults to false)
12491 progressText String The text to display inside the progress bar if progress = true (defaults to '')
12492 prompt Boolean True to prompt the user to enter single-line text (defaults to false)
12493 proxyDrag Boolean True to display a lightweight proxy while dragging (defaults to false)
12494 title String The title text
12495 value String The string value to set into the active textbox element if displayed
12496 wait Boolean True to display a progress bar (defaults to false)
12497 width Number The width of the dialog in pixels
12504 msg: 'Please enter your address:',
12506 buttons: Roo.MessageBox.OKCANCEL,
12509 animEl: 'addAddressBtn'
12512 * @param {Object} config Configuration options
12513 * @return {Roo.MessageBox} This message box
12515 show : function(options)
12518 // this causes nightmares if you show one dialog after another
12519 // especially on callbacks..
12521 if(this.isVisible()){
12524 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
12525 Roo.log("Old Dialog Message:" + msgEl.innerHTML );
12526 Roo.log("New Dialog Message:" + options.msg )
12527 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
12528 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
12531 var d = this.getDialog();
12533 d.setTitle(opt.title || " ");
12534 d.close.setDisplayed(opt.closable !== false);
12535 activeTextEl = textboxEl;
12536 opt.prompt = opt.prompt || (opt.multiline ? true : false);
12541 textareaEl.setHeight(typeof opt.multiline == "number" ?
12542 opt.multiline : this.defaultTextHeight);
12543 activeTextEl = textareaEl;
12552 progressEl.setDisplayed(opt.progress === true);
12553 this.updateProgress(0);
12554 activeTextEl.dom.value = opt.value || "";
12556 dlg.setDefaultButton(activeTextEl);
12558 var bs = opt.buttons;
12561 db = buttons["ok"];
12562 }else if(bs && bs.yes){
12563 db = buttons["yes"];
12565 dlg.setDefaultButton(db);
12567 bwidth = updateButtons(opt.buttons);
12568 this.updateText(opt.msg);
12570 d.el.addClass(opt.cls);
12572 d.proxyDrag = opt.proxyDrag === true;
12573 d.modal = opt.modal !== false;
12574 d.mask = opt.modal !== false ? mask : false;
12575 if(!d.isVisible()){
12576 // force it to the end of the z-index stack so it gets a cursor in FF
12577 document.body.appendChild(dlg.el.dom);
12578 d.animateTarget = null;
12579 d.show(options.animEl);
12586 * Displays a message box with a progress bar. This message box has no buttons and is not closeable by
12587 * the user. You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
12588 * and closing the message box when the process is complete.
12589 * @param {String} title The title bar text
12590 * @param {String} msg The message box body text
12591 * @return {Roo.MessageBox} This message box
12593 progress : function(title, msg){
12600 minWidth: this.minProgressWidth,
12607 * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
12608 * If a callback function is passed it will be called after the user clicks the button, and the
12609 * id of the button that was clicked will be passed as the only parameter to the callback
12610 * (could also be the top-right close button).
12611 * @param {String} title The title bar text
12612 * @param {String} msg The message box body text
12613 * @param {Function} fn (optional) The callback function invoked after the message box is closed
12614 * @param {Object} scope (optional) The scope of the callback function
12615 * @return {Roo.MessageBox} This message box
12617 alert : function(title, msg, fn, scope){
12630 * Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
12631 * interaction while waiting for a long-running process to complete that does not have defined intervals.
12632 * You are responsible for closing the message box when the process is complete.
12633 * @param {String} msg The message box body text
12634 * @param {String} title (optional) The title bar text
12635 * @return {Roo.MessageBox} This message box
12637 wait : function(msg, title){
12648 waitTimer = Roo.TaskMgr.start({
12650 Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
12658 * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
12659 * If a callback function is passed it will be called after the user clicks either button, and the id of the
12660 * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
12661 * @param {String} title The title bar text
12662 * @param {String} msg The message box body text
12663 * @param {Function} fn (optional) The callback function invoked after the message box is closed
12664 * @param {Object} scope (optional) The scope of the callback function
12665 * @return {Roo.MessageBox} This message box
12667 confirm : function(title, msg, fn, scope){
12671 buttons: this.YESNO,
12680 * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
12681 * JavaScript's Window.prompt). The prompt can be a single-line or multi-line textbox. If a callback function
12682 * is passed it will be called after the user clicks either button, and the id of the button that was clicked
12683 * (could also be the top-right close button) and the text that was entered will be passed as the two
12684 * parameters to the callback.
12685 * @param {String} title The title bar text
12686 * @param {String} msg The message box body text
12687 * @param {Function} fn (optional) The callback function invoked after the message box is closed
12688 * @param {Object} scope (optional) The scope of the callback function
12689 * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
12690 * property, or the height in pixels to create the textbox (defaults to false / single-line)
12691 * @return {Roo.MessageBox} This message box
12693 prompt : function(title, msg, fn, scope, multiline){
12697 buttons: this.OKCANCEL,
12702 multiline: multiline,
12709 * Button config that displays a single OK button
12714 * Button config that displays Yes and No buttons
12717 YESNO : {yes:true, no:true},
12719 * Button config that displays OK and Cancel buttons
12722 OKCANCEL : {ok:true, cancel:true},
12724 * Button config that displays Yes, No and Cancel buttons
12727 YESNOCANCEL : {yes:true, no:true, cancel:true},
12730 * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
12733 defaultTextHeight : 75,
12735 * The maximum width in pixels of the message box (defaults to 600)
12740 * The minimum width in pixels of the message box (defaults to 100)
12745 * The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
12746 * for setting a different minimum width than text-only dialogs may need (defaults to 250)
12749 minProgressWidth : 250,
12751 * An object containing the default button text strings that can be overriden for localized language support.
12752 * Supported properties are: ok, cancel, yes and no.
12753 * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
12766 * Shorthand for {@link Roo.MessageBox}
12768 Roo.Msg = Roo.MessageBox;/*
12770 * Ext JS Library 1.1.1
12771 * Copyright(c) 2006-2007, Ext JS, LLC.
12773 * Originally Released Under LGPL - original licence link has changed is not relivant.
12776 * <script type="text/javascript">
12779 * @class Roo.QuickTips
12780 * Provides attractive and customizable tooltips for any element.
12783 Roo.QuickTips = function(){
12784 var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
12785 var ce, bd, xy, dd;
12786 var visible = false, disabled = true, inited = false;
12787 var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
12789 var onOver = function(e){
12793 var t = e.getTarget();
12794 if(!t || t.nodeType !== 1 || t == document || t == document.body){
12797 if(ce && t == ce.el){
12798 clearTimeout(hideProc);
12801 if(t && tagEls[t.id]){
12802 tagEls[t.id].el = t;
12803 showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
12806 var ttp, et = Roo.fly(t);
12807 var ns = cfg.namespace;
12808 if(tm.interceptTitles && t.title){
12811 t.removeAttribute("title");
12812 e.preventDefault();
12814 ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
12817 showProc = show.defer(tm.showDelay, tm, [{
12819 text: ttp.replace(/\\n/g,'<br/>'),
12820 width: et.getAttributeNS(ns, cfg.width),
12821 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
12822 title: et.getAttributeNS(ns, cfg.title),
12823 cls: et.getAttributeNS(ns, cfg.cls)
12828 var onOut = function(e){
12829 clearTimeout(showProc);
12830 var t = e.getTarget();
12831 if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
12832 hideProc = setTimeout(hide, tm.hideDelay);
12836 var onMove = function(e){
12842 if(tm.trackMouse && ce){
12847 var onDown = function(e){
12848 clearTimeout(showProc);
12849 clearTimeout(hideProc);
12851 if(tm.hideOnClick){
12854 tm.enable.defer(100, tm);
12859 var getPad = function(){
12860 return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
12863 var show = function(o){
12867 clearTimeout(dismissProc);
12869 if(removeCls){ // in case manually hidden
12870 el.removeClass(removeCls);
12874 el.addClass(ce.cls);
12875 removeCls = ce.cls;
12878 tipTitle.update(ce.title);
12881 tipTitle.update('');
12884 el.dom.style.width = tm.maxWidth+'px';
12885 //tipBody.dom.style.width = '';
12886 tipBodyText.update(o.text);
12887 var p = getPad(), w = ce.width;
12889 var td = tipBodyText.dom;
12890 var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
12891 if(aw > tm.maxWidth){
12893 }else if(aw < tm.minWidth){
12899 //tipBody.setWidth(w);
12900 el.setWidth(parseInt(w, 10) + p);
12901 if(ce.autoHide === false){
12902 close.setDisplayed(true);
12907 close.setDisplayed(false);
12913 el.avoidY = xy[1]-18;
12918 el.setStyle("visibility", "visible");
12919 el.fadeIn({callback: afterShow});
12925 var afterShow = function(){
12929 if(tm.autoDismiss && ce.autoHide !== false){
12930 dismissProc = setTimeout(hide, tm.autoDismissDelay);
12935 var hide = function(noanim){
12936 clearTimeout(dismissProc);
12937 clearTimeout(hideProc);
12939 if(el.isVisible()){
12941 if(noanim !== true && tm.animate){
12942 el.fadeOut({callback: afterHide});
12949 var afterHide = function(){
12952 el.removeClass(removeCls);
12959 * @cfg {Number} minWidth
12960 * The minimum width of the quick tip (defaults to 40)
12964 * @cfg {Number} maxWidth
12965 * The maximum width of the quick tip (defaults to 300)
12969 * @cfg {Boolean} interceptTitles
12970 * True to automatically use the element's DOM title value if available (defaults to false)
12972 interceptTitles : false,
12974 * @cfg {Boolean} trackMouse
12975 * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
12977 trackMouse : false,
12979 * @cfg {Boolean} hideOnClick
12980 * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
12982 hideOnClick : true,
12984 * @cfg {Number} showDelay
12985 * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
12989 * @cfg {Number} hideDelay
12990 * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
12994 * @cfg {Boolean} autoHide
12995 * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
12996 * Used in conjunction with hideDelay.
13001 * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
13002 * (defaults to true). Used in conjunction with autoDismissDelay.
13004 autoDismiss : true,
13007 * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
13009 autoDismissDelay : 5000,
13011 * @cfg {Boolean} animate
13012 * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
13017 * @cfg {String} title
13018 * Title text to display (defaults to ''). This can be any valid HTML markup.
13022 * @cfg {String} text
13023 * Body text to display (defaults to ''). This can be any valid HTML markup.
13027 * @cfg {String} cls
13028 * A CSS class to apply to the base quick tip element (defaults to '').
13032 * @cfg {Number} width
13033 * Width in pixels of the quick tip (defaults to auto). Width will be ignored if it exceeds the bounds of
13034 * minWidth or maxWidth.
13039 * Initialize and enable QuickTips for first use. This should be called once before the first attempt to access
13040 * or display QuickTips in a page.
13043 tm = Roo.QuickTips;
13044 cfg = tm.tagConfig;
13046 if(!Roo.isReady){ // allow calling of init() before onReady
13047 Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
13050 el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
13051 el.fxDefaults = {stopFx: true};
13052 // maximum custom styling
13053 //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>');
13054 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>');
13055 tipTitle = el.child('h3');
13056 tipTitle.enableDisplayMode("block");
13057 tipBody = el.child('div.x-tip-bd');
13058 tipBodyText = el.child('div.x-tip-bd-inner');
13059 //bdLeft = el.child('div.x-tip-bd-left');
13060 //bdRight = el.child('div.x-tip-bd-right');
13061 close = el.child('div.x-tip-close');
13062 close.enableDisplayMode("block");
13063 close.on("click", hide);
13064 var d = Roo.get(document);
13065 d.on("mousedown", onDown);
13066 d.on("mouseover", onOver);
13067 d.on("mouseout", onOut);
13068 d.on("mousemove", onMove);
13069 esc = d.addKeyListener(27, hide);
13072 dd = el.initDD("default", null, {
13073 onDrag : function(){
13077 dd.setHandleElId(tipTitle.id);
13086 * Configures a new quick tip instance and assigns it to a target element. The following config options
13089 Property Type Description
13090 ---------- --------------------- ------------------------------------------------------------------------
13091 target Element/String/Array An Element, id or array of ids that this quick tip should be tied to
13093 * @param {Object} config The config object
13095 register : function(config){
13096 var cs = config instanceof Array ? config : arguments;
13097 for(var i = 0, len = cs.length; i < len; i++) {
13099 var target = c.target;
13101 if(target instanceof Array){
13102 for(var j = 0, jlen = target.length; j < jlen; j++){
13103 tagEls[target[j]] = c;
13106 tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
13113 * Removes this quick tip from its element and destroys it.
13114 * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
13116 unregister : function(el){
13117 delete tagEls[Roo.id(el)];
13121 * Enable this quick tip.
13123 enable : function(){
13124 if(inited && disabled){
13126 if(locks.length < 1){
13133 * Disable this quick tip.
13135 disable : function(){
13137 clearTimeout(showProc);
13138 clearTimeout(hideProc);
13139 clearTimeout(dismissProc);
13147 * Returns true if the quick tip is enabled, else false.
13149 isEnabled : function(){
13155 namespace : "roo", // was ext?? this may break..
13156 alt_namespace : "ext",
13157 attribute : "qtip",
13167 // backwards compat
13168 Roo.QuickTips.tips = Roo.QuickTips.register;/*
13170 * Ext JS Library 1.1.1
13171 * Copyright(c) 2006-2007, Ext JS, LLC.
13173 * Originally Released Under LGPL - original licence link has changed is not relivant.
13176 * <script type="text/javascript">
13181 * @class Roo.tree.TreePanel
13182 * @extends Roo.data.Tree
13183 * @cfg {Roo.tree.TreeNode} root The root node
13184 * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
13185 * @cfg {Boolean} lines false to disable tree lines (defaults to true)
13186 * @cfg {Boolean} enableDD true to enable drag and drop
13187 * @cfg {Boolean} enableDrag true to enable just drag
13188 * @cfg {Boolean} enableDrop true to enable just drop
13189 * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
13190 * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
13191 * @cfg {String} ddGroup The DD group this TreePanel belongs to
13192 * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
13193 * @cfg {Boolean} ddScroll true to enable YUI body scrolling
13194 * @cfg {Boolean} containerScroll true to register this container with ScrollManager
13195 * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
13196 * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
13197 * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
13198 * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
13199 * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
13200 * @cfg {Roo.tree.TreeLoader} loader A TreeLoader for use with this TreePanel
13201 * @cfg {Roo.tree.TreeEditor} editor The TreeEditor to display when clicked.
13202 * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
13203 * @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>
13204 * @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>
13207 * @param {String/HTMLElement/Element} el The container element
13208 * @param {Object} config
13210 Roo.tree.TreePanel = function(el, config){
13212 var loader = false;
13214 root = config.root;
13215 delete config.root;
13217 if (config.loader) {
13218 loader = config.loader;
13219 delete config.loader;
13222 Roo.apply(this, config);
13223 Roo.tree.TreePanel.superclass.constructor.call(this);
13224 this.el = Roo.get(el);
13225 this.el.addClass('x-tree');
13226 //console.log(root);
13228 this.setRootNode( Roo.factory(root, Roo.tree));
13231 this.loader = Roo.factory(loader, Roo.tree);
13234 * Read-only. The id of the container element becomes this TreePanel's id.
13236 this.id = this.el.id;
13239 * @event beforeload
13240 * Fires before a node is loaded, return false to cancel
13241 * @param {Node} node The node being loaded
13243 "beforeload" : true,
13246 * Fires when a node is loaded
13247 * @param {Node} node The node that was loaded
13251 * @event textchange
13252 * Fires when the text for a node is changed
13253 * @param {Node} node The node
13254 * @param {String} text The new text
13255 * @param {String} oldText The old text
13257 "textchange" : true,
13259 * @event beforeexpand
13260 * Fires before a node is expanded, return false to cancel.
13261 * @param {Node} node The node
13262 * @param {Boolean} deep
13263 * @param {Boolean} anim
13265 "beforeexpand" : true,
13267 * @event beforecollapse
13268 * Fires before a node is collapsed, return false to cancel.
13269 * @param {Node} node The node
13270 * @param {Boolean} deep
13271 * @param {Boolean} anim
13273 "beforecollapse" : true,
13276 * Fires when a node is expanded
13277 * @param {Node} node The node
13281 * @event disabledchange
13282 * Fires when the disabled status of a node changes
13283 * @param {Node} node The node
13284 * @param {Boolean} disabled
13286 "disabledchange" : true,
13289 * Fires when a node is collapsed
13290 * @param {Node} node The node
13294 * @event beforeclick
13295 * Fires before click processing on a node. Return false to cancel the default action.
13296 * @param {Node} node The node
13297 * @param {Roo.EventObject} e The event object
13299 "beforeclick":true,
13301 * @event checkchange
13302 * Fires when a node with a checkbox's checked property changes
13303 * @param {Node} this This node
13304 * @param {Boolean} checked
13306 "checkchange":true,
13309 * Fires when a node is clicked
13310 * @param {Node} node The node
13311 * @param {Roo.EventObject} e The event object
13316 * Fires when a node is double clicked
13317 * @param {Node} node The node
13318 * @param {Roo.EventObject} e The event object
13322 * @event contextmenu
13323 * Fires when a node is right clicked
13324 * @param {Node} node The node
13325 * @param {Roo.EventObject} e The event object
13327 "contextmenu":true,
13329 * @event beforechildrenrendered
13330 * Fires right before the child nodes for a node are rendered
13331 * @param {Node} node The node
13333 "beforechildrenrendered":true,
13336 * Fires when a node starts being dragged
13337 * @param {Roo.tree.TreePanel} this
13338 * @param {Roo.tree.TreeNode} node
13339 * @param {event} e The raw browser event
13341 "startdrag" : true,
13344 * Fires when a drag operation is complete
13345 * @param {Roo.tree.TreePanel} this
13346 * @param {Roo.tree.TreeNode} node
13347 * @param {event} e The raw browser event
13352 * Fires when a dragged node is dropped on a valid DD target
13353 * @param {Roo.tree.TreePanel} this
13354 * @param {Roo.tree.TreeNode} node
13355 * @param {DD} dd The dd it was dropped on
13356 * @param {event} e The raw browser event
13360 * @event beforenodedrop
13361 * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
13362 * passed to handlers has the following properties:<br />
13363 * <ul style="padding:5px;padding-left:16px;">
13364 * <li>tree - The TreePanel</li>
13365 * <li>target - The node being targeted for the drop</li>
13366 * <li>data - The drag data from the drag source</li>
13367 * <li>point - The point of the drop - append, above or below</li>
13368 * <li>source - The drag source</li>
13369 * <li>rawEvent - Raw mouse event</li>
13370 * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
13371 * to be inserted by setting them on this object.</li>
13372 * <li>cancel - Set this to true to cancel the drop.</li>
13374 * @param {Object} dropEvent
13376 "beforenodedrop" : true,
13379 * Fires after a DD object is dropped on a node in this tree. The dropEvent
13380 * passed to handlers has the following properties:<br />
13381 * <ul style="padding:5px;padding-left:16px;">
13382 * <li>tree - The TreePanel</li>
13383 * <li>target - The node being targeted for the drop</li>
13384 * <li>data - The drag data from the drag source</li>
13385 * <li>point - The point of the drop - append, above or below</li>
13386 * <li>source - The drag source</li>
13387 * <li>rawEvent - Raw mouse event</li>
13388 * <li>dropNode - Dropped node(s).</li>
13390 * @param {Object} dropEvent
13394 * @event nodedragover
13395 * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
13396 * passed to handlers has the following properties:<br />
13397 * <ul style="padding:5px;padding-left:16px;">
13398 * <li>tree - The TreePanel</li>
13399 * <li>target - The node being targeted for the drop</li>
13400 * <li>data - The drag data from the drag source</li>
13401 * <li>point - The point of the drop - append, above or below</li>
13402 * <li>source - The drag source</li>
13403 * <li>rawEvent - Raw mouse event</li>
13404 * <li>dropNode - Drop node(s) provided by the source.</li>
13405 * <li>cancel - Set this to true to signal drop not allowed.</li>
13407 * @param {Object} dragOverEvent
13409 "nodedragover" : true,
13411 * @event appendnode
13412 * Fires when append node to the tree
13413 * @param {Roo.tree.TreePanel} this
13414 * @param {Roo.tree.TreeNode} node
13415 * @param {Number} index The index of the newly appended node
13417 "appendnode" : true
13420 if(this.singleExpand){
13421 this.on("beforeexpand", this.restrictExpand, this);
13424 this.editor.tree = this;
13425 this.editor = Roo.factory(this.editor, Roo.tree);
13428 if (this.selModel) {
13429 this.selModel = Roo.factory(this.selModel, Roo.tree);
13433 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
13434 rootVisible : true,
13435 animate: Roo.enableFx,
13438 hlDrop : Roo.enableFx,
13442 rendererTip: false,
13444 restrictExpand : function(node){
13445 var p = node.parentNode;
13447 if(p.expandedChild && p.expandedChild.parentNode == p){
13448 p.expandedChild.collapse();
13450 p.expandedChild = node;
13454 // private override
13455 setRootNode : function(node){
13456 Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
13457 if(!this.rootVisible){
13458 node.ui = new Roo.tree.RootTreeNodeUI(node);
13464 * Returns the container element for this TreePanel
13466 getEl : function(){
13471 * Returns the default TreeLoader for this TreePanel
13473 getLoader : function(){
13474 return this.loader;
13480 expandAll : function(){
13481 this.root.expand(true);
13485 * Collapse all nodes
13487 collapseAll : function(){
13488 this.root.collapse(true);
13492 * Returns the selection model used by this TreePanel
13494 getSelectionModel : function(){
13495 if(!this.selModel){
13496 this.selModel = new Roo.tree.DefaultSelectionModel();
13498 return this.selModel;
13502 * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
13503 * @param {String} attribute (optional) Defaults to null (return the actual nodes)
13504 * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
13507 getChecked : function(a, startNode){
13508 startNode = startNode || this.root;
13510 var f = function(){
13511 if(this.attributes.checked){
13512 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
13515 startNode.cascade(f);
13520 * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
13521 * @param {String} path
13522 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
13523 * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
13524 * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
13526 expandPath : function(path, attr, callback){
13527 attr = attr || "id";
13528 var keys = path.split(this.pathSeparator);
13529 var curNode = this.root;
13530 if(curNode.attributes[attr] != keys[1]){ // invalid root
13532 callback(false, null);
13537 var f = function(){
13538 if(++index == keys.length){
13540 callback(true, curNode);
13544 var c = curNode.findChild(attr, keys[index]);
13547 callback(false, curNode);
13552 c.expand(false, false, f);
13554 curNode.expand(false, false, f);
13558 * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
13559 * @param {String} path
13560 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
13561 * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
13562 * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
13564 selectPath : function(path, attr, callback){
13565 attr = attr || "id";
13566 var keys = path.split(this.pathSeparator);
13567 var v = keys.pop();
13568 if(keys.length > 0){
13569 var f = function(success, node){
13570 if(success && node){
13571 var n = node.findChild(attr, v);
13577 }else if(callback){
13578 callback(false, n);
13582 callback(false, n);
13586 this.expandPath(keys.join(this.pathSeparator), attr, f);
13588 this.root.select();
13590 callback(true, this.root);
13595 getTreeEl : function(){
13600 * Trigger rendering of this TreePanel
13602 render : function(){
13603 if (this.innerCt) {
13604 return this; // stop it rendering more than once!!
13607 this.innerCt = this.el.createChild({tag:"ul",
13608 cls:"x-tree-root-ct " +
13609 (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
13611 if(this.containerScroll){
13612 Roo.dd.ScrollManager.register(this.el);
13614 if((this.enableDD || this.enableDrop) && !this.dropZone){
13616 * The dropZone used by this tree if drop is enabled
13617 * @type Roo.tree.TreeDropZone
13619 this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
13620 ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
13623 if((this.enableDD || this.enableDrag) && !this.dragZone){
13625 * The dragZone used by this tree if drag is enabled
13626 * @type Roo.tree.TreeDragZone
13628 this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
13629 ddGroup: this.ddGroup || "TreeDD",
13630 scroll: this.ddScroll
13633 this.getSelectionModel().init(this);
13635 Roo.log("ROOT not set in tree");
13638 this.root.render();
13639 if(!this.rootVisible){
13640 this.root.renderChildren();
13646 * Ext JS Library 1.1.1
13647 * Copyright(c) 2006-2007, Ext JS, LLC.
13649 * Originally Released Under LGPL - original licence link has changed is not relivant.
13652 * <script type="text/javascript">
13657 * @class Roo.tree.DefaultSelectionModel
13658 * @extends Roo.util.Observable
13659 * The default single selection for a TreePanel.
13660 * @param {Object} cfg Configuration
13662 Roo.tree.DefaultSelectionModel = function(cfg){
13663 this.selNode = null;
13669 * @event selectionchange
13670 * Fires when the selected node changes
13671 * @param {DefaultSelectionModel} this
13672 * @param {TreeNode} node the new selection
13674 "selectionchange" : true,
13677 * @event beforeselect
13678 * Fires before the selected node changes, return false to cancel the change
13679 * @param {DefaultSelectionModel} this
13680 * @param {TreeNode} node the new selection
13681 * @param {TreeNode} node the old selection
13683 "beforeselect" : true
13686 Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
13689 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
13690 init : function(tree){
13692 tree.getTreeEl().on("keydown", this.onKeyDown, this);
13693 tree.on("click", this.onNodeClick, this);
13696 onNodeClick : function(node, e){
13697 if (e.ctrlKey && this.selNode == node) {
13698 this.unselect(node);
13706 * @param {TreeNode} node The node to select
13707 * @return {TreeNode} The selected node
13709 select : function(node){
13710 var last = this.selNode;
13711 if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
13713 last.ui.onSelectedChange(false);
13715 this.selNode = node;
13716 node.ui.onSelectedChange(true);
13717 this.fireEvent("selectionchange", this, node, last);
13724 * @param {TreeNode} node The node to unselect
13726 unselect : function(node){
13727 if(this.selNode == node){
13728 this.clearSelections();
13733 * Clear all selections
13735 clearSelections : function(){
13736 var n = this.selNode;
13738 n.ui.onSelectedChange(false);
13739 this.selNode = null;
13740 this.fireEvent("selectionchange", this, null);
13746 * Get the selected node
13747 * @return {TreeNode} The selected node
13749 getSelectedNode : function(){
13750 return this.selNode;
13754 * Returns true if the node is selected
13755 * @param {TreeNode} node The node to check
13756 * @return {Boolean}
13758 isSelected : function(node){
13759 return this.selNode == node;
13763 * Selects the node above the selected node in the tree, intelligently walking the nodes
13764 * @return TreeNode The new selection
13766 selectPrevious : function(){
13767 var s = this.selNode || this.lastSelNode;
13771 var ps = s.previousSibling;
13773 if(!ps.isExpanded() || ps.childNodes.length < 1){
13774 return this.select(ps);
13776 var lc = ps.lastChild;
13777 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
13780 return this.select(lc);
13782 } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
13783 return this.select(s.parentNode);
13789 * Selects the node above the selected node in the tree, intelligently walking the nodes
13790 * @return TreeNode The new selection
13792 selectNext : function(){
13793 var s = this.selNode || this.lastSelNode;
13797 if(s.firstChild && s.isExpanded()){
13798 return this.select(s.firstChild);
13799 }else if(s.nextSibling){
13800 return this.select(s.nextSibling);
13801 }else if(s.parentNode){
13803 s.parentNode.bubble(function(){
13804 if(this.nextSibling){
13805 newS = this.getOwnerTree().selModel.select(this.nextSibling);
13814 onKeyDown : function(e){
13815 var s = this.selNode || this.lastSelNode;
13816 // undesirable, but required
13821 var k = e.getKey();
13829 this.selectPrevious();
13832 e.preventDefault();
13833 if(s.hasChildNodes()){
13834 if(!s.isExpanded()){
13836 }else if(s.firstChild){
13837 this.select(s.firstChild, e);
13842 e.preventDefault();
13843 if(s.hasChildNodes() && s.isExpanded()){
13845 }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
13846 this.select(s.parentNode, e);
13854 * @class Roo.tree.MultiSelectionModel
13855 * @extends Roo.util.Observable
13856 * Multi selection for a TreePanel.
13857 * @param {Object} cfg Configuration
13859 Roo.tree.MultiSelectionModel = function(){
13860 this.selNodes = [];
13864 * @event selectionchange
13865 * Fires when the selected nodes change
13866 * @param {MultiSelectionModel} this
13867 * @param {Array} nodes Array of the selected nodes
13869 "selectionchange" : true
13871 Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
13875 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
13876 init : function(tree){
13878 tree.getTreeEl().on("keydown", this.onKeyDown, this);
13879 tree.on("click", this.onNodeClick, this);
13882 onNodeClick : function(node, e){
13883 this.select(node, e, e.ctrlKey);
13888 * @param {TreeNode} node The node to select
13889 * @param {EventObject} e (optional) An event associated with the selection
13890 * @param {Boolean} keepExisting True to retain existing selections
13891 * @return {TreeNode} The selected node
13893 select : function(node, e, keepExisting){
13894 if(keepExisting !== true){
13895 this.clearSelections(true);
13897 if(this.isSelected(node)){
13898 this.lastSelNode = node;
13901 this.selNodes.push(node);
13902 this.selMap[node.id] = node;
13903 this.lastSelNode = node;
13904 node.ui.onSelectedChange(true);
13905 this.fireEvent("selectionchange", this, this.selNodes);
13911 * @param {TreeNode} node The node to unselect
13913 unselect : function(node){
13914 if(this.selMap[node.id]){
13915 node.ui.onSelectedChange(false);
13916 var sn = this.selNodes;
13919 index = sn.indexOf(node);
13921 for(var i = 0, len = sn.length; i < len; i++){
13929 this.selNodes.splice(index, 1);
13931 delete this.selMap[node.id];
13932 this.fireEvent("selectionchange", this, this.selNodes);
13937 * Clear all selections
13939 clearSelections : function(suppressEvent){
13940 var sn = this.selNodes;
13942 for(var i = 0, len = sn.length; i < len; i++){
13943 sn[i].ui.onSelectedChange(false);
13945 this.selNodes = [];
13947 if(suppressEvent !== true){
13948 this.fireEvent("selectionchange", this, this.selNodes);
13954 * Returns true if the node is selected
13955 * @param {TreeNode} node The node to check
13956 * @return {Boolean}
13958 isSelected : function(node){
13959 return this.selMap[node.id] ? true : false;
13963 * Returns an array of the selected nodes
13966 getSelectedNodes : function(){
13967 return this.selNodes;
13970 onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
13972 selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
13974 selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
13977 * Ext JS Library 1.1.1
13978 * Copyright(c) 2006-2007, Ext JS, LLC.
13980 * Originally Released Under LGPL - original licence link has changed is not relivant.
13983 * <script type="text/javascript">
13987 * @class Roo.tree.TreeNode
13988 * @extends Roo.data.Node
13989 * @cfg {String} text The text for this node
13990 * @cfg {Boolean} expanded true to start the node expanded
13991 * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
13992 * @cfg {Boolean} allowDrop false if this node cannot be drop on
13993 * @cfg {Boolean} disabled true to start the node disabled
13994 * @cfg {String} icon The path to an icon for the node. The preferred way to do this
13995 * is to use the cls or iconCls attributes and add the icon via a CSS background image.
13996 * @cfg {String} cls A css class to be added to the node
13997 * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
13998 * @cfg {String} href URL of the link used for the node (defaults to #)
13999 * @cfg {String} hrefTarget target frame for the link
14000 * @cfg {String} qtip An Ext QuickTip for the node
14001 * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
14002 * @cfg {Boolean} singleClickExpand True for single click expand on this node
14003 * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
14004 * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
14005 * (defaults to undefined with no checkbox rendered)
14007 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
14009 Roo.tree.TreeNode = function(attributes){
14010 attributes = attributes || {};
14011 if(typeof attributes == "string"){
14012 attributes = {text: attributes};
14014 this.childrenRendered = false;
14015 this.rendered = false;
14016 Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
14017 this.expanded = attributes.expanded === true;
14018 this.isTarget = attributes.isTarget !== false;
14019 this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
14020 this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
14023 * Read-only. The text for this node. To change it use setText().
14026 this.text = attributes.text;
14028 * True if this node is disabled.
14031 this.disabled = attributes.disabled === true;
14035 * @event textchange
14036 * Fires when the text for this node is changed
14037 * @param {Node} this This node
14038 * @param {String} text The new text
14039 * @param {String} oldText The old text
14041 "textchange" : true,
14043 * @event beforeexpand
14044 * Fires before this node is expanded, return false to cancel.
14045 * @param {Node} this This node
14046 * @param {Boolean} deep
14047 * @param {Boolean} anim
14049 "beforeexpand" : true,
14051 * @event beforecollapse
14052 * Fires before this node is collapsed, return false to cancel.
14053 * @param {Node} this This node
14054 * @param {Boolean} deep
14055 * @param {Boolean} anim
14057 "beforecollapse" : true,
14060 * Fires when this node is expanded
14061 * @param {Node} this This node
14065 * @event disabledchange
14066 * Fires when the disabled status of this node changes
14067 * @param {Node} this This node
14068 * @param {Boolean} disabled
14070 "disabledchange" : true,
14073 * Fires when this node is collapsed
14074 * @param {Node} this This node
14078 * @event beforeclick
14079 * Fires before click processing. Return false to cancel the default action.
14080 * @param {Node} this This node
14081 * @param {Roo.EventObject} e The event object
14083 "beforeclick":true,
14085 * @event checkchange
14086 * Fires when a node with a checkbox's checked property changes
14087 * @param {Node} this This node
14088 * @param {Boolean} checked
14090 "checkchange":true,
14093 * Fires when this node is clicked
14094 * @param {Node} this This node
14095 * @param {Roo.EventObject} e The event object
14100 * Fires when this node is double clicked
14101 * @param {Node} this This node
14102 * @param {Roo.EventObject} e The event object
14106 * @event contextmenu
14107 * Fires when this node is right clicked
14108 * @param {Node} this This node
14109 * @param {Roo.EventObject} e The event object
14111 "contextmenu":true,
14113 * @event beforechildrenrendered
14114 * Fires right before the child nodes for this node are rendered
14115 * @param {Node} this This node
14117 "beforechildrenrendered":true
14120 var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
14123 * Read-only. The UI for this node
14126 this.ui = new uiClass(this);
14128 // finally support items[]
14129 if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
14134 Roo.each(this.attributes.items, function(c) {
14135 this.appendChild(Roo.factory(c,Roo.Tree));
14137 delete this.attributes.items;
14142 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
14143 preventHScroll: true,
14145 * Returns true if this node is expanded
14146 * @return {Boolean}
14148 isExpanded : function(){
14149 return this.expanded;
14153 * Returns the UI object for this node
14154 * @return {TreeNodeUI}
14156 getUI : function(){
14160 // private override
14161 setFirstChild : function(node){
14162 var of = this.firstChild;
14163 Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
14164 if(this.childrenRendered && of && node != of){
14165 of.renderIndent(true, true);
14168 this.renderIndent(true, true);
14172 // private override
14173 setLastChild : function(node){
14174 var ol = this.lastChild;
14175 Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
14176 if(this.childrenRendered && ol && node != ol){
14177 ol.renderIndent(true, true);
14180 this.renderIndent(true, true);
14184 // these methods are overridden to provide lazy rendering support
14185 // private override
14186 appendChild : function()
14188 var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
14189 if(node && this.childrenRendered){
14192 this.ui.updateExpandIcon();
14196 // private override
14197 removeChild : function(node){
14198 this.ownerTree.getSelectionModel().unselect(node);
14199 Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
14200 // if it's been rendered remove dom node
14201 if(this.childrenRendered){
14204 if(this.childNodes.length < 1){
14205 this.collapse(false, false);
14207 this.ui.updateExpandIcon();
14209 if(!this.firstChild) {
14210 this.childrenRendered = false;
14215 // private override
14216 insertBefore : function(node, refNode){
14217 var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
14218 if(newNode && refNode && this.childrenRendered){
14221 this.ui.updateExpandIcon();
14226 * Sets the text for this node
14227 * @param {String} text
14229 setText : function(text){
14230 var oldText = this.text;
14232 this.attributes.text = text;
14233 if(this.rendered){ // event without subscribing
14234 this.ui.onTextChange(this, text, oldText);
14236 this.fireEvent("textchange", this, text, oldText);
14240 * Triggers selection of this node
14242 select : function(){
14243 this.getOwnerTree().getSelectionModel().select(this);
14247 * Triggers deselection of this node
14249 unselect : function(){
14250 this.getOwnerTree().getSelectionModel().unselect(this);
14254 * Returns true if this node is selected
14255 * @return {Boolean}
14257 isSelected : function(){
14258 return this.getOwnerTree().getSelectionModel().isSelected(this);
14262 * Expand this node.
14263 * @param {Boolean} deep (optional) True to expand all children as well
14264 * @param {Boolean} anim (optional) false to cancel the default animation
14265 * @param {Function} callback (optional) A callback to be called when
14266 * expanding this node completes (does not wait for deep expand to complete).
14267 * Called with 1 parameter, this node.
14269 expand : function(deep, anim, callback){
14270 if(!this.expanded){
14271 if(this.fireEvent("beforeexpand", this, deep, anim) === false){
14274 if(!this.childrenRendered){
14275 this.renderChildren();
14277 this.expanded = true;
14279 if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
14280 this.ui.animExpand(function(){
14281 this.fireEvent("expand", this);
14282 if(typeof callback == "function"){
14286 this.expandChildNodes(true);
14288 }.createDelegate(this));
14292 this.fireEvent("expand", this);
14293 if(typeof callback == "function"){
14298 if(typeof callback == "function"){
14303 this.expandChildNodes(true);
14307 isHiddenRoot : function(){
14308 return this.isRoot && !this.getOwnerTree().rootVisible;
14312 * Collapse this node.
14313 * @param {Boolean} deep (optional) True to collapse all children as well
14314 * @param {Boolean} anim (optional) false to cancel the default animation
14316 collapse : function(deep, anim){
14317 if(this.expanded && !this.isHiddenRoot()){
14318 if(this.fireEvent("beforecollapse", this, deep, anim) === false){
14321 this.expanded = false;
14322 if((this.getOwnerTree().animate && anim !== false) || anim){
14323 this.ui.animCollapse(function(){
14324 this.fireEvent("collapse", this);
14326 this.collapseChildNodes(true);
14328 }.createDelegate(this));
14331 this.ui.collapse();
14332 this.fireEvent("collapse", this);
14336 var cs = this.childNodes;
14337 for(var i = 0, len = cs.length; i < len; i++) {
14338 cs[i].collapse(true, false);
14344 delayedExpand : function(delay){
14345 if(!this.expandProcId){
14346 this.expandProcId = this.expand.defer(delay, this);
14351 cancelExpand : function(){
14352 if(this.expandProcId){
14353 clearTimeout(this.expandProcId);
14355 this.expandProcId = false;
14359 * Toggles expanded/collapsed state of the node
14361 toggle : function(){
14370 * Ensures all parent nodes are expanded
14372 ensureVisible : function(callback){
14373 var tree = this.getOwnerTree();
14374 tree.expandPath(this.parentNode.getPath(), false, function(){
14375 tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
14376 Roo.callback(callback);
14377 }.createDelegate(this));
14381 * Expand all child nodes
14382 * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
14384 expandChildNodes : function(deep){
14385 var cs = this.childNodes;
14386 for(var i = 0, len = cs.length; i < len; i++) {
14387 cs[i].expand(deep);
14392 * Collapse all child nodes
14393 * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
14395 collapseChildNodes : function(deep){
14396 var cs = this.childNodes;
14397 for(var i = 0, len = cs.length; i < len; i++) {
14398 cs[i].collapse(deep);
14403 * Disables this node
14405 disable : function(){
14406 this.disabled = true;
14408 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
14409 this.ui.onDisableChange(this, true);
14411 this.fireEvent("disabledchange", this, true);
14415 * Enables this node
14417 enable : function(){
14418 this.disabled = false;
14419 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
14420 this.ui.onDisableChange(this, false);
14422 this.fireEvent("disabledchange", this, false);
14426 renderChildren : function(suppressEvent){
14427 if(suppressEvent !== false){
14428 this.fireEvent("beforechildrenrendered", this);
14430 var cs = this.childNodes;
14431 for(var i = 0, len = cs.length; i < len; i++){
14432 cs[i].render(true);
14434 this.childrenRendered = true;
14438 sort : function(fn, scope){
14439 Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
14440 if(this.childrenRendered){
14441 var cs = this.childNodes;
14442 for(var i = 0, len = cs.length; i < len; i++){
14443 cs[i].render(true);
14449 render : function(bulkRender){
14450 this.ui.render(bulkRender);
14451 if(!this.rendered){
14452 this.rendered = true;
14454 this.expanded = false;
14455 this.expand(false, false);
14461 renderIndent : function(deep, refresh){
14463 this.ui.childIndent = null;
14465 this.ui.renderIndent();
14466 if(deep === true && this.childrenRendered){
14467 var cs = this.childNodes;
14468 for(var i = 0, len = cs.length; i < len; i++){
14469 cs[i].renderIndent(true, refresh);
14475 * Ext JS Library 1.1.1
14476 * Copyright(c) 2006-2007, Ext JS, LLC.
14478 * Originally Released Under LGPL - original licence link has changed is not relivant.
14481 * <script type="text/javascript">
14485 * @class Roo.tree.AsyncTreeNode
14486 * @extends Roo.tree.TreeNode
14487 * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
14489 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
14491 Roo.tree.AsyncTreeNode = function(config){
14492 this.loaded = false;
14493 this.loading = false;
14494 Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
14496 * @event beforeload
14497 * Fires before this node is loaded, return false to cancel
14498 * @param {Node} this This node
14500 this.addEvents({'beforeload':true, 'load': true});
14503 * Fires when this node is loaded
14504 * @param {Node} this This node
14507 * The loader used by this node (defaults to using the tree's defined loader)
14512 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
14513 expand : function(deep, anim, callback){
14514 if(this.loading){ // if an async load is already running, waiting til it's done
14516 var f = function(){
14517 if(!this.loading){ // done loading
14518 clearInterval(timer);
14519 this.expand(deep, anim, callback);
14521 }.createDelegate(this);
14522 timer = setInterval(f, 200);
14526 if(this.fireEvent("beforeload", this) === false){
14529 this.loading = true;
14530 this.ui.beforeLoad(this);
14531 var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
14533 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
14537 Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
14541 * Returns true if this node is currently loading
14542 * @return {Boolean}
14544 isLoading : function(){
14545 return this.loading;
14548 loadComplete : function(deep, anim, callback){
14549 this.loading = false;
14550 this.loaded = true;
14551 this.ui.afterLoad(this);
14552 this.fireEvent("load", this);
14553 this.expand(deep, anim, callback);
14557 * Returns true if this node has been loaded
14558 * @return {Boolean}
14560 isLoaded : function(){
14561 return this.loaded;
14564 hasChildNodes : function(){
14565 if(!this.isLeaf() && !this.loaded){
14568 return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
14573 * Trigger a reload for this node
14574 * @param {Function} callback
14576 reload : function(callback){
14577 this.collapse(false, false);
14578 while(this.firstChild){
14579 this.removeChild(this.firstChild);
14581 this.childrenRendered = false;
14582 this.loaded = false;
14583 if(this.isHiddenRoot()){
14584 this.expanded = false;
14586 this.expand(false, false, callback);
14590 * Ext JS Library 1.1.1
14591 * Copyright(c) 2006-2007, Ext JS, LLC.
14593 * Originally Released Under LGPL - original licence link has changed is not relivant.
14596 * <script type="text/javascript">
14600 * @class Roo.tree.TreeNodeUI
14602 * @param {Object} node The node to render
14603 * The TreeNode UI implementation is separate from the
14604 * tree implementation. Unless you are customizing the tree UI,
14605 * you should never have to use this directly.
14607 Roo.tree.TreeNodeUI = function(node){
14609 this.rendered = false;
14610 this.animating = false;
14611 this.emptyIcon = Roo.BLANK_IMAGE_URL;
14614 Roo.tree.TreeNodeUI.prototype = {
14615 removeChild : function(node){
14617 this.ctNode.removeChild(node.ui.getEl());
14621 beforeLoad : function(){
14622 this.addClass("x-tree-node-loading");
14625 afterLoad : function(){
14626 this.removeClass("x-tree-node-loading");
14629 onTextChange : function(node, text, oldText){
14631 this.textNode.innerHTML = text;
14635 onDisableChange : function(node, state){
14636 this.disabled = state;
14638 this.addClass("x-tree-node-disabled");
14640 this.removeClass("x-tree-node-disabled");
14644 onSelectedChange : function(state){
14647 this.addClass("x-tree-selected");
14650 this.removeClass("x-tree-selected");
14654 onMove : function(tree, node, oldParent, newParent, index, refNode){
14655 this.childIndent = null;
14657 var targetNode = newParent.ui.getContainer();
14658 if(!targetNode){//target not rendered
14659 this.holder = document.createElement("div");
14660 this.holder.appendChild(this.wrap);
14663 var insertBefore = refNode ? refNode.ui.getEl() : null;
14665 targetNode.insertBefore(this.wrap, insertBefore);
14667 targetNode.appendChild(this.wrap);
14669 this.node.renderIndent(true);
14673 addClass : function(cls){
14675 Roo.fly(this.elNode).addClass(cls);
14679 removeClass : function(cls){
14681 Roo.fly(this.elNode).removeClass(cls);
14685 remove : function(){
14687 this.holder = document.createElement("div");
14688 this.holder.appendChild(this.wrap);
14692 fireEvent : function(){
14693 return this.node.fireEvent.apply(this.node, arguments);
14696 initEvents : function(){
14697 this.node.on("move", this.onMove, this);
14698 var E = Roo.EventManager;
14699 var a = this.anchor;
14701 var el = Roo.fly(a, '_treeui');
14703 if(Roo.isOpera){ // opera render bug ignores the CSS
14704 el.setStyle("text-decoration", "none");
14707 el.on("click", this.onClick, this);
14708 el.on("dblclick", this.onDblClick, this);
14711 Roo.EventManager.on(this.checkbox,
14712 Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
14715 el.on("contextmenu", this.onContextMenu, this);
14717 var icon = Roo.fly(this.iconNode);
14718 icon.on("click", this.onClick, this);
14719 icon.on("dblclick", this.onDblClick, this);
14720 icon.on("contextmenu", this.onContextMenu, this);
14721 E.on(this.ecNode, "click", this.ecClick, this, true);
14723 if(this.node.disabled){
14724 this.addClass("x-tree-node-disabled");
14726 if(this.node.hidden){
14727 this.addClass("x-tree-node-disabled");
14729 var ot = this.node.getOwnerTree();
14730 var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
14731 if(dd && (!this.node.isRoot || ot.rootVisible)){
14732 Roo.dd.Registry.register(this.elNode, {
14734 handles: this.getDDHandles(),
14740 getDDHandles : function(){
14741 return [this.iconNode, this.textNode];
14746 this.wrap.style.display = "none";
14752 this.wrap.style.display = "";
14756 onContextMenu : function(e){
14757 if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
14758 e.preventDefault();
14760 this.fireEvent("contextmenu", this.node, e);
14764 onClick : function(e){
14769 if(this.fireEvent("beforeclick", this.node, e) !== false){
14770 if(!this.disabled && this.node.attributes.href){
14771 this.fireEvent("click", this.node, e);
14774 e.preventDefault();
14779 if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
14780 this.node.toggle();
14783 this.fireEvent("click", this.node, e);
14789 onDblClick : function(e){
14790 e.preventDefault();
14795 this.toggleCheck();
14797 if(!this.animating && this.node.hasChildNodes()){
14798 this.node.toggle();
14800 this.fireEvent("dblclick", this.node, e);
14803 onCheckChange : function(){
14804 var checked = this.checkbox.checked;
14805 this.node.attributes.checked = checked;
14806 this.fireEvent('checkchange', this.node, checked);
14809 ecClick : function(e){
14810 if(!this.animating && this.node.hasChildNodes()){
14811 this.node.toggle();
14815 startDrop : function(){
14816 this.dropping = true;
14819 // delayed drop so the click event doesn't get fired on a drop
14820 endDrop : function(){
14821 setTimeout(function(){
14822 this.dropping = false;
14823 }.createDelegate(this), 50);
14826 expand : function(){
14827 this.updateExpandIcon();
14828 this.ctNode.style.display = "";
14831 focus : function(){
14832 if(!this.node.preventHScroll){
14833 try{this.anchor.focus();
14835 }else if(!Roo.isIE){
14837 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
14838 var l = noscroll.scrollLeft;
14839 this.anchor.focus();
14840 noscroll.scrollLeft = l;
14845 toggleCheck : function(value){
14846 var cb = this.checkbox;
14848 cb.checked = (value === undefined ? !cb.checked : value);
14854 this.anchor.blur();
14858 animExpand : function(callback){
14859 var ct = Roo.get(this.ctNode);
14861 if(!this.node.hasChildNodes()){
14862 this.updateExpandIcon();
14863 this.ctNode.style.display = "";
14864 Roo.callback(callback);
14867 this.animating = true;
14868 this.updateExpandIcon();
14871 callback : function(){
14872 this.animating = false;
14873 Roo.callback(callback);
14876 duration: this.node.ownerTree.duration || .25
14880 highlight : function(){
14881 var tree = this.node.getOwnerTree();
14882 Roo.fly(this.wrap).highlight(
14883 tree.hlColor || "C3DAF9",
14884 {endColor: tree.hlBaseColor}
14888 collapse : function(){
14889 this.updateExpandIcon();
14890 this.ctNode.style.display = "none";
14893 animCollapse : function(callback){
14894 var ct = Roo.get(this.ctNode);
14895 ct.enableDisplayMode('block');
14898 this.animating = true;
14899 this.updateExpandIcon();
14902 callback : function(){
14903 this.animating = false;
14904 Roo.callback(callback);
14907 duration: this.node.ownerTree.duration || .25
14911 getContainer : function(){
14912 return this.ctNode;
14915 getEl : function(){
14919 appendDDGhost : function(ghostNode){
14920 ghostNode.appendChild(this.elNode.cloneNode(true));
14923 getDDRepairXY : function(){
14924 return Roo.lib.Dom.getXY(this.iconNode);
14927 onRender : function(){
14931 render : function(bulkRender){
14932 var n = this.node, a = n.attributes;
14933 var targetNode = n.parentNode ?
14934 n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
14936 if(!this.rendered){
14937 this.rendered = true;
14939 this.renderElements(n, a, targetNode, bulkRender);
14942 if(this.textNode.setAttributeNS){
14943 this.textNode.setAttributeNS("ext", "qtip", a.qtip);
14945 this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
14948 this.textNode.setAttribute("ext:qtip", a.qtip);
14950 this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
14953 }else if(a.qtipCfg){
14954 a.qtipCfg.target = Roo.id(this.textNode);
14955 Roo.QuickTips.register(a.qtipCfg);
14958 if(!this.node.expanded){
14959 this.updateExpandIcon();
14962 if(bulkRender === true) {
14963 targetNode.appendChild(this.wrap);
14968 renderElements : function(n, a, targetNode, bulkRender)
14970 // add some indent caching, this helps performance when rendering a large tree
14971 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
14972 var t = n.getOwnerTree();
14973 var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
14974 if (typeof(n.attributes.html) != 'undefined') {
14975 txt = n.attributes.html;
14977 var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
14978 var cb = typeof a.checked == 'boolean';
14979 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
14980 var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
14981 '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
14982 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
14983 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
14984 cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
14985 '<a hidefocus="on" href="',href,'" tabIndex="1" ',
14986 a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "",
14987 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
14988 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
14991 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
14992 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
14993 n.nextSibling.ui.getEl(), buf.join(""));
14995 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
14998 this.elNode = this.wrap.childNodes[0];
14999 this.ctNode = this.wrap.childNodes[1];
15000 var cs = this.elNode.childNodes;
15001 this.indentNode = cs[0];
15002 this.ecNode = cs[1];
15003 this.iconNode = cs[2];
15006 this.checkbox = cs[3];
15009 this.anchor = cs[index];
15010 this.textNode = cs[index].firstChild;
15013 getAnchor : function(){
15014 return this.anchor;
15017 getTextEl : function(){
15018 return this.textNode;
15021 getIconEl : function(){
15022 return this.iconNode;
15025 isChecked : function(){
15026 return this.checkbox ? this.checkbox.checked : false;
15029 updateExpandIcon : function(){
15031 var n = this.node, c1, c2;
15032 var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
15033 var hasChild = n.hasChildNodes();
15037 c1 = "x-tree-node-collapsed";
15038 c2 = "x-tree-node-expanded";
15041 c1 = "x-tree-node-expanded";
15042 c2 = "x-tree-node-collapsed";
15045 this.removeClass("x-tree-node-leaf");
15046 this.wasLeaf = false;
15048 if(this.c1 != c1 || this.c2 != c2){
15049 Roo.fly(this.elNode).replaceClass(c1, c2);
15050 this.c1 = c1; this.c2 = c2;
15053 // this changes non-leafs into leafs if they have no children.
15054 // it's not very rational behaviour..
15056 if(!this.wasLeaf && this.node.leaf){
15057 Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
15060 this.wasLeaf = true;
15063 var ecc = "x-tree-ec-icon "+cls;
15064 if(this.ecc != ecc){
15065 this.ecNode.className = ecc;
15071 getChildIndent : function(){
15072 if(!this.childIndent){
15076 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
15078 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
15080 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
15085 this.childIndent = buf.join("");
15087 return this.childIndent;
15090 renderIndent : function(){
15093 var p = this.node.parentNode;
15095 indent = p.ui.getChildIndent();
15097 if(this.indentMarkup != indent){ // don't rerender if not required
15098 this.indentNode.innerHTML = indent;
15099 this.indentMarkup = indent;
15101 this.updateExpandIcon();
15106 Roo.tree.RootTreeNodeUI = function(){
15107 Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
15109 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
15110 render : function(){
15111 if(!this.rendered){
15112 var targetNode = this.node.ownerTree.innerCt.dom;
15113 this.node.expanded = true;
15114 targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
15115 this.wrap = this.ctNode = targetNode.firstChild;
15118 collapse : function(){
15120 expand : function(){
15124 * Ext JS Library 1.1.1
15125 * Copyright(c) 2006-2007, Ext JS, LLC.
15127 * Originally Released Under LGPL - original licence link has changed is not relivant.
15130 * <script type="text/javascript">
15133 * @class Roo.tree.TreeLoader
15134 * @extends Roo.util.Observable
15135 * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
15136 * nodes from a specified URL. The response must be a javascript Array definition
15137 * who's elements are node definition objects. eg:
15142 { 'id': 1, 'text': 'A folder Node', 'leaf': false },
15143 { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
15150 * The old style respose with just an array is still supported, but not recommended.
15153 * A server request is sent, and child nodes are loaded only when a node is expanded.
15154 * The loading node's id is passed to the server under the parameter name "node" to
15155 * enable the server to produce the correct child nodes.
15157 * To pass extra parameters, an event handler may be attached to the "beforeload"
15158 * event, and the parameters specified in the TreeLoader's baseParams property:
15160 myTreeLoader.on("beforeload", function(treeLoader, node) {
15161 this.baseParams.category = node.attributes.category;
15166 * This would pass an HTTP parameter called "category" to the server containing
15167 * the value of the Node's "category" attribute.
15169 * Creates a new Treeloader.
15170 * @param {Object} config A config object containing config properties.
15172 Roo.tree.TreeLoader = function(config){
15173 this.baseParams = {};
15174 this.requestMethod = "POST";
15175 Roo.apply(this, config);
15180 * @event beforeload
15181 * Fires before a network request is made to retrieve the Json text which specifies a node's children.
15182 * @param {Object} This TreeLoader object.
15183 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
15184 * @param {Object} callback The callback function specified in the {@link #load} call.
15189 * Fires when the node has been successfuly loaded.
15190 * @param {Object} This TreeLoader object.
15191 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
15192 * @param {Object} response The response object containing the data from the server.
15196 * @event loadexception
15197 * Fires if the network request failed.
15198 * @param {Object} This TreeLoader object.
15199 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
15200 * @param {Object} response The response object containing the data from the server.
15202 loadexception : true,
15205 * Fires before a node is created, enabling you to return custom Node types
15206 * @param {Object} This TreeLoader object.
15207 * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
15212 Roo.tree.TreeLoader.superclass.constructor.call(this);
15215 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
15217 * @cfg {String} dataUrl The URL from which to request a Json string which
15218 * specifies an array of node definition object representing the child nodes
15222 * @cfg {String} requestMethod either GET or POST
15223 * defaults to POST (due to BC)
15227 * @cfg {Object} baseParams (optional) An object containing properties which
15228 * specify HTTP parameters to be passed to each request for child nodes.
15231 * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
15232 * created by this loader. If the attributes sent by the server have an attribute in this object,
15233 * they take priority.
15236 * @cfg {Object} uiProviders (optional) An object containing properties which
15238 * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
15239 * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
15240 * <i>uiProvider</i> attribute of a returned child node is a string rather
15241 * than a reference to a TreeNodeUI implementation, this that string value
15242 * is used as a property name in the uiProviders object. You can define the provider named
15243 * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
15248 * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
15249 * child nodes before loading.
15251 clearOnLoad : true,
15254 * @cfg {String} root (optional) Default to false. Use this to read data from an object
15255 * property on loading, rather than expecting an array. (eg. more compatible to a standard
15256 * Grid query { data : [ .....] }
15261 * @cfg {String} queryParam (optional)
15262 * Name of the query as it will be passed on the querystring (defaults to 'node')
15263 * eg. the request will be ?node=[id]
15270 * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
15271 * This is called automatically when a node is expanded, but may be used to reload
15272 * a node (or append new children if the {@link #clearOnLoad} option is false.)
15273 * @param {Roo.tree.TreeNode} node
15274 * @param {Function} callback
15276 load : function(node, callback){
15277 if(this.clearOnLoad){
15278 while(node.firstChild){
15279 node.removeChild(node.firstChild);
15282 if(node.attributes.children){ // preloaded json children
15283 var cs = node.attributes.children;
15284 for(var i = 0, len = cs.length; i < len; i++){
15285 node.appendChild(this.createNode(cs[i]));
15287 if(typeof callback == "function"){
15290 }else if(this.dataUrl){
15291 this.requestData(node, callback);
15295 getParams: function(node){
15296 var buf = [], bp = this.baseParams;
15297 for(var key in bp){
15298 if(typeof bp[key] != "function"){
15299 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
15302 var n = this.queryParam === false ? 'node' : this.queryParam;
15303 buf.push(n + "=", encodeURIComponent(node.id));
15304 return buf.join("");
15307 requestData : function(node, callback){
15308 if(this.fireEvent("beforeload", this, node, callback) !== false){
15309 this.transId = Roo.Ajax.request({
15310 method:this.requestMethod,
15311 url: this.dataUrl||this.url,
15312 success: this.handleResponse,
15313 failure: this.handleFailure,
15315 argument: {callback: callback, node: node},
15316 params: this.getParams(node)
15319 // if the load is cancelled, make sure we notify
15320 // the node that we are done
15321 if(typeof callback == "function"){
15327 isLoading : function(){
15328 return this.transId ? true : false;
15331 abort : function(){
15332 if(this.isLoading()){
15333 Roo.Ajax.abort(this.transId);
15338 createNode : function(attr)
15340 // apply baseAttrs, nice idea Corey!
15341 if(this.baseAttrs){
15342 Roo.applyIf(attr, this.baseAttrs);
15344 if(this.applyLoader !== false){
15345 attr.loader = this;
15347 // uiProvider = depreciated..
15349 if(typeof(attr.uiProvider) == 'string'){
15350 attr.uiProvider = this.uiProviders[attr.uiProvider] ||
15351 /** eval:var:attr */ eval(attr.uiProvider);
15353 if(typeof(this.uiProviders['default']) != 'undefined') {
15354 attr.uiProvider = this.uiProviders['default'];
15357 this.fireEvent('create', this, attr);
15359 attr.leaf = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
15361 new Roo.tree.TreeNode(attr) :
15362 new Roo.tree.AsyncTreeNode(attr));
15365 processResponse : function(response, node, callback)
15367 var json = response.responseText;
15370 var o = Roo.decode(json);
15372 if (this.root === false && typeof(o.success) != undefined) {
15373 this.root = 'data'; // the default behaviour for list like data..
15376 if (this.root !== false && !o.success) {
15377 // it's a failure condition.
15378 var a = response.argument;
15379 this.fireEvent("loadexception", this, a.node, response);
15380 Roo.log("Load failed - should have a handler really");
15386 if (this.root !== false) {
15390 for(var i = 0, len = o.length; i < len; i++){
15391 var n = this.createNode(o[i]);
15393 node.appendChild(n);
15396 if(typeof callback == "function"){
15397 callback(this, node);
15400 this.handleFailure(response);
15404 handleResponse : function(response){
15405 this.transId = false;
15406 var a = response.argument;
15407 this.processResponse(response, a.node, a.callback);
15408 this.fireEvent("load", this, a.node, response);
15411 handleFailure : function(response)
15413 // should handle failure better..
15414 this.transId = false;
15415 var a = response.argument;
15416 this.fireEvent("loadexception", this, a.node, response);
15417 if(typeof a.callback == "function"){
15418 a.callback(this, a.node);
15423 * Ext JS Library 1.1.1
15424 * Copyright(c) 2006-2007, Ext JS, LLC.
15426 * Originally Released Under LGPL - original licence link has changed is not relivant.
15429 * <script type="text/javascript">
15433 * @class Roo.tree.TreeFilter
15434 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
15435 * @param {TreePanel} tree
15436 * @param {Object} config (optional)
15438 Roo.tree.TreeFilter = function(tree, config){
15440 this.filtered = {};
15441 Roo.apply(this, config);
15444 Roo.tree.TreeFilter.prototype = {
15451 * Filter the data by a specific attribute.
15452 * @param {String/RegExp} value Either string that the attribute value
15453 * should start with or a RegExp to test against the attribute
15454 * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
15455 * @param {TreeNode} startNode (optional) The node to start the filter at.
15457 filter : function(value, attr, startNode){
15458 attr = attr || "text";
15460 if(typeof value == "string"){
15461 var vlen = value.length;
15462 // auto clear empty filter
15463 if(vlen == 0 && this.clearBlank){
15467 value = value.toLowerCase();
15469 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
15471 }else if(value.exec){ // regex?
15473 return value.test(n.attributes[attr]);
15476 throw 'Illegal filter type, must be string or regex';
15478 this.filterBy(f, null, startNode);
15482 * Filter by a function. The passed function will be called with each
15483 * node in the tree (or from the startNode). If the function returns true, the node is kept
15484 * otherwise it is filtered. If a node is filtered, its children are also filtered.
15485 * @param {Function} fn The filter function
15486 * @param {Object} scope (optional) The scope of the function (defaults to the current node)
15488 filterBy : function(fn, scope, startNode){
15489 startNode = startNode || this.tree.root;
15490 if(this.autoClear){
15493 var af = this.filtered, rv = this.reverse;
15494 var f = function(n){
15495 if(n == startNode){
15501 var m = fn.call(scope || n, n);
15509 startNode.cascade(f);
15512 if(typeof id != "function"){
15514 if(n && n.parentNode){
15515 n.parentNode.removeChild(n);
15523 * Clears the current filter. Note: with the "remove" option
15524 * set a filter cannot be cleared.
15526 clear : function(){
15528 var af = this.filtered;
15530 if(typeof id != "function"){
15537 this.filtered = {};
15542 * Ext JS Library 1.1.1
15543 * Copyright(c) 2006-2007, Ext JS, LLC.
15545 * Originally Released Under LGPL - original licence link has changed is not relivant.
15548 * <script type="text/javascript">
15553 * @class Roo.tree.TreeSorter
15554 * Provides sorting of nodes in a TreePanel
15556 * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
15557 * @cfg {String} property The named attribute on the node to sort by (defaults to text)
15558 * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
15559 * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
15560 * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
15561 * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
15563 * @param {TreePanel} tree
15564 * @param {Object} config
15566 Roo.tree.TreeSorter = function(tree, config){
15567 Roo.apply(this, config);
15568 tree.on("beforechildrenrendered", this.doSort, this);
15569 tree.on("append", this.updateSort, this);
15570 tree.on("insert", this.updateSort, this);
15572 var dsc = this.dir && this.dir.toLowerCase() == "desc";
15573 var p = this.property || "text";
15574 var sortType = this.sortType;
15575 var fs = this.folderSort;
15576 var cs = this.caseSensitive === true;
15577 var leafAttr = this.leafAttr || 'leaf';
15579 this.sortFn = function(n1, n2){
15581 if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
15584 if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
15588 var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
15589 var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
15591 return dsc ? +1 : -1;
15593 return dsc ? -1 : +1;
15600 Roo.tree.TreeSorter.prototype = {
15601 doSort : function(node){
15602 node.sort(this.sortFn);
15605 compareNodes : function(n1, n2){
15606 return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
15609 updateSort : function(tree, node){
15610 if(node.childrenRendered){
15611 this.doSort.defer(1, this, [node]);
15616 * Ext JS Library 1.1.1
15617 * Copyright(c) 2006-2007, Ext JS, LLC.
15619 * Originally Released Under LGPL - original licence link has changed is not relivant.
15622 * <script type="text/javascript">
15625 if(Roo.dd.DropZone){
15627 Roo.tree.TreeDropZone = function(tree, config){
15628 this.allowParentInsert = false;
15629 this.allowContainerDrop = false;
15630 this.appendOnly = false;
15631 Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
15633 this.lastInsertClass = "x-tree-no-status";
15634 this.dragOverData = {};
15637 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
15638 ddGroup : "TreeDD",
15641 expandDelay : 1000,
15643 expandNode : function(node){
15644 if(node.hasChildNodes() && !node.isExpanded()){
15645 node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
15649 queueExpand : function(node){
15650 this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
15653 cancelExpand : function(){
15654 if(this.expandProcId){
15655 clearTimeout(this.expandProcId);
15656 this.expandProcId = false;
15660 isValidDropPoint : function(n, pt, dd, e, data){
15661 if(!n || !data){ return false; }
15662 var targetNode = n.node;
15663 var dropNode = data.node;
15664 // default drop rules
15665 if(!(targetNode && targetNode.isTarget && pt)){
15668 if(pt == "append" && targetNode.allowChildren === false){
15671 if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
15674 if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
15677 // reuse the object
15678 var overEvent = this.dragOverData;
15679 overEvent.tree = this.tree;
15680 overEvent.target = targetNode;
15681 overEvent.data = data;
15682 overEvent.point = pt;
15683 overEvent.source = dd;
15684 overEvent.rawEvent = e;
15685 overEvent.dropNode = dropNode;
15686 overEvent.cancel = false;
15687 var result = this.tree.fireEvent("nodedragover", overEvent);
15688 return overEvent.cancel === false && result !== false;
15691 getDropPoint : function(e, n, dd)
15695 return tn.allowChildren !== false ? "append" : false; // always append for root
15697 var dragEl = n.ddel;
15698 var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
15699 var y = Roo.lib.Event.getPageY(e);
15700 //var noAppend = tn.allowChildren === false || tn.isLeaf();
15702 // we may drop nodes anywhere, as long as allowChildren has not been set to false..
15703 var noAppend = tn.allowChildren === false;
15704 if(this.appendOnly || tn.parentNode.allowChildren === false){
15705 return noAppend ? false : "append";
15707 var noBelow = false;
15708 if(!this.allowParentInsert){
15709 noBelow = tn.hasChildNodes() && tn.isExpanded();
15711 var q = (b - t) / (noAppend ? 2 : 3);
15712 if(y >= t && y < (t + q)){
15714 }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
15721 onNodeEnter : function(n, dd, e, data)
15723 this.cancelExpand();
15726 onNodeOver : function(n, dd, e, data)
15729 var pt = this.getDropPoint(e, n, dd);
15732 // auto node expand check
15733 if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
15734 this.queueExpand(node);
15735 }else if(pt != "append"){
15736 this.cancelExpand();
15739 // set the insert point style on the target node
15740 var returnCls = this.dropNotAllowed;
15741 if(this.isValidDropPoint(n, pt, dd, e, data)){
15746 returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
15747 cls = "x-tree-drag-insert-above";
15748 }else if(pt == "below"){
15749 returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
15750 cls = "x-tree-drag-insert-below";
15752 returnCls = "x-tree-drop-ok-append";
15753 cls = "x-tree-drag-append";
15755 if(this.lastInsertClass != cls){
15756 Roo.fly(el).replaceClass(this.lastInsertClass, cls);
15757 this.lastInsertClass = cls;
15764 onNodeOut : function(n, dd, e, data){
15766 this.cancelExpand();
15767 this.removeDropIndicators(n);
15770 onNodeDrop : function(n, dd, e, data){
15771 var point = this.getDropPoint(e, n, dd);
15772 var targetNode = n.node;
15773 targetNode.ui.startDrop();
15774 if(!this.isValidDropPoint(n, point, dd, e, data)){
15775 targetNode.ui.endDrop();
15778 // first try to find the drop node
15779 var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
15782 target: targetNode,
15787 dropNode: dropNode,
15790 var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
15791 if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
15792 targetNode.ui.endDrop();
15795 // allow target changing
15796 targetNode = dropEvent.target;
15797 if(point == "append" && !targetNode.isExpanded()){
15798 targetNode.expand(false, null, function(){
15799 this.completeDrop(dropEvent);
15800 }.createDelegate(this));
15802 this.completeDrop(dropEvent);
15807 completeDrop : function(de){
15808 var ns = de.dropNode, p = de.point, t = de.target;
15809 if(!(ns instanceof Array)){
15813 for(var i = 0, len = ns.length; i < len; i++){
15816 t.parentNode.insertBefore(n, t);
15817 }else if(p == "below"){
15818 t.parentNode.insertBefore(n, t.nextSibling);
15824 if(this.tree.hlDrop){
15828 this.tree.fireEvent("nodedrop", de);
15831 afterNodeMoved : function(dd, data, e, targetNode, dropNode){
15832 if(this.tree.hlDrop){
15833 dropNode.ui.focus();
15834 dropNode.ui.highlight();
15836 this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
15839 getTree : function(){
15843 removeDropIndicators : function(n){
15846 Roo.fly(el).removeClass([
15847 "x-tree-drag-insert-above",
15848 "x-tree-drag-insert-below",
15849 "x-tree-drag-append"]);
15850 this.lastInsertClass = "_noclass";
15854 beforeDragDrop : function(target, e, id){
15855 this.cancelExpand();
15859 afterRepair : function(data){
15860 if(data && Roo.enableFx){
15861 data.node.ui.highlight();
15871 * Ext JS Library 1.1.1
15872 * Copyright(c) 2006-2007, Ext JS, LLC.
15874 * Originally Released Under LGPL - original licence link has changed is not relivant.
15877 * <script type="text/javascript">
15881 if(Roo.dd.DragZone){
15882 Roo.tree.TreeDragZone = function(tree, config){
15883 Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
15887 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
15888 ddGroup : "TreeDD",
15890 onBeforeDrag : function(data, e){
15892 return n && n.draggable && !n.disabled;
15896 onInitDrag : function(e){
15897 var data = this.dragData;
15898 this.tree.getSelectionModel().select(data.node);
15899 this.proxy.update("");
15900 data.node.ui.appendDDGhost(this.proxy.ghost.dom);
15901 this.tree.fireEvent("startdrag", this.tree, data.node, e);
15904 getRepairXY : function(e, data){
15905 return data.node.ui.getDDRepairXY();
15908 onEndDrag : function(data, e){
15909 this.tree.fireEvent("enddrag", this.tree, data.node, e);
15914 onValidDrop : function(dd, e, id){
15915 this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
15919 beforeInvalidDrop : function(e, id){
15920 // this scrolls the original position back into view
15921 var sm = this.tree.getSelectionModel();
15922 sm.clearSelections();
15923 sm.select(this.dragData.node);
15928 * Ext JS Library 1.1.1
15929 * Copyright(c) 2006-2007, Ext JS, LLC.
15931 * Originally Released Under LGPL - original licence link has changed is not relivant.
15934 * <script type="text/javascript">
15937 * @class Roo.tree.TreeEditor
15938 * @extends Roo.Editor
15939 * Provides editor functionality for inline tree node editing. Any valid {@link Roo.form.Field} can be used
15940 * as the editor field.
15942 * @param {Object} config (used to be the tree panel.)
15943 * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
15945 * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
15946 * @cfg {Roo.form.TextField} field [required] The field configuration
15950 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
15953 if (oldconfig) { // old style..
15954 field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
15957 tree = config.tree;
15958 config.field = config.field || {};
15959 config.field.xtype = 'TextField';
15960 field = Roo.factory(config.field, Roo.form);
15962 config = config || {};
15967 * @event beforenodeedit
15968 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
15969 * false from the handler of this event.
15970 * @param {Editor} this
15971 * @param {Roo.tree.Node} node
15973 "beforenodeedit" : true
15977 Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
15981 tree.on('beforeclick', this.beforeNodeClick, this);
15982 tree.getTreeEl().on('mousedown', this.hide, this);
15983 this.on('complete', this.updateNode, this);
15984 this.on('beforestartedit', this.fitToTree, this);
15985 this.on('startedit', this.bindScroll, this, {delay:10});
15986 this.on('specialkey', this.onSpecialKey, this);
15989 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
15991 * @cfg {String} alignment
15992 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
15998 * @cfg {Boolean} hideEl
15999 * True to hide the bound element while the editor is displayed (defaults to false)
16003 * @cfg {String} cls
16004 * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
16006 cls: "x-small-editor x-tree-editor",
16008 * @cfg {Boolean} shim
16009 * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
16015 * @cfg {Number} maxWidth
16016 * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed
16017 * the containing tree element's size, it will be automatically limited for you to the container width, taking
16018 * scroll and client offsets into account prior to each edit.
16025 fitToTree : function(ed, el){
16026 var td = this.tree.getTreeEl().dom, nd = el.dom;
16027 if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible
16028 td.scrollLeft = nd.offsetLeft;
16032 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
16033 this.setSize(w, '');
16035 return this.fireEvent('beforenodeedit', this, this.editNode);
16040 triggerEdit : function(node){
16041 this.completeEdit();
16042 this.editNode = node;
16043 this.startEdit(node.ui.textNode, node.text);
16047 bindScroll : function(){
16048 this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
16052 beforeNodeClick : function(node, e){
16053 var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
16054 this.lastClick = new Date();
16055 if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
16057 this.triggerEdit(node);
16064 updateNode : function(ed, value){
16065 this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
16066 this.editNode.setText(value);
16070 onHide : function(){
16071 Roo.tree.TreeEditor.superclass.onHide.call(this);
16073 this.editNode.ui.focus();
16078 onSpecialKey : function(field, e){
16079 var k = e.getKey();
16083 }else if(k == e.ENTER && !e.hasModifier()){
16085 this.completeEdit();
16088 });//<Script type="text/javascript">
16091 * Ext JS Library 1.1.1
16092 * Copyright(c) 2006-2007, Ext JS, LLC.
16094 * Originally Released Under LGPL - original licence link has changed is not relivant.
16097 * <script type="text/javascript">
16101 * Not documented??? - probably should be...
16104 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
16105 //focus: Roo.emptyFn, // prevent odd scrolling behavior
16107 renderElements : function(n, a, targetNode, bulkRender){
16108 //consel.log("renderElements?");
16109 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
16111 var t = n.getOwnerTree();
16112 var tid = Pman.Tab.Document_TypesTree.tree.el.id;
16114 var cols = t.columns;
16115 var bw = t.borderWidth;
16117 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
16118 var cb = typeof a.checked == "boolean";
16119 var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
16120 var colcls = 'x-t-' + tid + '-c0';
16122 '<li class="x-tree-node">',
16125 '<div class="x-tree-node-el ', a.cls,'">',
16127 '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
16130 '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
16131 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon " />',
16132 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
16133 (a.icon ? ' x-tree-node-inline-icon' : ''),
16134 (a.iconCls ? ' '+a.iconCls : ''),
16135 '" unselectable="on" />',
16136 (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' +
16137 (a.checked ? 'checked="checked" />' : ' />')) : ''),
16139 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
16140 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
16141 '<span unselectable="on" qtip="' + tx + '">',
16145 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
16146 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
16148 for(var i = 1, len = cols.length; i < len; i++){
16150 colcls = 'x-t-' + tid + '-c' +i;
16151 tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
16152 buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
16153 '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
16159 '<div class="x-clear"></div></div>',
16160 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
16163 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
16164 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
16165 n.nextSibling.ui.getEl(), buf.join(""));
16167 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
16169 var el = this.wrap.firstChild;
16171 this.elNode = el.firstChild;
16172 this.ranchor = el.childNodes[1];
16173 this.ctNode = this.wrap.childNodes[1];
16174 var cs = el.firstChild.childNodes;
16175 this.indentNode = cs[0];
16176 this.ecNode = cs[1];
16177 this.iconNode = cs[2];
16180 this.checkbox = cs[3];
16183 this.anchor = cs[index];
16185 this.textNode = cs[index].firstChild;
16187 //el.on("click", this.onClick, this);
16188 //el.on("dblclick", this.onDblClick, this);
16191 // console.log(this);
16193 initEvents : function(){
16194 Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
16197 var a = this.ranchor;
16199 var el = Roo.get(a);
16201 if(Roo.isOpera){ // opera render bug ignores the CSS
16202 el.setStyle("text-decoration", "none");
16205 el.on("click", this.onClick, this);
16206 el.on("dblclick", this.onDblClick, this);
16207 el.on("contextmenu", this.onContextMenu, this);
16211 /*onSelectedChange : function(state){
16214 this.addClass("x-tree-selected");
16217 this.removeClass("x-tree-selected");
16220 addClass : function(cls){
16222 Roo.fly(this.elRow).addClass(cls);
16228 removeClass : function(cls){
16230 Roo.fly(this.elRow).removeClass(cls);
16236 });//<Script type="text/javascript">
16240 * Ext JS Library 1.1.1
16241 * Copyright(c) 2006-2007, Ext JS, LLC.
16243 * Originally Released Under LGPL - original licence link has changed is not relivant.
16246 * <script type="text/javascript">
16251 * @class Roo.tree.ColumnTree
16252 * @extends Roo.tree.TreePanel
16253 * @cfg {Object} columns Including width, header, renderer, cls, dataIndex
16254 * @cfg {int} borderWidth compined right/left border allowance
16256 * @param {String/HTMLElement/Element} el The container element
16257 * @param {Object} config
16259 Roo.tree.ColumnTree = function(el, config)
16261 Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
16265 * Fire this event on a container when it resizes
16266 * @param {int} w Width
16267 * @param {int} h Height
16271 this.on('resize', this.onResize, this);
16274 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
16278 borderWidth: Roo.isBorderBox ? 0 : 2,
16281 render : function(){
16282 // add the header.....
16284 Roo.tree.ColumnTree.superclass.render.apply(this);
16286 this.el.addClass('x-column-tree');
16288 this.headers = this.el.createChild(
16289 {cls:'x-tree-headers'},this.innerCt.dom);
16291 var cols = this.columns, c;
16292 var totalWidth = 0;
16294 var len = cols.length;
16295 for(var i = 0; i < len; i++){
16297 totalWidth += c.width;
16298 this.headEls.push(this.headers.createChild({
16299 cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
16301 cls:'x-tree-hd-text',
16304 style:'width:'+(c.width-this.borderWidth)+'px;'
16307 this.headers.createChild({cls:'x-clear'});
16308 // prevent floats from wrapping when clipped
16309 this.headers.setWidth(totalWidth);
16310 //this.innerCt.setWidth(totalWidth);
16311 this.innerCt.setStyle({ overflow: 'auto' });
16312 this.onResize(this.width, this.height);
16316 onResize : function(w,h)
16321 this.innerCt.setWidth(this.width);
16322 this.innerCt.setHeight(this.height-20);
16325 var cols = this.columns, c;
16326 var totalWidth = 0;
16328 var len = cols.length;
16329 for(var i = 0; i < len; i++){
16331 if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
16332 // it's the expander..
16333 expEl = this.headEls[i];
16336 totalWidth += c.width;
16340 expEl.setWidth( ((w - totalWidth)-this.borderWidth - 20));
16342 this.headers.setWidth(w-20);
16351 * Ext JS Library 1.1.1
16352 * Copyright(c) 2006-2007, Ext JS, LLC.
16354 * Originally Released Under LGPL - original licence link has changed is not relivant.
16357 * <script type="text/javascript">
16361 * @class Roo.menu.Menu
16362 * @extends Roo.util.Observable
16363 * @children Roo.menu.Item Roo.menu.Separator Roo.menu.TextItem
16364 * A menu object. This is the container to which you add all other menu items. Menu can also serve a as a base class
16365 * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
16367 * Creates a new Menu
16368 * @param {Object} config Configuration options
16370 Roo.menu.Menu = function(config){
16372 Roo.menu.Menu.superclass.constructor.call(this, config);
16374 this.id = this.id || Roo.id();
16377 * @event beforeshow
16378 * Fires before this menu is displayed
16379 * @param {Roo.menu.Menu} this
16383 * @event beforehide
16384 * Fires before this menu is hidden
16385 * @param {Roo.menu.Menu} this
16390 * Fires after this menu is displayed
16391 * @param {Roo.menu.Menu} this
16396 * Fires after this menu is hidden
16397 * @param {Roo.menu.Menu} this
16402 * Fires when this menu is clicked (or when the enter key is pressed while it is active)
16403 * @param {Roo.menu.Menu} this
16404 * @param {Roo.menu.Item} menuItem The menu item that was clicked
16405 * @param {Roo.EventObject} e
16410 * Fires when the mouse is hovering over this menu
16411 * @param {Roo.menu.Menu} this
16412 * @param {Roo.EventObject} e
16413 * @param {Roo.menu.Item} menuItem The menu item that was clicked
16418 * Fires when the mouse exits this menu
16419 * @param {Roo.menu.Menu} this
16420 * @param {Roo.EventObject} e
16421 * @param {Roo.menu.Item} menuItem The menu item that was clicked
16426 * Fires when a menu item contained in this menu is clicked
16427 * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
16428 * @param {Roo.EventObject} e
16432 if (this.registerMenu) {
16433 Roo.menu.MenuMgr.register(this);
16436 var mis = this.items;
16437 this.items = new Roo.util.MixedCollection();
16439 this.add.apply(this, mis);
16443 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
16445 * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
16449 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
16450 * for bottom-right shadow (defaults to "sides")
16454 * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
16455 * this menu (defaults to "tl-tr?")
16457 subMenuAlign : "tl-tr?",
16459 * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
16460 * relative to its element of origin (defaults to "tl-bl?")
16462 defaultAlign : "tl-bl?",
16464 * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
16466 allowOtherMenus : false,
16468 * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
16470 registerMenu : true,
16475 render : function(){
16479 var el = this.el = new Roo.Layer({
16481 shadow:this.shadow,
16483 parentEl: this.parentEl || document.body,
16487 this.keyNav = new Roo.menu.MenuNav(this);
16490 el.addClass("x-menu-plain");
16493 el.addClass(this.cls);
16495 // generic focus element
16496 this.focusEl = el.createChild({
16497 tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
16499 var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
16500 //disabling touch- as it's causing issues ..
16501 //ul.on(Roo.isTouch ? 'touchstart' : 'click' , this.onClick, this);
16502 ul.on('click' , this.onClick, this);
16505 ul.on("mouseover", this.onMouseOver, this);
16506 ul.on("mouseout", this.onMouseOut, this);
16507 this.items.each(function(item){
16512 var li = document.createElement("li");
16513 li.className = "x-menu-list-item";
16514 ul.dom.appendChild(li);
16515 item.render(li, this);
16522 autoWidth : function(){
16523 var el = this.el, ul = this.ul;
16527 var w = this.width;
16530 }else if(Roo.isIE){
16531 el.setWidth(this.minWidth);
16532 var t = el.dom.offsetWidth; // force recalc
16533 el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
16538 delayAutoWidth : function(){
16541 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
16543 this.awTask.delay(20);
16548 findTargetItem : function(e){
16549 var t = e.getTarget(".x-menu-list-item", this.ul, true);
16550 if(t && t.menuItemId){
16551 return this.items.get(t.menuItemId);
16556 onClick : function(e){
16557 Roo.log("menu.onClick");
16558 var t = this.findTargetItem(e);
16563 if (Roo.isTouch && e.type == 'touchstart' && t.menu && !t.disabled) {
16564 if(t == this.activeItem && t.shouldDeactivate(e)){
16565 this.activeItem.deactivate();
16566 delete this.activeItem;
16570 this.setActiveItem(t, true);
16578 this.fireEvent("click", this, t, e);
16582 setActiveItem : function(item, autoExpand){
16583 if(item != this.activeItem){
16584 if(this.activeItem){
16585 this.activeItem.deactivate();
16587 this.activeItem = item;
16588 item.activate(autoExpand);
16589 }else if(autoExpand){
16595 tryActivate : function(start, step){
16596 var items = this.items;
16597 for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
16598 var item = items.get(i);
16599 if(!item.disabled && item.canActivate){
16600 this.setActiveItem(item, false);
16608 onMouseOver : function(e){
16610 if(t = this.findTargetItem(e)){
16611 if(t.canActivate && !t.disabled){
16612 this.setActiveItem(t, true);
16615 this.fireEvent("mouseover", this, e, t);
16619 onMouseOut : function(e){
16621 if(t = this.findTargetItem(e)){
16622 if(t == this.activeItem && t.shouldDeactivate(e)){
16623 this.activeItem.deactivate();
16624 delete this.activeItem;
16627 this.fireEvent("mouseout", this, e, t);
16631 * Read-only. Returns true if the menu is currently displayed, else false.
16634 isVisible : function(){
16635 return this.el && !this.hidden;
16639 * Displays this menu relative to another element
16640 * @param {String/HTMLElement/Roo.Element} element The element to align to
16641 * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
16642 * the element (defaults to this.defaultAlign)
16643 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
16645 show : function(el, pos, parentMenu){
16646 this.parentMenu = parentMenu;
16650 this.fireEvent("beforeshow", this);
16651 this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
16655 * Displays this menu at a specific xy position
16656 * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
16657 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
16659 showAt : function(xy, parentMenu, /* private: */_e){
16660 this.parentMenu = parentMenu;
16665 this.fireEvent("beforeshow", this);
16666 xy = this.el.adjustForConstraints(xy);
16670 this.hidden = false;
16672 this.fireEvent("show", this);
16675 focus : function(){
16677 this.doFocus.defer(50, this);
16681 doFocus : function(){
16683 this.focusEl.focus();
16688 * Hides this menu and optionally all parent menus
16689 * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
16691 hide : function(deep){
16692 if(this.el && this.isVisible()){
16693 this.fireEvent("beforehide", this);
16694 if(this.activeItem){
16695 this.activeItem.deactivate();
16696 this.activeItem = null;
16699 this.hidden = true;
16700 this.fireEvent("hide", this);
16702 if(deep === true && this.parentMenu){
16703 this.parentMenu.hide(true);
16708 * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
16709 * Any of the following are valid:
16711 * <li>Any menu item object based on {@link Roo.menu.Item}</li>
16712 * <li>An HTMLElement object which will be converted to a menu item</li>
16713 * <li>A menu item config object that will be created as a new menu item</li>
16714 * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
16715 * it will be converted into a {@link Roo.menu.TextItem} and added</li>
16720 var menu = new Roo.menu.Menu();
16722 // Create a menu item to add by reference
16723 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
16725 // Add a bunch of items at once using different methods.
16726 // Only the last item added will be returned.
16727 var item = menu.add(
16728 menuItem, // add existing item by ref
16729 'Dynamic Item', // new TextItem
16730 '-', // new separator
16731 { text: 'Config Item' } // new item by config
16734 * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
16735 * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
16738 var a = arguments, l = a.length, item;
16739 for(var i = 0; i < l; i++){
16741 if ((typeof(el) == "object") && el.xtype && el.xns) {
16742 el = Roo.factory(el, Roo.menu);
16745 if(el.render){ // some kind of Item
16746 item = this.addItem(el);
16747 }else if(typeof el == "string"){ // string
16748 if(el == "separator" || el == "-"){
16749 item = this.addSeparator();
16751 item = this.addText(el);
16753 }else if(el.tagName || el.el){ // element
16754 item = this.addElement(el);
16755 }else if(typeof el == "object"){ // must be menu item config?
16756 item = this.addMenuItem(el);
16763 * Returns this menu's underlying {@link Roo.Element} object
16764 * @return {Roo.Element} The element
16766 getEl : function(){
16774 * Adds a separator bar to the menu
16775 * @return {Roo.menu.Item} The menu item that was added
16777 addSeparator : function(){
16778 return this.addItem(new Roo.menu.Separator());
16782 * Adds an {@link Roo.Element} object to the menu
16783 * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
16784 * @return {Roo.menu.Item} The menu item that was added
16786 addElement : function(el){
16787 return this.addItem(new Roo.menu.BaseItem(el));
16791 * Adds an existing object based on {@link Roo.menu.Item} to the menu
16792 * @param {Roo.menu.Item} item The menu item to add
16793 * @return {Roo.menu.Item} The menu item that was added
16795 addItem : function(item){
16796 this.items.add(item);
16798 var li = document.createElement("li");
16799 li.className = "x-menu-list-item";
16800 this.ul.dom.appendChild(li);
16801 item.render(li, this);
16802 this.delayAutoWidth();
16808 * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
16809 * @param {Object} config A MenuItem config object
16810 * @return {Roo.menu.Item} The menu item that was added
16812 addMenuItem : function(config){
16813 if(!(config instanceof Roo.menu.Item)){
16814 if(typeof config.checked == "boolean"){ // must be check menu item config?
16815 config = new Roo.menu.CheckItem(config);
16817 config = new Roo.menu.Item(config);
16820 return this.addItem(config);
16824 * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
16825 * @param {String} text The text to display in the menu item
16826 * @return {Roo.menu.Item} The menu item that was added
16828 addText : function(text){
16829 return this.addItem(new Roo.menu.TextItem({ text : text }));
16833 * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
16834 * @param {Number} index The index in the menu's list of current items where the new item should be inserted
16835 * @param {Roo.menu.Item} item The menu item to add
16836 * @return {Roo.menu.Item} The menu item that was added
16838 insert : function(index, item){
16839 this.items.insert(index, item);
16841 var li = document.createElement("li");
16842 li.className = "x-menu-list-item";
16843 this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
16844 item.render(li, this);
16845 this.delayAutoWidth();
16851 * Removes an {@link Roo.menu.Item} from the menu and destroys the object
16852 * @param {Roo.menu.Item} item The menu item to remove
16854 remove : function(item){
16855 this.items.removeKey(item.id);
16860 * Removes and destroys all items in the menu
16862 removeAll : function(){
16864 while(f = this.items.first()){
16870 // MenuNav is a private utility class used internally by the Menu
16871 Roo.menu.MenuNav = function(menu){
16872 Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
16873 this.scope = this.menu = menu;
16876 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
16877 doRelay : function(e, h){
16878 var k = e.getKey();
16879 if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
16880 this.menu.tryActivate(0, 1);
16883 return h.call(this.scope || this, e, this.menu);
16886 up : function(e, m){
16887 if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
16888 m.tryActivate(m.items.length-1, -1);
16892 down : function(e, m){
16893 if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
16894 m.tryActivate(0, 1);
16898 right : function(e, m){
16900 m.activeItem.expandMenu(true);
16904 left : function(e, m){
16906 if(m.parentMenu && m.parentMenu.activeItem){
16907 m.parentMenu.activeItem.activate();
16911 enter : function(e, m){
16913 e.stopPropagation();
16914 m.activeItem.onClick(e);
16915 m.fireEvent("click", this, m.activeItem);
16921 * Ext JS Library 1.1.1
16922 * Copyright(c) 2006-2007, Ext JS, LLC.
16924 * Originally Released Under LGPL - original licence link has changed is not relivant.
16927 * <script type="text/javascript">
16931 * @class Roo.menu.MenuMgr
16932 * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
16935 Roo.menu.MenuMgr = function(){
16936 var menus, active, groups = {}, attached = false, lastShow = new Date();
16938 // private - called when first menu is created
16941 active = new Roo.util.MixedCollection();
16942 Roo.get(document).addKeyListener(27, function(){
16943 if(active.length > 0){
16950 function hideAll(){
16951 if(active && active.length > 0){
16952 var c = active.clone();
16953 c.each(function(m){
16960 function onHide(m){
16962 if(active.length < 1){
16963 Roo.get(document).un("mousedown", onMouseDown);
16969 function onShow(m){
16970 var last = active.last();
16971 lastShow = new Date();
16974 Roo.get(document).on("mousedown", onMouseDown);
16978 m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
16979 m.parentMenu.activeChild = m;
16980 }else if(last && last.isVisible()){
16981 m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
16986 function onBeforeHide(m){
16988 m.activeChild.hide();
16990 if(m.autoHideTimer){
16991 clearTimeout(m.autoHideTimer);
16992 delete m.autoHideTimer;
16997 function onBeforeShow(m){
16998 var pm = m.parentMenu;
16999 if(!pm && !m.allowOtherMenus){
17001 }else if(pm && pm.activeChild && active != m){
17002 pm.activeChild.hide();
17007 function onMouseDown(e){
17008 if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
17014 function onBeforeCheck(mi, state){
17016 var g = groups[mi.group];
17017 for(var i = 0, l = g.length; i < l; i++){
17019 g[i].setChecked(false);
17028 * Hides all menus that are currently visible
17030 hideAll : function(){
17035 register : function(menu){
17039 menus[menu.id] = menu;
17040 menu.on("beforehide", onBeforeHide);
17041 menu.on("hide", onHide);
17042 menu.on("beforeshow", onBeforeShow);
17043 menu.on("show", onShow);
17044 var g = menu.group;
17045 if(g && menu.events["checkchange"]){
17049 groups[g].push(menu);
17050 menu.on("checkchange", onCheck);
17055 * Returns a {@link Roo.menu.Menu} object
17056 * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
17057 * be used to generate and return a new Menu instance.
17059 get : function(menu){
17060 if(typeof menu == "string"){ // menu id
17061 return menus[menu];
17062 }else if(menu.events){ // menu instance
17064 }else if(typeof menu.length == 'number'){ // array of menu items?
17065 return new Roo.menu.Menu({items:menu});
17066 }else{ // otherwise, must be a config
17067 return new Roo.menu.Menu(menu);
17072 unregister : function(menu){
17073 delete menus[menu.id];
17074 menu.un("beforehide", onBeforeHide);
17075 menu.un("hide", onHide);
17076 menu.un("beforeshow", onBeforeShow);
17077 menu.un("show", onShow);
17078 var g = menu.group;
17079 if(g && menu.events["checkchange"]){
17080 groups[g].remove(menu);
17081 menu.un("checkchange", onCheck);
17086 registerCheckable : function(menuItem){
17087 var g = menuItem.group;
17092 groups[g].push(menuItem);
17093 menuItem.on("beforecheckchange", onBeforeCheck);
17098 unregisterCheckable : function(menuItem){
17099 var g = menuItem.group;
17101 groups[g].remove(menuItem);
17102 menuItem.un("beforecheckchange", onBeforeCheck);
17108 * Ext JS Library 1.1.1
17109 * Copyright(c) 2006-2007, Ext JS, LLC.
17111 * Originally Released Under LGPL - original licence link has changed is not relivant.
17114 * <script type="text/javascript">
17119 * @class Roo.menu.BaseItem
17120 * @extends Roo.Component
17122 * The base class for all items that render into menus. BaseItem provides default rendering, activated state
17123 * management and base configuration options shared by all menu components.
17125 * Creates a new BaseItem
17126 * @param {Object} config Configuration options
17128 Roo.menu.BaseItem = function(config){
17129 Roo.menu.BaseItem.superclass.constructor.call(this, config);
17134 * Fires when this item is clicked
17135 * @param {Roo.menu.BaseItem} this
17136 * @param {Roo.EventObject} e
17141 * Fires when this item is activated
17142 * @param {Roo.menu.BaseItem} this
17146 * @event deactivate
17147 * Fires when this item is deactivated
17148 * @param {Roo.menu.BaseItem} this
17154 this.on("click", this.handler, this.scope, true);
17158 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
17160 * @cfg {Function} handler
17161 * A function that will handle the click event of this menu item (defaults to undefined)
17164 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
17166 canActivate : false,
17169 * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
17174 * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
17176 activeClass : "x-menu-item-active",
17178 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
17180 hideOnClick : true,
17182 * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
17187 ctype: "Roo.menu.BaseItem",
17190 actionMode : "container",
17193 render : function(container, parentMenu){
17194 this.parentMenu = parentMenu;
17195 Roo.menu.BaseItem.superclass.render.call(this, container);
17196 this.container.menuItemId = this.id;
17200 onRender : function(container, position){
17201 this.el = Roo.get(this.el);
17202 container.dom.appendChild(this.el.dom);
17206 onClick : function(e){
17207 if(!this.disabled && this.fireEvent("click", this, e) !== false
17208 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
17209 this.handleClick(e);
17216 activate : function(){
17220 var li = this.container;
17221 li.addClass(this.activeClass);
17222 this.region = li.getRegion().adjust(2, 2, -2, -2);
17223 this.fireEvent("activate", this);
17228 deactivate : function(){
17229 this.container.removeClass(this.activeClass);
17230 this.fireEvent("deactivate", this);
17234 shouldDeactivate : function(e){
17235 return !this.region || !this.region.contains(e.getPoint());
17239 handleClick : function(e){
17240 if(this.hideOnClick){
17241 this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
17246 expandMenu : function(autoActivate){
17251 hideMenu : function(){
17256 * Ext JS Library 1.1.1
17257 * Copyright(c) 2006-2007, Ext JS, LLC.
17259 * Originally Released Under LGPL - original licence link has changed is not relivant.
17262 * <script type="text/javascript">
17266 * @class Roo.menu.Adapter
17267 * @extends Roo.menu.BaseItem
17269 * 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.
17270 * It provides basic rendering, activation management and enable/disable logic required to work in menus.
17272 * Creates a new Adapter
17273 * @param {Object} config Configuration options
17275 Roo.menu.Adapter = function(component, config){
17276 Roo.menu.Adapter.superclass.constructor.call(this, config);
17277 this.component = component;
17279 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
17281 canActivate : true,
17284 onRender : function(container, position){
17285 this.component.render(container);
17286 this.el = this.component.getEl();
17290 activate : function(){
17294 this.component.focus();
17295 this.fireEvent("activate", this);
17300 deactivate : function(){
17301 this.fireEvent("deactivate", this);
17305 disable : function(){
17306 this.component.disable();
17307 Roo.menu.Adapter.superclass.disable.call(this);
17311 enable : function(){
17312 this.component.enable();
17313 Roo.menu.Adapter.superclass.enable.call(this);
17317 * Ext JS Library 1.1.1
17318 * Copyright(c) 2006-2007, Ext JS, LLC.
17320 * Originally Released Under LGPL - original licence link has changed is not relivant.
17323 * <script type="text/javascript">
17327 * @class Roo.menu.TextItem
17328 * @extends Roo.menu.BaseItem
17329 * Adds a static text string to a menu, usually used as either a heading or group separator.
17330 * Note: old style constructor with text is still supported.
17333 * Creates a new TextItem
17334 * @param {Object} cfg Configuration
17336 Roo.menu.TextItem = function(cfg){
17337 if (typeof(cfg) == 'string') {
17340 Roo.apply(this,cfg);
17343 Roo.menu.TextItem.superclass.constructor.call(this);
17346 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
17348 * @cfg {String} text Text to show on item.
17353 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
17355 hideOnClick : false,
17357 * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
17359 itemCls : "x-menu-text",
17362 onRender : function(){
17363 var s = document.createElement("span");
17364 s.className = this.itemCls;
17365 s.innerHTML = this.text;
17367 Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
17371 * Ext JS Library 1.1.1
17372 * Copyright(c) 2006-2007, Ext JS, LLC.
17374 * Originally Released Under LGPL - original licence link has changed is not relivant.
17377 * <script type="text/javascript">
17381 * @class Roo.menu.Separator
17382 * @extends Roo.menu.BaseItem
17383 * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
17384 * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
17386 * @param {Object} config Configuration options
17388 Roo.menu.Separator = function(config){
17389 Roo.menu.Separator.superclass.constructor.call(this, config);
17392 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
17394 * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
17396 itemCls : "x-menu-sep",
17398 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
17400 hideOnClick : false,
17403 onRender : function(li){
17404 var s = document.createElement("span");
17405 s.className = this.itemCls;
17406 s.innerHTML = " ";
17408 li.addClass("x-menu-sep-li");
17409 Roo.menu.Separator.superclass.onRender.apply(this, arguments);
17413 * Ext JS Library 1.1.1
17414 * Copyright(c) 2006-2007, Ext JS, LLC.
17416 * Originally Released Under LGPL - original licence link has changed is not relivant.
17419 * <script type="text/javascript">
17422 * @class Roo.menu.Item
17423 * @extends Roo.menu.BaseItem
17424 * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
17425 * display items. Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
17426 * activation and click handling.
17428 * Creates a new Item
17429 * @param {Object} config Configuration options
17431 Roo.menu.Item = function(config){
17432 Roo.menu.Item.superclass.constructor.call(this, config);
17434 this.menu = Roo.menu.MenuMgr.get(this.menu);
17437 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
17439 * @cfg {Roo.menu.Menu} menu
17443 * @cfg {String} text
17444 * The text to show on the menu item.
17448 * @cfg {String} html to render in menu
17449 * The text to show on the menu item (HTML version).
17453 * @cfg {String} icon
17454 * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
17458 * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
17460 itemCls : "x-menu-item",
17462 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
17464 canActivate : true,
17466 * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
17469 // doc'd in BaseItem
17473 ctype: "Roo.menu.Item",
17476 onRender : function(container, position){
17477 var el = document.createElement("a");
17478 el.hideFocus = true;
17479 el.unselectable = "on";
17480 el.href = this.href || "#";
17481 if(this.hrefTarget){
17482 el.target = this.hrefTarget;
17484 el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : "");
17486 var html = this.html.length ? this.html : String.format('{0}',this.text);
17488 el.innerHTML = String.format(
17489 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
17490 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
17492 Roo.menu.Item.superclass.onRender.call(this, container, position);
17496 * Sets the text to display in this menu item
17497 * @param {String} text The text to display
17498 * @param {Boolean} isHTML true to indicate text is pure html.
17500 setText : function(text, isHTML){
17508 var html = this.html.length ? this.html : String.format('{0}',this.text);
17510 this.el.update(String.format(
17511 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
17512 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
17513 this.parentMenu.autoWidth();
17518 handleClick : function(e){
17519 if(!this.href){ // if no link defined, stop the event automatically
17522 Roo.menu.Item.superclass.handleClick.apply(this, arguments);
17526 activate : function(autoExpand){
17527 if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
17537 shouldDeactivate : function(e){
17538 if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
17539 if(this.menu && this.menu.isVisible()){
17540 return !this.menu.getEl().getRegion().contains(e.getPoint());
17548 deactivate : function(){
17549 Roo.menu.Item.superclass.deactivate.apply(this, arguments);
17554 expandMenu : function(autoActivate){
17555 if(!this.disabled && this.menu){
17556 clearTimeout(this.hideTimer);
17557 delete this.hideTimer;
17558 if(!this.menu.isVisible() && !this.showTimer){
17559 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
17560 }else if (this.menu.isVisible() && autoActivate){
17561 this.menu.tryActivate(0, 1);
17567 deferExpand : function(autoActivate){
17568 delete this.showTimer;
17569 this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
17571 this.menu.tryActivate(0, 1);
17576 hideMenu : function(){
17577 clearTimeout(this.showTimer);
17578 delete this.showTimer;
17579 if(!this.hideTimer && this.menu && this.menu.isVisible()){
17580 this.hideTimer = this.deferHide.defer(this.hideDelay, this);
17585 deferHide : function(){
17586 delete this.hideTimer;
17591 * Ext JS Library 1.1.1
17592 * Copyright(c) 2006-2007, Ext JS, LLC.
17594 * Originally Released Under LGPL - original licence link has changed is not relivant.
17597 * <script type="text/javascript">
17601 * @class Roo.menu.CheckItem
17602 * @extends Roo.menu.Item
17603 * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
17605 * Creates a new CheckItem
17606 * @param {Object} config Configuration options
17608 Roo.menu.CheckItem = function(config){
17609 Roo.menu.CheckItem.superclass.constructor.call(this, config);
17612 * @event beforecheckchange
17613 * Fires before the checked value is set, providing an opportunity to cancel if needed
17614 * @param {Roo.menu.CheckItem} this
17615 * @param {Boolean} checked The new checked value that will be set
17617 "beforecheckchange" : true,
17619 * @event checkchange
17620 * Fires after the checked value has been set
17621 * @param {Roo.menu.CheckItem} this
17622 * @param {Boolean} checked The checked value that was set
17624 "checkchange" : true
17626 if(this.checkHandler){
17627 this.on('checkchange', this.checkHandler, this.scope);
17630 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
17632 * @cfg {String} group
17633 * All check items with the same group name will automatically be grouped into a single-select
17634 * radio button group (defaults to '')
17637 * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
17639 itemCls : "x-menu-item x-menu-check-item",
17641 * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
17643 groupClass : "x-menu-group-item",
17646 * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false). Note that
17647 * if this checkbox is part of a radio group (group = true) only the last item in the group that is
17648 * initialized with checked = true will be rendered as checked.
17653 ctype: "Roo.menu.CheckItem",
17656 onRender : function(c){
17657 Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
17659 this.el.addClass(this.groupClass);
17661 Roo.menu.MenuMgr.registerCheckable(this);
17663 this.checked = false;
17664 this.setChecked(true, true);
17669 destroy : function(){
17671 Roo.menu.MenuMgr.unregisterCheckable(this);
17673 Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
17677 * Set the checked state of this item
17678 * @param {Boolean} checked The new checked value
17679 * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
17681 setChecked : function(state, suppressEvent){
17682 if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
17683 if(this.container){
17684 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
17686 this.checked = state;
17687 if(suppressEvent !== true){
17688 this.fireEvent("checkchange", this, state);
17694 handleClick : function(e){
17695 if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
17696 this.setChecked(!this.checked);
17698 Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
17702 * Ext JS Library 1.1.1
17703 * Copyright(c) 2006-2007, Ext JS, LLC.
17705 * Originally Released Under LGPL - original licence link has changed is not relivant.
17708 * <script type="text/javascript">
17712 * @class Roo.menu.DateItem
17713 * @extends Roo.menu.Adapter
17714 * A menu item that wraps the {@link Roo.DatPicker} component.
17716 * Creates a new DateItem
17717 * @param {Object} config Configuration options
17719 Roo.menu.DateItem = function(config){
17720 Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
17721 /** The Roo.DatePicker object @type Roo.DatePicker */
17722 this.picker = this.component;
17723 this.addEvents({select: true});
17725 this.picker.on("render", function(picker){
17726 picker.getEl().swallowEvent("click");
17727 picker.container.addClass("x-menu-date-item");
17730 this.picker.on("select", this.onSelect, this);
17733 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
17735 onSelect : function(picker, date){
17736 this.fireEvent("select", this, date, picker);
17737 Roo.menu.DateItem.superclass.handleClick.call(this);
17741 * Ext JS Library 1.1.1
17742 * Copyright(c) 2006-2007, Ext JS, LLC.
17744 * Originally Released Under LGPL - original licence link has changed is not relivant.
17747 * <script type="text/javascript">
17751 * @class Roo.menu.ColorItem
17752 * @extends Roo.menu.Adapter
17753 * A menu item that wraps the {@link Roo.ColorPalette} component.
17755 * Creates a new ColorItem
17756 * @param {Object} config Configuration options
17758 Roo.menu.ColorItem = function(config){
17759 Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
17760 /** The Roo.ColorPalette object @type Roo.ColorPalette */
17761 this.palette = this.component;
17762 this.relayEvents(this.palette, ["select"]);
17763 if(this.selectHandler){
17764 this.on('select', this.selectHandler, this.scope);
17767 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
17769 * Ext JS Library 1.1.1
17770 * Copyright(c) 2006-2007, Ext JS, LLC.
17772 * Originally Released Under LGPL - original licence link has changed is not relivant.
17775 * <script type="text/javascript">
17780 * @class Roo.menu.DateMenu
17781 * @extends Roo.menu.Menu
17782 * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
17784 * Creates a new DateMenu
17785 * @param {Object} config Configuration options
17787 Roo.menu.DateMenu = function(config){
17788 Roo.menu.DateMenu.superclass.constructor.call(this, config);
17790 var di = new Roo.menu.DateItem(config);
17793 * The {@link Roo.DatePicker} instance for this DateMenu
17796 this.picker = di.picker;
17799 * @param {DatePicker} picker
17800 * @param {Date} date
17802 this.relayEvents(di, ["select"]);
17803 this.on('beforeshow', function(){
17805 this.picker.hideMonthPicker(false);
17809 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
17813 * Ext JS Library 1.1.1
17814 * Copyright(c) 2006-2007, Ext JS, LLC.
17816 * Originally Released Under LGPL - original licence link has changed is not relivant.
17819 * <script type="text/javascript">
17824 * @class Roo.menu.ColorMenu
17825 * @extends Roo.menu.Menu
17826 * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
17828 * Creates a new ColorMenu
17829 * @param {Object} config Configuration options
17831 Roo.menu.ColorMenu = function(config){
17832 Roo.menu.ColorMenu.superclass.constructor.call(this, config);
17834 var ci = new Roo.menu.ColorItem(config);
17837 * The {@link Roo.ColorPalette} instance for this ColorMenu
17838 * @type ColorPalette
17840 this.palette = ci.palette;
17843 * @param {ColorPalette} palette
17844 * @param {String} color
17846 this.relayEvents(ci, ["select"]);
17848 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
17850 * Ext JS Library 1.1.1
17851 * Copyright(c) 2006-2007, Ext JS, LLC.
17853 * Originally Released Under LGPL - original licence link has changed is not relivant.
17856 * <script type="text/javascript">
17860 * @class Roo.form.TextItem
17861 * @extends Roo.BoxComponent
17862 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
17864 * Creates a new TextItem
17865 * @param {Object} config Configuration options
17867 Roo.form.TextItem = function(config){
17868 Roo.form.TextItem.superclass.constructor.call(this, config);
17871 Roo.extend(Roo.form.TextItem, Roo.BoxComponent, {
17874 * @cfg {String} tag the tag for this item (default div)
17878 * @cfg {String} html the content for this item
17882 getAutoCreate : function()
17895 onRender : function(ct, position)
17897 Roo.form.TextItem.superclass.onRender.call(this, ct, position);
17900 var cfg = this.getAutoCreate();
17902 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
17904 if (!cfg.name.length) {
17907 this.el = ct.createChild(cfg, position);
17912 * @param {String} html update the Contents of the element.
17914 setHTML : function(html)
17916 this.fieldEl.dom.innerHTML = html;
17921 * Ext JS Library 1.1.1
17922 * Copyright(c) 2006-2007, Ext JS, LLC.
17924 * Originally Released Under LGPL - original licence link has changed is not relivant.
17927 * <script type="text/javascript">
17931 * @class Roo.form.Field
17932 * @extends Roo.BoxComponent
17933 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
17935 * Creates a new Field
17936 * @param {Object} config Configuration options
17938 Roo.form.Field = function(config){
17939 Roo.form.Field.superclass.constructor.call(this, config);
17942 Roo.extend(Roo.form.Field, Roo.BoxComponent, {
17944 * @cfg {String} fieldLabel Label to use when rendering a form.
17947 * @cfg {String} labelSeparator the ':' after a field label (default :) = set it to empty string to hide the field label.
17950 * @cfg {String} qtip Mouse over tip
17954 * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
17956 invalidClass : "x-form-invalid",
17958 * @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")
17960 invalidText : "The value in this field is invalid",
17962 * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
17964 focusClass : "x-form-focus",
17966 * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
17967 automatic validation (defaults to "keyup").
17969 validationEvent : "keyup",
17971 * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
17973 validateOnBlur : true,
17975 * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
17977 validationDelay : 250,
17979 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
17980 * {tag: "input", type: "text", size: "20", autocomplete: "off"})
17982 defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
17984 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
17986 fieldClass : "x-form-field",
17988 * @cfg {String} msgTarget The location where error text should display. Should be one of the following values (defaults to 'qtip'):
17991 ----------- ----------------------------------------------------------------------
17992 qtip Display a quick tip when the user hovers over the field
17993 title Display a default browser title attribute popup
17994 under Add a block div beneath the field containing the error text
17995 side Add an error icon to the right of the field with a popup on hover
17996 [element id] Add the error text directly to the innerHTML of the specified element
17999 msgTarget : 'qtip',
18001 * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
18006 * @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.
18011 * @cfg {Boolean} disabled True to disable the field (defaults to false).
18016 * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
18018 inputType : undefined,
18021 * @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).
18023 tabIndex : undefined,
18026 isFormField : true,
18031 * @property {Roo.Element} fieldEl
18032 * Element Containing the rendered Field (with label etc.)
18035 * @cfg {Mixed} value A value to initialize this field with.
18040 * @cfg {String} name The field's HTML name attribute.
18043 * @cfg {String} cls A CSS class to apply to the field's underlying element.
18046 loadedValue : false,
18050 initComponent : function(){
18051 Roo.form.Field.superclass.initComponent.call(this);
18055 * Fires when this field receives input focus.
18056 * @param {Roo.form.Field} this
18061 * Fires when this field loses input focus.
18062 * @param {Roo.form.Field} this
18066 * @event specialkey
18067 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
18068 * {@link Roo.EventObject#getKey} to determine which key was pressed.
18069 * @param {Roo.form.Field} this
18070 * @param {Roo.EventObject} e The event object
18075 * Fires just before the field blurs if the field value has changed.
18076 * @param {Roo.form.Field} this
18077 * @param {Mixed} newValue The new value
18078 * @param {Mixed} oldValue The original value
18083 * Fires after the field has been marked as invalid.
18084 * @param {Roo.form.Field} this
18085 * @param {String} msg The validation message
18090 * Fires after the field has been validated with no errors.
18091 * @param {Roo.form.Field} this
18096 * Fires after the key up
18097 * @param {Roo.form.Field} this
18098 * @param {Roo.EventObject} e The event Object
18105 * Returns the name attribute of the field if available
18106 * @return {String} name The field name
18108 getName: function(){
18109 return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
18113 onRender : function(ct, position){
18114 Roo.form.Field.superclass.onRender.call(this, ct, position);
18116 var cfg = this.getAutoCreate();
18118 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
18120 if (!cfg.name.length) {
18123 if(this.inputType){
18124 cfg.type = this.inputType;
18126 this.el = ct.createChild(cfg, position);
18128 var type = this.el.dom.type;
18130 if(type == 'password'){
18133 this.el.addClass('x-form-'+type);
18136 this.el.dom.readOnly = true;
18138 if(this.tabIndex !== undefined){
18139 this.el.dom.setAttribute('tabIndex', this.tabIndex);
18142 this.el.addClass([this.fieldClass, this.cls]);
18147 * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
18148 * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
18149 * @return {Roo.form.Field} this
18151 applyTo : function(target){
18152 this.allowDomMove = false;
18153 this.el = Roo.get(target);
18154 this.render(this.el.dom.parentNode);
18159 initValue : function(){
18160 if(this.value !== undefined){
18161 this.setValue(this.value);
18162 }else if(this.el.dom.value.length > 0){
18163 this.setValue(this.el.dom.value);
18168 * Returns true if this field has been changed since it was originally loaded and is not disabled.
18169 * DEPRICATED - it never worked well - use hasChanged/resetHasChanged.
18171 isDirty : function() {
18172 if(this.disabled) {
18175 return String(this.getValue()) !== String(this.originalValue);
18179 * stores the current value in loadedValue
18181 resetHasChanged : function()
18183 this.loadedValue = String(this.getValue());
18186 * checks the current value against the 'loaded' value.
18187 * Note - will return false if 'resetHasChanged' has not been called first.
18189 hasChanged : function()
18191 if(this.disabled || this.readOnly) {
18194 return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
18200 afterRender : function(){
18201 Roo.form.Field.superclass.afterRender.call(this);
18206 fireKey : function(e){
18207 //Roo.log('field ' + e.getKey());
18208 if(e.isNavKeyPress()){
18209 this.fireEvent("specialkey", this, e);
18214 * Resets the current field value to the originally loaded value and clears any validation messages
18216 reset : function(){
18217 this.setValue(this.resetValue);
18218 this.originalValue = this.getValue();
18219 this.clearInvalid();
18223 initEvents : function(){
18224 // safari killled keypress - so keydown is now used..
18225 this.el.on("keydown" , this.fireKey, this);
18226 this.el.on("focus", this.onFocus, this);
18227 this.el.on("blur", this.onBlur, this);
18228 this.el.relayEvent('keyup', this);
18230 // reference to original value for reset
18231 this.originalValue = this.getValue();
18232 this.resetValue = this.getValue();
18236 onFocus : function(){
18237 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
18238 this.el.addClass(this.focusClass);
18240 if(!this.hasFocus){
18241 this.hasFocus = true;
18242 this.startValue = this.getValue();
18243 this.fireEvent("focus", this);
18247 beforeBlur : Roo.emptyFn,
18250 onBlur : function(){
18252 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
18253 this.el.removeClass(this.focusClass);
18255 this.hasFocus = false;
18256 if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
18259 var v = this.getValue();
18260 if(String(v) !== String(this.startValue)){
18261 this.fireEvent('change', this, v, this.startValue);
18263 this.fireEvent("blur", this);
18267 * Returns whether or not the field value is currently valid
18268 * @param {Boolean} preventMark True to disable marking the field invalid
18269 * @return {Boolean} True if the value is valid, else false
18271 isValid : function(preventMark){
18275 var restore = this.preventMark;
18276 this.preventMark = preventMark === true;
18277 var v = this.validateValue(this.processValue(this.getRawValue()));
18278 this.preventMark = restore;
18283 * Validates the field value
18284 * @return {Boolean} True if the value is valid, else false
18286 validate : function(){
18287 if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
18288 this.clearInvalid();
18294 processValue : function(value){
18299 // Subclasses should provide the validation implementation by overriding this
18300 validateValue : function(value){
18305 * Mark this field as invalid
18306 * @param {String} msg The validation message
18308 markInvalid : function(msg){
18309 if(!this.rendered || this.preventMark){ // not rendered
18313 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
18315 obj.el.addClass(this.invalidClass);
18316 msg = msg || this.invalidText;
18317 switch(this.msgTarget){
18319 obj.el.dom.qtip = msg;
18320 obj.el.dom.qclass = 'x-form-invalid-tip';
18321 if(Roo.QuickTips){ // fix for floating editors interacting with DND
18322 Roo.QuickTips.enable();
18326 this.el.dom.title = msg;
18330 var elp = this.el.findParent('.x-form-element', 5, true);
18331 this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
18332 this.errorEl.setWidth(elp.getWidth(true)-20);
18334 this.errorEl.update(msg);
18335 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
18338 if(!this.errorIcon){
18339 var elp = this.el.findParent('.x-form-element', 5, true);
18340 this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
18342 this.alignErrorIcon();
18343 this.errorIcon.dom.qtip = msg;
18344 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
18345 this.errorIcon.show();
18346 this.on('resize', this.alignErrorIcon, this);
18349 var t = Roo.getDom(this.msgTarget);
18351 t.style.display = this.msgDisplay;
18354 this.fireEvent('invalid', this, msg);
18358 alignErrorIcon : function(){
18359 this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
18363 * Clear any invalid styles/messages for this field
18365 clearInvalid : function(){
18366 if(!this.rendered || this.preventMark){ // not rendered
18369 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
18371 obj.el.removeClass(this.invalidClass);
18372 switch(this.msgTarget){
18374 obj.el.dom.qtip = '';
18377 this.el.dom.title = '';
18381 Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
18385 if(this.errorIcon){
18386 this.errorIcon.dom.qtip = '';
18387 this.errorIcon.hide();
18388 this.un('resize', this.alignErrorIcon, this);
18392 var t = Roo.getDom(this.msgTarget);
18394 t.style.display = 'none';
18397 this.fireEvent('valid', this);
18401 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
18402 * @return {Mixed} value The field value
18404 getRawValue : function(){
18405 var v = this.el.getValue();
18411 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
18412 * @return {Mixed} value The field value
18414 getValue : function(){
18415 var v = this.el.getValue();
18421 * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
18422 * @param {Mixed} value The value to set
18424 setRawValue : function(v){
18425 return this.el.dom.value = (v === null || v === undefined ? '' : v);
18429 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
18430 * @param {Mixed} value The value to set
18432 setValue : function(v){
18435 this.el.dom.value = (v === null || v === undefined ? '' : v);
18440 adjustSize : function(w, h){
18441 var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
18442 s.width = this.adjustWidth(this.el.dom.tagName, s.width);
18446 adjustWidth : function(tag, w){
18447 tag = tag.toLowerCase();
18448 if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
18449 if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
18450 if(tag == 'input'){
18453 if(tag == 'textarea'){
18456 }else if(Roo.isOpera){
18457 if(tag == 'input'){
18460 if(tag == 'textarea'){
18470 // anything other than normal should be considered experimental
18471 Roo.form.Field.msgFx = {
18473 show: function(msgEl, f){
18474 msgEl.setDisplayed('block');
18477 hide : function(msgEl, f){
18478 msgEl.setDisplayed(false).update('');
18483 show: function(msgEl, f){
18484 msgEl.slideIn('t', {stopFx:true});
18487 hide : function(msgEl, f){
18488 msgEl.slideOut('t', {stopFx:true,useDisplay:true});
18493 show: function(msgEl, f){
18494 msgEl.fixDisplay();
18495 msgEl.alignTo(f.el, 'tl-tr');
18496 msgEl.slideIn('l', {stopFx:true});
18499 hide : function(msgEl, f){
18500 msgEl.slideOut('l', {stopFx:true,useDisplay:true});
18505 * Ext JS Library 1.1.1
18506 * Copyright(c) 2006-2007, Ext JS, LLC.
18508 * Originally Released Under LGPL - original licence link has changed is not relivant.
18511 * <script type="text/javascript">
18516 * @class Roo.form.TextField
18517 * @extends Roo.form.Field
18518 * Basic text field. Can be used as a direct replacement for traditional text inputs, or as the base
18519 * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
18521 * Creates a new TextField
18522 * @param {Object} config Configuration options
18524 Roo.form.TextField = function(config){
18525 Roo.form.TextField.superclass.constructor.call(this, config);
18529 * Fires when the autosize function is triggered. The field may or may not have actually changed size
18530 * according to the default logic, but this event provides a hook for the developer to apply additional
18531 * logic at runtime to resize the field if needed.
18532 * @param {Roo.form.Field} this This text field
18533 * @param {Number} width The new field width
18539 Roo.extend(Roo.form.TextField, Roo.form.Field, {
18541 * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
18545 * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
18549 * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
18553 * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
18557 * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
18561 * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
18563 disableKeyFilter : false,
18565 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
18569 * @cfg {Number} minLength Minimum input field length required (defaults to 0)
18573 * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
18575 maxLength : Number.MAX_VALUE,
18577 * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
18579 minLengthText : "The minimum length for this field is {0}",
18581 * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
18583 maxLengthText : "The maximum length for this field is {0}",
18585 * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
18587 selectOnFocus : false,
18589 * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space
18591 allowLeadingSpace : false,
18593 * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
18595 blankText : "This field is required",
18597 * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
18598 * If available, this function will be called only after the basic validators all return true, and will be passed the
18599 * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
18603 * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
18604 * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
18605 * current field value. If the test fails, the field will be marked invalid using {@link #regexText}.
18609 * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
18613 * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
18619 initEvents : function()
18621 if (this.emptyText) {
18622 this.el.attr('placeholder', this.emptyText);
18625 Roo.form.TextField.superclass.initEvents.call(this);
18626 if(this.validationEvent == 'keyup'){
18627 this.validationTask = new Roo.util.DelayedTask(this.validate, this);
18628 this.el.on('keyup', this.filterValidation, this);
18630 else if(this.validationEvent !== false){
18631 this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
18634 if(this.selectOnFocus){
18635 this.on("focus", this.preFocus, this);
18637 if (!this.allowLeadingSpace) {
18638 this.on('blur', this.cleanLeadingSpace, this);
18641 if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
18642 this.el.on("keypress", this.filterKeys, this);
18645 this.el.on("keyup", this.onKeyUp, this, {buffer:50});
18646 this.el.on("click", this.autoSize, this);
18648 if(this.el.is('input[type=password]') && Roo.isSafari){
18649 this.el.on('keydown', this.SafariOnKeyDown, this);
18653 processValue : function(value){
18654 if(this.stripCharsRe){
18655 var newValue = value.replace(this.stripCharsRe, '');
18656 if(newValue !== value){
18657 this.setRawValue(newValue);
18664 filterValidation : function(e){
18665 if(!e.isNavKeyPress()){
18666 this.validationTask.delay(this.validationDelay);
18671 onKeyUp : function(e){
18672 if(!e.isNavKeyPress()){
18676 // private - clean the leading white space
18677 cleanLeadingSpace : function(e)
18679 if ( this.inputType == 'file') {
18683 this.setValue((this.getValue() + '').replace(/^\s+/,''));
18686 * Resets the current field value to the originally-loaded value and clears any validation messages.
18689 reset : function(){
18690 Roo.form.TextField.superclass.reset.call(this);
18694 preFocus : function(){
18696 if(this.selectOnFocus){
18697 this.el.dom.select();
18703 filterKeys : function(e){
18704 var k = e.getKey();
18705 if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
18708 var c = e.getCharCode(), cc = String.fromCharCode(c);
18709 if(Roo.isIE && (e.isSpecialKey() || !cc)){
18712 if(!this.maskRe.test(cc)){
18717 setValue : function(v){
18719 Roo.form.TextField.superclass.setValue.apply(this, arguments);
18725 * Validates a value according to the field's validation rules and marks the field as invalid
18726 * if the validation fails
18727 * @param {Mixed} value The value to validate
18728 * @return {Boolean} True if the value is valid, else false
18730 validateValue : function(value){
18731 if(value.length < 1) { // if it's blank
18732 if(this.allowBlank){
18733 this.clearInvalid();
18736 this.markInvalid(this.blankText);
18740 if(value.length < this.minLength){
18741 this.markInvalid(String.format(this.minLengthText, this.minLength));
18744 if(value.length > this.maxLength){
18745 this.markInvalid(String.format(this.maxLengthText, this.maxLength));
18749 var vt = Roo.form.VTypes;
18750 if (value.trim() != value) { // trim before checking email (and other stuf??)
18751 value = value.trim();
18752 this.el.dom.value = value;
18755 if(!vt[this.vtype](value, this)){
18756 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
18760 if(typeof this.validator == "function"){
18761 var msg = this.validator(value);
18763 this.markInvalid(msg);
18767 if(this.regex && !this.regex.test(value)){
18768 this.markInvalid(this.regexText);
18775 * Selects text in this field
18776 * @param {Number} start (optional) The index where the selection should start (defaults to 0)
18777 * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
18779 selectText : function(start, end){
18780 var v = this.getRawValue();
18782 start = start === undefined ? 0 : start;
18783 end = end === undefined ? v.length : end;
18784 var d = this.el.dom;
18785 if(d.setSelectionRange){
18786 d.setSelectionRange(start, end);
18787 }else if(d.createTextRange){
18788 var range = d.createTextRange();
18789 range.moveStart("character", start);
18790 range.moveEnd("character", v.length-end);
18797 * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
18798 * This only takes effect if grow = true, and fires the autosize event.
18800 autoSize : function(){
18801 if(!this.grow || !this.rendered){
18805 this.metrics = Roo.util.TextMetrics.createInstance(this.el);
18808 var v = el.dom.value;
18809 var d = document.createElement('div');
18810 d.appendChild(document.createTextNode(v));
18814 var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
18815 this.el.setWidth(w);
18816 this.fireEvent("autosize", this, w);
18820 SafariOnKeyDown : function(event)
18822 // this is a workaround for a password hang bug on chrome/ webkit.
18824 var isSelectAll = false;
18826 if(this.el.dom.selectionEnd > 0){
18827 isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
18829 if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
18830 event.preventDefault();
18835 // skip handling paste
18836 if(isSelectAll && event.getCharCode() > 31 && !(event.ctrlKey && event.getCharCode() == 86)){ // backspace and delete key
18838 event.preventDefault();
18839 // this is very hacky as keydown always get's upper case.
18841 var cc = String.fromCharCode(event.getCharCode());
18844 this.setValue( event.shiftKey ? cc : cc.toLowerCase());
18850 });Roo.form.Password = function(config){
18851 Roo.form.Password.superclass.constructor.call(this, config);
18853 this.inputType = 'password';
18856 Roo.extend(Roo.form.Password, Roo.form.TextField, {
18857 onRender : function(ct, position)
18859 Roo.form.Password.superclass.onRender.call(this, ct, position);
18861 this.parentEl().addClass('form-password');
18863 this.wrap = this.el.wrap({
18864 cls : 'password-wrap'
18867 this.toggle = this.wrap.createChild({
18869 cls : 'password-toggle'
18873 this.toggleEl().addClass('password-hidden');
18875 this.toggleEl().on('click', this.onToggleClick, this);;
18878 parentEl : function()
18880 return this.el.findParent('.x-form-element', 5, true);
18883 toggleEl: function()
18885 return this.parentEl().select('button.password-toggle',true).first();
18888 onToggleClick : function(e)
18890 var input = this.el;
18891 var toggle = this.toggleEl();
18893 toggle.removeClass(['password-visible', 'password-hidden']);
18895 if(input.attr('type') == 'password') {
18896 input.attr('type', 'text');
18897 toggle.addClass('password-visible');
18900 input.attr('type', 'password');
18901 toggle.addClass('password-hidden');
18906 * Ext JS Library 1.1.1
18907 * Copyright(c) 2006-2007, Ext JS, LLC.
18909 * Originally Released Under LGPL - original licence link has changed is not relivant.
18912 * <script type="text/javascript">
18916 * @class Roo.form.Hidden
18917 * @extends Roo.form.TextField
18918 * Simple Hidden element used on forms
18920 * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
18923 * Creates a new Hidden form element.
18924 * @param {Object} config Configuration options
18929 // easy hidden field...
18930 Roo.form.Hidden = function(config){
18931 Roo.form.Hidden.superclass.constructor.call(this, config);
18934 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
18936 inputType: 'hidden',
18939 labelSeparator: '',
18941 itemCls : 'x-form-item-display-none'
18949 * Ext JS Library 1.1.1
18950 * Copyright(c) 2006-2007, Ext JS, LLC.
18952 * Originally Released Under LGPL - original licence link has changed is not relivant.
18955 * <script type="text/javascript">
18959 * @class Roo.form.TriggerField
18960 * @extends Roo.form.TextField
18961 * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
18962 * The trigger has no default action, so you must assign a function to implement the trigger click handler by
18963 * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
18964 * for which you can provide a custom implementation. For example:
18966 var trigger = new Roo.form.TriggerField();
18967 trigger.onTriggerClick = myTriggerFn;
18968 trigger.applyTo('my-field');
18971 * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
18972 * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
18973 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
18974 * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
18976 * Create a new TriggerField.
18977 * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
18978 * to the base TextField)
18980 Roo.form.TriggerField = function(config){
18981 this.mimicing = false;
18982 Roo.form.TriggerField.superclass.constructor.call(this, config);
18985 Roo.extend(Roo.form.TriggerField, Roo.form.TextField, {
18987 * @cfg {String} triggerClass A CSS class to apply to the trigger
18990 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
18991 * {tag: "input", type: "text", size: "16", autocomplete: "off"})
18993 defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
18995 * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
18999 /** @cfg {Boolean} grow @hide */
19000 /** @cfg {Number} growMin @hide */
19001 /** @cfg {Number} growMax @hide */
19007 autoSize: Roo.emptyFn,
19011 deferHeight : true,
19014 actionMode : 'wrap',
19016 onResize : function(w, h){
19017 Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
19018 if(typeof w == 'number'){
19019 var x = w - this.trigger.getWidth();
19020 this.el.setWidth(this.adjustWidth('input', x));
19021 this.trigger.setStyle('left', x+'px');
19026 adjustSize : Roo.BoxComponent.prototype.adjustSize,
19029 getResizeEl : function(){
19034 getPositionEl : function(){
19039 alignErrorIcon : function(){
19040 this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
19044 onRender : function(ct, position){
19045 Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
19046 this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
19047 this.trigger = this.wrap.createChild(this.triggerConfig ||
19048 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
19049 if(this.hideTrigger){
19050 this.trigger.setDisplayed(false);
19052 this.initTrigger();
19054 this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
19059 initTrigger : function(){
19060 this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
19061 this.trigger.addClassOnOver('x-form-trigger-over');
19062 this.trigger.addClassOnClick('x-form-trigger-click');
19066 onDestroy : function(){
19068 this.trigger.removeAllListeners();
19069 this.trigger.remove();
19072 this.wrap.remove();
19074 Roo.form.TriggerField.superclass.onDestroy.call(this);
19078 onFocus : function(){
19079 Roo.form.TriggerField.superclass.onFocus.call(this);
19080 if(!this.mimicing){
19081 this.wrap.addClass('x-trigger-wrap-focus');
19082 this.mimicing = true;
19083 Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
19084 if(this.monitorTab){
19085 this.el.on("keydown", this.checkTab, this);
19091 checkTab : function(e){
19092 if(e.getKey() == e.TAB){
19093 this.triggerBlur();
19098 onBlur : function(){
19103 mimicBlur : function(e, t){
19104 if(!this.wrap.contains(t) && this.validateBlur()){
19105 this.triggerBlur();
19110 triggerBlur : function(){
19111 this.mimicing = false;
19112 Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
19113 if(this.monitorTab){
19114 this.el.un("keydown", this.checkTab, this);
19116 this.wrap.removeClass('x-trigger-wrap-focus');
19117 Roo.form.TriggerField.superclass.onBlur.call(this);
19121 // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
19122 validateBlur : function(e, t){
19127 onDisable : function(){
19128 Roo.form.TriggerField.superclass.onDisable.call(this);
19130 this.wrap.addClass('x-item-disabled');
19135 onEnable : function(){
19136 Roo.form.TriggerField.superclass.onEnable.call(this);
19138 this.wrap.removeClass('x-item-disabled');
19143 onShow : function(){
19144 var ae = this.getActionEl();
19147 ae.dom.style.display = '';
19148 ae.dom.style.visibility = 'visible';
19154 onHide : function(){
19155 var ae = this.getActionEl();
19156 ae.dom.style.display = 'none';
19160 * The function that should handle the trigger's click event. This method does nothing by default until overridden
19161 * by an implementing function.
19163 * @param {EventObject} e
19165 onTriggerClick : Roo.emptyFn
19168 // TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
19169 // to be extended by an implementing class. For an example of implementing this class, see the custom
19170 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
19171 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
19172 initComponent : function(){
19173 Roo.form.TwinTriggerField.superclass.initComponent.call(this);
19175 this.triggerConfig = {
19176 tag:'span', cls:'x-form-twin-triggers', cn:[
19177 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
19178 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
19182 getTrigger : function(index){
19183 return this.triggers[index];
19186 initTrigger : function(){
19187 var ts = this.trigger.select('.x-form-trigger', true);
19188 this.wrap.setStyle('overflow', 'hidden');
19189 var triggerField = this;
19190 ts.each(function(t, all, index){
19191 t.hide = function(){
19192 var w = triggerField.wrap.getWidth();
19193 this.dom.style.display = 'none';
19194 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
19196 t.show = function(){
19197 var w = triggerField.wrap.getWidth();
19198 this.dom.style.display = '';
19199 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
19201 var triggerIndex = 'Trigger'+(index+1);
19203 if(this['hide'+triggerIndex]){
19204 t.dom.style.display = 'none';
19206 t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
19207 t.addClassOnOver('x-form-trigger-over');
19208 t.addClassOnClick('x-form-trigger-click');
19210 this.triggers = ts.elements;
19213 onTrigger1Click : Roo.emptyFn,
19214 onTrigger2Click : Roo.emptyFn
19217 * Ext JS Library 1.1.1
19218 * Copyright(c) 2006-2007, Ext JS, LLC.
19220 * Originally Released Under LGPL - original licence link has changed is not relivant.
19223 * <script type="text/javascript">
19227 * @class Roo.form.TextArea
19228 * @extends Roo.form.TextField
19229 * Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
19230 * support for auto-sizing.
19232 * Creates a new TextArea
19233 * @param {Object} config Configuration options
19235 Roo.form.TextArea = function(config){
19236 Roo.form.TextArea.superclass.constructor.call(this, config);
19237 // these are provided exchanges for backwards compat
19238 // minHeight/maxHeight were replaced by growMin/growMax to be
19239 // compatible with TextField growing config values
19240 if(this.minHeight !== undefined){
19241 this.growMin = this.minHeight;
19243 if(this.maxHeight !== undefined){
19244 this.growMax = this.maxHeight;
19248 Roo.extend(Roo.form.TextArea, Roo.form.TextField, {
19250 * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
19254 * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
19258 * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
19259 * in the field (equivalent to setting overflow: hidden, defaults to false)
19261 preventScrollbars: false,
19263 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
19264 * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
19268 onRender : function(ct, position){
19270 this.defaultAutoCreate = {
19272 style:"width:300px;height:60px;",
19273 autocomplete: "new-password"
19276 Roo.form.TextArea.superclass.onRender.call(this, ct, position);
19278 this.textSizeEl = Roo.DomHelper.append(document.body, {
19279 tag: "pre", cls: "x-form-grow-sizer"
19281 if(this.preventScrollbars){
19282 this.el.setStyle("overflow", "hidden");
19284 this.el.setHeight(this.growMin);
19288 onDestroy : function(){
19289 if(this.textSizeEl){
19290 this.textSizeEl.parentNode.removeChild(this.textSizeEl);
19292 Roo.form.TextArea.superclass.onDestroy.call(this);
19296 onKeyUp : function(e){
19297 if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
19303 * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
19304 * This only takes effect if grow = true, and fires the autosize event if the height changes.
19306 autoSize : function(){
19307 if(!this.grow || !this.textSizeEl){
19311 var v = el.dom.value;
19312 var ts = this.textSizeEl;
19315 ts.appendChild(document.createTextNode(v));
19318 Roo.fly(ts).setWidth(this.el.getWidth());
19320 v = "  ";
19323 v = v.replace(/\n/g, '<p> </p>');
19325 v += " \n ";
19328 var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
19329 if(h != this.lastHeight){
19330 this.lastHeight = h;
19331 this.el.setHeight(h);
19332 this.fireEvent("autosize", this, h);
19337 * Ext JS Library 1.1.1
19338 * Copyright(c) 2006-2007, Ext JS, LLC.
19340 * Originally Released Under LGPL - original licence link has changed is not relivant.
19343 * <script type="text/javascript">
19348 * @class Roo.form.NumberField
19349 * @extends Roo.form.TextField
19350 * Numeric text field that provides automatic keystroke filtering and numeric validation.
19352 * Creates a new NumberField
19353 * @param {Object} config Configuration options
19355 Roo.form.NumberField = function(config){
19356 Roo.form.NumberField.superclass.constructor.call(this, config);
19359 Roo.extend(Roo.form.NumberField, Roo.form.TextField, {
19361 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
19363 fieldClass: "x-form-field x-form-num-field",
19365 * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
19367 allowDecimals : true,
19369 * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
19371 decimalSeparator : ".",
19373 * @cfg {String} thousandSeparator Character(s) to allow as the thousand separator (defaults to '') - set to ',' for example
19375 thousandSeparator : "",
19377 * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
19379 decimalPrecision : 2,
19381 * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
19383 allowNegative : true,
19385 * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
19387 minValue : Number.NEGATIVE_INFINITY,
19389 * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
19391 maxValue : Number.MAX_VALUE,
19393 * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
19395 minText : "The minimum value for this field is {0}",
19397 * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
19399 maxText : "The maximum value for this field is {0}",
19401 * @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
19402 * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
19404 nanText : "{0} is not a valid number",
19407 initEvents : function(){
19408 Roo.form.NumberField.superclass.initEvents.call(this);
19409 var allowed = "0123456789";
19410 if(this.allowDecimals){
19411 allowed += this.decimalSeparator;
19413 allowed += this.thousandSeparator;
19414 if(this.allowNegative){
19417 this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
19418 var keyPress = function(e){
19419 var k = e.getKey();
19420 if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
19423 var c = e.getCharCode();
19424 if(allowed.indexOf(String.fromCharCode(c)) === -1){
19428 this.el.on("keypress", keyPress, this);
19432 validateValue : function(value){
19433 if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
19436 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
19439 var num = this.parseValue(value);
19441 this.markInvalid(String.format(this.nanText, value));
19444 if(num < this.minValue){
19445 this.markInvalid(String.format(this.minText, this.minValue));
19448 if(num > this.maxValue){
19449 this.markInvalid(String.format(this.maxText, this.maxValue));
19455 getValue : function(){
19456 return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
19460 parseValue : function(value){
19461 value = parseFloat(String(value).replace(this.decimalSeparator, ".").replace(this.thousandSeparator, ''));
19462 return isNaN(value) ? '' : value;
19466 fixPrecision : function(value){
19467 var nan = isNaN(value);
19468 if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
19469 return nan ? '' : value;
19471 return parseFloat(value).toFixed(this.decimalPrecision);
19474 setValue : function(v){
19475 v = this.fixPrecision(v);
19476 if(this.thousandSeparator != ''){
19477 // v = Roo.util.Format.number(v, this.decimalPrecision, this.thousandSeparator);
19479 Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
19483 decimalPrecisionFcn : function(v){
19484 return Math.floor(v);
19487 beforeBlur : function(){
19488 var v = this.parseValue(this.getRawValue());
19495 * Ext JS Library 1.1.1
19496 * Copyright(c) 2006-2007, Ext JS, LLC.
19498 * Originally Released Under LGPL - original licence link has changed is not relivant.
19501 * <script type="text/javascript">
19505 * @class Roo.form.DateField
19506 * @extends Roo.form.TriggerField
19507 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
19509 * Create a new DateField
19510 * @param {Object} config
19512 Roo.form.DateField = function(config)
19514 Roo.form.DateField.superclass.constructor.call(this, config);
19520 * Fires when a date is selected
19521 * @param {Roo.form.DateField} combo This combo box
19522 * @param {Date} date The date selected
19529 if(typeof this.minValue == "string") {
19530 this.minValue = this.parseDate(this.minValue);
19532 if(typeof this.maxValue == "string") {
19533 this.maxValue = this.parseDate(this.maxValue);
19535 this.ddMatch = null;
19536 if(this.disabledDates){
19537 var dd = this.disabledDates;
19539 for(var i = 0; i < dd.length; i++){
19541 if(i != dd.length-1) {
19545 this.ddMatch = new RegExp(re + ")");
19549 Roo.extend(Roo.form.DateField, Roo.form.TriggerField, {
19551 * @cfg {String} format
19552 * The default date format string which can be overriden for localization support. The format must be
19553 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
19557 * @cfg {String} altFormats
19558 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
19559 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
19561 altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
19563 * @cfg {Array} disabledDays
19564 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
19566 disabledDays : null,
19568 * @cfg {String} disabledDaysText
19569 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
19571 disabledDaysText : "Disabled",
19573 * @cfg {Array} disabledDates
19574 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
19575 * expression so they are very powerful. Some examples:
19577 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
19578 * <li>["03/08", "09/16"] would disable those days for every year</li>
19579 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
19580 * <li>["03/../2006"] would disable every day in March 2006</li>
19581 * <li>["^03"] would disable every day in every March</li>
19583 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
19584 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
19586 disabledDates : null,
19588 * @cfg {String} disabledDatesText
19589 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
19591 disabledDatesText : "Disabled",
19595 * @cfg {Date/String} zeroValue
19596 * if the date is less that this number, then the field is rendered as empty
19599 zeroValue : '1800-01-01',
19603 * @cfg {Date/String} minValue
19604 * The minimum allowed date. Can be either a Javascript date object or a string date in a
19605 * valid format (defaults to null).
19609 * @cfg {Date/String} maxValue
19610 * The maximum allowed date. Can be either a Javascript date object or a string date in a
19611 * valid format (defaults to null).
19615 * @cfg {String} minText
19616 * The error text to display when the date in the cell is before minValue (defaults to
19617 * 'The date in this field must be after {minValue}').
19619 minText : "The date in this field must be equal to or after {0}",
19621 * @cfg {String} maxText
19622 * The error text to display when the date in the cell is after maxValue (defaults to
19623 * 'The date in this field must be before {maxValue}').
19625 maxText : "The date in this field must be equal to or before {0}",
19627 * @cfg {String} invalidText
19628 * The error text to display when the date in the field is invalid (defaults to
19629 * '{value} is not a valid date - it must be in the format {format}').
19631 invalidText : "{0} is not a valid date - it must be in the format {1}",
19633 * @cfg {String} triggerClass
19634 * An additional CSS class used to style the trigger button. The trigger will always get the
19635 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
19636 * which displays a calendar icon).
19638 triggerClass : 'x-form-date-trigger',
19642 * @cfg {Boolean} useIso
19643 * if enabled, then the date field will use a hidden field to store the
19644 * real value as iso formated date. default (false)
19648 * @cfg {String/Object} autoCreate
19649 * A DomHelper element spec, or true for a default element spec (defaults to
19650 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
19653 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
19656 hiddenField: false,
19658 onRender : function(ct, position)
19660 Roo.form.DateField.superclass.onRender.call(this, ct, position);
19662 //this.el.dom.removeAttribute('name');
19663 Roo.log("Changing name?");
19664 this.el.dom.setAttribute('name', this.name + '____hidden___' );
19665 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
19667 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
19668 // prevent input submission
19669 this.hiddenName = this.name;
19676 validateValue : function(value)
19678 value = this.formatDate(value);
19679 if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
19680 Roo.log('super failed');
19683 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
19686 var svalue = value;
19687 value = this.parseDate(value);
19689 Roo.log('parse date failed' + svalue);
19690 this.markInvalid(String.format(this.invalidText, svalue, this.format));
19693 var time = value.getTime();
19694 if(this.minValue && time < this.minValue.getTime()){
19695 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
19698 if(this.maxValue && time > this.maxValue.getTime()){
19699 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
19702 if(this.disabledDays){
19703 var day = value.getDay();
19704 for(var i = 0; i < this.disabledDays.length; i++) {
19705 if(day === this.disabledDays[i]){
19706 this.markInvalid(this.disabledDaysText);
19711 var fvalue = this.formatDate(value);
19712 if(this.ddMatch && this.ddMatch.test(fvalue)){
19713 this.markInvalid(String.format(this.disabledDatesText, fvalue));
19720 // Provides logic to override the default TriggerField.validateBlur which just returns true
19721 validateBlur : function(){
19722 return !this.menu || !this.menu.isVisible();
19725 getName: function()
19727 // returns hidden if it's set..
19728 if (!this.rendered) {return ''};
19729 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
19734 * Returns the current date value of the date field.
19735 * @return {Date} The date value
19737 getValue : function(){
19739 return this.hiddenField ?
19740 this.hiddenField.value :
19741 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
19745 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
19746 * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
19747 * (the default format used is "m/d/y").
19750 //All of these calls set the same date value (May 4, 2006)
19752 //Pass a date object:
19753 var dt = new Date('5/4/06');
19754 dateField.setValue(dt);
19756 //Pass a date string (default format):
19757 dateField.setValue('5/4/06');
19759 //Pass a date string (custom format):
19760 dateField.format = 'Y-m-d';
19761 dateField.setValue('2006-5-4');
19763 * @param {String/Date} date The date or valid date string
19765 setValue : function(date){
19766 if (this.hiddenField) {
19767 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
19769 Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
19770 // make sure the value field is always stored as a date..
19771 this.value = this.parseDate(date);
19777 parseDate : function(value){
19779 if (value instanceof Date) {
19780 if (value < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
19787 if(!value || value instanceof Date){
19790 var v = Date.parseDate(value, this.format);
19791 if (!v && this.useIso) {
19792 v = Date.parseDate(value, 'Y-m-d');
19794 if(!v && this.altFormats){
19795 if(!this.altFormatsArray){
19796 this.altFormatsArray = this.altFormats.split("|");
19798 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
19799 v = Date.parseDate(value, this.altFormatsArray[i]);
19802 if (v < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
19809 formatDate : function(date, fmt){
19810 return (!date || !(date instanceof Date)) ?
19811 date : date.dateFormat(fmt || this.format);
19816 select: function(m, d){
19819 this.fireEvent('select', this, d);
19821 show : function(){ // retain focus styling
19825 this.focus.defer(10, this);
19826 var ml = this.menuListeners;
19827 this.menu.un("select", ml.select, this);
19828 this.menu.un("show", ml.show, this);
19829 this.menu.un("hide", ml.hide, this);
19834 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
19835 onTriggerClick : function(){
19836 if(this.disabled || this.readOnly){
19839 if(this.menu == null){
19840 this.menu = new Roo.menu.DateMenu();
19842 Roo.apply(this.menu.picker, {
19843 showClear: this.allowBlank,
19844 minDate : this.minValue,
19845 maxDate : this.maxValue,
19846 disabledDatesRE : this.ddMatch,
19847 disabledDatesText : this.disabledDatesText,
19848 disabledDays : this.disabledDays,
19849 disabledDaysText : this.disabledDaysText,
19850 format : this.useIso ? 'Y-m-d' : this.format,
19851 minText : String.format(this.minText, this.formatDate(this.minValue)),
19852 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
19854 this.menu.on(Roo.apply({}, this.menuListeners, {
19857 this.menu.picker.setValue(this.getValue() || new Date());
19858 this.menu.show(this.el, "tl-bl?");
19861 beforeBlur : function(){
19862 var v = this.parseDate(this.getRawValue());
19872 isDirty : function() {
19873 if(this.disabled) {
19877 if(typeof(this.startValue) === 'undefined'){
19881 return String(this.getValue()) !== String(this.startValue);
19885 cleanLeadingSpace : function(e)
19892 * Ext JS Library 1.1.1
19893 * Copyright(c) 2006-2007, Ext JS, LLC.
19895 * Originally Released Under LGPL - original licence link has changed is not relivant.
19898 * <script type="text/javascript">
19902 * @class Roo.form.MonthField
19903 * @extends Roo.form.TriggerField
19904 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
19906 * Create a new MonthField
19907 * @param {Object} config
19909 Roo.form.MonthField = function(config){
19911 Roo.form.MonthField.superclass.constructor.call(this, config);
19917 * Fires when a date is selected
19918 * @param {Roo.form.MonthFieeld} combo This combo box
19919 * @param {Date} date The date selected
19926 if(typeof this.minValue == "string") {
19927 this.minValue = this.parseDate(this.minValue);
19929 if(typeof this.maxValue == "string") {
19930 this.maxValue = this.parseDate(this.maxValue);
19932 this.ddMatch = null;
19933 if(this.disabledDates){
19934 var dd = this.disabledDates;
19936 for(var i = 0; i < dd.length; i++){
19938 if(i != dd.length-1) {
19942 this.ddMatch = new RegExp(re + ")");
19946 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField, {
19948 * @cfg {String} format
19949 * The default date format string which can be overriden for localization support. The format must be
19950 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
19954 * @cfg {String} altFormats
19955 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
19956 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
19958 altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
19960 * @cfg {Array} disabledDays
19961 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
19963 disabledDays : [0,1,2,3,4,5,6],
19965 * @cfg {String} disabledDaysText
19966 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
19968 disabledDaysText : "Disabled",
19970 * @cfg {Array} disabledDates
19971 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
19972 * expression so they are very powerful. Some examples:
19974 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
19975 * <li>["03/08", "09/16"] would disable those days for every year</li>
19976 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
19977 * <li>["03/../2006"] would disable every day in March 2006</li>
19978 * <li>["^03"] would disable every day in every March</li>
19980 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
19981 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
19983 disabledDates : null,
19985 * @cfg {String} disabledDatesText
19986 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
19988 disabledDatesText : "Disabled",
19990 * @cfg {Date/String} minValue
19991 * The minimum allowed date. Can be either a Javascript date object or a string date in a
19992 * valid format (defaults to null).
19996 * @cfg {Date/String} maxValue
19997 * The maximum allowed date. Can be either a Javascript date object or a string date in a
19998 * valid format (defaults to null).
20002 * @cfg {String} minText
20003 * The error text to display when the date in the cell is before minValue (defaults to
20004 * 'The date in this field must be after {minValue}').
20006 minText : "The date in this field must be equal to or after {0}",
20008 * @cfg {String} maxTextf
20009 * The error text to display when the date in the cell is after maxValue (defaults to
20010 * 'The date in this field must be before {maxValue}').
20012 maxText : "The date in this field must be equal to or before {0}",
20014 * @cfg {String} invalidText
20015 * The error text to display when the date in the field is invalid (defaults to
20016 * '{value} is not a valid date - it must be in the format {format}').
20018 invalidText : "{0} is not a valid date - it must be in the format {1}",
20020 * @cfg {String} triggerClass
20021 * An additional CSS class used to style the trigger button. The trigger will always get the
20022 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
20023 * which displays a calendar icon).
20025 triggerClass : 'x-form-date-trigger',
20029 * @cfg {Boolean} useIso
20030 * if enabled, then the date field will use a hidden field to store the
20031 * real value as iso formated date. default (true)
20035 * @cfg {String/Object} autoCreate
20036 * A DomHelper element spec, or true for a default element spec (defaults to
20037 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
20040 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
20043 hiddenField: false,
20045 hideMonthPicker : false,
20047 onRender : function(ct, position)
20049 Roo.form.MonthField.superclass.onRender.call(this, ct, position);
20051 this.el.dom.removeAttribute('name');
20052 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
20054 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
20055 // prevent input submission
20056 this.hiddenName = this.name;
20063 validateValue : function(value)
20065 value = this.formatDate(value);
20066 if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
20069 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
20072 var svalue = value;
20073 value = this.parseDate(value);
20075 this.markInvalid(String.format(this.invalidText, svalue, this.format));
20078 var time = value.getTime();
20079 if(this.minValue && time < this.minValue.getTime()){
20080 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
20083 if(this.maxValue && time > this.maxValue.getTime()){
20084 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
20087 /*if(this.disabledDays){
20088 var day = value.getDay();
20089 for(var i = 0; i < this.disabledDays.length; i++) {
20090 if(day === this.disabledDays[i]){
20091 this.markInvalid(this.disabledDaysText);
20097 var fvalue = this.formatDate(value);
20098 /*if(this.ddMatch && this.ddMatch.test(fvalue)){
20099 this.markInvalid(String.format(this.disabledDatesText, fvalue));
20107 // Provides logic to override the default TriggerField.validateBlur which just returns true
20108 validateBlur : function(){
20109 return !this.menu || !this.menu.isVisible();
20113 * Returns the current date value of the date field.
20114 * @return {Date} The date value
20116 getValue : function(){
20120 return this.hiddenField ?
20121 this.hiddenField.value :
20122 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
20126 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
20127 * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
20128 * (the default format used is "m/d/y").
20131 //All of these calls set the same date value (May 4, 2006)
20133 //Pass a date object:
20134 var dt = new Date('5/4/06');
20135 monthField.setValue(dt);
20137 //Pass a date string (default format):
20138 monthField.setValue('5/4/06');
20140 //Pass a date string (custom format):
20141 monthField.format = 'Y-m-d';
20142 monthField.setValue('2006-5-4');
20144 * @param {String/Date} date The date or valid date string
20146 setValue : function(date){
20147 Roo.log('month setValue' + date);
20148 // can only be first of month..
20150 var val = this.parseDate(date);
20152 if (this.hiddenField) {
20153 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
20155 Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
20156 this.value = this.parseDate(date);
20160 parseDate : function(value){
20161 if(!value || value instanceof Date){
20162 value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
20165 var v = Date.parseDate(value, this.format);
20166 if (!v && this.useIso) {
20167 v = Date.parseDate(value, 'Y-m-d');
20171 v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
20175 if(!v && this.altFormats){
20176 if(!this.altFormatsArray){
20177 this.altFormatsArray = this.altFormats.split("|");
20179 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
20180 v = Date.parseDate(value, this.altFormatsArray[i]);
20187 formatDate : function(date, fmt){
20188 return (!date || !(date instanceof Date)) ?
20189 date : date.dateFormat(fmt || this.format);
20194 select: function(m, d){
20196 this.fireEvent('select', this, d);
20198 show : function(){ // retain focus styling
20202 this.focus.defer(10, this);
20203 var ml = this.menuListeners;
20204 this.menu.un("select", ml.select, this);
20205 this.menu.un("show", ml.show, this);
20206 this.menu.un("hide", ml.hide, this);
20210 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
20211 onTriggerClick : function(){
20215 if(this.menu == null){
20216 this.menu = new Roo.menu.DateMenu();
20220 Roo.apply(this.menu.picker, {
20222 showClear: this.allowBlank,
20223 minDate : this.minValue,
20224 maxDate : this.maxValue,
20225 disabledDatesRE : this.ddMatch,
20226 disabledDatesText : this.disabledDatesText,
20228 format : this.useIso ? 'Y-m-d' : this.format,
20229 minText : String.format(this.minText, this.formatDate(this.minValue)),
20230 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
20233 this.menu.on(Roo.apply({}, this.menuListeners, {
20241 // hide month picker get's called when we called by 'before hide';
20243 var ignorehide = true;
20244 p.hideMonthPicker = function(disableAnim){
20248 if(this.monthPicker){
20249 Roo.log("hideMonthPicker called");
20250 if(disableAnim === true){
20251 this.monthPicker.hide();
20253 this.monthPicker.slideOut('t', {duration:.2});
20254 p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
20255 p.fireEvent("select", this, this.value);
20261 Roo.log('picker set value');
20262 Roo.log(this.getValue());
20263 p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
20264 m.show(this.el, 'tl-bl?');
20265 ignorehide = false;
20266 // this will trigger hideMonthPicker..
20269 // hidden the day picker
20270 Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
20276 p.showMonthPicker.defer(100, p);
20282 beforeBlur : function(){
20283 var v = this.parseDate(this.getRawValue());
20289 /** @cfg {Boolean} grow @hide */
20290 /** @cfg {Number} growMin @hide */
20291 /** @cfg {Number} growMax @hide */
20298 * Ext JS Library 1.1.1
20299 * Copyright(c) 2006-2007, Ext JS, LLC.
20301 * Originally Released Under LGPL - original licence link has changed is not relivant.
20304 * <script type="text/javascript">
20309 * @class Roo.form.ComboBox
20310 * @extends Roo.form.TriggerField
20311 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
20313 * Create a new ComboBox.
20314 * @param {Object} config Configuration options
20316 Roo.form.ComboBox = function(config){
20317 Roo.form.ComboBox.superclass.constructor.call(this, config);
20321 * Fires when the dropdown list is expanded
20322 * @param {Roo.form.ComboBox} combo This combo box
20327 * Fires when the dropdown list is collapsed
20328 * @param {Roo.form.ComboBox} combo This combo box
20332 * @event beforeselect
20333 * Fires before a list item is selected. Return false to cancel the selection.
20334 * @param {Roo.form.ComboBox} combo This combo box
20335 * @param {Roo.data.Record} record The data record returned from the underlying store
20336 * @param {Number} index The index of the selected item in the dropdown list
20338 'beforeselect' : true,
20341 * Fires when a list item is selected
20342 * @param {Roo.form.ComboBox} combo This combo box
20343 * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
20344 * @param {Number} index The index of the selected item in the dropdown list
20348 * @event beforequery
20349 * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
20350 * The event object passed has these properties:
20351 * @param {Roo.form.ComboBox} combo This combo box
20352 * @param {String} query The query
20353 * @param {Boolean} forceAll true to force "all" query
20354 * @param {Boolean} cancel true to cancel the query
20355 * @param {Object} e The query event object
20357 'beforequery': true,
20360 * Fires when the 'add' icon is pressed (add a listener to enable add button)
20361 * @param {Roo.form.ComboBox} combo This combo box
20366 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
20367 * @param {Roo.form.ComboBox} combo This combo box
20368 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
20374 if(this.transform){
20375 this.allowDomMove = false;
20376 var s = Roo.getDom(this.transform);
20377 if(!this.hiddenName){
20378 this.hiddenName = s.name;
20381 this.mode = 'local';
20382 var d = [], opts = s.options;
20383 for(var i = 0, len = opts.length;i < len; i++){
20385 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
20387 this.value = value;
20389 d.push([value, o.text]);
20391 this.store = new Roo.data.SimpleStore({
20393 fields: ['value', 'text'],
20396 this.valueField = 'value';
20397 this.displayField = 'text';
20399 s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
20400 if(!this.lazyRender){
20401 this.target = true;
20402 this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
20403 s.parentNode.removeChild(s); // remove it
20404 this.render(this.el.parentNode);
20406 s.parentNode.removeChild(s); // remove it
20411 this.store = Roo.factory(this.store, Roo.data);
20414 this.selectedIndex = -1;
20415 if(this.mode == 'local'){
20416 if(config.queryDelay === undefined){
20417 this.queryDelay = 10;
20419 if(config.minChars === undefined){
20425 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
20427 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
20430 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
20431 * rendering into an Roo.Editor, defaults to false)
20434 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
20435 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
20438 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
20441 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
20442 * the dropdown list (defaults to undefined, with no header element)
20446 * @cfg {String/Roo.Template} tpl The template to use to render the output
20450 defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
20452 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
20454 listWidth: undefined,
20456 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
20457 * mode = 'remote' or 'text' if mode = 'local')
20459 displayField: undefined,
20461 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
20462 * mode = 'remote' or 'value' if mode = 'local').
20463 * Note: use of a valueField requires the user make a selection
20464 * in order for a value to be mapped.
20466 valueField: undefined,
20470 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
20471 * field's data value (defaults to the underlying DOM element's name)
20473 hiddenName: undefined,
20475 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
20479 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
20481 selectedClass: 'x-combo-selected',
20483 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
20484 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
20485 * which displays a downward arrow icon).
20487 triggerClass : 'x-form-arrow-trigger',
20489 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
20493 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
20494 * anchor positions (defaults to 'tl-bl')
20496 listAlign: 'tl-bl?',
20498 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
20502 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
20503 * query specified by the allQuery config option (defaults to 'query')
20505 triggerAction: 'query',
20507 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
20508 * (defaults to 4, does not apply if editable = false)
20512 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
20513 * delay (typeAheadDelay) if it matches a known value (defaults to false)
20517 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
20518 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
20522 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
20523 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
20527 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
20528 * when editable = true (defaults to false)
20530 selectOnFocus:false,
20532 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
20534 queryParam: 'query',
20536 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
20537 * when mode = 'remote' (defaults to 'Loading...')
20539 loadingText: 'Loading...',
20541 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
20545 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
20549 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
20550 * traditional select (defaults to true)
20554 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
20558 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
20562 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
20563 * listWidth has a higher value)
20567 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
20568 * allow the user to set arbitrary text into the field (defaults to false)
20570 forceSelection:false,
20572 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
20573 * if typeAhead = true (defaults to 250)
20575 typeAheadDelay : 250,
20577 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
20578 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
20580 valueNotFoundText : undefined,
20582 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
20584 blockFocus : false,
20587 * @cfg {Boolean} disableClear Disable showing of clear button.
20589 disableClear : false,
20591 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
20593 alwaysQuery : false,
20599 // element that contains real text value.. (when hidden is used..)
20602 onRender : function(ct, position)
20604 Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
20606 if(this.hiddenName){
20607 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
20609 this.hiddenField.value =
20610 this.hiddenValue !== undefined ? this.hiddenValue :
20611 this.value !== undefined ? this.value : '';
20613 // prevent input submission
20614 this.el.dom.removeAttribute('name');
20620 this.el.dom.setAttribute('autocomplete', 'off');
20623 var cls = 'x-combo-list';
20625 this.list = new Roo.Layer({
20626 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
20629 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
20630 this.list.setWidth(lw);
20631 this.list.swallowEvent('mousewheel');
20632 this.assetHeight = 0;
20635 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
20636 this.assetHeight += this.header.getHeight();
20639 this.innerList = this.list.createChild({cls:cls+'-inner'});
20640 this.innerList.on('mouseover', this.onViewOver, this);
20641 this.innerList.on('mousemove', this.onViewMove, this);
20642 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
20644 if(this.allowBlank && !this.pageSize && !this.disableClear){
20645 this.footer = this.list.createChild({cls:cls+'-ft'});
20646 this.pageTb = new Roo.Toolbar(this.footer);
20650 this.footer = this.list.createChild({cls:cls+'-ft'});
20651 this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
20652 {pageSize: this.pageSize});
20656 if (this.pageTb && this.allowBlank && !this.disableClear) {
20658 this.pageTb.add(new Roo.Toolbar.Fill(), {
20659 cls: 'x-btn-icon x-btn-clear',
20661 handler: function()
20664 _this.clearValue();
20665 _this.onSelect(false, -1);
20670 this.assetHeight += this.footer.getHeight();
20675 this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
20678 this.view = new Roo.View(this.innerList, this.tpl, {
20681 selectedClass: this.selectedClass
20684 this.view.on('click', this.onViewClick, this);
20686 this.store.on('beforeload', this.onBeforeLoad, this);
20687 this.store.on('load', this.onLoad, this);
20688 this.store.on('loadexception', this.onLoadException, this);
20690 if(this.resizable){
20691 this.resizer = new Roo.Resizable(this.list, {
20692 pinned:true, handles:'se'
20694 this.resizer.on('resize', function(r, w, h){
20695 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
20696 this.listWidth = w;
20697 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
20698 this.restrictHeight();
20700 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
20702 if(!this.editable){
20703 this.editable = true;
20704 this.setEditable(false);
20708 if (typeof(this.events.add.listeners) != 'undefined') {
20710 this.addicon = this.wrap.createChild(
20711 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });
20713 this.addicon.on('click', function(e) {
20714 this.fireEvent('add', this);
20717 if (typeof(this.events.edit.listeners) != 'undefined') {
20719 this.editicon = this.wrap.createChild(
20720 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });
20721 if (this.addicon) {
20722 this.editicon.setStyle('margin-left', '40px');
20724 this.editicon.on('click', function(e) {
20726 // we fire even if inothing is selected..
20727 this.fireEvent('edit', this, this.lastData );
20737 initEvents : function(){
20738 Roo.form.ComboBox.superclass.initEvents.call(this);
20740 this.keyNav = new Roo.KeyNav(this.el, {
20741 "up" : function(e){
20742 this.inKeyMode = true;
20746 "down" : function(e){
20747 if(!this.isExpanded()){
20748 this.onTriggerClick();
20750 this.inKeyMode = true;
20755 "enter" : function(e){
20756 this.onViewClick();
20760 "esc" : function(e){
20764 "tab" : function(e){
20765 this.onViewClick(false);
20766 this.fireEvent("specialkey", this, e);
20772 doRelay : function(foo, bar, hname){
20773 if(hname == 'down' || this.scope.isExpanded()){
20774 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
20781 this.queryDelay = Math.max(this.queryDelay || 10,
20782 this.mode == 'local' ? 10 : 250);
20783 this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
20784 if(this.typeAhead){
20785 this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
20787 if(this.editable !== false){
20788 this.el.on("keyup", this.onKeyUp, this);
20790 if(this.forceSelection){
20791 this.on('blur', this.doForce, this);
20795 onDestroy : function(){
20797 this.view.setStore(null);
20798 this.view.el.removeAllListeners();
20799 this.view.el.remove();
20800 this.view.purgeListeners();
20803 this.list.destroy();
20806 this.store.un('beforeload', this.onBeforeLoad, this);
20807 this.store.un('load', this.onLoad, this);
20808 this.store.un('loadexception', this.onLoadException, this);
20810 Roo.form.ComboBox.superclass.onDestroy.call(this);
20814 fireKey : function(e){
20815 if(e.isNavKeyPress() && !this.list.isVisible()){
20816 this.fireEvent("specialkey", this, e);
20821 onResize: function(w, h){
20822 Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
20824 if(typeof w != 'number'){
20825 // we do not handle it!?!?
20828 var tw = this.trigger.getWidth();
20829 tw += this.addicon ? this.addicon.getWidth() : 0;
20830 tw += this.editicon ? this.editicon.getWidth() : 0;
20832 this.el.setWidth( this.adjustWidth('input', x));
20834 this.trigger.setStyle('left', x+'px');
20836 if(this.list && this.listWidth === undefined){
20837 var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
20838 this.list.setWidth(lw);
20839 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
20847 * Allow or prevent the user from directly editing the field text. If false is passed,
20848 * the user will only be able to select from the items defined in the dropdown list. This method
20849 * is the runtime equivalent of setting the 'editable' config option at config time.
20850 * @param {Boolean} value True to allow the user to directly edit the field text
20852 setEditable : function(value){
20853 if(value == this.editable){
20856 this.editable = value;
20858 this.el.dom.setAttribute('readOnly', true);
20859 this.el.on('mousedown', this.onTriggerClick, this);
20860 this.el.addClass('x-combo-noedit');
20862 this.el.dom.setAttribute('readOnly', false);
20863 this.el.un('mousedown', this.onTriggerClick, this);
20864 this.el.removeClass('x-combo-noedit');
20869 onBeforeLoad : function(){
20870 if(!this.hasFocus){
20873 this.innerList.update(this.loadingText ?
20874 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
20875 this.restrictHeight();
20876 this.selectedIndex = -1;
20880 onLoad : function(){
20881 if(!this.hasFocus){
20884 if(this.store.getCount() > 0){
20886 this.restrictHeight();
20887 if(this.lastQuery == this.allQuery){
20889 this.el.dom.select();
20891 if(!this.selectByValue(this.value, true)){
20892 this.select(0, true);
20896 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
20897 this.taTask.delay(this.typeAheadDelay);
20901 this.onEmptyResults();
20906 onLoadException : function()
20909 Roo.log(this.store.reader.jsonData);
20910 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
20911 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
20917 onTypeAhead : function(){
20918 if(this.store.getCount() > 0){
20919 var r = this.store.getAt(0);
20920 var newValue = r.data[this.displayField];
20921 var len = newValue.length;
20922 var selStart = this.getRawValue().length;
20923 if(selStart != len){
20924 this.setRawValue(newValue);
20925 this.selectText(selStart, newValue.length);
20931 onSelect : function(record, index){
20932 if(this.fireEvent('beforeselect', this, record, index) !== false){
20933 this.setFromData(index > -1 ? record.data : false);
20935 this.fireEvent('select', this, record, index);
20940 * Returns the currently selected field value or empty string if no value is set.
20941 * @return {String} value The selected value
20943 getValue : function(){
20944 if(this.valueField){
20945 return typeof this.value != 'undefined' ? this.value : '';
20947 return Roo.form.ComboBox.superclass.getValue.call(this);
20951 * Clears any text/value currently set in the field
20953 clearValue : function(){
20954 if(this.hiddenField){
20955 this.hiddenField.value = '';
20958 this.setRawValue('');
20959 this.lastSelectionText = '';
20964 * Sets the specified value into the field. If the value finds a match, the corresponding record text
20965 * will be displayed in the field. If the value does not match the data value of an existing item,
20966 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
20967 * Otherwise the field will be blank (although the value will still be set).
20968 * @param {String} value The value to match
20970 setValue : function(v){
20972 if(this.valueField){
20973 var r = this.findRecord(this.valueField, v);
20975 text = r.data[this.displayField];
20976 }else if(this.valueNotFoundText !== undefined){
20977 text = this.valueNotFoundText;
20980 this.lastSelectionText = text;
20981 if(this.hiddenField){
20982 this.hiddenField.value = v;
20984 Roo.form.ComboBox.superclass.setValue.call(this, text);
20988 * @property {Object} the last set data for the element
20993 * Sets the value of the field based on a object which is related to the record format for the store.
20994 * @param {Object} value the value to set as. or false on reset?
20996 setFromData : function(o){
20997 var dv = ''; // display value
20998 var vv = ''; // value value..
21000 if (this.displayField) {
21001 dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
21003 // this is an error condition!!!
21004 Roo.log('no displayField value set for '+ (this.name ? this.name : this.id));
21007 if(this.valueField){
21008 vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
21010 if(this.hiddenField){
21011 this.hiddenField.value = vv;
21013 this.lastSelectionText = dv;
21014 Roo.form.ComboBox.superclass.setValue.call(this, dv);
21018 // no hidden field.. - we store the value in 'value', but still display
21019 // display field!!!!
21020 this.lastSelectionText = dv;
21021 Roo.form.ComboBox.superclass.setValue.call(this, dv);
21027 reset : function(){
21028 // overridden so that last data is reset..
21029 this.setValue(this.resetValue);
21030 this.originalValue = this.getValue();
21031 this.clearInvalid();
21032 this.lastData = false;
21034 this.view.clearSelections();
21038 findRecord : function(prop, value){
21040 if(this.store.getCount() > 0){
21041 this.store.each(function(r){
21042 if(r.data[prop] == value){
21052 getName: function()
21054 // returns hidden if it's set..
21055 if (!this.rendered) {return ''};
21056 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
21060 onViewMove : function(e, t){
21061 this.inKeyMode = false;
21065 onViewOver : function(e, t){
21066 if(this.inKeyMode){ // prevent key nav and mouse over conflicts
21069 var item = this.view.findItemFromChild(t);
21071 var index = this.view.indexOf(item);
21072 this.select(index, false);
21077 onViewClick : function(doFocus)
21079 var index = this.view.getSelectedIndexes()[0];
21080 var r = this.store.getAt(index);
21082 this.onSelect(r, index);
21084 if(doFocus !== false && !this.blockFocus){
21090 restrictHeight : function(){
21091 this.innerList.dom.style.height = '';
21092 var inner = this.innerList.dom;
21093 var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
21094 this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
21095 this.list.beginUpdate();
21096 this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
21097 this.list.alignTo(this.el, this.listAlign);
21098 this.list.endUpdate();
21102 onEmptyResults : function(){
21107 * Returns true if the dropdown list is expanded, else false.
21109 isExpanded : function(){
21110 return this.list.isVisible();
21114 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
21115 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
21116 * @param {String} value The data value of the item to select
21117 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
21118 * selected item if it is not currently in view (defaults to true)
21119 * @return {Boolean} True if the value matched an item in the list, else false
21121 selectByValue : function(v, scrollIntoView){
21122 if(v !== undefined && v !== null){
21123 var r = this.findRecord(this.valueField || this.displayField, v);
21125 this.select(this.store.indexOf(r), scrollIntoView);
21133 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
21134 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
21135 * @param {Number} index The zero-based index of the list item to select
21136 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
21137 * selected item if it is not currently in view (defaults to true)
21139 select : function(index, scrollIntoView){
21140 this.selectedIndex = index;
21141 this.view.select(index);
21142 if(scrollIntoView !== false){
21143 var el = this.view.getNode(index);
21145 this.innerList.scrollChildIntoView(el, false);
21151 selectNext : function(){
21152 var ct = this.store.getCount();
21154 if(this.selectedIndex == -1){
21156 }else if(this.selectedIndex < ct-1){
21157 this.select(this.selectedIndex+1);
21163 selectPrev : function(){
21164 var ct = this.store.getCount();
21166 if(this.selectedIndex == -1){
21168 }else if(this.selectedIndex != 0){
21169 this.select(this.selectedIndex-1);
21175 onKeyUp : function(e){
21176 if(this.editable !== false && !e.isSpecialKey()){
21177 this.lastKey = e.getKey();
21178 this.dqTask.delay(this.queryDelay);
21183 validateBlur : function(){
21184 return !this.list || !this.list.isVisible();
21188 initQuery : function(){
21189 this.doQuery(this.getRawValue());
21193 doForce : function(){
21194 if(this.el.dom.value.length > 0){
21195 this.el.dom.value =
21196 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
21202 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
21203 * query allowing the query action to be canceled if needed.
21204 * @param {String} query The SQL query to execute
21205 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
21206 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
21207 * saved in the current store (defaults to false)
21209 doQuery : function(q, forceAll){
21210 if(q === undefined || q === null){
21215 forceAll: forceAll,
21219 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
21223 forceAll = qe.forceAll;
21224 if(forceAll === true || (q.length >= this.minChars)){
21225 if(this.lastQuery != q || this.alwaysQuery){
21226 this.lastQuery = q;
21227 if(this.mode == 'local'){
21228 this.selectedIndex = -1;
21230 this.store.clearFilter();
21232 this.store.filter(this.displayField, q);
21236 this.store.baseParams[this.queryParam] = q;
21238 params: this.getParams(q)
21243 this.selectedIndex = -1;
21250 getParams : function(q){
21252 //p[this.queryParam] = q;
21255 p.limit = this.pageSize;
21261 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
21263 collapse : function(){
21264 if(!this.isExpanded()){
21268 Roo.get(document).un('mousedown', this.collapseIf, this);
21269 Roo.get(document).un('mousewheel', this.collapseIf, this);
21270 if (!this.editable) {
21271 Roo.get(document).un('keydown', this.listKeyPress, this);
21273 this.fireEvent('collapse', this);
21277 collapseIf : function(e){
21278 if(!e.within(this.wrap) && !e.within(this.list)){
21284 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
21286 expand : function(){
21287 if(this.isExpanded() || !this.hasFocus){
21290 this.list.alignTo(this.el, this.listAlign);
21292 Roo.get(document).on('mousedown', this.collapseIf, this);
21293 Roo.get(document).on('mousewheel', this.collapseIf, this);
21294 if (!this.editable) {
21295 Roo.get(document).on('keydown', this.listKeyPress, this);
21298 this.fireEvent('expand', this);
21302 // Implements the default empty TriggerField.onTriggerClick function
21303 onTriggerClick : function(){
21307 if(this.isExpanded()){
21309 if (!this.blockFocus) {
21314 this.hasFocus = true;
21315 if(this.triggerAction == 'all') {
21316 this.doQuery(this.allQuery, true);
21318 this.doQuery(this.getRawValue());
21320 if (!this.blockFocus) {
21325 listKeyPress : function(e)
21327 //Roo.log('listkeypress');
21328 // scroll to first matching element based on key pres..
21329 if (e.isSpecialKey()) {
21332 var k = String.fromCharCode(e.getKey()).toUpperCase();
21335 var csel = this.view.getSelectedNodes();
21336 var cselitem = false;
21338 var ix = this.view.indexOf(csel[0]);
21339 cselitem = this.store.getAt(ix);
21340 if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
21346 this.store.each(function(v) {
21348 // start at existing selection.
21349 if (cselitem.id == v.id) {
21355 if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
21356 match = this.store.indexOf(v);
21361 if (match === false) {
21362 return true; // no more action?
21365 this.view.select(match);
21366 var sn = Roo.get(this.view.getSelectedNodes()[0]);
21367 sn.scrollIntoView(sn.dom.parentNode, false);
21369 cleanLeadingSpace : function()
21371 // override textfield strip white space (trigers set on blur)
21375 * @cfg {Boolean} grow
21379 * @cfg {Number} growMin
21383 * @cfg {Number} growMax
21391 * Copyright(c) 2010-2012, Roo J Solutions Limited
21398 * @class Roo.form.ComboBoxArray
21399 * @extends Roo.form.TextField
21400 * A facebook style adder... for lists of email / people / countries etc...
21401 * pick multiple items from a combo box, and shows each one.
21403 * Fred [x] Brian [x] [Pick another |v]
21406 * For this to work: it needs various extra information
21407 * - normal combo problay has
21409 * + displayField, valueField
21411 * For our purpose...
21414 * If we change from 'extends' to wrapping...
21421 * Create a new ComboBoxArray.
21422 * @param {Object} config Configuration options
21426 Roo.form.ComboBoxArray = function(config)
21430 * @event beforeremove
21431 * Fires before remove the value from the list
21432 * @param {Roo.form.ComboBoxArray} _self This combo box array
21433 * @param {Roo.form.ComboBoxArray.Item} item removed item
21435 'beforeremove' : true,
21438 * Fires when remove the value from the list
21439 * @param {Roo.form.ComboBoxArray} _self This combo box array
21440 * @param {Roo.form.ComboBoxArray.Item} item removed item
21447 Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
21449 this.items = new Roo.util.MixedCollection(false);
21451 // construct the child combo...
21461 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
21464 * @cfg {Roo.form.ComboBox} combo [required] The combo box that is wrapped
21469 // behavies liek a hiddne field
21470 inputType: 'hidden',
21472 * @cfg {Number} width The width of the box that displays the selected element
21479 * @cfg {String} name The name of the visable items on this form (eg. titles not ids)
21483 * @cfg {String} hiddenName The hidden name of the field, often contains an comma seperated list of names
21485 hiddenName : false,
21487 * @cfg {String} seperator The value seperator normally ','
21492 // private the array of items that are displayed..
21494 // private - the hidden field el.
21496 // private - the filed el..
21499 //validateValue : function() { return true; }, // all values are ok!
21500 //onAddClick: function() { },
21502 onRender : function(ct, position)
21505 // create the standard hidden element
21506 //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
21509 // give fake names to child combo;
21510 this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
21511 this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
21513 this.combo = Roo.factory(this.combo, Roo.form);
21514 this.combo.onRender(ct, position);
21515 if (typeof(this.combo.width) != 'undefined') {
21516 this.combo.onResize(this.combo.width,0);
21519 this.combo.initEvents();
21521 // assigned so form know we need to do this..
21522 this.store = this.combo.store;
21523 this.valueField = this.combo.valueField;
21524 this.displayField = this.combo.displayField ;
21527 this.combo.wrap.addClass('x-cbarray-grp');
21529 var cbwrap = this.combo.wrap.createChild(
21530 {tag: 'div', cls: 'x-cbarray-cb'},
21535 this.hiddenEl = this.combo.wrap.createChild({
21536 tag: 'input', type:'hidden' , name: this.hiddenName, value : ''
21538 this.el = this.combo.wrap.createChild({
21539 tag: 'input', type:'hidden' , name: this.name, value : ''
21541 // this.el.dom.removeAttribute("name");
21544 this.outerWrap = this.combo.wrap;
21545 this.wrap = cbwrap;
21547 this.outerWrap.setWidth(this.width);
21548 this.outerWrap.dom.removeChild(this.el.dom);
21550 this.wrap.dom.appendChild(this.el.dom);
21551 this.outerWrap.dom.removeChild(this.combo.trigger.dom);
21552 this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
21554 this.combo.trigger.setStyle('position','relative');
21555 this.combo.trigger.setStyle('left', '0px');
21556 this.combo.trigger.setStyle('top', '2px');
21558 this.combo.el.setStyle('vertical-align', 'text-bottom');
21560 //this.trigger.setStyle('vertical-align', 'top');
21562 // this should use the code from combo really... on('add' ....)
21566 this.adder = this.outerWrap.createChild(
21567 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});
21569 this.adder.on('click', function(e) {
21570 _t.fireEvent('adderclick', this, e);
21574 //this.adder.on('click', this.onAddClick, _t);
21577 this.combo.on('select', function(cb, rec, ix) {
21578 this.addItem(rec.data);
21581 cb.el.dom.value = '';
21582 //cb.lastData = rec.data;
21593 getName: function()
21595 // returns hidden if it's set..
21596 if (!this.rendered) {return ''};
21597 return this.hiddenName ? this.hiddenName : this.name;
21602 onResize: function(w, h){
21605 // not sure if this is needed..
21606 //this.combo.onResize(w,h);
21608 if(typeof w != 'number'){
21609 // we do not handle it!?!?
21612 var tw = this.combo.trigger.getWidth();
21613 tw += this.addicon ? this.addicon.getWidth() : 0;
21614 tw += this.editicon ? this.editicon.getWidth() : 0;
21616 this.combo.el.setWidth( this.combo.adjustWidth('input', x));
21618 this.combo.trigger.setStyle('left', '0px');
21620 if(this.list && this.listWidth === undefined){
21621 var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
21622 this.list.setWidth(lw);
21623 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
21630 addItem: function(rec)
21632 var valueField = this.combo.valueField;
21633 var displayField = this.combo.displayField;
21635 if (this.items.indexOfKey(rec[valueField]) > -1) {
21636 //console.log("GOT " + rec.data.id);
21640 var x = new Roo.form.ComboBoxArray.Item({
21641 //id : rec[this.idField],
21643 displayField : displayField ,
21644 tipField : displayField ,
21648 this.items.add(rec[valueField],x);
21649 // add it before the element..
21650 this.updateHiddenEl();
21651 x.render(this.outerWrap, this.wrap.dom);
21652 // add the image handler..
21655 updateHiddenEl : function()
21658 if (!this.hiddenEl) {
21662 var idField = this.combo.valueField;
21664 this.items.each(function(f) {
21665 ar.push(f.data[idField]);
21667 this.hiddenEl.dom.value = ar.join(this.seperator);
21673 this.items.clear();
21675 Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
21679 this.el.dom.value = '';
21680 if (this.hiddenEl) {
21681 this.hiddenEl.dom.value = '';
21685 getValue: function()
21687 return this.hiddenEl ? this.hiddenEl.dom.value : '';
21689 setValue: function(v) // not a valid action - must use addItems..
21694 if (this.store.isLocal && (typeof(v) == 'string')) {
21695 // then we can use the store to find the values..
21696 // comma seperated at present.. this needs to allow JSON based encoding..
21697 this.hiddenEl.value = v;
21699 Roo.each(v.split(this.seperator), function(k) {
21700 Roo.log("CHECK " + this.valueField + ',' + k);
21701 var li = this.store.query(this.valueField, k);
21706 add[this.valueField] = k;
21707 add[this.displayField] = li.item(0).data[this.displayField];
21713 if (typeof(v) == 'object' ) {
21714 // then let's assume it's an array of objects..
21715 Roo.each(v, function(l) {
21717 if (typeof(l) == 'string') {
21719 add[this.valueField] = l;
21720 add[this.displayField] = l
21729 setFromData: function(v)
21731 // this recieves an object, if setValues is called.
21733 this.el.dom.value = v[this.displayField];
21734 this.hiddenEl.dom.value = v[this.valueField];
21735 if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
21738 var kv = v[this.valueField];
21739 var dv = v[this.displayField];
21740 kv = typeof(kv) != 'string' ? '' : kv;
21741 dv = typeof(dv) != 'string' ? '' : dv;
21744 var keys = kv.split(this.seperator);
21745 var display = dv.split(this.seperator);
21746 for (var i = 0 ; i < keys.length; i++) {
21748 add[this.valueField] = keys[i];
21749 add[this.displayField] = display[i];
21757 * Validates the combox array value
21758 * @return {Boolean} True if the value is valid, else false
21760 validate : function(){
21761 if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
21762 this.clearInvalid();
21768 validateValue : function(value){
21769 return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
21777 isDirty : function() {
21778 if(this.disabled) {
21783 var d = Roo.decode(String(this.originalValue));
21785 return String(this.getValue()) !== String(this.originalValue);
21788 var originalValue = [];
21790 for (var i = 0; i < d.length; i++){
21791 originalValue.push(d[i][this.valueField]);
21794 return String(this.getValue()) !== String(originalValue.join(this.seperator));
21803 * @class Roo.form.ComboBoxArray.Item
21804 * @extends Roo.BoxComponent
21805 * A selected item in the list
21806 * Fred [x] Brian [x] [Pick another |v]
21809 * Create a new item.
21810 * @param {Object} config Configuration options
21813 Roo.form.ComboBoxArray.Item = function(config) {
21814 config.id = Roo.id();
21815 Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
21818 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
21821 displayField : false,
21825 defaultAutoCreate : {
21827 cls: 'x-cbarray-item',
21834 src : Roo.BLANK_IMAGE_URL ,
21842 onRender : function(ct, position)
21844 Roo.form.Field.superclass.onRender.call(this, ct, position);
21847 var cfg = this.getAutoCreate();
21848 this.el = ct.createChild(cfg, position);
21851 this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
21853 this.el.child('div').dom.innerHTML = this.cb.renderer ?
21854 this.cb.renderer(this.data) :
21855 String.format('{0}',this.data[this.displayField]);
21858 this.el.child('div').dom.setAttribute('qtip',
21859 String.format('{0}',this.data[this.tipField])
21862 this.el.child('img').on('click', this.remove, this);
21866 remove : function()
21868 if(this.cb.disabled){
21872 if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
21873 this.cb.items.remove(this);
21874 this.el.child('img').un('click', this.remove, this);
21876 this.cb.updateHiddenEl();
21878 this.cb.fireEvent('remove', this.cb, this);
21883 * RooJS Library 1.1.1
21884 * Copyright(c) 2008-2011 Alan Knowles
21891 * @class Roo.form.ComboNested
21892 * @extends Roo.form.ComboBox
21893 * A combobox for that allows selection of nested items in a list,
21908 * Create a new ComboNested
21909 * @param {Object} config Configuration options
21911 Roo.form.ComboNested = function(config){
21912 Roo.form.ComboCheck.superclass.constructor.call(this, config);
21913 // should verify some data...
21915 // hiddenName = required..
21916 // displayField = required
21917 // valudField == required
21918 var req= [ 'hiddenName', 'displayField', 'valueField' ];
21920 Roo.each(req, function(e) {
21921 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
21922 throw "Roo.form.ComboNested : missing value for: " + e;
21929 Roo.extend(Roo.form.ComboNested, Roo.form.ComboBox, {
21932 * @config {Number} max Number of columns to show
21937 list : null, // the outermost div..
21938 innerLists : null, // the
21942 loadingChildren : false,
21944 onRender : function(ct, position)
21946 Roo.form.ComboBox.superclass.onRender.call(this, ct, position); // skip parent call - got to above..
21948 if(this.hiddenName){
21949 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
21951 this.hiddenField.value =
21952 this.hiddenValue !== undefined ? this.hiddenValue :
21953 this.value !== undefined ? this.value : '';
21955 // prevent input submission
21956 this.el.dom.removeAttribute('name');
21962 this.el.dom.setAttribute('autocomplete', 'off');
21965 var cls = 'x-combo-list';
21967 this.list = new Roo.Layer({
21968 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
21971 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
21972 this.list.setWidth(lw);
21973 this.list.swallowEvent('mousewheel');
21974 this.assetHeight = 0;
21977 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
21978 this.assetHeight += this.header.getHeight();
21980 this.innerLists = [];
21983 for (var i =0 ; i < this.maxColumns; i++) {
21984 this.onRenderList( cls, i);
21987 // always needs footer, as we are going to have an 'OK' button.
21988 this.footer = this.list.createChild({cls:cls+'-ft'});
21989 this.pageTb = new Roo.Toolbar(this.footer);
21994 handler: function()
22000 if ( this.allowBlank && !this.disableClear) {
22002 this.pageTb.add(new Roo.Toolbar.Fill(), {
22003 cls: 'x-btn-icon x-btn-clear',
22005 handler: function()
22008 _this.clearValue();
22009 _this.onSelect(false, -1);
22014 this.assetHeight += this.footer.getHeight();
22018 onRenderList : function ( cls, i)
22021 var lw = Math.floor(
22022 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
22025 this.list.setWidth(lw); // default to '1'
22027 var il = this.innerLists[i] = this.list.createChild({cls:cls+'-inner'});
22028 //il.on('mouseover', this.onViewOver, this, { list: i });
22029 //il.on('mousemove', this.onViewMove, this, { list: i });
22031 il.setStyle({ 'overflow-x' : 'hidden'});
22034 this.tpl = new Roo.Template({
22035 html : '<div class="'+cls+'-item '+cls+'-item-{cn:this.isEmpty}">{' + this.displayField + '}</div>',
22036 isEmpty: function (value, allValues) {
22038 var dl = typeof(value.data) != 'undefined' ? value.data.length : value.length; ///json is a nested response..
22039 return dl ? 'has-children' : 'no-children'
22044 var store = this.store;
22046 store = new Roo.data.SimpleStore({
22047 //fields : this.store.reader.meta.fields,
22048 reader : this.store.reader,
22052 this.stores[i] = store;
22054 var view = this.views[i] = new Roo.View(
22060 selectedClass: this.selectedClass
22063 view.getEl().setWidth(lw);
22064 view.getEl().setStyle({
22065 position: i < 1 ? 'relative' : 'absolute',
22067 left: (i * lw ) + 'px',
22068 display : i > 0 ? 'none' : 'block'
22070 view.on('selectionchange', this.onSelectChange.createDelegate(this, {list : i }, true));
22071 view.on('dblclick', this.onDoubleClick.createDelegate(this, {list : i }, true));
22072 //view.on('click', this.onViewClick, this, { list : i });
22074 store.on('beforeload', this.onBeforeLoad, this);
22075 store.on('load', this.onLoad, this, { list : i});
22076 store.on('loadexception', this.onLoadException, this);
22078 // hide the other vies..
22084 restrictHeight : function()
22087 Roo.each(this.innerLists, function(il,i) {
22088 var el = this.views[i].getEl();
22089 el.dom.style.height = '';
22090 var inner = el.dom;
22091 var h = Math.max(il.clientHeight, il.offsetHeight, il.scrollHeight);
22092 // only adjust heights on other ones..
22093 mh = Math.max(h, mh);
22096 el.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
22097 il.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
22104 this.list.beginUpdate();
22105 this.list.setHeight(mh+this.list.getFrameWidth('tb')+this.assetHeight);
22106 this.list.alignTo(this.el, this.listAlign);
22107 this.list.endUpdate();
22112 // -- store handlers..
22114 onBeforeLoad : function()
22116 if(!this.hasFocus){
22119 this.innerLists[0].update(this.loadingText ?
22120 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
22121 this.restrictHeight();
22122 this.selectedIndex = -1;
22125 onLoad : function(a,b,c,d)
22127 if (!this.loadingChildren) {
22128 // then we are loading the top level. - hide the children
22129 for (var i = 1;i < this.views.length; i++) {
22130 this.views[i].getEl().setStyle({ display : 'none' });
22132 var lw = Math.floor(
22133 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
22136 this.list.setWidth(lw); // default to '1'
22140 if(!this.hasFocus){
22144 if(this.store.getCount() > 0) {
22146 this.restrictHeight();
22148 this.onEmptyResults();
22151 if (!this.loadingChildren) {
22152 this.selectActive();
22155 this.stores[1].loadData([]);
22156 this.stores[2].loadData([]);
22165 onLoadException : function()
22168 Roo.log(this.store.reader.jsonData);
22169 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
22170 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
22175 // no cleaning of leading spaces on blur here.
22176 cleanLeadingSpace : function(e) { },
22179 onSelectChange : function (view, sels, opts )
22181 var ix = view.getSelectedIndexes();
22183 if (opts.list > this.maxColumns - 2) {
22184 if (view.store.getCount()< 1) {
22185 this.views[opts.list ].getEl().setStyle({ display : 'none' });
22189 // used to clear ?? but if we are loading unselected
22190 this.setFromData(view.store.getAt(ix[0]).data);
22199 // this get's fired when trigger opens..
22200 // this.setFromData({});
22201 var str = this.stores[opts.list+1];
22202 str.data.clear(); // removeall wihtout the fire events..
22206 var rec = view.store.getAt(ix[0]);
22208 this.setFromData(rec.data);
22209 this.fireEvent('select', this, rec, ix[0]);
22211 var lw = Math.floor(
22213 (this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')
22214 ) / this.maxColumns
22216 this.loadingChildren = true;
22217 this.stores[opts.list+1].loadDataFromChildren( rec );
22218 this.loadingChildren = false;
22219 var dl = this.stores[opts.list+1]. getTotalCount();
22221 this.views[opts.list+1].getEl().setHeight( this.innerLists[0].getHeight());
22223 this.views[opts.list+1].getEl().setStyle({ display : dl ? 'block' : 'none' });
22224 for (var i = opts.list+2; i < this.views.length;i++) {
22225 this.views[i].getEl().setStyle({ display : 'none' });
22228 this.innerLists[opts.list+1].setHeight( this.innerLists[0].getHeight());
22229 this.list.setWidth(lw * (opts.list + (dl ? 2 : 1)));
22231 if (this.isLoading) {
22232 // this.selectActive(opts.list);
22240 onDoubleClick : function()
22242 this.collapse(); //??
22250 recordToStack : function(store, prop, value, stack)
22252 var cstore = new Roo.data.SimpleStore({
22253 //fields : this.store.reader.meta.fields, // we need array reader.. for
22254 reader : this.store.reader,
22258 var record = false;
22260 if(store.getCount() < 1){
22263 store.each(function(r){
22264 if(r.data[prop] == value){
22269 if (r.data.cn && r.data.cn.length) {
22270 cstore.loadDataFromChildren( r);
22271 var cret = _this.recordToStack(cstore, prop, value, stack);
22272 if (cret !== false) {
22281 if (record == false) {
22284 stack.unshift(srec);
22289 * find the stack of stores that match our value.
22294 selectActive : function ()
22296 // if store is not loaded, then we will need to wait for that to happen first.
22298 this.recordToStack(this.store, this.valueField, this.getValue(), stack);
22299 for (var i = 0; i < stack.length; i++ ) {
22300 this.views[i].select(stack[i].store.indexOf(stack[i]), false, false );
22312 * Ext JS Library 1.1.1
22313 * Copyright(c) 2006-2007, Ext JS, LLC.
22315 * Originally Released Under LGPL - original licence link has changed is not relivant.
22318 * <script type="text/javascript">
22321 * @class Roo.form.Checkbox
22322 * @extends Roo.form.Field
22323 * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
22325 * Creates a new Checkbox
22326 * @param {Object} config Configuration options
22328 Roo.form.Checkbox = function(config){
22329 Roo.form.Checkbox.superclass.constructor.call(this, config);
22333 * Fires when the checkbox is checked or unchecked.
22334 * @param {Roo.form.Checkbox} this This checkbox
22335 * @param {Boolean} checked The new checked value
22341 Roo.extend(Roo.form.Checkbox, Roo.form.Field, {
22343 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
22345 focusClass : undefined,
22347 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
22349 fieldClass: "x-form-field",
22351 * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
22355 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
22356 * {tag: "input", type: "checkbox", autocomplete: "off"})
22358 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
22360 * @cfg {String} boxLabel The text that appears beside the checkbox
22364 * @cfg {String} inputValue The value that should go into the generated input element's value attribute
22368 * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
22370 valueOff: '0', // value when not checked..
22372 actionMode : 'viewEl',
22375 itemCls : 'x-menu-check-item x-form-item',
22376 groupClass : 'x-menu-group-item',
22377 inputType : 'hidden',
22380 inSetChecked: false, // check that we are not calling self...
22382 inputElement: false, // real input element?
22383 basedOn: false, // ????
22385 isFormField: true, // not sure where this is needed!!!!
22387 onResize : function(){
22388 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
22389 if(!this.boxLabel){
22390 this.el.alignTo(this.wrap, 'c-c');
22394 initEvents : function(){
22395 Roo.form.Checkbox.superclass.initEvents.call(this);
22396 this.el.on("click", this.onClick, this);
22397 this.el.on("change", this.onClick, this);
22401 getResizeEl : function(){
22405 getPositionEl : function(){
22410 onRender : function(ct, position){
22411 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
22413 if(this.inputValue !== undefined){
22414 this.el.dom.value = this.inputValue;
22417 //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
22418 this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
22419 var viewEl = this.wrap.createChild({
22420 tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
22421 this.viewEl = viewEl;
22422 this.wrap.on('click', this.onClick, this);
22424 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
22425 this.el.on('propertychange', this.setFromHidden, this); //ie
22430 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
22431 // viewEl.on('click', this.onClick, this);
22433 //if(this.checked){
22434 this.setChecked(this.checked);
22436 //this.checked = this.el.dom;
22442 initValue : Roo.emptyFn,
22445 * Returns the checked state of the checkbox.
22446 * @return {Boolean} True if checked, else false
22448 getValue : function(){
22450 return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
22452 return this.valueOff;
22457 onClick : function(){
22458 if (this.disabled) {
22461 this.setChecked(!this.checked);
22463 //if(this.el.dom.checked != this.checked){
22464 // this.setValue(this.el.dom.checked);
22469 * Sets the checked state of the checkbox.
22470 * On is always based on a string comparison between inputValue and the param.
22471 * @param {Boolean/String} value - the value to set
22472 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
22474 setValue : function(v,suppressEvent){
22477 //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
22478 //if(this.el && this.el.dom){
22479 // this.el.dom.checked = this.checked;
22480 // this.el.dom.defaultChecked = this.checked;
22482 this.setChecked(String(v) === String(this.inputValue), suppressEvent);
22483 //this.fireEvent("check", this, this.checked);
22486 setChecked : function(state,suppressEvent)
22488 if (this.inSetChecked) {
22489 this.checked = state;
22495 this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
22497 this.checked = state;
22498 if(suppressEvent !== true){
22499 this.fireEvent('check', this, state);
22501 this.inSetChecked = true;
22503 this.el.dom.value = state ? this.inputValue : this.valueOff;
22505 this.inSetChecked = false;
22508 // handle setting of hidden value by some other method!!?!?
22509 setFromHidden: function()
22514 //console.log("SET FROM HIDDEN");
22515 //alert('setFrom hidden');
22516 this.setValue(this.el.dom.value);
22519 onDestroy : function()
22522 Roo.get(this.viewEl).remove();
22525 Roo.form.Checkbox.superclass.onDestroy.call(this);
22528 setBoxLabel : function(str)
22530 this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
22535 * Ext JS Library 1.1.1
22536 * Copyright(c) 2006-2007, Ext JS, LLC.
22538 * Originally Released Under LGPL - original licence link has changed is not relivant.
22541 * <script type="text/javascript">
22545 * @class Roo.form.Radio
22546 * @extends Roo.form.Checkbox
22547 * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
22548 * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
22550 * Creates a new Radio
22551 * @param {Object} config Configuration options
22553 Roo.form.Radio = function(){
22554 Roo.form.Radio.superclass.constructor.apply(this, arguments);
22556 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
22557 inputType: 'radio',
22560 * If this radio is part of a group, it will return the selected value
22563 getGroupValue : function(){
22564 return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
22568 onRender : function(ct, position){
22569 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
22571 if(this.inputValue !== undefined){
22572 this.el.dom.value = this.inputValue;
22575 this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
22576 //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
22577 //var viewEl = this.wrap.createChild({
22578 // tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
22579 //this.viewEl = viewEl;
22580 //this.wrap.on('click', this.onClick, this);
22582 //this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
22583 //this.el.on('propertychange', this.setFromHidden, this); //ie
22588 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
22589 // viewEl.on('click', this.onClick, this);
22592 this.el.dom.checked = 'checked' ;
22597 * Sets the checked state of the checkbox.
22598 * On is always based on a string comparison between inputValue and the param.
22599 * @param {Boolean/String} value - the value to set
22600 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
22602 setValue : function(v,suppressEvent){
22605 //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
22606 //if(this.el && this.el.dom){
22607 // this.el.dom.checked = this.checked;
22608 // this.el.dom.defaultChecked = this.checked;
22610 this.setChecked(String(v) === String(this.inputValue), suppressEvent);
22612 this.el.dom.form[this.name].value = v;
22614 //this.fireEvent("check", this, this.checked);
22617 setChecked : function(state,suppressEvent)
22621 this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
22623 this.checked = state;
22624 if(suppressEvent !== true){
22625 this.fireEvent('check', this, state);
22632 reset : function(){
22633 // this.setValue(this.resetValue);
22634 //this.originalValue = this.getValue();
22635 this.clearInvalid();
22638 });Roo.rtf = {}; // namespace
22639 Roo.rtf.Hex = function(hex)
22643 Roo.rtf.Paragraph = function(opts)
22645 this.content = []; ///??? is that used?
22646 };Roo.rtf.Span = function(opts)
22648 this.value = opts.value;
22651 Roo.rtf.Group = function(parent)
22653 // we dont want to acutally store parent - it will make debug a nightmare..
22661 Roo.rtf.Group.prototype = {
22665 addContent : function(node) {
22666 // could set styles...
22667 this.content.push(node);
22669 addChild : function(cn)
22673 // only for images really...
22674 toDataURL : function()
22676 var mimetype = false;
22678 case this.content.filter(function(a) { return a.value == 'pngblip' } ).length > 0:
22679 mimetype = "image/png";
22681 case this.content.filter(function(a) { return a.value == 'jpegblip' } ).length > 0:
22682 mimetype = "image/jpeg";
22685 return 'about:blank'; // ?? error?
22689 var hexstring = this.content[this.content.length-1].value;
22691 return 'data:' + mimetype + ';base64,' + btoa(hexstring.match(/\w{2}/g).map(function(a) {
22692 return String.fromCharCode(parseInt(a, 16));
22697 // this looks like it's normally the {rtf{ .... }}
22698 Roo.rtf.Document = function()
22700 // we dont want to acutally store parent - it will make debug a nightmare..
22706 Roo.extend(Roo.rtf.Document, Roo.rtf.Group, {
22707 addChild : function(cn)
22711 case 'rtlch': // most content seems to be inside this??
22714 this.rtlch.push(cn);
22717 this[cn.type] = cn;
22722 getElementsByType : function(type)
22725 this._getElementsByType(type, ret, this.cn, 'rtf');
22728 _getElementsByType : function (type, ret, search_array, path)
22730 search_array.forEach(function(n,i) {
22731 if (n.type == type) {
22732 n.path = path + '/' + n.type + ':' + i;
22735 if (n.cn.length > 0) {
22736 this._getElementsByType(type, ret, n.cn, path + '/' + n.type+':'+i);
22743 Roo.rtf.Ctrl = function(opts)
22745 this.value = opts.value;
22746 this.param = opts.param;
22751 * based on this https://github.com/iarna/rtf-parser
22752 * it's really only designed to extract pict from pasted RTF
22756 * var images = new Roo.rtf.Parser().parse(a_string).filter(function(g) { return g.type == 'pict'; });
22765 Roo.rtf.Parser = function(text) {
22766 //super({objectMode: true})
22768 this.parserState = this.parseText;
22770 // these are for interpeter...
22772 ///this.parserState = this.parseTop
22773 this.groupStack = [];
22774 this.hexStore = [];
22777 this.groups = []; // where we put the return.
22779 for (var ii = 0; ii < text.length; ++ii) {
22782 if (text[ii] === '\n') {
22788 this.parserState(text[ii]);
22794 Roo.rtf.Parser.prototype = {
22795 text : '', // string being parsed..
22797 controlWordParam : '',
22801 groupStack : false,
22806 row : 1, // reportin?
22810 push : function (el)
22812 var m = 'cmd'+ el.type;
22813 if (typeof(this[m]) == 'undefined') {
22814 Roo.log('invalid cmd:' + el.type);
22820 flushHexStore : function()
22822 if (this.hexStore.length < 1) {
22825 var hexstr = this.hexStore.map(
22830 this.group.addContent( new Roo.rtf.Hex( hexstr ));
22833 this.hexStore.splice(0)
22837 cmdgroupstart : function()
22839 this.flushHexStore();
22841 this.groupStack.push(this.group);
22844 if (this.doc === false) {
22845 this.group = this.doc = new Roo.rtf.Document();
22849 this.group = new Roo.rtf.Group(this.group);
22851 cmdignorable : function()
22853 this.flushHexStore();
22854 this.group.ignorable = true;
22856 cmdendparagraph : function()
22858 this.flushHexStore();
22859 this.group.addContent(new Roo.rtf.Paragraph());
22861 cmdgroupend : function ()
22863 this.flushHexStore();
22864 var endingGroup = this.group;
22867 this.group = this.groupStack.pop();
22869 this.group.addChild(endingGroup);
22874 var doc = this.group || this.doc;
22875 //if (endingGroup instanceof FontTable) {
22876 // doc.fonts = endingGroup.table
22877 //} else if (endingGroup instanceof ColorTable) {
22878 // doc.colors = endingGroup.table
22879 //} else if (endingGroup !== this.doc && !endingGroup.get('ignorable')) {
22880 if (endingGroup.ignorable === false) {
22882 this.groups.push(endingGroup);
22883 // Roo.log( endingGroup );
22885 //Roo.each(endingGroup.content, function(item)) {
22886 // doc.addContent(item);
22888 //process.emit('debug', 'GROUP END', endingGroup.type, endingGroup.get('ignorable'))
22891 cmdtext : function (cmd)
22893 this.flushHexStore();
22894 if (!this.group) { // an RTF fragment, missing the {\rtf1 header
22895 //this.group = this.doc
22896 return; // we really don't care about stray text...
22898 this.group.addContent(new Roo.rtf.Span(cmd));
22900 cmdcontrolword : function (cmd)
22902 this.flushHexStore();
22903 if (!this.group.type) {
22904 this.group.type = cmd.value;
22907 this.group.addContent(new Roo.rtf.Ctrl(cmd));
22908 // we actually don't care about ctrl words...
22911 var method = 'ctrl$' + cmd.value.replace(/-(.)/g, (_, char) => char.toUpperCase())
22912 if (this[method]) {
22913 this[method](cmd.param)
22915 if (!this.group.get('ignorable')) process.emit('debug', method, cmd.param)
22919 cmdhexchar : function(cmd) {
22920 this.hexStore.push(cmd);
22922 cmderror : function(cmd) {
22928 if (this.text !== '\u0000') this.emitText()
22934 parseText : function(c)
22937 this.parserState = this.parseEscapes;
22938 } else if (c === '{') {
22939 this.emitStartGroup();
22940 } else if (c === '}') {
22941 this.emitEndGroup();
22942 } else if (c === '\x0A' || c === '\x0D') {
22943 // cr/lf are noise chars
22949 parseEscapes: function (c)
22951 if (c === '\\' || c === '{' || c === '}') {
22953 this.parserState = this.parseText;
22955 this.parserState = this.parseControlSymbol;
22956 this.parseControlSymbol(c);
22959 parseControlSymbol: function(c)
22962 this.text += '\u00a0'; // nbsp
22963 this.parserState = this.parseText
22964 } else if (c === '-') {
22965 this.text += '\u00ad'; // soft hyphen
22966 } else if (c === '_') {
22967 this.text += '\u2011'; // non-breaking hyphen
22968 } else if (c === '*') {
22969 this.emitIgnorable();
22970 this.parserState = this.parseText;
22971 } else if (c === "'") {
22972 this.parserState = this.parseHexChar;
22973 } else if (c === '|') { // formula cacter
22974 this.emitFormula();
22975 this.parserState = this.parseText;
22976 } else if (c === ':') { // subentry in an index entry
22977 this.emitIndexSubEntry();
22978 this.parserState = this.parseText;
22979 } else if (c === '\x0a') {
22980 this.emitEndParagraph();
22981 this.parserState = this.parseText;
22982 } else if (c === '\x0d') {
22983 this.emitEndParagraph();
22984 this.parserState = this.parseText;
22986 this.parserState = this.parseControlWord;
22987 this.parseControlWord(c);
22990 parseHexChar: function (c)
22992 if (/^[A-Fa-f0-9]$/.test(c)) {
22994 if (this.hexChar.length >= 2) {
22995 this.emitHexChar();
22996 this.parserState = this.parseText;
23000 this.emitError("Invalid character \"" + c + "\" in hex literal.");
23001 this.parserState = this.parseText;
23004 parseControlWord : function(c)
23007 this.emitControlWord();
23008 this.parserState = this.parseText;
23009 } else if (/^[-\d]$/.test(c)) {
23010 this.parserState = this.parseControlWordParam;
23011 this.controlWordParam += c;
23012 } else if (/^[A-Za-z]$/.test(c)) {
23013 this.controlWord += c;
23015 this.emitControlWord();
23016 this.parserState = this.parseText;
23020 parseControlWordParam : function (c) {
23021 if (/^\d$/.test(c)) {
23022 this.controlWordParam += c;
23023 } else if (c === ' ') {
23024 this.emitControlWord();
23025 this.parserState = this.parseText;
23027 this.emitControlWord();
23028 this.parserState = this.parseText;
23036 emitText : function () {
23037 if (this.text === '') {
23049 emitControlWord : function ()
23052 if (this.controlWord === '') {
23053 // do we want to track this - it seems just to cause problems.
23054 //this.emitError('empty control word');
23057 type: 'controlword',
23058 value: this.controlWord,
23059 param: this.controlWordParam !== '' && Number(this.controlWordParam),
23065 this.controlWord = '';
23066 this.controlWordParam = '';
23068 emitStartGroup : function ()
23072 type: 'groupstart',
23078 emitEndGroup : function ()
23088 emitIgnorable : function ()
23098 emitHexChar : function ()
23103 value: this.hexChar,
23110 emitError : function (message)
23118 char: this.cpos //,
23119 //stack: new Error().stack
23122 emitEndParagraph : function () {
23125 type: 'endparagraph',
23133 Roo.htmleditor = {};
23136 * @class Roo.htmleditor.Filter
23137 * Base Class for filtering htmleditor stuff. - do not use this directly - extend it.
23138 * @cfg {DomElement} node The node to iterate and filter
23139 * @cfg {boolean|String|Array} tag Tags to replace
23141 * Create a new Filter.
23142 * @param {Object} config Configuration options
23147 Roo.htmleditor.Filter = function(cfg) {
23148 Roo.apply(this.cfg);
23149 // this does not actually call walk as it's really just a abstract class
23153 Roo.htmleditor.Filter.prototype = {
23159 // overrride to do replace comments.
23160 replaceComment : false,
23162 // overrride to do replace or do stuff with tags..
23163 replaceTag : false,
23165 walk : function(dom)
23167 Roo.each( Array.from(dom.childNodes), function( e ) {
23170 case e.nodeType == 8 && this.replaceComment !== false: // comment
23171 this.replaceComment(e);
23174 case e.nodeType != 1: //not a node.
23177 case this.tag === true: // everything
23178 case e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1:
23179 case e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'string' && this.tag == ":":
23180 case typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1: // array and it matches.
23181 case typeof(this.tag) == 'string' && this.tag == e.tagName: // array and it matches.
23182 if (this.replaceTag && false === this.replaceTag(e)) {
23185 if (e.hasChildNodes()) {
23190 default: // tags .. that do not match.
23191 if (e.hasChildNodes()) {
23201 removeNodeKeepChildren : function( node)
23204 ar = Array.from(node.childNodes);
23205 for (var i = 0; i < ar.length; i++) {
23207 node.removeChild(ar[i]);
23208 // what if we need to walk these???
23209 node.parentNode.insertBefore(ar[i], node);
23212 node.parentNode.removeChild(node);
23215 searchTag : function(dom)
23217 if(this.tag === false) {
23221 var els = dom.getElementsByTagName(this.tag);
23223 Roo.each(Array.from(els), function(e){
23224 if(e.parentNode == null) {
23227 if(this.replaceTag) {
23228 this.replaceTag(e);
23235 * @class Roo.htmleditor.FilterAttributes
23236 * clean attributes and styles including http:// etc.. in attribute
23238 * Run a new Attribute Filter
23239 * @param {Object} config Configuration options
23241 Roo.htmleditor.FilterAttributes = function(cfg)
23243 Roo.apply(this, cfg);
23244 this.attrib_black = this.attrib_black || [];
23245 this.attrib_white = this.attrib_white || [];
23247 this.attrib_clean = this.attrib_clean || [];
23248 this.style_white = this.style_white || [];
23249 this.style_black = this.style_black || [];
23250 this.walk(cfg.node);
23253 Roo.extend(Roo.htmleditor.FilterAttributes, Roo.htmleditor.Filter,
23255 tag: true, // all tags
23257 attrib_black : false, // array
23258 attrib_clean : false,
23259 attrib_white : false,
23261 style_white : false,
23262 style_black : false,
23265 replaceTag : function(node)
23267 if (!node.attributes || !node.attributes.length) {
23271 for (var i = node.attributes.length-1; i > -1 ; i--) {
23272 var a = node.attributes[i];
23274 if (this.attrib_white.length && this.attrib_white.indexOf(a.name.toLowerCase()) < 0) {
23275 node.removeAttribute(a.name);
23281 if (a.name.toLowerCase().substr(0,2)=='on') {
23282 node.removeAttribute(a.name);
23287 if (this.attrib_black.indexOf(a.name.toLowerCase()) > -1) {
23288 node.removeAttribute(a.name);
23291 if (this.attrib_clean.indexOf(a.name.toLowerCase()) > -1) {
23292 this.cleanAttr(node,a.name,a.value); // fixme..
23295 if (a.name == 'style') {
23296 this.cleanStyle(node,a.name,a.value);
23299 /// clean up MS crap..
23300 // tecnically this should be a list of valid class'es..
23303 if (a.name == 'class') {
23304 if (a.value.match(/^Mso/)) {
23305 node.removeAttribute('class');
23308 if (a.value.match(/^body$/)) {
23309 node.removeAttribute('class');
23319 return true; // clean children
23322 cleanAttr: function(node, n,v)
23325 if (v.match(/^\./) || v.match(/^\//)) {
23328 if (v.match(/^(http|https):\/\//)
23329 || v.match(/^mailto:/)
23330 || v.match(/^ftp:/)
23331 || v.match(/^data:/)
23335 if (v.match(/^#/)) {
23338 if (v.match(/^\{/)) { // allow template editing.
23341 // Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
23342 node.removeAttribute(n);
23345 cleanStyle : function(node, n,v)
23347 if (v.match(/expression/)) { //XSS?? should we even bother..
23348 node.removeAttribute(n);
23352 var parts = v.split(/;/);
23355 Roo.each(parts, function(p) {
23356 p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
23360 var l = p.split(':').shift().replace(/\s+/g,'');
23361 l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
23363 if ( this.style_black.length && (this.style_black.indexOf(l) > -1 || this.style_black.indexOf(l.toLowerCase()) > -1)) {
23367 // only allow 'c whitelisted system attributes'
23368 if ( this.style_white.length && style_white.indexOf(l) < 0 && style_white.indexOf(l.toLowerCase()) < 0 ) {
23376 if (clean.length) {
23377 node.setAttribute(n, clean.join(';'));
23379 node.removeAttribute(n);
23388 * @class Roo.htmleditor.FilterBlack
23389 * remove blacklisted elements.
23391 * Run a new Blacklisted Filter
23392 * @param {Object} config Configuration options
23395 Roo.htmleditor.FilterBlack = function(cfg)
23397 Roo.apply(this, cfg);
23398 this.walk(cfg.node);
23401 Roo.extend(Roo.htmleditor.FilterBlack, Roo.htmleditor.Filter,
23403 tag : true, // all elements.
23405 replaceTag : function(n)
23407 n.parentNode.removeChild(n);
23411 * @class Roo.htmleditor.FilterComment
23414 * Run a new Comments Filter
23415 * @param {Object} config Configuration options
23417 Roo.htmleditor.FilterComment = function(cfg)
23419 this.walk(cfg.node);
23422 Roo.extend(Roo.htmleditor.FilterComment, Roo.htmleditor.Filter,
23425 replaceComment : function(n)
23427 n.parentNode.removeChild(n);
23430 * @class Roo.htmleditor.FilterEmpty
23431 * filter empty elements
23433 * Run a new Empty Filter
23434 * @param {Object} config Configuration options
23437 Roo.htmleditor.FilterEmpty = function(cfg)
23439 // no need to apply config.
23440 this.walk(cfg.node);
23443 Roo.extend(Roo.htmleditor.FilterEmpty, Roo.htmleditor.FilterBlack,
23449 replaceTag : function(node)
23451 // start from leaf node
23452 if(node.hasChildNodes()) {
23456 // only filter empty leaf element with certain tags
23458 ['B', 'I', 'U', 'S'].indexOf(node.tagName) < 0
23460 node.attributes && node.attributes.length > 0
23462 node.hasChildNodes()
23464 return false; // don't walk
23467 Roo.htmleditor.FilterBlack.prototype.replaceTag.call(this, node);
23468 return false; // don't walk
23473 * @class Roo.htmleditor.FilterKeepChildren
23474 * remove tags but keep children
23476 * Run a new Keep Children Filter
23477 * @param {Object} config Configuration options
23480 Roo.htmleditor.FilterKeepChildren = function(cfg)
23482 Roo.apply(this, cfg);
23483 if (this.tag === false) {
23484 return; // dont walk.. (you can use this to use this just to do a child removal on a single tag )
23487 if ((typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1)) {
23488 this.cleanNamespace = true;
23491 this.walk(cfg.node);
23494 Roo.extend(Roo.htmleditor.FilterKeepChildren, Roo.htmleditor.FilterBlack,
23496 cleanNamespace : false, // should really be an option, rather than using ':' inside of this tag.
23498 replaceTag : function(node)
23500 // walk children...
23501 //Roo.log(node.tagName);
23502 var ar = Array.from(node.childNodes);
23505 for (var i = 0; i < ar.length; i++) {
23507 if (e.nodeType == 1) {
23509 (typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1)
23510 || // array and it matches
23511 (typeof(this.tag) == 'string' && this.tag == e.tagName)
23513 (e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1)
23515 (e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'string' && this.tag == ":")
23517 this.replaceTag(ar[i]); // child is blacklisted as well...
23522 ar = Array.from(node.childNodes);
23523 for (var i = 0; i < ar.length; i++) {
23525 node.removeChild(ar[i]);
23526 // what if we need to walk these???
23527 node.parentNode.insertBefore(ar[i], node);
23528 if (this.tag !== false) {
23533 //Roo.log("REMOVE:" + node.tagName);
23534 node.parentNode.removeChild(node);
23535 return false; // don't walk children
23540 * @class Roo.htmleditor.FilterParagraph
23541 * paragraphs cause a nightmare for shared content - this filter is designed to be called ? at various points when editing
23542 * like on 'push' to remove the <p> tags and replace them with line breaks.
23544 * Run a new Paragraph Filter
23545 * @param {Object} config Configuration options
23548 Roo.htmleditor.FilterParagraph = function(cfg)
23550 // no need to apply config.
23551 this.searchTag(cfg.node);
23554 Roo.extend(Roo.htmleditor.FilterParagraph, Roo.htmleditor.Filter,
23561 replaceTag : function(node)
23564 if (node.childNodes.length == 1 &&
23565 node.childNodes[0].nodeType == 3 &&
23566 node.childNodes[0].textContent.trim().length < 1
23568 // remove and replace with '<BR>';
23569 node.parentNode.replaceChild(node.ownerDocument.createElement('BR'),node);
23570 return false; // no need to walk..
23573 var ar = Array.from(node.childNodes);
23574 for (var i = 0; i < ar.length; i++) {
23575 node.removeChild(ar[i]);
23576 // what if we need to walk these???
23577 node.parentNode.insertBefore(ar[i], node);
23579 // now what about this?
23583 node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
23584 node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
23585 node.parentNode.removeChild(node);
23592 * @class Roo.htmleditor.FilterHashLink
23595 * Run a new Hash Link Filter
23596 * @param {Object} config Configuration options
23599 Roo.htmleditor.FilterHashLink = function(cfg)
23601 // no need to apply config.
23602 // this.walk(cfg.node);
23603 this.searchTag(cfg.node);
23606 Roo.extend(Roo.htmleditor.FilterHashLink, Roo.htmleditor.Filter,
23612 replaceTag : function(node)
23614 for(var i = 0; i < node.attributes.length; i ++) {
23615 var a = node.attributes[i];
23617 if(a.name.toLowerCase() == 'href' && a.value.startsWith('#')) {
23618 this.removeNodeKeepChildren(node);
23627 * @class Roo.htmleditor.FilterSpan
23628 * filter span's with no attributes out..
23630 * Run a new Span Filter
23631 * @param {Object} config Configuration options
23634 Roo.htmleditor.FilterSpan = function(cfg)
23636 // no need to apply config.
23637 this.searchTag(cfg.node);
23640 Roo.extend(Roo.htmleditor.FilterSpan, Roo.htmleditor.FilterKeepChildren,
23646 replaceTag : function(node)
23648 if (node.attributes && node.attributes.length > 0) {
23649 return true; // walk if there are any.
23651 Roo.htmleditor.FilterKeepChildren.prototype.replaceTag.call(this, node);
23657 * @class Roo.htmleditor.FilterTableWidth
23658 try and remove table width data - as that frequently messes up other stuff.
23660 * was cleanTableWidths.
23662 * Quite often pasting from word etc.. results in tables with column and widths.
23663 * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
23666 * Run a new Table Filter
23667 * @param {Object} config Configuration options
23670 Roo.htmleditor.FilterTableWidth = function(cfg)
23672 // no need to apply config.
23673 this.tag = ['TABLE', 'TD', 'TR', 'TH', 'THEAD', 'TBODY' ];
23674 this.walk(cfg.node);
23677 Roo.extend(Roo.htmleditor.FilterTableWidth, Roo.htmleditor.Filter,
23682 replaceTag: function(node) {
23686 if (node.hasAttribute('width')) {
23687 node.removeAttribute('width');
23691 if (node.hasAttribute("style")) {
23694 var styles = node.getAttribute("style").split(";");
23696 Roo.each(styles, function(s) {
23697 if (!s.match(/:/)) {
23700 var kv = s.split(":");
23701 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
23704 // what ever is left... we allow.
23707 node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
23708 if (!nstyle.length) {
23709 node.removeAttribute('style');
23713 return true; // continue doing children..
23716 * @class Roo.htmleditor.FilterWord
23717 * try and clean up all the mess that Word generates.
23719 * This is the 'nice version' - see 'Heavy' that white lists a very short list of elements, and multi-filters
23722 * Run a new Span Filter
23723 * @param {Object} config Configuration options
23726 Roo.htmleditor.FilterWord = function(cfg)
23728 // no need to apply config.
23729 this.replaceDocBullets(cfg.node);
23731 this.replaceAname(cfg.node);
23732 // this is disabled as the removal is done by other filters;
23733 // this.walk(cfg.node);
23734 this.replaceImageTable(cfg.node);
23738 Roo.extend(Roo.htmleditor.FilterWord, Roo.htmleditor.Filter,
23744 * Clean up MS wordisms...
23746 replaceTag : function(node)
23749 // no idea what this does - span with text, replaceds with just text.
23751 node.nodeName == 'SPAN' &&
23752 !node.hasAttributes() &&
23753 node.childNodes.length == 1 &&
23754 node.firstChild.nodeName == "#text"
23756 var textNode = node.firstChild;
23757 node.removeChild(textNode);
23758 if (node.getAttribute('lang') != 'zh-CN') { // do not space pad on chinese characters..
23759 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
23761 node.parentNode.insertBefore(textNode, node);
23762 if (node.getAttribute('lang') != 'zh-CN') { // do not space pad on chinese characters..
23763 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
23766 node.parentNode.removeChild(node);
23767 return false; // dont do chidren - we have remove our node - so no need to do chdhilren?
23772 if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
23773 node.parentNode.removeChild(node);
23774 return false; // dont do chidlren
23776 //Roo.log(node.tagName);
23777 // remove - but keep children..
23778 if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
23779 //Roo.log('-- removed');
23780 while (node.childNodes.length) {
23781 var cn = node.childNodes[0];
23782 node.removeChild(cn);
23783 node.parentNode.insertBefore(cn, node);
23784 // move node to parent - and clean it..
23785 if (cn.nodeType == 1) {
23786 this.replaceTag(cn);
23790 node.parentNode.removeChild(node);
23791 /// no need to iterate chidlren = it's got none..
23792 //this.iterateChildren(node, this.cleanWord);
23793 return false; // no need to iterate children.
23796 if (node.className.length) {
23798 var cn = node.className.split(/\W+/);
23800 Roo.each(cn, function(cls) {
23801 if (cls.match(/Mso[a-zA-Z]+/)) {
23806 node.className = cna.length ? cna.join(' ') : '';
23808 node.removeAttribute("class");
23812 if (node.hasAttribute("lang")) {
23813 node.removeAttribute("lang");
23816 if (node.hasAttribute("style")) {
23818 var styles = node.getAttribute("style").split(";");
23820 Roo.each(styles, function(s) {
23821 if (!s.match(/:/)) {
23824 var kv = s.split(":");
23825 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
23828 // what ever is left... we allow.
23831 node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
23832 if (!nstyle.length) {
23833 node.removeAttribute('style');
23836 return true; // do children
23842 styleToObject: function(node)
23844 var styles = (node.getAttribute("style") || '').split(";");
23846 Roo.each(styles, function(s) {
23847 if (!s.match(/:/)) {
23850 var kv = s.split(":");
23852 // what ever is left... we allow.
23853 ret[kv[0].trim()] = kv[1];
23859 replaceAname : function (doc)
23861 // replace all the a/name without..
23862 var aa = Array.from(doc.getElementsByTagName('a'));
23863 for (var i = 0; i < aa.length; i++) {
23865 if (a.hasAttribute("name")) {
23866 a.removeAttribute("name");
23868 if (a.hasAttribute("href")) {
23871 // reparent children.
23872 this.removeNodeKeepChildren(a);
23882 replaceDocBullets : function(doc)
23884 // this is a bit odd - but it appears some indents use ql-indent-1
23885 //Roo.log(doc.innerHTML);
23887 var listpara = Array.from(doc.getElementsByClassName('MsoListParagraphCxSpFirst'));
23888 for( var i = 0; i < listpara.length; i ++) {
23889 listpara[i].className = "MsoListParagraph";
23892 listpara = Array.from(doc.getElementsByClassName('MsoListParagraphCxSpMiddle'));
23893 for( var i = 0; i < listpara.length; i ++) {
23894 listpara[i].className = "MsoListParagraph";
23896 listpara = Array.from(doc.getElementsByClassName('MsoListParagraphCxSpLast'));
23897 for( var i = 0; i < listpara.length; i ++) {
23898 listpara[i].className = "MsoListParagraph";
23900 listpara = Array.from(doc.getElementsByClassName('ql-indent-1'));
23901 for( var i = 0; i < listpara.length; i ++) {
23902 listpara[i].className = "MsoListParagraph";
23905 // this is a bit hacky - we had one word document where h2 had a miso-list attribute.
23906 var htwo = Array.from(doc.getElementsByTagName('h2'));
23907 for( var i = 0; i < htwo.length; i ++) {
23908 if (htwo[i].hasAttribute('style') && htwo[i].getAttribute('style').match(/mso-list:/)) {
23909 htwo[i].className = "MsoListParagraph";
23912 listpara = Array.from(doc.getElementsByClassName('MsoNormal'));
23913 for( var i = 0; i < listpara.length; i ++) {
23914 if (listpara[i].hasAttribute('style') && listpara[i].getAttribute('style').match(/mso-list:/)) {
23915 listpara[i].className = "MsoListParagraph";
23917 listpara[i].className = "MsoNormalx";
23921 listpara = doc.getElementsByClassName('MsoListParagraph');
23922 // Roo.log(doc.innerHTML);
23926 while(listpara.length) {
23928 this.replaceDocBullet(listpara.item(0));
23935 replaceDocBullet : function(p)
23937 // gather all the siblings.
23939 parent = p.parentNode,
23940 doc = parent.ownerDocument,
23943 //Roo.log("Parsing: " + p.innerText) ;
23944 var listtype = 'ul';
23946 if (ns.nodeType != 1) {
23947 ns = ns.nextSibling;
23950 if (!ns.className.match(/(MsoListParagraph|ql-indent-1)/i)) {
23951 //Roo.log("Missing para r q1indent - got:" + ns.className);
23954 var spans = ns.getElementsByTagName('span');
23956 if (ns.hasAttribute('style') && ns.getAttribute('style').match(/mso-list/)) {
23958 ns = ns.nextSibling;
23960 if (!spans.length) {
23965 for (var i = 0; i < spans.length;i++) {
23967 if (se.hasAttribute('style') && se.hasAttribute('style') && se.style.fontFamily != '') {
23968 ff = se.style.fontFamily;
23974 //Roo.log("got font family: " + ff);
23975 if (typeof(ff) != 'undefined' && !ff.match(/(Symbol|Wingdings)/) && "·o".indexOf(se.innerText.trim()) < 0) {
23981 //Roo.log("no mso-list?");
23983 var spans = ns.getElementsByTagName('span');
23984 if (!spans.length) {
23987 var has_list = false;
23988 for(var i = 0; i < spans.length; i++) {
23989 if (spans[i].hasAttribute('style') && spans[i].getAttribute('style').match(/mso-list/)) {
23998 ns = ns.nextSibling;
24002 if (!items.length) {
24007 var ul = parent.ownerDocument.createElement(listtype); // what about number lists...
24008 parent.insertBefore(ul, p);
24010 var stack = [ ul ];
24011 var last_li = false;
24013 var margin_to_depth = {};
24016 items.forEach(function(n, ipos) {
24017 //Roo.log("got innertHMLT=" + n.innerHTML);
24019 var spans = n.getElementsByTagName('span');
24020 if (!spans.length) {
24021 //Roo.log("No spans found");
24023 parent.removeChild(n);
24026 return; // skip it...
24032 for(var i = 0; i < spans.length; i++) {
24034 style = this.styleToObject(spans[i]);
24035 if (typeof(style['mso-list']) == 'undefined') {
24038 if (listtype == 'ol') {
24039 num = spans[i].innerText.replace(/[^0-9]+]/g,'') * 1;
24041 spans[i].parentNode.removeChild(spans[i]); // remove the fake bullet.
24044 //Roo.log("NOW GOT innertHMLT=" + n.innerHTML);
24045 style = this.styleToObject(n); // mo-list is from the parent node.
24046 if (typeof(style['mso-list']) == 'undefined') {
24047 //Roo.log("parent is missing level");
24049 parent.removeChild(n);
24054 var margin = style['margin-left'];
24055 if (typeof(margin_to_depth[margin]) == 'undefined') {
24057 margin_to_depth[margin] = max_margins;
24059 nlvl = margin_to_depth[margin] ;
24063 var nul = doc.createElement(listtype); // what about number lists...
24065 last_li = doc.createElement('li');
24066 stack[lvl].appendChild(last_li);
24068 last_li.appendChild(nul);
24074 // not starting at 1..
24075 if (!stack[nlvl].hasAttribute("start") && listtype == "ol") {
24076 stack[nlvl].setAttribute("start", num);
24079 var nli = stack[nlvl].appendChild(doc.createElement('li'));
24081 nli.innerHTML = n.innerHTML;
24082 //Roo.log("innerHTML = " + n.innerHTML);
24083 parent.removeChild(n);
24095 replaceImageTable : function(doc)
24098 <table cellpadding=0 cellspacing=0 align=left>
24100 <td width=423 height=0></td>
24104 <td><img width=601 height=401
24105 src="file:///C:/Users/Alan/AppData/Local/Temp/msohtmlclip1/01/clip_image002.jpg"
24106 v:shapes="Picture_x0020_2"></td>
24110 var imgs = Array.from(doc.getElementsByTagName('img'));
24111 Roo.each(imgs, function(img) {
24112 var td = img.parentNode;
24113 if (td.nodeName != 'TD') {
24116 var tr = td.parentNode;
24117 if (tr.nodeName != 'TR') {
24120 var tbody = tr.parentNode;
24121 if (tbody.nodeName != 'TBODY') {
24124 var table = tbody.parentNode;
24125 if (table.nodeName != 'TABLE') {
24130 if (table.getElementsByTagName('tr').length != 2) {
24133 if (table.getElementsByTagName('td').length != 3) {
24136 if (table.innerText.trim() != '') {
24139 var p = table.parentNode;
24140 img.parentNode.removeChild(img);
24141 p.insertBefore(img, table);
24142 p.removeChild(table);
24153 * @class Roo.htmleditor.FilterStyleToTag
24154 * part of the word stuff... - certain 'styles' should be converted to tags.
24156 * font-weight: bold -> bold
24157 * ?? super / subscrit etc..
24160 * Run a new style to tag filter.
24161 * @param {Object} config Configuration options
24163 Roo.htmleditor.FilterStyleToTag = function(cfg)
24167 B : [ 'fontWeight' , 'bold', 'font-weight'],
24168 I : [ 'fontStyle' , 'italic', 'font-style'],
24169 //pre : [ 'font-style' , 'italic'],
24170 // h1.. h6 ?? font-size?
24171 SUP : [ 'verticalAlign' , 'super', 'vertical-align'],
24172 SUB : [ 'verticalAlign' , 'sub', 'vertical-align']
24177 Roo.apply(this, cfg);
24180 this.walk(cfg.node);
24187 Roo.extend(Roo.htmleditor.FilterStyleToTag, Roo.htmleditor.Filter,
24189 tag: true, // all tags
24194 replaceTag : function(node)
24198 if (node.getAttribute("style") === null) {
24202 for (var k in this.tags) {
24203 if (node.style[this.tags[k][0]] == this.tags[k][1]) {
24205 node.style.removeProperty(this.tags[k][2]);
24208 if (!inject.length) {
24211 var cn = Array.from(node.childNodes);
24213 Roo.each(inject, function(t) {
24214 var nc = node.ownerDocument.createElement(t);
24215 nn.appendChild(nc);
24218 for(var i = 0;i < cn.length;i++) {
24219 node.removeChild(cn[i]);
24220 nn.appendChild(cn[i]);
24222 return true /// iterate thru
24226 * @class Roo.htmleditor.FilterLongBr
24227 * BR/BR/BR - keep a maximum of 2...
24229 * Run a new Long BR Filter
24230 * @param {Object} config Configuration options
24233 Roo.htmleditor.FilterLongBr = function(cfg)
24235 // no need to apply config.
24236 this.searchTag(cfg.node);
24239 Roo.extend(Roo.htmleditor.FilterLongBr, Roo.htmleditor.Filter,
24246 replaceTag : function(node)
24249 var ps = node.nextSibling;
24250 while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
24251 ps = ps.nextSibling;
24254 if (!ps && [ 'TD', 'TH', 'LI', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(node.parentNode.tagName) > -1) {
24255 node.parentNode.removeChild(node); // remove last BR inside one fo these tags
24259 if (!ps || ps.nodeType != 1) {
24263 if (!ps || ps.tagName != 'BR') {
24270 if (!node.previousSibling) {
24273 var ps = node.previousSibling;
24275 while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
24276 ps = ps.previousSibling;
24278 if (!ps || ps.nodeType != 1) {
24281 // if header or BR before.. then it's a candidate for removal.. - as we only want '2' of these..
24282 if (!ps || [ 'BR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(ps.tagName) < 0) {
24286 node.parentNode.removeChild(node); // remove me...
24288 return false; // no need to do children
24295 * @class Roo.htmleditor.FilterBlock
24296 * removes id / data-block and contenteditable that are associated with blocks
24297 * usage should be done on a cloned copy of the dom
24299 * Run a new Attribute Filter { node : xxxx }}
24300 * @param {Object} config Configuration options
24302 Roo.htmleditor.FilterBlock = function(cfg)
24304 Roo.apply(this, cfg);
24305 var qa = cfg.node.querySelectorAll;
24306 this.removeAttributes('data-block');
24307 this.removeAttributes('contenteditable');
24308 this.removeAttributes('id');
24312 Roo.apply(Roo.htmleditor.FilterBlock.prototype,
24314 node: true, // all tags
24317 removeAttributes : function(attr)
24319 var ar = this.node.querySelectorAll('*[' + attr + ']');
24320 for (var i =0;i<ar.length;i++) {
24321 ar[i].removeAttribute(attr);
24330 * This is based loosely on tinymce
24331 * @class Roo.htmleditor.TidySerializer
24332 * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
24334 * @method Serializer
24335 * @param {Object} settings Name/value settings object.
24339 Roo.htmleditor.TidySerializer = function(settings)
24341 Roo.apply(this, settings);
24343 this.writer = new Roo.htmleditor.TidyWriter(settings);
24348 Roo.htmleditor.TidySerializer.prototype = {
24351 * @param {boolean} inner do the inner of the node.
24358 * Serializes the specified node into a string.
24361 * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('<p>text</p>'));
24362 * @method serialize
24363 * @param {DomElement} node Node instance to serialize.
24364 * @return {String} String with HTML based on DOM tree.
24366 serialize : function(node) {
24368 // = settings.validate;
24369 var writer = this.writer;
24373 3: function(node) {
24375 writer.text(node.nodeValue, node);
24378 8: function(node) {
24379 writer.comment(node.nodeValue);
24381 // Processing instruction
24382 7: function(node) {
24383 writer.pi(node.name, node.nodeValue);
24386 10: function(node) {
24387 writer.doctype(node.nodeValue);
24390 4: function(node) {
24391 writer.cdata(node.nodeValue);
24393 // Document fragment
24394 11: function(node) {
24395 node = node.firstChild;
24401 node = node.nextSibling
24406 1 != node.nodeType || this.inner ? this.handlers[11](node) : this.walk(node);
24407 return writer.getContent();
24410 walk: function(node)
24412 var attrName, attrValue, sortedAttrs, i, l, elementRule,
24413 handler = this.handlers[node.nodeType];
24420 var name = node.nodeName;
24421 var isEmpty = node.childNodes.length < 1;
24423 var writer = this.writer;
24424 var attrs = node.attributes;
24427 writer.start(node.nodeName, attrs, isEmpty, node);
24431 node = node.firstChild;
24438 node = node.nextSibling;
24444 // Serialize element and treat all non elements as fragments
24449 * This is based loosely on tinymce
24450 * @class Roo.htmleditor.TidyWriter
24451 * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
24454 * - not tested much with 'PRE' formated elements.
24460 Roo.htmleditor.TidyWriter = function(settings)
24463 // indent, indentBefore, indentAfter, encode, htmlOutput, html = [];
24464 Roo.apply(this, settings);
24468 this.encode = Roo.htmleditor.TidyEntities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
24471 Roo.htmleditor.TidyWriter.prototype = {
24478 // part of state...
24482 last_inline : false,
24487 * Writes the a start element such as <p id="a">.
24490 * @param {String} name Name of the element.
24491 * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
24492 * @param {Boolean} empty Optional empty state if the tag should end like <br />.
24494 start: function(name, attrs, empty, node)
24496 var i, l, attr, value;
24498 // there are some situations where adding line break && indentation will not work. will not work.
24499 // <span / b / i ... formating?
24501 var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
24502 var in_pre = this.in_pre || Roo.htmleditor.TidyWriter.whitespace_elements.indexOf(name) > -1;
24504 var is_short = empty ? Roo.htmleditor.TidyWriter.shortend_elements.indexOf(name) > -1 : false;
24506 var add_lb = name == 'BR' ? false : in_inline;
24508 if (!add_lb && !this.in_pre && this.lastElementEndsWS()) {
24512 var indentstr = this.indentstr;
24514 // e_inline = elements that can be inline, but still allow \n before and after?
24515 // only 'BR' ??? any others?
24517 // ADD LINE BEFORE tage
24518 if (!this.in_pre) {
24521 if (name == 'BR') {
24523 } else if (this.lastElementEndsWS()) {
24526 // otherwise - no new line. (and dont indent.)
24537 this.html.push(indentstr + '<', name.toLowerCase());
24540 for (i = 0, l = attrs.length; i < l; i++) {
24542 this.html.push(' ', attr.name, '="', this.encode(attr.value, true), '"');
24548 this.html[this.html.length] = '/>';
24550 this.html[this.html.length] = '></' + name.toLowerCase() + '>';
24552 var e_inline = name == 'BR' ? false : this.in_inline;
24554 if (!e_inline && !this.in_pre) {
24561 this.html[this.html.length] = '>';
24563 // there is a special situation, where we need to turn on in_inline - if any of the imediate chidlren are one of these.
24565 if (!in_inline && !in_pre) {
24566 var cn = node.firstChild;
24568 if (Roo.htmleditor.TidyWriter.inline_elements.indexOf(cn.nodeName) > -1) {
24572 cn = cn.nextSibling;
24580 indentstr : in_pre ? '' : (this.indentstr + this.indent),
24582 in_inline : in_inline
24584 // add a line after if we are not in a
24586 if (!in_inline && !in_pre) {
24595 lastElementEndsWS : function()
24597 var value = this.html.length > 0 ? this.html[this.html.length-1] : false;
24598 if (value === false) {
24601 return value.match(/\s+$/);
24606 * Writes the a end element such as </p>.
24609 * @param {String} name Name of the element.
24611 end: function(name) {
24614 var indentstr = '';
24615 var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
24617 if (!this.in_pre && !in_inline) {
24619 indentstr = this.indentstr;
24621 this.html.push(indentstr + '</', name.toLowerCase(), '>');
24622 this.last_inline = in_inline;
24624 // pop the indent state..
24627 * Writes a text node.
24629 * In pre - we should not mess with the contents.
24633 * @param {String} text String to write out.
24634 * @param {Boolean} raw Optional raw state if true the contents wont get encoded.
24636 text: function(in_text, node)
24638 // if not in whitespace critical
24639 if (in_text.length < 1) {
24642 var text = new XMLSerializer().serializeToString(document.createTextNode(in_text)); // escape it properly?
24645 this.html[this.html.length] = text;
24649 if (this.in_inline) {
24650 text = text.replace(/\s+/g,' '); // all white space inc line breaks to a slingle' '
24652 text = text.replace(/\s+/,' '); // all white space to single white space
24655 // if next tag is '<BR>', then we can trim right..
24656 if (node.nextSibling &&
24657 node.nextSibling.nodeType == 1 &&
24658 node.nextSibling.nodeName == 'BR' )
24660 text = text.replace(/\s+$/g,'');
24662 // if previous tag was a BR, we can also trim..
24663 if (node.previousSibling &&
24664 node.previousSibling.nodeType == 1 &&
24665 node.previousSibling.nodeName == 'BR' )
24667 text = this.indentstr + text.replace(/^\s+/g,'');
24669 if (text.match(/\n/)) {
24670 text = text.replace(
24671 /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
24673 // remoeve the last whitespace / line break.
24674 text = text.replace(/\n\s+$/,'');
24676 // repace long lines
24680 this.html[this.html.length] = text;
24683 // see if previous element was a inline element.
24684 var indentstr = this.indentstr;
24686 text = text.replace(/\s+/g," "); // all whitespace into single white space.
24688 // should trim left?
24689 if (node.previousSibling &&
24690 node.previousSibling.nodeType == 1 &&
24691 Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.previousSibling.nodeName) > -1)
24697 text = text.replace(/^\s+/,''); // trim left
24700 // should trim right?
24701 if (node.nextSibling &&
24702 node.nextSibling.nodeType == 1 &&
24703 Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.nextSibling.nodeName) > -1)
24708 text = text.replace(/\s+$/,''); // trim right
24715 if (text.length < 1) {
24718 if (!text.match(/\n/)) {
24719 this.html.push(indentstr + text);
24723 text = this.indentstr + text.replace(
24724 /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
24726 // remoeve the last whitespace / line break.
24727 text = text.replace(/\s+$/,'');
24729 this.html.push(text);
24731 // split and indent..
24736 * Writes a cdata node such as <![CDATA[data]]>.
24739 * @param {String} text String to write out inside the cdata.
24741 cdata: function(text) {
24742 this.html.push('<![CDATA[', text, ']]>');
24745 * Writes a comment node such as <!-- Comment -->.
24748 * @param {String} text String to write out inside the comment.
24750 comment: function(text) {
24751 this.html.push('<!--', text, '-->');
24754 * Writes a PI node such as <?xml attr="value" ?>.
24757 * @param {String} name Name of the pi.
24758 * @param {String} text String to write out inside the pi.
24760 pi: function(name, text) {
24761 text ? this.html.push('<?', name, ' ', this.encode(text), '?>') : this.html.push('<?', name, '?>');
24762 this.indent != '' && this.html.push('\n');
24765 * Writes a doctype node such as <!DOCTYPE data>.
24768 * @param {String} text String to write out inside the doctype.
24770 doctype: function(text) {
24771 this.html.push('<!DOCTYPE', text, '>', this.indent != '' ? '\n' : '');
24774 * Resets the internal buffer if one wants to reuse the writer.
24778 reset: function() {
24779 this.html.length = 0;
24788 * Returns the contents that got serialized.
24790 * @method getContent
24791 * @return {String} HTML contents that got written down.
24793 getContent: function() {
24794 return this.html.join('').replace(/\n$/, '');
24797 pushState : function(cfg)
24799 this.state.push(cfg);
24800 Roo.apply(this, cfg);
24803 popState : function()
24805 if (this.state.length < 1) {
24806 return; // nothing to push
24813 if (this.state.length > 0) {
24814 cfg = this.state[this.state.length-1];
24816 Roo.apply(this, cfg);
24819 addLine: function()
24821 if (this.html.length < 1) {
24826 var value = this.html[this.html.length - 1];
24827 if (value.length > 0 && '\n' !== value) {
24828 this.html.push('\n');
24833 //'pre script noscript style textarea video audio iframe object code'
24834 // shortended... 'area base basefont br col frame hr img input isindex link meta param embed source wbr track');
24838 Roo.htmleditor.TidyWriter.inline_elements = [
24839 'SPAN','STRONG','B','EM','I','FONT','STRIKE','U','VAR',
24840 'CITE','DFN','CODE','MARK','Q','SUP','SUB','SAMP', 'A'
24842 Roo.htmleditor.TidyWriter.shortend_elements = [
24843 'AREA','BASE','BASEFONT','BR','COL','FRAME','HR','IMG','INPUT',
24844 'ISINDEX','LINK','','META','PARAM','EMBED','SOURCE','WBR','TRACK'
24847 Roo.htmleditor.TidyWriter.whitespace_elements = [
24848 'PRE','SCRIPT','NOSCRIPT','STYLE','TEXTAREA','VIDEO','AUDIO','IFRAME','OBJECT','CODE'
24850 * This is based loosely on tinymce
24851 * @class Roo.htmleditor.TidyEntities
24853 * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
24855 * Not 100% sure this is actually used or needed.
24858 Roo.htmleditor.TidyEntities = {
24861 * initialize data..
24863 init : function (){
24865 this.namedEntities = this.buildEntitiesLookup(this.namedEntitiesData, 32);
24870 buildEntitiesLookup: function(items, radix) {
24871 var i, chr, entity, lookup = {};
24875 items = typeof(items) == 'string' ? items.split(',') : items;
24876 radix = radix || 10;
24877 // Build entities lookup table
24878 for (i = 0; i < items.length; i += 2) {
24879 chr = String.fromCharCode(parseInt(items[i], radix));
24880 // Only add non base entities
24881 if (!this.baseEntities[chr]) {
24882 entity = '&' + items[i + 1] + ';';
24883 lookup[chr] = entity;
24884 lookup[entity] = chr;
24923 // Needs to be escaped since the YUI compressor would otherwise break the code
24930 // Reverse lookup table for raw entities
24931 reverseEntities : {
24939 attrsCharsRegExp : /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
24940 textCharsRegExp : /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
24941 rawCharsRegExp : /[<>&\"\']/g,
24942 entityRegExp : /&#([a-z0-9]+);?|&([a-z0-9]+);/gi,
24943 namedEntities : false,
24944 namedEntitiesData : [
25445 * Encodes the specified string using raw entities. This means only the required XML base entities will be encoded.
25447 * @method encodeRaw
25448 * @param {String} text Text to encode.
25449 * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
25450 * @return {String} Entity encoded text.
25452 encodeRaw: function(text, attr)
25455 return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
25456 return t.baseEntities[chr] || chr;
25460 * Encoded the specified text with both the attributes and text entities. This function will produce larger text contents
25461 * since it doesn't know if the context is within a attribute or text node. This was added for compatibility
25462 * and is exposed as the DOMUtils.encode function.
25464 * @method encodeAllRaw
25465 * @param {String} text Text to encode.
25466 * @return {String} Entity encoded text.
25468 encodeAllRaw: function(text) {
25470 return ('' + text).replace(this.rawCharsRegExp, function(chr) {
25471 return t.baseEntities[chr] || chr;
25475 * Encodes the specified string using numeric entities. The core entities will be
25476 * encoded as named ones but all non lower ascii characters will be encoded into numeric entities.
25478 * @method encodeNumeric
25479 * @param {String} text Text to encode.
25480 * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
25481 * @return {String} Entity encoded text.
25483 encodeNumeric: function(text, attr) {
25485 return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
25486 // Multi byte sequence convert it to a single entity
25487 if (chr.length > 1) {
25488 return '&#' + (1024 * (chr.charCodeAt(0) - 55296) + (chr.charCodeAt(1) - 56320) + 65536) + ';';
25490 return t.baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
25494 * Encodes the specified string using named entities. The core entities will be encoded
25495 * as named ones but all non lower ascii characters will be encoded into named entities.
25497 * @method encodeNamed
25498 * @param {String} text Text to encode.
25499 * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
25500 * @param {Object} entities Optional parameter with entities to use.
25501 * @return {String} Entity encoded text.
25503 encodeNamed: function(text, attr, entities) {
25505 entities = entities || this.namedEntities;
25506 return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
25507 return t.baseEntities[chr] || entities[chr] || chr;
25511 * Returns an encode function based on the name(s) and it's optional entities.
25513 * @method getEncodeFunc
25514 * @param {String} name Comma separated list of encoders for example named,numeric.
25515 * @param {String} entities Optional parameter with entities to use instead of the built in set.
25516 * @return {function} Encode function to be used.
25518 getEncodeFunc: function(name, entities) {
25519 entities = this.buildEntitiesLookup(entities) || this.namedEntities;
25521 function encodeNamedAndNumeric(text, attr) {
25522 return text.replace(attr ? t.attrsCharsRegExp : t.textCharsRegExp, function(chr) {
25523 return t.baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr;
25527 function encodeCustomNamed(text, attr) {
25528 return t.encodeNamed(text, attr, entities);
25530 // Replace + with , to be compatible with previous TinyMCE versions
25531 name = this.makeMap(name.replace(/\+/g, ','));
25532 // Named and numeric encoder
25533 if (name.named && name.numeric) {
25534 return this.encodeNamedAndNumeric;
25540 return encodeCustomNamed;
25542 return this.encodeNamed;
25545 if (name.numeric) {
25546 return this.encodeNumeric;
25549 return this.encodeRaw;
25552 * Decodes the specified string, this will replace entities with raw UTF characters.
25555 * @param {String} text Text to entity decode.
25556 * @return {String} Entity decoded string.
25558 decode: function(text)
25561 return text.replace(this.entityRegExp, function(all, numeric) {
25563 numeric = 'x' === numeric.charAt(0).toLowerCase() ? parseInt(numeric.substr(1), 16) : parseInt(numeric, 10);
25564 // Support upper UTF
25565 if (numeric > 65535) {
25567 return String.fromCharCode(55296 + (numeric >> 10), 56320 + (1023 & numeric));
25569 return t.asciiMap[numeric] || String.fromCharCode(numeric);
25571 return t.reverseEntities[all] || t.namedEntities[all] || t.nativeDecode(all);
25574 nativeDecode : function (text) {
25577 makeMap : function (items, delim, map) {
25579 items = items || [];
25580 delim = delim || ',';
25581 if (typeof items == "string") {
25582 items = items.split(delim);
25587 map[items[i]] = {};
25595 Roo.htmleditor.TidyEntities.init();
25597 * @class Roo.htmleditor.KeyEnter
25598 * Handle Enter press..
25599 * @cfg {Roo.HtmlEditorCore} core the editor.
25601 * Create a new Filter.
25602 * @param {Object} config Configuration options
25609 Roo.htmleditor.KeyEnter = function(cfg) {
25610 Roo.apply(this, cfg);
25611 // this does not actually call walk as it's really just a abstract class
25613 Roo.get(this.core.doc.body).on('keypress', this.keypress, this);
25616 //Roo.htmleditor.KeyEnter.i = 0;
25619 Roo.htmleditor.KeyEnter.prototype = {
25623 keypress : function(e)
25625 if (e.charCode != 13 && e.charCode != 10) {
25626 Roo.log([e.charCode,e]);
25629 e.preventDefault();
25630 // https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
25631 var doc = this.core.doc;
25635 var sel = this.core.getSelection();
25636 var range = sel.getRangeAt(0);
25637 var n = range.commonAncestorContainer;
25638 var pc = range.closest([ 'ol', 'ul']);
25639 var pli = range.closest('li');
25640 if (!pc || e.ctrlKey) {
25641 // on it list, or ctrl pressed.
25643 sel.insertNode('br', 'after');
25645 // only do this if we have ctrl key..
25646 var br = doc.createElement('br');
25647 br.className = 'clear';
25648 br.setAttribute('style', 'clear: both');
25649 sel.insertNode(br, 'after');
25653 this.core.undoManager.addEvent();
25654 this.core.fireEditorEvent(e);
25658 // deal with <li> insetion
25659 if (pli.innerText.trim() == '' &&
25660 pli.previousSibling &&
25661 pli.previousSibling.nodeName == 'LI' &&
25662 pli.previousSibling.innerText.trim() == '') {
25663 pli.parentNode.removeChild(pli.previousSibling);
25664 sel.cursorAfter(pc);
25665 this.core.undoManager.addEvent();
25666 this.core.fireEditorEvent(e);
25670 var li = doc.createElement('LI');
25671 li.innerHTML = ' ';
25672 if (!pli || !pli.firstSibling) {
25673 pc.appendChild(li);
25675 pli.parentNode.insertBefore(li, pli.firstSibling);
25677 sel.cursorText (li.firstChild);
25679 this.core.undoManager.addEvent();
25680 this.core.fireEditorEvent(e);
25692 * @class Roo.htmleditor.Block
25693 * Base class for html editor blocks - do not use it directly .. extend it..
25694 * @cfg {DomElement} node The node to apply stuff to.
25695 * @cfg {String} friendly_name the name that appears in the context bar about this block
25696 * @cfg {Object} Context menu - see Roo.form.HtmlEditor.ToolbarContext
25699 * Create a new Filter.
25700 * @param {Object} config Configuration options
25703 Roo.htmleditor.Block = function(cfg)
25705 // do nothing .. should not be called really.
25708 * factory method to get the block from an element (using cache if necessary)
25710 * @param {HtmlElement} the dom element
25712 Roo.htmleditor.Block.factory = function(node)
25714 var cc = Roo.htmleditor.Block.cache;
25715 var id = Roo.get(node).id;
25716 if (typeof(cc[id]) != 'undefined' && (!cc[id].node || cc[id].node.closest('body'))) {
25717 Roo.htmleditor.Block.cache[id].readElement(node);
25718 return Roo.htmleditor.Block.cache[id];
25720 var db = node.getAttribute('data-block');
25722 db = node.nodeName.toLowerCase().toUpperCaseFirst();
25724 var cls = Roo.htmleditor['Block' + db];
25725 if (typeof(cls) == 'undefined') {
25726 //Roo.log(node.getAttribute('data-block'));
25727 Roo.log("OOps missing block : " + 'Block' + db);
25730 Roo.htmleditor.Block.cache[id] = new cls({ node: node });
25731 return Roo.htmleditor.Block.cache[id]; /// should trigger update element
25735 * initalize all Elements from content that are 'blockable'
25737 * @param the body element
25739 Roo.htmleditor.Block.initAll = function(body, type)
25741 if (typeof(type) == 'undefined') {
25742 var ia = Roo.htmleditor.Block.initAll;
25748 Roo.each(Roo.get(body).query(type), function(e) {
25749 Roo.htmleditor.Block.factory(e);
25752 // question goes here... do we need to clear out this cache sometimes?
25753 // or show we make it relivant to the htmleditor.
25754 Roo.htmleditor.Block.cache = {};
25756 Roo.htmleditor.Block.prototype = {
25760 // used by context menu
25761 friendly_name : 'Based Block',
25763 // text for button to delete this element
25764 deleteTitle : false,
25768 * Update a node with values from this object
25769 * @param {DomElement} node
25771 updateElement : function(node)
25773 Roo.DomHelper.update(node === undefined ? this.node : node, this.toObject());
25776 * convert to plain HTML for calling insertAtCursor..
25778 toHTML : function()
25780 return Roo.DomHelper.markup(this.toObject());
25783 * used by readEleemnt to extract data from a node
25784 * may need improving as it's pretty basic
25786 * @param {DomElement} node
25787 * @param {String} tag - tag to find, eg. IMG ?? might be better to use DomQuery ?
25788 * @param {String} attribute (use html - for contents, style for using next param as style, or false to return the node)
25789 * @param {String} style the style property - eg. text-align
25791 getVal : function(node, tag, attr, style)
25794 if (tag !== true && n.tagName != tag.toUpperCase()) {
25795 // in theory we could do figure[3] << 3rd figure? or some more complex search..?
25796 // but kiss for now.
25797 n = node.getElementsByTagName(tag).item(0);
25802 if (attr === false) {
25805 if (attr == 'html') {
25806 return n.innerHTML;
25808 if (attr == 'style') {
25809 return n.style[style];
25812 return n.hasAttribute(attr) ? n.getAttribute(attr) : '';
25816 * create a DomHelper friendly object - for use with
25817 * Roo.DomHelper.markup / overwrite / etc..
25820 toObject : function()
25825 * Read a node that has a 'data-block' property - and extract the values from it.
25826 * @param {DomElement} node - the node
25828 readElement : function(node)
25839 * @class Roo.htmleditor.BlockFigure
25840 * Block that has an image and a figcaption
25841 * @cfg {String} image_src the url for the image
25842 * @cfg {String} align (left|right) alignment for the block default left
25843 * @cfg {String} caption the text to appear below (and in the alt tag)
25844 * @cfg {String} caption_display (block|none) display or not the caption
25845 * @cfg {String|number} image_width the width of the image number or %?
25846 * @cfg {String|number} image_height the height of the image number or %?
25849 * Create a new Filter.
25850 * @param {Object} config Configuration options
25853 Roo.htmleditor.BlockFigure = function(cfg)
25856 this.readElement(cfg.node);
25857 this.updateElement(cfg.node);
25859 Roo.apply(this, cfg);
25861 Roo.extend(Roo.htmleditor.BlockFigure, Roo.htmleditor.Block, {
25868 caption_display : 'block',
25874 // margin: '2%', not used
25876 text_align: 'left', // (left|right) alignment for the text caption default left. - not used at present
25879 // used by context menu
25880 friendly_name : 'Image with caption',
25881 deleteTitle : "Delete Image and Caption",
25883 contextMenu : function(toolbar)
25886 var block = function() {
25887 return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
25891 var rooui = typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
25893 var syncValue = toolbar.editorcore.syncValue;
25899 xtype : 'TextItem',
25901 xns : rooui.Toolbar //Boostrap?
25905 text: 'Change Image URL',
25908 click: function (btn, state)
25912 Roo.MessageBox.show({
25913 title : "Image Source URL",
25914 msg : "Enter the url for the image",
25915 buttons: Roo.MessageBox.OKCANCEL,
25916 fn: function(btn, val){
25923 toolbar.editorcore.onEditorEvent();
25927 //multiline: multiline,
25929 value : b.image_src
25933 xns : rooui.Toolbar
25938 text: 'Change Link URL',
25941 click: function (btn, state)
25945 Roo.MessageBox.show({
25946 title : "Link URL",
25947 msg : "Enter the url for the link - leave blank to have no link",
25948 buttons: Roo.MessageBox.OKCANCEL,
25949 fn: function(btn, val){
25956 toolbar.editorcore.onEditorEvent();
25960 //multiline: multiline,
25966 xns : rooui.Toolbar
25970 text: 'Show Video URL',
25973 click: function (btn, state)
25975 Roo.MessageBox.alert("Video URL",
25976 block().video_url == '' ? 'This image is not linked ot a video' :
25977 'The image is linked to: <a target="_new" href="' + block().video_url + '">' + block().video_url + '</a>');
25980 xns : rooui.Toolbar
25985 xtype : 'TextItem',
25987 xns : rooui.Toolbar //Boostrap?
25990 xtype : 'ComboBox',
25991 allowBlank : false,
25992 displayField : 'val',
25995 triggerAction : 'all',
25997 valueField : 'val',
26001 select : function (combo, r, index)
26003 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26005 b.width = r.get('val');
26008 toolbar.editorcore.onEditorEvent();
26013 xtype : 'SimpleStore',
26026 xtype : 'TextItem',
26028 xns : rooui.Toolbar //Boostrap?
26031 xtype : 'ComboBox',
26032 allowBlank : false,
26033 displayField : 'val',
26036 triggerAction : 'all',
26038 valueField : 'val',
26042 select : function (combo, r, index)
26044 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26046 b.align = r.get('val');
26049 toolbar.editorcore.onEditorEvent();
26054 xtype : 'SimpleStore',
26068 text: 'Hide Caption',
26069 name : 'caption_display',
26071 enableToggle : true,
26072 setValue : function(v) {
26073 // this trigger toggle.
26075 this.setText(v ? "Hide Caption" : "Show Caption");
26076 this.setPressed(v != 'block');
26079 toggle: function (btn, state)
26082 b.caption_display = b.caption_display == 'block' ? 'none' : 'block';
26083 this.setText(b.caption_display == 'block' ? "Hide Caption" : "Show Caption");
26086 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26087 toolbar.editorcore.onEditorEvent();
26090 xns : rooui.Toolbar
26096 * create a DomHelper friendly object - for use with
26097 * Roo.DomHelper.markup / overwrite / etc..
26099 toObject : function()
26101 var d = document.createElement('div');
26102 d.innerHTML = this.caption;
26104 var m = this.width != '100%' && this.align == 'center' ? '0 auto' : 0;
26106 var iw = this.align == 'center' ? this.width : '100%';
26109 contenteditable : 'false',
26110 src : this.image_src,
26111 alt : d.innerText.replace(/\n/g, " ").replace(/\s+/g, ' ').trim(), // removeHTML and reduce spaces..
26114 maxWidth : iw + ' !important', // this is not getting rendered?
26118 width: this.align == 'center' ? this.width : '100%'
26123 '<div class="{0}" width="420" height="315" src="{1}" frameborder="0" allowfullscreen>' +
26125 '<img class="{0}-thumbnail" src="{3}/Images/{4}/{5}#image-{4}" />' +
26130 if (this.href.length > 0) {
26134 contenteditable : 'true',
26142 if (this.video_url.length > 0) {
26147 allowfullscreen : true,
26148 width : 420, // these are for video tricks - that we replace the outer
26150 src : this.video_url,
26161 'data-block' : 'Figure',
26162 'data-width' : this.width,
26163 'data-caption' : this.caption,
26164 'data-caption-display' : this.caption_display,
26165 contenteditable : 'false',
26169 float : this.align ,
26170 maxWidth : this.align == 'center' ? '100% !important' : (this.width + ' !important'),
26171 width : this.align == 'center' ? '100%' : this.width,
26173 padding: this.align == 'center' ? '0' : '0 10px' ,
26174 textAlign : this.align // seems to work for email..
26178 align : this.align,
26184 // show figcaption only if caption_display is 'block'
26185 if(this.caption_display == 'block') {
26189 textAlign : 'left',
26191 lineHeight : '24px',
26192 display : this.caption_display,
26193 maxWidth : (this.align == 'center' ? this.width : '100%' ) + ' !important',
26195 width: this.align == 'center' ? this.width : '100%'
26199 cls : this.cls.length > 0 ? (this.cls + '-thumbnail' ) : '',
26204 marginTop : '16px',
26205 textAlign : 'start'
26210 // we can not rely on yahoo syndication to use CSS elements - so have to use '<i>' to encase stuff.
26212 contenteditable : Roo.htmleditor.BlockFigure.caption_edit,
26213 html : this.caption.length ? this.caption : "Caption" // fake caption
26227 readElement : function(node)
26229 // this should not really come from the link...
26230 this.video_url = this.getVal(node, 'div', 'src');
26231 this.cls = this.getVal(node, 'div', 'class');
26232 this.href = this.getVal(node, 'a', 'href');
26235 this.image_src = this.getVal(node, 'img', 'src');
26237 this.align = this.getVal(node, 'figure', 'align');
26239 // caption display is stored in figure
26240 this.caption_display = this.getVal(node, true, 'data-caption-display');
26242 // backward compatible
26243 // it was stored in figcaption
26244 if(this.caption_display == '') {
26245 this.caption_display = this.getVal(node, 'figcaption', 'data-display');
26248 // read caption from figcaption
26249 var figcaption = this.getVal(node, 'figcaption', false);
26251 if (figcaption !== '') {
26252 this.caption = this.getVal(figcaption, 'i', 'html');
26256 // read caption from data-caption in figure if no caption from figcaption
26257 var dc = this.getVal(node, true, 'data-caption');
26259 if(this.caption_display == 'none' && dc && dc.length){
26263 //this.text_align = this.getVal(node, 'figcaption', 'style','text-align');
26264 this.width = this.getVal(node, true, 'data-width');
26265 //this.margin = this.getVal(node, 'figure', 'style', 'margin');
26268 removeNode : function()
26282 Roo.apply(Roo.htmleditor.BlockFigure, {
26283 caption_edit : true
26289 * @class Roo.htmleditor.BlockTable
26290 * Block that manages a table
26293 * Create a new Filter.
26294 * @param {Object} config Configuration options
26297 Roo.htmleditor.BlockTable = function(cfg)
26300 this.readElement(cfg.node);
26301 this.updateElement(cfg.node);
26303 Roo.apply(this, cfg);
26306 for(var r = 0; r < this.no_row; r++) {
26308 for(var c = 0; c < this.no_col; c++) {
26309 this.rows[r][c] = this.emptyCell();
26316 Roo.extend(Roo.htmleditor.BlockTable, Roo.htmleditor.Block, {
26325 // used by context menu
26326 friendly_name : 'Table',
26327 deleteTitle : 'Delete Table',
26328 // context menu is drawn once..
26330 contextMenu : function(toolbar)
26333 var block = function() {
26334 return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
26338 var rooui = typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
26340 var syncValue = toolbar.editorcore.syncValue;
26346 xtype : 'TextItem',
26348 xns : rooui.Toolbar //Boostrap?
26351 xtype : 'ComboBox',
26352 allowBlank : false,
26353 displayField : 'val',
26356 triggerAction : 'all',
26358 valueField : 'val',
26362 select : function (combo, r, index)
26364 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26366 b.width = r.get('val');
26369 toolbar.editorcore.onEditorEvent();
26374 xtype : 'SimpleStore',
26386 xtype : 'TextItem',
26387 text : "Columns: ",
26388 xns : rooui.Toolbar //Boostrap?
26395 click : function (_self, e)
26397 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26398 block().removeColumn();
26400 toolbar.editorcore.onEditorEvent();
26403 xns : rooui.Toolbar
26409 click : function (_self, e)
26411 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26412 block().addColumn();
26414 toolbar.editorcore.onEditorEvent();
26417 xns : rooui.Toolbar
26421 xtype : 'TextItem',
26423 xns : rooui.Toolbar //Boostrap?
26430 click : function (_self, e)
26432 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26433 block().removeRow();
26435 toolbar.editorcore.onEditorEvent();
26438 xns : rooui.Toolbar
26444 click : function (_self, e)
26448 toolbar.editorcore.onEditorEvent();
26451 xns : rooui.Toolbar
26456 text: 'Reset Column Widths',
26459 click : function (_self, e)
26461 block().resetWidths();
26463 toolbar.editorcore.onEditorEvent();
26466 xns : rooui.Toolbar
26477 * create a DomHelper friendly object - for use with
26478 * Roo.DomHelper.markup / overwrite / etc..
26479 * ?? should it be called with option to hide all editing features?
26481 toObject : function()
26486 contenteditable : 'false', // this stops cell selection from picking the table.
26487 'data-block' : 'Table',
26490 border : 'solid 1px #000', // ??? hard coded?
26491 'border-collapse' : 'collapse'
26494 { tag : 'tbody' , cn : [] }
26498 // do we have a head = not really
26500 Roo.each(this.rows, function( row ) {
26505 border : 'solid 1px #000',
26511 ret.cn[0].cn.push(tr);
26512 // does the row have any properties? ?? height?
26514 Roo.each(row, function( cell ) {
26518 contenteditable : 'true',
26519 'data-block' : 'Td',
26523 if (cell.colspan > 1) {
26524 td.colspan = cell.colspan ;
26525 nc += cell.colspan;
26529 if (cell.rowspan > 1) {
26530 td.rowspan = cell.rowspan ;
26539 ncols = Math.max(nc, ncols);
26543 // add the header row..
26552 readElement : function(node)
26554 node = node ? node : this.node ;
26555 this.width = this.getVal(node, true, 'style', 'width') || '100%';
26559 var trs = Array.from(node.rows);
26560 trs.forEach(function(tr) {
26562 this.rows.push(row);
26566 Array.from(tr.cells).forEach(function(td) {
26569 colspan : td.hasAttribute('colspan') ? td.getAttribute('colspan')*1 : 1,
26570 rowspan : td.hasAttribute('rowspan') ? td.getAttribute('rowspan')*1 : 1,
26571 style : td.hasAttribute('style') ? td.getAttribute('style') : '',
26572 html : td.innerHTML
26574 no_column += add.colspan;
26581 this.no_col = Math.max(this.no_col, no_column);
26588 normalizeRows: function()
26592 this.rows.forEach(function(row) {
26595 row = this.normalizeRow(row);
26597 row.forEach(function(c) {
26598 while (typeof(ret[rid][cid]) != 'undefined') {
26601 if (typeof(ret[rid]) == 'undefined') {
26607 if (c.rowspan < 2) {
26611 for(var i = 1 ;i < c.rowspan; i++) {
26612 if (typeof(ret[rid+i]) == 'undefined') {
26615 ret[rid+i][cid] = c;
26623 normalizeRow: function(row)
26626 row.forEach(function(c) {
26627 if (c.colspan < 2) {
26631 for(var i =0 ;i < c.colspan; i++) {
26639 deleteColumn : function(sel)
26641 if (!sel || sel.type != 'col') {
26644 if (this.no_col < 2) {
26648 this.rows.forEach(function(row) {
26649 var cols = this.normalizeRow(row);
26650 var col = cols[sel.col];
26651 if (col.colspan > 1) {
26661 removeColumn : function()
26663 this.deleteColumn({
26665 col : this.no_col-1
26667 this.updateElement();
26671 addColumn : function()
26674 this.rows.forEach(function(row) {
26675 row.push(this.emptyCell());
26678 this.updateElement();
26681 deleteRow : function(sel)
26683 if (!sel || sel.type != 'row') {
26687 if (this.no_row < 2) {
26691 var rows = this.normalizeRows();
26694 rows[sel.row].forEach(function(col) {
26695 if (col.rowspan > 1) {
26698 col.remove = 1; // flage it as removed.
26703 this.rows.forEach(function(row) {
26705 row.forEach(function(c) {
26706 if (typeof(c.remove) == 'undefined') {
26711 if (newrow.length > 0) {
26715 this.rows = newrows;
26720 this.updateElement();
26723 removeRow : function()
26727 row : this.no_row-1
26733 addRow : function()
26737 for (var i = 0; i < this.no_col; i++ ) {
26739 row.push(this.emptyCell());
26742 this.rows.push(row);
26743 this.updateElement();
26747 // the default cell object... at present...
26748 emptyCell : function() {
26749 return (new Roo.htmleditor.BlockTd({})).toObject();
26754 removeNode : function()
26761 resetWidths : function()
26763 Array.from(this.node.getElementsByTagName('td')).forEach(function(n) {
26764 var nn = Roo.htmleditor.Block.factory(n);
26766 nn.updateElement(n);
26779 * since selections really work on the table cell, then editing really should work from there
26781 * The original plan was to support merging etc... - but that may not be needed yet..
26783 * So this simple version will support:
26785 * adjust the width +/-
26786 * reset the width...
26795 * @class Roo.htmleditor.BlockTable
26796 * Block that manages a table
26799 * Create a new Filter.
26800 * @param {Object} config Configuration options
26803 Roo.htmleditor.BlockTd = function(cfg)
26806 this.readElement(cfg.node);
26807 this.updateElement(cfg.node);
26809 Roo.apply(this, cfg);
26814 Roo.extend(Roo.htmleditor.BlockTd, Roo.htmleditor.Block, {
26819 textAlign : 'left',
26826 // used by context menu
26827 friendly_name : 'Table Cell',
26828 deleteTitle : false, // use our customer delete
26830 // context menu is drawn once..
26832 contextMenu : function(toolbar)
26835 var cell = function() {
26836 return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
26839 var table = function() {
26840 return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode.closest('table'));
26844 var saveSel = function()
26846 lr = toolbar.editorcore.getSelection().getRangeAt(0);
26848 var restoreSel = function()
26852 toolbar.editorcore.focus();
26853 var cr = toolbar.editorcore.getSelection();
26854 cr.removeAllRanges();
26856 toolbar.editorcore.onEditorEvent();
26857 }).defer(10, this);
26863 var rooui = typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
26865 var syncValue = toolbar.editorcore.syncValue;
26872 text : 'Edit Table',
26874 click : function() {
26875 var t = toolbar.tb.selectedNode.closest('table');
26876 toolbar.editorcore.selectNode(t);
26877 toolbar.editorcore.onEditorEvent();
26886 xtype : 'TextItem',
26887 text : "Column Width: ",
26888 xns : rooui.Toolbar
26895 click : function (_self, e)
26897 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26898 cell().shrinkColumn();
26900 toolbar.editorcore.onEditorEvent();
26903 xns : rooui.Toolbar
26909 click : function (_self, e)
26911 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26912 cell().growColumn();
26914 toolbar.editorcore.onEditorEvent();
26917 xns : rooui.Toolbar
26921 xtype : 'TextItem',
26922 text : "Vertical Align: ",
26923 xns : rooui.Toolbar //Boostrap?
26926 xtype : 'ComboBox',
26927 allowBlank : false,
26928 displayField : 'val',
26931 triggerAction : 'all',
26933 valueField : 'val',
26937 select : function (combo, r, index)
26939 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26941 b.valign = r.get('val');
26944 toolbar.editorcore.onEditorEvent();
26949 xtype : 'SimpleStore',
26953 ['bottom'] // there are afew more...
26961 xtype : 'TextItem',
26962 text : "Merge Cells: ",
26963 xns : rooui.Toolbar
26972 click : function (_self, e)
26974 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26975 cell().mergeRight();
26976 //block().growColumn();
26978 toolbar.editorcore.onEditorEvent();
26981 xns : rooui.Toolbar
26988 click : function (_self, e)
26990 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26991 cell().mergeBelow();
26992 //block().growColumn();
26994 toolbar.editorcore.onEditorEvent();
26997 xns : rooui.Toolbar
27000 xtype : 'TextItem',
27002 xns : rooui.Toolbar
27010 click : function (_self, e)
27012 //toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
27015 toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
27016 toolbar.editorcore.onEditorEvent();
27020 xns : rooui.Toolbar
27024 xns : rooui.Toolbar
27033 xns : rooui.Toolbar,
27042 click : function (_self, e)
27046 cell().deleteColumn();
27048 toolbar.editorcore.selectNode(t.node);
27049 toolbar.editorcore.onEditorEvent();
27058 click : function (_self, e)
27061 cell().deleteRow();
27064 toolbar.editorcore.selectNode(t.node);
27065 toolbar.editorcore.onEditorEvent();
27072 xtype : 'Separator',
27079 click : function (_self, e)
27082 var nn = t.node.nextSibling || t.node.previousSibling;
27083 t.node.parentNode.removeChild(t.node);
27085 toolbar.editorcore.selectNode(nn, true);
27087 toolbar.editorcore.onEditorEvent();
27097 // align... << fixme
27105 * create a DomHelper friendly object - for use with
27106 * Roo.DomHelper.markup / overwrite / etc..
27107 * ?? should it be called with option to hide all editing features?
27110 * create a DomHelper friendly object - for use with
27111 * Roo.DomHelper.markup / overwrite / etc..
27112 * ?? should it be called with option to hide all editing features?
27114 toObject : function()
27118 contenteditable : 'true', // this stops cell selection from picking the table.
27119 'data-block' : 'Td',
27120 valign : this.valign,
27122 'text-align' : this.textAlign,
27123 border : 'solid 1px rgb(0, 0, 0)', // ??? hard coded?
27124 'border-collapse' : 'collapse',
27125 padding : '6px', // 8 for desktop / 4 for mobile
27126 'vertical-align': this.valign
27130 if (this.width != '') {
27131 ret.width = this.width;
27132 ret.style.width = this.width;
27136 if (this.colspan > 1) {
27137 ret.colspan = this.colspan ;
27139 if (this.rowspan > 1) {
27140 ret.rowspan = this.rowspan ;
27149 readElement : function(node)
27151 node = node ? node : this.node ;
27152 this.width = node.style.width;
27153 this.colspan = Math.max(1,1*node.getAttribute('colspan'));
27154 this.rowspan = Math.max(1,1*node.getAttribute('rowspan'));
27155 this.html = node.innerHTML;
27156 if (node.style.textAlign != '') {
27157 this.textAlign = node.style.textAlign;
27163 // the default cell object... at present...
27164 emptyCell : function() {
27168 textAlign : 'left',
27169 html : " " // is this going to be editable now?
27174 removeNode : function()
27176 return this.node.closest('table');
27184 toTableArray : function()
27187 var tab = this.node.closest('tr').closest('table');
27188 Array.from(tab.rows).forEach(function(r, ri){
27192 this.colWidths = [];
27193 var all_auto = true;
27194 Array.from(tab.rows).forEach(function(r, ri){
27197 Array.from(r.cells).forEach(function(ce, ci){
27202 colspan : ce.colSpan,
27203 rowspan : ce.rowSpan
27205 if (ce.isEqualNode(this.node)) {
27208 // if we have been filled up by a row?
27209 if (typeof(ret[rn][cn]) != 'undefined') {
27210 while(typeof(ret[rn][cn]) != 'undefined') {
27216 if (typeof(this.colWidths[cn]) == 'undefined' && c.colspan < 2) {
27217 this.colWidths[cn] = ce.style.width;
27218 if (this.colWidths[cn] != '') {
27224 if (c.colspan < 2 && c.rowspan < 2 ) {
27229 for(var j = 0; j < c.rowspan; j++) {
27230 if (typeof(ret[rn+j]) == 'undefined') {
27231 continue; // we have a problem..
27234 for(var i = 0; i < c.colspan; i++) {
27235 ret[rn+j][cn+i] = c;
27244 // initalize widths.?
27245 // either all widths or no widths..
27247 this.colWidths[0] = false; // no widths flag.
27258 mergeRight: function()
27261 // get the contents of the next cell along..
27262 var tr = this.node.closest('tr');
27263 var i = Array.prototype.indexOf.call(tr.childNodes, this.node);
27264 if (i >= tr.childNodes.length - 1) {
27265 return; // no cells on right to merge with.
27267 var table = this.toTableArray();
27269 if (typeof(table[this.cellData.row][this.cellData.col+this.cellData.colspan]) == 'undefined') {
27270 return; // nothing right?
27272 var rc = table[this.cellData.row][this.cellData.col+this.cellData.colspan];
27273 // right cell - must be same rowspan and on the same row.
27274 if (rc.rowspan != this.cellData.rowspan || rc.row != this.cellData.row) {
27275 return; // right hand side is not same rowspan.
27280 this.node.innerHTML += ' ' + rc.cell.innerHTML;
27281 tr.removeChild(rc.cell);
27282 this.colspan += rc.colspan;
27283 this.node.setAttribute('colspan', this.colspan);
27285 var table = this.toTableArray();
27286 this.normalizeWidths(table);
27287 this.updateWidths(table);
27291 mergeBelow : function()
27293 var table = this.toTableArray();
27294 if (typeof(table[this.cellData.row+this.cellData.rowspan]) == 'undefined') {
27295 return; // no row below
27297 if (typeof(table[this.cellData.row+this.cellData.rowspan][this.cellData.col]) == 'undefined') {
27298 return; // nothing right?
27300 var rc = table[this.cellData.row+this.cellData.rowspan][this.cellData.col];
27302 if (rc.colspan != this.cellData.colspan || rc.col != this.cellData.col) {
27303 return; // right hand side is not same rowspan.
27305 this.node.innerHTML = this.node.innerHTML + rc.cell.innerHTML ;
27306 rc.cell.parentNode.removeChild(rc.cell);
27307 this.rowspan += rc.rowspan;
27308 this.node.setAttribute('rowspan', this.rowspan);
27313 if (this.node.rowSpan < 2 && this.node.colSpan < 2) {
27316 var table = this.toTableArray();
27317 var cd = this.cellData;
27321 for(var r = cd.row; r < cd.row + cd.rowspan; r++) {
27324 for(var c = cd.col; c < cd.col + cd.colspan; c++) {
27325 if (r == cd.row && c == cd.col) {
27326 this.node.removeAttribute('rowspan');
27327 this.node.removeAttribute('colspan');
27330 var ntd = this.node.cloneNode(); // which col/row should be 0..
27331 ntd.removeAttribute('id');
27332 ntd.style.width = this.colWidths[c];
27333 ntd.innerHTML = '';
27334 table[r][c] = { cell : ntd, col : c, row: r , colspan : 1 , rowspan : 1 };
27338 this.redrawAllCells(table);
27344 redrawAllCells: function(table)
27348 var tab = this.node.closest('tr').closest('table');
27349 var ctr = tab.rows[0].parentNode;
27350 Array.from(tab.rows).forEach(function(r, ri){
27352 Array.from(r.cells).forEach(function(ce, ci){
27353 ce.parentNode.removeChild(ce);
27355 r.parentNode.removeChild(r);
27357 for(var r = 0 ; r < table.length; r++) {
27358 var re = tab.rows[r];
27360 var re = tab.ownerDocument.createElement('tr');
27361 ctr.appendChild(re);
27362 for(var c = 0 ; c < table[r].length; c++) {
27363 if (table[r][c].cell === false) {
27367 re.appendChild(table[r][c].cell);
27369 table[r][c].cell = false;
27374 updateWidths : function(table)
27376 for(var r = 0 ; r < table.length; r++) {
27378 for(var c = 0 ; c < table[r].length; c++) {
27379 if (table[r][c].cell === false) {
27383 if (this.colWidths[0] != false && table[r][c].colspan < 2) {
27384 var el = Roo.htmleditor.Block.factory(table[r][c].cell);
27385 el.width = Math.floor(this.colWidths[c]) +'%';
27386 el.updateElement(el.node);
27388 if (this.colWidths[0] != false && table[r][c].colspan > 1) {
27389 var el = Roo.htmleditor.Block.factory(table[r][c].cell);
27392 for(var i = 0; i < table[r][c].colspan; i ++) {
27393 if (typeof(this.colWidths[c + i]) != 'undefined') {
27394 lv = this.colWidths[c + i];
27396 this.colWidths[c + i] = lv;
27398 width += Math.floor(this.colWidths[c + i]);
27400 el.width = width +'%';
27401 el.updateElement(el.node);
27403 table[r][c].cell = false; // done
27407 normalizeWidths : function(table)
27409 if (this.colWidths[0] === false) {
27410 var nw = 100.0 / this.colWidths.length;
27411 this.colWidths.forEach(function(w,i) {
27412 this.colWidths[i] = nw;
27417 var t = 0, missing = [];
27419 this.colWidths.forEach(function(w,i) {
27421 this.colWidths[i] = this.colWidths[i] == '' ? 0 : (this.colWidths[i]+'').replace(/[^0-9]+/g,'')*1;
27422 var add = this.colWidths[i];
27431 var nc = this.colWidths.length;
27432 if (missing.length) {
27433 var mult = (nc - missing.length) / (1.0 * nc);
27435 var ew = (100 -t) / (1.0 * missing.length);
27436 this.colWidths.forEach(function(w,i) {
27438 this.colWidths[i] = w * mult;
27442 this.colWidths[i] = ew;
27444 // have to make up numbers..
27447 // now we should have all the widths..
27452 shrinkColumn : function()
27454 var table = this.toTableArray();
27455 this.normalizeWidths(table);
27456 var col = this.cellData.col;
27457 var nw = this.colWidths[col] * 0.8;
27461 var otherAdd = (this.colWidths[col] * 0.2) / (this.colWidths.length -1);
27462 this.colWidths.forEach(function(w,i) {
27464 this.colWidths[i] = nw;
27467 if (typeof(this.colWidths[i]) == 'undefined') {
27468 this.colWidths[i] = otherAdd;
27470 this.colWidths[i] += otherAdd;
27473 this.updateWidths(table);
27476 growColumn : function()
27478 var table = this.toTableArray();
27479 this.normalizeWidths(table);
27480 var col = this.cellData.col;
27481 var nw = this.colWidths[col] * 1.2;
27485 var otherSub = (this.colWidths[col] * 0.2) / (this.colWidths.length -1);
27486 this.colWidths.forEach(function(w,i) {
27488 this.colWidths[i] = nw;
27491 if (typeof(this.colWidths[i]) == 'undefined') {
27492 this.colWidths[i] = otherSub;
27494 this.colWidths[i] -= otherSub;
27498 this.updateWidths(table);
27501 deleteRow : function()
27503 // delete this rows 'tr'
27504 // if any of the cells in this row have a rowspan > 1 && row!= this row..
27505 // then reduce the rowspan.
27506 var table = this.toTableArray();
27507 // this.cellData.row;
27508 for (var i =0;i< table[this.cellData.row].length ; i++) {
27509 var c = table[this.cellData.row][i];
27510 if (c.row != this.cellData.row) {
27513 c.cell.setAttribute('rowspan', c.rowspan);
27516 if (c.rowspan > 1) {
27518 c.cell.setAttribute('rowspan', c.rowspan);
27521 table.splice(this.cellData.row,1);
27522 this.redrawAllCells(table);
27525 deleteColumn : function()
27527 var table = this.toTableArray();
27529 for (var i =0;i< table.length ; i++) {
27530 var c = table[i][this.cellData.col];
27531 if (c.col != this.cellData.col) {
27532 table[i][this.cellData.col].colspan--;
27533 } else if (c.colspan > 1) {
27535 c.cell.setAttribute('colspan', c.colspan);
27537 table[i].splice(this.cellData.col,1);
27540 this.redrawAllCells(table);
27548 //<script type="text/javascript">
27551 * Based Ext JS Library 1.1.1
27552 * Copyright(c) 2006-2007, Ext JS, LLC.
27558 * @class Roo.HtmlEditorCore
27559 * @extends Roo.Component
27560 * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
27562 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
27565 Roo.HtmlEditorCore = function(config){
27568 Roo.HtmlEditorCore.superclass.constructor.call(this, config);
27573 * @event initialize
27574 * Fires when the editor is fully initialized (including the iframe)
27575 * @param {Roo.HtmlEditorCore} this
27580 * Fires when the editor is first receives the focus. Any insertion must wait
27581 * until after this event.
27582 * @param {Roo.HtmlEditorCore} this
27586 * @event beforesync
27587 * Fires before the textarea is updated with content from the editor iframe. Return false
27588 * to cancel the sync.
27589 * @param {Roo.HtmlEditorCore} this
27590 * @param {String} html
27594 * @event beforepush
27595 * Fires before the iframe editor is updated with content from the textarea. Return false
27596 * to cancel the push.
27597 * @param {Roo.HtmlEditorCore} this
27598 * @param {String} html
27603 * Fires when the textarea is updated with content from the editor iframe.
27604 * @param {Roo.HtmlEditorCore} this
27605 * @param {String} html
27610 * Fires when the iframe editor is updated with content from the textarea.
27611 * @param {Roo.HtmlEditorCore} this
27612 * @param {String} html
27617 * @event editorevent
27618 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
27619 * @param {Roo.HtmlEditorCore} this
27626 // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
27628 // defaults : white / black...
27629 this.applyBlacklists();
27636 Roo.extend(Roo.HtmlEditorCore, Roo.Component, {
27640 * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field
27646 * @cfg {String} css styling for resizing. (used on bootstrap only)
27650 * @cfg {Number} height (in pixels)
27654 * @cfg {Number} width (in pixels)
27658 * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
27659 * if you are doing an email editor, this probably needs disabling, it's designed
27664 * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
27666 enableBlocks : true,
27668 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
27671 stylesheets: false,
27673 * @cfg {String} language default en - language of text (usefull for rtl languages)
27679 * @cfg {boolean} allowComments - default false - allow comments in HTML source
27680 * - by default they are stripped - if you are editing email you may need this.
27682 allowComments: false,
27686 // private properties
27687 validationEvent : false,
27689 initialized : false,
27691 sourceEditMode : false,
27692 onFocus : Roo.emptyFn,
27694 hideMode:'offsets',
27698 // blacklist + whitelisted elements..
27705 undoManager : false,
27707 * Protected method that will not generally be called directly. It
27708 * is called when the editor initializes the iframe with HTML contents. Override this method if you
27709 * want to change the initialization markup of the iframe (e.g. to add stylesheets).
27711 getDocMarkup : function(){
27715 // inherit styels from page...??
27716 if (this.stylesheets === false) {
27718 Roo.get(document.head).select('style').each(function(node) {
27719 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
27722 Roo.get(document.head).select('link').each(function(node) {
27723 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
27726 } else if (!this.stylesheets.length) {
27728 st = '<style type="text/css">' +
27729 'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
27732 for (var i in this.stylesheets) {
27733 if (typeof(this.stylesheets[i]) != 'string') {
27736 st += '<link rel="stylesheet" href="' + this.stylesheets[i] +'" type="text/css">';
27741 st += '<style type="text/css">' +
27742 'IMG { cursor: pointer } ' +
27745 st += '<meta name="google" content="notranslate">';
27747 var cls = 'notranslate roo-htmleditor-body';
27749 if(this.bodyCls.length){
27750 cls += ' ' + this.bodyCls;
27753 return '<html class="notranslate" translate="no"><head>' + st +
27754 //<style type="text/css">' +
27755 //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
27757 ' </head><body contenteditable="true" data-enable-grammerly="true" class="' + cls + '"></body></html>';
27761 onRender : function(ct, position)
27764 //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
27765 this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
27768 this.el.dom.style.border = '0 none';
27769 this.el.dom.setAttribute('tabIndex', -1);
27770 this.el.addClass('x-hidden hide');
27774 if(Roo.isIE){ // fix IE 1px bogus margin
27775 this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
27779 this.frameId = Roo.id();
27783 cls: 'form-control', // bootstrap..
27785 name: this.frameId,
27786 frameBorder : 'no',
27787 'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL : "javascript:false"
27790 ifcfg.style = { resize : this.resize };
27793 var iframe = this.owner.wrap.createChild(ifcfg, this.el);
27796 this.iframe = iframe.dom;
27798 this.assignDocWin();
27800 this.doc.designMode = 'on';
27803 this.doc.write(this.getDocMarkup());
27807 var task = { // must defer to wait for browser to be ready
27809 //console.log("run task?" + this.doc.readyState);
27810 this.assignDocWin();
27811 if(this.doc.body || this.doc.readyState == 'complete'){
27813 this.doc.designMode="on";
27818 Roo.TaskMgr.stop(task);
27819 this.initEditor.defer(10, this);
27826 Roo.TaskMgr.start(task);
27831 onResize : function(w, h)
27833 Roo.log('resize: ' +w + ',' + h );
27834 //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
27838 if(typeof w == 'number'){
27840 this.iframe.style.width = w + 'px';
27842 if(typeof h == 'number'){
27844 this.iframe.style.height = h + 'px';
27846 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
27853 * Toggles the editor between standard and source edit mode.
27854 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
27856 toggleSourceEdit : function(sourceEditMode){
27858 this.sourceEditMode = sourceEditMode === true;
27860 if(this.sourceEditMode){
27862 Roo.get(this.iframe).addClass(['x-hidden','hide', 'd-none']); //FIXME - what's the BS styles for these
27865 Roo.get(this.iframe).removeClass(['x-hidden','hide', 'd-none']);
27866 //this.iframe.className = '';
27869 //this.setSize(this.owner.wrap.getSize());
27870 //this.fireEvent('editmodechange', this, this.sourceEditMode);
27877 * Protected method that will not generally be called directly. If you need/want
27878 * custom HTML cleanup, this is the method you should override.
27879 * @param {String} html The HTML to be cleaned
27880 * return {String} The cleaned HTML
27882 cleanHtml : function(html)
27884 html = String(html);
27885 if(html.length > 5){
27886 if(Roo.isSafari){ // strip safari nonsense
27887 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
27890 if(html == ' '){
27897 * HTML Editor -> Textarea
27898 * Protected method that will not generally be called directly. Syncs the contents
27899 * of the editor iframe with the textarea.
27901 syncValue : function()
27903 //Roo.log("HtmlEditorCore:syncValue (EDITOR->TEXT)");
27904 if(this.initialized){
27906 if (this.undoManager) {
27907 this.undoManager.addEvent();
27911 var bd = (this.doc.body || this.doc.documentElement);
27914 var sel = this.win.getSelection();
27916 var div = document.createElement('div');
27917 div.innerHTML = bd.innerHTML;
27918 var gtx = div.getElementsByClassName('gtx-trans-icon'); // google translate - really annoying and difficult to get rid of.
27919 if (gtx.length > 0) {
27920 var rm = gtx.item(0).parentNode;
27921 rm.parentNode.removeChild(rm);
27925 if (this.enableBlocks) {
27926 Array.from(bd.getElementsByTagName('img')).forEach(function(img) {
27927 var fig = img.closest('figure');
27929 var bf = new Roo.htmleditor.BlockFigure({
27932 bf.updateElement();
27936 new Roo.htmleditor.FilterBlock({ node : div });
27939 var html = div.innerHTML;
27942 if (this.autoClean) {
27943 new Roo.htmleditor.FilterBlack({ node : div, tag : this.black});
27944 new Roo.htmleditor.FilterAttributes({
27954 'data-caption-display',
27967 attrib_clean : ['href', 'src' ]
27969 new Roo.htmleditor.FilterEmpty({ node : div});
27971 var tidy = new Roo.htmleditor.TidySerializer({
27974 html = tidy.serialize(div);
27980 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
27981 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
27983 html = '<div style="'+m[0]+'">' + html + '</div>';
27986 html = this.cleanHtml(html);
27987 // fix up the special chars.. normaly like back quotes in word...
27988 // however we do not want to do this with chinese..
27989 html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
27991 var cc = match.charCodeAt();
27993 // Get the character value, handling surrogate pairs
27994 if (match.length == 2) {
27995 // It's a surrogate pair, calculate the Unicode code point
27996 var high = match.charCodeAt(0) - 0xD800;
27997 var low = match.charCodeAt(1) - 0xDC00;
27998 cc = (high * 0x400) + low + 0x10000;
28000 (cc >= 0x4E00 && cc < 0xA000 ) ||
28001 (cc >= 0x3400 && cc < 0x4E00 ) ||
28002 (cc >= 0xf900 && cc < 0xfb00 )
28007 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
28008 return "&#" + cc + ";";
28015 if(this.owner.fireEvent('beforesync', this, html) !== false){
28016 this.el.dom.value = html;
28017 this.owner.fireEvent('sync', this, html);
28023 * TEXTAREA -> EDITABLE
28024 * Protected method that will not generally be called directly. Pushes the value of the textarea
28025 * into the iframe editor.
28027 pushValue : function()
28029 //Roo.log("HtmlEditorCore:pushValue (TEXT->EDITOR)");
28030 if(this.initialized){
28031 var v = this.el.dom.value.trim();
28034 if(this.owner.fireEvent('beforepush', this, v) !== false){
28035 var d = (this.doc.body || this.doc.documentElement);
28038 this.el.dom.value = d.innerHTML;
28039 this.owner.fireEvent('push', this, v);
28041 if (this.autoClean) {
28042 new Roo.htmleditor.FilterParagraph({node : this.doc.body}); // paragraphs
28043 new Roo.htmleditor.FilterSpan({node : this.doc.body}); // empty spans
28045 if (this.enableBlocks) {
28046 Roo.htmleditor.Block.initAll(this.doc.body);
28049 this.updateLanguage();
28051 var lc = this.doc.body.lastChild;
28052 if (lc && lc.nodeType == 1 && lc.getAttribute("contenteditable") == "false") {
28053 // add an extra line at the end.
28054 this.doc.body.appendChild(this.doc.createElement('br'));
28062 deferFocus : function(){
28063 this.focus.defer(10, this);
28067 focus : function(){
28068 if(this.win && !this.sourceEditMode){
28075 assignDocWin: function()
28077 var iframe = this.iframe;
28080 this.doc = iframe.contentWindow.document;
28081 this.win = iframe.contentWindow;
28083 // if (!Roo.get(this.frameId)) {
28086 // this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
28087 // this.win = Roo.get(this.frameId).dom.contentWindow;
28089 if (!Roo.get(this.frameId) && !iframe.contentDocument) {
28093 this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
28094 this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
28099 initEditor : function(){
28100 //console.log("INIT EDITOR");
28101 this.assignDocWin();
28105 this.doc.designMode="on";
28107 this.doc.write(this.getDocMarkup());
28110 var dbody = (this.doc.body || this.doc.documentElement);
28111 //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
28112 // this copies styles from the containing element into thsi one..
28113 // not sure why we need all of this..
28114 //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
28116 //var ss = this.el.getStyles( 'background-image', 'background-repeat');
28117 //ss['background-attachment'] = 'fixed'; // w3c
28118 dbody.bgProperties = 'fixed'; // ie
28119 dbody.setAttribute("translate", "no");
28121 //Roo.DomHelper.applyStyles(dbody, ss);
28122 Roo.EventManager.on(this.doc, {
28124 'mouseup': this.onEditorEvent,
28125 'dblclick': this.onEditorEvent,
28126 'click': this.onEditorEvent,
28127 'keyup': this.onEditorEvent,
28132 Roo.EventManager.on(this.doc, {
28133 'paste': this.onPasteEvent,
28137 Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
28140 if(Roo.isIE || Roo.isSafari || Roo.isOpera){
28141 Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
28143 this.initialized = true;
28146 // initialize special key events - enter
28147 new Roo.htmleditor.KeyEnter({core : this});
28151 this.owner.fireEvent('initialize', this);
28154 // this is to prevent a href clicks resulting in a redirect?
28156 onPasteEvent : function(e,v)
28158 // I think we better assume paste is going to be a dirty load of rubish from word..
28160 // even pasting into a 'email version' of this widget will have to clean up that mess.
28161 var cd = (e.browserEvent.clipboardData || window.clipboardData);
28163 // check what type of paste - if it's an image, then handle it differently.
28164 if (cd.files && cd.files.length > 0 && cd.types.indexOf('text/html') < 0) {
28166 var urlAPI = (window.createObjectURL && window) ||
28167 (window.URL && URL.revokeObjectURL && URL) ||
28168 (window.webkitURL && webkitURL);
28170 var r = new FileReader();
28172 r.addEventListener('load',function()
28175 var d = (new DOMParser().parseFromString('<img src="' + r.result+ '">', 'text/html')).body;
28176 // is insert asycn?
28177 if (t.enableBlocks) {
28179 Array.from(d.getElementsByTagName('img')).forEach(function(img) {
28180 if (img.closest('figure')) { // assume!! that it's aready
28183 var fig = new Roo.htmleditor.BlockFigure({
28184 image_src : img.src
28186 fig.updateElement(img); // replace it..
28190 t.insertAtCursor(d.innerHTML.replace(/ /g,' '));
28191 t.owner.fireEvent('paste', this);
28193 r.readAsDataURL(cd.files[0]);
28195 e.preventDefault();
28199 if (cd.types.indexOf('text/html') < 0 ) {
28203 var html = cd.getData('text/html'); // clipboard event
28204 if (cd.types.indexOf('text/rtf') > -1) {
28205 var parser = new Roo.rtf.Parser(cd.getData('text/rtf'));
28206 images = parser.doc ? parser.doc.getElementsByType('pict') : [];
28208 // Roo.log(images);
28211 images = images.filter(function(g) { return !g.path.match(/^rtf\/(head|pgdsctbl|listtable|footerf)/); }) // ignore headers/footers etc.
28212 .map(function(g) { return g.toDataURL(); })
28213 .filter(function(g) { return g != 'about:blank'; });
28216 html = this.cleanWordChars(html);
28218 var d = (new DOMParser().parseFromString(html, 'text/html')).body;
28221 var sn = this.getParentElement();
28222 // check if d contains a table, and prevent nesting??
28223 //Roo.log(d.getElementsByTagName('table'));
28225 //Roo.log(sn.closest('table'));
28226 if (d.getElementsByTagName('table').length && sn && sn.closest('table')) {
28227 e.preventDefault();
28228 this.insertAtCursor("You can not nest tables");
28229 //Roo.log("prevent?"); // fixme -
28235 if (images.length > 0) {
28236 // replace all v:imagedata - with img.
28237 var ar = Array.from(d.getElementsByTagName('v:imagedata'));
28238 Roo.each(ar, function(node) {
28239 node.parentNode.insertBefore(d.ownerDocument.createElement('img'), node );
28240 node.parentNode.removeChild(node);
28244 Roo.each(d.getElementsByTagName('img'), function(img, i) {
28245 img.setAttribute('src', images[i]);
28248 if (this.autoClean) {
28249 new Roo.htmleditor.FilterWord({ node : d });
28251 new Roo.htmleditor.FilterStyleToTag({ node : d });
28252 new Roo.htmleditor.FilterAttributes({
28261 /* THESE ARE NOT ALLWOED FOR PASTE
28263 'data-caption-display',
28277 attrib_clean : ['href', 'src' ]
28279 new Roo.htmleditor.FilterBlack({ node : d, tag : this.black});
28280 // should be fonts..
28281 new Roo.htmleditor.FilterKeepChildren({node : d, tag : [ 'FONT', ':' ]} );
28282 new Roo.htmleditor.FilterParagraph({ node : d });
28283 new Roo.htmleditor.FilterHashLink({node : d});
28284 new Roo.htmleditor.FilterSpan({ node : d });
28285 new Roo.htmleditor.FilterLongBr({ node : d });
28286 new Roo.htmleditor.FilterComment({ node : d });
28287 new Roo.htmleditor.FilterEmpty({ node : d});
28291 if (this.enableBlocks) {
28293 Array.from(d.getElementsByTagName('img')).forEach(function(img) {
28294 if (img.closest('figure')) { // assume!! that it's aready
28297 var fig = new Roo.htmleditor.BlockFigure({
28298 image_src : img.src
28300 fig.updateElement(img); // replace it..
28306 this.insertAtCursor(d.innerHTML.replace(/ /g,' '));
28307 if (this.enableBlocks) {
28308 Roo.htmleditor.Block.initAll(this.doc.body);
28312 e.preventDefault();
28313 this.owner.fireEvent('paste', this);
28315 // default behaveiour should be our local cleanup paste? (optional?)
28316 // for simple editor - we want to hammer the paste and get rid of everything... - so over-rideable..
28317 //this.owner.fireEvent('paste', e, v);
28320 onDestroy : function(){
28326 //for (var i =0; i < this.toolbars.length;i++) {
28327 // // fixme - ask toolbars for heights?
28328 // this.toolbars[i].onDestroy();
28331 //this.wrap.dom.innerHTML = '';
28332 //this.wrap.remove();
28337 onFirstFocus : function(){
28339 this.assignDocWin();
28340 this.undoManager = new Roo.lib.UndoManager(100,(this.doc.body || this.doc.documentElement));
28342 this.activated = true;
28345 if(Roo.isGecko){ // prevent silly gecko errors
28347 var s = this.win.getSelection();
28348 if(!s.focusNode || s.focusNode.nodeType != 3){
28349 var r = s.getRangeAt(0);
28350 r.selectNodeContents((this.doc.body || this.doc.documentElement));
28355 this.execCmd('useCSS', true);
28356 this.execCmd('styleWithCSS', false);
28359 this.owner.fireEvent('activate', this);
28363 adjustFont: function(btn){
28364 var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
28365 //if(Roo.isSafari){ // safari
28368 var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
28369 if(Roo.isSafari){ // safari
28370 var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
28371 v = (v < 10) ? 10 : v;
28372 v = (v > 48) ? 48 : v;
28373 v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
28378 v = Math.max(1, v+adjust);
28380 this.execCmd('FontSize', v );
28383 onEditorEvent : function(e)
28387 if (e && (e.ctrlKey || e.metaKey) && e.keyCode === 90) {
28388 return; // we do not handle this.. (undo manager does..)
28390 // clicking a 'block'?
28392 // in theory this detects if the last element is not a br, then we try and do that.
28393 // its so clicking in space at bottom triggers adding a br and moving the cursor.
28395 e.target.nodeName == 'BODY' &&
28396 e.type == "mouseup" &&
28397 this.doc.body.lastChild
28399 var lc = this.doc.body.lastChild;
28400 // gtx-trans is google translate plugin adding crap.
28401 while ((lc.nodeType == 3 && lc.nodeValue == '') || lc.id == 'gtx-trans') {
28402 lc = lc.previousSibling;
28404 if (lc.nodeType == 1 && lc.nodeName != 'BR') {
28405 // if last element is <BR> - then dont do anything.
28407 var ns = this.doc.createElement('br');
28408 this.doc.body.appendChild(ns);
28409 range = this.doc.createRange();
28410 range.setStartAfter(ns);
28411 range.collapse(true);
28412 var sel = this.win.getSelection();
28413 sel.removeAllRanges();
28414 sel.addRange(range);
28420 this.fireEditorEvent(e);
28421 // this.updateToolbar();
28422 this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
28425 fireEditorEvent: function(e)
28427 this.owner.fireEvent('editorevent', this, e);
28430 insertTag : function(tg)
28432 // could be a bit smarter... -> wrap the current selected tRoo..
28433 if (tg.toLowerCase() == 'span' ||
28434 tg.toLowerCase() == 'code' ||
28435 tg.toLowerCase() == 'sup' ||
28436 tg.toLowerCase() == 'sub'
28439 range = this.createRange(this.getSelection());
28440 var wrappingNode = this.doc.createElement(tg.toLowerCase());
28441 wrappingNode.appendChild(range.extractContents());
28442 range.insertNode(wrappingNode);
28449 this.execCmd("formatblock", tg);
28450 this.undoManager.addEvent();
28453 insertText : function(txt)
28457 var range = this.createRange();
28458 range.deleteContents();
28459 //alert(Sender.getAttribute('label'));
28461 range.insertNode(this.doc.createTextNode(txt));
28462 this.undoManager.addEvent();
28468 * Executes a Midas editor command on the editor document and performs necessary focus and
28469 * toolbar updates. <b>This should only be called after the editor is initialized.</b>
28470 * @param {String} cmd The Midas command
28471 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
28473 relayCmd : function(cmd, value)
28477 case 'justifyleft':
28478 case 'justifyright':
28479 case 'justifycenter':
28480 // if we are in a cell, then we will adjust the
28481 var n = this.getParentElement();
28482 var td = n.closest('td');
28484 var bl = Roo.htmleditor.Block.factory(td);
28485 bl.textAlign = cmd.replace('justify','');
28486 bl.updateElement();
28487 this.owner.fireEvent('editorevent', this);
28490 this.execCmd('styleWithCSS', true); //
28495 // if there is no selection, then we insert, and set the curson inside it..
28496 this.execCmd('styleWithCSS', false);
28506 this.execCmd(cmd, value);
28507 this.owner.fireEvent('editorevent', this);
28508 //this.updateToolbar();
28509 this.owner.deferFocus();
28513 * Executes a Midas editor command directly on the editor document.
28514 * For visual commands, you should use {@link #relayCmd} instead.
28515 * <b>This should only be called after the editor is initialized.</b>
28516 * @param {String} cmd The Midas command
28517 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
28519 execCmd : function(cmd, value){
28520 this.doc.execCommand(cmd, false, value === undefined ? null : value);
28527 * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
28529 * @param {String} text | dom node..
28531 insertAtCursor : function(text)
28534 if(!this.activated){
28538 if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
28542 // from jquery ui (MIT licenced)
28544 var win = this.win;
28546 if (win.getSelection && win.getSelection().getRangeAt) {
28548 // delete the existing?
28550 this.createRange(this.getSelection()).deleteContents();
28551 range = win.getSelection().getRangeAt(0);
28552 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
28553 range.insertNode(node);
28554 range = range.cloneRange();
28555 range.collapse(false);
28557 win.getSelection().removeAllRanges();
28558 win.getSelection().addRange(range);
28562 } else if (win.document.selection && win.document.selection.createRange) {
28563 // no firefox support
28564 var txt = typeof(text) == 'string' ? text : text.outerHTML;
28565 win.document.selection.createRange().pasteHTML(txt);
28568 // no firefox support
28569 var txt = typeof(text) == 'string' ? text : text.outerHTML;
28570 this.execCmd('InsertHTML', txt);
28578 mozKeyPress : function(e){
28580 var c = e.getCharCode(), cmd;
28583 c = String.fromCharCode(c).toLowerCase();
28597 // this.cleanUpPaste.defer(100, this);
28603 this.relayCmd(cmd);
28604 //this.win.focus();
28605 //this.execCmd(cmd);
28606 //this.deferFocus();
28607 e.preventDefault();
28615 fixKeys : function(){ // load time branching for fastest keydown performance
28619 return function(e){
28620 var k = e.getKey(), r;
28623 r = this.doc.selection.createRange();
28626 r.pasteHTML('    ');
28631 /// this is handled by Roo.htmleditor.KeyEnter
28634 r = this.doc.selection.createRange();
28636 var target = r.parentElement();
28637 if(!target || target.tagName.toLowerCase() != 'li'){
28639 r.pasteHTML('<br/>');
28646 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
28647 // this.cleanUpPaste.defer(100, this);
28653 }else if(Roo.isOpera){
28654 return function(e){
28655 var k = e.getKey();
28659 this.execCmd('InsertHTML','    ');
28663 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
28664 // this.cleanUpPaste.defer(100, this);
28669 }else if(Roo.isSafari){
28670 return function(e){
28671 var k = e.getKey();
28675 this.execCmd('InsertText','\t');
28679 this.mozKeyPress(e);
28681 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
28682 // this.cleanUpPaste.defer(100, this);
28690 getAllAncestors: function()
28692 var p = this.getSelectedNode();
28695 a.push(p); // push blank onto stack..
28696 p = this.getParentElement();
28700 while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
28704 a.push(this.doc.body);
28708 lastSelNode : false,
28711 getSelection : function()
28713 this.assignDocWin();
28714 return Roo.lib.Selection.wrap(Roo.isIE ? this.doc.selection : this.win.getSelection(), this.doc);
28717 * Select a dom node
28718 * @param {DomElement} node the node to select
28720 selectNode : function(node, collapse)
28722 var nodeRange = node.ownerDocument.createRange();
28724 nodeRange.selectNode(node);
28726 nodeRange.selectNodeContents(node);
28728 if (collapse === true) {
28729 nodeRange.collapse(true);
28732 var s = this.win.getSelection();
28733 s.removeAllRanges();
28734 s.addRange(nodeRange);
28737 getSelectedNode: function()
28739 // this may only work on Gecko!!!
28741 // should we cache this!!!!
28745 var range = this.createRange(this.getSelection()).cloneRange();
28748 var parent = range.parentElement();
28750 var testRange = range.duplicate();
28751 testRange.moveToElementText(parent);
28752 if (testRange.inRange(range)) {
28755 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
28758 parent = parent.parentElement;
28763 // is ancestor a text element.
28764 var ac = range.commonAncestorContainer;
28765 if (ac.nodeType == 3) {
28766 ac = ac.parentNode;
28769 var ar = ac.childNodes;
28772 var other_nodes = [];
28773 var has_other_nodes = false;
28774 for (var i=0;i<ar.length;i++) {
28775 if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ?
28778 // fullly contained node.
28780 if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
28785 // probably selected..
28786 if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
28787 other_nodes.push(ar[i]);
28791 if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0)) {
28796 has_other_nodes = true;
28798 if (!nodes.length && other_nodes.length) {
28799 nodes= other_nodes;
28801 if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
28809 createRange: function(sel)
28811 // this has strange effects when using with
28812 // top toolbar - not sure if it's a great idea.
28813 //this.editor.contentWindow.focus();
28814 if (typeof sel != "undefined") {
28816 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
28818 return this.doc.createRange();
28821 return this.doc.createRange();
28824 getParentElement: function()
28827 this.assignDocWin();
28828 var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
28830 var range = this.createRange(sel);
28833 var p = range.commonAncestorContainer;
28834 while (p.nodeType == 3) { // text node
28845 * Range intersection.. the hard stuff...
28849 * [ -- selected range --- ]
28853 * if end is before start or hits it. fail.
28854 * if start is after end or hits it fail.
28856 * if either hits (but other is outside. - then it's not
28862 // @see http://www.thismuchiknow.co.uk/?p=64.
28863 rangeIntersectsNode : function(range, node)
28865 var nodeRange = node.ownerDocument.createRange();
28867 nodeRange.selectNode(node);
28869 nodeRange.selectNodeContents(node);
28872 var rangeStartRange = range.cloneRange();
28873 rangeStartRange.collapse(true);
28875 var rangeEndRange = range.cloneRange();
28876 rangeEndRange.collapse(false);
28878 var nodeStartRange = nodeRange.cloneRange();
28879 nodeStartRange.collapse(true);
28881 var nodeEndRange = nodeRange.cloneRange();
28882 nodeEndRange.collapse(false);
28884 return rangeStartRange.compareBoundaryPoints(
28885 Range.START_TO_START, nodeEndRange) == -1 &&
28886 rangeEndRange.compareBoundaryPoints(
28887 Range.START_TO_START, nodeStartRange) == 1;
28891 rangeCompareNode : function(range, node)
28893 var nodeRange = node.ownerDocument.createRange();
28895 nodeRange.selectNode(node);
28897 nodeRange.selectNodeContents(node);
28901 range.collapse(true);
28903 nodeRange.collapse(true);
28905 var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
28906 var ee = range.compareBoundaryPoints( Range.END_TO_END, nodeRange);
28908 //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
28910 var nodeIsBefore = ss == 1;
28911 var nodeIsAfter = ee == -1;
28913 if (nodeIsBefore && nodeIsAfter) {
28916 if (!nodeIsBefore && nodeIsAfter) {
28917 return 1; //right trailed.
28920 if (nodeIsBefore && !nodeIsAfter) {
28921 return 2; // left trailed.
28927 cleanWordChars : function(input) {// change the chars to hex code
28930 [ 8211, "–" ],
28931 [ 8212, "—" ],
28939 var output = input;
28940 Roo.each(swapCodes, function(sw) {
28941 var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
28943 output = output.replace(swapper, sw[1]);
28953 cleanUpChild : function (node)
28956 new Roo.htmleditor.FilterComment({node : node});
28957 new Roo.htmleditor.FilterAttributes({
28959 attrib_black : this.ablack,
28960 attrib_clean : this.aclean,
28961 style_white : this.cwhite,
28962 style_black : this.cblack
28964 new Roo.htmleditor.FilterBlack({ node : node, tag : this.black});
28965 new Roo.htmleditor.FilterKeepChildren({node : node, tag : this.tag_remove} );
28971 * Clean up MS wordisms...
28972 * @deprecated - use filter directly
28974 cleanWord : function(node)
28976 new Roo.htmleditor.FilterWord({ node : node ? node : this.doc.body });
28977 new Roo.htmleditor.FilterKeepChildren({node : node ? node : this.doc.body, tag : [ 'FONT', ':' ]} );
28984 * @deprecated - use filters
28986 cleanTableWidths : function(node)
28988 new Roo.htmleditor.FilterTableWidth({ node : node ? node : this.doc.body});
28995 applyBlacklists : function()
28997 var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white : [];
28998 var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black : [];
29000 this.aclean = typeof(this.owner.aclean) != 'undefined' && this.owner.aclean ? this.owner.aclean : Roo.HtmlEditorCore.aclean;
29001 this.ablack = typeof(this.owner.ablack) != 'undefined' && this.owner.ablack ? this.owner.ablack : Roo.HtmlEditorCore.ablack;
29002 this.tag_remove = typeof(this.owner.tag_remove) != 'undefined' && this.owner.tag_remove ? this.owner.tag_remove : Roo.HtmlEditorCore.tag_remove;
29006 Roo.each(Roo.HtmlEditorCore.white, function(tag) {
29007 if (b.indexOf(tag) > -1) {
29010 this.white.push(tag);
29014 Roo.each(w, function(tag) {
29015 if (b.indexOf(tag) > -1) {
29018 if (this.white.indexOf(tag) > -1) {
29021 this.white.push(tag);
29026 Roo.each(Roo.HtmlEditorCore.black, function(tag) {
29027 if (w.indexOf(tag) > -1) {
29030 this.black.push(tag);
29034 Roo.each(b, function(tag) {
29035 if (w.indexOf(tag) > -1) {
29038 if (this.black.indexOf(tag) > -1) {
29041 this.black.push(tag);
29046 w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite : [];
29047 b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack : [];
29051 Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
29052 if (b.indexOf(tag) > -1) {
29055 this.cwhite.push(tag);
29059 Roo.each(w, function(tag) {
29060 if (b.indexOf(tag) > -1) {
29063 if (this.cwhite.indexOf(tag) > -1) {
29066 this.cwhite.push(tag);
29071 Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
29072 if (w.indexOf(tag) > -1) {
29075 this.cblack.push(tag);
29079 Roo.each(b, function(tag) {
29080 if (w.indexOf(tag) > -1) {
29083 if (this.cblack.indexOf(tag) > -1) {
29086 this.cblack.push(tag);
29091 setStylesheets : function(stylesheets)
29093 if(typeof(stylesheets) == 'string'){
29094 Roo.get(this.iframe.contentDocument.head).createChild({
29096 rel : 'stylesheet',
29105 Roo.each(stylesheets, function(s) {
29110 Roo.get(_this.iframe.contentDocument.head).createChild({
29112 rel : 'stylesheet',
29122 updateLanguage : function()
29124 if (!this.iframe || !this.iframe.contentDocument) {
29127 Roo.get(this.iframe.contentDocument.body).attr("lang", this.language);
29131 removeStylesheets : function()
29135 Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
29140 setStyle : function(style)
29142 Roo.get(this.iframe.contentDocument.head).createChild({
29151 // hide stuff that is not compatible
29165 * @event specialkey
29169 * @cfg {String} fieldClass @hide
29172 * @cfg {String} focusClass @hide
29175 * @cfg {String} autoCreate @hide
29178 * @cfg {String} inputType @hide
29181 * @cfg {String} invalidClass @hide
29184 * @cfg {String} invalidText @hide
29187 * @cfg {String} msgFx @hide
29190 * @cfg {String} validateOnBlur @hide
29194 Roo.HtmlEditorCore.white = [
29195 'AREA', 'BR', 'IMG', 'INPUT', 'HR', 'WBR',
29197 'ADDRESS', 'BLOCKQUOTE', 'CENTER', 'DD', 'DIR', 'DIV',
29198 'DL', 'DT', 'H1', 'H2', 'H3', 'H4',
29199 'H5', 'H6', 'HR', 'ISINDEX', 'LISTING', 'MARQUEE',
29200 'MENU', 'MULTICOL', 'OL', 'P', 'PLAINTEXT', 'PRE',
29201 'TABLE', 'UL', 'XMP',
29203 'CAPTION', 'COL', 'COLGROUP', 'TBODY', 'TD', 'TFOOT', 'TH',
29206 'DIR', 'MENU', 'OL', 'UL', 'DL',
29212 Roo.HtmlEditorCore.black = [
29213 // 'embed', 'object', // enable - backend responsiblity to clean thiese
29215 'BASE', 'BASEFONT', 'BGSOUND', 'BLINK', 'BODY',
29216 'FRAME', 'FRAMESET', 'HEAD', 'HTML', 'ILAYER',
29217 'IFRAME', 'LAYER', 'LINK', 'META', 'OBJECT',
29218 'SCRIPT', 'STYLE' ,'TITLE', 'XML',
29219 //'FONT' // CLEAN LATER..
29220 'COLGROUP', 'COL' // messy tables.
29224 Roo.HtmlEditorCore.clean = [ // ?? needed???
29225 'SCRIPT', 'STYLE', 'TITLE', 'XML'
29227 Roo.HtmlEditorCore.tag_remove = [
29232 Roo.HtmlEditorCore.ablack = [
29236 Roo.HtmlEditorCore.aclean = [
29237 'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc'
29241 Roo.HtmlEditorCore.pwhite= [
29242 'http', 'https', 'mailto'
29245 // white listed style attributes.
29246 Roo.HtmlEditorCore.cwhite= [
29247 // 'text-align', /// default is to allow most things..
29253 // black listed style attributes.
29254 Roo.HtmlEditorCore.cblack= [
29255 // 'font-size' -- this can be set by the project
29261 //<script type="text/javascript">
29264 * Ext JS Library 1.1.1
29265 * Copyright(c) 2006-2007, Ext JS, LLC.
29271 Roo.form.HtmlEditor = function(config){
29275 Roo.form.HtmlEditor.superclass.constructor.call(this, config);
29277 if (!this.toolbars) {
29278 this.toolbars = [];
29280 this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
29286 * @class Roo.form.HtmlEditor
29287 * @extends Roo.form.Field
29288 * Provides a lightweight HTML Editor component.
29290 * This has been tested on Fireforx / Chrome.. IE may not be so great..
29292 * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
29293 * supported by this editor.</b><br/><br/>
29294 * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
29295 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
29297 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
29299 * @cfg {Boolean} clearUp
29303 * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
29308 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
29313 * @cfg {Number} height (in pixels)
29317 * @cfg {Number} width (in pixels)
29322 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets - this is usally a good idea rootURL + '/roojs1/css/undoreset.css', .
29325 stylesheets: false,
29329 * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
29334 * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
29340 * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
29345 * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
29350 * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
29352 allowComments: false,
29354 * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
29356 enableBlocks : true,
29359 * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
29360 * if you are doing an email editor, this probably needs disabling, it's designed
29364 * @cfg {string} bodyCls default '' default classes to add to body of editable area - usually undoreset is a good start..
29368 * @cfg {String} language default en - language of text (usefull for rtl languages)
29377 // private properties
29378 validationEvent : false,
29380 initialized : false,
29383 onFocus : Roo.emptyFn,
29385 hideMode:'offsets',
29387 actionMode : 'container', // defaults to hiding it...
29389 defaultAutoCreate : { // modified by initCompnoent..
29391 style:"width:500px;height:300px;",
29392 autocomplete: "new-password"
29396 initComponent : function(){
29399 * @event initialize
29400 * Fires when the editor is fully initialized (including the iframe)
29401 * @param {HtmlEditor} this
29406 * Fires when the editor is first receives the focus. Any insertion must wait
29407 * until after this event.
29408 * @param {HtmlEditor} this
29412 * @event beforesync
29413 * Fires before the textarea is updated with content from the editor iframe. Return false
29414 * to cancel the sync.
29415 * @param {HtmlEditor} this
29416 * @param {String} html
29420 * @event beforepush
29421 * Fires before the iframe editor is updated with content from the textarea. Return false
29422 * to cancel the push.
29423 * @param {HtmlEditor} this
29424 * @param {String} html
29429 * Fires when the textarea is updated with content from the editor iframe.
29430 * @param {HtmlEditor} this
29431 * @param {String} html
29436 * Fires when the iframe editor is updated with content from the textarea.
29437 * @param {HtmlEditor} this
29438 * @param {String} html
29442 * @event editmodechange
29443 * Fires when the editor switches edit modes
29444 * @param {HtmlEditor} this
29445 * @param {Boolean} sourceEdit True if source edit, false if standard editing.
29447 editmodechange: true,
29449 * @event editorevent
29450 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
29451 * @param {HtmlEditor} this
29455 * @event firstfocus
29456 * Fires when on first focus - needed by toolbars..
29457 * @param {HtmlEditor} this
29462 * Auto save the htmlEditor value as a file into Events
29463 * @param {HtmlEditor} this
29467 * @event savedpreview
29468 * preview the saved version of htmlEditor
29469 * @param {HtmlEditor} this
29471 savedpreview: true,
29474 * @event stylesheetsclick
29475 * Fires when press the Sytlesheets button
29476 * @param {Roo.HtmlEditorCore} this
29478 stylesheetsclick: true,
29481 * Fires when press user pastes into the editor
29482 * @param {Roo.HtmlEditorCore} this
29487 this.defaultAutoCreate = {
29489 style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
29490 autocomplete: "new-password"
29495 * Protected method that will not generally be called directly. It
29496 * is called when the editor creates its toolbar. Override this method if you need to
29497 * add custom toolbar buttons.
29498 * @param {HtmlEditor} editor
29500 createToolbar : function(editor){
29501 Roo.log("create toolbars");
29502 if (!editor.toolbars || !editor.toolbars.length) {
29503 editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
29506 for (var i =0 ; i < editor.toolbars.length;i++) {
29507 editor.toolbars[i] = Roo.factory(
29508 typeof(editor.toolbars[i]) == 'string' ?
29509 { xtype: editor.toolbars[i]} : editor.toolbars[i],
29510 Roo.form.HtmlEditor);
29511 editor.toolbars[i].init(editor);
29517 * get the Context selected node
29518 * @returns {DomElement|boolean} selected node if active or false if none
29521 getSelectedNode : function()
29523 if (this.toolbars.length < 2 || !this.toolbars[1].tb) {
29526 return this.toolbars[1].tb.selectedNode;
29530 onRender : function(ct, position)
29533 Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
29535 this.wrap = this.el.wrap({
29536 cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
29539 this.editorcore.onRender(ct, position);
29541 if (this.resizable) {
29542 this.resizeEl = new Roo.Resizable(this.wrap, {
29546 minHeight : this.height,
29547 height: this.height,
29548 handles : this.resizable,
29551 resize : function(r, w, h) {
29552 _t.onResize(w,h); // -something
29558 this.createToolbar(this);
29562 this.setSize(this.wrap.getSize());
29564 if (this.resizeEl) {
29565 this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
29566 // should trigger onReize..
29569 this.keyNav = new Roo.KeyNav(this.el, {
29571 "tab" : function(e){
29572 e.preventDefault();
29574 var value = this.getValue();
29576 var start = this.el.dom.selectionStart;
29577 var end = this.el.dom.selectionEnd;
29581 this.setValue(value.substring(0, start) + "\t" + value.substring(end));
29582 this.el.dom.setSelectionRange(end + 1, end + 1);
29586 var f = value.substring(0, start).split("\t");
29588 if(f.pop().length != 0){
29592 this.setValue(f.join("\t") + value.substring(end));
29593 this.el.dom.setSelectionRange(start - 1, start - 1);
29597 "home" : function(e){
29598 e.preventDefault();
29600 var curr = this.el.dom.selectionStart;
29601 var lines = this.getValue().split("\n");
29608 this.el.dom.setSelectionRange(0, 0);
29614 for (var i = 0; i < lines.length;i++) {
29615 pos += lines[i].length;
29625 pos -= lines[i].length;
29631 this.el.dom.setSelectionRange(pos, pos);
29635 this.el.dom.selectionStart = pos;
29636 this.el.dom.selectionEnd = curr;
29639 "end" : function(e){
29640 e.preventDefault();
29642 var curr = this.el.dom.selectionStart;
29643 var lines = this.getValue().split("\n");
29650 this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
29656 for (var i = 0; i < lines.length;i++) {
29658 pos += lines[i].length;
29672 this.el.dom.setSelectionRange(pos, pos);
29676 this.el.dom.selectionStart = curr;
29677 this.el.dom.selectionEnd = pos;
29682 doRelay : function(foo, bar, hname){
29683 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
29689 // if(this.autosave && this.w){
29690 // this.autoSaveFn = setInterval(this.autosave, 1000);
29695 onResize : function(w, h)
29697 Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
29702 if(typeof w == 'number'){
29703 var aw = w - this.wrap.getFrameWidth('lr');
29704 this.el.setWidth(this.adjustWidth('textarea', aw));
29707 if(typeof h == 'number'){
29709 for (var i =0; i < this.toolbars.length;i++) {
29710 // fixme - ask toolbars for heights?
29711 tbh += this.toolbars[i].tb.el.getHeight();
29712 if (this.toolbars[i].footer) {
29713 tbh += this.toolbars[i].footer.el.getHeight();
29720 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
29721 ah -= 5; // knock a few pixes off for look..
29723 this.el.setHeight(this.adjustWidth('textarea', ah));
29727 Roo.log('onResize:' + [w,h,ew,eh].join(',') );
29728 this.editorcore.onResize(ew,eh);
29733 * Toggles the editor between standard and source edit mode.
29734 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
29736 toggleSourceEdit : function(sourceEditMode)
29738 this.editorcore.toggleSourceEdit(sourceEditMode);
29740 if(this.editorcore.sourceEditMode){
29741 Roo.log('editor - showing textarea');
29744 // Roo.log(this.syncValue());
29745 this.editorcore.syncValue();
29746 this.el.removeClass('x-hidden');
29747 this.el.dom.removeAttribute('tabIndex');
29749 this.el.dom.scrollTop = 0;
29752 for (var i = 0; i < this.toolbars.length; i++) {
29753 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
29754 this.toolbars[i].tb.hide();
29755 this.toolbars[i].footer.hide();
29760 Roo.log('editor - hiding textarea');
29762 // Roo.log(this.pushValue());
29763 this.editorcore.pushValue();
29765 this.el.addClass('x-hidden');
29766 this.el.dom.setAttribute('tabIndex', -1);
29768 for (var i = 0; i < this.toolbars.length; i++) {
29769 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
29770 this.toolbars[i].tb.show();
29771 this.toolbars[i].footer.show();
29775 //this.deferFocus();
29778 this.setSize(this.wrap.getSize());
29779 this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
29781 this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
29784 // private (for BoxComponent)
29785 adjustSize : Roo.BoxComponent.prototype.adjustSize,
29787 // private (for BoxComponent)
29788 getResizeEl : function(){
29792 // private (for BoxComponent)
29793 getPositionEl : function(){
29798 initEvents : function(){
29799 this.originalValue = this.getValue();
29803 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
29806 markInvalid : Roo.emptyFn,
29808 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
29811 clearInvalid : Roo.emptyFn,
29813 setValue : function(v){
29814 Roo.form.HtmlEditor.superclass.setValue.call(this, v);
29815 this.editorcore.pushValue();
29819 * update the language in the body - really done by core
29820 * @param {String} language - eg. en / ar / zh-CN etc..
29822 updateLanguage : function(lang)
29824 this.language = lang;
29825 this.editorcore.language = lang;
29826 this.editorcore.updateLanguage();
29830 deferFocus : function(){
29831 this.focus.defer(10, this);
29835 focus : function(){
29836 this.editorcore.focus();
29842 onDestroy : function(){
29848 for (var i =0; i < this.toolbars.length;i++) {
29849 // fixme - ask toolbars for heights?
29850 this.toolbars[i].onDestroy();
29853 this.wrap.dom.innerHTML = '';
29854 this.wrap.remove();
29859 onFirstFocus : function(){
29860 //Roo.log("onFirstFocus");
29861 this.editorcore.onFirstFocus();
29862 for (var i =0; i < this.toolbars.length;i++) {
29863 this.toolbars[i].onFirstFocus();
29869 syncValue : function()
29871 this.editorcore.syncValue();
29874 pushValue : function()
29876 this.editorcore.pushValue();
29879 setStylesheets : function(stylesheets)
29881 this.editorcore.setStylesheets(stylesheets);
29884 removeStylesheets : function()
29886 this.editorcore.removeStylesheets();
29890 // hide stuff that is not compatible
29904 * @event specialkey
29908 * @cfg {String} fieldClass @hide
29911 * @cfg {String} focusClass @hide
29914 * @cfg {String} autoCreate @hide
29917 * @cfg {String} inputType @hide
29920 * @cfg {String} invalidClass @hide
29923 * @cfg {String} invalidText @hide
29926 * @cfg {String} msgFx @hide
29929 * @cfg {String} validateOnBlur @hide
29935 * Ext JS Library 1.1.1
29936 * Copyright(c) 2006-2007, Ext JS, LLC.
29942 * @class Roo.form.HtmlEditor.ToolbarStandard
29947 new Roo.form.HtmlEditor({
29950 new Roo.form.HtmlEditorToolbar1({
29951 disable : { fonts: 1 , format: 1, ..., ... , ...],
29957 * @cfg {Object} disable List of elements to disable..
29958 * @cfg {Roo.Toolbar.Item|Roo.Toolbar.Button|Roo.Toolbar.SplitButton|Roo.form.Field} btns[] List of additional buttons.
29962 * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
29965 Roo.form.HtmlEditor.ToolbarStandard = function(config)
29968 Roo.apply(this, config);
29970 // default disabled, based on 'good practice'..
29971 this.disable = this.disable || {};
29972 Roo.applyIf(this.disable, {
29975 specialElements : true
29979 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
29980 // dont call parent... till later.
29983 Roo.form.HtmlEditor.ToolbarStandard.prototype = {
29990 editorcore : false,
29992 * @cfg {Object} disable List of toolbar elements to disable
29999 * @cfg {String} createLinkText The default text for the create link prompt
30001 createLinkText : 'Please enter the URL for the link:',
30003 * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
30005 defaultLinkValue : 'http:/'+'/',
30009 * @cfg {Array} fontFamilies An array of available font families
30027 // "á" , ?? a acute?
30032 "°" // , // degrees
30034 // "é" , // e ecute
30035 // "ú" , // u ecute?
30038 specialElements : [
30040 text: "Insert Table",
30043 ihtml : '<table><tr><td>Cell</td></tr></table>'
30047 text: "Insert Image",
30050 ihtml : '<img src="about:blank"/>'
30059 "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password",
30060 "input:submit", "input:button", "select", "textarea", "label" ],
30063 ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"],
30065 ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
30074 * @cfg {String} defaultFont default font to use.
30076 defaultFont: 'tahoma',
30078 fontSelect : false,
30081 formatCombo : false,
30083 init : function(editor)
30085 this.editor = editor;
30086 this.editorcore = editor.editorcore ? editor.editorcore : editor;
30087 var editorcore = this.editorcore;
30091 var fid = editorcore.frameId;
30093 function btn(id, toggle, handler){
30094 var xid = fid + '-'+ id ;
30098 cls : 'x-btn-icon x-edit-'+id,
30099 enableToggle:toggle !== false,
30100 scope: _t, // was editor...
30101 handler:handler||_t.relayBtnCmd,
30102 clickEvent:'mousedown',
30103 tooltip: etb.buttonTips[id] || undefined, ///tips ???
30110 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
30112 // stop form submits
30113 tb.el.on('click', function(e){
30114 e.preventDefault(); // what does this do?
30117 if(!this.disable.font) { // && !Roo.isSafari){
30118 /* why no safari for fonts
30119 editor.fontSelect = tb.el.createChild({
30122 cls:'x-font-select',
30123 html: this.createFontOptions()
30126 editor.fontSelect.on('change', function(){
30127 var font = editor.fontSelect.dom.value;
30128 editor.relayCmd('fontname', font);
30129 editor.deferFocus();
30133 editor.fontSelect.dom,
30139 if(!this.disable.formats){
30140 this.formatCombo = new Roo.form.ComboBox({
30141 store: new Roo.data.SimpleStore({
30144 data : this.formats // from states.js
30148 //autoCreate : {tag: "div", size: "20"},
30149 displayField:'tag',
30153 triggerAction: 'all',
30154 emptyText:'Add tag',
30155 selectOnFocus:true,
30158 'select': function(c, r, i) {
30159 editorcore.insertTag(r.get('tag'));
30165 tb.addField(this.formatCombo);
30169 if(!this.disable.format){
30174 btn('strikethrough')
30177 if(!this.disable.fontSize){
30182 btn('increasefontsize', false, editorcore.adjustFont),
30183 btn('decreasefontsize', false, editorcore.adjustFont)
30188 if(!this.disable.colors){
30191 id:editorcore.frameId +'-forecolor',
30192 cls:'x-btn-icon x-edit-forecolor',
30193 clickEvent:'mousedown',
30194 tooltip: this.buttonTips['forecolor'] || undefined,
30196 menu : new Roo.menu.ColorMenu({
30197 allowReselect: true,
30198 focus: Roo.emptyFn,
30201 selectHandler: function(cp, color){
30202 editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
30203 editor.deferFocus();
30206 clickEvent:'mousedown'
30209 id:editorcore.frameId +'backcolor',
30210 cls:'x-btn-icon x-edit-backcolor',
30211 clickEvent:'mousedown',
30212 tooltip: this.buttonTips['backcolor'] || undefined,
30214 menu : new Roo.menu.ColorMenu({
30215 focus: Roo.emptyFn,
30218 allowReselect: true,
30219 selectHandler: function(cp, color){
30221 editorcore.execCmd('useCSS', false);
30222 editorcore.execCmd('hilitecolor', color);
30223 editorcore.execCmd('useCSS', true);
30224 editor.deferFocus();
30226 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor',
30227 Roo.isSafari || Roo.isIE ? '#'+color : color);
30228 editor.deferFocus();
30232 clickEvent:'mousedown'
30237 // now add all the items...
30240 if(!this.disable.alignments){
30243 btn('justifyleft'),
30244 btn('justifycenter'),
30245 btn('justifyright')
30249 //if(!Roo.isSafari){
30250 if(!this.disable.links){
30253 btn('createlink', false, this.createLink) /// MOVE TO HERE?!!?!?!?!
30257 if(!this.disable.lists){
30260 btn('insertorderedlist'),
30261 btn('insertunorderedlist')
30264 if(!this.disable.sourceEdit){
30267 btn('sourceedit', true, function(btn){
30268 this.toggleSourceEdit(btn.pressed);
30275 // special menu.. - needs to be tidied up..
30276 if (!this.disable.special) {
30279 cls: 'x-edit-none',
30285 for (var i =0; i < this.specialChars.length; i++) {
30286 smenu.menu.items.push({
30288 html: this.specialChars[i],
30289 handler: function(a,b) {
30290 editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
30291 //editor.insertAtCursor(a.html);
30305 if (!this.disable.cleanStyles) {
30307 cls: 'x-btn-icon x-btn-clear',
30313 for (var i =0; i < this.cleanStyles.length; i++) {
30314 cmenu.menu.items.push({
30315 actiontype : this.cleanStyles[i],
30316 html: 'Remove ' + this.cleanStyles[i],
30317 handler: function(a,b) {
30320 var c = Roo.get(editorcore.doc.body);
30321 c.select('[style]').each(function(s) {
30322 s.dom.style.removeProperty(a.actiontype);
30324 editorcore.syncValue();
30329 cmenu.menu.items.push({
30330 actiontype : 'tablewidths',
30331 html: 'Remove Table Widths',
30332 handler: function(a,b) {
30333 editorcore.cleanTableWidths();
30334 editorcore.syncValue();
30338 cmenu.menu.items.push({
30339 actiontype : 'word',
30340 html: 'Remove MS Word Formating',
30341 handler: function(a,b) {
30342 editorcore.cleanWord();
30343 editorcore.syncValue();
30348 cmenu.menu.items.push({
30349 actiontype : 'all',
30350 html: 'Remove All Styles',
30351 handler: function(a,b) {
30353 var c = Roo.get(editorcore.doc.body);
30354 c.select('[style]').each(function(s) {
30355 s.dom.removeAttribute('style');
30357 editorcore.syncValue();
30362 cmenu.menu.items.push({
30363 actiontype : 'all',
30364 html: 'Remove All CSS Classes',
30365 handler: function(a,b) {
30367 var c = Roo.get(editorcore.doc.body);
30368 c.select('[class]').each(function(s) {
30369 s.dom.removeAttribute('class');
30371 editorcore.cleanWord();
30372 editorcore.syncValue();
30377 cmenu.menu.items.push({
30378 actiontype : 'tidy',
30379 html: 'Tidy HTML Source',
30380 handler: function(a,b) {
30381 new Roo.htmleditor.Tidy(editorcore.doc.body);
30382 editorcore.syncValue();
30391 if (!this.disable.specialElements) {
30394 cls: 'x-edit-none',
30399 for (var i =0; i < this.specialElements.length; i++) {
30400 semenu.menu.items.push(
30402 handler: function(a,b) {
30403 editor.insertAtCursor(this.ihtml);
30405 }, this.specialElements[i])
30417 for(var i =0; i< this.btns.length;i++) {
30418 var b = Roo.factory(this.btns[i],this.btns[i].xns || Roo.form);
30419 b.cls = 'x-edit-none';
30421 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
30422 b.cls += ' x-init-enable';
30425 b.scope = editorcore;
30433 // disable everything...
30435 this.tb.items.each(function(item){
30438 item.id != editorcore.frameId+ '-sourceedit' &&
30439 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
30445 this.rendered = true;
30447 // the all the btns;
30448 editor.on('editorevent', this.updateToolbar, this);
30449 // other toolbars need to implement this..
30450 //editor.on('editmodechange', this.updateToolbar, this);
30454 relayBtnCmd : function(btn) {
30455 this.editorcore.relayCmd(btn.cmd);
30457 // private used internally
30458 createLink : function(){
30459 //Roo.log("create link?");
30460 var ec = this.editorcore;
30461 var ar = ec.getAllAncestors();
30463 for(var i = 0;i< ar.length;i++) {
30464 if (ar[i] && ar[i].nodeName == 'A') {
30472 Roo.MessageBox.show({
30473 title : "Add / Edit Link URL",
30474 msg : "Enter the url for the link",
30475 buttons: Roo.MessageBox.OKCANCEL,
30476 fn: function(btn, url){
30480 if(url && url != 'http:/'+'/'){
30482 n.setAttribute('href', url);
30484 ec.relayCmd('createlink', url);
30490 //multiline: multiline,
30492 value : n ? n.getAttribute('href') : ''
30496 }).defer(100, this); // we have to defer this , otherwise the mouse click gives focus to the main window.
30502 * Protected method that will not generally be called directly. It triggers
30503 * a toolbar update by reading the markup state of the current selection in the editor.
30505 updateToolbar: function(){
30507 if(!this.editorcore.activated){
30508 this.editor.onFirstFocus();
30512 var btns = this.tb.items.map,
30513 doc = this.editorcore.doc,
30514 frameId = this.editorcore.frameId;
30516 if(!this.disable.font && !Roo.isSafari){
30518 var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
30519 if(name != this.fontSelect.dom.value){
30520 this.fontSelect.dom.value = name;
30524 if(!this.disable.format){
30525 btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
30526 btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
30527 btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
30528 btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
30530 if(!this.disable.alignments){
30531 btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
30532 btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
30533 btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
30535 if(!Roo.isSafari && !this.disable.lists){
30536 btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
30537 btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
30540 var ans = this.editorcore.getAllAncestors();
30541 if (this.formatCombo) {
30544 var store = this.formatCombo.store;
30545 this.formatCombo.setValue("");
30546 for (var i =0; i < ans.length;i++) {
30547 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
30549 this.formatCombo.setValue(ans[i].tagName.toLowerCase());
30557 // hides menus... - so this cant be on a menu...
30558 Roo.menu.MenuMgr.hideAll();
30560 //this.editorsyncValue();
30564 createFontOptions : function(){
30565 var buf = [], fs = this.fontFamilies, ff, lc;
30569 for(var i = 0, len = fs.length; i< len; i++){
30571 lc = ff.toLowerCase();
30573 '<option value="',lc,'" style="font-family:',ff,';"',
30574 (this.defaultFont == lc ? ' selected="true">' : '>'),
30579 return buf.join('');
30582 toggleSourceEdit : function(sourceEditMode){
30584 Roo.log("toolbar toogle");
30585 if(sourceEditMode === undefined){
30586 sourceEditMode = !this.sourceEditMode;
30588 this.sourceEditMode = sourceEditMode === true;
30589 var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
30590 // just toggle the button?
30591 if(btn.pressed !== this.sourceEditMode){
30592 btn.toggle(this.sourceEditMode);
30596 if(sourceEditMode){
30597 Roo.log("disabling buttons");
30598 this.tb.items.each(function(item){
30599 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
30605 Roo.log("enabling buttons");
30606 if(this.editorcore.initialized){
30607 this.tb.items.each(function(item){
30610 // initialize 'blocks'
30611 Roo.each(Roo.get(this.editorcore.doc.body).query('*[data-block]'), function(e) {
30612 Roo.htmleditor.Block.factory(e).updateElement(e);
30618 Roo.log("calling toggole on editor");
30619 // tell the editor that it's been pressed..
30620 this.editor.toggleSourceEdit(sourceEditMode);
30624 * Object collection of toolbar tooltips for the buttons in the editor. The key
30625 * is the command id associated with that button and the value is a valid QuickTips object.
30630 title: 'Bold (Ctrl+B)',
30631 text: 'Make the selected text bold.',
30632 cls: 'x-html-editor-tip'
30635 title: 'Italic (Ctrl+I)',
30636 text: 'Make the selected text italic.',
30637 cls: 'x-html-editor-tip'
30645 title: 'Bold (Ctrl+B)',
30646 text: 'Make the selected text bold.',
30647 cls: 'x-html-editor-tip'
30650 title: 'Italic (Ctrl+I)',
30651 text: 'Make the selected text italic.',
30652 cls: 'x-html-editor-tip'
30655 title: 'Underline (Ctrl+U)',
30656 text: 'Underline the selected text.',
30657 cls: 'x-html-editor-tip'
30660 title: 'Strikethrough',
30661 text: 'Strikethrough the selected text.',
30662 cls: 'x-html-editor-tip'
30664 increasefontsize : {
30665 title: 'Grow Text',
30666 text: 'Increase the font size.',
30667 cls: 'x-html-editor-tip'
30669 decreasefontsize : {
30670 title: 'Shrink Text',
30671 text: 'Decrease the font size.',
30672 cls: 'x-html-editor-tip'
30675 title: 'Text Highlight Color',
30676 text: 'Change the background color of the selected text.',
30677 cls: 'x-html-editor-tip'
30680 title: 'Font Color',
30681 text: 'Change the color of the selected text.',
30682 cls: 'x-html-editor-tip'
30685 title: 'Align Text Left',
30686 text: 'Align text to the left.',
30687 cls: 'x-html-editor-tip'
30690 title: 'Center Text',
30691 text: 'Center text in the editor.',
30692 cls: 'x-html-editor-tip'
30695 title: 'Align Text Right',
30696 text: 'Align text to the right.',
30697 cls: 'x-html-editor-tip'
30699 insertunorderedlist : {
30700 title: 'Bullet List',
30701 text: 'Start a bulleted list.',
30702 cls: 'x-html-editor-tip'
30704 insertorderedlist : {
30705 title: 'Numbered List',
30706 text: 'Start a numbered list.',
30707 cls: 'x-html-editor-tip'
30710 title: 'Hyperlink',
30711 text: 'Make the selected text a hyperlink.',
30712 cls: 'x-html-editor-tip'
30715 title: 'Source Edit',
30716 text: 'Switch to source editing mode.',
30717 cls: 'x-html-editor-tip'
30721 onDestroy : function(){
30724 this.tb.items.each(function(item){
30726 item.menu.removeAll();
30728 item.menu.el.destroy();
30736 onFirstFocus: function() {
30737 this.tb.items.each(function(item){
30746 // <script type="text/javascript">
30749 * Ext JS Library 1.1.1
30750 * Copyright(c) 2006-2007, Ext JS, LLC.
30757 * @class Roo.form.HtmlEditor.ToolbarContext
30762 new Roo.form.HtmlEditor({
30765 { xtype: 'ToolbarStandard', styles : {} }
30766 { xtype: 'ToolbarContext', disable : {} }
30772 * @config : {Object} disable List of elements to disable.. (not done yet.)
30773 * @config : {Object} styles Map of styles available.
30777 Roo.form.HtmlEditor.ToolbarContext = function(config)
30780 Roo.apply(this, config);
30781 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
30782 // dont call parent... till later.
30783 this.styles = this.styles || {};
30788 Roo.form.HtmlEditor.ToolbarContext.types = {
30803 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
30829 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
30900 name : 'selectoptions',
30906 // should we really allow this??
30907 // should this just be
30924 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
30925 Roo.form.HtmlEditor.ToolbarContext.stores = false;
30927 Roo.form.HtmlEditor.ToolbarContext.options = {
30929 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
30930 [ 'Courier New', 'Courier New'],
30931 [ 'Tahoma', 'Tahoma'],
30932 [ 'Times New Roman,serif', 'Times'],
30933 [ 'Verdana','Verdana' ]
30937 // fixme - these need to be configurable..
30940 //Roo.form.HtmlEditor.ToolbarContext.types
30943 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype, {
30950 editorcore : false,
30952 * @cfg {Object} disable List of toolbar elements to disable
30957 * @cfg {Object} styles List of styles
30958 * eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] }
30960 * These must be defined in the page, so they get rendered correctly..
30971 init : function(editor)
30973 this.editor = editor;
30974 this.editorcore = editor.editorcore ? editor.editorcore : editor;
30975 var editorcore = this.editorcore;
30977 var fid = editorcore.frameId;
30979 function btn(id, toggle, handler){
30980 var xid = fid + '-'+ id ;
30984 cls : 'x-btn-icon x-edit-'+id,
30985 enableToggle:toggle !== false,
30986 scope: editorcore, // was editor...
30987 handler:handler||editorcore.relayBtnCmd,
30988 clickEvent:'mousedown',
30989 tooltip: etb.buttonTips[id] || undefined, ///tips ???
30993 // create a new element.
30994 var wdiv = editor.wrap.createChild({
30996 }, editor.wrap.dom.firstChild.nextSibling, true);
30998 // can we do this more than once??
31000 // stop form submits
31003 // disable everything...
31004 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
31005 this.toolbars = {};
31006 // block toolbars are built in updateToolbar when needed.
31007 for (var i in ty) {
31009 this.toolbars[i] = this.buildToolbar(ty[i],i);
31011 this.tb = this.toolbars.BODY;
31013 this.buildFooter();
31014 this.footer.show();
31015 editor.on('hide', function( ) { this.footer.hide() }, this);
31016 editor.on('show', function( ) { this.footer.show() }, this);
31019 this.rendered = true;
31021 // the all the btns;
31022 editor.on('editorevent', this.updateToolbar, this);
31023 // other toolbars need to implement this..
31024 //editor.on('editmodechange', this.updateToolbar, this);
31030 * Protected method that will not generally be called directly. It triggers
31031 * a toolbar update by reading the markup state of the current selection in the editor.
31033 * Note you can force an update by calling on('editorevent', scope, false)
31035 updateToolbar: function(editor ,ev, sel)
31039 ev.stopEvent(); // se if we can stop this looping with mutiple events.
31043 // capture mouse up - this is handy for selecting images..
31044 // perhaps should go somewhere else...
31045 if(!this.editorcore.activated){
31046 this.editor.onFirstFocus();
31049 //Roo.log(ev ? ev.target : 'NOTARGET');
31052 // http://developer.yahoo.com/yui/docs/simple-editor.js.html
31053 // selectNode - might want to handle IE?
31058 (ev.type == 'mouseup' || ev.type == 'click' ) &&
31059 ev.target && ev.target.tagName != 'BODY' ) { // && ev.target.tagName == 'IMG') {
31060 // they have click on an image...
31061 // let's see if we can change the selection...
31064 // this triggers looping?
31065 //this.editorcore.selectNode(sel);
31069 // this forces an id..
31070 Array.from(this.editorcore.doc.body.querySelectorAll('.roo-ed-selection')).forEach(function(e) {
31071 e.classList.remove('roo-ed-selection');
31073 //Roo.select('.roo-ed-selection', false, this.editorcore.doc).removeClass('roo-ed-selection');
31074 //Roo.get(node).addClass('roo-ed-selection');
31076 //var updateFooter = sel ? false : true;
31079 var ans = this.editorcore.getAllAncestors();
31082 var ty = Roo.form.HtmlEditor.ToolbarContext.types;
31085 sel = ans.length ? (ans[0] ? ans[0] : ans[1]) : this.editorcore.doc.body;
31086 sel = sel ? sel : this.editorcore.doc.body;
31087 sel = sel.tagName.length ? sel : this.editorcore.doc.body;
31091 var tn = sel.tagName.toUpperCase();
31092 var lastSel = this.tb.selectedNode;
31093 this.tb.selectedNode = sel;
31094 var left_label = tn;
31096 // ok see if we are editing a block?
31099 // you are not actually selecting the block.
31100 if (sel && sel.hasAttribute('data-block')) {
31102 } else if (sel && sel.closest('[data-block]')) {
31104 db = sel.closest('[data-block]');
31105 //var cepar = sel.closest('[contenteditable=true]');
31106 //if (db && cepar && cepar.tagName != 'BODY') {
31107 // db = false; // we are inside an editable block.. = not sure how we are going to handle nested blocks!?
31113 //if (db && !sel.hasAttribute('contenteditable') && sel.getAttribute('contenteditable') != 'true' ) {
31114 if (db && this.editorcore.enableBlocks) {
31115 block = Roo.htmleditor.Block.factory(db);
31120 db.classList.length > 0 ? db.className + ' ' : ''
31121 ) + 'roo-ed-selection';
31123 // since we removed it earlier... its not there..
31124 tn = 'BLOCK.' + db.getAttribute('data-block');
31126 //this.editorcore.selectNode(db);
31127 if (typeof(this.toolbars[tn]) == 'undefined') {
31128 this.toolbars[tn] = this.buildToolbar( false ,tn ,block.friendly_name, block);
31130 this.toolbars[tn].selectedNode = db;
31131 left_label = block.friendly_name;
31132 ans = this.editorcore.getAllAncestors();
31140 if (this.tb.name == tn && lastSel == this.tb.selectedNode && ev !== false) {
31141 return; // no change?
31147 ///console.log("show: " + tn);
31148 this.tb = typeof(this.toolbars[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
31152 this.tb.items.first().el.innerHTML = left_label + ': ';
31155 // update attributes
31156 if (block && this.tb.fields) {
31158 this.tb.fields.each(function(e) {
31159 e.setValue(block[e.name]);
31163 } else if (this.tb.fields && this.tb.selectedNode) {
31164 this.tb.fields.each( function(e) {
31166 e.setValue(this.tb.selectedNode.style[e.stylename]);
31169 e.setValue(this.tb.selectedNode.getAttribute(e.attrname));
31171 this.updateToolbarStyles(this.tb.selectedNode);
31176 Roo.menu.MenuMgr.hideAll();
31181 // update the footer
31183 this.updateFooter(ans);
31187 updateToolbarStyles : function(sel)
31189 var hasStyles = false;
31190 for(var i in this.styles) {
31196 if (hasStyles && this.tb.hasStyles) {
31197 var st = this.tb.fields.item(0);
31199 st.store.removeAll();
31200 var cn = sel.className.split(/\s+/);
31203 if (this.styles['*']) {
31205 Roo.each(this.styles['*'], function(v) {
31206 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
31209 if (this.styles[tn]) {
31210 Roo.each(this.styles[tn], function(v) {
31211 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
31215 st.store.loadData(avs);
31222 updateFooter : function(ans)
31225 if (ans === false) {
31226 this.footDisp.dom.innerHTML = '';
31230 this.footerEls = ans.reverse();
31231 Roo.each(this.footerEls, function(a,i) {
31232 if (!a) { return; }
31233 html += html.length ? ' > ' : '';
31235 html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
31240 var sz = this.footDisp.up('td').getSize();
31241 this.footDisp.dom.style.width = (sz.width -10) + 'px';
31242 this.footDisp.dom.style.marginLeft = '5px';
31244 this.footDisp.dom.style.overflow = 'hidden';
31246 this.footDisp.dom.innerHTML = html;
31253 onDestroy : function(){
31256 this.tb.items.each(function(item){
31258 item.menu.removeAll();
31260 item.menu.el.destroy();
31268 onFirstFocus: function() {
31269 // need to do this for all the toolbars..
31270 this.tb.items.each(function(item){
31274 buildToolbar: function(tlist, nm, friendly_name, block)
31276 var editor = this.editor;
31277 var editorcore = this.editorcore;
31278 // create a new element.
31279 var wdiv = editor.wrap.createChild({
31281 }, editor.wrap.dom.firstChild.nextSibling, true);
31284 var tb = new Roo.Toolbar(wdiv);
31285 ///this.tb = tb; // << this sets the active toolbar..
31286 if (tlist === false && block) {
31287 tlist = block.contextMenu(this);
31290 tb.hasStyles = false;
31293 tb.add((typeof(friendly_name) == 'undefined' ? nm : friendly_name) + ": ");
31295 var styles = Array.from(this.styles);
31299 if (styles && styles.length) {
31300 tb.hasStyles = true;
31301 // this needs a multi-select checkbox...
31302 tb.addField( new Roo.form.ComboBox({
31303 store: new Roo.data.SimpleStore({
31305 fields: ['val', 'selected'],
31308 name : '-roo-edit-className',
31309 attrname : 'className',
31310 displayField: 'val',
31314 triggerAction: 'all',
31315 emptyText:'Select Style',
31316 selectOnFocus:true,
31319 'select': function(c, r, i) {
31320 // initial support only for on class per el..
31321 tb.selectedNode.className = r ? r.get('val') : '';
31322 editorcore.syncValue();
31329 var tbc = Roo.form.HtmlEditor.ToolbarContext;
31332 for (var i = 0; i < tlist.length; i++) {
31334 // newer versions will use xtype cfg to create menus.
31335 if (typeof(tlist[i].xtype) != 'undefined') {
31337 tb[typeof(tlist[i].name)== 'undefined' ? 'add' : 'addField'](Roo.factory(tlist[i]));
31343 var item = tlist[i];
31344 tb.add(item.title + ": ");
31347 //optname == used so you can configure the options available..
31348 var opts = item.opts ? item.opts : false;
31349 if (item.optname) { // use the b
31350 opts = Roo.form.HtmlEditor.ToolbarContext.options[item.optname];
31355 // opts == pulldown..
31356 tb.addField( new Roo.form.ComboBox({
31357 store: typeof(tbc.stores[i]) != 'undefined' ? Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
31359 fields: ['val', 'display'],
31362 name : '-roo-edit-' + tlist[i].name,
31364 attrname : tlist[i].name,
31365 stylename : item.style ? item.style : false,
31367 displayField: item.displayField ? item.displayField : 'val',
31368 valueField : 'val',
31370 mode: typeof(tbc.stores[tlist[i].name]) != 'undefined' ? 'remote' : 'local',
31372 triggerAction: 'all',
31373 emptyText:'Select',
31374 selectOnFocus:true,
31375 width: item.width ? item.width : 130,
31377 'select': function(c, r, i) {
31381 tb.selectedNode.style[c.stylename] = r.get('val');
31382 editorcore.syncValue();
31386 tb.selectedNode.removeAttribute(c.attrname);
31387 editorcore.syncValue();
31390 tb.selectedNode.setAttribute(c.attrname, r.get('val'));
31391 editorcore.syncValue();
31400 tb.addField( new Roo.form.TextField({
31403 //allowBlank:false,
31409 tb.addField( new Roo.form.TextField({
31410 name: '-roo-edit-' + tlist[i].name,
31411 attrname : tlist[i].name,
31417 'change' : function(f, nv, ov) {
31420 tb.selectedNode.setAttribute(f.attrname, nv);
31421 editorcore.syncValue();
31429 var show_delete = !block || block.deleteTitle !== false;
31431 show_delete = false;
31435 text: 'Stylesheets',
31438 click : function ()
31440 _this.editor.fireEvent('stylesheetsclick', _this.editor);
31449 text: block && block.deleteTitle ? block.deleteTitle : 'Remove Block or Formating', // remove the tag, and puts the children outside...
31452 click : function ()
31454 var sn = tb.selectedNode;
31456 sn = Roo.htmleditor.Block.factory(tb.selectedNode).removeNode();
31462 var stn = sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
31463 if (sn.hasAttribute('data-block')) {
31464 stn = sn.nextSibling || sn.previousSibling || sn.parentNode;
31465 sn.parentNode.removeChild(sn);
31467 } else if (sn && sn.tagName != 'BODY') {
31468 // remove and keep parents.
31469 a = new Roo.htmleditor.FilterKeepChildren({tag : false});
31474 var range = editorcore.createRange();
31476 range.setStart(stn,0);
31477 range.setEnd(stn,0);
31478 var selection = editorcore.getSelection();
31479 selection.removeAllRanges();
31480 selection.addRange(range);
31483 //_this.updateToolbar(null, null, pn);
31484 _this.updateToolbar(null, null, null);
31485 _this.updateFooter(false);
31496 tb.el.on('click', function(e){
31497 e.preventDefault(); // what does this do?
31499 tb.el.setVisibilityMode( Roo.Element.DISPLAY);
31502 // dont need to disable them... as they will get hidden
31507 buildFooter : function()
31510 var fel = this.editor.wrap.createChild();
31511 this.footer = new Roo.Toolbar(fel);
31512 // toolbar has scrolly on left / right?
31513 var footDisp= new Roo.Toolbar.Fill();
31519 handler : function() {
31520 _t.footDisp.scrollTo('left',0,true)
31524 this.footer.add( footDisp );
31529 handler : function() {
31531 _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
31535 var fel = Roo.get(footDisp.el);
31536 fel.addClass('x-editor-context');
31537 this.footDispWrap = fel;
31538 this.footDispWrap.overflow = 'hidden';
31540 this.footDisp = fel.createChild();
31541 this.footDispWrap.on('click', this.onContextClick, this)
31545 // when the footer contect changes
31546 onContextClick : function (ev,dom)
31548 ev.preventDefault();
31549 var cn = dom.className;
31551 if (!cn.match(/x-ed-loc-/)) {
31554 var n = cn.split('-').pop();
31555 var ans = this.footerEls;
31558 this.editorcore.selectNode(sel);
31561 this.updateToolbar(null, null, sel);
31578 * Ext JS Library 1.1.1
31579 * Copyright(c) 2006-2007, Ext JS, LLC.
31581 * Originally Released Under LGPL - original licence link has changed is not relivant.
31584 * <script type="text/javascript">
31588 * @class Roo.form.BasicForm
31589 * @extends Roo.util.Observable
31590 * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
31592 * @param {String/HTMLElement/Roo.Element} el The form element or its id
31593 * @param {Object} config Configuration options
31595 Roo.form.BasicForm = function(el, config){
31596 this.allItems = [];
31597 this.childForms = [];
31598 Roo.apply(this, config);
31600 * The Roo.form.Field items in this form.
31601 * @type MixedCollection
31605 this.items = new Roo.util.MixedCollection(false, function(o){
31606 return o.id || (o.id = Roo.id());
31610 * @event beforeaction
31611 * Fires before any action is performed. Return false to cancel the action.
31612 * @param {Form} this
31613 * @param {Action} action The action to be performed
31615 beforeaction: true,
31617 * @event actionfailed
31618 * Fires when an action fails.
31619 * @param {Form} this
31620 * @param {Action} action The action that failed
31622 actionfailed : true,
31624 * @event actioncomplete
31625 * Fires when an action is completed.
31626 * @param {Form} this
31627 * @param {Action} action The action that completed
31629 actioncomplete : true
31634 Roo.form.BasicForm.superclass.constructor.call(this);
31636 Roo.form.BasicForm.popover.apply();
31639 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
31641 * @cfg {String} method
31642 * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
31645 * @cfg {DataReader} reader
31646 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
31647 * This is optional as there is built-in support for processing JSON.
31650 * @cfg {DataReader} errorReader
31651 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
31652 * This is completely optional as there is built-in support for processing JSON.
31655 * @cfg {String} url
31656 * The URL to use for form actions if one isn't supplied in the action options.
31659 * @cfg {Boolean} fileUpload
31660 * Set to true if this form is a file upload.
31664 * @cfg {Object} baseParams
31665 * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
31670 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
31675 activeAction : null,
31678 * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
31679 * or setValues() data instead of when the form was first created.
31681 trackResetOnLoad : false,
31685 * childForms - used for multi-tab forms
31688 childForms : false,
31691 * allItems - full list of fields.
31697 * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
31698 * element by passing it or its id or mask the form itself by passing in true.
31701 waitMsgTarget : false,
31706 disableMask : false,
31709 * @cfg {Boolean} errorMask Should the form be masked (and the active element highlighted on error - default false
31714 * @cfg {Number} maskOffset space around form element to mask if there is an error Default 100
31719 initEl : function(el){
31720 this.el = Roo.get(el);
31721 this.id = this.el.id || Roo.id();
31722 this.el.on('submit', this.onSubmit, this);
31723 this.el.addClass('x-form');
31727 onSubmit : function(e){
31732 * Returns true if client-side validation on the form is successful.
31735 isValid : function(){
31737 var target = false;
31738 this.items.each(function(f){
31745 if(!target && f.el.isVisible(true)){
31750 if(this.errorMask && !valid){
31751 Roo.form.BasicForm.popover.mask(this, target);
31757 * Returns array of invalid form fields.
31761 invalidFields : function()
31764 this.items.each(function(f){
31777 * DEPRICATED Returns true if any fields in this form have changed since their original load.
31780 isDirty : function(){
31782 this.items.each(function(f){
31792 * Returns true if any fields in this form have changed since their original load. (New version)
31796 hasChanged : function()
31799 this.items.each(function(f){
31800 if(f.hasChanged()){
31809 * Resets all hasChanged to 'false' -
31810 * The old 'isDirty' used 'original value..' however this breaks reset() and a few other things.
31811 * So hasChanged storage is only to be used for this purpose
31814 resetHasChanged : function()
31816 this.items.each(function(f){
31817 f.resetHasChanged();
31824 * Performs a predefined action (submit or load) or custom actions you define on this form.
31825 * @param {String} actionName The name of the action type
31826 * @param {Object} options (optional) The options to pass to the action. All of the config options listed
31827 * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
31828 * accept other config options):
31830 Property Type Description
31831 ---------------- --------------- ----------------------------------------------------------------------------------
31832 url String The url for the action (defaults to the form's url)
31833 method String The form method to use (defaults to the form's method, or POST if not defined)
31834 params String/Object The params to pass (defaults to the form's baseParams, or none if not defined)
31835 clientValidation Boolean Applies to submit only. Pass true to call form.isValid() prior to posting to
31836 validate the form on the client (defaults to false)
31838 * @return {BasicForm} this
31840 doAction : function(action, options){
31841 if(typeof action == 'string'){
31842 action = new Roo.form.Action.ACTION_TYPES[action](this, options);
31844 if(this.fireEvent('beforeaction', this, action) !== false){
31845 this.beforeAction(action);
31846 action.run.defer(100, action);
31852 * Shortcut to do a submit action.
31853 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
31854 * @return {BasicForm} this
31856 submit : function(options){
31857 this.doAction('submit', options);
31862 * Shortcut to do a load action.
31863 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
31864 * @return {BasicForm} this
31866 load : function(options){
31867 this.doAction('load', options);
31872 * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
31873 * @param {Record} record The record to edit
31874 * @return {BasicForm} this
31876 updateRecord : function(record){
31877 record.beginEdit();
31878 var fs = record.fields;
31879 fs.each(function(f){
31880 var field = this.findField(f.name);
31882 record.set(f.name, field.getValue());
31890 * Loads an Roo.data.Record into this form.
31891 * @param {Record} record The record to load
31892 * @return {BasicForm} this
31894 loadRecord : function(record){
31895 this.setValues(record.data);
31900 beforeAction : function(action){
31901 var o = action.options;
31903 if(!this.disableMask) {
31904 if(this.waitMsgTarget === true){
31905 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
31906 }else if(this.waitMsgTarget){
31907 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
31908 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
31910 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
31918 afterAction : function(action, success){
31919 this.activeAction = null;
31920 var o = action.options;
31922 if(!this.disableMask) {
31923 if(this.waitMsgTarget === true){
31925 }else if(this.waitMsgTarget){
31926 this.waitMsgTarget.unmask();
31928 Roo.MessageBox.updateProgress(1);
31929 Roo.MessageBox.hide();
31937 Roo.callback(o.success, o.scope, [this, action]);
31938 this.fireEvent('actioncomplete', this, action);
31942 // failure condition..
31943 // we have a scenario where updates need confirming.
31944 // eg. if a locking scenario exists..
31945 // we look for { errors : { needs_confirm : true }} in the response.
31947 (typeof(action.result) != 'undefined') &&
31948 (typeof(action.result.errors) != 'undefined') &&
31949 (typeof(action.result.errors.needs_confirm) != 'undefined')
31952 Roo.MessageBox.confirm(
31953 "Change requires confirmation",
31954 action.result.errorMsg,
31959 _t.doAction('submit', { params : { _submit_confirmed : 1 } } );
31969 Roo.callback(o.failure, o.scope, [this, action]);
31970 // show an error message if no failed handler is set..
31971 if (!this.hasListener('actionfailed')) {
31972 Roo.MessageBox.alert("Error",
31973 (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
31974 action.result.errorMsg :
31975 "Saving Failed, please check your entries or try again"
31979 this.fireEvent('actionfailed', this, action);
31985 * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
31986 * @param {String} id The value to search for
31989 findField : function(id){
31990 var field = this.items.get(id);
31992 this.items.each(function(f){
31993 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
31999 return field || null;
32003 * Add a secondary form to this one,
32004 * Used to provide tabbed forms. One form is primary, with hidden values
32005 * which mirror the elements from the other forms.
32007 * @param {Roo.form.Form} form to add.
32010 addForm : function(form)
32013 if (this.childForms.indexOf(form) > -1) {
32017 this.childForms.push(form);
32019 Roo.each(form.allItems, function (fe) {
32021 n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
32022 if (this.findField(n)) { // already added..
32025 var add = new Roo.form.Hidden({
32028 add.render(this.el);
32035 * Mark fields in this form invalid in bulk.
32036 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
32037 * @return {BasicForm} this
32039 markInvalid : function(errors){
32040 if(errors instanceof Array){
32041 for(var i = 0, len = errors.length; i < len; i++){
32042 var fieldError = errors[i];
32043 var f = this.findField(fieldError.id);
32045 f.markInvalid(fieldError.msg);
32051 if(typeof errors[id] != 'function' && (field = this.findField(id))){
32052 field.markInvalid(errors[id]);
32056 Roo.each(this.childForms || [], function (f) {
32057 f.markInvalid(errors);
32064 * Set values for fields in this form in bulk.
32065 * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
32066 * @return {BasicForm} this
32068 setValues : function(values){
32069 if(values instanceof Array){ // array of objects
32070 for(var i = 0, len = values.length; i < len; i++){
32072 var f = this.findField(v.id);
32074 f.setValue(v.value);
32075 if(this.trackResetOnLoad){
32076 f.originalValue = f.getValue();
32080 }else{ // object hash
32083 if(typeof values[id] != 'function' && (field = this.findField(id))){
32088 if (field.setFromData &&
32089 field.valueField &&
32090 field.displayField &&
32091 // combos' with local stores can
32092 // be queried via setValue()
32093 // to set their value..
32094 (field.store && !field.store.isLocal)
32098 sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
32099 sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
32100 field.setFromData(sd);
32102 } else if (field.inputType && field.inputType == 'radio') {
32104 field.setValue(values[id]);
32106 field.setValue(values[id]);
32110 if(this.trackResetOnLoad){
32111 field.originalValue = field.getValue();
32116 this.resetHasChanged();
32119 Roo.each(this.childForms || [], function (f) {
32120 f.setValues(values);
32121 f.resetHasChanged();
32128 * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
32129 * they are returned as an array.
32130 * @param {Boolean} asString (def)
32133 getValues : function(asString)
32135 if (this.childForms) {
32136 // copy values from the child forms
32137 Roo.each(this.childForms, function (f) {
32138 this.setValues(f.getFieldValues()); // get the full set of data, as we might be copying comboboxes from external into this one.
32143 if (typeof(FormData) != 'undefined' && asString !== true) {
32144 // this relies on a 'recent' version of chrome apparently...
32146 var fd = (new FormData(this.el.dom)).entries();
32148 var ent = fd.next();
32149 while (!ent.done) {
32150 ret[ent.value[0]] = ent.value[1]; // not sure how this will handle duplicates..
32161 var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
32162 if(asString === true){
32165 return Roo.urlDecode(fs);
32169 * Returns the fields in this form as an object with key/value pairs.
32170 * This differs from getValues as it calls getValue on each child item, rather than using dom data.
32171 * Normally this will not return readOnly data
32172 * @param {Boolean} with_readonly return readonly field data.
32175 getFieldValues : function(with_readonly)
32177 if (this.childForms) {
32178 // copy values from the child forms
32179 // should this call getFieldValues - probably not as we do not currently copy
32180 // hidden fields when we generate..
32181 Roo.each(this.childForms, function (f) {
32182 this.setValues(f.getFieldValues());
32187 this.items.each(function(f){
32189 if (f.readOnly && with_readonly !== true) {
32190 return; // skip read only values. - this is in theory to stop 'old' values being copied over new ones
32191 // if a subform contains a copy of them.
32192 // if you have subforms with the same editable data, you will need to copy the data back
32196 if (!f.getName()) {
32199 var v = f.getValue();
32200 if (f.inputType =='radio') {
32201 if (typeof(ret[f.getName()]) == 'undefined') {
32202 ret[f.getName()] = ''; // empty..
32205 if (!f.el.dom.checked) {
32209 v = f.el.dom.value;
32213 // not sure if this supported any more..
32214 if ((typeof(v) == 'object') && f.getRawValue) {
32215 v = f.getRawValue() ; // dates..
32217 // combo boxes where name != hiddenName...
32218 if (f.name != f.getName()) {
32219 ret[f.name] = f.getRawValue();
32221 ret[f.getName()] = v;
32228 * Clears all invalid messages in this form.
32229 * @return {BasicForm} this
32231 clearInvalid : function(){
32232 this.items.each(function(f){
32236 Roo.each(this.childForms || [], function (f) {
32245 * Resets this form.
32246 * @return {BasicForm} this
32248 reset : function(){
32249 this.items.each(function(f){
32253 Roo.each(this.childForms || [], function (f) {
32256 this.resetHasChanged();
32262 * Add Roo.form components to this form.
32263 * @param {Field} field1
32264 * @param {Field} field2 (optional)
32265 * @param {Field} etc (optional)
32266 * @return {BasicForm} this
32269 this.items.addAll(Array.prototype.slice.call(arguments, 0));
32275 * Removes a field from the items collection (does NOT remove its markup).
32276 * @param {Field} field
32277 * @return {BasicForm} this
32279 remove : function(field){
32280 this.items.remove(field);
32285 * Looks at the fields in this form, checks them for an id attribute,
32286 * and calls applyTo on the existing dom element with that id.
32287 * @return {BasicForm} this
32289 render : function(){
32290 this.items.each(function(f){
32291 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
32299 * Calls {@link Ext#apply} for all fields in this form with the passed object.
32300 * @param {Object} values
32301 * @return {BasicForm} this
32303 applyToFields : function(o){
32304 this.items.each(function(f){
32311 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
32312 * @param {Object} values
32313 * @return {BasicForm} this
32315 applyIfToFields : function(o){
32316 this.items.each(function(f){
32324 Roo.BasicForm = Roo.form.BasicForm;
32326 Roo.apply(Roo.form.BasicForm, {
32340 intervalID : false,
32346 if(this.isApplied){
32351 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
32352 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
32353 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
32354 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
32357 this.maskEl.top.enableDisplayMode("block");
32358 this.maskEl.left.enableDisplayMode("block");
32359 this.maskEl.bottom.enableDisplayMode("block");
32360 this.maskEl.right.enableDisplayMode("block");
32362 Roo.get(document.body).on('click', function(){
32366 Roo.get(document.body).on('touchstart', function(){
32370 this.isApplied = true
32373 mask : function(form, target)
32377 this.target = target;
32379 if(!this.form.errorMask || !target.el){
32383 var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.x-layout-active-content', 100, true) || Roo.get(document.body);
32385 var ot = this.target.el.calcOffsetsTo(scrollable);
32387 var scrollTo = ot[1] - this.form.maskOffset;
32389 scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
32391 scrollable.scrollTo('top', scrollTo);
32393 var el = this.target.wrap || this.target.el;
32395 var box = el.getBox();
32397 this.maskEl.top.setStyle('position', 'absolute');
32398 this.maskEl.top.setStyle('z-index', 10000);
32399 this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
32400 this.maskEl.top.setLeft(0);
32401 this.maskEl.top.setTop(0);
32402 this.maskEl.top.show();
32404 this.maskEl.left.setStyle('position', 'absolute');
32405 this.maskEl.left.setStyle('z-index', 10000);
32406 this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
32407 this.maskEl.left.setLeft(0);
32408 this.maskEl.left.setTop(box.y - this.padding);
32409 this.maskEl.left.show();
32411 this.maskEl.bottom.setStyle('position', 'absolute');
32412 this.maskEl.bottom.setStyle('z-index', 10000);
32413 this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
32414 this.maskEl.bottom.setLeft(0);
32415 this.maskEl.bottom.setTop(box.bottom + this.padding);
32416 this.maskEl.bottom.show();
32418 this.maskEl.right.setStyle('position', 'absolute');
32419 this.maskEl.right.setStyle('z-index', 10000);
32420 this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
32421 this.maskEl.right.setLeft(box.right + this.padding);
32422 this.maskEl.right.setTop(box.y - this.padding);
32423 this.maskEl.right.show();
32425 this.intervalID = window.setInterval(function() {
32426 Roo.form.BasicForm.popover.unmask();
32429 window.onwheel = function(){ return false;};
32431 (function(){ this.isMasked = true; }).defer(500, this);
32435 unmask : function()
32437 if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
32441 this.maskEl.top.setStyle('position', 'absolute');
32442 this.maskEl.top.setSize(0, 0).setXY([0, 0]);
32443 this.maskEl.top.hide();
32445 this.maskEl.left.setStyle('position', 'absolute');
32446 this.maskEl.left.setSize(0, 0).setXY([0, 0]);
32447 this.maskEl.left.hide();
32449 this.maskEl.bottom.setStyle('position', 'absolute');
32450 this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
32451 this.maskEl.bottom.hide();
32453 this.maskEl.right.setStyle('position', 'absolute');
32454 this.maskEl.right.setSize(0, 0).setXY([0, 0]);
32455 this.maskEl.right.hide();
32457 window.onwheel = function(){ return true;};
32459 if(this.intervalID){
32460 window.clearInterval(this.intervalID);
32461 this.intervalID = false;
32464 this.isMasked = false;
32472 * Ext JS Library 1.1.1
32473 * Copyright(c) 2006-2007, Ext JS, LLC.
32475 * Originally Released Under LGPL - original licence link has changed is not relivant.
32478 * <script type="text/javascript">
32482 * @class Roo.form.Form
32483 * @extends Roo.form.BasicForm
32484 * @children Roo.form.Column Roo.form.FieldSet Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
32485 * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
32487 * @param {Object} config Configuration options
32489 Roo.form.Form = function(config){
32491 if (config.items) {
32492 xitems = config.items;
32493 delete config.items;
32497 Roo.form.Form.superclass.constructor.call(this, null, config);
32498 this.url = this.url || this.action;
32500 this.root = new Roo.form.Layout(Roo.applyIf({
32504 this.active = this.root;
32506 * Array of all the buttons that have been added to this form via {@link addButton}
32510 this.allItems = [];
32513 * @event clientvalidation
32514 * If the monitorValid config option is true, this event fires repetitively to notify of valid state
32515 * @param {Form} this
32516 * @param {Boolean} valid true if the form has passed client-side validation
32518 clientvalidation: true,
32521 * Fires when the form is rendered
32522 * @param {Roo.form.Form} form
32527 if (this.progressUrl) {
32528 // push a hidden field onto the list of fields..
32532 name : 'UPLOAD_IDENTIFIER'
32537 Roo.each(xitems, this.addxtype, this);
32541 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
32543 * @cfg {Roo.Button} buttons[] buttons at bottom of form
32547 * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
32550 * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
32553 * @cfg {String} buttonAlign (left|center|right) Valid values are "left," "center" and "right" (defaults to "center")
32555 buttonAlign:'center',
32558 * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
32563 * @cfg {String} labelAlign (left|top|right) Valid values are "left," "top" and "right" (defaults to "left").
32564 * This property cascades to child containers if not set.
32569 * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
32570 * fires a looping event with that state. This is required to bind buttons to the valid
32571 * state using the config value formBind:true on the button.
32573 monitorValid : false,
32576 * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
32581 * @cfg {String} progressUrl - Url to return progress data
32584 progressUrl : false,
32586 * @cfg {boolean|FormData} formData - true to use new 'FormData' post, or set to a new FormData({dom form}) Object, if
32587 * sending a formdata with extra parameters - eg uploaded elements.
32593 * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
32594 * fields are added and the column is closed. If no fields are passed the column remains open
32595 * until end() is called.
32596 * @param {Object} config The config to pass to the column
32597 * @param {Field} field1 (optional)
32598 * @param {Field} field2 (optional)
32599 * @param {Field} etc (optional)
32600 * @return Column The column container object
32602 column : function(c){
32603 var col = new Roo.form.Column(c);
32605 if(arguments.length > 1){ // duplicate code required because of Opera
32606 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
32613 * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
32614 * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
32615 * until end() is called.
32616 * @param {Object} config The config to pass to the fieldset
32617 * @param {Field} field1 (optional)
32618 * @param {Field} field2 (optional)
32619 * @param {Field} etc (optional)
32620 * @return FieldSet The fieldset container object
32622 fieldset : function(c){
32623 var fs = new Roo.form.FieldSet(c);
32625 if(arguments.length > 1){ // duplicate code required because of Opera
32626 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
32633 * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
32634 * fields are added and the container is closed. If no fields are passed the container remains open
32635 * until end() is called.
32636 * @param {Object} config The config to pass to the Layout
32637 * @param {Field} field1 (optional)
32638 * @param {Field} field2 (optional)
32639 * @param {Field} etc (optional)
32640 * @return Layout The container object
32642 container : function(c){
32643 var l = new Roo.form.Layout(c);
32645 if(arguments.length > 1){ // duplicate code required because of Opera
32646 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
32653 * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
32654 * @param {Object} container A Roo.form.Layout or subclass of Layout
32655 * @return {Form} this
32657 start : function(c){
32658 // cascade label info
32659 Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
32660 this.active.stack.push(c);
32661 c.ownerCt = this.active;
32667 * Closes the current open container
32668 * @return {Form} this
32671 if(this.active == this.root){
32674 this.active = this.active.ownerCt;
32679 * Add Roo.form components to the current open container (e.g. column, fieldset, etc.). Fields added via this method
32680 * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
32681 * as the label of the field.
32682 * @param {Field} field1
32683 * @param {Field} field2 (optional)
32684 * @param {Field} etc. (optional)
32685 * @return {Form} this
32688 this.active.stack.push.apply(this.active.stack, arguments);
32689 this.allItems.push.apply(this.allItems,arguments);
32691 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
32692 if(a[i].isFormField){
32697 Roo.form.Form.superclass.add.apply(this, r);
32707 * Find any element that has been added to a form, using it's ID or name
32708 * This can include framesets, columns etc. along with regular fields..
32709 * @param {String} id - id or name to find.
32711 * @return {Element} e - or false if nothing found.
32713 findbyId : function(id)
32719 Roo.each(this.allItems, function(f){
32720 if (f.id == id || f.name == id ){
32731 * Render this form into the passed container. This should only be called once!
32732 * @param {String/HTMLElement/Element} container The element this component should be rendered into
32733 * @return {Form} this
32735 render : function(ct)
32741 var o = this.autoCreate || {
32743 method : this.method || 'POST',
32744 id : this.id || Roo.id()
32746 this.initEl(ct.createChild(o));
32748 this.root.render(this.el);
32752 this.items.each(function(f){
32753 f.render('x-form-el-'+f.id);
32756 if(this.buttons.length > 0){
32757 // tables are required to maintain order and for correct IE layout
32758 var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
32759 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
32760 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
32762 var tr = tb.getElementsByTagName('tr')[0];
32763 for(var i = 0, len = this.buttons.length; i < len; i++) {
32764 var b = this.buttons[i];
32765 var td = document.createElement('td');
32766 td.className = 'x-form-btn-td';
32767 b.render(tr.appendChild(td));
32770 if(this.monitorValid){ // initialize after render
32771 this.startMonitoring();
32773 this.fireEvent('rendered', this);
32778 * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
32779 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
32780 * object or a valid Roo.DomHelper element config
32781 * @param {Function} handler The function called when the button is clicked
32782 * @param {Object} scope (optional) The scope of the handler function
32783 * @return {Roo.Button}
32785 addButton : function(config, handler, scope){
32789 minWidth: this.minButtonWidth,
32792 if(typeof config == "string"){
32795 Roo.apply(bc, config);
32797 var btn = new Roo.Button(null, bc);
32798 this.buttons.push(btn);
32803 * Adds a series of form elements (using the xtype property as the factory method.
32804 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
32805 * @param {Object} config
32808 addxtype : function()
32810 var ar = Array.prototype.slice.call(arguments, 0);
32812 for(var i = 0; i < ar.length; i++) {
32814 continue; // skip -- if this happends something invalid got sent, we
32815 // should ignore it, as basically that interface element will not show up
32816 // and that should be pretty obvious!!
32819 if (Roo.form[ar[i].xtype]) {
32821 var fe = Roo.factory(ar[i], Roo.form);
32827 fe.store.form = this;
32832 this.allItems.push(fe);
32833 if (fe.items && fe.addxtype) {
32834 fe.addxtype.apply(fe, fe.items);
32844 // console.log('adding ' + ar[i].xtype);
32846 if (ar[i].xtype == 'Button') {
32847 //console.log('adding button');
32848 //console.log(ar[i]);
32849 this.addButton(ar[i]);
32850 this.allItems.push(fe);
32854 if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
32855 alert('end is not supported on xtype any more, use items');
32857 // //console.log('adding end');
32865 * Starts monitoring of the valid state of this form. Usually this is done by passing the config
32866 * option "monitorValid"
32868 startMonitoring : function(){
32871 Roo.TaskMgr.start({
32872 run : this.bindHandler,
32873 interval : this.monitorPoll || 200,
32880 * Stops monitoring of the valid state of this form
32882 stopMonitoring : function(){
32883 this.bound = false;
32887 bindHandler : function(){
32889 return false; // stops binding
32892 this.items.each(function(f){
32893 if(!f.isValid(true)){
32898 for(var i = 0, len = this.buttons.length; i < len; i++){
32899 var btn = this.buttons[i];
32900 if(btn.formBind === true && btn.disabled === valid){
32901 btn.setDisabled(!valid);
32904 this.fireEvent('clientvalidation', this, valid);
32918 Roo.Form = Roo.form.Form;
32921 * Ext JS Library 1.1.1
32922 * Copyright(c) 2006-2007, Ext JS, LLC.
32924 * Originally Released Under LGPL - original licence link has changed is not relivant.
32927 * <script type="text/javascript">
32930 // as we use this in bootstrap.
32931 Roo.namespace('Roo.form');
32933 * @class Roo.form.Action
32934 * Internal Class used to handle form actions
32936 * @param {Roo.form.BasicForm} el The form element or its id
32937 * @param {Object} config Configuration options
32942 // define the action interface
32943 Roo.form.Action = function(form, options){
32945 this.options = options || {};
32948 * Client Validation Failed
32951 Roo.form.Action.CLIENT_INVALID = 'client';
32953 * Server Validation Failed
32956 Roo.form.Action.SERVER_INVALID = 'server';
32958 * Connect to Server Failed
32961 Roo.form.Action.CONNECT_FAILURE = 'connect';
32963 * Reading Data from Server Failed
32966 Roo.form.Action.LOAD_FAILURE = 'load';
32968 Roo.form.Action.prototype = {
32970 failureType : undefined,
32971 response : undefined,
32972 result : undefined,
32974 // interface method
32975 run : function(options){
32979 // interface method
32980 success : function(response){
32984 // interface method
32985 handleResponse : function(response){
32989 // default connection failure
32990 failure : function(response){
32992 this.response = response;
32993 this.failureType = Roo.form.Action.CONNECT_FAILURE;
32994 this.form.afterAction(this, false);
32997 processResponse : function(response){
32998 this.response = response;
32999 if(!response.responseText){
33002 this.result = this.handleResponse(response);
33003 return this.result;
33006 // utility functions used internally
33007 getUrl : function(appendParams){
33008 var url = this.options.url || this.form.url || this.form.el.dom.action;
33010 var p = this.getParams();
33012 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
33018 getMethod : function(){
33019 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
33022 getParams : function(){
33023 var bp = this.form.baseParams;
33024 var p = this.options.params;
33026 if(typeof p == "object"){
33027 p = Roo.urlEncode(Roo.applyIf(p, bp));
33028 }else if(typeof p == 'string' && bp){
33029 p += '&' + Roo.urlEncode(bp);
33032 p = Roo.urlEncode(bp);
33037 createCallback : function(){
33039 success: this.success,
33040 failure: this.failure,
33042 timeout: (this.form.timeout*1000),
33043 upload: this.form.fileUpload ? this.success : undefined
33048 Roo.form.Action.Submit = function(form, options){
33049 Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
33052 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
33055 haveProgress : false,
33056 uploadComplete : false,
33058 // uploadProgress indicator.
33059 uploadProgress : function()
33061 if (!this.form.progressUrl) {
33065 if (!this.haveProgress) {
33066 Roo.MessageBox.progress("Uploading", "Uploading");
33068 if (this.uploadComplete) {
33069 Roo.MessageBox.hide();
33073 this.haveProgress = true;
33075 var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
33077 var c = new Roo.data.Connection();
33079 url : this.form.progressUrl,
33084 success : function(req){
33085 //console.log(data);
33089 rdata = Roo.decode(req.responseText)
33091 Roo.log("Invalid data from server..");
33095 if (!rdata || !rdata.success) {
33097 Roo.MessageBox.alert(Roo.encode(rdata));
33100 var data = rdata.data;
33102 if (this.uploadComplete) {
33103 Roo.MessageBox.hide();
33108 Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
33109 Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
33112 this.uploadProgress.defer(2000,this);
33115 failure: function(data) {
33116 Roo.log('progress url failed ');
33127 // run get Values on the form, so it syncs any secondary forms.
33128 this.form.getValues();
33130 var o = this.options;
33131 var method = this.getMethod();
33132 var isPost = method == 'POST';
33133 if(o.clientValidation === false || this.form.isValid()){
33135 if (this.form.progressUrl) {
33136 this.form.findField('UPLOAD_IDENTIFIER').setValue(
33137 (new Date() * 1) + '' + Math.random());
33142 Roo.Ajax.request(Roo.apply(this.createCallback(), {
33143 form:this.form.el.dom,
33144 url:this.getUrl(!isPost),
33146 params:isPost ? this.getParams() : null,
33147 isUpload: this.form.fileUpload,
33148 formData : this.form.formData
33151 this.uploadProgress();
33153 }else if (o.clientValidation !== false){ // client validation failed
33154 this.failureType = Roo.form.Action.CLIENT_INVALID;
33155 this.form.afterAction(this, false);
33159 success : function(response)
33161 this.uploadComplete= true;
33162 if (this.haveProgress) {
33163 Roo.MessageBox.hide();
33167 var result = this.processResponse(response);
33168 if(result === true || result.success){
33169 this.form.afterAction(this, true);
33173 this.form.markInvalid(result.errors);
33174 this.failureType = Roo.form.Action.SERVER_INVALID;
33176 this.form.afterAction(this, false);
33178 failure : function(response)
33180 this.uploadComplete= true;
33181 if (this.haveProgress) {
33182 Roo.MessageBox.hide();
33185 this.response = response;
33186 this.failureType = Roo.form.Action.CONNECT_FAILURE;
33187 this.form.afterAction(this, false);
33190 handleResponse : function(response){
33191 if(this.form.errorReader){
33192 var rs = this.form.errorReader.read(response);
33195 for(var i = 0, len = rs.records.length; i < len; i++) {
33196 var r = rs.records[i];
33197 errors[i] = r.data;
33200 if(errors.length < 1){
33204 success : rs.success,
33210 var rt = response.responseText;
33211 if (rt.match(/^\<!--\[CDATA\[/)) {
33212 rt = rt.replace(/^\<!--\[CDATA\[/,'');
33213 rt = rt.replace(/\]\]--\>$/,'');
33216 ret = Roo.decode(rt);
33220 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
33230 Roo.form.Action.Load = function(form, options){
33231 Roo.form.Action.Load.superclass.constructor.call(this, form, options);
33232 this.reader = this.form.reader;
33235 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
33240 Roo.Ajax.request(Roo.apply(
33241 this.createCallback(), {
33242 method:this.getMethod(),
33243 url:this.getUrl(false),
33244 params:this.getParams()
33248 success : function(response){
33250 var result = this.processResponse(response);
33251 if(result === true || !result.success || !result.data){
33252 this.failureType = Roo.form.Action.LOAD_FAILURE;
33253 this.form.afterAction(this, false);
33256 this.form.clearInvalid();
33257 this.form.setValues(result.data);
33258 this.form.afterAction(this, true);
33261 handleResponse : function(response){
33262 if(this.form.reader){
33263 var rs = this.form.reader.read(response);
33264 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
33266 success : rs.success,
33270 return Roo.decode(response.responseText);
33274 Roo.form.Action.ACTION_TYPES = {
33275 'load' : Roo.form.Action.Load,
33276 'submit' : Roo.form.Action.Submit
33279 * Ext JS Library 1.1.1
33280 * Copyright(c) 2006-2007, Ext JS, LLC.
33282 * Originally Released Under LGPL - original licence link has changed is not relivant.
33285 * <script type="text/javascript">
33289 * @class Roo.form.Layout
33290 * @extends Roo.Component
33291 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
33292 * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
33294 * @param {Object} config Configuration options
33296 Roo.form.Layout = function(config){
33298 if (config.items) {
33299 xitems = config.items;
33300 delete config.items;
33302 Roo.form.Layout.superclass.constructor.call(this, config);
33304 Roo.each(xitems, this.addxtype, this);
33308 Roo.extend(Roo.form.Layout, Roo.Component, {
33310 * @cfg {String/Object} autoCreate
33311 * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
33314 * @cfg {String/Object/Function} style
33315 * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
33316 * a function which returns such a specification.
33319 * @cfg {String} labelAlign (left|top|right)
33320 * Valid values are "left," "top" and "right" (defaults to "left")
33323 * @cfg {Number} labelWidth
33324 * Fixed width in pixels of all field labels (defaults to undefined)
33327 * @cfg {Boolean} clear
33328 * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
33332 * @cfg {String} labelSeparator
33333 * The separator to use after field labels (defaults to ':')
33335 labelSeparator : ':',
33337 * @cfg {Boolean} hideLabels
33338 * True to suppress the display of field labels in this layout (defaults to false)
33340 hideLabels : false,
33343 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
33348 onRender : function(ct, position){
33349 if(this.el){ // from markup
33350 this.el = Roo.get(this.el);
33351 }else { // generate
33352 var cfg = this.getAutoCreate();
33353 this.el = ct.createChild(cfg, position);
33356 this.el.applyStyles(this.style);
33358 if(this.labelAlign){
33359 this.el.addClass('x-form-label-'+this.labelAlign);
33361 if(this.hideLabels){
33362 this.labelStyle = "display:none";
33363 this.elementStyle = "padding-left:0;";
33365 if(typeof this.labelWidth == 'number'){
33366 this.labelStyle = "width:"+this.labelWidth+"px;";
33367 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
33369 if(this.labelAlign == 'top'){
33370 this.labelStyle = "width:auto;";
33371 this.elementStyle = "padding-left:0;";
33374 var stack = this.stack;
33375 var slen = stack.length;
33377 if(!this.fieldTpl){
33378 var t = new Roo.Template(
33379 '<div class="x-form-item {5}">',
33380 '<label for="{0}" style="{2}">{1}{4}</label>',
33381 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
33383 '</div><div class="x-form-clear-left"></div>'
33385 t.disableFormats = true;
33387 Roo.form.Layout.prototype.fieldTpl = t;
33389 for(var i = 0; i < slen; i++) {
33390 if(stack[i].isFormField){
33391 this.renderField(stack[i]);
33393 this.renderComponent(stack[i]);
33398 this.el.createChild({cls:'x-form-clear'});
33403 renderField : function(f){
33404 f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
33407 f.labelStyle||this.labelStyle||'', //2
33408 this.elementStyle||'', //3
33409 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
33410 f.itemCls||this.itemCls||'' //5
33411 ], true).getPrevSibling());
33415 renderComponent : function(c){
33416 c.render(c.isLayout ? this.el : this.el.createChild());
33419 * Adds a object form elements (using the xtype property as the factory method.)
33420 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column
33421 * @param {Object} config
33423 addxtype : function(o)
33425 // create the lement.
33426 o.form = this.form;
33427 var fe = Roo.factory(o, Roo.form);
33428 this.form.allItems.push(fe);
33429 this.stack.push(fe);
33431 if (fe.isFormField) {
33432 this.form.items.add(fe);
33441 * @class Roo.form.Column
33442 * @extends Roo.form.Layout
33443 * @children Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
33444 * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
33446 * @param {Object} config Configuration options
33448 Roo.form.Column = function(config){
33449 Roo.form.Column.superclass.constructor.call(this, config);
33452 Roo.extend(Roo.form.Column, Roo.form.Layout, {
33454 * @cfg {Number/String} width
33455 * The fixed width of the column in pixels or CSS value (defaults to "auto")
33458 * @cfg {String/Object} autoCreate
33459 * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
33463 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
33466 onRender : function(ct, position){
33467 Roo.form.Column.superclass.onRender.call(this, ct, position);
33469 this.el.setWidth(this.width);
33475 * @class Roo.form.Row
33476 * @extends Roo.form.Layout
33477 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
33478 * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
33480 * @param {Object} config Configuration options
33484 Roo.form.Row = function(config){
33485 Roo.form.Row.superclass.constructor.call(this, config);
33488 Roo.extend(Roo.form.Row, Roo.form.Layout, {
33490 * @cfg {Number/String} width
33491 * The fixed width of the column in pixels or CSS value (defaults to "auto")
33494 * @cfg {Number/String} height
33495 * The fixed height of the column in pixels or CSS value (defaults to "auto")
33497 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
33501 onRender : function(ct, position){
33502 //console.log('row render');
33504 var t = new Roo.Template(
33505 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
33506 '<label for="{0}" style="{2}">{1}{4}</label>',
33507 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
33511 t.disableFormats = true;
33513 Roo.form.Layout.prototype.rowTpl = t;
33515 this.fieldTpl = this.rowTpl;
33517 //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
33518 var labelWidth = 100;
33520 if ((this.labelAlign != 'top')) {
33521 if (typeof this.labelWidth == 'number') {
33522 labelWidth = this.labelWidth
33524 this.padWidth = 20 + labelWidth;
33528 Roo.form.Column.superclass.onRender.call(this, ct, position);
33530 this.el.setWidth(this.width);
33533 this.el.setHeight(this.height);
33538 renderField : function(f){
33539 f.fieldEl = this.fieldTpl.append(this.el, [
33540 f.id, f.fieldLabel,
33541 f.labelStyle||this.labelStyle||'',
33542 this.elementStyle||'',
33543 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
33544 f.itemCls||this.itemCls||'',
33545 f.width ? f.width + this.padWidth : 160 + this.padWidth
33552 * @class Roo.form.FieldSet
33553 * @extends Roo.form.Layout
33554 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
33555 * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
33557 * @param {Object} config Configuration options
33559 Roo.form.FieldSet = function(config){
33560 Roo.form.FieldSet.superclass.constructor.call(this, config);
33563 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
33565 * @cfg {String} legend
33566 * The text to display as the legend for the FieldSet (defaults to '')
33569 * @cfg {String/Object} autoCreate
33570 * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
33574 defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
33577 onRender : function(ct, position){
33578 Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
33580 this.setLegend(this.legend);
33585 setLegend : function(text){
33587 this.el.child('legend').update(text);
33592 * Ext JS Library 1.1.1
33593 * Copyright(c) 2006-2007, Ext JS, LLC.
33595 * Originally Released Under LGPL - original licence link has changed is not relivant.
33598 * <script type="text/javascript">
33601 * @class Roo.form.VTypes
33602 * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
33605 Roo.form.VTypes = function(){
33606 // closure these in so they are only created once.
33607 var alpha = /^[a-zA-Z_]+$/;
33608 var alphanum = /^[a-zA-Z0-9_]+$/;
33609 var email = /^([\w'-]+)(\.[\w'-]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
33610 var url = /^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
33611 var urlWeb = /^((https?):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
33613 // All these messages and functions are configurable
33616 * The function used to validate email addresses
33617 * @param {String} value The email address
33619 email : function(v){
33620 return email.test(v);
33623 * The error text to display when the email validation function returns false
33626 emailText : 'This field should be an e-mail address in the format "user@domain.com"',
33628 * The keystroke filter mask to be applied on email input
33631 emailMask : /[a-z0-9_\.\-@]/i,
33634 * The function used to validate URLs
33635 * @param {String} value The URL
33638 return url.test(v);
33641 * The funciton used to validate URLs (only allow schemes 'https' and 'http')
33642 * @param {String} v The URL
33644 urlWeb : function(v) {
33645 return urlWeb.test(v);
33648 * The error text to display when the url validation function returns false
33651 urlText : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
33654 * The function used to validate alpha values
33655 * @param {String} value The value
33657 alpha : function(v){
33658 return alpha.test(v);
33661 * The error text to display when the alpha validation function returns false
33664 alphaText : 'This field should only contain letters and _',
33666 * The keystroke filter mask to be applied on alpha input
33669 alphaMask : /[a-z_]/i,
33672 * The function used to validate alphanumeric values
33673 * @param {String} value The value
33675 alphanum : function(v){
33676 return alphanum.test(v);
33679 * The error text to display when the alphanumeric validation function returns false
33682 alphanumText : 'This field should only contain letters, numbers and _',
33684 * The keystroke filter mask to be applied on alphanumeric input
33687 alphanumMask : /[a-z0-9_]/i
33689 }();//<script type="text/javascript">
33692 * @class Roo.form.FCKeditor
33693 * @extends Roo.form.TextArea
33694 * Wrapper around the FCKEditor http://www.fckeditor.net
33696 * Creates a new FCKeditor
33697 * @param {Object} config Configuration options
33699 Roo.form.FCKeditor = function(config){
33700 Roo.form.FCKeditor.superclass.constructor.call(this, config);
33703 * @event editorinit
33704 * Fired when the editor is initialized - you can add extra handlers here..
33705 * @param {FCKeditor} this
33706 * @param {Object} the FCK object.
33713 Roo.form.FCKeditor.editors = { };
33714 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
33716 //defaultAutoCreate : {
33717 // tag : "textarea",style : "width:100px;height:60px;" ,autocomplete : "off"
33721 * @cfg {Object} fck options - see fck manual for details.
33726 * @cfg {Object} fck toolbar set (Basic or Default)
33728 toolbarSet : 'Basic',
33730 * @cfg {Object} fck BasePath
33732 basePath : '/fckeditor/',
33740 onRender : function(ct, position)
33743 this.defaultAutoCreate = {
33745 style:"width:300px;height:60px;",
33746 autocomplete: "new-password"
33749 Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
33752 this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
33753 if(this.preventScrollbars){
33754 this.el.setStyle("overflow", "hidden");
33756 this.el.setHeight(this.growMin);
33759 //console.log('onrender' + this.getId() );
33760 Roo.form.FCKeditor.editors[this.getId()] = this;
33763 this.replaceTextarea() ;
33767 getEditor : function() {
33768 return this.fckEditor;
33771 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
33772 * @param {Mixed} value The value to set
33776 setValue : function(value)
33778 //console.log('setValue: ' + value);
33780 if(typeof(value) == 'undefined') { // not sure why this is happending...
33783 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
33785 //if(!this.el || !this.getEditor()) {
33786 // this.value = value;
33787 //this.setValue.defer(100,this,[value]);
33791 if(!this.getEditor()) {
33795 this.getEditor().SetData(value);
33802 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
33803 * @return {Mixed} value The field value
33805 getValue : function()
33808 if (this.frame && this.frame.dom.style.display == 'none') {
33809 return Roo.form.FCKeditor.superclass.getValue.call(this);
33812 if(!this.el || !this.getEditor()) {
33814 // this.getValue.defer(100,this);
33819 var value=this.getEditor().GetData();
33820 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
33821 return Roo.form.FCKeditor.superclass.getValue.call(this);
33827 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
33828 * @return {Mixed} value The field value
33830 getRawValue : function()
33832 if (this.frame && this.frame.dom.style.display == 'none') {
33833 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
33836 if(!this.el || !this.getEditor()) {
33837 //this.getRawValue.defer(100,this);
33844 var value=this.getEditor().GetData();
33845 Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
33846 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
33850 setSize : function(w,h) {
33854 //if (this.frame && this.frame.dom.style.display == 'none') {
33855 // Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
33858 //if(!this.el || !this.getEditor()) {
33859 // this.setSize.defer(100,this, [w,h]);
33865 Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
33867 this.frame.dom.setAttribute('width', w);
33868 this.frame.dom.setAttribute('height', h);
33869 this.frame.setSize(w,h);
33873 toggleSourceEdit : function(value) {
33877 this.el.dom.style.display = value ? '' : 'none';
33878 this.frame.dom.style.display = value ? 'none' : '';
33883 focus: function(tag)
33885 if (this.frame.dom.style.display == 'none') {
33886 return Roo.form.FCKeditor.superclass.focus.call(this);
33888 if(!this.el || !this.getEditor()) {
33889 this.focus.defer(100,this, [tag]);
33896 var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
33897 this.getEditor().Focus();
33899 if (!this.getEditor().Selection.GetSelection()) {
33900 this.focus.defer(100,this, [tag]);
33905 var r = this.getEditor().EditorDocument.createRange();
33906 r.setStart(tgs[0],0);
33907 r.setEnd(tgs[0],0);
33908 this.getEditor().Selection.GetSelection().removeAllRanges();
33909 this.getEditor().Selection.GetSelection().addRange(r);
33910 this.getEditor().Focus();
33917 replaceTextarea : function()
33919 if ( document.getElementById( this.getId() + '___Frame' ) ) {
33922 //if ( !this.checkBrowser || this._isCompatibleBrowser() )
33924 // We must check the elements firstly using the Id and then the name.
33925 var oTextarea = document.getElementById( this.getId() );
33927 var colElementsByName = document.getElementsByName( this.getId() ) ;
33929 oTextarea.style.display = 'none' ;
33931 if ( oTextarea.tabIndex ) {
33932 this.TabIndex = oTextarea.tabIndex ;
33935 this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
33936 this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
33937 this.frame = Roo.get(this.getId() + '___Frame')
33940 _getConfigHtml : function()
33944 for ( var o in this.fckconfig ) {
33945 sConfig += sConfig.length > 0 ? '&' : '';
33946 sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
33949 return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
33953 _getIFrameHtml : function()
33955 var sFile = 'fckeditor.html' ;
33956 /* no idea what this is about..
33959 if ( (/fcksource=true/i).test( window.top.location.search ) )
33960 sFile = 'fckeditor.original.html' ;
33965 var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
33966 sLink += this.toolbarSet ? ( '&Toolbar=' + this.toolbarSet) : '';
33969 var html = '<iframe id="' + this.getId() +
33970 '___Frame" src="' + sLink +
33971 '" width="' + this.width +
33972 '" height="' + this.height + '"' +
33973 (this.tabIndex ? ' tabindex="' + this.tabIndex + '"' :'' ) +
33974 ' frameborder="0" scrolling="no"></iframe>' ;
33979 _insertHtmlBefore : function( html, element )
33981 if ( element.insertAdjacentHTML ) {
33983 element.insertAdjacentHTML( 'beforeBegin', html ) ;
33985 var oRange = document.createRange() ;
33986 oRange.setStartBefore( element ) ;
33987 var oFragment = oRange.createContextualFragment( html );
33988 element.parentNode.insertBefore( oFragment, element ) ;
34001 //Roo.reg('fckeditor', Roo.form.FCKeditor);
34003 function FCKeditor_OnComplete(editorInstance){
34004 var f = Roo.form.FCKeditor.editors[editorInstance.Name];
34005 f.fckEditor = editorInstance;
34006 //console.log("loaded");
34007 f.fireEvent('editorinit', f, editorInstance);
34027 //<script type="text/javascript">
34029 * @class Roo.form.GridField
34030 * @extends Roo.form.Field
34031 * Embed a grid (or editable grid into a form)
34034 * This embeds a grid in a form, the value of the field should be the json encoded array of rows
34036 * xgrid.store = Roo.data.Store
34037 * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
34038 * xgrid.store.reader = Roo.data.JsonReader
34042 * Creates a new GridField
34043 * @param {Object} config Configuration options
34045 Roo.form.GridField = function(config){
34046 Roo.form.GridField.superclass.constructor.call(this, config);
34050 Roo.extend(Roo.form.GridField, Roo.form.Field, {
34052 * @cfg {Number} width - used to restrict width of grid..
34056 * @cfg {Number} height - used to restrict height of grid..
34060 * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
34066 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
34067 * {tag: "input", type: "checkbox", autocomplete: "off"})
34069 // defaultAutoCreate : { tag: 'div' },
34070 defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
34072 * @cfg {String} addTitle Text to include for adding a title.
34076 onResize : function(){
34077 Roo.form.Field.superclass.onResize.apply(this, arguments);
34080 initEvents : function(){
34081 // Roo.form.Checkbox.superclass.initEvents.call(this);
34082 // has no events...
34087 getResizeEl : function(){
34091 getPositionEl : function(){
34096 onRender : function(ct, position){
34098 this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
34099 var style = this.style;
34102 Roo.form.GridField.superclass.onRender.call(this, ct, position);
34103 this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
34104 this.viewEl = this.wrap.createChild({ tag: 'div' });
34106 this.viewEl.applyStyles(style);
34109 this.viewEl.setWidth(this.width);
34112 this.viewEl.setHeight(this.height);
34114 //if(this.inputValue !== undefined){
34115 //this.setValue(this.value);
34118 this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
34121 this.grid.render();
34122 this.grid.getDataSource().on('remove', this.refreshValue, this);
34123 this.grid.getDataSource().on('update', this.refreshValue, this);
34124 this.grid.on('afteredit', this.refreshValue, this);
34130 * Sets the value of the item.
34131 * @param {String} either an object or a string..
34133 setValue : function(v){
34135 v = v || []; // empty set..
34136 // this does not seem smart - it really only affects memoryproxy grids..
34137 if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
34138 var ds = this.grid.getDataSource();
34139 // assumes a json reader..
34141 data[ds.reader.meta.root ] = typeof(v) == 'string' ? Roo.decode(v) : v;
34142 ds.loadData( data);
34144 // clear selection so it does not get stale.
34145 if (this.grid.sm) {
34146 this.grid.sm.clearSelections();
34149 Roo.form.GridField.superclass.setValue.call(this, v);
34150 this.refreshValue();
34151 // should load data in the grid really....
34155 refreshValue: function() {
34157 this.grid.getDataSource().each(function(r) {
34160 this.el.dom.value = Roo.encode(val);
34168 * Ext JS Library 1.1.1
34169 * Copyright(c) 2006-2007, Ext JS, LLC.
34171 * Originally Released Under LGPL - original licence link has changed is not relivant.
34174 * <script type="text/javascript">
34177 * @class Roo.form.DisplayField
34178 * @extends Roo.form.Field
34179 * A generic Field to display non-editable data.
34180 * @cfg {Boolean} closable (true|false) default false
34182 * Creates a new Display Field item.
34183 * @param {Object} config Configuration options
34185 Roo.form.DisplayField = function(config){
34186 Roo.form.DisplayField.superclass.constructor.call(this, config);
34191 * Fires after the click the close btn
34192 * @param {Roo.form.DisplayField} this
34198 Roo.extend(Roo.form.DisplayField, Roo.form.TextField, {
34199 inputType: 'hidden',
34205 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
34207 focusClass : undefined,
34209 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
34211 fieldClass: 'x-form-field',
34214 * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
34216 valueRenderer: undefined,
34220 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
34221 * {tag: "input", type: "checkbox", autocomplete: "off"})
34224 // defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
34228 onResize : function(){
34229 Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
34233 initEvents : function(){
34234 // Roo.form.Checkbox.superclass.initEvents.call(this);
34235 // has no events...
34238 this.closeEl.on('click', this.onClose, this);
34244 getResizeEl : function(){
34248 getPositionEl : function(){
34253 onRender : function(ct, position){
34255 Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
34256 //if(this.inputValue !== undefined){
34257 this.wrap = this.el.wrap();
34259 this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
34262 this.closeEl = this.wrap.createChild({ tag: 'div', cls: 'x-dlg-close'});
34265 if (this.bodyStyle) {
34266 this.viewEl.applyStyles(this.bodyStyle);
34268 //this.viewEl.setStyle('padding', '2px');
34270 this.setValue(this.value);
34275 initValue : Roo.emptyFn,
34280 onClick : function(){
34285 * Sets the checked state of the checkbox.
34286 * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
34288 setValue : function(v){
34290 var html = this.valueRenderer ? this.valueRenderer(v) : String.format('{0}', v);
34291 // this might be called before we have a dom element..
34292 if (!this.viewEl) {
34295 this.viewEl.dom.innerHTML = html;
34296 Roo.form.DisplayField.superclass.setValue.call(this, v);
34300 onClose : function(e)
34302 e.preventDefault();
34304 this.fireEvent('close', this);
34313 * @class Roo.form.DayPicker
34314 * @extends Roo.form.Field
34315 * A Day picker show [M] [T] [W] ....
34317 * Creates a new Day Picker
34318 * @param {Object} config Configuration options
34320 Roo.form.DayPicker= function(config){
34321 Roo.form.DayPicker.superclass.constructor.call(this, config);
34325 Roo.extend(Roo.form.DayPicker, Roo.form.Field, {
34327 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
34329 focusClass : undefined,
34331 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
34333 fieldClass: "x-form-field",
34336 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
34337 * {tag: "input", type: "checkbox", autocomplete: "off"})
34339 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
34342 actionMode : 'viewEl',
34346 inputType : 'hidden',
34349 inputElement: false, // real input element?
34350 basedOn: false, // ????
34352 isFormField: true, // not sure where this is needed!!!!
34354 onResize : function(){
34355 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
34356 if(!this.boxLabel){
34357 this.el.alignTo(this.wrap, 'c-c');
34361 initEvents : function(){
34362 Roo.form.Checkbox.superclass.initEvents.call(this);
34363 this.el.on("click", this.onClick, this);
34364 this.el.on("change", this.onClick, this);
34368 getResizeEl : function(){
34372 getPositionEl : function(){
34378 onRender : function(ct, position){
34379 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
34381 this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
34383 var r1 = '<table><tr>';
34384 var r2 = '<tr class="x-form-daypick-icons">';
34385 for (var i=0; i < 7; i++) {
34386 r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
34387 r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL +'"></td>';
34390 var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
34391 viewEl.select('img').on('click', this.onClick, this);
34392 this.viewEl = viewEl;
34395 // this will not work on Chrome!!!
34396 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
34397 this.el.on('propertychange', this.setFromHidden, this); //ie
34405 initValue : Roo.emptyFn,
34408 * Returns the checked state of the checkbox.
34409 * @return {Boolean} True if checked, else false
34411 getValue : function(){
34412 return this.el.dom.value;
34417 onClick : function(e){
34418 //this.setChecked(!this.checked);
34419 Roo.get(e.target).toggleClass('x-menu-item-checked');
34420 this.refreshValue();
34421 //if(this.el.dom.checked != this.checked){
34422 // this.setValue(this.el.dom.checked);
34427 refreshValue : function()
34430 this.viewEl.select('img',true).each(function(e,i,n) {
34431 val += e.is(".x-menu-item-checked") ? String(n) : '';
34433 this.setValue(val, true);
34437 * Sets the checked state of the checkbox.
34438 * On is always based on a string comparison between inputValue and the param.
34439 * @param {Boolean/String} value - the value to set
34440 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
34442 setValue : function(v,suppressEvent){
34443 if (!this.el.dom) {
34446 var old = this.el.dom.value ;
34447 this.el.dom.value = v;
34448 if (suppressEvent) {
34452 // update display..
34453 this.viewEl.select('img',true).each(function(e,i,n) {
34455 var on = e.is(".x-menu-item-checked");
34456 var newv = v.indexOf(String(n)) > -1;
34458 e.toggleClass('x-menu-item-checked');
34464 this.fireEvent('change', this, v, old);
34469 // handle setting of hidden value by some other method!!?!?
34470 setFromHidden: function()
34475 //console.log("SET FROM HIDDEN");
34476 //alert('setFrom hidden');
34477 this.setValue(this.el.dom.value);
34480 onDestroy : function()
34483 Roo.get(this.viewEl).remove();
34486 Roo.form.DayPicker.superclass.onDestroy.call(this);
34490 * RooJS Library 1.1.1
34491 * Copyright(c) 2008-2011 Alan Knowles
34498 * @class Roo.form.ComboCheck
34499 * @extends Roo.form.ComboBox
34500 * A combobox for multiple select items.
34502 * FIXME - could do with a reset button..
34505 * Create a new ComboCheck
34506 * @param {Object} config Configuration options
34508 Roo.form.ComboCheck = function(config){
34509 Roo.form.ComboCheck.superclass.constructor.call(this, config);
34510 // should verify some data...
34512 // hiddenName = required..
34513 // displayField = required
34514 // valudField == required
34515 var req= [ 'hiddenName', 'displayField', 'valueField' ];
34517 Roo.each(req, function(e) {
34518 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
34519 throw "Roo.form.ComboCheck : missing value for: " + e;
34526 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
34531 selectedClass: 'x-menu-item-checked',
34534 onRender : function(ct, position){
34540 var cls = 'x-combo-list';
34543 this.tpl = new Roo.Template({
34544 html : '<div class="'+cls+'-item x-menu-check-item">' +
34545 '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' +
34546 '<span>{' + this.displayField + '}</span>' +
34553 Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
34554 this.view.singleSelect = false;
34555 this.view.multiSelect = true;
34556 this.view.toggleSelect = true;
34557 this.pageTb.add(new Roo.Toolbar.Fill(),{
34559 text: 'Select All',
34560 handler: function() {
34566 handler: function() {
34572 cleanLeadingSpace : function(e)
34574 // this is disabled, as it retriggers setvalue on blur
34577 doForce : function() {
34578 // no idea what this did, but it blanks out our values.
34581 onViewOver : function(e, t){
34587 onViewClick : function(doFocus,index){
34591 select: function () {
34592 //Roo.log("SELECT CALLED");
34595 selectByValue : function(xv, scrollIntoView){
34596 var ar = this.getValueArray();
34599 Roo.each(ar, function(v) {
34600 if(v === undefined || v === null){
34603 var r = this.findRecord(this.valueField, v);
34605 sels.push(this.store.indexOf(r))
34609 this.view.select(sels);
34613 selectAll : function()
34616 this.store.each(function(r,i) {
34619 this.view.select(sels);
34625 onSelect : function(record, index){
34626 // Roo.log("onselect Called");
34627 // this is only called by the clear button now..
34628 this.view.clearSelections();
34629 this.setValue('[]');
34630 if (this.value != this.valueBefore) {
34631 this.fireEvent('change', this, this.value, this.valueBefore);
34632 this.valueBefore = this.value;
34635 getValueArray : function()
34640 //Roo.log(this.value);
34641 if (typeof(this.value) == 'undefined') {
34644 var ar = Roo.decode(this.value);
34645 return ar instanceof Array ? ar : []; //?? valid?
34648 Roo.log(e + "\nRoo.form.ComboCheck:getValueArray invalid data:" + this.getValue());
34653 expand : function ()
34656 Roo.form.ComboCheck.superclass.expand.call(this);
34657 this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
34658 //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
34663 collapse : function(){
34664 Roo.form.ComboCheck.superclass.collapse.call(this);
34665 var sl = this.view.getSelectedIndexes();
34666 var st = this.store;
34670 Roo.each(sl, function(i) {
34672 nv.push(r.get(this.valueField));
34674 this.setValue(Roo.encode(nv));
34675 if (this.value != this.valueBefore) {
34677 this.fireEvent('change', this, this.value, this.valueBefore);
34678 this.valueBefore = this.value;
34683 setValue : function(v){
34687 var vals = this.getValueArray();
34689 Roo.each(vals, function(k) {
34690 var r = this.findRecord(this.valueField, k);
34692 tv.push(r.data[this.displayField]);
34693 }else if(this.valueNotFoundText !== undefined){
34694 tv.push( this.valueNotFoundText );
34699 Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
34700 this.hiddenField.value = v;
34706 * Ext JS Library 1.1.1
34707 * Copyright(c) 2006-2007, Ext JS, LLC.
34709 * Originally Released Under LGPL - original licence link has changed is not relivant.
34712 * <script type="text/javascript">
34716 * @class Roo.form.Signature
34717 * @extends Roo.form.Field
34721 * @param {Object} config Configuration options
34724 Roo.form.Signature = function(config){
34725 Roo.form.Signature.superclass.constructor.call(this, config);
34727 this.addEvents({// not in used??
34730 * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
34731 * @param {Roo.form.Signature} combo This combo box
34736 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
34737 * @param {Roo.form.ComboBox} combo This combo box
34738 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
34744 Roo.extend(Roo.form.Signature, Roo.form.Field, {
34746 * @cfg {Object} labels Label to use when rendering a form.
34750 * confirm : "Confirm"
34755 confirm : "Confirm"
34758 * @cfg {Number} width The signature panel width (defaults to 300)
34762 * @cfg {Number} height The signature panel height (defaults to 100)
34766 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
34768 allowBlank : false,
34771 // {Object} signPanel The signature SVG panel element (defaults to {})
34773 // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
34774 isMouseDown : false,
34775 // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
34776 isConfirmed : false,
34777 // {String} signatureTmp SVG mapping string (defaults to empty string)
34781 defaultAutoCreate : { // modified by initCompnoent..
34787 onRender : function(ct, position){
34789 Roo.form.Signature.superclass.onRender.call(this, ct, position);
34791 this.wrap = this.el.wrap({
34792 cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
34795 this.createToolbar(this);
34796 this.signPanel = this.wrap.createChild({
34798 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
34802 this.svgID = Roo.id();
34803 this.svgEl = this.signPanel.createChild({
34804 xmlns : 'http://www.w3.org/2000/svg',
34806 id : this.svgID + "-svg",
34808 height: this.height,
34809 viewBox: '0 0 '+this.width+' '+this.height,
34813 id: this.svgID + "-svg-r",
34815 height: this.height,
34820 id: this.svgID + "-svg-l",
34822 y1: (this.height*0.8), // start set the line in 80% of height
34823 x2: this.width, // end
34824 y2: (this.height*0.8), // end set the line in 80% of height
34826 'stroke-width': "1",
34827 'stroke-dasharray': "3",
34828 'shape-rendering': "crispEdges",
34829 'pointer-events': "none"
34833 id: this.svgID + "-svg-p",
34835 'stroke-width': "3",
34837 'pointer-events': 'none'
34842 this.svgBox = this.svgEl.dom.getScreenCTM();
34844 createSVG : function(){
34845 var svg = this.signPanel;
34846 var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
34849 r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
34850 r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
34851 r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
34852 r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
34853 r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
34854 r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
34855 r.addEventListener('touchend', function(e) { return t.up(e); }, false);
34858 isTouchEvent : function(e){
34859 return e.type.match(/^touch/);
34861 getCoords : function (e) {
34862 var pt = this.svgEl.dom.createSVGPoint();
34865 if (this.isTouchEvent(e)) {
34866 pt.x = e.targetTouches[0].clientX;
34867 pt.y = e.targetTouches[0].clientY;
34869 var a = this.svgEl.dom.getScreenCTM();
34870 var b = a.inverse();
34871 var mx = pt.matrixTransform(b);
34872 return mx.x + ',' + mx.y;
34874 //mouse event headler
34875 down : function (e) {
34876 this.signatureTmp += 'M' + this.getCoords(e) + ' ';
34877 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
34879 this.isMouseDown = true;
34881 e.preventDefault();
34883 move : function (e) {
34884 if (this.isMouseDown) {
34885 this.signatureTmp += 'L' + this.getCoords(e) + ' ';
34886 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
34889 e.preventDefault();
34891 up : function (e) {
34892 this.isMouseDown = false;
34893 var sp = this.signatureTmp.split(' ');
34896 if(!sp[sp.length-2].match(/^L/)){
34900 this.signatureTmp = sp.join(" ");
34903 if(this.getValue() != this.signatureTmp){
34904 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
34905 this.isConfirmed = false;
34907 e.preventDefault();
34911 * Protected method that will not generally be called directly. It
34912 * is called when the editor creates its toolbar. Override this method if you need to
34913 * add custom toolbar buttons.
34914 * @param {HtmlEditor} editor
34916 createToolbar : function(editor){
34917 function btn(id, toggle, handler){
34918 var xid = fid + '-'+ id ;
34922 cls : 'x-btn-icon x-edit-'+id,
34923 enableToggle:toggle !== false,
34924 scope: editor, // was editor...
34925 handler:handler||editor.relayBtnCmd,
34926 clickEvent:'mousedown',
34927 tooltip: etb.buttonTips[id] || undefined, ///tips ???
34933 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
34937 cls : ' x-signature-btn x-signature-'+id,
34938 scope: editor, // was editor...
34939 handler: this.reset,
34940 clickEvent:'mousedown',
34941 text: this.labels.clear
34948 cls : ' x-signature-btn x-signature-'+id,
34949 scope: editor, // was editor...
34950 handler: this.confirmHandler,
34951 clickEvent:'mousedown',
34952 text: this.labels.confirm
34959 * when user is clicked confirm then show this image.....
34961 * @return {String} Image Data URI
34963 getImageDataURI : function(){
34964 var svg = this.svgEl.dom.parentNode.innerHTML;
34965 var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
34970 * @return {Boolean} this.isConfirmed
34972 getConfirmed : function(){
34973 return this.isConfirmed;
34977 * @return {Number} this.width
34979 getWidth : function(){
34984 * @return {Number} this.height
34986 getHeight : function(){
34987 return this.height;
34990 getSignature : function(){
34991 return this.signatureTmp;
34994 reset : function(){
34995 this.signatureTmp = '';
34996 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
34997 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
34998 this.isConfirmed = false;
34999 Roo.form.Signature.superclass.reset.call(this);
35001 setSignature : function(s){
35002 this.signatureTmp = s;
35003 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
35004 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
35006 this.isConfirmed = false;
35007 Roo.form.Signature.superclass.reset.call(this);
35010 // Roo.log(this.signPanel.dom.contentWindow.up())
35013 setConfirmed : function(){
35017 // Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
35020 confirmHandler : function(){
35021 if(!this.getSignature()){
35025 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
35026 this.setValue(this.getSignature());
35027 this.isConfirmed = true;
35029 this.fireEvent('confirm', this);
35032 // Subclasses should provide the validation implementation by overriding this
35033 validateValue : function(value){
35034 if(this.allowBlank){
35038 if(this.isConfirmed){
35045 * Ext JS Library 1.1.1
35046 * Copyright(c) 2006-2007, Ext JS, LLC.
35048 * Originally Released Under LGPL - original licence link has changed is not relivant.
35051 * <script type="text/javascript">
35056 * @class Roo.form.ComboBox
35057 * @extends Roo.form.TriggerField
35058 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
35060 * Create a new ComboBox.
35061 * @param {Object} config Configuration options
35063 Roo.form.Select = function(config){
35064 Roo.form.Select.superclass.constructor.call(this, config);
35068 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
35070 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
35073 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
35074 * rendering into an Roo.Editor, defaults to false)
35077 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
35078 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
35081 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
35084 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
35085 * the dropdown list (defaults to undefined, with no header element)
35089 * @cfg {String/Roo.Template} tpl The template to use to render the output
35093 defaultAutoCreate : {tag: "select" },
35095 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
35097 listWidth: undefined,
35099 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
35100 * mode = 'remote' or 'text' if mode = 'local')
35102 displayField: undefined,
35104 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
35105 * mode = 'remote' or 'value' if mode = 'local').
35106 * Note: use of a valueField requires the user make a selection
35107 * in order for a value to be mapped.
35109 valueField: undefined,
35113 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
35114 * field's data value (defaults to the underlying DOM element's name)
35116 hiddenName: undefined,
35118 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
35122 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
35124 selectedClass: 'x-combo-selected',
35126 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
35127 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
35128 * which displays a downward arrow icon).
35130 triggerClass : 'x-form-arrow-trigger',
35132 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
35136 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
35137 * anchor positions (defaults to 'tl-bl')
35139 listAlign: 'tl-bl?',
35141 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
35145 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
35146 * query specified by the allQuery config option (defaults to 'query')
35148 triggerAction: 'query',
35150 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
35151 * (defaults to 4, does not apply if editable = false)
35155 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
35156 * delay (typeAheadDelay) if it matches a known value (defaults to false)
35160 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
35161 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
35165 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
35166 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
35170 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
35171 * when editable = true (defaults to false)
35173 selectOnFocus:false,
35175 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
35177 queryParam: 'query',
35179 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
35180 * when mode = 'remote' (defaults to 'Loading...')
35182 loadingText: 'Loading...',
35184 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
35188 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
35192 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
35193 * traditional select (defaults to true)
35197 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
35201 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
35205 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
35206 * listWidth has a higher value)
35210 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
35211 * allow the user to set arbitrary text into the field (defaults to false)
35213 forceSelection:false,
35215 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
35216 * if typeAhead = true (defaults to 250)
35218 typeAheadDelay : 250,
35220 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
35221 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
35223 valueNotFoundText : undefined,
35226 * @cfg {String} defaultValue The value displayed after loading the store.
35231 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
35233 blockFocus : false,
35236 * @cfg {Boolean} disableClear Disable showing of clear button.
35238 disableClear : false,
35240 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
35242 alwaysQuery : false,
35248 // element that contains real text value.. (when hidden is used..)
35251 onRender : function(ct, position){
35252 Roo.form.Field.prototype.onRender.call(this, ct, position);
35255 this.store.on('beforeload', this.onBeforeLoad, this);
35256 this.store.on('load', this.onLoad, this);
35257 this.store.on('loadexception', this.onLoadException, this);
35258 this.store.load({});
35266 initEvents : function(){
35267 //Roo.form.ComboBox.superclass.initEvents.call(this);
35271 onDestroy : function(){
35274 this.store.un('beforeload', this.onBeforeLoad, this);
35275 this.store.un('load', this.onLoad, this);
35276 this.store.un('loadexception', this.onLoadException, this);
35278 //Roo.form.ComboBox.superclass.onDestroy.call(this);
35282 fireKey : function(e){
35283 if(e.isNavKeyPress() && !this.list.isVisible()){
35284 this.fireEvent("specialkey", this, e);
35289 onResize: function(w, h){
35297 * Allow or prevent the user from directly editing the field text. If false is passed,
35298 * the user will only be able to select from the items defined in the dropdown list. This method
35299 * is the runtime equivalent of setting the 'editable' config option at config time.
35300 * @param {Boolean} value True to allow the user to directly edit the field text
35302 setEditable : function(value){
35307 onBeforeLoad : function(){
35309 Roo.log("Select before load");
35312 this.innerList.update(this.loadingText ?
35313 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
35314 //this.restrictHeight();
35315 this.selectedIndex = -1;
35319 onLoad : function(){
35322 var dom = this.el.dom;
35323 dom.innerHTML = '';
35324 var od = dom.ownerDocument;
35326 if (this.emptyText) {
35327 var op = od.createElement('option');
35328 op.setAttribute('value', '');
35329 op.innerHTML = String.format('{0}', this.emptyText);
35330 dom.appendChild(op);
35332 if(this.store.getCount() > 0){
35334 var vf = this.valueField;
35335 var df = this.displayField;
35336 this.store.data.each(function(r) {
35337 // which colmsn to use... testing - cdoe / title..
35338 var op = od.createElement('option');
35339 op.setAttribute('value', r.data[vf]);
35340 op.innerHTML = String.format('{0}', r.data[df]);
35341 dom.appendChild(op);
35343 if (typeof(this.defaultValue != 'undefined')) {
35344 this.setValue(this.defaultValue);
35349 //this.onEmptyResults();
35354 onLoadException : function()
35356 dom.innerHTML = '';
35358 Roo.log("Select on load exception");
35362 Roo.log(this.store.reader.jsonData);
35363 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
35364 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
35370 onTypeAhead : function(){
35375 onSelect : function(record, index){
35376 Roo.log('on select?');
35378 if(this.fireEvent('beforeselect', this, record, index) !== false){
35379 this.setFromData(index > -1 ? record.data : false);
35381 this.fireEvent('select', this, record, index);
35386 * Returns the currently selected field value or empty string if no value is set.
35387 * @return {String} value The selected value
35389 getValue : function(){
35390 var dom = this.el.dom;
35391 this.value = dom.options[dom.selectedIndex].value;
35397 * Clears any text/value currently set in the field
35399 clearValue : function(){
35401 this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
35406 * Sets the specified value into the field. If the value finds a match, the corresponding record text
35407 * will be displayed in the field. If the value does not match the data value of an existing item,
35408 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
35409 * Otherwise the field will be blank (although the value will still be set).
35410 * @param {String} value The value to match
35412 setValue : function(v){
35413 var d = this.el.dom;
35414 for (var i =0; i < d.options.length;i++) {
35415 if (v == d.options[i].value) {
35416 d.selectedIndex = i;
35424 * @property {Object} the last set data for the element
35429 * Sets the value of the field based on a object which is related to the record format for the store.
35430 * @param {Object} value the value to set as. or false on reset?
35432 setFromData : function(o){
35433 Roo.log('setfrom data?');
35439 reset : function(){
35443 findRecord : function(prop, value){
35448 if(this.store.getCount() > 0){
35449 this.store.each(function(r){
35450 if(r.data[prop] == value){
35460 getName: function()
35462 // returns hidden if it's set..
35463 if (!this.rendered) {return ''};
35464 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
35472 onEmptyResults : function(){
35473 Roo.log('empty results');
35478 * Returns true if the dropdown list is expanded, else false.
35480 isExpanded : function(){
35485 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
35486 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
35487 * @param {String} value The data value of the item to select
35488 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
35489 * selected item if it is not currently in view (defaults to true)
35490 * @return {Boolean} True if the value matched an item in the list, else false
35492 selectByValue : function(v, scrollIntoView){
35493 Roo.log('select By Value');
35496 if(v !== undefined && v !== null){
35497 var r = this.findRecord(this.valueField || this.displayField, v);
35499 this.select(this.store.indexOf(r), scrollIntoView);
35507 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
35508 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
35509 * @param {Number} index The zero-based index of the list item to select
35510 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
35511 * selected item if it is not currently in view (defaults to true)
35513 select : function(index, scrollIntoView){
35514 Roo.log('select ');
35517 this.selectedIndex = index;
35518 this.view.select(index);
35519 if(scrollIntoView !== false){
35520 var el = this.view.getNode(index);
35522 this.innerList.scrollChildIntoView(el, false);
35530 validateBlur : function(){
35537 initQuery : function(){
35538 this.doQuery(this.getRawValue());
35542 doForce : function(){
35543 if(this.el.dom.value.length > 0){
35544 this.el.dom.value =
35545 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
35551 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
35552 * query allowing the query action to be canceled if needed.
35553 * @param {String} query The SQL query to execute
35554 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
35555 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
35556 * saved in the current store (defaults to false)
35558 doQuery : function(q, forceAll){
35560 Roo.log('doQuery?');
35561 if(q === undefined || q === null){
35566 forceAll: forceAll,
35570 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
35574 forceAll = qe.forceAll;
35575 if(forceAll === true || (q.length >= this.minChars)){
35576 if(this.lastQuery != q || this.alwaysQuery){
35577 this.lastQuery = q;
35578 if(this.mode == 'local'){
35579 this.selectedIndex = -1;
35581 this.store.clearFilter();
35583 this.store.filter(this.displayField, q);
35587 this.store.baseParams[this.queryParam] = q;
35589 params: this.getParams(q)
35594 this.selectedIndex = -1;
35601 getParams : function(q){
35603 //p[this.queryParam] = q;
35606 p.limit = this.pageSize;
35612 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
35614 collapse : function(){
35619 collapseIf : function(e){
35624 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
35626 expand : function(){
35634 * @cfg {Boolean} grow
35638 * @cfg {Number} growMin
35642 * @cfg {Number} growMax
35650 setWidth : function()
35654 getResizeEl : function(){
35657 });//<script type="text/javasscript">
35661 * @class Roo.DDView
35662 * A DnD enabled version of Roo.View.
35663 * @param {Element/String} container The Element in which to create the View.
35664 * @param {String} tpl The template string used to create the markup for each element of the View
35665 * @param {Object} config The configuration properties. These include all the config options of
35666 * {@link Roo.View} plus some specific to this class.<br>
35668 * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
35669 * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
35671 * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
35672 .x-view-drag-insert-above {
35673 border-top:1px dotted #3366cc;
35675 .x-view-drag-insert-below {
35676 border-bottom:1px dotted #3366cc;
35682 Roo.DDView = function(container, tpl, config) {
35683 Roo.DDView.superclass.constructor.apply(this, arguments);
35684 this.getEl().setStyle("outline", "0px none");
35685 this.getEl().unselectable();
35686 if (this.dragGroup) {
35687 this.setDraggable(this.dragGroup.split(","));
35689 if (this.dropGroup) {
35690 this.setDroppable(this.dropGroup.split(","));
35692 if (this.deletable) {
35693 this.setDeletable();
35695 this.isDirtyFlag = false;
35701 Roo.extend(Roo.DDView, Roo.View, {
35702 /** @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
35703 /** @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
35704 /** @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
35705 /** @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
35709 reset: Roo.emptyFn,
35711 clearInvalid: Roo.form.Field.prototype.clearInvalid,
35713 validate: function() {
35717 destroy: function() {
35718 this.purgeListeners();
35719 this.getEl.removeAllListeners();
35720 this.getEl().remove();
35721 if (this.dragZone) {
35722 if (this.dragZone.destroy) {
35723 this.dragZone.destroy();
35726 if (this.dropZone) {
35727 if (this.dropZone.destroy) {
35728 this.dropZone.destroy();
35733 /** Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
35734 getName: function() {
35738 /** Loads the View from a JSON string representing the Records to put into the Store. */
35739 setValue: function(v) {
35741 throw "DDView.setValue(). DDView must be constructed with a valid Store";
35744 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
35745 this.store.proxy = new Roo.data.MemoryProxy(data);
35749 /** @return {String} a parenthesised list of the ids of the Records in the View. */
35750 getValue: function() {
35752 this.store.each(function(rec) {
35753 result += rec.id + ',';
35755 return result.substr(0, result.length - 1) + ')';
35758 getIds: function() {
35759 var i = 0, result = new Array(this.store.getCount());
35760 this.store.each(function(rec) {
35761 result[i++] = rec.id;
35766 isDirty: function() {
35767 return this.isDirtyFlag;
35771 * Part of the Roo.dd.DropZone interface. If no target node is found, the
35772 * whole Element becomes the target, and this causes the drop gesture to append.
35774 getTargetFromEvent : function(e) {
35775 var target = e.getTarget();
35776 while ((target !== null) && (target.parentNode != this.el.dom)) {
35777 target = target.parentNode;
35780 target = this.el.dom.lastChild || this.el.dom;
35786 * Create the drag data which consists of an object which has the property "ddel" as
35787 * the drag proxy element.
35789 getDragData : function(e) {
35790 var target = this.findItemFromChild(e.getTarget());
35792 this.handleSelection(e);
35793 var selNodes = this.getSelectedNodes();
35796 copy: this.copy || (this.allowCopy && e.ctrlKey),
35800 var selectedIndices = this.getSelectedIndexes();
35801 for (var i = 0; i < selectedIndices.length; i++) {
35802 dragData.records.push(this.store.getAt(selectedIndices[i]));
35804 if (selNodes.length == 1) {
35805 dragData.ddel = target.cloneNode(true); // the div element
35807 var div = document.createElement('div'); // create the multi element drag "ghost"
35808 div.className = 'multi-proxy';
35809 for (var i = 0, len = selNodes.length; i < len; i++) {
35810 div.appendChild(selNodes[i].cloneNode(true));
35812 dragData.ddel = div;
35814 //console.log(dragData)
35815 //console.log(dragData.ddel.innerHTML)
35818 //console.log('nodragData')
35822 /** Specify to which ddGroup items in this DDView may be dragged. */
35823 setDraggable: function(ddGroup) {
35824 if (ddGroup instanceof Array) {
35825 Roo.each(ddGroup, this.setDraggable, this);
35828 if (this.dragZone) {
35829 this.dragZone.addToGroup(ddGroup);
35831 this.dragZone = new Roo.dd.DragZone(this.getEl(), {
35832 containerScroll: true,
35836 // Draggability implies selection. DragZone's mousedown selects the element.
35837 if (!this.multiSelect) { this.singleSelect = true; }
35839 // Wire the DragZone's handlers up to methods in *this*
35840 this.dragZone.getDragData = this.getDragData.createDelegate(this);
35844 /** Specify from which ddGroup this DDView accepts drops. */
35845 setDroppable: function(ddGroup) {
35846 if (ddGroup instanceof Array) {
35847 Roo.each(ddGroup, this.setDroppable, this);
35850 if (this.dropZone) {
35851 this.dropZone.addToGroup(ddGroup);
35853 this.dropZone = new Roo.dd.DropZone(this.getEl(), {
35854 containerScroll: true,
35858 // Wire the DropZone's handlers up to methods in *this*
35859 this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
35860 this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
35861 this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
35862 this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
35863 this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
35867 /** Decide whether to drop above or below a View node. */
35868 getDropPoint : function(e, n, dd){
35869 if (n == this.el.dom) { return "above"; }
35870 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
35871 var c = t + (b - t) / 2;
35872 var y = Roo.lib.Event.getPageY(e);
35880 onNodeEnter : function(n, dd, e, data){
35884 onNodeOver : function(n, dd, e, data){
35885 var pt = this.getDropPoint(e, n, dd);
35886 // set the insert point style on the target node
35887 var dragElClass = this.dropNotAllowed;
35890 if (pt == "above"){
35891 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
35892 targetElClass = "x-view-drag-insert-above";
35894 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
35895 targetElClass = "x-view-drag-insert-below";
35897 if (this.lastInsertClass != targetElClass){
35898 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
35899 this.lastInsertClass = targetElClass;
35902 return dragElClass;
35905 onNodeOut : function(n, dd, e, data){
35906 this.removeDropIndicators(n);
35909 onNodeDrop : function(n, dd, e, data){
35910 if (this.fireEvent("drop", this, n, dd, e, data) === false) {
35913 var pt = this.getDropPoint(e, n, dd);
35914 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
35915 if (pt == "below") { insertAt++; }
35916 for (var i = 0; i < data.records.length; i++) {
35917 var r = data.records[i];
35918 var dup = this.store.getById(r.id);
35919 if (dup && (dd != this.dragZone)) {
35920 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
35923 this.store.insert(insertAt++, r.copy());
35925 data.source.isDirtyFlag = true;
35927 this.store.insert(insertAt++, r);
35929 this.isDirtyFlag = true;
35932 this.dragZone.cachedTarget = null;
35936 removeDropIndicators : function(n){
35938 Roo.fly(n).removeClass([
35939 "x-view-drag-insert-above",
35940 "x-view-drag-insert-below"]);
35941 this.lastInsertClass = "_noclass";
35946 * Utility method. Add a delete option to the DDView's context menu.
35947 * @param {String} imageUrl The URL of the "delete" icon image.
35949 setDeletable: function(imageUrl) {
35950 if (!this.singleSelect && !this.multiSelect) {
35951 this.singleSelect = true;
35953 var c = this.getContextMenu();
35954 this.contextMenu.on("itemclick", function(item) {
35957 this.remove(this.getSelectedIndexes());
35961 this.contextMenu.add({
35968 /** Return the context menu for this DDView. */
35969 getContextMenu: function() {
35970 if (!this.contextMenu) {
35971 // Create the View's context menu
35972 this.contextMenu = new Roo.menu.Menu({
35973 id: this.id + "-contextmenu"
35975 this.el.on("contextmenu", this.showContextMenu, this);
35977 return this.contextMenu;
35980 disableContextMenu: function() {
35981 if (this.contextMenu) {
35982 this.el.un("contextmenu", this.showContextMenu, this);
35986 showContextMenu: function(e, item) {
35987 item = this.findItemFromChild(e.getTarget());
35990 this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
35991 this.contextMenu.showAt(e.getXY());
35996 * Remove {@link Roo.data.Record}s at the specified indices.
35997 * @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
35999 remove: function(selectedIndices) {
36000 selectedIndices = [].concat(selectedIndices);
36001 for (var i = 0; i < selectedIndices.length; i++) {
36002 var rec = this.store.getAt(selectedIndices[i]);
36003 this.store.remove(rec);
36008 * Double click fires the event, but also, if this is draggable, and there is only one other
36009 * related DropZone, it transfers the selected node.
36011 onDblClick : function(e){
36012 var item = this.findItemFromChild(e.getTarget());
36014 if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
36017 if (this.dragGroup) {
36018 var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
36019 while (targets.indexOf(this.dropZone) > -1) {
36020 targets.remove(this.dropZone);
36022 if (targets.length == 1) {
36023 this.dragZone.cachedTarget = null;
36024 var el = Roo.get(targets[0].getEl());
36025 var box = el.getBox(true);
36026 targets[0].onNodeDrop(el.dom, {
36028 xy: [box.x, box.y + box.height - 1]
36029 }, null, this.getDragData(e));
36035 handleSelection: function(e) {
36036 this.dragZone.cachedTarget = null;
36037 var item = this.findItemFromChild(e.getTarget());
36039 this.clearSelections(true);
36042 if (item && (this.multiSelect || this.singleSelect)){
36043 if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
36044 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
36045 }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
36046 this.unselect(item);
36048 this.select(item, this.multiSelect && e.ctrlKey);
36049 this.lastSelection = item;
36054 onItemClick : function(item, index, e){
36055 if(this.fireEvent("beforeclick", this, index, item, e) === false){
36061 unselect : function(nodeInfo, suppressEvent){
36062 var node = this.getNode(nodeInfo);
36063 if(node && this.isSelected(node)){
36064 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
36065 Roo.fly(node).removeClass(this.selectedClass);
36066 this.selections.remove(node);
36067 if(!suppressEvent){
36068 this.fireEvent("selectionchange", this, this.selections);
36076 * Ext JS Library 1.1.1
36077 * Copyright(c) 2006-2007, Ext JS, LLC.
36079 * Originally Released Under LGPL - original licence link has changed is not relivant.
36082 * <script type="text/javascript">
36086 * @class Roo.layout.Manager
36087 * @extends Roo.util.Observable
36088 * Base class for layout managers.
36090 Roo.layout.Manager = function(container, config){
36091 Roo.layout.Manager.superclass.constructor.call(this);
36092 this.el = Roo.get(container);
36093 // ie scrollbar fix
36094 if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
36095 document.body.scroll = "no";
36096 }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
36097 this.el.position('relative');
36099 this.id = this.el.id;
36100 this.el.addClass("x-layout-container");
36101 /** false to disable window resize monitoring @type Boolean */
36102 this.monitorWindowResize = true;
36107 * Fires when a layout is performed.
36108 * @param {Roo.layout.Manager} this
36112 * @event regionresized
36113 * Fires when the user resizes a region.
36114 * @param {Roo.layout.Region} region The resized region
36115 * @param {Number} newSize The new size (width for east/west, height for north/south)
36117 "regionresized" : true,
36119 * @event regioncollapsed
36120 * Fires when a region is collapsed.
36121 * @param {Roo.layout.Region} region The collapsed region
36123 "regioncollapsed" : true,
36125 * @event regionexpanded
36126 * Fires when a region is expanded.
36127 * @param {Roo.layout.Region} region The expanded region
36129 "regionexpanded" : true
36131 this.updating = false;
36132 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
36135 Roo.extend(Roo.layout.Manager, Roo.util.Observable, {
36137 * Returns true if this layout is currently being updated
36138 * @return {Boolean}
36140 isUpdating : function(){
36141 return this.updating;
36145 * Suspend the LayoutManager from doing auto-layouts while
36146 * making multiple add or remove calls
36148 beginUpdate : function(){
36149 this.updating = true;
36153 * Restore auto-layouts and optionally disable the manager from performing a layout
36154 * @param {Boolean} noLayout true to disable a layout update
36156 endUpdate : function(noLayout){
36157 this.updating = false;
36163 layout: function(){
36167 onRegionResized : function(region, newSize){
36168 this.fireEvent("regionresized", region, newSize);
36172 onRegionCollapsed : function(region){
36173 this.fireEvent("regioncollapsed", region);
36176 onRegionExpanded : function(region){
36177 this.fireEvent("regionexpanded", region);
36181 * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
36182 * performs box-model adjustments.
36183 * @return {Object} The size as an object {width: (the width), height: (the height)}
36185 getViewSize : function(){
36187 if(this.el.dom != document.body){
36188 size = this.el.getSize();
36190 size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
36192 size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
36193 size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
36198 * Returns the Element this layout is bound to.
36199 * @return {Roo.Element}
36201 getEl : function(){
36206 * Returns the specified region.
36207 * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
36208 * @return {Roo.layout.Region}
36210 getRegion : function(target){
36211 return this.regions[target.toLowerCase()];
36214 onWindowResize : function(){
36215 if(this.monitorWindowResize){
36221 * Ext JS Library 1.1.1
36222 * Copyright(c) 2006-2007, Ext JS, LLC.
36224 * Originally Released Under LGPL - original licence link has changed is not relivant.
36227 * <script type="text/javascript">
36230 * @class Roo.layout.Border
36231 * @extends Roo.layout.Manager
36232 * @children Roo.panel.Content
36233 * This class represents a common layout manager used in desktop applications. For screenshots and more details,
36234 * please see: <br><br>
36235 * <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>
36236 * <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>
36239 var layout = new Roo.layout.Border(document.body, {
36273 preferredTabWidth: 150
36278 var CP = Roo.panel.Content;
36280 layout.beginUpdate();
36281 layout.add("north", new CP("north", "North"));
36282 layout.add("south", new CP("south", {title: "South", closable: true}));
36283 layout.add("west", new CP("west", {title: "West"}));
36284 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
36285 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
36286 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
36287 layout.getRegion("center").showPanel("center1");
36288 layout.endUpdate();
36291 <b>The container the layout is rendered into can be either the body element or any other element.
36292 If it is not the body element, the container needs to either be an absolute positioned element,
36293 or you will need to add "position:relative" to the css of the container. You will also need to specify
36294 the container size if it is not the body element.</b>
36297 * Create a new BorderLayout
36298 * @param {String/HTMLElement/Element} container The container this layout is bound to
36299 * @param {Object} config Configuration options
36301 Roo.layout.Border = function(container, config){
36302 config = config || {};
36303 Roo.layout.Border.superclass.constructor.call(this, container, config);
36304 this.factory = config.factory || Roo.layout.Border.RegionFactory;
36305 for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
36306 var target = this.factory.validRegions[i];
36307 if(config[target]){
36308 this.addRegion(target, config[target]);
36313 Roo.extend(Roo.layout.Border, Roo.layout.Manager, {
36316 * @cfg {Roo.layout.Region} east
36319 * @cfg {Roo.layout.Region} west
36322 * @cfg {Roo.layout.Region} north
36325 * @cfg {Roo.layout.Region} south
36328 * @cfg {Roo.layout.Region} center
36331 * Creates and adds a new region if it doesn't already exist.
36332 * @param {String} target The target region key (north, south, east, west or center).
36333 * @param {Object} config The regions config object
36334 * @return {BorderLayoutRegion} The new region
36336 addRegion : function(target, config){
36337 if(!this.regions[target]){
36338 var r = this.factory.create(target, this, config);
36339 this.bindRegion(target, r);
36341 return this.regions[target];
36345 bindRegion : function(name, r){
36346 this.regions[name] = r;
36347 r.on("visibilitychange", this.layout, this);
36348 r.on("paneladded", this.layout, this);
36349 r.on("panelremoved", this.layout, this);
36350 r.on("invalidated", this.layout, this);
36351 r.on("resized", this.onRegionResized, this);
36352 r.on("collapsed", this.onRegionCollapsed, this);
36353 r.on("expanded", this.onRegionExpanded, this);
36357 * Performs a layout update.
36359 layout : function(){
36360 if(this.updating) {
36363 var size = this.getViewSize();
36364 var w = size.width;
36365 var h = size.height;
36370 //var x = 0, y = 0;
36372 var rs = this.regions;
36373 var north = rs["north"];
36374 var south = rs["south"];
36375 var west = rs["west"];
36376 var east = rs["east"];
36377 var center = rs["center"];
36378 //if(this.hideOnLayout){ // not supported anymore
36379 //c.el.setStyle("display", "none");
36381 if(north && north.isVisible()){
36382 var b = north.getBox();
36383 var m = north.getMargins();
36384 b.width = w - (m.left+m.right);
36387 centerY = b.height + b.y + m.bottom;
36388 centerH -= centerY;
36389 north.updateBox(this.safeBox(b));
36391 if(south && south.isVisible()){
36392 var b = south.getBox();
36393 var m = south.getMargins();
36394 b.width = w - (m.left+m.right);
36396 var totalHeight = (b.height + m.top + m.bottom);
36397 b.y = h - totalHeight + m.top;
36398 centerH -= totalHeight;
36399 south.updateBox(this.safeBox(b));
36401 if(west && west.isVisible()){
36402 var b = west.getBox();
36403 var m = west.getMargins();
36404 b.height = centerH - (m.top+m.bottom);
36406 b.y = centerY + m.top;
36407 var totalWidth = (b.width + m.left + m.right);
36408 centerX += totalWidth;
36409 centerW -= totalWidth;
36410 west.updateBox(this.safeBox(b));
36412 if(east && east.isVisible()){
36413 var b = east.getBox();
36414 var m = east.getMargins();
36415 b.height = centerH - (m.top+m.bottom);
36416 var totalWidth = (b.width + m.left + m.right);
36417 b.x = w - totalWidth + m.left;
36418 b.y = centerY + m.top;
36419 centerW -= totalWidth;
36420 east.updateBox(this.safeBox(b));
36423 var m = center.getMargins();
36425 x: centerX + m.left,
36426 y: centerY + m.top,
36427 width: centerW - (m.left+m.right),
36428 height: centerH - (m.top+m.bottom)
36430 //if(this.hideOnLayout){
36431 //center.el.setStyle("display", "block");
36433 center.updateBox(this.safeBox(centerBox));
36436 this.fireEvent("layout", this);
36440 safeBox : function(box){
36441 box.width = Math.max(0, box.width);
36442 box.height = Math.max(0, box.height);
36447 * Adds a ContentPanel (or subclass) to this layout.
36448 * @param {String} target The target region key (north, south, east, west or center).
36449 * @param {Roo.panel.Content} panel The panel to add
36450 * @return {Roo.panel.Content} The added panel
36452 add : function(target, panel){
36454 target = target.toLowerCase();
36455 return this.regions[target].add(panel);
36459 * Remove a ContentPanel (or subclass) to this layout.
36460 * @param {String} target The target region key (north, south, east, west or center).
36461 * @param {Number/String/Roo.panel.Content} panel The index, id or panel to remove
36462 * @return {Roo.panel.Content} The removed panel
36464 remove : function(target, panel){
36465 target = target.toLowerCase();
36466 return this.regions[target].remove(panel);
36470 * Searches all regions for a panel with the specified id
36471 * @param {String} panelId
36472 * @return {Roo.panel.Content} The panel or null if it wasn't found
36474 findPanel : function(panelId){
36475 var rs = this.regions;
36476 for(var target in rs){
36477 if(typeof rs[target] != "function"){
36478 var p = rs[target].getPanel(panelId);
36488 * Searches all regions for a panel with the specified id and activates (shows) it.
36489 * @param {String/panel.Content} panelId The panels id or the panel itself
36490 * @return {Roo.panel.Content} The shown panel or null
36492 showPanel : function(panelId) {
36493 var rs = this.regions;
36494 for(var target in rs){
36495 var r = rs[target];
36496 if(typeof r != "function"){
36497 if(r.hasPanel(panelId)){
36498 return r.showPanel(panelId);
36506 * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
36507 * @param {Roo.state.Provider} provider (optional) An alternate state provider
36509 restoreState : function(provider){
36511 provider = Roo.state.Manager;
36513 var sm = new Roo.layout.StateManager();
36514 sm.init(this, provider);
36518 * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object. This config
36519 * object should contain properties for each region to add ContentPanels to, and each property's value should be
36520 * a valid ContentPanel config object. Example:
36522 // Create the main layout
36523 var layout = new Roo.layout.Border('main-ct', {
36534 // Create and add multiple ContentPanels at once via configs
36537 id: 'source-files',
36539 title:'Ext Source Files',
36552 * @param {Object} regions An object containing ContentPanel configs by region name
36554 batchAdd : function(regions){
36555 this.beginUpdate();
36556 for(var rname in regions){
36557 var lr = this.regions[rname];
36559 this.addTypedPanels(lr, regions[rname]);
36566 addTypedPanels : function(lr, ps){
36567 if(typeof ps == 'string'){
36568 lr.add(new Roo.panel.Content(ps));
36570 else if(ps instanceof Array){
36571 for(var i =0, len = ps.length; i < len; i++){
36572 this.addTypedPanels(lr, ps[i]);
36575 else if(!ps.events){ // raw config?
36577 delete ps.el; // prevent conflict
36578 lr.add(new Roo.panel.Content(el || Roo.id(), ps));
36580 else { // panel object assumed!
36585 * Adds a xtype elements to the layout.
36589 xtype : 'ContentPanel',
36596 xtype : 'NestedLayoutPanel',
36602 items : [ ... list of content panels or nested layout panels.. ]
36606 * @param {Object} cfg Xtype definition of item to add.
36608 addxtype : function(cfg)
36610 // basically accepts a pannel...
36611 // can accept a layout region..!?!?
36612 //Roo.log('Roo.layout.Border add ' + cfg.xtype)
36614 // if (!cfg.xtype.match(/Panel$/)) {
36619 if (typeof(cfg.region) == 'undefined') {
36620 Roo.log("Failed to add Panel, region was not set");
36624 var region = cfg.region;
36630 xitems = cfg.items;
36638 if(cfg.autoCreate) {
36639 ret = new Roo.panel[cfg.xtype](cfg); // new panel!!!!!
36641 var el = this.el.createChild();
36642 ret = new Roo.panel[cfg.xtype](el, cfg); // new panel!!!!!
36645 this.add(region, ret);
36648 // needs grid and region
36650 //var el = this.getRegion(region).el.createChild();
36651 var el = this.el.createChild();
36652 // create the grid first...
36654 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
36656 if (region == 'center' && this.active ) {
36657 cfg.background = false;
36659 ret = new Roo.panel[cfg.xtype](grid, cfg); // new panel!!!!!
36661 this.add(region, ret);
36662 if (cfg.background) {
36663 ret.on('activate', function(gp) {
36664 if (!gp.grid.rendered) {
36672 case 'NestedLayout':
36673 // create a new Layout (which is a Border Layout...
36674 var el = this.el.createChild();
36675 var clayout = cfg.layout;
36677 clayout.items = clayout.items || [];
36678 // replace this exitems with the clayout ones..
36679 xitems = clayout.items;
36682 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
36683 cfg.background = false;
36685 var layout = new Roo.layout.Border(el, clayout);
36687 ret = new Roo.panel[cfg.xtype](layout, cfg); // new panel!!!!!
36688 //console.log('adding nested layout panel ' + cfg.toSource());
36689 this.add(region, ret);
36690 nb = {}; /// find first...
36694 ret = new Roo.panel[cfg.xtype](cfg); // new panel!!!!!
36695 this.add(region, ret);
36697 case 'Tree': // our new panel!
36698 cfg.el = this.el.createChild();
36699 ret = new Roo.panel[cfg.xtype](cfg); // new panel!!!!!
36700 this.add(region, ret);
36702 case 'ContentPanel':
36703 case 'ScrollPanel': // ContentPanel (el, cfg)
36705 if(cfg.autoCreate) {
36706 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
36708 var el = this.el.createChild();
36709 ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
36712 this.add(region, ret);
36716 case 'TreePanel': // our new panel!
36717 cfg.el = this.el.createChild();
36718 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
36719 this.add(region, ret);
36722 case 'NestedLayoutPanel':
36723 // create a new Layout (which is a Border Layout...
36724 var el = this.el.createChild();
36725 var clayout = cfg.layout;
36727 clayout.items = clayout.items || [];
36728 // replace this exitems with the clayout ones..
36729 xitems = clayout.items;
36732 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
36733 cfg.background = false;
36735 var layout = new Roo.layout.Border(el, clayout);
36737 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
36738 //console.log('adding nested layout panel ' + cfg.toSource());
36739 this.add(region, ret);
36740 nb = {}; /// find first...
36745 // needs grid and region
36747 //var el = this.getRegion(region).el.createChild();
36748 var el = this.el.createChild();
36749 // create the grid first...
36751 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
36753 if (region == 'center' && this.active ) {
36754 cfg.background = false;
36756 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
36758 this.add(region, ret);
36759 if (cfg.background) {
36760 ret.on('activate', function(gp) {
36761 if (!gp.grid.rendered) {
36776 if (typeof(Roo[cfg.xtype]) != 'undefined') {
36778 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
36779 this.add(region, ret);
36782 alert("Can not add '" + cfg.xtype + "' to BorderLayout");
36786 // GridPanel (grid, cfg)
36789 this.beginUpdate();
36793 Roo.each(xitems, function(i) {
36794 region = nb && i.region ? i.region : false;
36796 var add = ret.addxtype(i);
36799 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
36800 if (!i.background) {
36801 abn[region] = nb[region] ;
36808 // make the last non-background panel active..
36809 //if (nb) { Roo.log(abn); }
36812 for(var r in abn) {
36813 region = this.getRegion(r);
36815 // tried using nb[r], but it does not work..
36817 region.showPanel(abn[r]);
36828 * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
36829 * the beginUpdate and endUpdate calls internally. The key to this method is the <b>panels</b> property that can be
36830 * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
36831 * during creation. The following code is equivalent to the constructor-based example at the beginning of this class:
36834 var CP = Roo.ContentPanel;
36836 var layout = Roo.layout.Border.create({
36840 panels: [new CP("north", "North")]
36849 panels: [new CP("west", {title: "West"})]
36858 panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
36867 panels: [new CP("south", {title: "South", closable: true})]
36874 preferredTabWidth: 150,
36876 new CP("center1", {title: "Close Me", closable: true}),
36877 new CP("center2", {title: "Center Panel", closable: false})
36882 layout.getRegion("center").showPanel("center1");
36887 Roo.layout.Border.create = function(config, targetEl){
36888 var layout = new Roo.layout.Border(targetEl || document.body, config);
36889 layout.beginUpdate();
36890 var regions = Roo.layout.Border.RegionFactory.validRegions;
36891 for(var j = 0, jlen = regions.length; j < jlen; j++){
36892 var lr = regions[j];
36893 if(layout.regions[lr] && config[lr].panels){
36894 var r = layout.regions[lr];
36895 var ps = config[lr].panels;
36896 layout.addTypedPanels(r, ps);
36899 layout.endUpdate();
36904 Roo.layout.Border.RegionFactory = {
36906 validRegions : ["north","south","east","west","center"],
36909 create : function(target, mgr, config){
36910 target = target.toLowerCase();
36911 if(config.lightweight || config.basic){
36912 return new Roo.layout.BasicRegion(mgr, config, target);
36914 var cn = target.charAt(0).toUpperCase() + target.slice(1);
36915 if (typeof (Roo.layout[cn]) == 'undefined') {
36916 throw 'Layout region "'+target+'" not supported.';
36918 return new Roo.layout[cn](mgr, config);
36924 * Ext JS Library 1.1.1
36925 * Copyright(c) 2006-2007, Ext JS, LLC.
36927 * Originally Released Under LGPL - original licence link has changed is not relivant.
36930 * <script type="text/javascript">
36934 * @class Roo.layout.BasicRegion
36935 * @extends Roo.util.Observable
36936 * This class represents a lightweight region in a layout manager. This region does not move dom nodes
36937 * and does not have a titlebar, tabs or any other features. All it does is size and position
36938 * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
36940 Roo.layout.BasicRegion= function(mgr, config, pos, skipConfig){
36942 this.position = pos;
36945 * @scope Roo.layout.BasicRegion
36949 * @event beforeremove
36950 * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
36951 * @param {Roo.layout.Region} this
36952 * @param {Roo.panel.Content} panel The panel
36953 * @param {Object} e The cancel event object
36955 "beforeremove" : true,
36957 * @event invalidated
36958 * Fires when the layout for this region is changed.
36959 * @param {Roo.layout.Region} this
36961 "invalidated" : true,
36963 * @event visibilitychange
36964 * Fires when this region is shown or hidden
36965 * @param {Roo.layout.Region} this
36966 * @param {Boolean} visibility true or false
36968 "visibilitychange" : true,
36970 * @event paneladded
36971 * Fires when a panel is added.
36972 * @param {Roo.layout.Region} this
36973 * @param {Roo.panel.Content} panel The panel
36975 "paneladded" : true,
36977 * @event panelremoved
36978 * Fires when a panel is removed.
36979 * @param {Roo.layout.Region} this
36980 * @param {Roo.panel.Content} panel The panel
36982 "panelremoved" : true,
36984 * @event beforecollapse
36985 * Fires when this region before collapse.
36986 * @param {Roo.layout.Region} this
36988 "beforecollapse" : true,
36991 * Fires when this region is collapsed.
36992 * @param {Roo.layout.Region} this
36994 "collapsed" : true,
36997 * Fires when this region is expanded.
36998 * @param {Roo.layout.Region} this
37003 * Fires when this region is slid into view.
37004 * @param {Roo.layout.Region} this
37006 "slideshow" : true,
37009 * Fires when this region slides out of view.
37010 * @param {Roo.layout.Region} this
37012 "slidehide" : true,
37014 * @event panelactivated
37015 * Fires when a panel is activated.
37016 * @param {Roo.layout.Region} this
37017 * @param {Roo.panel.Content} panel The activated panel
37019 "panelactivated" : true,
37022 * Fires when the user resizes this region.
37023 * @param {Roo.layout.Region} this
37024 * @param {Number} newSize The new size (width for east/west, height for north/south)
37028 /** A collection of panels in this region. @type Roo.util.MixedCollection */
37029 this.panels = new Roo.util.MixedCollection();
37030 this.panels.getKey = this.getPanelId.createDelegate(this);
37032 this.activePanel = null;
37033 // ensure listeners are added...
37035 if (config.listeners || config.events) {
37036 Roo.layout.BasicRegion.superclass.constructor.call(this, {
37037 listeners : config.listeners || {},
37038 events : config.events || {}
37042 if(skipConfig !== true){
37043 this.applyConfig(config);
37047 Roo.extend(Roo.layout.BasicRegion, Roo.util.Observable, {
37048 getPanelId : function(p){
37052 applyConfig : function(config){
37053 this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
37054 this.config = config;
37059 * Resizes the region to the specified size. For vertical regions (west, east) this adjusts
37060 * the width, for horizontal (north, south) the height.
37061 * @param {Number} newSize The new width or height
37063 resizeTo : function(newSize){
37064 var el = this.el ? this.el :
37065 (this.activePanel ? this.activePanel.getEl() : null);
37067 switch(this.position){
37070 el.setWidth(newSize);
37071 this.fireEvent("resized", this, newSize);
37075 el.setHeight(newSize);
37076 this.fireEvent("resized", this, newSize);
37082 getBox : function(){
37083 return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
37086 getMargins : function(){
37087 return this.margins;
37090 updateBox : function(box){
37092 var el = this.activePanel.getEl();
37093 el.dom.style.left = box.x + "px";
37094 el.dom.style.top = box.y + "px";
37095 this.activePanel.setSize(box.width, box.height);
37099 * Returns the container element for this region.
37100 * @return {Roo.Element}
37102 getEl : function(){
37103 return this.activePanel;
37107 * Returns true if this region is currently visible.
37108 * @return {Boolean}
37110 isVisible : function(){
37111 return this.activePanel ? true : false;
37114 setActivePanel : function(panel){
37115 panel = this.getPanel(panel);
37116 if(this.activePanel && this.activePanel != panel){
37117 this.activePanel.setActiveState(false);
37118 this.activePanel.getEl().setLeftTop(-10000,-10000);
37120 this.activePanel = panel;
37121 panel.setActiveState(true);
37123 panel.setSize(this.box.width, this.box.height);
37125 this.fireEvent("panelactivated", this, panel);
37126 this.fireEvent("invalidated");
37130 * Show the specified panel.
37131 * @param {Number/String/panel.Content} panelId The panels index, id or the panel itself
37132 * @return {Roo.panel.Content} The shown panel or null
37134 showPanel : function(panel){
37135 if(panel = this.getPanel(panel)){
37136 this.setActivePanel(panel);
37142 * Get the active panel for this region.
37143 * @return {Roo.panel.Content} The active panel or null
37145 getActivePanel : function(){
37146 return this.activePanel;
37150 * Add the passed ContentPanel(s)
37151 * @param {panel.Content...} panel The ContentPanel(s) to add (you can pass more than one)
37152 * @return {Roo.panel.Content} The panel added (if only one was added)
37154 add : function(panel){
37155 if(arguments.length > 1){
37156 for(var i = 0, len = arguments.length; i < len; i++) {
37157 this.add(arguments[i]);
37161 if(this.hasPanel(panel)){
37162 this.showPanel(panel);
37165 var el = panel.getEl();
37166 if(el.dom.parentNode != this.mgr.el.dom){
37167 this.mgr.el.dom.appendChild(el.dom);
37169 if(panel.setRegion){
37170 panel.setRegion(this);
37172 this.panels.add(panel);
37173 el.setStyle("position", "absolute");
37174 if(!panel.background){
37175 this.setActivePanel(panel);
37176 if(this.config.initialSize && this.panels.getCount()==1){
37177 this.resizeTo(this.config.initialSize);
37180 this.fireEvent("paneladded", this, panel);
37185 * Returns true if the panel is in this region.
37186 * @param {Number/String/panel.Content} panel The panels index, id or the panel itself
37187 * @return {Boolean}
37189 hasPanel : function(panel){
37190 if(typeof panel == "object"){ // must be panel obj
37191 panel = panel.getId();
37193 return this.getPanel(panel) ? true : false;
37197 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
37198 * @param {Number/String/panel.Content} panel The panels index, id or the panel itself
37199 * @param {Boolean} preservePanel Overrides the config preservePanel option
37200 * @return {Roo.panel.Content} The panel that was removed
37202 remove : function(panel, preservePanel){
37203 panel = this.getPanel(panel);
37208 this.fireEvent("beforeremove", this, panel, e);
37209 if(e.cancel === true){
37212 var panelId = panel.getId();
37213 this.panels.removeKey(panelId);
37218 * Returns the panel specified or null if it's not in this region.
37219 * @param {Number/String/panel.Content} panel The panels index, id or the panel itself
37220 * @return {Roo.panel.Content}
37222 getPanel : function(id){
37223 if(typeof id == "object"){ // must be panel obj
37226 return this.panels.get(id);
37230 * Returns this regions position (north/south/east/west/center).
37233 getPosition: function(){
37234 return this.position;
37238 * Ext JS Library 1.1.1
37239 * Copyright(c) 2006-2007, Ext JS, LLC.
37241 * Originally Released Under LGPL - original licence link has changed is not relivant.
37244 * <script type="text/javascript">
37248 * @class Roo.layout.Region
37249 * @extends Roo.layout.BasicRegion
37250 * This class represents a region in a layout manager.
37251 * @cfg {Boolean} collapsible False to disable collapsing (defaults to true)
37252 * @cfg {Boolean} collapsed True to set the initial display to collapsed (defaults to false)
37253 * @cfg {Boolean} floatable False to disable floating (defaults to true)
37254 * @cfg {Object} margins Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
37255 * @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})
37256 * @cfg {String} tabPosition (top|bottom) "top" or "bottom" (defaults to "bottom")
37257 * @cfg {String} collapsedTitle Optional string message to display in the collapsed block of a north or south region
37258 * @cfg {Boolean} alwaysShowTabs True to always display tabs even when there is only 1 panel (defaults to false)
37259 * @cfg {Boolean} autoScroll True to enable overflow scrolling (defaults to false)
37260 * @cfg {Boolean} titlebar True to display a title bar (defaults to true)
37261 * @cfg {String} title The title for the region (overrides panel titles)
37262 * @cfg {Boolean} animate True to animate expand/collapse (defaults to false)
37263 * @cfg {Boolean} autoHide False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
37264 * @cfg {Boolean} preservePanels True to preserve removed panels so they can be readded later (defaults to false)
37265 * @cfg {Boolean} closeOnTab True to place the close icon on the tabs instead of the region titlebar (defaults to false)
37266 * @cfg {Boolean} hideTabs True to hide the tab strip (defaults to false)
37267 * @cfg {Boolean} resizeTabs True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
37268 * the space available, similar to FireFox 1.5 tabs (defaults to false)
37269 * @cfg {Number} minTabWidth The minimum tab width (defaults to 40)
37270 * @cfg {Number} preferredTabWidth The preferred tab width (defaults to 150)
37271 * @cfg {Boolean} showPin True to show a pin button
37272 * @cfg {Boolean} hidden True to start the region hidden (defaults to false)
37273 * @cfg {Boolean} hideWhenEmpty True to hide the region when it has no panels
37274 * @cfg {Boolean} disableTabTips True to disable tab tooltips
37275 * @cfg {Number} width For East/West panels
37276 * @cfg {Number} height For North/South panels
37277 * @cfg {Boolean} split To show the splitter
37278 * @cfg {Boolean} toolbar xtype configuration for a toolbar - shows on right of tabbar
37280 Roo.layout.Region = function(mgr, config, pos){
37281 Roo.layout.Region.superclass.constructor.call(this, mgr, config, pos, true);
37282 var dh = Roo.DomHelper;
37283 /** This region's container element
37284 * @type Roo.Element */
37285 this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
37286 /** This region's title element
37287 * @type Roo.Element */
37289 this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
37290 {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: " "},
37291 {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
37293 this.titleEl.enableDisplayMode();
37294 /** This region's title text element
37295 * @type HTMLElement */
37296 this.titleTextEl = this.titleEl.dom.firstChild;
37297 this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
37298 this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
37299 this.closeBtn.enableDisplayMode();
37300 this.closeBtn.on("click", this.closeClicked, this);
37301 this.closeBtn.hide();
37303 this.createBody(config);
37304 this.visible = true;
37305 this.collapsed = false;
37307 if(config.hideWhenEmpty){
37309 this.on("paneladded", this.validateVisibility, this);
37310 this.on("panelremoved", this.validateVisibility, this);
37312 this.applyConfig(config);
37315 Roo.extend(Roo.layout.Region, Roo.layout.BasicRegion, {
37317 createBody : function(){
37318 /** This region's body element
37319 * @type Roo.Element */
37320 this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
37323 applyConfig : function(c){
37324 if(c.collapsible && this.position != "center" && !this.collapsedEl){
37325 var dh = Roo.DomHelper;
37326 if(c.titlebar !== false){
37327 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
37328 this.collapseBtn.on("click", this.collapse, this);
37329 this.collapseBtn.enableDisplayMode();
37331 if(c.showPin === true || this.showPin){
37332 this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
37333 this.stickBtn.enableDisplayMode();
37334 this.stickBtn.on("click", this.expand, this);
37335 this.stickBtn.hide();
37338 /** This region's collapsed element
37339 * @type Roo.Element */
37340 this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
37341 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
37343 if(c.floatable !== false){
37344 this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
37345 this.collapsedEl.on("click", this.collapseClick, this);
37348 if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
37349 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
37350 id: "message", unselectable: "on", style:{"float":"left"}});
37351 this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
37353 this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
37354 this.expandBtn.on("click", this.expand, this);
37356 if(this.collapseBtn){
37357 this.collapseBtn.setVisible(c.collapsible == true);
37359 this.cmargins = c.cmargins || this.cmargins ||
37360 (this.position == "west" || this.position == "east" ?
37361 {top: 0, left: 2, right:2, bottom: 0} :
37362 {top: 2, left: 0, right:0, bottom: 2});
37363 this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
37364 this.bottomTabs = c.tabPosition != "top";
37365 this.autoScroll = c.autoScroll || false;
37366 if(this.autoScroll){
37367 this.bodyEl.setStyle("overflow", "auto");
37369 this.bodyEl.setStyle("overflow", "hidden");
37371 //if(c.titlebar !== false){
37372 if((!c.titlebar && !c.title) || c.titlebar === false){
37373 this.titleEl.hide();
37375 this.titleEl.show();
37377 this.titleTextEl.innerHTML = c.title;
37381 this.duration = c.duration || .30;
37382 this.slideDuration = c.slideDuration || .45;
37385 this.collapse(true);
37392 * Returns true if this region is currently visible.
37393 * @return {Boolean}
37395 isVisible : function(){
37396 return this.visible;
37400 * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
37401 * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&#160;")
37403 setCollapsedTitle : function(title){
37404 title = title || " ";
37405 if(this.collapsedTitleTextEl){
37406 this.collapsedTitleTextEl.innerHTML = title;
37410 getBox : function(){
37412 if(!this.collapsed){
37413 b = this.el.getBox(false, true);
37415 b = this.collapsedEl.getBox(false, true);
37420 getMargins : function(){
37421 return this.collapsed ? this.cmargins : this.margins;
37424 highlight : function(){
37425 this.el.addClass("x-layout-panel-dragover");
37428 unhighlight : function(){
37429 this.el.removeClass("x-layout-panel-dragover");
37432 updateBox : function(box){
37434 if(!this.collapsed){
37435 this.el.dom.style.left = box.x + "px";
37436 this.el.dom.style.top = box.y + "px";
37437 this.updateBody(box.width, box.height);
37439 this.collapsedEl.dom.style.left = box.x + "px";
37440 this.collapsedEl.dom.style.top = box.y + "px";
37441 this.collapsedEl.setSize(box.width, box.height);
37444 this.tabs.autoSizeTabs();
37448 updateBody : function(w, h){
37450 this.el.setWidth(w);
37451 w -= this.el.getBorderWidth("rl");
37452 if(this.config.adjustments){
37453 w += this.config.adjustments[0];
37457 this.el.setHeight(h);
37458 h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
37459 h -= this.el.getBorderWidth("tb");
37460 if(this.config.adjustments){
37461 h += this.config.adjustments[1];
37463 this.bodyEl.setHeight(h);
37465 h = this.tabs.syncHeight(h);
37468 if(this.panelSize){
37469 w = w !== null ? w : this.panelSize.width;
37470 h = h !== null ? h : this.panelSize.height;
37472 if(this.activePanel){
37473 var el = this.activePanel.getEl();
37474 w = w !== null ? w : el.getWidth();
37475 h = h !== null ? h : el.getHeight();
37476 this.panelSize = {width: w, height: h};
37477 this.activePanel.setSize(w, h);
37479 if(Roo.isIE && this.tabs){
37480 this.tabs.el.repaint();
37485 * Returns the container element for this region.
37486 * @return {Roo.Element}
37488 getEl : function(){
37493 * Hides this region.
37496 if(!this.collapsed){
37497 this.el.dom.style.left = "-2000px";
37500 this.collapsedEl.dom.style.left = "-2000px";
37501 this.collapsedEl.hide();
37503 this.visible = false;
37504 this.fireEvent("visibilitychange", this, false);
37508 * Shows this region if it was previously hidden.
37511 if(!this.collapsed){
37514 this.collapsedEl.show();
37516 this.visible = true;
37517 this.fireEvent("visibilitychange", this, true);
37520 closeClicked : function(){
37521 if(this.activePanel){
37522 this.remove(this.activePanel);
37526 collapseClick : function(e){
37528 e.stopPropagation();
37531 e.stopPropagation();
37537 * Collapses this region.
37538 * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
37540 collapse : function(skipAnim, skipCheck){
37541 if(this.collapsed) {
37545 if(skipCheck || this.fireEvent("beforecollapse", this) != false){
37547 this.collapsed = true;
37549 this.split.el.hide();
37551 if(this.config.animate && skipAnim !== true){
37552 this.fireEvent("invalidated", this);
37553 this.animateCollapse();
37555 this.el.setLocation(-20000,-20000);
37557 this.collapsedEl.show();
37558 this.fireEvent("collapsed", this);
37559 this.fireEvent("invalidated", this);
37565 animateCollapse : function(){
37570 * Expands this region if it was previously collapsed.
37571 * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
37572 * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
37574 expand : function(e, skipAnim){
37576 e.stopPropagation();
37578 if(!this.collapsed || this.el.hasActiveFx()) {
37582 this.afterSlideIn();
37585 this.collapsed = false;
37586 if(this.config.animate && skipAnim !== true){
37587 this.animateExpand();
37591 this.split.el.show();
37593 this.collapsedEl.setLocation(-2000,-2000);
37594 this.collapsedEl.hide();
37595 this.fireEvent("invalidated", this);
37596 this.fireEvent("expanded", this);
37600 animateExpand : function(){
37604 initTabs : function()
37606 this.bodyEl.setStyle("overflow", "hidden");
37607 var ts = new Roo.panel.Tab(
37610 tabPosition: this.bottomTabs ? 'bottom' : 'top',
37611 disableTooltips: this.config.disableTabTips,
37612 toolbar : this.config.toolbar
37615 if(this.config.hideTabs){
37616 ts.stripWrap.setDisplayed(false);
37619 ts.resizeTabs = this.config.resizeTabs === true;
37620 ts.minTabWidth = this.config.minTabWidth || 40;
37621 ts.maxTabWidth = this.config.maxTabWidth || 250;
37622 ts.preferredTabWidth = this.config.preferredTabWidth || 150;
37623 ts.monitorResize = false;
37624 ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
37625 ts.bodyEl.addClass('x-layout-tabs-body');
37626 this.panels.each(this.initPanelAsTab, this);
37629 initPanelAsTab : function(panel){
37630 var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
37631 this.config.closeOnTab && panel.isClosable());
37632 if(panel.tabTip !== undefined){
37633 ti.setTooltip(panel.tabTip);
37635 ti.on("activate", function(){
37636 this.setActivePanel(panel);
37638 if(this.config.closeOnTab){
37639 ti.on("beforeclose", function(t, e){
37641 this.remove(panel);
37647 updatePanelTitle : function(panel, title){
37648 if(this.activePanel == panel){
37649 this.updateTitle(title);
37652 var ti = this.tabs.getTab(panel.getEl().id);
37654 if(panel.tabTip !== undefined){
37655 ti.setTooltip(panel.tabTip);
37660 updateTitle : function(title){
37661 if(this.titleTextEl && !this.config.title){
37662 this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : " ");
37666 setActivePanel : function(panel){
37667 panel = this.getPanel(panel);
37668 if(this.activePanel && this.activePanel != panel){
37669 this.activePanel.setActiveState(false);
37671 this.activePanel = panel;
37672 panel.setActiveState(true);
37673 if(this.panelSize){
37674 panel.setSize(this.panelSize.width, this.panelSize.height);
37677 this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
37679 this.updateTitle(panel.getTitle());
37681 this.fireEvent("invalidated", this);
37683 this.fireEvent("panelactivated", this, panel);
37687 * Shows the specified panel.
37688 * @param {Number/String/panel.Content} panelId The panel's index, id or the panel itself
37689 * @return {Roo.panel.Content} The shown panel, or null if a panel could not be found from panelId
37691 showPanel : function(panel)
37693 panel = this.getPanel(panel);
37696 var tab = this.tabs.getTab(panel.getEl().id);
37697 if(tab.isHidden()){
37698 this.tabs.unhideTab(tab.id);
37702 this.setActivePanel(panel);
37709 * Get the active panel for this region.
37710 * @return {Roo.panel.Content} The active panel or null
37712 getActivePanel : function(){
37713 return this.activePanel;
37716 validateVisibility : function(){
37717 if(this.panels.getCount() < 1){
37718 this.updateTitle(" ");
37719 this.closeBtn.hide();
37722 if(!this.isVisible()){
37729 * Adds the passed ContentPanel(s) to this region.
37730 * @param {panel.Content...} panel The ContentPanel(s) to add (you can pass more than one)
37731 * @return {Roo.panel.Content} The panel added (if only one was added; null otherwise)
37733 add : function(panel){
37734 if(arguments.length > 1){
37735 for(var i = 0, len = arguments.length; i < len; i++) {
37736 this.add(arguments[i]);
37740 if(this.hasPanel(panel)){
37741 this.showPanel(panel);
37744 panel.setRegion(this);
37745 this.panels.add(panel);
37746 if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
37747 this.bodyEl.dom.appendChild(panel.getEl().dom);
37748 if(panel.background !== true){
37749 this.setActivePanel(panel);
37751 this.fireEvent("paneladded", this, panel);
37757 this.initPanelAsTab(panel);
37759 if(panel.background !== true){
37760 this.tabs.activate(panel.getEl().id);
37762 this.fireEvent("paneladded", this, panel);
37767 * Hides the tab for the specified panel.
37768 * @param {Number/String/panel.Content} panel The panel's index, id or the panel itself
37770 hidePanel : function(panel){
37771 if(this.tabs && (panel = this.getPanel(panel))){
37772 this.tabs.hideTab(panel.getEl().id);
37777 * Unhides the tab for a previously hidden panel.
37778 * @param {Number/String/panel.Content} panel The panel's index, id or the panel itself
37780 unhidePanel : function(panel){
37781 if(this.tabs && (panel = this.getPanel(panel))){
37782 this.tabs.unhideTab(panel.getEl().id);
37786 clearPanels : function(){
37787 while(this.panels.getCount() > 0){
37788 this.remove(this.panels.first());
37793 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
37794 * @param {Number/String/panel.Content} panel The panel's index, id or the panel itself
37795 * @param {Boolean} preservePanel Overrides the config preservePanel option
37796 * @return {Roo.panel.Content} The panel that was removed
37798 remove : function(panel, preservePanel){
37799 panel = this.getPanel(panel);
37804 this.fireEvent("beforeremove", this, panel, e);
37805 if(e.cancel === true){
37808 preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
37809 var panelId = panel.getId();
37810 this.panels.removeKey(panelId);
37812 document.body.appendChild(panel.getEl().dom);
37815 this.tabs.removeTab(panel.getEl().id);
37816 }else if (!preservePanel){
37817 this.bodyEl.dom.removeChild(panel.getEl().dom);
37819 if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
37820 var p = this.panels.first();
37821 var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
37822 tempEl.appendChild(p.getEl().dom);
37823 this.bodyEl.update("");
37824 this.bodyEl.dom.appendChild(p.getEl().dom);
37826 this.updateTitle(p.getTitle());
37828 this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
37829 this.setActivePanel(p);
37831 panel.setRegion(null);
37832 if(this.activePanel == panel){
37833 this.activePanel = null;
37835 if(this.config.autoDestroy !== false && preservePanel !== true){
37836 try{panel.destroy();}catch(e){}
37838 this.fireEvent("panelremoved", this, panel);
37843 * Returns the TabPanel component used by this region
37844 * @return {Roo.panel.Tab}
37846 getTabs : function(){
37850 createTool : function(parentEl, className){
37851 var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
37852 children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: " "}]}, true);
37853 btn.addClassOnOver("x-layout-tools-button-over");
37858 * Ext JS Library 1.1.1
37859 * Copyright(c) 2006-2007, Ext JS, LLC.
37861 * Originally Released Under LGPL - original licence link has changed is not relivant.
37864 * <script type="text/javascript">
37870 * @class Roo.layout.SplitRegion
37871 * @extends Roo.layout.Region
37872 * Adds a splitbar and other (private) useful functionality to a {@link Roo.layout.Region}.
37874 Roo.layout.SplitRegion = function(mgr, config, pos, cursor){
37875 this.cursor = cursor;
37876 Roo.layout.SplitRegion.superclass.constructor.call(this, mgr, config, pos);
37879 Roo.extend(Roo.layout.SplitRegion, Roo.layout.Region, {
37880 splitTip : "Drag to resize.",
37881 collapsibleSplitTip : "Drag to resize. Double click to hide.",
37882 useSplitTips : false,
37884 applyConfig : function(config){
37885 Roo.layout.SplitRegion.superclass.applyConfig.call(this, config);
37888 var splitEl = Roo.DomHelper.append(this.mgr.el.dom,
37889 {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: " "});
37890 /** The SplitBar for this region
37891 * @type Roo.SplitBar */
37892 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
37893 this.split.on("moved", this.onSplitMove, this);
37894 this.split.useShim = config.useShim === true;
37895 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
37896 if(this.useSplitTips){
37897 this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
37899 if(config.collapsible){
37900 this.split.el.on("dblclick", this.collapse, this);
37903 if(typeof config.minSize != "undefined"){
37904 this.split.minSize = config.minSize;
37906 if(typeof config.maxSize != "undefined"){
37907 this.split.maxSize = config.maxSize;
37909 if(config.hideWhenEmpty || config.hidden || config.collapsed){
37910 this.hideSplitter();
37915 getHMaxSize : function(){
37916 var cmax = this.config.maxSize || 10000;
37917 var center = this.mgr.getRegion("center");
37918 return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
37921 getVMaxSize : function(){
37922 var cmax = this.config.maxSize || 10000;
37923 var center = this.mgr.getRegion("center");
37924 return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
37927 onSplitMove : function(split, newSize){
37928 this.fireEvent("resized", this, newSize);
37932 * Returns the {@link Roo.SplitBar} for this region.
37933 * @return {Roo.SplitBar}
37935 getSplitBar : function(){
37940 this.hideSplitter();
37941 Roo.layout.SplitRegion.superclass.hide.call(this);
37944 hideSplitter : function(){
37946 this.split.el.setLocation(-2000,-2000);
37947 this.split.el.hide();
37953 this.split.el.show();
37955 Roo.layout.SplitRegion.superclass.show.call(this);
37958 beforeSlide: function(){
37959 if(Roo.isGecko){// firefox overflow auto bug workaround
37960 this.bodyEl.clip();
37962 this.tabs.bodyEl.clip();
37964 if(this.activePanel){
37965 this.activePanel.getEl().clip();
37967 if(this.activePanel.beforeSlide){
37968 this.activePanel.beforeSlide();
37974 afterSlide : function(){
37975 if(Roo.isGecko){// firefox overflow auto bug workaround
37976 this.bodyEl.unclip();
37978 this.tabs.bodyEl.unclip();
37980 if(this.activePanel){
37981 this.activePanel.getEl().unclip();
37982 if(this.activePanel.afterSlide){
37983 this.activePanel.afterSlide();
37989 initAutoHide : function(){
37990 if(this.autoHide !== false){
37991 if(!this.autoHideHd){
37992 var st = new Roo.util.DelayedTask(this.slideIn, this);
37993 this.autoHideHd = {
37994 "mouseout": function(e){
37995 if(!e.within(this.el, true)){
37999 "mouseover" : function(e){
38005 this.el.on(this.autoHideHd);
38009 clearAutoHide : function(){
38010 if(this.autoHide !== false){
38011 this.el.un("mouseout", this.autoHideHd.mouseout);
38012 this.el.un("mouseover", this.autoHideHd.mouseover);
38016 clearMonitor : function(){
38017 Roo.get(document).un("click", this.slideInIf, this);
38020 // these names are backwards but not changed for compat
38021 slideOut : function(){
38022 if(this.isSlid || this.el.hasActiveFx()){
38025 this.isSlid = true;
38026 if(this.collapseBtn){
38027 this.collapseBtn.hide();
38029 this.closeBtnState = this.closeBtn.getStyle('display');
38030 this.closeBtn.hide();
38032 this.stickBtn.show();
38035 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
38036 this.beforeSlide();
38037 this.el.setStyle("z-index", 10001);
38038 this.el.slideIn(this.getSlideAnchor(), {
38039 callback: function(){
38041 this.initAutoHide();
38042 Roo.get(document).on("click", this.slideInIf, this);
38043 this.fireEvent("slideshow", this);
38050 afterSlideIn : function(){
38051 this.clearAutoHide();
38052 this.isSlid = false;
38053 this.clearMonitor();
38054 this.el.setStyle("z-index", "");
38055 if(this.collapseBtn){
38056 this.collapseBtn.show();
38058 this.closeBtn.setStyle('display', this.closeBtnState);
38060 this.stickBtn.hide();
38062 this.fireEvent("slidehide", this);
38065 slideIn : function(cb){
38066 if(!this.isSlid || this.el.hasActiveFx()){
38070 this.isSlid = false;
38071 this.beforeSlide();
38072 this.el.slideOut(this.getSlideAnchor(), {
38073 callback: function(){
38074 this.el.setLeftTop(-10000, -10000);
38076 this.afterSlideIn();
38084 slideInIf : function(e){
38085 if(!e.within(this.el)){
38090 animateCollapse : function(){
38091 this.beforeSlide();
38092 this.el.setStyle("z-index", 20000);
38093 var anchor = this.getSlideAnchor();
38094 this.el.slideOut(anchor, {
38095 callback : function(){
38096 this.el.setStyle("z-index", "");
38097 this.collapsedEl.slideIn(anchor, {duration:.3});
38099 this.el.setLocation(-10000,-10000);
38101 this.fireEvent("collapsed", this);
38108 animateExpand : function(){
38109 this.beforeSlide();
38110 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
38111 this.el.setStyle("z-index", 20000);
38112 this.collapsedEl.hide({
38115 this.el.slideIn(this.getSlideAnchor(), {
38116 callback : function(){
38117 this.el.setStyle("z-index", "");
38120 this.split.el.show();
38122 this.fireEvent("invalidated", this);
38123 this.fireEvent("expanded", this);
38151 getAnchor : function(){
38152 return this.anchors[this.position];
38155 getCollapseAnchor : function(){
38156 return this.canchors[this.position];
38159 getSlideAnchor : function(){
38160 return this.sanchors[this.position];
38163 getAlignAdj : function(){
38164 var cm = this.cmargins;
38165 switch(this.position){
38181 getExpandAdj : function(){
38182 var c = this.collapsedEl, cm = this.cmargins;
38183 switch(this.position){
38185 return [-(cm.right+c.getWidth()+cm.left), 0];
38188 return [cm.right+c.getWidth()+cm.left, 0];
38191 return [0, -(cm.top+cm.bottom+c.getHeight())];
38194 return [0, cm.top+cm.bottom+c.getHeight()];
38200 * Ext JS Library 1.1.1
38201 * Copyright(c) 2006-2007, Ext JS, LLC.
38203 * Originally Released Under LGPL - original licence link has changed is not relivant.
38206 * <script type="text/javascript">
38209 * These classes are private internal classes
38211 Roo.layout.Center = function(mgr, config){
38212 Roo.layout.Region.call(this, mgr, config, "center");
38213 this.visible = true;
38214 this.minWidth = config.minWidth || 20;
38215 this.minHeight = config.minHeight || 20;
38218 Roo.extend(Roo.layout.Center, Roo.layout.Region, {
38220 // center panel can't be hidden
38224 // center panel can't be hidden
38227 getMinWidth: function(){
38228 return this.minWidth;
38231 getMinHeight: function(){
38232 return this.minHeight;
38235 Roo.layout.West = function(mgr, config){
38236 Roo.layout.SplitRegion.call(this, mgr, config, "west", "w-resize");
38238 this.split.placement = Roo.SplitBar.LEFT;
38239 this.split.orientation = Roo.SplitBar.HORIZONTAL;
38240 this.split.el.addClass("x-layout-split-h");
38242 var size = config.initialSize || config.width;
38243 if(typeof size != "undefined"){
38244 this.el.setWidth(size);
38247 Roo.extend(Roo.layout.West, Roo.layout.SplitRegion, {
38248 orientation: Roo.SplitBar.HORIZONTAL,
38249 getBox : function(){
38250 if(this.collapsed){
38251 return this.collapsedEl.getBox();
38253 var box = this.el.getBox();
38255 box.width += this.split.el.getWidth();
38260 updateBox : function(box){
38261 if(this.split && !this.collapsed){
38262 var sw = this.split.el.getWidth();
38264 this.split.el.setLeft(box.x+box.width);
38265 this.split.el.setTop(box.y);
38266 this.split.el.setHeight(box.height);
38268 if(this.collapsed){
38269 this.updateBody(null, box.height);
38271 Roo.layout.Region.prototype.updateBox.call(this, box);
38274 Roo.layout.East = function(mgr, config){
38275 Roo.layout.SplitRegion.call(this, mgr, config, "east", "e-resize");
38277 this.split.placement = Roo.SplitBar.RIGHT;
38278 this.split.orientation = Roo.SplitBar.HORIZONTAL;
38279 this.split.el.addClass("x-layout-split-h");
38281 var size = config.initialSize || config.width;
38282 if(typeof size != "undefined"){
38283 this.el.setWidth(size);
38286 Roo.extend(Roo.layout.East, Roo.layout.SplitRegion, {
38287 orientation: Roo.SplitBar.HORIZONTAL,
38288 getBox : function(){
38289 if(this.collapsed){
38290 return this.collapsedEl.getBox();
38292 var box = this.el.getBox();
38294 var sw = this.split.el.getWidth();
38301 updateBox : function(box){
38302 if(this.split && !this.collapsed){
38303 var sw = this.split.el.getWidth();
38305 this.split.el.setLeft(box.x);
38306 this.split.el.setTop(box.y);
38307 this.split.el.setHeight(box.height);
38310 if(this.collapsed){
38311 this.updateBody(null, box.height);
38313 Roo.layout.Region.prototype.updateBox.call(this, box);
38315 });Roo.layout.South = function(mgr, config){
38316 Roo.layout.SplitRegion.call(this, mgr, config, "south", "s-resize");
38318 this.split.placement = Roo.SplitBar.BOTTOM;
38319 this.split.orientation = Roo.SplitBar.VERTICAL;
38320 this.split.el.addClass("x-layout-split-v");
38322 var size = config.initialSize || config.height;
38323 if(typeof size != "undefined"){
38324 this.el.setHeight(size);
38327 Roo.extend(Roo.layout.South, Roo.layout.SplitRegion, {
38328 orientation: Roo.SplitBar.VERTICAL,
38329 getBox : function(){
38330 if(this.collapsed){
38331 return this.collapsedEl.getBox();
38333 var box = this.el.getBox();
38335 var sh = this.split.el.getHeight();
38342 updateBox : function(box){
38343 if(this.split && !this.collapsed){
38344 var sh = this.split.el.getHeight();
38347 this.split.el.setLeft(box.x);
38348 this.split.el.setTop(box.y-sh);
38349 this.split.el.setWidth(box.width);
38351 if(this.collapsed){
38352 this.updateBody(box.width, null);
38354 Roo.layout.Region.prototype.updateBox.call(this, box);
38359 Roo.layout.North = function(mgr, config){
38360 Roo.layout.Region.call(this, mgr, config, "north", "n-resize");
38362 this.split.placement = Roo.SplitBar.TOP;
38363 this.split.orientation = Roo.SplitBar.VERTICAL;
38364 this.split.el.addClass("x-layout-split-v");
38366 var size = config.initialSize || config.height;
38367 if(typeof size != "undefined"){
38368 this.el.setHeight(size);
38371 Roo.extend(Roo.layout.North, Roo.layout.SplitRegion, {
38372 orientation: Roo.SplitBar.VERTICAL,
38373 getBox : function(){
38374 if(this.collapsed){
38375 return this.collapsedEl.getBox();
38377 var box = this.el.getBox();
38379 box.height += this.split.el.getHeight();
38384 updateBox : function(box){
38385 if(this.split && !this.collapsed){
38386 box.height -= this.split.el.getHeight();
38387 this.split.el.setLeft(box.x);
38388 this.split.el.setTop(box.y+box.height);
38389 this.split.el.setWidth(box.width);
38391 if(this.collapsed){
38392 this.updateBody(box.width, null);
38394 Roo.layout.Region.prototype.updateBox.call(this, box);
38398 * Ext JS Library 1.1.1
38399 * Copyright(c) 2006-2007, Ext JS, LLC.
38401 * Originally Released Under LGPL - original licence link has changed is not relivant.
38404 * <script type="text/javascript">
38409 * Private internal class for reading and applying state
38411 Roo.layout.StateManager = function(layout){
38412 // default empty state
38421 Roo.layout.StateManager.prototype = {
38422 init : function(layout, provider){
38423 this.provider = provider;
38424 var state = provider.get(layout.id+"-layout-state");
38426 var wasUpdating = layout.isUpdating();
38428 layout.beginUpdate();
38430 for(var key in state){
38431 if(typeof state[key] != "function"){
38432 var rstate = state[key];
38433 var r = layout.getRegion(key);
38436 r.resizeTo(rstate.size);
38438 if(rstate.collapsed == true){
38441 r.expand(null, true);
38447 layout.endUpdate();
38449 this.state = state;
38451 this.layout = layout;
38452 layout.on("regionresized", this.onRegionResized, this);
38453 layout.on("regioncollapsed", this.onRegionCollapsed, this);
38454 layout.on("regionexpanded", this.onRegionExpanded, this);
38457 storeState : function(){
38458 this.provider.set(this.layout.id+"-layout-state", this.state);
38461 onRegionResized : function(region, newSize){
38462 this.state[region.getPosition()].size = newSize;
38466 onRegionCollapsed : function(region){
38467 this.state[region.getPosition()].collapsed = true;
38471 onRegionExpanded : function(region){
38472 this.state[region.getPosition()].collapsed = false;
38477 * Ext JS Library 1.1.1
38478 * Copyright(c) 2006-2007, Ext JS, LLC.
38480 * Originally Released Under LGPL - original licence link has changed is not relivant.
38483 * <script type="text/javascript">
38486 * @class Roo.panel.Content
38487 * @extends Roo.util.Observable
38488 * @children Roo.form.Form Roo.JsonView Roo.View
38489 * @parent Roo.layout.Border Roo.LayoutDialog builder
38490 * A basic Content Panel element.
38491 * @cfg {Boolean} fitToFrame True for this panel to adjust its size to fit when the region resizes (defaults to false)
38492 * @cfg {Boolean} fitContainer When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container (defaults to false)
38493 * @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
38494 * @cfg {Boolean} closable True if the panel can be closed/removed
38495 * @cfg {Boolean} background True if the panel should not be activated when it is added (defaults to false)
38496 * @cfg {String|HTMLElement|Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
38497 * @cfg {Roo.Toolbar} toolbar A toolbar for this panel
38498 * @cfg {Boolean} autoScroll True to scroll overflow in this panel (use with {@link #fitToFrame})
38499 * @cfg {String} title The title for this panel
38500 * @cfg {Array} adjustments Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
38501 * @cfg {String} url Calls {@link #setUrl} with this value
38502 * @cfg {String} region (center|north|south|east|west) [required] which region to put this panel on (when used with xtype constructors)
38503 * @cfg {String|Object} params When used with {@link #url}, calls {@link #setUrl} with this value
38504 * @cfg {Boolean} loadOnce When used with {@link #url}, calls {@link #setUrl} with this value
38505 * @cfg {String} content Raw content to fill content panel with (uses setContent on construction.)
38506 * @cfg {String} style Extra style to add to the content panel
38507 * @cfg {Roo.menu.Menu} menu popup menu
38510 * Create a new Content Panel.
38511 * @param {String/HTMLElement/Roo.Element} el The container element for this panel
38512 * @param {String/Object} config A string to set only the title or a config object
38513 * @param {String} content (optional) Set the HTML content for this panel
38514 * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
38516 Roo.panel.Content = function(el, config, content){
38519 if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
38523 if (config && config.parentLayout) {
38524 el = config.parentLayout.el.createChild();
38527 if(el.autoCreate){ // xtype is available if this is called from factory
38531 this.el = Roo.get(el);
38532 if(!this.el && config && config.autoCreate){
38533 if(typeof config.autoCreate == "object"){
38534 if(!config.autoCreate.id){
38535 config.autoCreate.id = config.id||el;
38537 this.el = Roo.DomHelper.append(document.body,
38538 config.autoCreate, true);
38540 this.el = Roo.DomHelper.append(document.body,
38541 {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
38546 this.closable = false;
38547 this.loaded = false;
38548 this.active = false;
38549 if(typeof config == "string"){
38550 this.title = config;
38552 Roo.apply(this, config);
38555 if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
38556 this.wrapEl = this.el.wrap();
38557 this.toolbar.container = this.el.insertSibling(false, 'before');
38558 this.toolbar = new Roo.Toolbar(this.toolbar);
38561 // xtype created footer. - not sure if will work as we normally have to render first..
38562 if (this.footer && !this.footer.el && this.footer.xtype) {
38563 if (!this.wrapEl) {
38564 this.wrapEl = this.el.wrap();
38567 this.footer.container = this.wrapEl.createChild();
38569 this.footer = Roo.factory(this.footer, Roo);
38574 this.resizeEl = Roo.get(this.resizeEl, true);
38576 this.resizeEl = this.el;
38578 // handle view.xtype
38586 * Fires when this panel is activated.
38587 * @param {Roo.panel.Content} this
38591 * @event deactivate
38592 * Fires when this panel is activated.
38593 * @param {Roo.panel.Content} this
38595 "deactivate" : true,
38599 * Fires when this panel is resized if fitToFrame is true.
38600 * @param {Roo.panel.Content} this
38601 * @param {Number} width The width after any component adjustments
38602 * @param {Number} height The height after any component adjustments
38608 * Fires when this tab is created
38609 * @param {Roo.panel.Content} this
38619 if(this.autoScroll){
38620 this.resizeEl.setStyle("overflow", "auto");
38622 // fix randome scrolling
38623 this.el.on('scroll', function() {
38624 Roo.log('fix random scolling');
38625 this.scrollTo('top',0);
38628 content = content || this.content;
38630 this.setContent(content);
38632 if(config && config.url){
38633 this.setUrl(this.url, this.params, this.loadOnce);
38638 Roo.panel.Content.superclass.constructor.call(this);
38640 if (this.view && typeof(this.view.xtype) != 'undefined') {
38641 this.view.el = this.el.appendChild(document.createElement("div"));
38642 this.view = Roo.factory(this.view);
38643 this.view.render && this.view.render(false, '');
38647 this.fireEvent('render', this);
38650 Roo.extend(Roo.panel.Content, Roo.util.Observable, {
38652 setRegion : function(region){
38653 this.region = region;
38655 this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
38657 this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
38662 * Returns the toolbar for this Panel if one was configured.
38663 * @return {Roo.Toolbar}
38665 getToolbar : function(){
38666 return this.toolbar;
38669 setActiveState : function(active){
38670 this.active = active;
38672 this.fireEvent("deactivate", this);
38674 this.fireEvent("activate", this);
38678 * Updates this panel's element
38679 * @param {String} content The new content
38680 * @param {Boolean} loadScripts (optional) true to look for and process scripts
38682 setContent : function(content, loadScripts){
38683 this.el.update(content, loadScripts);
38686 ignoreResize : function(w, h){
38687 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
38690 this.lastSize = {width: w, height: h};
38695 * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
38696 * @return {Roo.UpdateManager} The UpdateManager
38698 getUpdateManager : function(){
38699 return this.el.getUpdateManager();
38702 * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
38703 * @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:
38706 url: "your-url.php",
38707 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
38708 callback: yourFunction,
38709 scope: yourObject, //(optional scope)
38712 text: "Loading...",
38717 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
38718 * 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.
38719 * @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}
38720 * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
38721 * @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.
38722 * @return {Roo.panel.Content} this
38725 var um = this.el.getUpdateManager();
38726 um.update.apply(um, arguments);
38732 * 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.
38733 * @param {String/Function} url The URL to load the content from or a function to call to get the URL
38734 * @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)
38735 * @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)
38736 * @return {Roo.UpdateManager} The UpdateManager
38738 setUrl : function(url, params, loadOnce){
38739 if(this.refreshDelegate){
38740 this.removeListener("activate", this.refreshDelegate);
38742 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
38743 this.on("activate", this.refreshDelegate);
38744 return this.el.getUpdateManager();
38747 _handleRefresh : function(url, params, loadOnce){
38748 if(!loadOnce || !this.loaded){
38749 var updater = this.el.getUpdateManager();
38750 updater.update(url, params, this._setLoaded.createDelegate(this));
38754 _setLoaded : function(){
38755 this.loaded = true;
38759 * Returns this panel's id
38762 getId : function(){
38767 * Returns this panel's element - used by regiosn to add.
38768 * @return {Roo.Element}
38770 getEl : function(){
38771 return this.wrapEl || this.el;
38774 adjustForComponents : function(width, height)
38776 //Roo.log('adjustForComponents ');
38777 if(this.resizeEl != this.el){
38778 width -= this.el.getFrameWidth('lr');
38779 height -= this.el.getFrameWidth('tb');
38782 var te = this.toolbar.getEl();
38783 height -= te.getHeight();
38784 te.setWidth(width);
38787 var te = this.footer.getEl();
38788 //Roo.log("footer:" + te.getHeight());
38790 height -= te.getHeight();
38791 te.setWidth(width);
38795 if(this.adjustments){
38796 width += this.adjustments[0];
38797 height += this.adjustments[1];
38799 return {"width": width, "height": height};
38802 setSize : function(width, height){
38803 if(this.fitToFrame && !this.ignoreResize(width, height)){
38804 if(this.fitContainer && this.resizeEl != this.el){
38805 this.el.setSize(width, height);
38807 var size = this.adjustForComponents(width, height);
38808 this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
38809 this.fireEvent('resize', this, size.width, size.height);
38814 * Returns this panel's title
38817 getTitle : function(){
38822 * Set this panel's title
38823 * @param {String} title
38825 setTitle : function(title){
38826 this.title = title;
38828 this.region.updatePanelTitle(this, title);
38833 * Returns true is this panel was configured to be closable
38834 * @return {Boolean}
38836 isClosable : function(){
38837 return this.closable;
38840 beforeSlide : function(){
38842 this.resizeEl.clip();
38845 afterSlide : function(){
38847 this.resizeEl.unclip();
38851 * Force a content refresh from the URL specified in the {@link #setUrl} method.
38852 * Will fail silently if the {@link #setUrl} method has not been called.
38853 * This does not activate the panel, just updates its content.
38855 refresh : function(){
38856 if(this.refreshDelegate){
38857 this.loaded = false;
38858 this.refreshDelegate();
38863 * Destroys this panel
38865 destroy : function(){
38866 this.el.removeAllListeners();
38867 var tempEl = document.createElement("span");
38868 tempEl.appendChild(this.el.dom);
38869 tempEl.innerHTML = "";
38875 * form - if the content panel contains a form - this is a reference to it.
38876 * @type {Roo.form.Form}
38880 * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
38881 * This contains a reference to it.
38887 * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
38897 * @param {Object} cfg Xtype definition of item to add.
38900 addxtype : function(cfg) {
38901 if(cfg.xtype.match(/^Cropbox$/)) {
38903 this.cropbox = new Roo.factory(cfg);
38905 this.cropbox.render(this.el);
38907 return this.cropbox;
38910 if (cfg.xtype.match(/^Form$/)) {
38913 //if (this.footer) {
38914 // el = this.footer.container.insertSibling(false, 'before');
38916 el = this.el.createChild();
38919 this.form = new Roo.form.Form(cfg);
38922 if ( this.form.allItems.length) {
38923 this.form.render(el.dom);
38927 // should only have one of theses..
38928 if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
38929 // views.. should not be just added - used named prop 'view''
38931 cfg.el = this.el.appendChild(document.createElement("div"));
38934 var ret = new Roo.factory(cfg);
38936 ret.render && ret.render(false, ''); // render blank..
38956 * @class Roo.panel.Grid
38957 * @extends Roo.panel.Content
38958 * @parent Roo.layout.Border Roo.LayoutDialog builder
38960 * Create a new GridPanel.
38961 * @cfg {Roo.grid.Grid} grid The grid for this panel
38963 Roo.panel.Grid = function(grid, config){
38965 // universal ctor...
38966 if (typeof(grid.grid) != 'undefined') {
38968 grid = config.grid;
38970 this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
38971 {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
38973 this.wrapper.dom.appendChild(grid.getGridEl().dom);
38975 Roo.panel.Grid.superclass.constructor.call(this, this.wrapper, config);
38978 this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
38980 // xtype created footer. - not sure if will work as we normally have to render first..
38981 if (this.footer && !this.footer.el && this.footer.xtype) {
38983 this.footer.container = this.grid.getView().getFooterPanel(true);
38984 this.footer.dataSource = this.grid.dataSource;
38985 this.footer = Roo.factory(this.footer, Roo);
38989 grid.monitorWindowResize = false; // turn off autosizing
38990 grid.autoHeight = false;
38991 grid.autoWidth = false;
38993 this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
38996 Roo.extend(Roo.panel.Grid, Roo.panel.Content, {
38997 getId : function(){
38998 return this.grid.id;
39002 * Returns the grid for this panel
39003 * @return {Roo.grid.Grid}
39005 getGrid : function(){
39009 setSize : function(width, height){
39010 if(!this.ignoreResize(width, height)){
39011 var grid = this.grid;
39012 var size = this.adjustForComponents(width, height);
39013 grid.getGridEl().setSize(size.width, size.height);
39018 beforeSlide : function(){
39019 this.grid.getView().scroller.clip();
39022 afterSlide : function(){
39023 this.grid.getView().scroller.unclip();
39026 destroy : function(){
39027 this.grid.destroy();
39029 Roo.panel.Grid.superclass.destroy.call(this);
39035 * @class Roo.panel.NestedLayout
39036 * @extends Roo.panel.Content
39037 * @parent Roo.layout.Border Roo.LayoutDialog builder
39038 * @cfg {Roo.layout.Border} layout [required] The layout for this panel
39042 * Create a new NestedLayoutPanel.
39045 * @param {Roo.layout.Border} layout [required] The layout for this panel
39046 * @param {String/Object} config A string to set only the title or a config object
39048 Roo.panel.NestedLayout = function(layout, config)
39050 // construct with only one argument..
39051 /* FIXME - implement nicer consturctors
39052 if (layout.layout) {
39054 layout = config.layout;
39055 delete config.layout;
39057 if (layout.xtype && !layout.getEl) {
39058 // then layout needs constructing..
39059 layout = Roo.factory(layout, Roo);
39064 Roo.panel.NestedLayout.superclass.constructor.call(this, layout.getEl(), config);
39066 layout.monitorWindowResize = false; // turn off autosizing
39067 this.layout = layout;
39068 this.layout.getEl().addClass("x-layout-nested-layout");
39075 Roo.extend(Roo.panel.NestedLayout, Roo.panel.Content, {
39079 setSize : function(width, height){
39080 if(!this.ignoreResize(width, height)){
39081 var size = this.adjustForComponents(width, height);
39082 var el = this.layout.getEl();
39083 el.setSize(size.width, size.height);
39084 var touch = el.dom.offsetWidth;
39085 this.layout.layout();
39086 // ie requires a double layout on the first pass
39087 if(Roo.isIE && !this.initialized){
39088 this.initialized = true;
39089 this.layout.layout();
39094 // activate all subpanels if not currently active..
39096 setActiveState : function(active){
39097 this.active = active;
39099 this.fireEvent("deactivate", this);
39103 this.fireEvent("activate", this);
39104 // not sure if this should happen before or after..
39105 if (!this.layout) {
39106 return; // should not happen..
39109 for (var r in this.layout.regions) {
39110 reg = this.layout.getRegion(r);
39111 if (reg.getActivePanel()) {
39112 //reg.showPanel(reg.getActivePanel()); // force it to activate..
39113 reg.setActivePanel(reg.getActivePanel());
39116 if (!reg.panels.length) {
39119 reg.showPanel(reg.getPanel(0));
39128 * Returns the nested BorderLayout for this panel
39129 * @return {Roo.layout.Border}
39131 getLayout : function(){
39132 return this.layout;
39136 * Adds a xtype elements to the layout of the nested panel
39140 xtype : 'ContentPanel',
39147 xtype : 'panel.NestedLayout',
39153 items : [ ... list of content panels or nested layout panels.. ]
39157 * @param {Object} cfg Xtype definition of item to add.
39159 addxtype : function(cfg) {
39160 return this.layout.addxtype(cfg);
39165 Roo.panel.Scroll = function(el, config, content){
39166 config = config || {};
39167 config.fitToFrame = true;
39168 Roo.panel.Scroll.superclass.constructor.call(this, el, config, content);
39170 this.el.dom.style.overflow = "hidden";
39171 var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
39172 this.el.removeClass("x-layout-inactive-content");
39173 this.el.on("mousewheel", this.onWheel, this);
39175 var up = wrap.createChild({cls: "x-scroller-up", html: " "}, this.el.dom);
39176 var down = wrap.createChild({cls: "x-scroller-down", html: " "});
39177 up.unselectable(); down.unselectable();
39178 up.on("click", this.scrollUp, this);
39179 down.on("click", this.scrollDown, this);
39180 up.addClassOnOver("x-scroller-btn-over");
39181 down.addClassOnOver("x-scroller-btn-over");
39182 up.addClassOnClick("x-scroller-btn-click");
39183 down.addClassOnClick("x-scroller-btn-click");
39184 this.adjustments = [0, -(up.getHeight() + down.getHeight())];
39186 this.resizeEl = this.el;
39187 this.el = wrap; this.up = up; this.down = down;
39190 Roo.extend(Roo.panel.Scroll, Roo.panel.Content, {
39192 wheelIncrement : 5,
39193 scrollUp : function(){
39194 this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
39197 scrollDown : function(){
39198 this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
39201 afterScroll : function(){
39202 var el = this.resizeEl;
39203 var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
39204 this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
39205 this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
39208 setSize : function(){
39209 Roo.panel.Scroll.superclass.setSize.apply(this, arguments);
39210 this.afterScroll();
39213 onWheel : function(e){
39214 var d = e.getWheelDelta();
39215 this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
39216 this.afterScroll();
39220 setContent : function(content, loadScripts){
39221 this.resizeEl.update(content, loadScripts);
39229 * @class Roo.panel.Tree
39230 * @extends Roo.panel.Content
39231 * @parent Roo.layout.Border Roo.LayoutDialog builder
39232 * Treepanel component
39235 * Create a new TreePanel. - defaults to fit/scoll contents.
39236 * @param {String/Object} config A string to set only the panel's title, or a config object
39238 Roo.panel.Tree = function(config){
39239 var el = config.el;
39240 var tree = config.tree;
39241 delete config.tree;
39242 delete config.el; // hopefull!
39244 // wrapper for IE7 strict & safari scroll issue
39246 var treeEl = el.createChild();
39247 config.resizeEl = treeEl;
39251 Roo.panel.Tree.superclass.constructor.call(this, el, config);
39254 this.tree = new Roo.tree.TreePanel(treeEl , tree);
39255 //console.log(tree);
39256 this.on('activate', function()
39258 if (this.tree.rendered) {
39261 //console.log('render tree');
39262 this.tree.render();
39264 // this should not be needed.. - it's actually the 'el' that resizes?
39265 // actuall it breaks the containerScroll - dragging nodes auto scroll at top
39267 //this.on('resize', function (cp, w, h) {
39268 // this.tree.innerCt.setWidth(w);
39269 // this.tree.innerCt.setHeight(h);
39270 // //this.tree.innerCt.setStyle('overflow-y', 'auto');
39277 Roo.extend(Roo.panel.Tree, Roo.panel.Content, {
39281 * @cfg {Roo.tree.panel.Tree} tree [required] The tree TreePanel, with config etc.
39288 * Ext JS Library 1.1.1
39289 * Copyright(c) 2006-2007, Ext JS, LLC.
39291 * Originally Released Under LGPL - original licence link has changed is not relivant.
39294 * <script type="text/javascript">
39299 * @class Roo.layout.Reader
39300 * @extends Roo.layout.Border
39301 * This is a pre-built layout that represents a classic, 5-pane application. It consists of a header, a primary
39302 * center region containing two nested regions (a top one for a list view and one for item preview below),
39303 * and regions on either side that can be used for navigation, application commands, informational displays, etc.
39304 * The setup and configuration work exactly the same as it does for a {@link Roo.layout.Border} - this class simply
39305 * expedites the setup of the overall layout and regions for this common application style.
39308 var reader = new Roo.layout.Reader();
39309 var CP = Roo.panel.Content; // shortcut for adding
39311 reader.beginUpdate();
39312 reader.add("north", new CP("north", "North"));
39313 reader.add("west", new CP("west", {title: "West"}));
39314 reader.add("east", new CP("east", {title: "East"}));
39316 reader.regions.listView.add(new CP("listView", "List"));
39317 reader.regions.preview.add(new CP("preview", "Preview"));
39318 reader.endUpdate();
39321 * Create a new ReaderLayout
39322 * @param {Object} config Configuration options
39323 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
39324 * document.body if omitted)
39326 Roo.layout.Reader = function(config, renderTo){
39327 var c = config || {size:{}};
39328 Roo.layout.Reader.superclass.constructor.call(this, renderTo || document.body, {
39329 north: c.north !== false ? Roo.apply({
39333 }, c.north) : false,
39334 west: c.west !== false ? Roo.apply({
39342 margins:{left:5,right:0,bottom:5,top:5},
39343 cmargins:{left:5,right:5,bottom:5,top:5}
39344 }, c.west) : false,
39345 east: c.east !== false ? Roo.apply({
39353 margins:{left:0,right:5,bottom:5,top:5},
39354 cmargins:{left:5,right:5,bottom:5,top:5}
39355 }, c.east) : false,
39356 center: Roo.apply({
39357 tabPosition: 'top',
39361 margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
39365 this.el.addClass('x-reader');
39367 this.beginUpdate();
39369 var inner = new Roo.layout.Border(Roo.get(document.body).createChild(), {
39370 south: c.preview !== false ? Roo.apply({
39377 cmargins:{top:5,left:0, right:0, bottom:0}
39378 }, c.preview) : false,
39379 center: Roo.apply({
39385 this.add('center', new Roo.panel.NestedLayout(inner,
39386 Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
39390 this.regions.preview = inner.getRegion('south');
39391 this.regions.listView = inner.getRegion('center');
39394 Roo.extend(Roo.layout.Reader, Roo.layout.Border);/*
39396 * Ext JS Library 1.1.1
39397 * Copyright(c) 2006-2007, Ext JS, LLC.
39399 * Originally Released Under LGPL - original licence link has changed is not relivant.
39402 * <script type="text/javascript">
39406 * @class Roo.grid.Grid
39407 * @extends Roo.util.Observable
39408 * This class represents the primary interface of a component based grid control.
39409 * <br><br>Usage:<pre><code>
39410 var grid = new Roo.grid.Grid("my-container-id", {
39413 selModel: mySelectionModel,
39414 autoSizeColumns: true,
39415 monitorWindowResize: false,
39416 trackMouseOver: true
39421 * <b>Common Problems:</b><br/>
39422 * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
39423 * element will correct this<br/>
39424 * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
39425 * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
39426 * are unpredictable.<br/>
39427 * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
39428 * grid to calculate dimensions/offsets.<br/>
39430 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
39431 * The container MUST have some type of size defined for the grid to fill. The container will be
39432 * automatically set to position relative if it isn't already.
39433 * @param {Object} config A config object that sets properties on this grid.
39435 Roo.grid.Grid = function(container, config){
39436 // initialize the container
39437 this.container = Roo.get(container);
39438 this.container.update("");
39439 this.container.setStyle("overflow", "hidden");
39440 this.container.addClass('x-grid-container');
39442 this.id = this.container.id;
39444 Roo.apply(this, config);
39445 // check and correct shorthanded configs
39447 this.dataSource = this.ds;
39451 this.colModel = this.cm;
39455 this.selModel = this.sm;
39459 if (this.selModel) {
39460 this.selModel = Roo.factory(this.selModel, Roo.grid);
39461 this.sm = this.selModel;
39462 this.sm.xmodule = this.xmodule || false;
39464 if (typeof(this.colModel.config) == 'undefined') {
39465 this.colModel = new Roo.grid.ColumnModel(this.colModel);
39466 this.cm = this.colModel;
39467 this.cm.xmodule = this.xmodule || false;
39469 if (this.dataSource) {
39470 this.dataSource= Roo.factory(this.dataSource, Roo.data);
39471 this.ds = this.dataSource;
39472 this.ds.xmodule = this.xmodule || false;
39479 this.container.setWidth(this.width);
39483 this.container.setHeight(this.height);
39490 * The raw click event for the entire grid.
39491 * @param {Roo.EventObject} e
39496 * The raw dblclick event for the entire grid.
39497 * @param {Roo.EventObject} e
39501 * @event contextmenu
39502 * The raw contextmenu event for the entire grid.
39503 * @param {Roo.EventObject} e
39505 "contextmenu" : true,
39508 * The raw mousedown event for the entire grid.
39509 * @param {Roo.EventObject} e
39511 "mousedown" : true,
39514 * The raw mouseup event for the entire grid.
39515 * @param {Roo.EventObject} e
39520 * The raw mouseover event for the entire grid.
39521 * @param {Roo.EventObject} e
39523 "mouseover" : true,
39526 * The raw mouseout event for the entire grid.
39527 * @param {Roo.EventObject} e
39532 * The raw keypress event for the entire grid.
39533 * @param {Roo.EventObject} e
39538 * The raw keydown event for the entire grid.
39539 * @param {Roo.EventObject} e
39547 * Fires when a cell is clicked
39548 * @param {Grid} this
39549 * @param {Number} rowIndex
39550 * @param {Number} columnIndex
39551 * @param {Roo.EventObject} e
39553 "cellclick" : true,
39555 * @event celldblclick
39556 * Fires when a cell is double clicked
39557 * @param {Grid} this
39558 * @param {Number} rowIndex
39559 * @param {Number} columnIndex
39560 * @param {Roo.EventObject} e
39562 "celldblclick" : true,
39565 * Fires when a row is clicked
39566 * @param {Grid} this
39567 * @param {Number} rowIndex
39568 * @param {Roo.EventObject} e
39572 * @event rowdblclick
39573 * Fires when a row is double clicked
39574 * @param {Grid} this
39575 * @param {Number} rowIndex
39576 * @param {Roo.EventObject} e
39578 "rowdblclick" : true,
39580 * @event headerclick
39581 * Fires when a header is clicked
39582 * @param {Grid} this
39583 * @param {Number} columnIndex
39584 * @param {Roo.EventObject} e
39586 "headerclick" : true,
39588 * @event headerdblclick
39589 * Fires when a header cell is double clicked
39590 * @param {Grid} this
39591 * @param {Number} columnIndex
39592 * @param {Roo.EventObject} e
39594 "headerdblclick" : true,
39596 * @event rowcontextmenu
39597 * Fires when a row is right clicked
39598 * @param {Grid} this
39599 * @param {Number} rowIndex
39600 * @param {Roo.EventObject} e
39602 "rowcontextmenu" : true,
39604 * @event cellcontextmenu
39605 * Fires when a cell is right clicked
39606 * @param {Grid} this
39607 * @param {Number} rowIndex
39608 * @param {Number} cellIndex
39609 * @param {Roo.EventObject} e
39611 "cellcontextmenu" : true,
39613 * @event headercontextmenu
39614 * Fires when a header is right clicked
39615 * @param {Grid} this
39616 * @param {Number} columnIndex
39617 * @param {Roo.EventObject} e
39619 "headercontextmenu" : true,
39621 * @event bodyscroll
39622 * Fires when the body element is scrolled
39623 * @param {Number} scrollLeft
39624 * @param {Number} scrollTop
39626 "bodyscroll" : true,
39628 * @event columnresize
39629 * Fires when the user resizes a column
39630 * @param {Number} columnIndex
39631 * @param {Number} newSize
39633 "columnresize" : true,
39635 * @event columnmove
39636 * Fires when the user moves a column
39637 * @param {Number} oldIndex
39638 * @param {Number} newIndex
39640 "columnmove" : true,
39643 * Fires when row(s) start being dragged
39644 * @param {Grid} this
39645 * @param {Roo.GridDD} dd The drag drop object
39646 * @param {event} e The raw browser event
39648 "startdrag" : true,
39651 * Fires when a drag operation is complete
39652 * @param {Grid} this
39653 * @param {Roo.GridDD} dd The drag drop object
39654 * @param {event} e The raw browser event
39659 * Fires when dragged row(s) are dropped on a valid DD target
39660 * @param {Grid} this
39661 * @param {Roo.GridDD} dd The drag drop object
39662 * @param {String} targetId The target drag drop object
39663 * @param {event} e The raw browser event
39668 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
39669 * @param {Grid} this
39670 * @param {Roo.GridDD} dd The drag drop object
39671 * @param {String} targetId The target drag drop object
39672 * @param {event} e The raw browser event
39677 * Fires when the dragged row(s) first cross another DD target while being dragged
39678 * @param {Grid} this
39679 * @param {Roo.GridDD} dd The drag drop object
39680 * @param {String} targetId The target drag drop object
39681 * @param {event} e The raw browser event
39683 "dragenter" : true,
39686 * Fires when the dragged row(s) leave another DD target while being dragged
39687 * @param {Grid} this
39688 * @param {Roo.GridDD} dd The drag drop object
39689 * @param {String} targetId The target drag drop object
39690 * @param {event} e The raw browser event
39695 * Fires when a row is rendered, so you can change add a style to it.
39696 * @param {GridView} gridview The grid view
39697 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
39703 * Fires when the grid is rendered
39704 * @param {Grid} grid
39709 Roo.grid.Grid.superclass.constructor.call(this);
39711 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
39714 * @cfg {Roo.grid.AbstractSelectionModel} sm The selection Model (default = Roo.grid.RowSelectionModel)
39717 * @cfg {Roo.grid.GridView} view The view that renders the grid (default = Roo.grid.GridView)
39720 * @cfg {Roo.grid.ColumnModel} cm[] The columns of the grid
39723 * @cfg {Roo.data.Store} ds The data store for the grid
39726 * @cfg {Roo.Toolbar} toolbar a toolbar for buttons etc.
39730 * @cfg {Roo.PagingToolbar} footer the paging toolbar
39734 * @cfg {String} ddGroup - drag drop group.
39737 * @cfg {String} dragGroup - drag group (?? not sure if needed.)
39741 * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
39743 minColumnWidth : 25,
39746 * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
39747 * <b>on initial render.</b> It is more efficient to explicitly size the columns
39748 * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option. Default is false.
39750 autoSizeColumns : false,
39753 * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
39755 autoSizeHeaders : true,
39758 * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
39760 monitorWindowResize : true,
39763 * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
39764 * rows measured to get a columns size. Default is 0 (all rows).
39766 maxRowsToMeasure : 0,
39769 * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
39771 trackMouseOver : true,
39774 * @cfg {Boolean} enableDrag True to enable drag of rows. Default is false. (double check if this is needed?)
39777 * @cfg {Boolean} enableDrop True to enable drop of elements. Default is false. (double check if this is needed?)
39781 * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
39783 enableDragDrop : false,
39786 * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
39788 enableColumnMove : true,
39791 * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
39793 enableColumnHide : true,
39796 * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
39798 enableRowHeightSync : false,
39801 * @cfg {Boolean} stripeRows True to stripe the rows. Default is true.
39806 * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
39808 autoHeight : false,
39811 * @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.
39813 autoExpandColumn : false,
39816 * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
39819 autoExpandMin : 50,
39822 * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
39824 autoExpandMax : 1000,
39827 * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
39832 * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
39836 * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
39840 * @cfg {boolean} sortColMenu Sort the column order menu when it shows (usefull for long lists..) default false
39842 sortColMenu : false,
39848 * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
39849 * of a fixed width. Default is false.
39852 * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
39857 * @cfg {String} ddText Configures the text is the drag proxy (defaults to "%0 selected row(s)").
39858 * %0 is replaced with the number of selected rows.
39860 ddText : "{0} selected row{1}",
39864 * Called once after all setup has been completed and the grid is ready to be rendered.
39865 * @return {Roo.grid.Grid} this
39867 render : function()
39869 var c = this.container;
39870 // try to detect autoHeight/width mode
39871 if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
39872 this.autoHeight = true;
39874 var view = this.getView();
39877 c.on("click", this.onClick, this);
39878 c.on("dblclick", this.onDblClick, this);
39879 c.on("contextmenu", this.onContextMenu, this);
39880 c.on("keydown", this.onKeyDown, this);
39882 c.on("touchstart", this.onTouchStart, this);
39885 this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
39887 this.getSelectionModel().init(this);
39892 this.loadMask = new Roo.LoadMask(this.container,
39893 Roo.apply({store:this.dataSource}, this.loadMask));
39897 if (this.toolbar && this.toolbar.xtype) {
39898 this.toolbar.container = this.getView().getHeaderPanel(true);
39899 this.toolbar = new Roo.Toolbar(this.toolbar);
39901 if (this.footer && this.footer.xtype) {
39902 this.footer.dataSource = this.getDataSource();
39903 this.footer.container = this.getView().getFooterPanel(true);
39904 this.footer = Roo.factory(this.footer, Roo);
39906 if (this.dropTarget && this.dropTarget.xtype) {
39907 delete this.dropTarget.xtype;
39908 this.dropTarget = new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
39912 this.rendered = true;
39913 this.fireEvent('render', this);
39918 * Reconfigures the grid to use a different Store and Column Model.
39919 * The View will be bound to the new objects and refreshed.
39920 * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
39921 * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
39923 reconfigure : function(dataSource, colModel){
39925 this.loadMask.destroy();
39926 this.loadMask = new Roo.LoadMask(this.container,
39927 Roo.apply({store:dataSource}, this.loadMask));
39929 this.view.bind(dataSource, colModel);
39930 this.dataSource = dataSource;
39931 this.colModel = colModel;
39932 this.view.refresh(true);
39936 * Add's a column, default at the end..
39938 * @param {int} position to add (default end)
39939 * @param {Array} of objects of column configuration see {@link Roo.grid.ColumnModel}
39941 addColumns : function(pos, ar)
39944 for (var i =0;i< ar.length;i++) {
39946 cfg.id = typeof(cfg.id) == 'undefined' ? Roo.id() : cfg.id; // don't normally use this..
39947 this.cm.lookup[cfg.id] = cfg;
39951 if (typeof(pos) == 'undefined' || pos >= this.cm.config.length) {
39952 pos = this.cm.config.length; //this.cm.config.push(cfg);
39954 pos = Math.max(0,pos);
39957 this.cm.config.splice.apply(this.cm.config, ar);
39961 this.view.generateRules(this.cm);
39962 this.view.refresh(true);
39970 onKeyDown : function(e){
39971 this.fireEvent("keydown", e);
39975 * Destroy this grid.
39976 * @param {Boolean} removeEl True to remove the element
39978 destroy : function(removeEl, keepListeners){
39980 this.loadMask.destroy();
39982 var c = this.container;
39983 c.removeAllListeners();
39984 this.view.destroy();
39985 this.colModel.purgeListeners();
39986 if(!keepListeners){
39987 this.purgeListeners();
39990 if(removeEl === true){
39996 processEvent : function(name, e){
39997 // does this fire select???
39998 //Roo.log('grid:processEvent ' + name);
40000 if (name != 'touchstart' ) {
40001 this.fireEvent(name, e);
40004 var t = e.getTarget();
40006 var header = v.findHeaderIndex(t);
40007 if(header !== false){
40008 var ename = name == 'touchstart' ? 'click' : name;
40010 this.fireEvent("header" + ename, this, header, e);
40012 var row = v.findRowIndex(t);
40013 var cell = v.findCellIndex(t);
40014 if (name == 'touchstart') {
40015 // first touch is always a click.
40016 // hopefull this happens after selection is updated.?
40019 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
40020 var cs = this.selModel.getSelectedCell();
40021 if (row == cs[0] && cell == cs[1]){
40025 if (typeof(this.selModel.getSelections) != 'undefined') {
40026 var cs = this.selModel.getSelections();
40027 var ds = this.dataSource;
40028 if (cs.length == 1 && ds.getAt(row) == cs[0]){
40039 this.fireEvent("row" + name, this, row, e);
40040 if(cell !== false){
40041 this.fireEvent("cell" + name, this, row, cell, e);
40048 onClick : function(e){
40049 this.processEvent("click", e);
40052 onTouchStart : function(e){
40053 this.processEvent("touchstart", e);
40057 onContextMenu : function(e, t){
40058 this.processEvent("contextmenu", e);
40062 onDblClick : function(e){
40063 this.processEvent("dblclick", e);
40067 walkCells : function(row, col, step, fn, scope){
40068 var cm = this.colModel, clen = cm.getColumnCount();
40069 var ds = this.dataSource, rlen = ds.getCount(), first = true;
40081 if(fn.call(scope || this, row, col, cm) === true){
40099 if(fn.call(scope || this, row, col, cm) === true){
40111 getSelections : function(){
40112 return this.selModel.getSelections();
40116 * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
40117 * but if manual update is required this method will initiate it.
40119 autoSize : function(){
40121 this.view.layout();
40122 if(this.view.adjustForScroll){
40123 this.view.adjustForScroll();
40129 * Returns the grid's underlying element.
40130 * @return {Element} The element
40132 getGridEl : function(){
40133 return this.container;
40136 // private for compatibility, overridden by editor grid
40137 stopEditing : function(){},
40140 * Returns the grid's SelectionModel.
40141 * @return {SelectionModel}
40143 getSelectionModel : function(){
40144 if(!this.selModel){
40145 this.selModel = new Roo.grid.RowSelectionModel();
40147 return this.selModel;
40151 * Returns the grid's DataSource.
40152 * @return {DataSource}
40154 getDataSource : function(){
40155 return this.dataSource;
40159 * Returns the grid's ColumnModel.
40160 * @return {ColumnModel}
40162 getColumnModel : function(){
40163 return this.colModel;
40167 * Returns the grid's GridView object.
40168 * @return {GridView}
40170 getView : function(){
40172 this.view = new Roo.grid.GridView(this.viewConfig);
40173 this.relayEvents(this.view, [
40174 "beforerowremoved", "beforerowsinserted",
40175 "beforerefresh", "rowremoved",
40176 "rowsinserted", "rowupdated" ,"refresh"
40182 * Called to get grid's drag proxy text, by default returns this.ddText.
40183 * Override this to put something different in the dragged text.
40186 getDragDropText : function(){
40187 var count = this.selModel.getCount();
40188 return String.format(this.ddText, count, count == 1 ? '' : 's');
40193 * Ext JS Library 1.1.1
40194 * Copyright(c) 2006-2007, Ext JS, LLC.
40196 * Originally Released Under LGPL - original licence link has changed is not relivant.
40199 * <script type="text/javascript">
40202 * @class Roo.grid.AbstractGridView
40203 * @extends Roo.util.Observable
40205 * Abstract base class for grid Views
40208 Roo.grid.AbstractGridView = function(){
40212 "beforerowremoved" : true,
40213 "beforerowsinserted" : true,
40214 "beforerefresh" : true,
40215 "rowremoved" : true,
40216 "rowsinserted" : true,
40217 "rowupdated" : true,
40220 Roo.grid.AbstractGridView.superclass.constructor.call(this);
40223 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
40224 rowClass : "x-grid-row",
40225 cellClass : "x-grid-cell",
40226 tdClass : "x-grid-td",
40227 hdClass : "x-grid-hd",
40228 splitClass : "x-grid-hd-split",
40230 init: function(grid){
40232 var cid = this.grid.getGridEl().id;
40233 this.colSelector = "#" + cid + " ." + this.cellClass + "-";
40234 this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
40235 this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
40236 this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
40239 getColumnRenderers : function(){
40240 var renderers = [];
40241 var cm = this.grid.colModel;
40242 var colCount = cm.getColumnCount();
40243 for(var i = 0; i < colCount; i++){
40244 renderers[i] = cm.getRenderer(i);
40249 getColumnIds : function(){
40251 var cm = this.grid.colModel;
40252 var colCount = cm.getColumnCount();
40253 for(var i = 0; i < colCount; i++){
40254 ids[i] = cm.getColumnId(i);
40259 getDataIndexes : function(){
40260 if(!this.indexMap){
40261 this.indexMap = this.buildIndexMap();
40263 return this.indexMap.colToData;
40266 getColumnIndexByDataIndex : function(dataIndex){
40267 if(!this.indexMap){
40268 this.indexMap = this.buildIndexMap();
40270 return this.indexMap.dataToCol[dataIndex];
40274 * Set a css style for a column dynamically.
40275 * @param {Number} colIndex The index of the column
40276 * @param {String} name The css property name
40277 * @param {String} value The css value
40279 setCSSStyle : function(colIndex, name, value){
40280 var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
40281 Roo.util.CSS.updateRule(selector, name, value);
40284 generateRules : function(cm){
40285 var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
40286 Roo.util.CSS.removeStyleSheet(rulesId);
40287 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
40288 var cid = cm.getColumnId(i);
40289 ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
40290 this.tdSelector, cid, " {\n}\n",
40291 this.hdSelector, cid, " {\n}\n",
40292 this.splitSelector, cid, " {\n}\n");
40294 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
40298 * Ext JS Library 1.1.1
40299 * Copyright(c) 2006-2007, Ext JS, LLC.
40301 * Originally Released Under LGPL - original licence link has changed is not relivant.
40304 * <script type="text/javascript">
40308 // This is a support class used internally by the Grid components
40309 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
40311 this.view = grid.getView();
40312 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
40313 Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
40315 this.setHandleElId(Roo.id(hd));
40316 this.setOuterHandleElId(Roo.id(hd2));
40318 this.scroll = false;
40320 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
40322 getDragData : function(e){
40323 var t = Roo.lib.Event.getTarget(e);
40324 var h = this.view.findHeaderCell(t);
40326 return {ddel: h.firstChild, header:h};
40331 onInitDrag : function(e){
40332 this.view.headersDisabled = true;
40333 var clone = this.dragData.ddel.cloneNode(true);
40334 clone.id = Roo.id();
40335 clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
40336 this.proxy.update(clone);
40340 afterValidDrop : function(){
40342 setTimeout(function(){
40343 v.headersDisabled = false;
40347 afterInvalidDrop : function(){
40349 setTimeout(function(){
40350 v.headersDisabled = false;
40356 * Ext JS Library 1.1.1
40357 * Copyright(c) 2006-2007, Ext JS, LLC.
40359 * Originally Released Under LGPL - original licence link has changed is not relivant.
40362 * <script type="text/javascript">
40365 // This is a support class used internally by the Grid components
40366 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
40368 this.view = grid.getView();
40369 // split the proxies so they don't interfere with mouse events
40370 this.proxyTop = Roo.DomHelper.append(document.body, {
40371 cls:"col-move-top", html:" "
40373 this.proxyBottom = Roo.DomHelper.append(document.body, {
40374 cls:"col-move-bottom", html:" "
40376 this.proxyTop.hide = this.proxyBottom.hide = function(){
40377 this.setLeftTop(-100,-100);
40378 this.setStyle("visibility", "hidden");
40380 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
40381 // temporarily disabled
40382 //Roo.dd.ScrollManager.register(this.view.scroller.dom);
40383 Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
40385 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
40386 proxyOffsets : [-4, -9],
40387 fly: Roo.Element.fly,
40389 getTargetFromEvent : function(e){
40390 var t = Roo.lib.Event.getTarget(e);
40391 var cindex = this.view.findCellIndex(t);
40392 if(cindex !== false){
40393 return this.view.getHeaderCell(cindex);
40398 nextVisible : function(h){
40399 var v = this.view, cm = this.grid.colModel;
40402 if(!cm.isHidden(v.getCellIndex(h))){
40410 prevVisible : function(h){
40411 var v = this.view, cm = this.grid.colModel;
40414 if(!cm.isHidden(v.getCellIndex(h))){
40422 positionIndicator : function(h, n, e){
40423 var x = Roo.lib.Event.getPageX(e);
40424 var r = Roo.lib.Dom.getRegion(n.firstChild);
40425 var px, pt, py = r.top + this.proxyOffsets[1];
40426 if((r.right - x) <= (r.right-r.left)/2){
40427 px = r.right+this.view.borderWidth;
40433 var oldIndex = this.view.getCellIndex(h);
40434 var newIndex = this.view.getCellIndex(n);
40436 if(this.grid.colModel.isFixed(newIndex)){
40440 var locked = this.grid.colModel.isLocked(newIndex);
40445 if(oldIndex < newIndex){
40448 if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
40451 px += this.proxyOffsets[0];
40452 this.proxyTop.setLeftTop(px, py);
40453 this.proxyTop.show();
40454 if(!this.bottomOffset){
40455 this.bottomOffset = this.view.mainHd.getHeight();
40457 this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
40458 this.proxyBottom.show();
40462 onNodeEnter : function(n, dd, e, data){
40463 if(data.header != n){
40464 this.positionIndicator(data.header, n, e);
40468 onNodeOver : function(n, dd, e, data){
40469 var result = false;
40470 if(data.header != n){
40471 result = this.positionIndicator(data.header, n, e);
40474 this.proxyTop.hide();
40475 this.proxyBottom.hide();
40477 return result ? this.dropAllowed : this.dropNotAllowed;
40480 onNodeOut : function(n, dd, e, data){
40481 this.proxyTop.hide();
40482 this.proxyBottom.hide();
40485 onNodeDrop : function(n, dd, e, data){
40486 var h = data.header;
40488 var cm = this.grid.colModel;
40489 var x = Roo.lib.Event.getPageX(e);
40490 var r = Roo.lib.Dom.getRegion(n.firstChild);
40491 var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
40492 var oldIndex = this.view.getCellIndex(h);
40493 var newIndex = this.view.getCellIndex(n);
40494 var locked = cm.isLocked(newIndex);
40498 if(oldIndex < newIndex){
40501 if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
40504 cm.setLocked(oldIndex, locked, true);
40505 cm.moveColumn(oldIndex, newIndex);
40506 this.grid.fireEvent("columnmove", oldIndex, newIndex);
40514 * Ext JS Library 1.1.1
40515 * Copyright(c) 2006-2007, Ext JS, LLC.
40517 * Originally Released Under LGPL - original licence link has changed is not relivant.
40520 * <script type="text/javascript">
40524 * @class Roo.grid.GridView
40525 * @extends Roo.util.Observable
40528 * @param {Object} config
40530 Roo.grid.GridView = function(config){
40531 Roo.grid.GridView.superclass.constructor.call(this);
40534 Roo.apply(this, config);
40537 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
40539 unselectable : 'unselectable="on"',
40540 unselectableCls : 'x-unselectable',
40543 rowClass : "x-grid-row",
40545 cellClass : "x-grid-col",
40547 tdClass : "x-grid-td",
40549 hdClass : "x-grid-hd",
40551 splitClass : "x-grid-split",
40553 sortClasses : ["sort-asc", "sort-desc"],
40555 enableMoveAnim : false,
40559 dh : Roo.DomHelper,
40561 fly : Roo.Element.fly,
40563 css : Roo.util.CSS,
40569 scrollIncrement : 22,
40571 cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
40573 findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
40575 bind : function(ds, cm){
40577 this.ds.un("load", this.onLoad, this);
40578 this.ds.un("datachanged", this.onDataChange, this);
40579 this.ds.un("add", this.onAdd, this);
40580 this.ds.un("remove", this.onRemove, this);
40581 this.ds.un("update", this.onUpdate, this);
40582 this.ds.un("clear", this.onClear, this);
40585 ds.on("load", this.onLoad, this);
40586 ds.on("datachanged", this.onDataChange, this);
40587 ds.on("add", this.onAdd, this);
40588 ds.on("remove", this.onRemove, this);
40589 ds.on("update", this.onUpdate, this);
40590 ds.on("clear", this.onClear, this);
40595 this.cm.un("widthchange", this.onColWidthChange, this);
40596 this.cm.un("headerchange", this.onHeaderChange, this);
40597 this.cm.un("hiddenchange", this.onHiddenChange, this);
40598 this.cm.un("columnmoved", this.onColumnMove, this);
40599 this.cm.un("columnlockchange", this.onColumnLock, this);
40602 this.generateRules(cm);
40603 cm.on("widthchange", this.onColWidthChange, this);
40604 cm.on("headerchange", this.onHeaderChange, this);
40605 cm.on("hiddenchange", this.onHiddenChange, this);
40606 cm.on("columnmoved", this.onColumnMove, this);
40607 cm.on("columnlockchange", this.onColumnLock, this);
40612 init: function(grid){
40613 Roo.grid.GridView.superclass.init.call(this, grid);
40615 this.bind(grid.dataSource, grid.colModel);
40617 grid.on("headerclick", this.handleHeaderClick, this);
40619 if(grid.trackMouseOver){
40620 grid.on("mouseover", this.onRowOver, this);
40621 grid.on("mouseout", this.onRowOut, this);
40623 grid.cancelTextSelection = function(){};
40624 this.gridId = grid.id;
40626 var tpls = this.templates || {};
40629 tpls.master = new Roo.Template(
40630 '<div class="x-grid" hidefocus="true">',
40631 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
40632 '<div class="x-grid-topbar"></div>',
40633 '<div class="x-grid-scroller"><div></div></div>',
40634 '<div class="x-grid-locked">',
40635 '<div class="x-grid-header">{lockedHeader}</div>',
40636 '<div class="x-grid-body">{lockedBody}</div>',
40638 '<div class="x-grid-viewport">',
40639 '<div class="x-grid-header">{header}</div>',
40640 '<div class="x-grid-body">{body}</div>',
40642 '<div class="x-grid-bottombar"></div>',
40644 '<div class="x-grid-resize-proxy"> </div>',
40647 tpls.master.disableformats = true;
40651 tpls.header = new Roo.Template(
40652 '<table border="0" cellspacing="0" cellpadding="0">',
40653 '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
40656 tpls.header.disableformats = true;
40658 tpls.header.compile();
40661 tpls.hcell = new Roo.Template(
40662 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
40663 '<div class="x-grid-hd-text ' + this.unselectableCls + '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
40666 tpls.hcell.disableFormats = true;
40668 tpls.hcell.compile();
40671 tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
40672 this.unselectableCls + '" ' + this.unselectable +'> </div>');
40673 tpls.hsplit.disableFormats = true;
40675 tpls.hsplit.compile();
40678 tpls.body = new Roo.Template(
40679 '<table border="0" cellspacing="0" cellpadding="0">',
40680 "<tbody>{rows}</tbody>",
40683 tpls.body.disableFormats = true;
40685 tpls.body.compile();
40688 tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
40689 tpls.row.disableFormats = true;
40691 tpls.row.compile();
40694 tpls.cell = new Roo.Template(
40695 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
40696 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
40697 this.unselectableCls + '" ' + this.unselectable +'" {attr}>{value}</div></div>',
40700 tpls.cell.disableFormats = true;
40702 tpls.cell.compile();
40704 this.templates = tpls;
40707 // remap these for backwards compat
40708 onColWidthChange : function(){
40709 this.updateColumns.apply(this, arguments);
40711 onHeaderChange : function(){
40712 this.updateHeaders.apply(this, arguments);
40714 onHiddenChange : function(){
40715 this.handleHiddenChange.apply(this, arguments);
40717 onColumnMove : function(){
40718 this.handleColumnMove.apply(this, arguments);
40720 onColumnLock : function(){
40721 this.handleLockChange.apply(this, arguments);
40724 onDataChange : function(){
40726 this.updateHeaderSortState();
40729 onClear : function(){
40733 onUpdate : function(ds, record){
40734 this.refreshRow(record);
40737 refreshRow : function(record){
40738 var ds = this.ds, index;
40739 if(typeof record == 'number'){
40741 record = ds.getAt(index);
40743 index = ds.indexOf(record);
40745 this.insertRows(ds, index, index, true);
40746 this.onRemove(ds, record, index+1, true);
40747 this.syncRowHeights(index, index);
40749 this.fireEvent("rowupdated", this, index, record);
40752 onAdd : function(ds, records, index){
40753 this.insertRows(ds, index, index + (records.length-1));
40756 onRemove : function(ds, record, index, isUpdate){
40757 if(isUpdate !== true){
40758 this.fireEvent("beforerowremoved", this, index, record);
40760 var bt = this.getBodyTable(), lt = this.getLockedTable();
40761 if(bt.rows[index]){
40762 bt.firstChild.removeChild(bt.rows[index]);
40764 if(lt.rows[index]){
40765 lt.firstChild.removeChild(lt.rows[index]);
40767 if(isUpdate !== true){
40768 this.stripeRows(index);
40769 this.syncRowHeights(index, index);
40771 this.fireEvent("rowremoved", this, index, record);
40775 onLoad : function(){
40776 this.scrollToTop();
40780 * Scrolls the grid to the top
40782 scrollToTop : function(){
40784 this.scroller.dom.scrollTop = 0;
40790 * Gets a panel in the header of the grid that can be used for toolbars etc.
40791 * After modifying the contents of this panel a call to grid.autoSize() may be
40792 * required to register any changes in size.
40793 * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
40794 * @return Roo.Element
40796 getHeaderPanel : function(doShow){
40798 this.headerPanel.show();
40800 return this.headerPanel;
40804 * Gets a panel in the footer of the grid that can be used for toolbars etc.
40805 * After modifying the contents of this panel a call to grid.autoSize() may be
40806 * required to register any changes in size.
40807 * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
40808 * @return Roo.Element
40810 getFooterPanel : function(doShow){
40812 this.footerPanel.show();
40814 return this.footerPanel;
40817 initElements : function(){
40818 var E = Roo.Element;
40819 var el = this.grid.getGridEl().dom.firstChild;
40820 var cs = el.childNodes;
40822 this.el = new E(el);
40824 this.focusEl = new E(el.firstChild);
40825 this.focusEl.swallowEvent("click", true);
40827 this.headerPanel = new E(cs[1]);
40828 this.headerPanel.enableDisplayMode("block");
40830 this.scroller = new E(cs[2]);
40831 this.scrollSizer = new E(this.scroller.dom.firstChild);
40833 this.lockedWrap = new E(cs[3]);
40834 this.lockedHd = new E(this.lockedWrap.dom.firstChild);
40835 this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
40837 this.mainWrap = new E(cs[4]);
40838 this.mainHd = new E(this.mainWrap.dom.firstChild);
40839 this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
40841 this.footerPanel = new E(cs[5]);
40842 this.footerPanel.enableDisplayMode("block");
40844 this.resizeProxy = new E(cs[6]);
40846 this.headerSelector = String.format(
40847 '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
40848 this.lockedHd.id, this.mainHd.id
40851 this.splitterSelector = String.format(
40852 '#{0} div.x-grid-split, #{1} div.x-grid-split',
40853 this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
40856 idToCssName : function(s)
40858 return s.replace(/[^a-z0-9]+/ig, '-');
40861 getHeaderCell : function(index){
40862 return Roo.DomQuery.select(this.headerSelector)[index];
40865 getHeaderCellMeasure : function(index){
40866 return this.getHeaderCell(index).firstChild;
40869 getHeaderCellText : function(index){
40870 return this.getHeaderCell(index).firstChild.firstChild;
40873 getLockedTable : function(){
40874 return this.lockedBody.dom.firstChild;
40877 getBodyTable : function(){
40878 return this.mainBody.dom.firstChild;
40881 getLockedRow : function(index){
40882 return this.getLockedTable().rows[index];
40885 getRow : function(index){
40886 return this.getBodyTable().rows[index];
40889 getRowComposite : function(index){
40891 this.rowEl = new Roo.CompositeElementLite();
40893 var els = [], lrow, mrow;
40894 if(lrow = this.getLockedRow(index)){
40897 if(mrow = this.getRow(index)){
40900 this.rowEl.elements = els;
40904 * Gets the 'td' of the cell
40906 * @param {Integer} rowIndex row to select
40907 * @param {Integer} colIndex column to select
40911 getCell : function(rowIndex, colIndex){
40912 var locked = this.cm.getLockedCount();
40914 if(colIndex < locked){
40915 source = this.lockedBody.dom.firstChild;
40917 source = this.mainBody.dom.firstChild;
40918 colIndex -= locked;
40920 return source.rows[rowIndex].childNodes[colIndex];
40923 getCellText : function(rowIndex, colIndex){
40924 return this.getCell(rowIndex, colIndex).firstChild.firstChild;
40927 getCellBox : function(cell){
40928 var b = this.fly(cell).getBox();
40929 if(Roo.isOpera){ // opera fails to report the Y
40930 b.y = cell.offsetTop + this.mainBody.getY();
40935 getCellIndex : function(cell){
40936 var id = String(cell.className).match(this.cellRE);
40938 return parseInt(id[1], 10);
40943 findHeaderIndex : function(n){
40944 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
40945 return r ? this.getCellIndex(r) : false;
40948 findHeaderCell : function(n){
40949 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
40950 return r ? r : false;
40953 findRowIndex : function(n){
40957 var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
40958 return r ? r.rowIndex : false;
40961 findCellIndex : function(node){
40962 var stop = this.el.dom;
40963 while(node && node != stop){
40964 if(this.findRE.test(node.className)){
40965 return this.getCellIndex(node);
40967 node = node.parentNode;
40972 getColumnId : function(index){
40973 return this.cm.getColumnId(index);
40976 getSplitters : function()
40978 if(this.splitterSelector){
40979 return Roo.DomQuery.select(this.splitterSelector);
40985 getSplitter : function(index){
40986 return this.getSplitters()[index];
40989 onRowOver : function(e, t){
40991 if((row = this.findRowIndex(t)) !== false){
40992 this.getRowComposite(row).addClass("x-grid-row-over");
40996 onRowOut : function(e, t){
40998 if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
40999 this.getRowComposite(row).removeClass("x-grid-row-over");
41003 renderHeaders : function(){
41005 var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
41006 var cb = [], lb = [], sb = [], lsb = [], p = {};
41007 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
41008 p.cellId = "x-grid-hd-0-" + i;
41009 p.splitId = "x-grid-csplit-0-" + i;
41010 p.id = cm.getColumnId(i);
41011 p.value = cm.getColumnHeader(i) || "";
41012 p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</) ? '' : p.value || "";
41013 p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
41014 if(!cm.isLocked(i)){
41015 cb[cb.length] = ct.apply(p);
41016 sb[sb.length] = st.apply(p);
41018 lb[lb.length] = ct.apply(p);
41019 lsb[lsb.length] = st.apply(p);
41022 return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
41023 ht.apply({cells: cb.join(""), splits:sb.join("")})];
41026 updateHeaders : function(){
41027 var html = this.renderHeaders();
41028 this.lockedHd.update(html[0]);
41029 this.mainHd.update(html[1]);
41033 * Focuses the specified row.
41034 * @param {Number} row The row index
41036 focusRow : function(row)
41038 //Roo.log('GridView.focusRow');
41039 var x = this.scroller.dom.scrollLeft;
41040 this.focusCell(row, 0, false);
41041 this.scroller.dom.scrollLeft = x;
41045 * Focuses the specified cell.
41046 * @param {Number} row The row index
41047 * @param {Number} col The column index
41048 * @param {Boolean} hscroll false to disable horizontal scrolling
41050 focusCell : function(row, col, hscroll)
41052 //Roo.log('GridView.focusCell');
41053 var el = this.ensureVisible(row, col, hscroll);
41054 this.focusEl.alignTo(el, "tl-tl");
41056 this.focusEl.focus();
41058 this.focusEl.focus.defer(1, this.focusEl);
41063 * Scrolls the specified cell into view
41064 * @param {Number} row The row index
41065 * @param {Number} col The column index
41066 * @param {Boolean} hscroll false to disable horizontal scrolling
41068 ensureVisible : function(row, col, hscroll)
41070 //Roo.log('GridView.ensureVisible,' + row + ',' + col);
41071 //return null; //disable for testing.
41072 if(typeof row != "number"){
41073 row = row.rowIndex;
41075 if(row < 0 && row >= this.ds.getCount()){
41078 col = (col !== undefined ? col : 0);
41079 var cm = this.grid.colModel;
41080 while(cm.isHidden(col)){
41084 var el = this.getCell(row, col);
41088 var c = this.scroller.dom;
41090 var ctop = parseInt(el.offsetTop, 10);
41091 var cleft = parseInt(el.offsetLeft, 10);
41092 var cbot = ctop + el.offsetHeight;
41093 var cright = cleft + el.offsetWidth;
41095 var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
41096 var stop = parseInt(c.scrollTop, 10);
41097 var sleft = parseInt(c.scrollLeft, 10);
41098 var sbot = stop + ch;
41099 var sright = sleft + c.clientWidth;
41101 Roo.log('GridView.ensureVisible:' +
41103 ' c.clientHeight:' + c.clientHeight +
41104 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
41112 c.scrollTop = ctop;
41113 //Roo.log("set scrolltop to ctop DISABLE?");
41114 }else if(cbot > sbot){
41115 //Roo.log("set scrolltop to cbot-ch");
41116 c.scrollTop = cbot-ch;
41119 if(hscroll !== false){
41121 c.scrollLeft = cleft;
41122 }else if(cright > sright){
41123 c.scrollLeft = cright-c.clientWidth;
41130 updateColumns : function(){
41131 this.grid.stopEditing();
41132 var cm = this.grid.colModel, colIds = this.getColumnIds();
41133 //var totalWidth = cm.getTotalWidth();
41135 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
41136 //if(cm.isHidden(i)) continue;
41137 var w = cm.getColumnWidth(i);
41138 this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
41139 this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
41141 this.updateSplitters();
41144 generateRules : function(cm){
41145 var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
41146 Roo.util.CSS.removeStyleSheet(rulesId);
41147 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
41148 var cid = cm.getColumnId(i);
41150 if(cm.config[i].align){
41151 align = 'text-align:'+cm.config[i].align+';';
41154 if(cm.isHidden(i)){
41155 hidden = 'display:none;';
41157 var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
41159 this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
41160 this.hdSelector, cid, " {\n", align, width, "}\n",
41161 this.tdSelector, cid, " {\n",hidden,"\n}\n",
41162 this.splitSelector, cid, " {\n", hidden , "\n}\n");
41164 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
41167 updateSplitters : function(){
41168 var cm = this.cm, s = this.getSplitters();
41169 if(s){ // splitters not created yet
41170 var pos = 0, locked = true;
41171 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
41172 if(cm.isHidden(i)) {
41175 var w = cm.getColumnWidth(i); // make sure it's a number
41176 if(!cm.isLocked(i) && locked){
41181 s[i].style.left = (pos-this.splitOffset) + "px";
41186 handleHiddenChange : function(colModel, colIndex, hidden){
41188 this.hideColumn(colIndex);
41190 this.unhideColumn(colIndex);
41194 hideColumn : function(colIndex){
41195 var cid = this.getColumnId(colIndex);
41196 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
41197 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
41199 this.updateHeaders();
41201 this.updateSplitters();
41205 unhideColumn : function(colIndex){
41206 var cid = this.getColumnId(colIndex);
41207 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
41208 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
41211 this.updateHeaders();
41213 this.updateSplitters();
41217 insertRows : function(dm, firstRow, lastRow, isUpdate){
41218 if(firstRow == 0 && lastRow == dm.getCount()-1){
41222 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
41224 var s = this.getScrollState();
41225 var markup = this.renderRows(firstRow, lastRow);
41226 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
41227 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
41228 this.restoreScroll(s);
41230 this.fireEvent("rowsinserted", this, firstRow, lastRow);
41231 this.syncRowHeights(firstRow, lastRow);
41232 this.stripeRows(firstRow);
41238 bufferRows : function(markup, target, index){
41239 var before = null, trows = target.rows, tbody = target.tBodies[0];
41240 if(index < trows.length){
41241 before = trows[index];
41243 var b = document.createElement("div");
41244 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
41245 var rows = b.firstChild.rows;
41246 for(var i = 0, len = rows.length; i < len; i++){
41248 tbody.insertBefore(rows[0], before);
41250 tbody.appendChild(rows[0]);
41257 deleteRows : function(dm, firstRow, lastRow){
41258 if(dm.getRowCount()<1){
41259 this.fireEvent("beforerefresh", this);
41260 this.mainBody.update("");
41261 this.lockedBody.update("");
41262 this.fireEvent("refresh", this);
41264 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
41265 var bt = this.getBodyTable();
41266 var tbody = bt.firstChild;
41267 var rows = bt.rows;
41268 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
41269 tbody.removeChild(rows[firstRow]);
41271 this.stripeRows(firstRow);
41272 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
41276 updateRows : function(dataSource, firstRow, lastRow){
41277 var s = this.getScrollState();
41279 this.restoreScroll(s);
41282 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
41286 this.updateHeaderSortState();
41289 getScrollState : function(){
41291 var sb = this.scroller.dom;
41292 return {left: sb.scrollLeft, top: sb.scrollTop};
41295 stripeRows : function(startRow){
41296 if(!this.grid.stripeRows || this.ds.getCount() < 1){
41299 startRow = startRow || 0;
41300 var rows = this.getBodyTable().rows;
41301 var lrows = this.getLockedTable().rows;
41302 var cls = ' x-grid-row-alt ';
41303 for(var i = startRow, len = rows.length; i < len; i++){
41304 var row = rows[i], lrow = lrows[i];
41305 var isAlt = ((i+1) % 2 == 0);
41306 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
41307 if(isAlt == hasAlt){
41311 row.className += " x-grid-row-alt";
41313 row.className = row.className.replace("x-grid-row-alt", "");
41316 lrow.className = row.className;
41321 restoreScroll : function(state){
41322 //Roo.log('GridView.restoreScroll');
41323 var sb = this.scroller.dom;
41324 sb.scrollLeft = state.left;
41325 sb.scrollTop = state.top;
41329 syncScroll : function(){
41330 //Roo.log('GridView.syncScroll');
41331 var sb = this.scroller.dom;
41332 var sh = this.mainHd.dom;
41333 var bs = this.mainBody.dom;
41334 var lv = this.lockedBody.dom;
41335 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
41336 lv.scrollTop = bs.scrollTop = sb.scrollTop;
41339 handleScroll : function(e){
41341 var sb = this.scroller.dom;
41342 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
41346 handleWheel : function(e){
41347 var d = e.getWheelDelta();
41348 this.scroller.dom.scrollTop -= d*22;
41349 // set this here to prevent jumpy scrolling on large tables
41350 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
41354 renderRows : function(startRow, endRow){
41355 // pull in all the crap needed to render rows
41356 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
41357 var colCount = cm.getColumnCount();
41359 if(ds.getCount() < 1){
41363 // build a map for all the columns
41365 for(var i = 0; i < colCount; i++){
41366 var name = cm.getDataIndex(i);
41368 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
41369 renderer : cm.getRenderer(i),
41370 id : cm.getColumnId(i),
41371 locked : cm.isLocked(i),
41372 has_editor : cm.isCellEditable(i)
41376 startRow = startRow || 0;
41377 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
41379 // records to render
41380 var rs = ds.getRange(startRow, endRow);
41382 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
41385 // As much as I hate to duplicate code, this was branched because FireFox really hates
41386 // [].join("") on strings. The performance difference was substantial enough to
41387 // branch this function
41388 doRender : Roo.isGecko ?
41389 function(cs, rs, ds, startRow, colCount, stripe){
41390 var ts = this.templates, ct = ts.cell, rt = ts.row;
41392 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
41394 var hasListener = this.grid.hasListener('rowclass');
41396 for(var j = 0, len = rs.length; j < len; j++){
41397 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
41398 for(var i = 0; i < colCount; i++){
41400 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
41402 p.css = p.attr = "";
41403 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
41404 if(p.value == undefined || p.value === "") {
41405 p.value = " ";
41408 p.css += ' x-grid-editable-cell';
41410 if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
41411 p.css += ' x-grid-dirty-cell';
41413 var markup = ct.apply(p);
41421 if(stripe && ((rowIndex+1) % 2 == 0)){
41422 alt.push("x-grid-row-alt")
41425 alt.push( " x-grid-dirty-row");
41428 if(this.getRowClass){
41429 alt.push(this.getRowClass(r, rowIndex));
41435 rowIndex : rowIndex,
41438 this.grid.fireEvent('rowclass', this, rowcfg);
41439 alt.push(rowcfg.rowClass);
41441 rp.alt = alt.join(" ");
41442 lbuf+= rt.apply(rp);
41444 buf+= rt.apply(rp);
41446 return [lbuf, buf];
41448 function(cs, rs, ds, startRow, colCount, stripe){
41449 var ts = this.templates, ct = ts.cell, rt = ts.row;
41451 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
41452 var hasListener = this.grid.hasListener('rowclass');
41455 for(var j = 0, len = rs.length; j < len; j++){
41456 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
41457 for(var i = 0; i < colCount; i++){
41459 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
41461 p.css = p.attr = "";
41462 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
41463 if(p.value == undefined || p.value === "") {
41464 p.value = " ";
41468 p.css += ' x-grid-editable-cell';
41470 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
41471 p.css += ' x-grid-dirty-cell'
41474 var markup = ct.apply(p);
41476 cb[cb.length] = markup;
41478 lcb[lcb.length] = markup;
41482 if(stripe && ((rowIndex+1) % 2 == 0)){
41483 alt.push( "x-grid-row-alt");
41486 alt.push(" x-grid-dirty-row");
41489 if(this.getRowClass){
41490 alt.push( this.getRowClass(r, rowIndex));
41496 rowIndex : rowIndex,
41499 this.grid.fireEvent('rowclass', this, rowcfg);
41500 alt.push(rowcfg.rowClass);
41503 rp.alt = alt.join(" ");
41504 rp.cells = lcb.join("");
41505 lbuf[lbuf.length] = rt.apply(rp);
41506 rp.cells = cb.join("");
41507 buf[buf.length] = rt.apply(rp);
41509 return [lbuf.join(""), buf.join("")];
41512 renderBody : function(){
41513 var markup = this.renderRows();
41514 var bt = this.templates.body;
41515 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
41519 * Refreshes the grid
41520 * @param {Boolean} headersToo
41522 refresh : function(headersToo){
41523 this.fireEvent("beforerefresh", this);
41524 this.grid.stopEditing();
41525 var result = this.renderBody();
41526 this.lockedBody.update(result[0]);
41527 this.mainBody.update(result[1]);
41528 if(headersToo === true){
41529 this.updateHeaders();
41530 this.updateColumns();
41531 this.updateSplitters();
41532 this.updateHeaderSortState();
41534 this.syncRowHeights();
41536 this.fireEvent("refresh", this);
41539 handleColumnMove : function(cm, oldIndex, newIndex){
41540 this.indexMap = null;
41541 var s = this.getScrollState();
41542 this.refresh(true);
41543 this.restoreScroll(s);
41544 this.afterMove(newIndex);
41547 afterMove : function(colIndex){
41548 if(this.enableMoveAnim && Roo.enableFx){
41549 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
41551 // if multisort - fix sortOrder, and reload..
41552 if (this.grid.dataSource.multiSort) {
41553 // the we can call sort again..
41554 var dm = this.grid.dataSource;
41555 var cm = this.grid.colModel;
41557 for(var i = 0; i < cm.config.length; i++ ) {
41559 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
41560 continue; // dont' bother, it's not in sort list or being set.
41563 so.push(cm.config[i].dataIndex);
41566 dm.load(dm.lastOptions);
41573 updateCell : function(dm, rowIndex, dataIndex){
41574 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
41575 if(typeof colIndex == "undefined"){ // not present in grid
41578 var cm = this.grid.colModel;
41579 var cell = this.getCell(rowIndex, colIndex);
41580 var cellText = this.getCellText(rowIndex, colIndex);
41583 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
41584 id : cm.getColumnId(colIndex),
41585 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
41587 var renderer = cm.getRenderer(colIndex);
41588 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
41589 if(typeof val == "undefined" || val === "") {
41592 cellText.innerHTML = val;
41593 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
41594 this.syncRowHeights(rowIndex, rowIndex);
41597 calcColumnWidth : function(colIndex, maxRowsToMeasure){
41599 if(this.grid.autoSizeHeaders){
41600 var h = this.getHeaderCellMeasure(colIndex);
41601 maxWidth = Math.max(maxWidth, h.scrollWidth);
41604 if(this.cm.isLocked(colIndex)){
41605 tb = this.getLockedTable();
41608 tb = this.getBodyTable();
41609 index = colIndex - this.cm.getLockedCount();
41612 var rows = tb.rows;
41613 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
41614 for(var i = 0; i < stopIndex; i++){
41615 var cell = rows[i].childNodes[index].firstChild;
41616 maxWidth = Math.max(maxWidth, cell.scrollWidth);
41619 return maxWidth + /*margin for error in IE*/ 5;
41622 * Autofit a column to its content.
41623 * @param {Number} colIndex
41624 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
41626 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
41627 if(this.cm.isHidden(colIndex)){
41628 return; // can't calc a hidden column
41631 var cid = this.cm.getColumnId(colIndex);
41632 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
41633 if(this.grid.autoSizeHeaders){
41634 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
41637 var newWidth = this.calcColumnWidth(colIndex);
41638 this.cm.setColumnWidth(colIndex,
41639 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
41640 if(!suppressEvent){
41641 this.grid.fireEvent("columnresize", colIndex, newWidth);
41646 * Autofits all columns to their content and then expands to fit any extra space in the grid
41648 autoSizeColumns : function(){
41649 var cm = this.grid.colModel;
41650 var colCount = cm.getColumnCount();
41651 for(var i = 0; i < colCount; i++){
41652 this.autoSizeColumn(i, true, true);
41654 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
41657 this.updateColumns();
41663 * Autofits all columns to the grid's width proportionate with their current size
41664 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
41666 fitColumns : function(reserveScrollSpace){
41667 var cm = this.grid.colModel;
41668 var colCount = cm.getColumnCount();
41672 for (i = 0; i < colCount; i++){
41673 if(!cm.isHidden(i) && !cm.isFixed(i)){
41674 w = cm.getColumnWidth(i);
41680 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
41681 if(reserveScrollSpace){
41684 var frac = (avail - cm.getTotalWidth())/width;
41685 while (cols.length){
41688 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
41690 this.updateColumns();
41694 onRowSelect : function(rowIndex){
41695 var row = this.getRowComposite(rowIndex);
41696 row.addClass("x-grid-row-selected");
41699 onRowDeselect : function(rowIndex){
41700 var row = this.getRowComposite(rowIndex);
41701 row.removeClass("x-grid-row-selected");
41704 onCellSelect : function(row, col){
41705 var cell = this.getCell(row, col);
41707 Roo.fly(cell).addClass("x-grid-cell-selected");
41711 onCellDeselect : function(row, col){
41712 var cell = this.getCell(row, col);
41714 Roo.fly(cell).removeClass("x-grid-cell-selected");
41718 updateHeaderSortState : function(){
41720 // sort state can be single { field: xxx, direction : yyy}
41721 // or { xxx=>ASC , yyy : DESC ..... }
41724 if (!this.ds.multiSort) {
41725 var state = this.ds.getSortState();
41729 mstate[state.field] = state.direction;
41730 // FIXME... - this is not used here.. but might be elsewhere..
41731 this.sortState = state;
41734 mstate = this.ds.sortToggle;
41736 //remove existing sort classes..
41738 var sc = this.sortClasses;
41739 var hds = this.el.select(this.headerSelector).removeClass(sc);
41741 for(var f in mstate) {
41743 var sortColumn = this.cm.findColumnIndex(f);
41745 if(sortColumn != -1){
41746 var sortDir = mstate[f];
41747 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
41756 handleHeaderClick : function(g, index,e){
41758 Roo.log("header click");
41761 // touch events on header are handled by context
41762 this.handleHdCtx(g,index,e);
41767 if(this.headersDisabled){
41770 var dm = g.dataSource, cm = g.colModel;
41771 if(!cm.isSortable(index)){
41776 if (dm.multiSort) {
41777 // update the sortOrder
41779 for(var i = 0; i < cm.config.length; i++ ) {
41781 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
41782 continue; // dont' bother, it's not in sort list or being set.
41785 so.push(cm.config[i].dataIndex);
41791 dm.sort(cm.getDataIndex(index));
41795 destroy : function(){
41797 this.colMenu.removeAll();
41798 Roo.menu.MenuMgr.unregister(this.colMenu);
41799 this.colMenu.getEl().remove();
41800 delete this.colMenu;
41803 this.hmenu.removeAll();
41804 Roo.menu.MenuMgr.unregister(this.hmenu);
41805 this.hmenu.getEl().remove();
41808 if(this.grid.enableColumnMove){
41809 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
41811 for(var dd in dds){
41812 if(!dds[dd].config.isTarget && dds[dd].dragElId){
41813 var elid = dds[dd].dragElId;
41815 Roo.get(elid).remove();
41816 } else if(dds[dd].config.isTarget){
41817 dds[dd].proxyTop.remove();
41818 dds[dd].proxyBottom.remove();
41821 if(Roo.dd.DDM.locationCache[dd]){
41822 delete Roo.dd.DDM.locationCache[dd];
41825 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
41828 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
41829 this.bind(null, null);
41830 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
41833 handleLockChange : function(){
41834 this.refresh(true);
41837 onDenyColumnLock : function(){
41841 onDenyColumnHide : function(){
41845 handleHdMenuClick : function(item){
41846 var index = this.hdCtxIndex;
41847 var cm = this.cm, ds = this.ds;
41850 ds.sort(cm.getDataIndex(index), "ASC");
41853 ds.sort(cm.getDataIndex(index), "DESC");
41856 var lc = cm.getLockedCount();
41857 if(cm.getColumnCount(true) <= lc+1){
41858 this.onDenyColumnLock();
41862 cm.setLocked(index, true, true);
41863 cm.moveColumn(index, lc);
41864 this.grid.fireEvent("columnmove", index, lc);
41866 cm.setLocked(index, true);
41870 var lc = cm.getLockedCount();
41871 if((lc-1) != index){
41872 cm.setLocked(index, false, true);
41873 cm.moveColumn(index, lc-1);
41874 this.grid.fireEvent("columnmove", index, lc-1);
41876 cm.setLocked(index, false);
41879 case 'wider': // used to expand cols on touch..
41881 var cw = cm.getColumnWidth(index);
41882 cw += (item.id == 'wider' ? 1 : -1) * 50;
41883 cw = Math.max(0, cw);
41884 cw = Math.min(cw,4000);
41885 cm.setColumnWidth(index, cw);
41889 index = cm.getIndexById(item.id.substr(4));
41891 if(item.checked && cm.getColumnCount(true) <= 1){
41892 this.onDenyColumnHide();
41895 cm.setHidden(index, item.checked);
41901 beforeColMenuShow : function(){
41902 var cm = this.cm, colCount = cm.getColumnCount();
41903 this.colMenu.removeAll();
41906 for(var i = 0; i < colCount; i++){
41908 id: "col-"+cm.getColumnId(i),
41909 text: cm.getColumnHeader(i),
41910 checked: !cm.isHidden(i),
41915 if (this.grid.sortColMenu) {
41916 items.sort(function(a,b) {
41917 if (a.text == b.text) {
41920 return a.text.toUpperCase() > b.text.toUpperCase() ? 1 : -1;
41924 for(var i = 0; i < colCount; i++){
41925 this.colMenu.add(new Roo.menu.CheckItem(items[i]));
41929 handleHdCtx : function(g, index, e){
41931 var hd = this.getHeaderCell(index);
41932 this.hdCtxIndex = index;
41933 var ms = this.hmenu.items, cm = this.cm;
41934 ms.get("asc").setDisabled(!cm.isSortable(index));
41935 ms.get("desc").setDisabled(!cm.isSortable(index));
41936 if(this.grid.enableColLock !== false){
41937 ms.get("lock").setDisabled(cm.isLocked(index));
41938 ms.get("unlock").setDisabled(!cm.isLocked(index));
41940 this.hmenu.show(hd, "tl-bl");
41943 handleHdOver : function(e){
41944 var hd = this.findHeaderCell(e.getTarget());
41945 if(hd && !this.headersDisabled){
41946 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
41947 this.fly(hd).addClass("x-grid-hd-over");
41952 handleHdOut : function(e){
41953 var hd = this.findHeaderCell(e.getTarget());
41955 this.fly(hd).removeClass("x-grid-hd-over");
41959 handleSplitDblClick : function(e, t){
41960 var i = this.getCellIndex(t);
41961 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
41962 this.autoSizeColumn(i, true);
41967 render : function(){
41970 var colCount = cm.getColumnCount();
41972 if(this.grid.monitorWindowResize === true){
41973 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
41975 var header = this.renderHeaders();
41976 var body = this.templates.body.apply({rows:""});
41977 var html = this.templates.master.apply({
41980 lockedHeader: header[0],
41984 //this.updateColumns();
41986 this.grid.getGridEl().dom.innerHTML = html;
41988 this.initElements();
41990 // a kludge to fix the random scolling effect in webkit
41991 this.el.on("scroll", function() {
41992 this.el.dom.scrollTop=0; // hopefully not recursive..
41995 this.scroller.on("scroll", this.handleScroll, this);
41996 this.lockedBody.on("mousewheel", this.handleWheel, this);
41997 this.mainBody.on("mousewheel", this.handleWheel, this);
41999 this.mainHd.on("mouseover", this.handleHdOver, this);
42000 this.mainHd.on("mouseout", this.handleHdOut, this);
42001 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
42002 {delegate: "."+this.splitClass});
42004 this.lockedHd.on("mouseover", this.handleHdOver, this);
42005 this.lockedHd.on("mouseout", this.handleHdOut, this);
42006 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
42007 {delegate: "."+this.splitClass});
42009 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
42010 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
42013 this.updateSplitters();
42015 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
42016 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
42017 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
42020 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
42021 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
42023 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
42024 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
42026 if(this.grid.enableColLock !== false){
42027 this.hmenu.add('-',
42028 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
42029 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
42033 this.hmenu.add('-',
42034 {id:"wider", text: this.columnsWiderText},
42035 {id:"narrow", text: this.columnsNarrowText }
42041 if(this.grid.enableColumnHide !== false){
42043 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
42044 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
42045 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
42047 this.hmenu.add('-',
42048 {id:"columns", text: this.columnsText, menu: this.colMenu}
42051 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
42053 this.grid.on("headercontextmenu", this.handleHdCtx, this);
42056 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
42057 this.dd = new Roo.grid.GridDragZone(this.grid, {
42058 ddGroup : this.grid.ddGroup || 'GridDD'
42064 for(var i = 0; i < colCount; i++){
42065 if(cm.isHidden(i)){
42066 this.hideColumn(i);
42068 if(cm.config[i].align){
42069 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
42070 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
42074 this.updateHeaderSortState();
42076 this.beforeInitialResize();
42079 // two part rendering gives faster view to the user
42080 this.renderPhase2.defer(1, this);
42083 renderPhase2 : function(){
42084 // render the rows now
42086 if(this.grid.autoSizeColumns){
42087 this.autoSizeColumns();
42091 beforeInitialResize : function(){
42095 onColumnSplitterMoved : function(i, w){
42096 this.userResized = true;
42097 var cm = this.grid.colModel;
42098 cm.setColumnWidth(i, w, true);
42099 var cid = cm.getColumnId(i);
42100 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
42101 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
42102 this.updateSplitters();
42104 this.grid.fireEvent("columnresize", i, w);
42107 syncRowHeights : function(startIndex, endIndex){
42108 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
42109 startIndex = startIndex || 0;
42110 var mrows = this.getBodyTable().rows;
42111 var lrows = this.getLockedTable().rows;
42112 var len = mrows.length-1;
42113 endIndex = Math.min(endIndex || len, len);
42114 for(var i = startIndex; i <= endIndex; i++){
42115 var m = mrows[i], l = lrows[i];
42116 var h = Math.max(m.offsetHeight, l.offsetHeight);
42117 m.style.height = l.style.height = h + "px";
42122 layout : function(initialRender, is2ndPass)
42125 var auto = g.autoHeight;
42126 var scrollOffset = 16;
42127 var c = g.getGridEl(), cm = this.cm,
42128 expandCol = g.autoExpandColumn,
42130 //c.beginMeasure();
42132 if(!c.dom.offsetWidth){ // display:none?
42134 this.lockedWrap.show();
42135 this.mainWrap.show();
42140 var hasLock = this.cm.isLocked(0);
42142 var tbh = this.headerPanel.getHeight();
42143 var bbh = this.footerPanel.getHeight();
42146 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
42147 var newHeight = ch + c.getBorderWidth("tb");
42149 newHeight = Math.min(g.maxHeight, newHeight);
42151 c.setHeight(newHeight);
42155 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
42158 var s = this.scroller;
42160 var csize = c.getSize(true);
42162 this.el.setSize(csize.width, csize.height);
42164 this.headerPanel.setWidth(csize.width);
42165 this.footerPanel.setWidth(csize.width);
42167 var hdHeight = this.mainHd.getHeight();
42168 var vw = csize.width;
42169 var vh = csize.height - (tbh + bbh);
42173 var bt = this.getBodyTable();
42175 if(cm.getLockedCount() == cm.config.length){
42176 bt = this.getLockedTable();
42179 var ltWidth = hasLock ?
42180 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
42182 var scrollHeight = bt.offsetHeight;
42183 var scrollWidth = ltWidth + bt.offsetWidth;
42184 var vscroll = false, hscroll = false;
42186 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
42188 var lw = this.lockedWrap, mw = this.mainWrap;
42189 var lb = this.lockedBody, mb = this.mainBody;
42191 setTimeout(function(){
42192 var t = s.dom.offsetTop;
42193 var w = s.dom.clientWidth,
42194 h = s.dom.clientHeight;
42197 lw.setSize(ltWidth, h);
42199 mw.setLeftTop(ltWidth, t);
42200 mw.setSize(w-ltWidth, h);
42202 lb.setHeight(h-hdHeight);
42203 mb.setHeight(h-hdHeight);
42205 if(is2ndPass !== true && !gv.userResized && expandCol){
42206 // high speed resize without full column calculation
42208 var ci = cm.getIndexById(expandCol);
42210 ci = cm.findColumnIndex(expandCol);
42212 ci = Math.max(0, ci); // make sure it's got at least the first col.
42213 var expandId = cm.getColumnId(ci);
42214 var tw = cm.getTotalWidth(false);
42215 var currentWidth = cm.getColumnWidth(ci);
42216 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
42217 if(currentWidth != cw){
42218 cm.setColumnWidth(ci, cw, true);
42219 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
42220 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
42221 gv.updateSplitters();
42222 gv.layout(false, true);
42234 onWindowResize : function(){
42235 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
42241 appendFooter : function(parentEl){
42245 sortAscText : "Sort Ascending",
42246 sortDescText : "Sort Descending",
42247 lockText : "Lock Column",
42248 unlockText : "Unlock Column",
42249 columnsText : "Columns",
42251 columnsWiderText : "Wider",
42252 columnsNarrowText : "Thinner"
42256 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
42257 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
42258 this.proxy.el.addClass('x-grid3-col-dd');
42261 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
42262 handleMouseDown : function(e){
42266 callHandleMouseDown : function(e){
42267 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
42272 * Ext JS Library 1.1.1
42273 * Copyright(c) 2006-2007, Ext JS, LLC.
42275 * Originally Released Under LGPL - original licence link has changed is not relivant.
42278 * <script type="text/javascript">
42281 * @extends Roo.dd.DDProxy
42282 * @class Roo.grid.SplitDragZone
42283 * Support for Column Header resizing
42285 * @param {Object} config
42288 // This is a support class used internally by the Grid components
42289 Roo.grid.SplitDragZone = function(grid, hd, hd2){
42291 this.view = grid.getView();
42292 this.proxy = this.view.resizeProxy;
42293 Roo.grid.SplitDragZone.superclass.constructor.call(
42296 "gridSplitters" + this.grid.getGridEl().id, // SGROUP
42298 dragElId : Roo.id(this.proxy.dom),
42303 this.setHandleElId(Roo.id(hd));
42304 if (hd2 !== false) {
42305 this.setOuterHandleElId(Roo.id(hd2));
42308 this.scroll = false;
42310 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
42311 fly: Roo.Element.fly,
42313 b4StartDrag : function(x, y){
42314 this.view.headersDisabled = true;
42315 var h = this.view.mainWrap ? this.view.mainWrap.getHeight() : (
42316 this.view.headEl.getHeight() + this.view.bodyEl.getHeight()
42318 this.proxy.setHeight(h);
42320 // for old system colWidth really stored the actual width?
42321 // in bootstrap we tried using xs/ms/etc.. to do % sizing?
42322 // which in reality did not work.. - it worked only for fixed sizes
42323 // for resizable we need to use actual sizes.
42324 var w = this.cm.getColumnWidth(this.cellIndex);
42325 if (!this.view.mainWrap) {
42327 w = this.view.getHeaderIndex(this.cellIndex).getWidth();
42332 // this was w-this.grid.minColumnWidth;
42333 // doesnt really make sense? - w = thie curren width or the rendered one?
42334 var minw = Math.max(w-this.grid.minColumnWidth, 0);
42335 this.resetConstraints();
42336 this.setXConstraint(minw, 1000);
42337 this.setYConstraint(0, 0);
42338 this.minX = x - minw;
42339 this.maxX = x + 1000;
42341 if (!this.view.mainWrap) { // this is Bootstrap code..
42342 this.getDragEl().style.display='block';
42345 Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
42349 handleMouseDown : function(e){
42350 ev = Roo.EventObject.setEvent(e);
42351 var t = this.fly(ev.getTarget());
42352 if(t.hasClass("x-grid-split")){
42353 this.cellIndex = this.view.getCellIndex(t.dom);
42354 this.split = t.dom;
42355 this.cm = this.grid.colModel;
42356 if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
42357 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
42362 endDrag : function(e){
42363 this.view.headersDisabled = false;
42364 var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
42365 var diff = endX - this.startPos;
42367 var w = this.cm.getColumnWidth(this.cellIndex);
42368 if (!this.view.mainWrap) {
42371 this.view.onColumnSplitterMoved(this.cellIndex, w+diff);
42374 autoOffset : function(){
42375 this.setDelta(0,0);
42379 * Ext JS Library 1.1.1
42380 * Copyright(c) 2006-2007, Ext JS, LLC.
42382 * Originally Released Under LGPL - original licence link has changed is not relivant.
42385 * <script type="text/javascript">
42389 // This is a support class used internally by the Grid components
42390 Roo.grid.GridDragZone = function(grid, config){
42391 this.view = grid.getView();
42392 Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
42393 if(this.view.lockedBody){
42394 this.setHandleElId(Roo.id(this.view.mainBody.dom));
42395 this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
42397 this.scroll = false;
42399 this.ddel = document.createElement('div');
42400 this.ddel.className = 'x-grid-dd-wrap';
42403 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
42404 ddGroup : "GridDD",
42406 getDragData : function(e){
42407 var t = Roo.lib.Event.getTarget(e);
42408 var rowIndex = this.view.findRowIndex(t);
42409 var sm = this.grid.selModel;
42411 //Roo.log(rowIndex);
42413 if (sm.getSelectedCell) {
42414 // cell selection..
42415 if (!sm.getSelectedCell()) {
42418 if (rowIndex != sm.getSelectedCell()[0]) {
42423 if (sm.getSelections && sm.getSelections().length < 1) {
42428 // before it used to all dragging of unseleted... - now we dont do that.
42429 if(rowIndex !== false){
42434 //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
42436 //if(!sm.isSelected(rowIndex) || e.hasModifier()){
42439 if (e.hasModifier()){
42440 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
42443 Roo.log("getDragData");
42448 rowIndex: rowIndex,
42449 selections: sm.getSelections ? sm.getSelections() : (
42450 sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : [])
42457 onInitDrag : function(e){
42458 var data = this.dragData;
42459 this.ddel.innerHTML = this.grid.getDragDropText();
42460 this.proxy.update(this.ddel);
42461 // fire start drag?
42464 afterRepair : function(){
42465 this.dragging = false;
42468 getRepairXY : function(e, data){
42472 onEndDrag : function(data, e){
42476 onValidDrop : function(dd, e, id){
42481 beforeInvalidDrop : function(e, id){
42486 * Ext JS Library 1.1.1
42487 * Copyright(c) 2006-2007, Ext JS, LLC.
42489 * Originally Released Under LGPL - original licence link has changed is not relivant.
42492 * <script type="text/javascript">
42497 * @class Roo.grid.ColumnModel
42498 * @extends Roo.util.Observable
42499 * This is the default implementation of a ColumnModel used by the Grid. It defines
42500 * the columns in the grid.
42503 var colModel = new Roo.grid.ColumnModel([
42504 {header: "Ticker", width: 60, sortable: true, locked: true},
42505 {header: "Company Name", width: 150, sortable: true},
42506 {header: "Market Cap.", width: 100, sortable: true},
42507 {header: "$ Sales", width: 100, sortable: true, renderer: money},
42508 {header: "Employees", width: 100, sortable: true, resizable: false}
42513 * The config options listed for this class are options which may appear in each
42514 * individual column definition.
42515 * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
42517 * @param {Object} config An Array of column config objects. See this class's
42518 * config objects for details.
42520 Roo.grid.ColumnModel = function(config){
42522 * The config passed into the constructor
42524 this.config = []; //config;
42527 // if no id, create one
42528 // if the column does not have a dataIndex mapping,
42529 // map it to the order it is in the config
42530 for(var i = 0, len = config.length; i < len; i++){
42531 this.addColumn(config[i]);
42536 * The width of columns which have no width specified (defaults to 100)
42539 this.defaultWidth = 100;
42542 * Default sortable of columns which have no sortable specified (defaults to false)
42545 this.defaultSortable = false;
42549 * @event widthchange
42550 * Fires when the width of a column changes.
42551 * @param {ColumnModel} this
42552 * @param {Number} columnIndex The column index
42553 * @param {Number} newWidth The new width
42555 "widthchange": true,
42557 * @event headerchange
42558 * Fires when the text of a header changes.
42559 * @param {ColumnModel} this
42560 * @param {Number} columnIndex The column index
42561 * @param {Number} newText The new header text
42563 "headerchange": true,
42565 * @event hiddenchange
42566 * Fires when a column is hidden or "unhidden".
42567 * @param {ColumnModel} this
42568 * @param {Number} columnIndex The column index
42569 * @param {Boolean} hidden true if hidden, false otherwise
42571 "hiddenchange": true,
42573 * @event columnmoved
42574 * Fires when a column is moved.
42575 * @param {ColumnModel} this
42576 * @param {Number} oldIndex
42577 * @param {Number} newIndex
42579 "columnmoved" : true,
42581 * @event columlockchange
42582 * Fires when a column's locked state is changed
42583 * @param {ColumnModel} this
42584 * @param {Number} colIndex
42585 * @param {Boolean} locked true if locked
42587 "columnlockchange" : true
42589 Roo.grid.ColumnModel.superclass.constructor.call(this);
42591 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
42593 * @cfg {String} header [required] The header text to display in the Grid view.
42596 * @cfg {String} xsHeader Header at Bootsrap Extra Small width (default for all)
42599 * @cfg {String} smHeader Header at Bootsrap Small width
42602 * @cfg {String} mdHeader Header at Bootsrap Medium width
42605 * @cfg {String} lgHeader Header at Bootsrap Large width
42608 * @cfg {String} xlHeader Header at Bootsrap extra Large width
42611 * @cfg {String} dataIndex The name of the field in the grid's {@link Roo.data.Store}'s
42612 * {@link Roo.data.Record} definition from which to draw the column's value. If not
42613 * specified, the column's index is used as an index into the Record's data Array.
42616 * @cfg {Number} width The initial width in pixels of the column. Using this
42617 * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
42620 * @cfg {Boolean} sortable True if sorting is to be allowed on this column.
42621 * Defaults to the value of the {@link #defaultSortable} property.
42622 * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
42625 * @cfg {Boolean} locked True to lock the column in place while scrolling the Grid. Defaults to false.
42628 * @cfg {Boolean} fixed True if the column width cannot be changed. Defaults to false.
42631 * @cfg {Boolean} resizable False to disable column resizing. Defaults to true.
42634 * @cfg {Boolean} hidden True to hide the column. Defaults to false.
42637 * @cfg {Function} renderer A function used to generate HTML markup for a cell
42638 * given the cell's data value. See {@link #setRenderer}. If not specified, the
42639 * default renderer returns the escaped data value. If an object is returned (bootstrap only)
42640 * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
42643 * @cfg {Roo.grid.GridEditor} editor For grid editors - returns the grid editor
42646 * @cfg {String} align (left|right) Set the CSS text-align property of the column. Defaults to undefined (left).
42649 * @cfg {String} valign (top|bottom|middle) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc). Defaults to undefined (middle)
42652 * @cfg {String} cursor ( auto|default|none|context-menu|help|pointer|progress|wait|cell|crosshair|text|vertical-text|alias|copy|move|no-drop|not-allowed|e-resize|n-resize|ne-resize|nw-resize|s-resize|se-resize|sw-resize|w-resize|ew-resize|ns-resize|nesw-resize|nwse-resize|col-resize|row-resize|all-scroll|zoom-in|zoom-out|grab|grabbing)
42655 * @cfg {String} tooltip mouse over tooltip text
42658 * @cfg {Number} xs can be '0' for hidden at this size (number less than 12)
42661 * @cfg {Number} sm can be '0' for hidden at this size (number less than 12)
42664 * @cfg {Number} md can be '0' for hidden at this size (number less than 12)
42667 * @cfg {Number} lg can be '0' for hidden at this size (number less than 12)
42670 * @cfg {Number} xl can be '0' for hidden at this size (number less than 12)
42673 * Returns the id of the column at the specified index.
42674 * @param {Number} index The column index
42675 * @return {String} the id
42677 getColumnId : function(index){
42678 return this.config[index].id;
42682 * Returns the column for a specified id.
42683 * @param {String} id The column id
42684 * @return {Object} the column
42686 getColumnById : function(id){
42687 return this.lookup[id];
42692 * Returns the column Object for a specified dataIndex.
42693 * @param {String} dataIndex The column dataIndex
42694 * @return {Object|Boolean} the column or false if not found
42696 getColumnByDataIndex: function(dataIndex){
42697 var index = this.findColumnIndex(dataIndex);
42698 return index > -1 ? this.config[index] : false;
42702 * Returns the index for a specified column id.
42703 * @param {String} id The column id
42704 * @return {Number} the index, or -1 if not found
42706 getIndexById : function(id){
42707 for(var i = 0, len = this.config.length; i < len; i++){
42708 if(this.config[i].id == id){
42716 * Returns the index for a specified column dataIndex.
42717 * @param {String} dataIndex The column dataIndex
42718 * @return {Number} the index, or -1 if not found
42721 findColumnIndex : function(dataIndex){
42722 for(var i = 0, len = this.config.length; i < len; i++){
42723 if(this.config[i].dataIndex == dataIndex){
42731 moveColumn : function(oldIndex, newIndex){
42732 var c = this.config[oldIndex];
42733 this.config.splice(oldIndex, 1);
42734 this.config.splice(newIndex, 0, c);
42735 this.dataMap = null;
42736 this.fireEvent("columnmoved", this, oldIndex, newIndex);
42739 isLocked : function(colIndex){
42740 return this.config[colIndex].locked === true;
42743 setLocked : function(colIndex, value, suppressEvent){
42744 if(this.isLocked(colIndex) == value){
42747 this.config[colIndex].locked = value;
42748 if(!suppressEvent){
42749 this.fireEvent("columnlockchange", this, colIndex, value);
42753 getTotalLockedWidth : function(){
42754 var totalWidth = 0;
42755 for(var i = 0; i < this.config.length; i++){
42756 if(this.isLocked(i) && !this.isHidden(i)){
42757 this.totalWidth += this.getColumnWidth(i);
42763 getLockedCount : function(){
42764 for(var i = 0, len = this.config.length; i < len; i++){
42765 if(!this.isLocked(i)){
42770 return this.config.length;
42774 * Returns the number of columns.
42777 getColumnCount : function(visibleOnly){
42778 if(visibleOnly === true){
42780 for(var i = 0, len = this.config.length; i < len; i++){
42781 if(!this.isHidden(i)){
42787 return this.config.length;
42791 * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
42792 * @param {Function} fn
42793 * @param {Object} scope (optional)
42794 * @return {Array} result
42796 getColumnsBy : function(fn, scope){
42798 for(var i = 0, len = this.config.length; i < len; i++){
42799 var c = this.config[i];
42800 if(fn.call(scope||this, c, i) === true){
42808 * Returns true if the specified column is sortable.
42809 * @param {Number} col The column index
42810 * @return {Boolean}
42812 isSortable : function(col){
42813 if(typeof this.config[col].sortable == "undefined"){
42814 return this.defaultSortable;
42816 return this.config[col].sortable;
42820 * Returns the rendering (formatting) function defined for the column.
42821 * @param {Number} col The column index.
42822 * @return {Function} The function used to render the cell. See {@link #setRenderer}.
42824 getRenderer : function(col){
42825 if(!this.config[col].renderer){
42826 return Roo.grid.ColumnModel.defaultRenderer;
42828 return this.config[col].renderer;
42832 * Sets the rendering (formatting) function for a column.
42833 * @param {Number} col The column index
42834 * @param {Function} fn The function to use to process the cell's raw data
42835 * to return HTML markup for the grid view. The render function is called with
42836 * the following parameters:<ul>
42837 * <li>Data value.</li>
42838 * <li>Cell metadata. An object in which you may set the following attributes:<ul>
42839 * <li>css A CSS style string to apply to the table cell.</li>
42840 * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
42841 * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
42842 * <li>Row index</li>
42843 * <li>Column index</li>
42844 * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
42846 setRenderer : function(col, fn){
42847 this.config[col].renderer = fn;
42851 * Returns the width for the specified column.
42852 * @param {Number} col The column index
42853 * @param (optional) {String} gridSize bootstrap width size.
42856 getColumnWidth : function(col, gridSize)
42858 var cfg = this.config[col];
42860 if (typeof(gridSize) == 'undefined') {
42861 return cfg.width * 1 || this.defaultWidth;
42863 if (gridSize === false) { // if we set it..
42864 return cfg.width || false;
42866 var sizes = ['xl', 'lg', 'md', 'sm', 'xs'];
42868 for(var i = sizes.indexOf(gridSize); i < sizes.length; i++) {
42869 if (typeof(cfg[ sizes[i] ] ) == 'undefined') {
42872 return cfg[ sizes[i] ];
42879 * Sets the width for a column.
42880 * @param {Number} col The column index
42881 * @param {Number} width The new width
42883 setColumnWidth : function(col, width, suppressEvent){
42884 this.config[col].width = width;
42885 this.totalWidth = null;
42886 if(!suppressEvent){
42887 this.fireEvent("widthchange", this, col, width);
42892 * Returns the total width of all columns.
42893 * @param {Boolean} includeHidden True to include hidden column widths
42896 getTotalWidth : function(includeHidden){
42897 if(!this.totalWidth){
42898 this.totalWidth = 0;
42899 for(var i = 0, len = this.config.length; i < len; i++){
42900 if(includeHidden || !this.isHidden(i)){
42901 this.totalWidth += this.getColumnWidth(i);
42905 return this.totalWidth;
42909 * Returns the header for the specified column.
42910 * @param {Number} col The column index
42913 getColumnHeader : function(col){
42914 return this.config[col].header;
42918 * Sets the header for a column.
42919 * @param {Number} col The column index
42920 * @param {String} header The new header
42922 setColumnHeader : function(col, header){
42923 this.config[col].header = header;
42924 this.fireEvent("headerchange", this, col, header);
42928 * Returns the tooltip for the specified column.
42929 * @param {Number} col The column index
42932 getColumnTooltip : function(col){
42933 return this.config[col].tooltip;
42936 * Sets the tooltip for a column.
42937 * @param {Number} col The column index
42938 * @param {String} tooltip The new tooltip
42940 setColumnTooltip : function(col, tooltip){
42941 this.config[col].tooltip = tooltip;
42945 * Returns the dataIndex for the specified column.
42946 * @param {Number} col The column index
42949 getDataIndex : function(col){
42950 return this.config[col].dataIndex;
42954 * Sets the dataIndex for a column.
42955 * @param {Number} col The column index
42956 * @param {Number} dataIndex The new dataIndex
42958 setDataIndex : function(col, dataIndex){
42959 this.config[col].dataIndex = dataIndex;
42965 * Returns true if the cell is editable.
42966 * @param {Number} colIndex The column index
42967 * @param {Number} rowIndex The row index - this is nto actually used..?
42968 * @return {Boolean}
42970 isCellEditable : function(colIndex, rowIndex){
42971 return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
42975 * Returns the editor defined for the cell/column.
42976 * return false or null to disable editing.
42977 * @param {Number} colIndex The column index
42978 * @param {Number} rowIndex The row index
42981 getCellEditor : function(colIndex, rowIndex){
42982 return this.config[colIndex].editor;
42986 * Sets if a column is editable.
42987 * @param {Number} col The column index
42988 * @param {Boolean} editable True if the column is editable
42990 setEditable : function(col, editable){
42991 this.config[col].editable = editable;
42996 * Returns true if the column is hidden.
42997 * @param {Number} colIndex The column index
42998 * @return {Boolean}
43000 isHidden : function(colIndex){
43001 return this.config[colIndex].hidden;
43006 * Returns true if the column width cannot be changed
43008 isFixed : function(colIndex){
43009 return this.config[colIndex].fixed;
43013 * Returns true if the column can be resized
43014 * @return {Boolean}
43016 isResizable : function(colIndex){
43017 return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
43020 * Sets if a column is hidden.
43021 * @param {Number} colIndex The column index
43022 * @param {Boolean} hidden True if the column is hidden
43024 setHidden : function(colIndex, hidden){
43025 this.config[colIndex].hidden = hidden;
43026 this.totalWidth = null;
43027 this.fireEvent("hiddenchange", this, colIndex, hidden);
43031 * Sets the editor for a column.
43032 * @param {Number} col The column index
43033 * @param {Object} editor The editor object
43035 setEditor : function(col, editor){
43036 this.config[col].editor = editor;
43039 * Add a column (experimental...) - defaults to adding to the end..
43040 * @param {Object} config
43042 addColumn : function(c)
43045 var i = this.config.length;
43046 this.config[i] = c;
43048 if(typeof c.dataIndex == "undefined"){
43051 if(typeof c.renderer == "string"){
43052 c.renderer = Roo.util.Format[c.renderer];
43054 if(typeof c.id == "undefined"){
43057 if(c.editor && c.editor.xtype){
43058 c.editor = Roo.factory(c.editor, Roo.grid);
43060 if(c.editor && c.editor.isFormField){
43061 c.editor = new Roo.grid.GridEditor(c.editor);
43063 this.lookup[c.id] = c;
43068 Roo.grid.ColumnModel.defaultRenderer = function(value)
43070 if(typeof value == "object") {
43073 if(typeof value == "string" && value.length < 1){
43077 return String.format("{0}", value);
43080 // Alias for backwards compatibility
43081 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
43084 * Ext JS Library 1.1.1
43085 * Copyright(c) 2006-2007, Ext JS, LLC.
43087 * Originally Released Under LGPL - original licence link has changed is not relivant.
43090 * <script type="text/javascript">
43094 * @class Roo.grid.AbstractSelectionModel
43095 * @extends Roo.util.Observable
43097 * Abstract base class for grid SelectionModels. It provides the interface that should be
43098 * implemented by descendant classes. This class should not be directly instantiated.
43101 Roo.grid.AbstractSelectionModel = function(){
43102 this.locked = false;
43103 Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
43106 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable, {
43107 /** @ignore Called by the grid automatically. Do not call directly. */
43108 init : function(grid){
43114 * Locks the selections.
43117 this.locked = true;
43121 * Unlocks the selections.
43123 unlock : function(){
43124 this.locked = false;
43128 * Returns true if the selections are locked.
43129 * @return {Boolean}
43131 isLocked : function(){
43132 return this.locked;
43136 * Ext JS Library 1.1.1
43137 * Copyright(c) 2006-2007, Ext JS, LLC.
43139 * Originally Released Under LGPL - original licence link has changed is not relivant.
43142 * <script type="text/javascript">
43145 * @extends Roo.grid.AbstractSelectionModel
43146 * @class Roo.grid.RowSelectionModel
43147 * The default SelectionModel used by {@link Roo.grid.Grid}.
43148 * It supports multiple selections and keyboard selection/navigation.
43150 * @param {Object} config
43152 Roo.grid.RowSelectionModel = function(config){
43153 Roo.apply(this, config);
43154 this.selections = new Roo.util.MixedCollection(false, function(o){
43159 this.lastActive = false;
43163 * @event selectionchange
43164 * Fires when the selection changes
43165 * @param {SelectionModel} this
43167 "selectionchange" : true,
43169 * @event afterselectionchange
43170 * Fires after the selection changes (eg. by key press or clicking)
43171 * @param {SelectionModel} this
43173 "afterselectionchange" : true,
43175 * @event beforerowselect
43176 * Fires when a row is selected being selected, return false to cancel.
43177 * @param {SelectionModel} this
43178 * @param {Number} rowIndex The selected index
43179 * @param {Boolean} keepExisting False if other selections will be cleared
43181 "beforerowselect" : true,
43184 * Fires when a row is selected.
43185 * @param {SelectionModel} this
43186 * @param {Number} rowIndex The selected index
43187 * @param {Roo.data.Record} r The record
43189 "rowselect" : true,
43191 * @event rowdeselect
43192 * Fires when a row is deselected.
43193 * @param {SelectionModel} this
43194 * @param {Number} rowIndex The selected index
43196 "rowdeselect" : true
43198 Roo.grid.RowSelectionModel.superclass.constructor.call(this);
43199 this.locked = false;
43202 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel, {
43204 * @cfg {Boolean} singleSelect
43205 * True to allow selection of only one row at a time (defaults to false)
43207 singleSelect : false,
43210 initEvents : function(){
43212 if(!this.grid.enableDragDrop && !this.grid.enableDrag){
43213 this.grid.on("mousedown", this.handleMouseDown, this);
43214 }else{ // allow click to work like normal
43215 this.grid.on("rowclick", this.handleDragableRowClick, this);
43217 // bootstrap does not have a view..
43218 var view = this.grid.view ? this.grid.view : this.grid;
43219 this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
43220 "up" : function(e){
43222 this.selectPrevious(e.shiftKey);
43223 }else if(this.last !== false && this.lastActive !== false){
43224 var last = this.last;
43225 this.selectRange(this.last, this.lastActive-1);
43226 view.focusRow(this.lastActive);
43227 if(last !== false){
43231 this.selectFirstRow();
43233 this.fireEvent("afterselectionchange", this);
43235 "down" : function(e){
43237 this.selectNext(e.shiftKey);
43238 }else if(this.last !== false && this.lastActive !== false){
43239 var last = this.last;
43240 this.selectRange(this.last, this.lastActive+1);
43241 view.focusRow(this.lastActive);
43242 if(last !== false){
43246 this.selectFirstRow();
43248 this.fireEvent("afterselectionchange", this);
43254 view.on("refresh", this.onRefresh, this);
43255 view.on("rowupdated", this.onRowUpdated, this);
43256 view.on("rowremoved", this.onRemove, this);
43260 onRefresh : function(){
43261 var ds = this.grid.ds, i, v = this.grid.view;
43262 var s = this.selections;
43263 s.each(function(r){
43264 if((i = ds.indexOfId(r.id)) != -1){
43266 s.add(ds.getAt(i)); // updating the selection relate data
43274 onRemove : function(v, index, r){
43275 this.selections.remove(r);
43279 onRowUpdated : function(v, index, r){
43280 if(this.isSelected(r)){
43281 v.onRowSelect(index);
43287 * @param {Array} records The records to select
43288 * @param {Boolean} keepExisting (optional) True to keep existing selections
43290 selectRecords : function(records, keepExisting){
43292 this.clearSelections();
43294 var ds = this.grid.ds;
43295 for(var i = 0, len = records.length; i < len; i++){
43296 this.selectRow(ds.indexOf(records[i]), true);
43301 * Gets the number of selected rows.
43304 getCount : function(){
43305 return this.selections.length;
43309 * Selects the first row in the grid.
43311 selectFirstRow : function(){
43316 * Select the last row.
43317 * @param {Boolean} keepExisting (optional) True to keep existing selections
43319 selectLastRow : function(keepExisting){
43320 this.selectRow(this.grid.ds.getCount() - 1, keepExisting);
43324 * Selects the row immediately following the last selected row.
43325 * @param {Boolean} keepExisting (optional) True to keep existing selections
43327 selectNext : function(keepExisting){
43328 if(this.last !== false && (this.last+1) < this.grid.ds.getCount()){
43329 this.selectRow(this.last+1, keepExisting);
43330 var view = this.grid.view ? this.grid.view : this.grid;
43331 view.focusRow(this.last);
43336 * Selects the row that precedes the last selected row.
43337 * @param {Boolean} keepExisting (optional) True to keep existing selections
43339 selectPrevious : function(keepExisting){
43341 this.selectRow(this.last-1, keepExisting);
43342 var view = this.grid.view ? this.grid.view : this.grid;
43343 view.focusRow(this.last);
43348 * Returns the selected records
43349 * @return {Array} Array of selected records
43351 getSelections : function(){
43352 return [].concat(this.selections.items);
43356 * Returns the first selected record.
43359 getSelected : function(){
43360 return this.selections.itemAt(0);
43365 * Clears all selections.
43367 clearSelections : function(fast){
43372 var ds = this.grid.ds;
43373 var s = this.selections;
43374 s.each(function(r){
43375 this.deselectRow(ds.indexOfId(r.id));
43379 this.selections.clear();
43386 * Selects all rows.
43388 selectAll : function(){
43392 this.selections.clear();
43393 for(var i = 0, len = this.grid.ds.getCount(); i < len; i++){
43394 this.selectRow(i, true);
43399 * Returns True if there is a selection.
43400 * @return {Boolean}
43402 hasSelection : function(){
43403 return this.selections.length > 0;
43407 * Returns True if the specified row is selected.
43408 * @param {Number/Record} record The record or index of the record to check
43409 * @return {Boolean}
43411 isSelected : function(index){
43412 var r = typeof index == "number" ? this.grid.ds.getAt(index) : index;
43413 return (r && this.selections.key(r.id) ? true : false);
43417 * Returns True if the specified record id is selected.
43418 * @param {String} id The id of record to check
43419 * @return {Boolean}
43421 isIdSelected : function(id){
43422 return (this.selections.key(id) ? true : false);
43426 handleMouseDown : function(e, t)
43428 var view = this.grid.view ? this.grid.view : this.grid;
43430 if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
43433 if(e.shiftKey && this.last !== false){
43434 var last = this.last;
43435 this.selectRange(last, rowIndex, e.ctrlKey);
43436 this.last = last; // reset the last
43437 view.focusRow(rowIndex);
43439 var isSelected = this.isSelected(rowIndex);
43440 if(e.button !== 0 && isSelected){
43441 view.focusRow(rowIndex);
43442 }else if(e.ctrlKey && isSelected){
43443 this.deselectRow(rowIndex);
43444 }else if(!isSelected){
43445 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
43446 view.focusRow(rowIndex);
43449 this.fireEvent("afterselectionchange", this);
43452 handleDragableRowClick : function(grid, rowIndex, e)
43454 if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
43455 this.selectRow(rowIndex, false);
43456 var view = this.grid.view ? this.grid.view : this.grid;
43457 view.focusRow(rowIndex);
43458 this.fireEvent("afterselectionchange", this);
43463 * Selects multiple rows.
43464 * @param {Array} rows Array of the indexes of the row to select
43465 * @param {Boolean} keepExisting (optional) True to keep existing selections
43467 selectRows : function(rows, keepExisting){
43469 this.clearSelections();
43471 for(var i = 0, len = rows.length; i < len; i++){
43472 this.selectRow(rows[i], true);
43477 * Selects a range of rows. All rows in between startRow and endRow are also selected.
43478 * @param {Number} startRow The index of the first row in the range
43479 * @param {Number} endRow The index of the last row in the range
43480 * @param {Boolean} keepExisting (optional) True to retain existing selections
43482 selectRange : function(startRow, endRow, keepExisting){
43487 this.clearSelections();
43489 if(startRow <= endRow){
43490 for(var i = startRow; i <= endRow; i++){
43491 this.selectRow(i, true);
43494 for(var i = startRow; i >= endRow; i--){
43495 this.selectRow(i, true);
43501 * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
43502 * @param {Number} startRow The index of the first row in the range
43503 * @param {Number} endRow The index of the last row in the range
43505 deselectRange : function(startRow, endRow, preventViewNotify){
43509 for(var i = startRow; i <= endRow; i++){
43510 this.deselectRow(i, preventViewNotify);
43516 * @param {Number} row The index of the row to select
43517 * @param {Boolean} keepExisting (optional) True to keep existing selections
43519 selectRow : function(index, keepExisting, preventViewNotify){
43520 if(this.locked || (index < 0 || index >= this.grid.ds.getCount())) {
43523 if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
43524 if(!keepExisting || this.singleSelect){
43525 this.clearSelections();
43527 var r = this.grid.ds.getAt(index);
43528 this.selections.add(r);
43529 this.last = this.lastActive = index;
43530 if(!preventViewNotify){
43531 var view = this.grid.view ? this.grid.view : this.grid;
43532 view.onRowSelect(index);
43534 this.fireEvent("rowselect", this, index, r);
43535 this.fireEvent("selectionchange", this);
43541 * @param {Number} row The index of the row to deselect
43543 deselectRow : function(index, preventViewNotify){
43547 if(this.last == index){
43550 if(this.lastActive == index){
43551 this.lastActive = false;
43553 var r = this.grid.ds.getAt(index);
43554 this.selections.remove(r);
43555 if(!preventViewNotify){
43556 var view = this.grid.view ? this.grid.view : this.grid;
43557 view.onRowDeselect(index);
43559 this.fireEvent("rowdeselect", this, index);
43560 this.fireEvent("selectionchange", this);
43564 restoreLast : function(){
43566 this.last = this._last;
43571 acceptsNav : function(row, col, cm){
43572 return !cm.isHidden(col) && cm.isCellEditable(col, row);
43576 onEditorKey : function(field, e){
43577 var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
43582 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
43584 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
43586 }else if(k == e.ENTER && !e.ctrlKey){
43590 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
43592 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
43594 }else if(k == e.ESC){
43598 g.startEditing(newCell[0], newCell[1]);
43603 * Ext JS Library 1.1.1
43604 * Copyright(c) 2006-2007, Ext JS, LLC.
43606 * Originally Released Under LGPL - original licence link has changed is not relivant.
43609 * <script type="text/javascript">
43612 * @class Roo.grid.CellSelectionModel
43613 * @extends Roo.grid.AbstractSelectionModel
43614 * This class provides the basic implementation for cell selection in a grid.
43616 * @param {Object} config The object containing the configuration of this model.
43617 * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
43619 Roo.grid.CellSelectionModel = function(config){
43620 Roo.apply(this, config);
43622 this.selection = null;
43626 * @event beforerowselect
43627 * Fires before a cell is selected.
43628 * @param {SelectionModel} this
43629 * @param {Number} rowIndex The selected row index
43630 * @param {Number} colIndex The selected cell index
43632 "beforecellselect" : true,
43634 * @event cellselect
43635 * Fires when a cell is selected.
43636 * @param {SelectionModel} this
43637 * @param {Number} rowIndex The selected row index
43638 * @param {Number} colIndex The selected cell index
43640 "cellselect" : true,
43642 * @event selectionchange
43643 * Fires when the active selection changes.
43644 * @param {SelectionModel} this
43645 * @param {Object} selection null for no selection or an object (o) with two properties
43647 <li>o.record: the record object for the row the selection is in</li>
43648 <li>o.cell: An array of [rowIndex, columnIndex]</li>
43651 "selectionchange" : true,
43654 * Fires when the tab (or enter) was pressed on the last editable cell
43655 * You can use this to trigger add new row.
43656 * @param {SelectionModel} this
43660 * @event beforeeditnext
43661 * Fires before the next editable sell is made active
43662 * You can use this to skip to another cell or fire the tabend
43663 * if you set cell to false
43664 * @param {Object} eventdata object : { cell : [ row, col ] }
43666 "beforeeditnext" : true
43668 Roo.grid.CellSelectionModel.superclass.constructor.call(this);
43671 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel, {
43673 enter_is_tab: false,
43676 initEvents : function(){
43677 this.grid.on("mousedown", this.handleMouseDown, this);
43678 this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
43679 var view = this.grid.view;
43680 view.on("refresh", this.onViewChange, this);
43681 view.on("rowupdated", this.onRowUpdated, this);
43682 view.on("beforerowremoved", this.clearSelections, this);
43683 view.on("beforerowsinserted", this.clearSelections, this);
43684 if(this.grid.isEditor){
43685 this.grid.on("beforeedit", this.beforeEdit, this);
43690 beforeEdit : function(e){
43691 this.select(e.row, e.column, false, true, e.record);
43695 onRowUpdated : function(v, index, r){
43696 if(this.selection && this.selection.record == r){
43697 v.onCellSelect(index, this.selection.cell[1]);
43702 onViewChange : function(){
43703 this.clearSelections(true);
43707 * Returns the currently selected cell,.
43708 * @return {Array} The selected cell (row, column) or null if none selected.
43710 getSelectedCell : function(){
43711 return this.selection ? this.selection.cell : null;
43715 * Clears all selections.
43716 * @param {Boolean} true to prevent the gridview from being notified about the change.
43718 clearSelections : function(preventNotify){
43719 var s = this.selection;
43721 if(preventNotify !== true){
43722 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
43724 this.selection = null;
43725 this.fireEvent("selectionchange", this, null);
43730 * Returns true if there is a selection.
43731 * @return {Boolean}
43733 hasSelection : function(){
43734 return this.selection ? true : false;
43738 handleMouseDown : function(e, t){
43739 var v = this.grid.getView();
43740 if(this.isLocked()){
43743 var row = v.findRowIndex(t);
43744 var cell = v.findCellIndex(t);
43745 if(row !== false && cell !== false){
43746 this.select(row, cell);
43752 * @param {Number} rowIndex
43753 * @param {Number} collIndex
43755 select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
43756 if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
43757 this.clearSelections();
43758 r = r || this.grid.dataSource.getAt(rowIndex);
43761 cell : [rowIndex, colIndex]
43763 if(!preventViewNotify){
43764 var v = this.grid.getView();
43765 v.onCellSelect(rowIndex, colIndex);
43766 if(preventFocus !== true){
43767 v.focusCell(rowIndex, colIndex);
43770 this.fireEvent("cellselect", this, rowIndex, colIndex);
43771 this.fireEvent("selectionchange", this, this.selection);
43776 isSelectable : function(rowIndex, colIndex, cm){
43777 return !cm.isHidden(colIndex);
43781 handleKeyDown : function(e){
43782 //Roo.log('Cell Sel Model handleKeyDown');
43783 if(!e.isNavKeyPress()){
43786 var g = this.grid, s = this.selection;
43789 var cell = g.walkCells(0, 0, 1, this.isSelectable, this);
43791 this.select(cell[0], cell[1]);
43796 var walk = function(row, col, step){
43797 return g.walkCells(row, col, step, sm.isSelectable, sm);
43799 var k = e.getKey(), r = s.cell[0], c = s.cell[1];
43806 // handled by onEditorKey
43807 if (g.isEditor && g.editing) {
43811 newCell = walk(r, c-1, -1);
43813 newCell = walk(r, c+1, 1);
43818 newCell = walk(r+1, c, 1);
43822 newCell = walk(r-1, c, -1);
43826 newCell = walk(r, c+1, 1);
43830 newCell = walk(r, c-1, -1);
43835 if(g.isEditor && !g.editing){
43836 g.startEditing(r, c);
43845 this.select(newCell[0], newCell[1]);
43851 acceptsNav : function(row, col, cm){
43852 return !cm.isHidden(col) && cm.isCellEditable(col, row);
43856 * @param {Number} field (not used) - as it's normally used as a listener
43857 * @param {Number} e - event - fake it by using
43859 * var e = Roo.EventObjectImpl.prototype;
43860 * e.keyCode = e.TAB
43864 onEditorKey : function(field, e){
43866 var k = e.getKey(),
43869 ed = g.activeEditor,
43871 ///Roo.log('onEditorKey' + k);
43874 if (this.enter_is_tab && k == e.ENTER) {
43880 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
43882 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
43888 } else if(k == e.ENTER && !e.ctrlKey){
43891 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
43893 } else if(k == e.ESC){
43898 var ecall = { cell : newCell, forward : forward };
43899 this.fireEvent('beforeeditnext', ecall );
43900 newCell = ecall.cell;
43901 forward = ecall.forward;
43905 //Roo.log('next cell after edit');
43906 g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
43907 } else if (forward) {
43908 // tabbed past last
43909 this.fireEvent.defer(100, this, ['tabend',this]);
43914 * Ext JS Library 1.1.1
43915 * Copyright(c) 2006-2007, Ext JS, LLC.
43917 * Originally Released Under LGPL - original licence link has changed is not relivant.
43920 * <script type="text/javascript">
43924 * @class Roo.grid.EditorGrid
43925 * @extends Roo.grid.Grid
43926 * Class for creating and editable grid.
43927 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
43928 * The container MUST have some type of size defined for the grid to fill. The container will be
43929 * automatically set to position relative if it isn't already.
43930 * @param {Object} dataSource The data model to bind to
43931 * @param {Object} colModel The column model with info about this grid's columns
43933 Roo.grid.EditorGrid = function(container, config){
43934 Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
43935 this.getGridEl().addClass("xedit-grid");
43937 if(!this.selModel){
43938 this.selModel = new Roo.grid.CellSelectionModel();
43941 this.activeEditor = null;
43945 * @event beforeedit
43946 * Fires before cell editing is triggered. The edit event object has the following properties <br />
43947 * <ul style="padding:5px;padding-left:16px;">
43948 * <li>grid - This grid</li>
43949 * <li>record - The record being edited</li>
43950 * <li>field - The field name being edited</li>
43951 * <li>value - The value for the field being edited.</li>
43952 * <li>row - The grid row index</li>
43953 * <li>column - The grid column index</li>
43954 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
43956 * @param {Object} e An edit event (see above for description)
43958 "beforeedit" : true,
43961 * Fires after a cell is edited. <br />
43962 * <ul style="padding:5px;padding-left:16px;">
43963 * <li>grid - This grid</li>
43964 * <li>record - The record being edited</li>
43965 * <li>field - The field name being edited</li>
43966 * <li>value - The value being set</li>
43967 * <li>originalValue - The original value for the field, before the edit.</li>
43968 * <li>row - The grid row index</li>
43969 * <li>column - The grid column index</li>
43971 * @param {Object} e An edit event (see above for description)
43973 "afteredit" : true,
43975 * @event validateedit
43976 * Fires after a cell is edited, but before the value is set in the record.
43977 * You can use this to modify the value being set in the field, Return false
43978 * to cancel the change. The edit event object has the following properties <br />
43979 * <ul style="padding:5px;padding-left:16px;">
43980 * <li>editor - This editor</li>
43981 * <li>grid - This grid</li>
43982 * <li>record - The record being edited</li>
43983 * <li>field - The field name being edited</li>
43984 * <li>value - The value being set</li>
43985 * <li>originalValue - The original value for the field, before the edit.</li>
43986 * <li>row - The grid row index</li>
43987 * <li>column - The grid column index</li>
43988 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
43990 * @param {Object} e An edit event (see above for description)
43992 "validateedit" : true
43994 this.on("bodyscroll", this.stopEditing, this);
43995 this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick, this);
43998 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
44000 * @cfg {Number} clicksToEdit
44001 * The number of clicks on a cell required to display the cell's editor (defaults to 2)
44008 trackMouseOver: false, // causes very odd FF errors
44010 onCellDblClick : function(g, row, col){
44011 this.startEditing(row, col);
44014 onEditComplete : function(ed, value, startValue){
44015 this.editing = false;
44016 this.activeEditor = null;
44017 ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
44019 var field = this.colModel.getDataIndex(ed.col);
44024 originalValue: startValue,
44031 var cell = Roo.get(this.view.getCell(ed.row,ed.col));
44034 if(String(value) !== String(startValue)){
44036 if(this.fireEvent("validateedit", e) !== false && !e.cancel){
44037 r.set(field, e.value);
44038 // if we are dealing with a combo box..
44039 // then we also set the 'name' colum to be the displayField
44040 if (ed.field.displayField && ed.field.name) {
44041 r.set(ed.field.name, ed.field.el.dom.value);
44044 delete e.cancel; //?? why!!!
44045 this.fireEvent("afteredit", e);
44048 this.fireEvent("afteredit", e); // always fire it!
44050 this.view.focusCell(ed.row, ed.col);
44054 * Starts editing the specified for the specified row/column
44055 * @param {Number} rowIndex
44056 * @param {Number} colIndex
44058 startEditing : function(row, col){
44059 this.stopEditing();
44060 if(this.colModel.isCellEditable(col, row)){
44061 this.view.ensureVisible(row, col, true);
44063 var r = this.dataSource.getAt(row);
44064 var field = this.colModel.getDataIndex(col);
44065 var cell = Roo.get(this.view.getCell(row,col));
44070 value: r.data[field],
44075 if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
44076 this.editing = true;
44077 var ed = this.colModel.getCellEditor(col, row);
44083 ed.render(ed.parentEl || document.body);
44089 (function(){ // complex but required for focus issues in safari, ie and opera
44093 ed.on("complete", this.onEditComplete, this, {single: true});
44094 ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
44095 this.activeEditor = ed;
44096 var v = r.data[field];
44097 ed.startEdit(this.view.getCell(row, col), v);
44098 // combo's with 'displayField and name set
44099 if (ed.field.displayField && ed.field.name) {
44100 ed.field.el.dom.value = r.data[ed.field.name];
44104 }).defer(50, this);
44110 * Stops any active editing
44112 stopEditing : function(){
44113 if(this.activeEditor){
44114 this.activeEditor.completeEdit();
44116 this.activeEditor = null;
44120 * Called to get grid's drag proxy text, by default returns this.ddText.
44123 getDragDropText : function(){
44124 var count = this.selModel.getSelectedCell() ? 1 : 0;
44125 return String.format(this.ddText, count, count == 1 ? '' : 's');
44130 * Ext JS Library 1.1.1
44131 * Copyright(c) 2006-2007, Ext JS, LLC.
44133 * Originally Released Under LGPL - original licence link has changed is not relivant.
44136 * <script type="text/javascript">
44139 // private - not really -- you end up using it !
44140 // This is a support class used internally by the Grid components
44143 * @class Roo.grid.GridEditor
44144 * @extends Roo.Editor
44145 * Class for creating and editable grid elements.
44146 * @param {Object} config any settings (must include field)
44148 Roo.grid.GridEditor = function(field, config){
44149 if (!config && field.field) {
44151 field = Roo.factory(config.field, Roo.form);
44153 Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
44154 field.monitorTab = false;
44157 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
44160 * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
44163 alignment: "tl-tl",
44166 cls: "x-small-editor x-grid-editor",
44171 * Ext JS Library 1.1.1
44172 * Copyright(c) 2006-2007, Ext JS, LLC.
44174 * Originally Released Under LGPL - original licence link has changed is not relivant.
44177 * <script type="text/javascript">
44182 Roo.grid.PropertyRecord = Roo.data.Record.create([
44183 {name:'name',type:'string'}, 'value'
44187 Roo.grid.PropertyStore = function(grid, source){
44189 this.store = new Roo.data.Store({
44190 recordType : Roo.grid.PropertyRecord
44192 this.store.on('update', this.onUpdate, this);
44194 this.setSource(source);
44196 Roo.grid.PropertyStore.superclass.constructor.call(this);
44201 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
44202 setSource : function(o){
44204 this.store.removeAll();
44207 if(this.isEditableValue(o[k])){
44208 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
44211 this.store.loadRecords({records: data}, {}, true);
44214 onUpdate : function(ds, record, type){
44215 if(type == Roo.data.Record.EDIT){
44216 var v = record.data['value'];
44217 var oldValue = record.modified['value'];
44218 if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
44219 this.source[record.id] = v;
44221 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
44228 getProperty : function(row){
44229 return this.store.getAt(row);
44232 isEditableValue: function(val){
44233 if(val && val instanceof Date){
44235 }else if(typeof val == 'object' || typeof val == 'function'){
44241 setValue : function(prop, value){
44242 this.source[prop] = value;
44243 this.store.getById(prop).set('value', value);
44246 getSource : function(){
44247 return this.source;
44251 Roo.grid.PropertyColumnModel = function(grid, store){
44254 g.PropertyColumnModel.superclass.constructor.call(this, [
44255 {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
44256 {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
44258 this.store = store;
44259 this.bselect = Roo.DomHelper.append(document.body, {
44260 tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
44261 {tag: 'option', value: 'true', html: 'true'},
44262 {tag: 'option', value: 'false', html: 'false'}
44265 Roo.id(this.bselect);
44268 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
44269 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
44270 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
44271 'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
44272 'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
44274 this.renderCellDelegate = this.renderCell.createDelegate(this);
44275 this.renderPropDelegate = this.renderProp.createDelegate(this);
44278 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
44282 valueText : 'Value',
44284 dateFormat : 'm/j/Y',
44287 renderDate : function(dateVal){
44288 return dateVal.dateFormat(this.dateFormat);
44291 renderBool : function(bVal){
44292 return bVal ? 'true' : 'false';
44295 isCellEditable : function(colIndex, rowIndex){
44296 return colIndex == 1;
44299 getRenderer : function(col){
44301 this.renderCellDelegate : this.renderPropDelegate;
44304 renderProp : function(v){
44305 return this.getPropertyName(v);
44308 renderCell : function(val){
44310 if(val instanceof Date){
44311 rv = this.renderDate(val);
44312 }else if(typeof val == 'boolean'){
44313 rv = this.renderBool(val);
44315 return Roo.util.Format.htmlEncode(rv);
44318 getPropertyName : function(name){
44319 var pn = this.grid.propertyNames;
44320 return pn && pn[name] ? pn[name] : name;
44323 getCellEditor : function(colIndex, rowIndex){
44324 var p = this.store.getProperty(rowIndex);
44325 var n = p.data['name'], val = p.data['value'];
44327 if(typeof(this.grid.customEditors[n]) == 'string'){
44328 return this.editors[this.grid.customEditors[n]];
44330 if(typeof(this.grid.customEditors[n]) != 'undefined'){
44331 return this.grid.customEditors[n];
44333 if(val instanceof Date){
44334 return this.editors['date'];
44335 }else if(typeof val == 'number'){
44336 return this.editors['number'];
44337 }else if(typeof val == 'boolean'){
44338 return this.editors['boolean'];
44340 return this.editors['string'];
44346 * @class Roo.grid.PropertyGrid
44347 * @extends Roo.grid.EditorGrid
44348 * This class represents the interface of a component based property grid control.
44349 * <br><br>Usage:<pre><code>
44350 var grid = new Roo.grid.PropertyGrid("my-container-id", {
44358 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
44359 * The container MUST have some type of size defined for the grid to fill. The container will be
44360 * automatically set to position relative if it isn't already.
44361 * @param {Object} config A config object that sets properties on this grid.
44363 Roo.grid.PropertyGrid = function(container, config){
44364 config = config || {};
44365 var store = new Roo.grid.PropertyStore(this);
44366 this.store = store;
44367 var cm = new Roo.grid.PropertyColumnModel(this, store);
44368 store.store.sort('name', 'ASC');
44369 Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
44372 enableColLock:false,
44373 enableColumnMove:false,
44375 trackMouseOver: false,
44378 this.getGridEl().addClass('x-props-grid');
44379 this.lastEditRow = null;
44380 this.on('columnresize', this.onColumnResize, this);
44383 * @event beforepropertychange
44384 * Fires before a property changes (return false to stop?)
44385 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
44386 * @param {String} id Record Id
44387 * @param {String} newval New Value
44388 * @param {String} oldval Old Value
44390 "beforepropertychange": true,
44392 * @event propertychange
44393 * Fires after a property changes
44394 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
44395 * @param {String} id Record Id
44396 * @param {String} newval New Value
44397 * @param {String} oldval Old Value
44399 "propertychange": true
44401 this.customEditors = this.customEditors || {};
44403 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
44406 * @cfg {Object} customEditors map of colnames=> custom editors.
44407 * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
44408 * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
44409 * false disables editing of the field.
44413 * @cfg {Object} propertyNames map of property Names to their displayed value
44416 render : function(){
44417 Roo.grid.PropertyGrid.superclass.render.call(this);
44418 this.autoSize.defer(100, this);
44421 autoSize : function(){
44422 Roo.grid.PropertyGrid.superclass.autoSize.call(this);
44424 this.view.fitColumns();
44428 onColumnResize : function(){
44429 this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
44433 * Sets the data for the Grid
44434 * accepts a Key => Value object of all the elements avaiable.
44435 * @param {Object} data to appear in grid.
44437 setSource : function(source){
44438 this.store.setSource(source);
44442 * Gets all the data from the grid.
44443 * @return {Object} data data stored in grid
44445 getSource : function(){
44446 return this.store.getSource();
44455 * @class Roo.grid.Calendar
44456 * @extends Roo.grid.Grid
44457 * This class extends the Grid to provide a calendar widget
44458 * <br><br>Usage:<pre><code>
44459 var grid = new Roo.grid.Calendar("my-container-id", {
44462 selModel: mySelectionModel,
44463 autoSizeColumns: true,
44464 monitorWindowResize: false,
44465 trackMouseOver: true
44466 eventstore : real data store..
44472 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
44473 * The container MUST have some type of size defined for the grid to fill. The container will be
44474 * automatically set to position relative if it isn't already.
44475 * @param {Object} config A config object that sets properties on this grid.
44477 Roo.grid.Calendar = function(container, config){
44478 // initialize the container
44479 this.container = Roo.get(container);
44480 this.container.update("");
44481 this.container.setStyle("overflow", "hidden");
44482 this.container.addClass('x-grid-container');
44484 this.id = this.container.id;
44486 Roo.apply(this, config);
44487 // check and correct shorthanded configs
44491 for (var r = 0;r < 6;r++) {
44494 for (var c =0;c < 7;c++) {
44498 if (this.eventStore) {
44499 this.eventStore= Roo.factory(this.eventStore, Roo.data);
44500 this.eventStore.on('load',this.onLoad, this);
44501 this.eventStore.on('beforeload',this.clearEvents, this);
44505 this.dataSource = new Roo.data.Store({
44506 proxy: new Roo.data.MemoryProxy(rows),
44507 reader: new Roo.data.ArrayReader({}, [
44508 'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
44511 this.dataSource.load();
44512 this.ds = this.dataSource;
44513 this.ds.xmodule = this.xmodule || false;
44516 var cellRender = function(v,x,r)
44518 return String.format(
44519 '<div class="fc-day fc-widget-content"><div>' +
44520 '<div class="fc-event-container"></div>' +
44521 '<div class="fc-day-number">{0}</div>'+
44523 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
44524 '</div></div>', v);
44529 this.colModel = new Roo.grid.ColumnModel( [
44531 xtype: 'ColumnModel',
44533 dataIndex : 'weekday0',
44535 renderer : cellRender
44538 xtype: 'ColumnModel',
44540 dataIndex : 'weekday1',
44542 renderer : cellRender
44545 xtype: 'ColumnModel',
44547 dataIndex : 'weekday2',
44548 header : 'Tuesday',
44549 renderer : cellRender
44552 xtype: 'ColumnModel',
44554 dataIndex : 'weekday3',
44555 header : 'Wednesday',
44556 renderer : cellRender
44559 xtype: 'ColumnModel',
44561 dataIndex : 'weekday4',
44562 header : 'Thursday',
44563 renderer : cellRender
44566 xtype: 'ColumnModel',
44568 dataIndex : 'weekday5',
44570 renderer : cellRender
44573 xtype: 'ColumnModel',
44575 dataIndex : 'weekday6',
44576 header : 'Saturday',
44577 renderer : cellRender
44580 this.cm = this.colModel;
44581 this.cm.xmodule = this.xmodule || false;
44585 //this.selModel = new Roo.grid.CellSelectionModel();
44586 //this.sm = this.selModel;
44587 //this.selModel.init(this);
44591 this.container.setWidth(this.width);
44595 this.container.setHeight(this.height);
44602 * The raw click event for the entire grid.
44603 * @param {Roo.EventObject} e
44608 * The raw dblclick event for the entire grid.
44609 * @param {Roo.EventObject} e
44613 * @event contextmenu
44614 * The raw contextmenu event for the entire grid.
44615 * @param {Roo.EventObject} e
44617 "contextmenu" : true,
44620 * The raw mousedown event for the entire grid.
44621 * @param {Roo.EventObject} e
44623 "mousedown" : true,
44626 * The raw mouseup event for the entire grid.
44627 * @param {Roo.EventObject} e
44632 * The raw mouseover event for the entire grid.
44633 * @param {Roo.EventObject} e
44635 "mouseover" : true,
44638 * The raw mouseout event for the entire grid.
44639 * @param {Roo.EventObject} e
44644 * The raw keypress event for the entire grid.
44645 * @param {Roo.EventObject} e
44650 * The raw keydown event for the entire grid.
44651 * @param {Roo.EventObject} e
44659 * Fires when a cell is clicked
44660 * @param {Grid} this
44661 * @param {Number} rowIndex
44662 * @param {Number} columnIndex
44663 * @param {Roo.EventObject} e
44665 "cellclick" : true,
44667 * @event celldblclick
44668 * Fires when a cell is double clicked
44669 * @param {Grid} this
44670 * @param {Number} rowIndex
44671 * @param {Number} columnIndex
44672 * @param {Roo.EventObject} e
44674 "celldblclick" : true,
44677 * Fires when a row is clicked
44678 * @param {Grid} this
44679 * @param {Number} rowIndex
44680 * @param {Roo.EventObject} e
44684 * @event rowdblclick
44685 * Fires when a row is double clicked
44686 * @param {Grid} this
44687 * @param {Number} rowIndex
44688 * @param {Roo.EventObject} e
44690 "rowdblclick" : true,
44692 * @event headerclick
44693 * Fires when a header is clicked
44694 * @param {Grid} this
44695 * @param {Number} columnIndex
44696 * @param {Roo.EventObject} e
44698 "headerclick" : true,
44700 * @event headerdblclick
44701 * Fires when a header cell is double clicked
44702 * @param {Grid} this
44703 * @param {Number} columnIndex
44704 * @param {Roo.EventObject} e
44706 "headerdblclick" : true,
44708 * @event rowcontextmenu
44709 * Fires when a row is right clicked
44710 * @param {Grid} this
44711 * @param {Number} rowIndex
44712 * @param {Roo.EventObject} e
44714 "rowcontextmenu" : true,
44716 * @event cellcontextmenu
44717 * Fires when a cell is right clicked
44718 * @param {Grid} this
44719 * @param {Number} rowIndex
44720 * @param {Number} cellIndex
44721 * @param {Roo.EventObject} e
44723 "cellcontextmenu" : true,
44725 * @event headercontextmenu
44726 * Fires when a header is right clicked
44727 * @param {Grid} this
44728 * @param {Number} columnIndex
44729 * @param {Roo.EventObject} e
44731 "headercontextmenu" : true,
44733 * @event bodyscroll
44734 * Fires when the body element is scrolled
44735 * @param {Number} scrollLeft
44736 * @param {Number} scrollTop
44738 "bodyscroll" : true,
44740 * @event columnresize
44741 * Fires when the user resizes a column
44742 * @param {Number} columnIndex
44743 * @param {Number} newSize
44745 "columnresize" : true,
44747 * @event columnmove
44748 * Fires when the user moves a column
44749 * @param {Number} oldIndex
44750 * @param {Number} newIndex
44752 "columnmove" : true,
44755 * Fires when row(s) start being dragged
44756 * @param {Grid} this
44757 * @param {Roo.GridDD} dd The drag drop object
44758 * @param {event} e The raw browser event
44760 "startdrag" : true,
44763 * Fires when a drag operation is complete
44764 * @param {Grid} this
44765 * @param {Roo.GridDD} dd The drag drop object
44766 * @param {event} e The raw browser event
44771 * Fires when dragged row(s) are dropped on a valid DD target
44772 * @param {Grid} this
44773 * @param {Roo.GridDD} dd The drag drop object
44774 * @param {String} targetId The target drag drop object
44775 * @param {event} e The raw browser event
44780 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
44781 * @param {Grid} this
44782 * @param {Roo.GridDD} dd The drag drop object
44783 * @param {String} targetId The target drag drop object
44784 * @param {event} e The raw browser event
44789 * Fires when the dragged row(s) first cross another DD target while being dragged
44790 * @param {Grid} this
44791 * @param {Roo.GridDD} dd The drag drop object
44792 * @param {String} targetId The target drag drop object
44793 * @param {event} e The raw browser event
44795 "dragenter" : true,
44798 * Fires when the dragged row(s) leave another DD target while being dragged
44799 * @param {Grid} this
44800 * @param {Roo.GridDD} dd The drag drop object
44801 * @param {String} targetId The target drag drop object
44802 * @param {event} e The raw browser event
44807 * Fires when a row is rendered, so you can change add a style to it.
44808 * @param {GridView} gridview The grid view
44809 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
44815 * Fires when the grid is rendered
44816 * @param {Grid} grid
44821 * Fires when a date is selected
44822 * @param {DatePicker} this
44823 * @param {Date} date The selected date
44827 * @event monthchange
44828 * Fires when the displayed month changes
44829 * @param {DatePicker} this
44830 * @param {Date} date The selected month
44832 'monthchange': true,
44834 * @event evententer
44835 * Fires when mouse over an event
44836 * @param {Calendar} this
44837 * @param {event} Event
44839 'evententer': true,
44841 * @event eventleave
44842 * Fires when the mouse leaves an
44843 * @param {Calendar} this
44846 'eventleave': true,
44848 * @event eventclick
44849 * Fires when the mouse click an
44850 * @param {Calendar} this
44853 'eventclick': true,
44855 * @event eventrender
44856 * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
44857 * @param {Calendar} this
44858 * @param {data} data to be modified
44860 'eventrender': true
44864 Roo.grid.Grid.superclass.constructor.call(this);
44865 this.on('render', function() {
44866 this.view.el.addClass('x-grid-cal');
44868 (function() { this.setDate(new Date()); }).defer(100,this); //default today..
44872 if (!Roo.grid.Calendar.style) {
44873 Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
44876 '.x-grid-cal .x-grid-col' : {
44877 height: 'auto !important',
44878 'vertical-align': 'top'
44880 '.x-grid-cal .fc-event-hori' : {
44891 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
44893 * @cfg {Store} eventStore The store that loads events.
44898 activeDate : false,
44901 monitorWindowResize : false,
44904 resizeColumns : function() {
44905 var col = (this.view.el.getWidth() / 7) - 3;
44906 // loop through cols, and setWidth
44907 for(var i =0 ; i < 7 ; i++){
44908 this.cm.setColumnWidth(i, col);
44911 setDate :function(date) {
44913 Roo.log('setDate?');
44915 this.resizeColumns();
44916 var vd = this.activeDate;
44917 this.activeDate = date;
44918 // if(vd && this.el){
44919 // var t = date.getTime();
44920 // if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
44921 // Roo.log('using add remove');
44923 // this.fireEvent('monthchange', this, date);
44925 // this.cells.removeClass("fc-state-highlight");
44926 // this.cells.each(function(c){
44927 // if(c.dateValue == t){
44928 // c.addClass("fc-state-highlight");
44929 // setTimeout(function(){
44930 // try{c.dom.firstChild.focus();}catch(e){}
44940 var days = date.getDaysInMonth();
44942 var firstOfMonth = date.getFirstDateOfMonth();
44943 var startingPos = firstOfMonth.getDay()-this.startDay;
44945 if(startingPos < this.startDay){
44949 var pm = date.add(Date.MONTH, -1);
44950 var prevStart = pm.getDaysInMonth()-startingPos;
44954 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
44956 this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
44957 //this.cells.addClassOnOver('fc-state-hover');
44959 var cells = this.cells.elements;
44960 var textEls = this.textNodes;
44962 //Roo.each(cells, function(cell){
44963 // cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
44966 days += startingPos;
44968 // convert everything to numbers so it's fast
44969 var day = 86400000;
44970 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
44973 //Roo.log(prevStart);
44975 var today = new Date().clearTime().getTime();
44976 var sel = date.clearTime().getTime();
44977 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
44978 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
44979 var ddMatch = this.disabledDatesRE;
44980 var ddText = this.disabledDatesText;
44981 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
44982 var ddaysText = this.disabledDaysText;
44983 var format = this.format;
44985 var setCellClass = function(cal, cell){
44987 //Roo.log('set Cell Class');
44989 var t = d.getTime();
44994 cell.dateValue = t;
44996 cell.className += " fc-today";
44997 cell.className += " fc-state-highlight";
44998 cell.title = cal.todayText;
45001 // disable highlight in other month..
45002 cell.className += " fc-state-highlight";
45007 //cell.className = " fc-state-disabled";
45008 cell.title = cal.minText;
45012 //cell.className = " fc-state-disabled";
45013 cell.title = cal.maxText;
45017 if(ddays.indexOf(d.getDay()) != -1){
45018 // cell.title = ddaysText;
45019 // cell.className = " fc-state-disabled";
45022 if(ddMatch && format){
45023 var fvalue = d.dateFormat(format);
45024 if(ddMatch.test(fvalue)){
45025 cell.title = ddText.replace("%0", fvalue);
45026 cell.className = " fc-state-disabled";
45030 if (!cell.initialClassName) {
45031 cell.initialClassName = cell.dom.className;
45034 cell.dom.className = cell.initialClassName + ' ' + cell.className;
45039 for(; i < startingPos; i++) {
45040 cells[i].dayName = (++prevStart);
45041 Roo.log(textEls[i]);
45042 d.setDate(d.getDate()+1);
45044 //cells[i].className = "fc-past fc-other-month";
45045 setCellClass(this, cells[i]);
45050 for(; i < days; i++){
45051 intDay = i - startingPos + 1;
45052 cells[i].dayName = (intDay);
45053 d.setDate(d.getDate()+1);
45055 cells[i].className = ''; // "x-date-active";
45056 setCellClass(this, cells[i]);
45060 for(; i < 42; i++) {
45061 //textEls[i].innerHTML = (++extraDays);
45063 d.setDate(d.getDate()+1);
45064 cells[i].dayName = (++extraDays);
45065 cells[i].className = "fc-future fc-other-month";
45066 setCellClass(this, cells[i]);
45069 //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
45071 var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
45073 // this will cause all the cells to mis
45076 for (var r = 0;r < 6;r++) {
45077 for (var c =0;c < 7;c++) {
45078 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
45082 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
45083 for(i=0;i<cells.length;i++) {
45085 this.cells.elements[i].dayName = cells[i].dayName ;
45086 this.cells.elements[i].className = cells[i].className;
45087 this.cells.elements[i].initialClassName = cells[i].initialClassName ;
45088 this.cells.elements[i].title = cells[i].title ;
45089 this.cells.elements[i].dateValue = cells[i].dateValue ;
45095 //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
45096 //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
45098 ////if(totalRows != 6){
45099 //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
45100 // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
45103 this.fireEvent('monthchange', this, date);
45108 * Returns the grid's SelectionModel.
45109 * @return {SelectionModel}
45111 getSelectionModel : function(){
45112 if(!this.selModel){
45113 this.selModel = new Roo.grid.CellSelectionModel();
45115 return this.selModel;
45119 this.eventStore.load()
45125 findCell : function(dt) {
45126 dt = dt.clearTime().getTime();
45128 this.cells.each(function(c){
45129 //Roo.log("check " +c.dateValue + '?=' + dt);
45130 if(c.dateValue == dt){
45140 findCells : function(rec) {
45141 var s = rec.data.start_dt.clone().clearTime().getTime();
45143 var e= rec.data.end_dt.clone().clearTime().getTime();
45146 this.cells.each(function(c){
45147 ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
45149 if(c.dateValue > e){
45152 if(c.dateValue < s){
45161 findBestRow: function(cells)
45165 for (var i =0 ; i < cells.length;i++) {
45166 ret = Math.max(cells[i].rows || 0,ret);
45173 addItem : function(rec)
45175 // look for vertical location slot in
45176 var cells = this.findCells(rec);
45178 rec.row = this.findBestRow(cells);
45180 // work out the location.
45184 for(var i =0; i < cells.length; i++) {
45192 if (crow.start.getY() == cells[i].getY()) {
45194 crow.end = cells[i];
45210 for (var i = 0; i < cells.length;i++) {
45211 cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
45218 clearEvents: function() {
45220 if (!this.eventStore.getCount()) {
45223 // reset number of rows in cells.
45224 Roo.each(this.cells.elements, function(c){
45228 this.eventStore.each(function(e) {
45229 this.clearEvent(e);
45234 clearEvent : function(ev)
45237 Roo.each(ev.els, function(el) {
45238 el.un('mouseenter' ,this.onEventEnter, this);
45239 el.un('mouseleave' ,this.onEventLeave, this);
45247 renderEvent : function(ev,ctr) {
45249 ctr = this.view.el.select('.fc-event-container',true).first();
45253 this.clearEvent(ev);
45259 var cells = ev.cells;
45260 var rows = ev.rows;
45261 this.fireEvent('eventrender', this, ev);
45263 for(var i =0; i < rows.length; i++) {
45267 cls += ' fc-event-start';
45269 if ((i+1) == rows.length) {
45270 cls += ' fc-event-end';
45273 //Roo.log(ev.data);
45274 // how many rows should it span..
45275 var cg = this.eventTmpl.append(ctr,Roo.apply({
45278 }, ev.data) , true);
45281 cg.on('mouseenter' ,this.onEventEnter, this, ev);
45282 cg.on('mouseleave' ,this.onEventLeave, this, ev);
45283 cg.on('click', this.onEventClick, this, ev);
45287 var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
45288 var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
45291 cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);
45292 cg.setWidth(ebox.right - sbox.x -2);
45296 renderEvents: function()
45298 // first make sure there is enough space..
45300 if (!this.eventTmpl) {
45301 this.eventTmpl = new Roo.Template(
45302 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}" style="position: absolute" unselectable="on">' +
45303 '<div class="fc-event-inner">' +
45304 '<span class="fc-event-time">{time}</span>' +
45305 '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
45307 '<div class="ui-resizable-heandle ui-resizable-e"> </div>' +
45315 this.cells.each(function(c) {
45316 //Roo.log(c.select('.fc-day-content div',true).first());
45317 c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
45320 var ctr = this.view.el.select('.fc-event-container',true).first();
45323 this.eventStore.each(function(ev){
45325 this.renderEvent(ev);
45329 this.view.layout();
45333 onEventEnter: function (e, el,event,d) {
45334 this.fireEvent('evententer', this, el, event);
45337 onEventLeave: function (e, el,event,d) {
45338 this.fireEvent('eventleave', this, el, event);
45341 onEventClick: function (e, el,event,d) {
45342 this.fireEvent('eventclick', this, el, event);
45345 onMonthChange: function () {
45349 onLoad: function () {
45351 //Roo.log('calendar onload');
45353 if(this.eventStore.getCount() > 0){
45357 this.eventStore.each(function(d){
45362 if (typeof(add.end_dt) == 'undefined') {
45363 Roo.log("Missing End time in calendar data: ");
45367 if (typeof(add.start_dt) == 'undefined') {
45368 Roo.log("Missing Start time in calendar data: ");
45372 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
45373 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
45374 add.id = add.id || d.id;
45375 add.title = add.title || '??';
45383 this.renderEvents();
45393 render : function ()
45397 if (!this.view.el.hasClass('course-timesheet')) {
45398 this.view.el.addClass('course-timesheet');
45400 if (this.tsStyle) {
45405 Roo.log(_this.grid.view.el.getWidth());
45408 this.tsStyle = Roo.util.CSS.createStyleSheet({
45409 '.course-timesheet .x-grid-row' : {
45412 '.x-grid-row td' : {
45413 'vertical-align' : 0
45415 '.course-edit-link' : {
45417 'text-overflow' : 'ellipsis',
45418 'overflow' : 'hidden',
45419 'white-space' : 'nowrap',
45420 'cursor' : 'pointer'
45425 '.de-act-sup-link' : {
45426 'color' : 'purple',
45427 'text-decoration' : 'line-through'
45431 'text-decoration' : 'line-through'
45433 '.course-timesheet .course-highlight' : {
45434 'border-top-style': 'dashed !important',
45435 'border-bottom-bottom': 'dashed !important'
45437 '.course-timesheet .course-item' : {
45438 'font-family' : 'tahoma, arial, helvetica',
45439 'font-size' : '11px',
45440 'overflow' : 'hidden',
45441 'padding-left' : '10px',
45442 'padding-right' : '10px',
45443 'padding-top' : '10px'
45451 monitorWindowResize : false,
45452 cellrenderer : function(v,x,r)
45457 xtype: 'CellSelectionModel',
45464 beforeload : function (_self, options)
45466 options.params = options.params || {};
45467 options.params._month = _this.monthField.getValue();
45468 options.params.limit = 9999;
45469 options.params['sort'] = 'when_dt';
45470 options.params['dir'] = 'ASC';
45471 this.proxy.loadResponse = this.loadResponse;
45473 //this.addColumns();
45475 load : function (_self, records, options)
45477 _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
45478 // if you click on the translation.. you can edit it...
45479 var el = Roo.get(this);
45480 var id = el.dom.getAttribute('data-id');
45481 var d = el.dom.getAttribute('data-date');
45482 var t = el.dom.getAttribute('data-time');
45483 //var id = this.child('span').dom.textContent;
45486 Pman.Dialog.CourseCalendar.show({
45490 productitem_active : id ? 1 : 0
45492 _this.grid.ds.load({});
45497 _this.panel.fireEvent('resize', [ '', '' ]);
45500 loadResponse : function(o, success, response){
45501 // this is overridden on before load..
45503 Roo.log("our code?");
45504 //Roo.log(success);
45505 //Roo.log(response)
45506 delete this.activeRequest;
45508 this.fireEvent("loadexception", this, o, response);
45509 o.request.callback.call(o.request.scope, null, o.request.arg, false);
45514 result = o.reader.read(response);
45516 Roo.log("load exception?");
45517 this.fireEvent("loadexception", this, o, response, e);
45518 o.request.callback.call(o.request.scope, null, o.request.arg, false);
45521 Roo.log("ready...");
45522 // loop through result.records;
45523 // and set this.tdate[date] = [] << array of records..
45525 Roo.each(result.records, function(r){
45527 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
45528 _this.tdata[r.data.when_dt.format('j')] = [];
45530 _this.tdata[r.data.when_dt.format('j')].push(r.data);
45533 //Roo.log(_this.tdata);
45535 result.records = [];
45536 result.totalRecords = 6;
45538 // let's generate some duumy records for the rows.
45539 //var st = _this.dateField.getValue();
45541 // work out monday..
45542 //st = st.add(Date.DAY, -1 * st.format('w'));
45544 var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
45546 var firstOfMonth = date.getFirstDayOfMonth();
45547 var days = date.getDaysInMonth();
45549 var firstAdded = false;
45550 for (var i = 0; i < result.totalRecords ; i++) {
45551 //var d= st.add(Date.DAY, i);
45554 for(var w = 0 ; w < 7 ; w++){
45555 if(!firstAdded && firstOfMonth != w){
45562 var dd = (d > 0 && d < 10) ? "0"+d : d;
45563 row['weekday'+w] = String.format(
45564 '<span style="font-size: 16px;"><b>{0}</b></span>'+
45565 '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
45567 date.format('Y-m-')+dd
45570 if(typeof(_this.tdata[d]) != 'undefined'){
45571 Roo.each(_this.tdata[d], function(r){
45575 var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
45576 if(r.parent_id*1>0){
45577 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
45580 if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
45581 deactive = 'de-act-link';
45584 row['weekday'+w] += String.format(
45585 '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
45587 r.product_id_name, //1
45588 r.when_dt.format('h:ia'), //2
45598 // only do this if something added..
45600 result.records.push(_this.grid.dataSource.reader.newRow(row));
45604 // push it twice. (second one with an hour..
45608 this.fireEvent("load", this, o, o.request.arg);
45609 o.request.callback.call(o.request.scope, result, o.request.arg, true);
45611 sortInfo : {field: 'when_dt', direction : 'ASC' },
45613 xtype: 'HttpProxy',
45616 url : baseURL + '/Roo/Shop_course.php'
45619 xtype: 'JsonReader',
45636 'name': 'parent_id',
45640 'name': 'product_id',
45644 'name': 'productitem_id',
45662 click : function (_self, e)
45664 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
45665 sd.setMonth(sd.getMonth()-1);
45666 _this.monthField.setValue(sd.format('Y-m-d'));
45667 _this.grid.ds.load({});
45673 xtype: 'Separator',
45677 xtype: 'MonthField',
45680 render : function (_self)
45682 _this.monthField = _self;
45683 // _this.monthField.set today
45685 select : function (combo, date)
45687 _this.grid.ds.load({});
45690 value : (function() { return new Date(); })()
45693 xtype: 'Separator',
45699 text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
45709 click : function (_self, e)
45711 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
45712 sd.setMonth(sd.getMonth()+1);
45713 _this.monthField.setValue(sd.format('Y-m-d'));
45714 _this.grid.ds.load({});
45727 * Ext JS Library 1.1.1
45728 * Copyright(c) 2006-2007, Ext JS, LLC.
45730 * Originally Released Under LGPL - original licence link has changed is not relivant.
45733 * <script type="text/javascript">
45737 * @class Roo.LoadMask
45738 * A simple utility class for generically masking elements while loading data. If the element being masked has
45739 * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
45740 * process and the mask element will be cached for reuse. For all other elements, this mask will replace the
45741 * element's UpdateManager load indicator and will be destroyed after the initial load.
45743 * Create a new LoadMask
45744 * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
45745 * @param {Object} config The config object
45747 Roo.LoadMask = function(el, config){
45748 this.el = Roo.get(el);
45749 Roo.apply(this, config);
45751 this.store.on('beforeload', this.onBeforeLoad, this);
45752 this.store.on('load', this.onLoad, this);
45753 this.store.on('loadexception', this.onLoadException, this);
45754 this.removeMask = false;
45756 var um = this.el.getUpdateManager();
45757 um.showLoadIndicator = false; // disable the default indicator
45758 um.on('beforeupdate', this.onBeforeLoad, this);
45759 um.on('update', this.onLoad, this);
45760 um.on('failure', this.onLoad, this);
45761 this.removeMask = true;
45765 Roo.LoadMask.prototype = {
45767 * @cfg {Boolean} removeMask
45768 * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
45769 * False to persist the mask element reference for multiple uses (e.g., for paged data widgets). Defaults to false.
45771 removeMask : false,
45773 * @cfg {String} msg
45774 * The text to display in a centered loading message box (defaults to 'Loading...')
45776 msg : 'Loading...',
45778 * @cfg {String} msgCls
45779 * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
45781 msgCls : 'x-mask-loading',
45784 * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
45790 * Disables the mask to prevent it from being displayed
45792 disable : function(){
45793 this.disabled = true;
45797 * Enables the mask so that it can be displayed
45799 enable : function(){
45800 this.disabled = false;
45803 onLoadException : function()
45805 Roo.log(arguments);
45807 if (typeof(arguments[3]) != 'undefined') {
45808 Roo.MessageBox.alert("Error loading",arguments[3]);
45812 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
45813 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
45820 (function() { this.el.unmask(this.removeMask); }).defer(50, this);
45823 onLoad : function()
45825 (function() { this.el.unmask(this.removeMask); }).defer(50, this);
45829 onBeforeLoad : function(){
45830 if(!this.disabled){
45831 (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
45836 destroy : function(){
45838 this.store.un('beforeload', this.onBeforeLoad, this);
45839 this.store.un('load', this.onLoad, this);
45840 this.store.un('loadexception', this.onLoadException, this);
45842 var um = this.el.getUpdateManager();
45843 um.un('beforeupdate', this.onBeforeLoad, this);
45844 um.un('update', this.onLoad, this);
45845 um.un('failure', this.onLoad, this);
45850 * Ext JS Library 1.1.1
45851 * Copyright(c) 2006-2007, Ext JS, LLC.
45853 * Originally Released Under LGPL - original licence link has changed is not relivant.
45856 * <script type="text/javascript">
45861 * @class Roo.XTemplate
45862 * @extends Roo.Template
45863 * Provides a template that can have nested templates for loops or conditionals. The syntax is:
45865 var t = new Roo.XTemplate(
45866 '<select name="{name}">',
45867 '<tpl for="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
45871 // then append, applying the master template values
45874 * Supported features:
45879 {a_variable} - output encoded.
45880 {a_variable.format:("Y-m-d")} - call a method on the variable
45881 {a_variable:raw} - unencoded output
45882 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
45883 {a_variable:this.method_on_template(...)} - call a method on the template object.
45888 <tpl for="a_variable or condition.."></tpl>
45889 <tpl if="a_variable or condition"></tpl>
45890 <tpl exec="some javascript"></tpl>
45891 <tpl name="named_template"></tpl> (experimental)
45893 <tpl for="."></tpl> - just iterate the property..
45894 <tpl for=".."></tpl> - iterates with the parent (probably the template)
45898 Roo.XTemplate = function()
45900 Roo.XTemplate.superclass.constructor.apply(this, arguments);
45907 Roo.extend(Roo.XTemplate, Roo.Template, {
45910 * The various sub templates
45915 * basic tag replacing syntax
45918 * // you can fake an object call by doing this
45922 re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
45925 * compile the template
45927 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
45930 compile: function()
45934 s = ['<tpl>', s, '</tpl>'].join('');
45936 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
45937 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
45938 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
45939 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
45940 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
45945 while(true == !!(m = s.match(re))){
45946 var forMatch = m[0].match(nameRe),
45947 ifMatch = m[0].match(ifRe),
45948 execMatch = m[0].match(execRe),
45949 namedMatch = m[0].match(namedRe),
45954 name = forMatch && forMatch[1] ? forMatch[1] : '';
45957 // if - puts fn into test..
45958 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
45960 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
45965 // exec - calls a function... returns empty if true is returned.
45966 exp = execMatch && execMatch[1] ? execMatch[1] : null;
45968 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
45976 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
45977 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
45978 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
45981 var uid = namedMatch ? namedMatch[1] : id;
45985 id: namedMatch ? namedMatch[1] : id,
45992 s = s.replace(m[0], '');
45994 s = s.replace(m[0], '{xtpl'+ id + '}');
45999 for(var i = tpls.length-1; i >= 0; --i){
46000 this.compileTpl(tpls[i]);
46001 this.tpls[tpls[i].id] = tpls[i];
46003 this.master = tpls[tpls.length-1];
46007 * same as applyTemplate, except it's done to one of the subTemplates
46008 * when using named templates, you can do:
46010 * var str = pl.applySubTemplate('your-name', values);
46013 * @param {Number} id of the template
46014 * @param {Object} values to apply to template
46015 * @param {Object} parent (normaly the instance of this object)
46017 applySubTemplate : function(id, values, parent)
46021 var t = this.tpls[id];
46025 if(t.test && !t.test.call(this, values, parent)){
46029 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
46030 Roo.log(e.toString());
46036 if(t.exec && t.exec.call(this, values, parent)){
46040 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
46041 Roo.log(e.toString());
46046 var vs = t.target ? t.target.call(this, values, parent) : values;
46047 parent = t.target ? values : parent;
46048 if(t.target && vs instanceof Array){
46050 for(var i = 0, len = vs.length; i < len; i++){
46051 buf[buf.length] = t.compiled.call(this, vs[i], parent);
46053 return buf.join('');
46055 return t.compiled.call(this, vs, parent);
46057 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
46058 Roo.log(e.toString());
46059 Roo.log(t.compiled);
46064 compileTpl : function(tpl)
46066 var fm = Roo.util.Format;
46067 var useF = this.disableFormats !== true;
46068 var sep = Roo.isGecko ? "+" : ",";
46069 var undef = function(str) {
46070 Roo.log("Property not found :" + str);
46074 var fn = function(m, name, format, args)
46076 //Roo.log(arguments);
46077 args = args ? args.replace(/\\'/g,"'") : args;
46078 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
46079 if (typeof(format) == 'undefined') {
46080 format= 'htmlEncode';
46082 if (format == 'raw' ) {
46086 if(name.substr(0, 4) == 'xtpl'){
46087 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
46090 // build an array of options to determine if value is undefined..
46092 // basically get 'xxxx.yyyy' then do
46093 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
46094 // (function () { Roo.log("Property not found"); return ''; })() :
46099 Roo.each(name.split('.'), function(st) {
46100 lookfor += (lookfor.length ? '.': '') + st;
46101 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
46104 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
46107 if(format && useF){
46109 args = args ? ',' + args : "";
46111 if(format.substr(0, 5) != "this."){
46112 format = "fm." + format + '(';
46114 format = 'this.call("'+ format.substr(5) + '", ';
46118 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
46122 // called with xxyx.yuu:(test,test)
46124 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
46126 // raw.. - :raw modifier..
46127 return "'"+ sep + udef_st + name + ")"+sep+"'";
46131 // branched to use + in gecko and [].join() in others
46133 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
46134 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
46137 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
46138 body.push(tpl.body.replace(/(\r\n|\n)/g,
46139 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
46140 body.push("'].join('');};};");
46141 body = body.join('');
46144 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
46146 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
46152 applyTemplate : function(values){
46153 return this.master.compiled.call(this, values, {});
46154 //var s = this.subs;
46157 apply : function(){
46158 return this.applyTemplate.apply(this, arguments);
46163 Roo.XTemplate.from = function(el){
46164 el = Roo.getDom(el);
46165 return new Roo.XTemplate(el.value || el.innerHTML);
46166 };// old names for panel elements
46167 Roo.GridPanel = Roo.panel.Grid;
46168 Roo.CalendarPanel = Roo.panel.Calendar;
46169 Roo.ContentPanel = Roo.panel.Content;
46170 Roo.NestedLayoutPanel = Roo.panel.NestedLayout;
46171 Roo.TabPanel = Roo.panel.Tab;
46172 Roo.TabPanelItem = Roo.panel.TabItem;
46173 Roo.TreePanel = Roo.panel.Tree;
46177 Roo.ScrollPanel = Roo.panel.Scroll;
46179 Roo.BorderLayout = Roo.layout.Border;
46180 Roo.BasicLayoutRegion = Roo.layout.BasicRegion;
46181 Roo.LayoutRegion = Roo.layout.Region;
46182 Roo.SplitLayoutRegion = Roo.layout.SplitRegion;
46183 Roo.LayoutManager = Roo.layout.Manager;
46186 Roo.NorthLayoutRegion = Roo.layout.North;
46187 Roo.EastLayoutRegion = Roo.layout.East;
46188 Roo.WestLayoutRegion = Roo.layout.West;
46189 Roo.SouthLayoutRegion = Roo.layout.South;
46190 Roo.CenterLayoutRegion = Roo.layout.Center;
46193 Roo.LayoutStateManager = Roo.layout.StateManager;
46194 Roo.ReaderLayout = Roo.layout.Reader;