return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
},
- // internal
- callback : function(cb, scope, args, delay){
- if(typeof cb == "function"){
- if(delay){
- cb.defer(delay, scope, args || []);
- }else{
- cb.apply(scope, args || []);
- }
+ // internal (non-delayed, will get a return value..)
+ callback : function(cb, scope, args, delay)
+ {
+ if(typeof cb != "function"){
+ return false;
+ }
+ if(delay){
+ cb.defer(delay, scope, args || []);
+ return false
}
+ return cb.apply(scope, args || []);
+
},
/**
/**
Returns the number of milliseconds between this date and date
@param {Date} date (optional) Defaults to now
- @return {Number} The diff in milliseconds
+ @param {String} interval (optional) Default Date.MILLI, A valid date interval enum value (eg. Date.DAY)
+ @return {Number} The diff in milliseconds or units of interval
@member Date getElapsed
*/
-Date.prototype.getElapsed = function(date) {
- return Math.abs((date || new Date()).getTime()-this.getTime());
+Date.prototype.getElapsed = function(date, interval)
+{
+ date = date || new Date();
+ var ret = Math.abs(date.getTime()-this.getTime());
+ switch (interval) {
+
+ case Date.SECOND:
+ return Math.floor(ret / (1000));
+ case Date.MINUTE:
+ return Math.floor(ret / (1000*60));
+ case Date.HOUR:
+ return Math.floor(ret / (1000*60*60));
+ case Date.DAY:
+ return Math.floor(ret / (1000*60*60*24));
+ case Date.MONTH: // this does not give exact number...??
+ return ((date.format("Y") - this.format("Y")) * 12) + (date.format("m") - this.format("m"));
+ case Date.YEAR: // this does not give exact number...??
+ return (date.format("Y") - this.format("Y"));
+
+ case Date.MILLI:
+ default:
+ return ret;
+ }
};
+
// was in date file..
}
};
})();
-/*
+/**
+ * Originally based of this code... - refactored for Roo...
+ * https://github.com/aaalsaleh/undo-manager
+
+ * undo-manager.js
+ * @author Abdulrahman Alsaleh
+ * @copyright 2015 Abdulrahman Alsaleh
+ * @license MIT License (c)
+ *
+ * Hackily modifyed by alan@roojs.com
+ *
+ *
+ *
+ *
+ * TOTALLY UNTESTED...
+ *
+ * Documentation to be done....
+ */
+
+
+/**
+* @class Roo.lib.UndoManager
+* An undo manager implementation in JavaScript. It follows the W3C UndoManager and DOM Transaction
+* Draft and the undocumented and disabled Mozilla Firefox's UndoManager implementation.
+
+ * Usage:
+ * <pre><code>
+
+
+editor.undoManager = new Roo.lib.UndoManager(1000, editor);
+
+</code></pre>
+
+* For more information see this blog post with examples:
+* <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
+ - Create Elements using DOM, HTML fragments and Templates</a>.
+* @constructor
+* @param {Number} limit how far back to go ... use 1000?
+* @param {Object} scope usually use document..
+*/
+
+Roo.lib.UndoManager = function (limit, undoScopeHost)
+{
+ this.stack = [];
+ this.limit = limit;
+ this.scope = undoScopeHost;
+ this.fireEvent = typeof CustomEvent != 'undefined' && undoScopeHost && undoScopeHost.dispatchEvent;
+ if (this.fireEvent) {
+ this.bindEvents();
+ }
+ this.reset();
+
+};
+
+Roo.lib.UndoManager.prototype = {
+
+ limit : false,
+ stack : false,
+ scope : false,
+ fireEvent : false,
+ position : 0,
+ length : 0,
+
+
+ /**
+ * To push and execute a transaction, the method undoManager.transact
+ * must be called by passing a transaction object as the first argument, and a merge
+ * flag as the second argument. A transaction object has the following properties:
+ *
+ * Usage:
+<pre><code>
+undoManager.transact({
+ label: 'Typing',
+ execute: function() { ... },
+ undo: function() { ... },
+ // redo same as execute
+ redo: function() { this.execute(); }
+}, false);
+
+// merge transaction
+undoManager.transact({
+ label: 'Typing',
+ execute: function() { ... }, // this will be run...
+ undo: function() { ... }, // what to do when undo is run.
+ // redo same as execute
+ redo: function() { this.execute(); }
+}, true);
+</code></pre>
+ *
+ *
+ * @param {Object} transaction The transaction to add to the stack.
+ * @return {String} The HTML fragment
+ */
+
+
+ transact : function (transaction, merge)
+ {
+ if (arguments.length < 2) {
+ throw new TypeError('Not enough arguments to UndoManager.transact.');
+ }
+
+ transaction.execute();
+
+ this.stack.splice(0, this.position);
+ if (merge && this.length) {
+ this.stack[0].push(transaction);
+ } else {
+ this.stack.unshift([transaction]);
+ }
+
+ this.position = 0;
+
+ if (this.limit && this.stack.length > this.limit) {
+ this.length = this.stack.length = this.limit;
+ } else {
+ this.length = this.stack.length;
+ }
+
+ if (this.fireEvent) {
+ this.scope.dispatchEvent(
+ new CustomEvent('DOMTransaction', {
+ detail: {
+ transactions: this.stack[0].slice()
+ },
+ bubbles: true,
+ cancelable: false
+ })
+ );
+ }
+
+ //Roo.log("transaction: pos:" + this.position + " len: " + this.length + " slen:" + this.stack.length);
+
+
+ },
+
+ undo : function ()
+ {
+ //Roo.log("undo: pos:" + this.position + " len: " + this.length + " slen:" + this.stack.length);
+
+ if (this.position < this.length) {
+ for (var i = this.stack[this.position].length - 1; i >= 0; i--) {
+ this.stack[this.position][i].undo();
+ }
+ this.position++;
+
+ if (this.fireEvent) {
+ this.scope.dispatchEvent(
+ new CustomEvent('undo', {
+ detail: {
+ transactions: this.stack[this.position - 1].slice()
+ },
+ bubbles: true,
+ cancelable: false
+ })
+ );
+ }
+ }
+ },
+
+ redo : function ()
+ {
+ if (this.position > 0) {
+ for (var i = 0, n = this.stack[this.position - 1].length; i < n; i++) {
+ this.stack[this.position - 1][i].redo();
+ }
+ this.position--;
+
+ if (this.fireEvent) {
+ this.scope.dispatchEvent(
+ new CustomEvent('redo', {
+ detail: {
+ transactions: this.stack[this.position].slice()
+ },
+ bubbles: true,
+ cancelable: false
+ })
+ );
+ }
+ }
+ },
+
+ item : function (index)
+ {
+ if (index >= 0 && index < this.length) {
+ return this.stack[index].slice();
+ }
+ return null;
+ },
+
+ clearUndo : function () {
+ this.stack.length = this.length = this.position;
+ },
+
+ clearRedo : function () {
+ this.stack.splice(0, this.position);
+ this.position = 0;
+ this.length = this.stack.length;
+ },
+ /**
+ * Reset the undo - probaly done on load to clear all history.
+ */
+ reset : function()
+ {
+ this.stack = [];
+ this.position = 0;
+ this.length = 0;
+ this.current_html = this.scope.innerHTML;
+ if (this.timer !== false) {
+ clearTimeout(this.timer);
+ }
+ this.timer = false;
+ this.merge = false;
+ this.addEvent();
+
+ },
+ current_html : '',
+ timer : false,
+ merge : false,
+
+
+ // this will handle the undo/redo on the element.?
+ bindEvents : function()
+ {
+ var el = this.scope;
+ el.undoManager = this;
+
+
+ this.scope.addEventListener('keydown', function(e) {
+ if ((e.ctrlKey || e.metaKey) && e.keyCode === 90) {
+ if (e.shiftKey) {
+ el.undoManager.redo(); // Ctrl/Command + Shift + Z
+ } else {
+ el.undoManager.undo(); // Ctrl/Command + Z
+ }
+
+ e.preventDefault();
+ }
+ });
+ /// ignore keyup..
+ this.scope.addEventListener('keyup', function(e) {
+ if ((e.ctrlKey || e.metaKey) && e.keyCode === 90) {
+ e.preventDefault();
+ }
+ });
+
+
+
+ var t = this;
+
+ el.addEventListener('input', function(e) {
+ if(el.innerHTML == t.current_html) {
+ return;
+ }
+ // only record events every second.
+ if (t.timer !== false) {
+ clearTimeout(t.timer);
+ t.timer = false;
+ }
+ t.timer = setTimeout(function() { t.merge = false; }, 1000);
+
+ t.addEvent(t.merge);
+ t.merge = true; // ignore changes happening every second..
+ });
+ },
+ /**
+ * Manually add an event.
+ * Normall called without arguements - and it will just get added to the stack.
+ *
+ */
+
+ addEvent : function(merge)
+ {
+ //Roo.log("undomanager +" + (merge ? 'Y':'n'));
+ // not sure if this should clear the timer
+ merge = typeof(merge) == 'undefined' ? false : merge;
+
+ this.scope.undoManager.transact({
+ scope : this.scope,
+ oldHTML: this.current_html,
+ newHTML: this.scope.innerHTML,
+ // nothing to execute (content already changed when input is fired)
+ execute: function() { },
+ undo: function() {
+ this.scope.innerHTML = this.current_html = this.oldHTML;
+ },
+ redo: function() {
+ this.scope.innerHTML = this.current_html = this.newHTML;
+ }
+ }, false); //merge);
+
+ this.merge = merge;
+
+ this.current_html = this.scope.innerHTML;
+ }
+
+
+
+
+
+
+};
+/**
+ * @class Roo.lib.Range
+ * @constructor
+ * This is a toolkit, normally used to copy features into a Dom Range element
+ * Roo.lib.Range.wrap(x);
+ *
+ *
+ *
+ */
+Roo.lib.Range = function() { };
+
+/**
+ * Wrap a Dom Range object, to give it new features...
+ * @static
+ * @param {Range} the range to wrap
+ */
+Roo.lib.Range.wrap = function(r) {
+ return Roo.apply(r, Roo.lib.Range.prototype);
+};
+/**
+ * find a parent node eg. LI / OL
+ * @param {string|Array} node name or array of nodenames
+ * @return {DomElement|false}
+ */
+Roo.apply(Roo.lib.Range.prototype,
+{
+
+ closest : function(str)
+ {
+ if (typeof(str) != 'string') {
+ // assume it's a array.
+ for(var i = 0;i < str.length;i++) {
+ var r = this.closest(str[i]);
+ if (r !== false) {
+ return r;
+ }
+
+ }
+ return false;
+ }
+ str = str.toLowerCase();
+ var n = this.commonAncestorContainer; // might not be a node
+ while (n.nodeType != 1) {
+ n = n.parentNode;
+ }
+
+ if (n.nodeName.toLowerCase() == str ) {
+ return n;
+ }
+ if (n.nodeName.toLowerCase() == 'body') {
+ return false;
+ }
+
+ return n.closest(str) || false;
+
+ },
+ cloneRange : function()
+ {
+ return Roo.lib.Range.wrap(Range.prototype.cloneRange.call(this));
+ }
+});/**
+ * @class Roo.lib.Selection
+ * @constructor
+ * This is a toolkit, normally used to copy features into a Dom Selection element
+ * Roo.lib.Selection.wrap(x);
+ *
+ *
+ *
+ */
+Roo.lib.Selection = function() { };
+
+/**
+ * Wrap a Dom Range object, to give it new features...
+ * @static
+ * @param {Range} the range to wrap
+ */
+Roo.lib.Selection.wrap = function(r, doc) {
+ Roo.apply(r, Roo.lib.Selection.prototype);
+ r.ownerDocument = doc; // usefull so we dont have to keep referening to it.
+ return r;
+};
+/**
+ * find a parent node eg. LI / OL
+ * @param {string|Array} node name or array of nodenames
+ * @return {DomElement|false}
+ */
+Roo.apply(Roo.lib.Selection.prototype,
+{
+ /**
+ * the owner document
+ */
+ ownerDocument : false,
+
+ getRangeAt : function(n)
+ {
+ return Roo.lib.Range.wrap(Selection.prototype.getRangeAt.call(this,n));
+ },
+
+ /**
+ * insert node at selection
+ * @param {DomElement|string} node
+ * @param {string} cursor (after|in|none) where to place the cursor after inserting.
+ */
+ insertNode: function(node, cursor)
+ {
+ if (typeof(node) == 'string') {
+ node = this.ownerDocument.createElement(node);
+ if (cursor == 'in') {
+ node.innerHTML = ' ';
+ }
+ }
+
+ var range = this.getRangeAt(0);
+
+ if (this.type != 'Caret') {
+ range.deleteContents();
+ }
+ var sn = node.childNodes[0]; // select the contents.
+
+
+
+ range.insertNode(node);
+ if (cursor == 'after') {
+ node.insertAdjacentHTML('afterend', ' ');
+ sn = node.nextSibling;
+ }
+
+ if (cursor == 'none') {
+ return;
+ }
+
+ this.cursorText(sn);
+ },
+
+ cursorText : function(n)
+ {
+
+ //var range = this.getRangeAt(0);
+ range = Roo.lib.Range.wrap(new Range());
+ //range.selectNode(n);
+
+ var ix = Array.from(n.parentNode.childNodes).indexOf(n);
+ range.setStart(n.parentNode,ix);
+ range.setEnd(n.parentNode,ix+1);
+ //range.collapse(false);
+
+ this.removeAllRanges();
+ this.addRange(range);
+
+ Roo.log([n, range, this,this.baseOffset,this.extentOffset, this.type]);
+ },
+ cursorAfter : function(n)
+ {
+ if (!n.nextSibling || n.nextSibling.nodeValue != ' ') {
+ n.insertAdjacentHTML('afterend', ' ');
+ }
+ this.cursorText (n.nextSibling);
+ }
+
+
+});/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
if (typeof(o) == 'string') {
return parentNode.appendChild(document.createTextNode(o));
}
- o.tag = o.tag || div;
+ o.tag = o.tag || 'div';
if (o.ns && Roo.isIE) {
ns = false;
o.tag = o.ns + ':' + o.tag;
init : function(){
Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
...
- // supposed you have a {@link Roo.BorderLayout}
- var layout = new Roo.BorderLayout(...);
+ // supposed you have a {@link Roo.layout.Border}
+ var layout = new Roo.layout.Border(...);
layout.restoreState();
// or a {Roo.BasicDialog}
var dialog = new Roo.BasicDialog(...);
*/
actionMode : "el",
+ /**
+ * @cfg {String} style
+ * css styles to add to component
+ * eg. text-align:right;
+ */
+ style : false,
+
/** @private */
getActionEl : function(){
return this[this.actionMode];
*
* Each sub module is expected to have a parent pointing to the class name of it's parent module.
*
- * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
+ * When the top level is false, a 'Roo.layout.Border' is created and the element is flagged as 'topModule'
* - if mulitple topModules exist, the last one is defined as the top module.
*
* Embeded Roo
el = el ? Roo.get(el) : false;
- if (typeof(Roo.BorderLayout) == 'undefined' ) {
+ if (typeof(Roo.layout.Border) == 'undefined' ) {
this.parent = {
el : new Roo.bootstrap.layout.Border({
// it's a top level one..
this.parent = {
- el : new Roo.BorderLayout(el || document.body, {
+ el : new Roo.layout.Border(el || document.body, {
center: {
titlebar: false,
autoScroll:false,
* If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
*
* @param {Proxy}
- * @param {Object} return from JsonData.reader() - success, totalRecords, records
- * @param {Object} load options
+ * @param {Object} ret return data from JsonData.reader() - success, totalRecords, records
+ * @param {Object} opts - load Options
* @param {Object} jsonData from your request (normally this contains the Exception)
*/
loadexception : true
*/
/**
* @class Roo.data.MemoryProxy
+ * @extends Roo.data.DataProxy
* An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
* to the Reader when its load method is called.
* @constructor
- * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
+ * @param {Object} config A config object containing the objects needed for the Store to access data,
*/
-Roo.data.MemoryProxy = function(data){
- if (data.data) {
- data = data.data;
+Roo.data.MemoryProxy = function(config){
+ var data = config;
+ if (typeof(config) != 'undefined' && typeof(config.data) != 'undefined') {
+ data = config.data;
}
Roo.data.MemoryProxy.superclass.constructor.call(this);
this.data = data;
Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
+ /**
+ * @cfg {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
+ */
/**
* Load data from the requested source (in this case an in-memory
* data object passed to the constructor), read the data object into
// thse are take from connection...
/**
- * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
+ * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
*/
/**
- * @cfg {Object} extraParams (Optional) An object containing properties which are used as
+ * @cfg {Object} extraParams An object containing properties which are used as
* extra parameters to each request made by this object. (defaults to undefined)
*/
/**
- * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
+ * @cfg {Object} defaultHeaders An object containing request headers which are added
* to each request made by this object. (defaults to undefined)
*/
/**
- * @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
+ * @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)
*/
/**
- * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
+ * @cfg {Number} timeout The timeout in milliseconds to be used for requests. (defaults to 30000)
*/
/**
- * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
+ * @cfg {Boolean} autoAbort Whether this request should abort any pending requests. (defaults to false)
* @type Boolean
*/
}
-}); /*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-/**
- * @class Roo.TabPanel
- * @extends Roo.util.Observable
- * A lightweight tab container.
- * <br><br>
- * Usage:
- * <pre><code>
-// basic tabs 1, built from existing content
-var tabs = new Roo.TabPanel("tabs1");
-tabs.addTab("script", "View Script");
-tabs.addTab("markup", "View Markup");
-tabs.activate("script");
-
-// more advanced tabs, built from javascript
-var jtabs = new Roo.TabPanel("jtabs");
-jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
-
-// set up the UpdateManager
-var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
-var updater = tab2.getUpdateManager();
-updater.setDefaultUrl("ajax1.htm");
-tab2.on('activate', updater.refresh, updater, true);
-
-// Use setUrl for Ajax loading
-var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
-tab3.setUrl("ajax2.htm", null, true);
-
-// Disabled tab
-var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
-tab4.disable();
+});Roo.panel = {};
+/*
+* Licence: LGPL
+*/
-jtabs.activate("jtabs-1");
- * </code></pre>
+/**
+ * @class Roo.panel.Cropbox
+ * @extends Roo.BoxComponent
+ * Panel Cropbox class
+ * @cfg {String} emptyText show when image has been loaded
+ * @cfg {String} rotateNotify show when image too small to rotate
+ * @cfg {Number} errorTimeout default 3000
+ * @cfg {Number} minWidth default 300
+ * @cfg {Number} minHeight default 300
+ * @cfg {Number} outputMaxWidth default 1200
+ * @cfg {Number} windowSize default 300
+ * @cfg {Array} buttons default ['rotateLeft', 'pictureBtn', 'rotateRight']
+ * @cfg {Boolean} isDocument (true|false) default false
+ * @cfg {String} url action url
+ * @cfg {String} paramName default 'imageUpload'
+ * @cfg {String} method default POST
+ * @cfg {Boolean} loadMask (true|false) default true
+ * @cfg {Boolean} loadingText default 'Loading...'
+ *
* @constructor
- * Create a new TabPanel.
- * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
- * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
+ * Create a new Cropbox
+ * @param {Object} config The config object
*/
-Roo.TabPanel = function(container, config){
- /**
- * The container element for this TabPanel.
- * @type Roo.Element
- */
- this.el = Roo.get(container, true);
- if(config){
- if(typeof config == "boolean"){
- this.tabPosition = config ? "bottom" : "top";
- }else{
- Roo.apply(this, config);
- }
- }
- if(this.tabPosition == "bottom"){
- this.bodyEl = Roo.get(this.createBody(this.el.dom));
- this.el.addClass("x-tabs-bottom");
- }
- this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
- this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
- this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
- if(Roo.isIE){
- Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
- }
- if(this.tabPosition != "bottom"){
- /** The body element that contains {@link Roo.TabPanelItem} bodies. +
- * @type Roo.Element
- */
- this.bodyEl = Roo.get(this.createBody(this.el.dom));
- this.el.addClass("x-tabs-top");
- }
- this.items = [];
-
- this.bodyEl.setStyle("position", "relative");
-
- this.active = null;
- this.activateDelegate = this.activate.createDelegate(this);
+ Roo.panel.Cropbox = function(config){
+ Roo.panel.Cropbox.superclass.constructor.call(this, config);
+
this.addEvents({
/**
- * @event tabchange
- * Fires when the active tab changes
- * @param {Roo.TabPanel} this
- * @param {Roo.TabPanelItem} activePanel The new active tab
+ * @event beforeselectfile
+ * Fire before select file
+ * @param {Roo.panel.Cropbox} this
*/
- "tabchange": true,
+ "beforeselectfile" : true,
/**
- * @event beforetabchange
- * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
- * @param {Roo.TabPanel} this
- * @param {Object} e Set cancel to true on this object to cancel the tab change
- * @param {Roo.TabPanelItem} tab The tab being changed to
+ * @event initial
+ * Fire after initEvent
+ * @param {Roo.panel.Cropbox} this
*/
- "beforetabchange" : true
+ "initial" : true,
+ /**
+ * @event crop
+ * Fire after initEvent
+ * @param {Roo.panel.Cropbox} this
+ * @param {String} data
+ */
+ "crop" : true,
+ /**
+ * @event prepare
+ * Fire when preparing the file data
+ * @param {Roo.panel.Cropbox} this
+ * @param {Object} file
+ */
+ "prepare" : true,
+ /**
+ * @event exception
+ * Fire when get exception
+ * @param {Roo.panel.Cropbox} this
+ * @param {XMLHttpRequest} xhr
+ */
+ "exception" : true,
+ /**
+ * @event beforeloadcanvas
+ * Fire before load the canvas
+ * @param {Roo.panel.Cropbox} this
+ * @param {String} src
+ */
+ "beforeloadcanvas" : true,
+ /**
+ * @event trash
+ * Fire when trash image
+ * @param {Roo.panel.Cropbox} this
+ */
+ "trash" : true,
+ /**
+ * @event download
+ * Fire when download the image
+ * @param {Roo.panel.Cropbox} this
+ */
+ "download" : true,
+ /**
+ * @event footerbuttonclick
+ * Fire when footerbuttonclick
+ * @param {Roo.panel.Cropbox} this
+ * @param {String} type
+ */
+ "footerbuttonclick" : true,
+ /**
+ * @event resize
+ * Fire when resize
+ * @param {Roo.panel.Cropbox} this
+ */
+ "resize" : true,
+ /**
+ * @event rotate
+ * Fire when rotate the image
+ * @param {Roo.panel.Cropbox} this
+ * @param {String} pos
+ */
+ "rotate" : true,
+ /**
+ * @event inspect
+ * Fire when inspect the file
+ * @param {Roo.panel.Cropbox} this
+ * @param {Object} file
+ */
+ "inspect" : true,
+ /**
+ * @event upload
+ * Fire when xhr upload the file
+ * @param {Roo.panel.Cropbox} this
+ * @param {Object} data
+ */
+ "upload" : true,
+ /**
+ * @event arrange
+ * Fire when arrange the file data
+ * @param {Roo.panel.Cropbox} this
+ * @param {Object} formData
+ */
+ "arrange" : true,
+ /**
+ * @event loadcanvas
+ * Fire after load the canvas
+ * @param {Roo.panel.Cropbox}
+ * @param {Object} imgEl
+ */
+ "loadcanvas" : true
});
+
+ this.buttons = this.buttons || Roo.panel.Cropbox.footer.STANDARD;
+};
- Roo.EventManager.onWindowResize(this.onResize, this);
- this.cpad = this.el.getPadding("lr");
- this.hiddenCount = 0;
-
+Roo.extend(Roo.panel.Cropbox, Roo.Component, {
+
+ emptyText : 'Click to upload image',
+ rotateNotify : 'Image is too small to rotate',
+ errorTimeout : 3000,
+ scale : 0,
+ baseScale : 1,
+ rotate : 0,
+ dragable : false,
+ pinching : false,
+ mouseX : 0,
+ mouseY : 0,
+ cropData : false,
+ minWidth : 300,
+ minHeight : 300,
+ outputMaxWidth : 1200,
+ windowSize : 300,
+ file : false,
+ exif : {},
+ baseRotate : 1,
+ cropType : 'image/jpeg',
+ buttons : false,
+ canvasLoaded : false,
+ isDocument : false,
+ method : 'POST',
+ paramName : 'imageUpload',
+ loadMask : true,
+ loadingText : 'Loading...',
+ maskEl : false,
+
+ getAutoCreate : function()
+ {
+ var cfg = {
+ tag : 'div',
+ cls : 'roo-upload-cropbox',
+ cn : [
+ {
+ tag : 'input',
+ cls : 'roo-upload-cropbox-selector',
+ type : 'file'
+ },
+ {
+ tag : 'div',
+ cls : 'roo-upload-cropbox-body',
+ style : 'cursor:pointer',
+ cn : [
+ {
+ tag : 'div',
+ cls : 'roo-upload-cropbox-preview'
+ },
+ {
+ tag : 'div',
+ cls : 'roo-upload-cropbox-thumb'
+ },
+ {
+ tag : 'div',
+ cls : 'roo-upload-cropbox-empty-notify',
+ html : this.emptyText
+ },
+ {
+ tag : 'div',
+ cls : 'roo-upload-cropbox-error-notify alert alert-danger',
+ html : this.rotateNotify
+ }
+ ]
+ },
+ {
+ tag : 'div',
+ cls : 'roo-upload-cropbox-footer',
+ cn : {
+ tag : 'div',
+ cls : 'btn-group btn-group-justified roo-upload-cropbox-btn-group',
+ cn : []
+ }
+ }
+ ]
+ };
+
+ return cfg;
+ },
+
+ onRender : function(ct, position)
+ {
+ Roo.panel.Cropbox.superclass.onRender.call(this, ct, position);
- // toolbar on the tabbar support...
- if (this.toolbar) {
- var tcfg = this.toolbar;
- tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');
- this.toolbar = new Roo.Toolbar(tcfg);
- if (Roo.isSafari) {
- var tbl = tcfg.container.child('table', true);
- tbl.setAttribute('width', '100%');
+ if(this.el){
+ if (this.el.attr('xtype')) {
+ this.el.attr('xtypex', this.el.attr('xtype'));
+ this.el.dom.removeAttribute('xtype');
+
+ this.initEvents();
+ }
}
+ else {
+ var cfg = Roo.apply({}, this.getAutoCreate());
- }
-
-
-
- Roo.TabPanel.superclass.constructor.call(this);
-};
-
-Roo.extend(Roo.TabPanel, Roo.util.Observable, {
- /*
- *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
- */
- tabPosition : "top",
- /*
- *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
- */
- currentTabWidth : 0,
- /*
- *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
- */
- minTabWidth : 40,
- /*
- *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
- */
- maxTabWidth : 250,
- /*
- *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
- */
- preferredTabWidth : 175,
- /*
- *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
- */
- resizeTabs : false,
- /*
- *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
- */
- monitorResize : true,
- /*
- *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar.
- */
- toolbar : false,
-
- /**
- * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
- * @param {String} id The id of the div to use <b>or create</b>
- * @param {String} text The text for the tab
- * @param {String} content (optional) Content to put in the TabPanelItem body
- * @param {Boolean} closable (optional) True to create a close icon on the tab
- * @return {Roo.TabPanelItem} The created TabPanelItem
- */
- addTab : function(id, text, content, closable){
- var item = new Roo.TabPanelItem(this, id, text, closable);
- this.addTabItem(item);
- if(content){
- item.setContent(content);
+ cfg.id = this.id || Roo.id();
+
+ if (this.cls) {
+ cfg.cls = (typeof(cfg.cls) == 'undefined' ? this.cls : cfg.cls) + ' ' + this.cls;
+ }
+
+ if (this.style) { // fixme needs to support more complex style data.
+ cfg.style = (typeof(cfg.style) == 'undefined' ? this.style : cfg.style) + '; ' + this.style;
+ }
+
+ this.el = ct.createChild(cfg, position);
+
+ this.initEvents();
}
- return item;
- },
-
- /**
- * Returns the {@link Roo.TabPanelItem} with the specified id/index
- * @param {String/Number} id The id or index of the TabPanelItem to fetch.
- * @return {Roo.TabPanelItem}
- */
- getTab : function(id){
- return this.items[id];
- },
-
- /**
- * Hides the {@link Roo.TabPanelItem} with the specified id/index
- * @param {String/Number} id The id or index of the TabPanelItem to hide.
- */
- hideTab : function(id){
- var t = this.items[id];
- if(!t.isHidden()){
- t.setHidden(true);
- this.hiddenCount++;
- this.autoSizeTabs();
+
+ if (this.buttons.length) {
+
+ Roo.each(this.buttons, function(bb) {
+
+ var btn = this.el.select('.roo-upload-cropbox-footer div.roo-upload-cropbox-btn-group').first().createChild(bb);
+
+ btn.on('click', this.onFooterButtonClick.createDelegate(this, [bb.action], true));
+
+ }, this);
}
- },
-
- /**
- * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
- * @param {String/Number} id The id or index of the TabPanelItem to unhide.
- */
- unhideTab : function(id){
- var t = this.items[id];
- if(t.isHidden()){
- t.setHidden(false);
- this.hiddenCount--;
- this.autoSizeTabs();
+
+ if(this.loadMask){
+ this.maskEl = this.el;
}
},
-
- /**
- * Adds an existing {@link Roo.TabPanelItem}.
- * @param {Roo.TabPanelItem} item The TabPanelItem to add
- */
- addTabItem : function(item){
- this.items[item.id] = item;
- this.items.push(item);
- if(this.resizeTabs){
- item.setWidth(this.currentTabWidth || this.preferredTabWidth);
- this.autoSizeTabs();
- }else{
- item.autoSize();
- }
+
+ initEvents : function()
+ {
+ this.urlAPI = (window.createObjectURL && window) ||
+ (window.URL && URL.revokeObjectURL && URL) ||
+ (window.webkitURL && webkitURL);
+
+ this.bodyEl = this.el.select('.roo-upload-cropbox-body', true).first();
+ this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
+
+ this.selectorEl = this.el.select('.roo-upload-cropbox-selector', true).first();
+ this.selectorEl.hide();
+
+ this.previewEl = this.el.select('.roo-upload-cropbox-preview', true).first();
+ this.previewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
+
+ this.thumbEl = this.el.select('.roo-upload-cropbox-thumb', true).first();
+ this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
+ this.thumbEl.hide();
+
+ this.notifyEl = this.el.select('.roo-upload-cropbox-empty-notify', true).first();
+ this.notifyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
+
+ this.errorEl = this.el.select('.roo-upload-cropbox-error-notify', true).first();
+ this.errorEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
+ this.errorEl.hide();
+
+ this.footerEl = this.el.select('.roo-upload-cropbox-footer', true).first();
+ this.footerEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
+ this.footerEl.hide();
+
+ this.setThumbBoxSize();
+
+ this.bind();
+
+ this.resize();
+
+ this.fireEvent('initial', this);
},
- /**
- * Removes a {@link Roo.TabPanelItem}.
- * @param {String/Number} id The id or index of the TabPanelItem to remove.
- */
- removeTab : function(id){
- var items = this.items;
- var tab = items[id];
- if(!tab) { return; }
- var index = items.indexOf(tab);
- if(this.active == tab && items.length > 1){
- var newTab = this.getNextAvailable(index);
- if(newTab) {
- newTab.activate();
- }
+ bind : function()
+ {
+ var _this = this;
+
+ window.addEventListener("resize", function() { _this.resize(); } );
+
+ this.bodyEl.on('click', this.beforeSelectFile, this);
+
+ if(Roo.isTouch){
+ this.bodyEl.on('touchstart', this.onTouchStart, this);
+ this.bodyEl.on('touchmove', this.onTouchMove, this);
+ this.bodyEl.on('touchend', this.onTouchEnd, this);
}
- this.stripEl.dom.removeChild(tab.pnode.dom);
- if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
- this.bodyEl.dom.removeChild(tab.bodyEl.dom);
+
+ if(!Roo.isTouch){
+ this.bodyEl.on('mousedown', this.onMouseDown, this);
+ this.bodyEl.on('mousemove', this.onMouseMove, this);
+ var mousewheel = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel';
+ this.bodyEl.on(mousewheel, this.onMouseWheel, this);
+ Roo.get(document).on('mouseup', this.onMouseUp, this);
}
- items.splice(index, 1);
- delete this.items[tab.id];
- tab.fireEvent("close", tab);
- tab.purgeListeners();
- this.autoSizeTabs();
+
+ this.selectorEl.on('change', this.onFileSelected, this);
},
-
- getNextAvailable : function(start){
- var items = this.items;
- var index = start;
- // look for a next tab that will slide over to
- // replace the one being removed
- while(index < items.length){
- var item = items[++index];
- if(item && !item.isHidden()){
- return item;
- }
- }
- // if one isn't found select the previous tab (on the left)
- index = start;
- while(index >= 0){
- var item = items[--index];
- if(item && !item.isHidden()){
- return item;
- }
- }
- return null;
+
+ reset : function()
+ {
+ this.scale = 0;
+ this.baseScale = 1;
+ this.rotate = 0;
+ this.baseRotate = 1;
+ this.dragable = false;
+ this.pinching = false;
+ this.mouseX = 0;
+ this.mouseY = 0;
+ this.cropData = false;
+ this.notifyEl.dom.innerHTML = this.emptyText;
+
+ // this.selectorEl.dom.value = '';
+
},
-
- /**
- * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
- * @param {String/Number} id The id or index of the TabPanelItem to disable.
- */
- disableTab : function(id){
- var tab = this.items[id];
- if(tab && this.active != tab){
- tab.disable();
+
+ resize : function()
+ {
+ if(this.fireEvent('resize', this) != false){
+ this.setThumbBoxPosition();
+ this.setCanvasPosition();
}
},
-
- /**
- * Enables a {@link Roo.TabPanelItem} that is disabled.
- * @param {String/Number} id The id or index of the TabPanelItem to enable.
- */
- enableTab : function(id){
- var tab = this.items[id];
- tab.enable();
+
+ onFooterButtonClick : function(e, el, o, type)
+ {
+ switch (type) {
+ case 'rotate-left' :
+ this.onRotateLeft(e);
+ break;
+ case 'rotate-right' :
+ this.onRotateRight(e);
+ break;
+ case 'picture' :
+ this.beforeSelectFile(e);
+ break;
+ case 'trash' :
+ this.trash(e);
+ break;
+ case 'crop' :
+ this.crop(e);
+ break;
+ case 'download' :
+ this.download(e);
+ break;
+ case 'center' :
+ this.center(e);
+ break;
+ default :
+ break;
+ }
+
+ this.fireEvent('footerbuttonclick', this, type);
},
-
- /**
- * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
- * @param {String/Number} id The id or index of the TabPanelItem to activate.
- * @return {Roo.TabPanelItem} The TabPanelItem.
- */
- activate : function(id){
- var tab = this.items[id];
- if(!tab){
- return null;
+
+ beforeSelectFile : function(e)
+ {
+ e.preventDefault();
+
+ if(this.fireEvent('beforeselectfile', this) != false){
+ this.selectorEl.dom.click();
}
- if(tab == this.active || tab.disabled){
- return tab;
+ },
+
+ onFileSelected : function(e)
+ {
+ e.preventDefault();
+
+ if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
+ return;
}
- var e = {};
- this.fireEvent("beforetabchange", this, e, tab);
- if(e.cancel !== true && !tab.disabled){
- if(this.active){
- this.active.hide();
- }
- this.active = this.items[id];
- this.active.show();
- this.fireEvent("tabchange", this, this.active);
+
+ var file = this.selectorEl.dom.files[0];
+
+ if(this.fireEvent('inspect', this, file) != false){
+ this.prepare(file);
}
- return tab;
+
},
-
- /**
- * Gets the active {@link Roo.TabPanelItem}.
- * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
- */
- getActiveTab : function(){
- return this.active;
+
+ trash : function(e)
+ {
+ this.fireEvent('trash', this);
},
-
- /**
- * Updates the tab body element to fit the height of the container element
- * for overflow scrolling
- * @param {Number} targetHeight (optional) Override the starting height from the elements height
- */
- syncHeight : function(targetHeight){
- var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
- var bm = this.bodyEl.getMargins();
- var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
- this.bodyEl.setHeight(newHeight);
- return newHeight;
+
+ download : function(e)
+ {
+ this.fireEvent('download', this);
},
- onResize : function(){
- if(this.monitorResize){
- this.autoSizeTabs();
+ center : function(e)
+ {
+ this.setCanvasPosition();
+ },
+
+ loadCanvas : function(src)
+ {
+ if(this.fireEvent('beforeloadcanvas', this, src) != false){
+
+ this.reset();
+
+ this.imageEl = document.createElement('img');
+
+ var _this = this;
+
+ this.imageEl.addEventListener("load", function(){ _this.onLoadCanvas(); });
+
+ this.imageEl.src = src;
}
},
+
+ onLoadCanvas : function()
+ {
+ this.imageEl.OriginWidth = this.imageEl.naturalWidth || this.imageEl.width;
+ this.imageEl.OriginHeight = this.imageEl.naturalHeight || this.imageEl.height;
- /**
- * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
- */
- beginUpdate : function(){
- this.updating = true;
+ if(this.fireEvent('loadcanvas', this, this.imageEl) != false){
+
+ this.bodyEl.un('click', this.beforeSelectFile, this);
+
+ this.notifyEl.hide();
+ this.thumbEl.show();
+ this.footerEl.show();
+
+ this.baseRotateLevel();
+
+ if(this.isDocument){
+ this.setThumbBoxSize();
+ }
+
+ this.setThumbBoxPosition();
+
+ this.baseScaleLevel();
+
+ this.draw();
+
+ this.resize();
+
+ this.canvasLoaded = true;
+
+ }
+
+ if(this.loadMask){
+ this.maskEl.unmask();
+ }
+
},
+
+ setCanvasPosition : function(center = true)
+ {
+ if(!this.canvasEl){
+ return;
+ }
- /**
- * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
- */
- endUpdate : function(){
- this.updating = false;
- this.autoSizeTabs();
- },
+ var newCenterLeft = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
+ var newCenterTop = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
+
+ if(center) {
+ this.previewEl.setLeft(newCenterLeft);
+ this.previewEl.setTop(newCenterTop);
- /**
- * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
- */
- autoSizeTabs : function(){
- var count = this.items.length;
- var vcount = count - this.hiddenCount;
- if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
return;
}
- var w = Math.max(this.el.getWidth() - this.cpad, 10);
- var availWidth = Math.floor(w / vcount);
- var b = this.stripBody;
- if(b.getWidth() > w){
- var tabs = this.items;
- this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
- if(availWidth < this.minTabWidth){
- /*if(!this.sleft){ // incomplete scrolling code
- this.createScrollButtons();
- }
- this.showScroll();
- this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
- }
- }else{
- if(this.currentTabWidth < this.preferredTabWidth){
- this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
- }
- }
- },
+
+ var oldScaleLevel = this.baseScale * Math.pow(1.02, this.startScale);
+ var oldCanvasWidth = Math.floor(this.imageEl.OriginWidth * oldScaleLevel);
+ var oldCanvasHeight = Math.floor(this.imageEl.OriginHeight * oldScaleLevel);
- /**
- * Returns the number of tabs in this TabPanel.
- * @return {Number}
- */
- getCount : function(){
- return this.items.length;
- },
+ var oldCenterLeft = Math.ceil((this.bodyEl.getWidth() - oldCanvasWidth) / 2);
+ var oldCenterTop = Math.ceil((this.bodyEl.getHeight() - oldCanvasHeight) / 2);
- /**
- * Resizes all the tabs to the passed width
- * @param {Number} The new width
- */
- setTabWidth : function(width){
- this.currentTabWidth = width;
- for(var i = 0, len = this.items.length; i < len; i++) {
- if(!this.items[i].isHidden()) {
- this.items[i].setWidth(width);
- }
+ var leftDiff = newCenterLeft - oldCenterLeft;
+ var topDiff = newCenterTop - oldCenterTop;
+
+ var newPreviewLeft = this.previewEl.getLeft(true) + leftDiff;
+ var newPreviewTop = this.previewEl.getTop(true) + topDiff;
+
+ this.previewEl.setLeft(newPreviewLeft);
+ this.previewEl.setTop(newPreviewTop);
+
+ },
+
+ onMouseDown : function(e)
+ {
+ e.stopEvent();
+
+ this.dragable = true;
+ this.pinching = false;
+
+ if(this.isDocument && (this.canvasEl.width < this.thumbEl.getWidth() || this.canvasEl.height < this.thumbEl.getHeight())){
+ this.dragable = false;
+ return;
}
+
+ this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
+ this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
+
},
-
- /**
- * Destroys this TabPanel
- * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
- */
- destroy : function(removeEl){
- Roo.EventManager.removeResizeListener(this.onResize, this);
- for(var i = 0, len = this.items.length; i < len; i++){
- this.items[i].purgeListeners();
+
+ onMouseMove : function(e)
+ {
+ e.stopEvent();
+
+ if(!this.canvasLoaded){
+ return;
}
- if(removeEl === true){
- this.el.update("");
- this.el.remove();
+
+ if (!this.dragable){
+ return;
}
- }
-});
-
-/**
- * @class Roo.TabPanelItem
- * @extends Roo.util.Observable
- * Represents an individual item (tab plus body) in a TabPanel.
- * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
- * @param {String} id The id of this TabPanelItem
- * @param {String} text The text for the tab of this TabPanelItem
- * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
- */
-Roo.TabPanelItem = function(tabPanel, id, text, closable){
- /**
- * The {@link Roo.TabPanel} this TabPanelItem belongs to
- * @type Roo.TabPanel
- */
- this.tabPanel = tabPanel;
- /**
- * The id for this TabPanelItem
- * @type String
- */
- this.id = id;
- /** @private */
- this.disabled = false;
- /** @private */
- this.text = text;
- /** @private */
- this.loaded = false;
- this.closable = closable;
- /**
- * The body element for this TabPanelItem.
- * @type Roo.Element
- */
- this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
- this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
- this.bodyEl.setStyle("display", "block");
- this.bodyEl.setStyle("zoom", "1");
- this.hideAction();
+ var maxPaddingLeft = this.canvasEl.width / 0.9 * 0.05;
+ var maxPaddingTop = maxPaddingLeft * this.minHeight / this.minWidth;
- var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
- /** @private */
- this.el = Roo.get(els.el, true);
- this.inner = Roo.get(els.inner, true);
- this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
- this.pnode = Roo.get(els.el.parentNode, true);
- this.el.on("mousedown", this.onTabMouseDown, this);
- this.el.on("click", this.onTabClick, this);
- /** @private */
- if(closable){
- var c = Roo.get(els.close, true);
- c.dom.title = this.closeText;
- c.addClassOnOver("close-over");
- c.on("click", this.closeClick, this);
- }
+ if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight <= this.minWidth / this.minHeight)) {
+ maxPaddingLeft = (this.canvasEl.height * this.minWidth / this.minHeight - this.canvasEl.width) / 2 + maxPaddingLeft;
+ }
- this.addEvents({
- /**
- * @event activate
- * Fires when this tab becomes the active tab.
- * @param {Roo.TabPanel} tabPanel The parent TabPanel
- * @param {Roo.TabPanelItem} this
- */
- "activate": true,
- /**
- * @event beforeclose
- * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
- * @param {Roo.TabPanelItem} this
- * @param {Object} e Set cancel to true on this object to cancel the close.
- */
- "beforeclose": true,
- /**
- * @event close
- * Fires when this tab is closed.
- * @param {Roo.TabPanelItem} this
- */
- "close": true,
- /**
- * @event deactivate
- * Fires when this tab is no longer the active tab.
- * @param {Roo.TabPanel} tabPanel The parent TabPanel
- * @param {Roo.TabPanelItem} this
- */
- "deactivate" : true
- });
- this.hidden = false;
+ if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight >= this.minWidth / this.minHeight)) {
+ maxPaddingTop = (this.canvasEl.width * this.minHeight / this.minWidth - this.canvasEl.height) / 2 + maxPaddingTop;
+ }
+
+ var minX = Math.ceil(this.thumbEl.getLeft(true) + this.thumbEl.getWidth() - this.canvasEl.width - maxPaddingLeft);
+ var minY = Math.ceil(this.thumbEl.getTop(true) + this.thumbEl.getHeight() - this.canvasEl.height - maxPaddingTop);
+
+ var maxX = Math.ceil(this.thumbEl.getLeft(true) + maxPaddingLeft);
+ var maxY = Math.ceil(this.thumbEl.getTop(true) + maxPaddingTop);
- Roo.TabPanelItem.superclass.constructor.call(this);
-};
+ if(minX > maxX) {
+ var tempX = minX;
+ minX = maxX;
+ maxX = tempX;
+ }
-Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
- purgeListeners : function(){
- Roo.util.Observable.prototype.purgeListeners.call(this);
- this.el.removeAllListeners();
- },
- /**
- * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
- */
- show : function(){
- this.pnode.addClass("on");
- this.showAction();
- if(Roo.isOpera){
- this.tabPanel.stripWrap.repaint();
+ if(minY > maxY) {
+ var tempY = minY;
+ minY = maxY;
+ maxY = tempY;
}
- this.fireEvent("activate", this.tabPanel, this);
- },
- /**
- * Returns true if this tab is the active tab.
- * @return {Boolean}
- */
- isActive : function(){
- return this.tabPanel.getActiveTab() == this;
- },
+ var x = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
+ var y = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
+
+ x = x - this.mouseX;
+ y = y - this.mouseY;
- /**
- * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
- */
- hide : function(){
- this.pnode.removeClass("on");
- this.hideAction();
- this.fireEvent("deactivate", this.tabPanel, this);
+ var bgX = Math.ceil(x + this.previewEl.getLeft(true));
+ var bgY = Math.ceil(y + this.previewEl.getTop(true));
+
+ bgX = (bgX < minX) ? minX : ((bgX > maxX) ? maxX : bgX);
+ bgY = (bgY < minY) ? minY : ((bgY > maxY) ? maxY : bgY);
+
+ this.previewEl.setLeft(bgX);
+ this.previewEl.setTop(bgY);
+
+ this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
+ this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
},
-
- hideAction : function(){
- this.bodyEl.hide();
- this.bodyEl.setStyle("position", "absolute");
- this.bodyEl.setLeft("-20000px");
- this.bodyEl.setTop("-20000px");
+
+ onMouseUp : function(e)
+ {
+ e.stopEvent();
+
+ this.dragable = false;
},
+
+ onMouseWheel : function(e)
+ {
+ e.stopEvent();
+
+ this.startScale = this.scale;
+ this.scale = (e.getWheelDelta() > 0) ? (this.scale + 1) : (this.scale - 1);
+
+ if(!this.zoomable()){
+ this.scale = this.startScale;
+ return;
+ }
- showAction : function(){
- this.bodyEl.setStyle("position", "relative");
- this.bodyEl.setTop("");
- this.bodyEl.setLeft("");
- this.bodyEl.show();
+
+ this.draw();
+
+ return;
},
-
- /**
- * Set the tooltip for the tab.
- * @param {String} tooltip The tab's tooltip
- */
- setTooltip : function(text){
- if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
- this.textEl.dom.qtip = text;
- this.textEl.dom.removeAttribute('title');
- }else{
- this.textEl.dom.title = text;
+
+ zoomable : function()
+ {
+ var minScale = this.thumbEl.getWidth() / this.minWidth;
+
+ if(this.minWidth < this.minHeight){
+ minScale = this.thumbEl.getHeight() / this.minHeight;
}
- },
+
+ var width = Math.ceil(this.imageEl.OriginWidth * this.getScaleLevel() / minScale);
+ var height = Math.ceil(this.imageEl.OriginHeight * this.getScaleLevel() / minScale);
+
+ var maxWidth = this.imageEl.OriginWidth;
+ var maxHeight = this.imageEl.OriginHeight;
- onTabClick : function(e){
- e.preventDefault();
- this.tabPanel.activate(this.id);
- },
- onTabMouseDown : function(e){
- e.preventDefault();
- this.tabPanel.activate(this.id);
- },
+ var newCanvasWidth = Math.floor(this.imageEl.OriginWidth * this.getScaleLevel());
+ var newCanvasHeight = Math.floor(this.imageEl.OriginHeight * this.getScaleLevel());
- getWidth : function(){
- return this.inner.getWidth();
- },
+ var oldCenterLeft = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
+ var oldCenterTop = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
- setWidth : function(width){
- var iwidth = width - this.pnode.getPadding("lr");
- this.inner.setWidth(iwidth);
- this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
- this.pnode.setWidth(width);
- },
+ var newCenterLeft = Math.ceil((this.bodyEl.getWidth() - newCanvasWidth) / 2);
+ var newCenterTop = Math.ceil((this.bodyEl.getHeight() - newCanvasHeight) / 2);
- /**
- * Show or hide the tab
- * @param {Boolean} hidden True to hide or false to show.
- */
- setHidden : function(hidden){
- this.hidden = hidden;
- this.pnode.setStyle("display", hidden ? "none" : "");
- },
+ var leftDiff = newCenterLeft - oldCenterLeft;
+ var topDiff = newCenterTop - oldCenterTop;
- /**
- * Returns true if this tab is "hidden"
- * @return {Boolean}
- */
- isHidden : function(){
- return this.hidden;
- },
+ var newPreviewLeft = this.previewEl.getLeft(true) + leftDiff;
+ var newPreviewTop = this.previewEl.getTop(true) + topDiff;
- /**
- * Returns the text for this tab
- * @return {String}
- */
- getText : function(){
- return this.text;
- },
+ var paddingLeft = newPreviewLeft - this.thumbEl.getLeft(true);
+ var paddingTop = newPreviewTop - this.thumbEl.getTop(true);
- autoSize : function(){
- //this.el.beginMeasure();
- this.textEl.setWidth(1);
- /*
- * #2804 [new] Tabs in Roojs
- * increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
- */
- this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
- //this.el.endMeasure();
- },
+ var paddingRight = this.thumbEl.getLeft(true) + this.thumbEl.getWidth() - newCanvasWidth - newPreviewLeft;
+ var paddingBottom = this.thumbEl.getTop(true) + this.thumbEl.getHeight() - newCanvasHeight - newPreviewTop;
- /**
- * Sets the text for the tab (Note: this also sets the tooltip text)
- * @param {String} text The tab's text and tooltip
- */
- setText : function(text){
- this.text = text;
- this.textEl.update(text);
- this.setTooltip(text);
- if(!this.tabPanel.resizeTabs){
- this.autoSize();
- }
- },
- /**
- * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
- */
- activate : function(){
- this.tabPanel.activate(this.id);
- },
+ var maxPaddingLeft = newCanvasWidth / 0.9 * 0.05;
+ var maxPaddingTop = maxPaddingLeft * this.minHeight / this.minWidth;
- /**
- * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
- */
- disable : function(){
- if(this.tabPanel.active != this){
- this.disabled = true;
- this.pnode.addClass("disabled");
+ if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight <= this.minWidth / this.minHeight)) {
+ maxPaddingLeft = (newCanvasHeight * this.minWidth / this.minHeight - newCanvasWidth) / 2 + maxPaddingLeft;
}
- },
- /**
- * Enables this TabPanelItem if it was previously disabled.
- */
- enable : function(){
- this.disabled = false;
- this.pnode.removeClass("disabled");
- },
-
- /**
- * Sets the content for this TabPanelItem.
- * @param {String} content The content
- * @param {Boolean} loadScripts true to look for and load scripts
- */
- setContent : function(content, loadScripts){
- this.bodyEl.update(content, loadScripts);
+ if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight >= this.minWidth / this.minHeight)) {
+ maxPaddingTop = (newCanvasWidth * this.minHeight / this.minWidth - newCanvasHeight) / 2 + maxPaddingTop;
+ }
+
+ if(
+ this.isDocument &&
+ (this.rotate == 0 || this.rotate == 180) &&
+ (
+ width > this.imageEl.OriginWidth ||
+ height > this.imageEl.OriginHeight ||
+ (width < this.minWidth && height < this.minHeight)
+ )
+ ){
+ return false;
+ }
+
+ if(
+ this.isDocument &&
+ (this.rotate == 90 || this.rotate == 270) &&
+ (
+ width > this.imageEl.OriginWidth ||
+ height > this.imageEl.OriginHeight ||
+ (width < this.minHeight && height < this.minWidth)
+ )
+ ){
+ return false;
+ }
+
+ if(
+ !this.isDocument &&
+ (this.rotate == 0 || this.rotate == 180) &&
+ (
+ // for zoom out
+ paddingLeft > maxPaddingLeft ||
+ paddingRight > maxPaddingLeft ||
+ paddingTop > maxPaddingTop ||
+ paddingBottom > maxPaddingTop ||
+ // for zoom in
+ width > maxWidth ||
+ height > maxHeight
+ )
+ ){
+ return false;
+ }
+
+ if(
+ !this.isDocument &&
+ (this.rotate == 90 || this.rotate == 270) &&
+ (
+ width < this.minHeight ||
+ width > this.imageEl.OriginWidth ||
+ height < this.minWidth ||
+ height > this.imageEl.OriginHeight
+ )
+ ){
+ return false;
+ }
+
+ return true;
+
},
+
+ onRotateLeft : function(e)
+ {
+ if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
+
+ var minScale = this.thumbEl.getWidth() / this.minWidth;
+
+ var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
+ var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
+
+ this.startScale = this.scale;
+
+ while (this.getScaleLevel() < minScale){
+
+ this.scale = this.scale + 1;
+
+ if(!this.zoomable()){
+ break;
+ }
+
+ if(
+ Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
+ Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
+ ){
+ continue;
+ }
+
+ this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
- /**
- * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
- * @return {Roo.UpdateManager} The UpdateManager
- */
- getUpdateManager : function(){
- return this.bodyEl.getUpdateManager();
- },
+ this.draw();
+
+ return;
+ }
+
+ this.scale = this.startScale;
+
+ this.onRotateFail();
+
+ return false;
+ }
+
+ this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
- /**
- * Set a URL to be used to load the content for this TabPanelItem.
- * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
- * @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)
- * @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)
- * @return {Roo.UpdateManager} The UpdateManager
- */
- setUrl : function(url, params, loadOnce){
- if(this.refreshDelegate){
- this.un('activate', this.refreshDelegate);
+ if(this.isDocument){
+ this.setThumbBoxSize();
+ this.setThumbBoxPosition();
+ this.setCanvasPosition();
}
- this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
- this.on("activate", this.refreshDelegate);
- return this.bodyEl.getUpdateManager();
+
+ this.draw();
+
+ this.fireEvent('rotate', this, 'left');
+
},
+
+ onRotateRight : function(e)
+ {
+ if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
+
+ var minScale = this.thumbEl.getWidth() / this.minWidth;
+
+ var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
+ var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
+
+ this.startScale = this.scale;
+
+ while (this.getScaleLevel() < minScale){
+
+ this.scale = this.scale + 1;
+
+ if(!this.zoomable()){
+ break;
+ }
+
+ if(
+ Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
+ Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
+ ){
+ continue;
+ }
+
+ this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
- /** @private */
- _handleRefresh : function(url, params, loadOnce){
- if(!loadOnce || !this.loaded){
- var updater = this.bodyEl.getUpdateManager();
- updater.update(url, params, this._setLoaded.createDelegate(this));
+ this.draw();
+
+ return;
+ }
+
+ this.scale = this.startScale;
+
+ this.onRotateFail();
+
+ return false;
}
- },
+
+ this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
- /**
- * Forces a content refresh from the URL specified in the {@link #setUrl} method.
- * Will fail silently if the setUrl method has not been called.
- * This does not activate the panel, just updates its content.
- */
- refresh : function(){
- if(this.refreshDelegate){
- this.loaded = false;
- this.refreshDelegate();
+ if(this.isDocument){
+ this.setThumbBoxSize();
+ this.setThumbBoxPosition();
+ this.setCanvasPosition();
}
+
+ this.draw();
+
+ this.fireEvent('rotate', this, 'right');
},
-
- /** @private */
- _setLoaded : function(){
- this.loaded = true;
+
+ onRotateFail : function()
+ {
+ this.errorEl.show(true);
+
+ var _this = this;
+
+ (function() { _this.errorEl.hide(true); }).defer(this.errorTimeout);
},
-
- /** @private */
- closeClick : function(e){
- var o = {};
- e.stopEvent();
- this.fireEvent("beforeclose", this, o);
- if(o.cancel !== true){
- this.tabPanel.removeTab(this.id);
+
+ draw : function()
+ {
+ this.previewEl.dom.innerHTML = '';
+
+ var canvasEl = document.createElement("canvas");
+
+ var contextEl = canvasEl.getContext("2d");
+
+ canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
+ canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
+ var center = this.imageEl.OriginWidth / 2;
+
+ if(this.imageEl.OriginWidth < this.imageEl.OriginHeight){
+ canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
+ canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
+ center = this.imageEl.OriginHeight / 2;
}
- },
- /**
- * The text displayed in the tooltip for the close icon.
- * @type String
- */
- closeText : "Close this tab"
-});
+
+ contextEl.scale(this.getScaleLevel(), this.getScaleLevel());
+
+ contextEl.translate(center, center);
+ contextEl.rotate(this.rotate * Math.PI / 180);
-/** @private */
-Roo.TabPanel.prototype.createStrip = function(container){
- var strip = document.createElement("div");
- strip.className = "x-tabs-wrap";
- container.appendChild(strip);
- return strip;
-};
-/** @private */
-Roo.TabPanel.prototype.createStripList = function(strip){
- // div wrapper for retard IE
- // returns the "tr" element.
- strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
- '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
- '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
- return strip.firstChild.firstChild.firstChild.firstChild;
-};
-/** @private */
-Roo.TabPanel.prototype.createBody = function(container){
- var body = document.createElement("div");
- Roo.id(body, "tab-body");
- Roo.fly(body).addClass("x-tabs-body");
- container.appendChild(body);
- return body;
-};
-/** @private */
-Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
- var body = Roo.getDom(id);
- if(!body){
- body = document.createElement("div");
- body.id = id;
- }
- Roo.fly(body).addClass("x-tabs-item-body");
- bodyEl.insertBefore(body, bodyEl.firstChild);
- return body;
-};
-/** @private */
-Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
- var td = document.createElement("td");
- stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
- //stripEl.appendChild(td);
- if(closable){
- td.className = "x-tabs-closable";
- if(!this.closeTpl){
- this.closeTpl = new Roo.Template(
- '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
- '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
- '<div unselectable="on" class="close-icon"> </div></em></span></a>'
- );
- }
- var el = this.closeTpl.overwrite(td, {"text": text});
- var close = el.getElementsByTagName("div")[0];
- var inner = el.getElementsByTagName("em")[0];
- return {"el": el, "close": close, "inner": inner};
- } else {
- if(!this.tabTpl){
- this.tabTpl = new Roo.Template(
- '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
- '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
- );
+ contextEl.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
+
+ this.canvasEl = document.createElement("canvas");
+
+ this.contextEl = this.canvasEl.getContext("2d");
+
+ switch (this.rotate) {
+ case 0 :
+
+ this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
+ this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
+
+ this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
+
+ break;
+ case 90 :
+
+ this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
+ this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
+
+ if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
+ 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);
+ break;
+ }
+
+ this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
+
+ break;
+ case 180 :
+
+ this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
+ this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
+
+ if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
+ 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);
+ break;
+ }
+
+ 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);
+
+ break;
+ case 270 :
+
+ this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
+ this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
+
+ if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
+ this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
+ break;
+ }
+
+ 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);
+
+ break;
+ default :
+ break;
}
- var el = this.tabTpl.overwrite(td, {"text": text});
- var inner = el.getElementsByTagName("em")[0];
- return {"el": el, "inner": inner};
- }
-};/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-/**
- * @class Roo.Button
- * @extends Roo.util.Observable
- * Simple Button class
- * @cfg {String} text The button text
- * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
- * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
- * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
- * @cfg {Object} scope The scope of the handler
- * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
- * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
- * @cfg {Boolean} hidden True to start hidden (defaults to false)
- * @cfg {Boolean} disabled True to start disabled (defaults to false)
- * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
- * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
- applies if enableToggle = true)
- * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
- * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
- an {@link Roo.util.ClickRepeater} config object (defaults to false).
- * @constructor
- * Create a new button
- * @param {Object} config The config object
- */
-Roo.Button = function(renderTo, config)
-{
- if (!config) {
- config = renderTo;
- renderTo = config.renderTo || false;
- }
-
- Roo.apply(this, config);
- this.addEvents({
- /**
- * @event click
- * Fires when this button is clicked
- * @param {Button} this
- * @param {EventObject} e The click event
- */
- "click" : true,
- /**
- * @event toggle
- * Fires when the "pressed" state of this button changes (only if enableToggle = true)
- * @param {Button} this
- * @param {Boolean} pressed
- */
- "toggle" : true,
- /**
- * @event mouseover
- * Fires when the mouse hovers over the button
- * @param {Button} this
- * @param {Event} e The event object
- */
- 'mouseover' : true,
- /**
- * @event mouseout
- * Fires when the mouse exits the button
- * @param {Button} this
- * @param {Event} e The event object
- */
- 'mouseout': true,
- /**
- * @event render
- * Fires when the button is rendered
- * @param {Button} this
- */
- 'render': true
- });
- if(this.menu){
- this.menu = Roo.menu.MenuMgr.get(this.menu);
- }
- // register listeners first!! - so render can be captured..
- Roo.util.Observable.call(this);
- if(renderTo){
- this.render(renderTo);
- }
+
+ this.previewEl.appendChild(this.canvasEl);
+
+ this.setCanvasPosition(false);
+ },
-
-};
+ crop : function()
+ {
+ if(!this.canvasLoaded){
+ return;
+ }
+
+ var imageCanvas = document.createElement("canvas");
+
+ var imageContext = imageCanvas.getContext("2d");
+
+ imageCanvas.width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
+ imageCanvas.height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
+
+ var center = imageCanvas.width / 2;
+
+ imageContext.translate(center, center);
+
+ imageContext.rotate(this.rotate * Math.PI / 180);
+
+ imageContext.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
+
+ var canvas = document.createElement("canvas");
+
+ var context = canvas.getContext("2d");
-Roo.extend(Roo.Button, Roo.util.Observable, {
- /**
- *
- */
-
- /**
- * Read-only. True if this button is hidden
- * @type Boolean
- */
- hidden : false,
- /**
- * Read-only. True if this button is disabled
- * @type Boolean
- */
- disabled : false,
- /**
- * Read-only. True if this button is pressed (only if enableToggle = true)
- * @type Boolean
- */
- pressed : false,
+ canvas.width = this.thumbEl.getWidth() / this.getScaleLevel();
+
+ canvas.height = this.thumbEl.getHeight() / this.getScaleLevel();
- /**
- * @cfg {Number} tabIndex
- * The DOM tabIndex for this button (defaults to undefined)
- */
- tabIndex : undefined,
+ switch (this.rotate) {
+ case 0 :
+
+ var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
+ var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
+
+ var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
+ var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
+
+ var sx = this.thumbEl.getLeft(true) - this.previewEl.getLeft(true);
+ var sy = this.thumbEl.getTop(true) - this.previewEl.getTop(true);
- /**
- * @cfg {Boolean} enableToggle
- * True to enable pressed/not pressed toggling (defaults to false)
- */
- enableToggle: false,
- /**
- * @cfg {Roo.menu.Menu} menu
- * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
- */
- menu : undefined,
- /**
- * @cfg {String} menuAlign
- * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
- */
- menuAlign : "tl-bl?",
+ sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
+ sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
- /**
- * @cfg {String} iconCls
- * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
- */
- iconCls : undefined,
- /**
- * @cfg {String} type
- * The button's type, corresponding to the DOM input element type attribute. Either "submit," "reset" or "button" (default).
- */
- type : 'button',
+ if(canvas.width > this.outputMaxWidth) {
+ var scale = this.outputMaxWidth / canvas.width;
+ canvas.width = canvas.width * scale;
+ canvas.height = canvas.height * scale;
+ context.scale(scale, scale);
+ }
- // private
- menuClassTarget: 'tr',
+ context.fillStyle = 'white';
+ context.fillRect(0, 0, this.thumbEl.getWidth() / this.getScaleLevel(), this.thumbEl.getHeight() / this.getScaleLevel());
- /**
- * @cfg {String} clickEvent
- * The type of event to map to the button's event handler (defaults to 'click')
- */
- clickEvent : 'click',
- /**
- * @cfg {Boolean} handleMouseEvents
- * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
- */
- handleMouseEvents : true,
+ context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
+
+ break;
+ case 90 :
+
+ var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
+ var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
+
+ var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
+ var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
+
+ var targetWidth = this.minWidth - 2 * x;
+ var targetHeight = this.minHeight - 2 * y;
+
+ var scale = 1;
+
+ if((x == 0 && y == 0) || (x == 0 && y > 0)){
+ scale = targetWidth / width;
+ }
+
+ if(x > 0 && y == 0){
+ scale = targetHeight / height;
+ }
+
+ if(x > 0 && y > 0){
+ scale = targetWidth / width;
+
+ if(width < height){
+ scale = targetHeight / height;
+ }
+ }
+
+ context.scale(scale, scale);
+
+ var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
+ var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
- /**
- * @cfg {String} tooltipType
- * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
- */
- tooltipType : 'qtip',
+ sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
+ sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
+
+ sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
+
+ context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
+
+ break;
+ case 180 :
+
+ var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
+ var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
+
+ var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
+ var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
+
+ var targetWidth = this.minWidth - 2 * x;
+ var targetHeight = this.minHeight - 2 * y;
+
+ var scale = 1;
+
+ if((x == 0 && y == 0) || (x == 0 && y > 0)){
+ scale = targetWidth / width;
+ }
+
+ if(x > 0 && y == 0){
+ scale = targetHeight / height;
+ }
+
+ if(x > 0 && y > 0){
+ scale = targetWidth / width;
+
+ if(width < height){
+ scale = targetHeight / height;
+ }
+ }
+
+ context.scale(scale, scale);
+
+ var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
+ var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
- /**
- * @cfg {String} cls
- * A CSS class to apply to the button's main element.
- */
-
- /**
- * @cfg {Roo.Template} template (Optional)
- * An {@link Roo.Template} with which to create the Button's main element. This Template must
- * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
- * require code modifications if required elements (e.g. a button) aren't present.
- */
+ sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
+ sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
- // private
- render : function(renderTo){
- var btn;
- if(this.hideParent){
- this.parentEl = Roo.get(renderTo);
- }
- if(!this.dhconfig){
- if(!this.template){
- if(!Roo.Button.buttonTemplate){
- // hideous table template
- Roo.Button.buttonTemplate = new Roo.Template(
- '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
- '<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>',
- "</tr></tbody></table>");
+ sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
+ sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
+
+ context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
+
+ break;
+ case 270 :
+
+ var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
+ var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
+
+ var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
+ var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
+
+ var targetWidth = this.minWidth - 2 * x;
+ var targetHeight = this.minHeight - 2 * y;
+
+ var scale = 1;
+
+ if((x == 0 && y == 0) || (x == 0 && y > 0)){
+ scale = targetWidth / width;
}
- this.template = Roo.Button.buttonTemplate;
- }
- btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
- var btnEl = btn.child("button:first");
- btnEl.on('focus', this.onFocus, this);
- btnEl.on('blur', this.onBlur, this);
- if(this.cls){
- btn.addClass(this.cls);
- }
- if(this.icon){
- btnEl.setStyle('background-image', 'url(' +this.icon +')');
- }
- if(this.iconCls){
- btnEl.addClass(this.iconCls);
- if(!this.cls){
- btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
+
+ if(x > 0 && y == 0){
+ scale = targetHeight / height;
}
- }
- if(this.tabIndex !== undefined){
- btnEl.dom.tabIndex = this.tabIndex;
- }
- if(this.tooltip){
- if(typeof this.tooltip == 'object'){
- Roo.QuickTips.tips(Roo.apply({
- target: btnEl.id
- }, this.tooltip));
- } else {
- btnEl.dom[this.tooltipType] = this.tooltip;
+
+ if(x > 0 && y > 0){
+ scale = targetWidth / width;
+
+ if(width < height){
+ scale = targetHeight / height;
+ }
}
- }
- }else{
- btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
- }
- this.el = btn;
- if(this.id){
- this.el.dom.id = this.el.id = this.id;
- }
- if(this.menu){
- this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
- this.menu.on("show", this.onMenuShow, this);
- this.menu.on("hide", this.onMenuHide, this);
- }
- btn.addClass("x-btn");
- if(Roo.isIE && !Roo.isIE7){
- this.autoWidth.defer(1, this);
- }else{
- this.autoWidth();
- }
- if(this.handleMouseEvents){
- btn.on("mouseover", this.onMouseOver, this);
- btn.on("mouseout", this.onMouseOut, this);
- btn.on("mousedown", this.onMouseDown, this);
- }
- btn.on(this.clickEvent, this.onClick, this);
- //btn.on("mouseup", this.onMouseUp, this);
- if(this.hidden){
- this.hide();
- }
- if(this.disabled){
- this.disable();
+
+ context.scale(scale, scale);
+ var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
+ var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
+
+ sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
+ sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
+
+ sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
+
+ context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
+
+ break;
+ default :
+ break;
}
- Roo.ButtonToggleMgr.register(this);
- if(this.pressed){
- this.el.addClass("x-btn-pressed");
+
+ this.cropData = canvas.toDataURL(this.cropType);
+
+ if(this.fireEvent('crop', this, this.cropData) !== false){
+ this.process(this.file, this.cropData);
}
- if(this.repeat){
- var repeater = new Roo.util.ClickRepeater(btn,
- typeof this.repeat == "object" ? this.repeat : {}
- );
- repeater.on("click", this.onClick, this);
+
+ return;
+
+ },
+
+ setThumbBoxSize : function()
+ {
+ var width, height;
+
+ if(this.isDocument && typeof(this.imageEl) != 'undefined'){
+ width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.max(this.minWidth, this.minHeight) : Math.min(this.minWidth, this.minHeight);
+ height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.min(this.minWidth, this.minHeight) : Math.max(this.minWidth, this.minHeight);
+
+ this.minWidth = width;
+ this.minHeight = height;
+
+ if(this.rotate == 90 || this.rotate == 270){
+ this.minWidth = height;
+ this.minHeight = width;
+ }
}
- this.fireEvent('render', this);
+ height = this.windowSize;
+ width = Math.ceil(this.minWidth * height / this.minHeight);
+
+ if(this.minWidth > this.minHeight){
+ width = this.windowSize;
+ height = Math.ceil(this.minHeight * width / this.minWidth);
+ }
+ this.thumbEl.setStyle({
+ width : width + 'px',
+ height : height + 'px'
+ });
+
+ return;
+
},
- /**
- * Returns the button's underlying element
- * @return {Roo.Element} The element
- */
- getEl : function(){
- return this.el;
+
+ setThumbBoxPosition : function()
+ {
+ var x = Math.ceil((this.bodyEl.getWidth() - this.thumbEl.getWidth()) / 2 );
+ var y = Math.ceil((this.bodyEl.getHeight() - this.thumbEl.getHeight()) / 2);
+
+ this.thumbEl.setLeft(x);
+ this.thumbEl.setTop(y);
+
},
- /**
- * Destroys this Button and removes any listeners.
- */
- destroy : function(){
- Roo.ButtonToggleMgr.unregister(this);
- this.el.removeAllListeners();
- this.purgeListeners();
- this.el.remove();
+ baseRotateLevel : function()
+ {
+ this.baseRotate = 1;
+
+ if(
+ typeof(this.exif) != 'undefined' &&
+ typeof(this.exif[Roo.panel.Cropbox['tags']['Orientation']]) != 'undefined' &&
+ [1, 3, 6, 8].indexOf(this.exif[Roo.panel.Cropbox['tags']['Orientation']]) != -1
+ ){
+ this.baseRotate = this.exif[Roo.panel.Cropbox['tags']['Orientation']];
+ }
+
+ this.rotate = Roo.panel.Cropbox['Orientation'][this.baseRotate];
+
},
+
+ baseScaleLevel : function()
+ {
+ var width, height;
+
+ if(this.isDocument){
+
+ if(this.baseRotate == 6 || this.baseRotate == 8){
+
+ height = this.thumbEl.getHeight();
+ this.baseScale = height / this.imageEl.OriginWidth;
- // private
- autoWidth : function(){
- if(this.el){
- this.el.setWidth("auto");
- if(Roo.isIE7 && Roo.isStrict){
- var ib = this.el.child('button');
- if(ib && ib.getWidth() > 20){
- ib.clip();
- ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
+ if(this.imageEl.OriginHeight * this.baseScale > this.thumbEl.getWidth()){
+ width = this.thumbEl.getWidth();
+ this.baseScale = width / this.imageEl.OriginHeight;
}
+
+ return;
}
- if(this.minWidth){
- if(this.hidden){
- this.el.beginMeasure();
- }
- if(this.el.getWidth() < this.minWidth){
- this.el.setWidth(this.minWidth);
- }
- if(this.hidden){
- this.el.endMeasure();
+
+ height = this.thumbEl.getHeight();
+ this.baseScale = height / this.imageEl.OriginHeight;
+
+ if(this.imageEl.OriginWidth * this.baseScale > this.thumbEl.getWidth()){
+ width = this.thumbEl.getWidth();
+ this.baseScale = width / this.imageEl.OriginWidth;
+ }
+
+ return;
+ }
+
+ if(this.baseRotate == 6 || this.baseRotate == 8){
+
+ width = this.thumbEl.getHeight();
+ this.baseScale = width / this.imageEl.OriginHeight;
+
+ if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getWidth()){
+ height = this.thumbEl.getWidth();
+ this.baseScale = height / this.imageEl.OriginHeight;
+ }
+
+ if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
+ height = this.thumbEl.getWidth();
+ this.baseScale = height / this.imageEl.OriginHeight;
+
+ if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getHeight()){
+ width = this.thumbEl.getHeight();
+ this.baseScale = width / this.imageEl.OriginWidth;
}
}
+
+ return;
+ }
+
+ width = this.thumbEl.getWidth();
+ this.baseScale = width / this.imageEl.OriginWidth;
+
+ if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getHeight()){
+ height = this.thumbEl.getHeight();
+ this.baseScale = height / this.imageEl.OriginHeight;
+ }
+
+ if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
+
+ height = this.thumbEl.getHeight();
+ this.baseScale = height / this.imageEl.OriginHeight;
+
+ if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getWidth()){
+ width = this.thumbEl.getWidth();
+ this.baseScale = width / this.imageEl.OriginWidth;
+ }
+
}
- },
- /**
- * Assigns this button's click handler
- * @param {Function} handler The function to call when the button is clicked
- * @param {Object} scope (optional) Scope for the function passed in
- */
- setHandler : function(handler, scope){
- this.handler = handler;
- this.scope = scope;
- },
-
- /**
- * Sets this button's text
- * @param {String} text The button text
- */
- setText : function(text){
- this.text = text;
- if(this.el){
- this.el.child("td.x-btn-center button.x-btn-text").update(text);
+ if(this.imageEl.OriginWidth < this.minWidth || this.imageEl.OriginHeight < this.minHeight) {
+ this.baseScale = width / this.minWidth;
}
- this.autoWidth();
+
+ return;
},
- /**
- * Gets the text for this button
- * @return {String} The button text
- */
- getText : function(){
- return this.text;
+ getScaleLevel : function()
+ {
+ return this.baseScale * Math.pow(1.02, this.scale);
},
- /**
- * Show this button
- */
- show: function(){
- this.hidden = false;
- if(this.el){
- this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
+ onTouchStart : function(e)
+ {
+ if(!this.canvasLoaded){
+ this.beforeSelectFile(e);
+ return;
+ }
+
+ var touches = e.browserEvent.touches;
+
+ if(!touches){
+ return;
+ }
+
+ if(touches.length == 1){
+ this.onMouseDown(e);
+ return;
+ }
+
+ if(touches.length != 2){
+ return;
+ }
+
+ var coords = [];
+
+ for(var i = 0, finger; finger = touches[i]; i++){
+ coords.push(finger.pageX, finger.pageY);
}
+
+ var x = Math.pow(coords[0] - coords[2], 2);
+ var y = Math.pow(coords[1] - coords[3], 2);
+
+ this.startDistance = Math.sqrt(x + y);
+
+ this.startScale = this.scale;
+
+ this.pinching = true;
+ this.dragable = false;
+
},
- /**
- * Hide this button
- */
- hide: function(){
- this.hidden = true;
- if(this.el){
- this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
+ onTouchMove : function(e)
+ {
+ if(!this.pinching && !this.dragable){
+ return;
+ }
+
+ var touches = e.browserEvent.touches;
+
+ if(!touches){
+ return;
+ }
+
+ if(this.dragable){
+ this.onMouseMove(e);
+ return;
+ }
+
+ var coords = [];
+
+ for(var i = 0, finger; finger = touches[i]; i++){
+ coords.push(finger.pageX, finger.pageY);
+ }
+
+ var x = Math.pow(coords[0] - coords[2], 2);
+ var y = Math.pow(coords[1] - coords[3], 2);
+
+ this.endDistance = Math.sqrt(x + y);
+
+ this.scale = this.startScale + Math.floor(Math.log(this.endDistance / this.startDistance) / Math.log(1.1));
+
+ if(!this.zoomable()){
+ this.scale = this.startScale;
+ return;
}
+
+ this.draw();
+
},
- /**
- * Convenience function for boolean show/hide
- * @param {Boolean} visible True to show, false to hide
- */
- setVisible: function(visible){
- if(visible) {
- this.show();
- }else{
- this.hide();
- }
+ onTouchEnd : function(e)
+ {
+ this.pinching = false;
+ this.dragable = false;
+
},
- /**
- * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
- * @param {Boolean} state (optional) Force a particular state
- */
- toggle : function(state){
- state = state === undefined ? !this.pressed : state;
- if(state != this.pressed){
- if(state){
- this.el.addClass("x-btn-pressed");
- this.pressed = true;
- this.fireEvent("toggle", this, true);
- }else{
- this.el.removeClass("x-btn-pressed");
- this.pressed = false;
- this.fireEvent("toggle", this, false);
+ process : function(file, crop)
+ {
+ if(this.loadMask){
+ this.maskEl.mask(this.loadingText);
+ }
+
+ this.xhr = new XMLHttpRequest();
+
+ file.xhr = this.xhr;
+
+ this.xhr.open(this.method, this.url, true);
+
+ var headers = {
+ "Accept": "application/json",
+ "Cache-Control": "no-cache",
+ "X-Requested-With": "XMLHttpRequest"
+ };
+
+ for (var headerName in headers) {
+ var headerValue = headers[headerName];
+ if (headerValue) {
+ this.xhr.setRequestHeader(headerName, headerValue);
}
- if(this.toggleHandler){
- this.toggleHandler.call(this.scope || this, this, state);
+ }
+
+ var _this = this;
+
+ this.xhr.onload = function()
+ {
+ _this.xhrOnLoad(_this.xhr);
+ }
+
+ this.xhr.onerror = function()
+ {
+ _this.xhrOnError(_this.xhr);
+ }
+
+ var formData = new FormData();
+
+ formData.append('returnHTML', 'NO');
+
+ if(crop){
+ formData.append('crop', crop);
+ var blobBin = atob(crop.split(',')[1]);
+ var array = [];
+ for(var i = 0; i < blobBin.length; i++) {
+ array.push(blobBin.charCodeAt(i));
}
+ var croppedFile =new Blob([new Uint8Array(array)], {type: this.cropType});
+ formData.append(this.paramName, croppedFile, file.name);
+ }
+
+ if(typeof(file.filename) != 'undefined'){
+ formData.append('filename', file.filename);
+ }
+
+ if(typeof(file.mimetype) != 'undefined'){
+ formData.append('mimetype', file.mimetype);
}
+
+ if(this.fireEvent('arrange', this, formData) != false){
+ this.xhr.send(formData);
+ };
},
- /**
- * Focus the button
- */
- focus : function(){
- this.el.child('button:first').focus();
+ xhrOnLoad : function(xhr)
+ {
+ if(this.loadMask){
+ this.maskEl.unmask();
+ }
+
+ if (xhr.readyState !== 4) {
+ this.fireEvent('exception', this, xhr);
+ return;
+ }
+
+ var response = Roo.decode(xhr.responseText);
+
+ if(!response.success){
+ this.fireEvent('exception', this, xhr);
+ return;
+ }
+
+ var response = Roo.decode(xhr.responseText);
+
+ this.fireEvent('upload', this, response);
+
},
- /**
- * Disable this button
- */
- disable : function(){
- if(this.el){
- this.el.addClass("x-btn-disabled");
+ xhrOnError : function()
+ {
+ if(this.loadMask){
+ this.maskEl.unmask();
}
- this.disabled = true;
+
+ Roo.log('xhr on error');
+
+ var response = Roo.decode(xhr.responseText);
+
+ Roo.log(response);
+
},
- /**
- * Enable this button
- */
- enable : function(){
- if(this.el){
- this.el.removeClass("x-btn-disabled");
+ prepare : function(file)
+ {
+ if(this.loadMask){
+ this.maskEl.mask(this.loadingText);
}
- this.disabled = false;
- },
-
- /**
- * Convenience function for boolean enable/disable
- * @param {Boolean} enabled True to enable, false to disable
- */
- setDisabled : function(v){
- this[v !== true ? "enable" : "disable"]();
- },
-
- // private
- onClick : function(e)
- {
- if(e){
- e.preventDefault();
+
+ this.file = false;
+ this.exif = {};
+
+ if(typeof(file) === 'string'){
+ this.loadCanvas(file);
+ return;
}
- if(e.button != 0){
+
+ if(!file || !this.urlAPI){
return;
}
- if(!this.disabled){
- if(this.enableToggle){
- this.toggle();
- }
- if(this.menu && !this.menu.isVisible()){
- this.menu.show(this.el, this.menuAlign);
- }
- this.fireEvent("click", this, e);
- if(this.handler){
- this.el.removeClass("x-btn-over");
- this.handler.call(this.scope || this, this, e);
+
+ this.file = file;
+ if(typeof(file.type) != 'undefined' && file.type.length != 0) {
+ this.cropType = file.type;
+ }
+
+ var _this = this;
+
+ if(this.fireEvent('prepare', this, this.file) != false){
+
+ var reader = new FileReader();
+
+ reader.onload = function (e) {
+ if (e.target.error) {
+ Roo.log(e.target.error);
+ return;
+ }
+
+ var buffer = e.target.result,
+ dataView = new DataView(buffer),
+ offset = 2,
+ maxOffset = dataView.byteLength - 4,
+ markerBytes,
+ markerLength;
+
+ if (dataView.getUint16(0) === 0xffd8) {
+ while (offset < maxOffset) {
+ markerBytes = dataView.getUint16(offset);
+
+ if ((markerBytes >= 0xffe0 && markerBytes <= 0xffef) || markerBytes === 0xfffe) {
+ markerLength = dataView.getUint16(offset + 2) + 2;
+ if (offset + markerLength > dataView.byteLength) {
+ Roo.log('Invalid meta data: Invalid segment size.');
+ break;
+ }
+
+ if(markerBytes == 0xffe1){
+ _this.parseExifData(
+ dataView,
+ offset,
+ markerLength
+ );
+ }
+
+ offset += markerLength;
+
+ continue;
+ }
+
+ break;
+ }
+
+ }
+
+ var url = _this.urlAPI.createObjectURL(_this.file);
+
+ _this.loadCanvas(url);
+
+ return;
}
+
+ reader.readAsArrayBuffer(this.file);
+
}
+
},
- // private
- onMouseOver : function(e){
- if(!this.disabled){
- this.el.addClass("x-btn-over");
- this.fireEvent('mouseover', this, e);
+
+ parseExifData : function(dataView, offset, length)
+ {
+ var tiffOffset = offset + 10,
+ littleEndian,
+ dirOffset;
+
+ if (dataView.getUint32(offset + 4) !== 0x45786966) {
+ // No Exif data, might be XMP data instead
+ return;
}
- },
- // private
- onMouseOut : function(e){
- if(!e.within(this.el, true)){
- this.el.removeClass("x-btn-over");
- this.fireEvent('mouseout', this, e);
+
+ // Check for the ASCII code for "Exif" (0x45786966):
+ if (dataView.getUint32(offset + 4) !== 0x45786966) {
+ // No Exif data, might be XMP data instead
+ return;
}
- },
- // private
- onFocus : function(e){
- if(!this.disabled){
- this.el.addClass("x-btn-focus");
+ if (tiffOffset + 8 > dataView.byteLength) {
+ Roo.log('Invalid Exif data: Invalid segment size.');
+ return;
}
- },
- // private
- onBlur : function(e){
- this.el.removeClass("x-btn-focus");
- },
- // private
- onMouseDown : function(e){
- if(!this.disabled && e.button == 0){
- this.el.addClass("x-btn-click");
- Roo.get(document).on('mouseup', this.onMouseUp, this);
+ // Check for the two null bytes:
+ if (dataView.getUint16(offset + 8) !== 0x0000) {
+ Roo.log('Invalid Exif data: Missing byte alignment offset.');
+ return;
+ }
+ // Check the byte alignment:
+ switch (dataView.getUint16(tiffOffset)) {
+ case 0x4949:
+ littleEndian = true;
+ break;
+ case 0x4D4D:
+ littleEndian = false;
+ break;
+ default:
+ Roo.log('Invalid Exif data: Invalid byte alignment marker.');
+ return;
+ }
+ // Check for the TIFF tag marker (0x002A):
+ if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) {
+ Roo.log('Invalid Exif data: Missing TIFF marker.');
+ return;
}
+ // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
+ dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
+
+ this.parseExifTags(
+ dataView,
+ tiffOffset,
+ tiffOffset + dirOffset,
+ littleEndian
+ );
},
- // private
- onMouseUp : function(e){
- if(e.button == 0){
- this.el.removeClass("x-btn-click");
- Roo.get(document).un('mouseup', this.onMouseUp, this);
+
+ parseExifTags : function(dataView, tiffOffset, dirOffset, littleEndian)
+ {
+ var tagsNumber,
+ dirEndOffset,
+ i;
+ if (dirOffset + 6 > dataView.byteLength) {
+ Roo.log('Invalid Exif data: Invalid directory offset.');
+ return;
+ }
+ tagsNumber = dataView.getUint16(dirOffset, littleEndian);
+ dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
+ if (dirEndOffset + 4 > dataView.byteLength) {
+ Roo.log('Invalid Exif data: Invalid directory size.');
+ return;
+ }
+ for (i = 0; i < tagsNumber; i += 1) {
+ this.parseExifTag(
+ dataView,
+ tiffOffset,
+ dirOffset + 2 + 12 * i, // tag offset
+ littleEndian
+ );
}
+ // Return the offset to the next directory:
+ return dataView.getUint32(dirEndOffset, littleEndian);
},
- // private
- onMenuShow : function(e){
- this.el.addClass("x-btn-menu-active");
+
+ parseExifTag : function (dataView, tiffOffset, offset, littleEndian)
+ {
+ var tag = dataView.getUint16(offset, littleEndian);
+
+ this.exif[tag] = this.getExifValue(
+ dataView,
+ tiffOffset,
+ offset,
+ dataView.getUint16(offset + 2, littleEndian), // tag type
+ dataView.getUint32(offset + 4, littleEndian), // tag length
+ littleEndian
+ );
},
- // private
- onMenuHide : function(e){
- this.el.removeClass("x-btn-menu-active");
- }
+
+ getExifValue : function (dataView, tiffOffset, offset, type, length, littleEndian)
+ {
+ var tagType = Roo.panel.Cropbox.exifTagTypes[type],
+ tagSize,
+ dataOffset,
+ values,
+ i,
+ str,
+ c;
+
+ if (!tagType) {
+ Roo.log('Invalid Exif data: Invalid tag type.');
+ return;
+ }
+
+ tagSize = tagType.size * length;
+ // Determine if the value is contained in the dataOffset bytes,
+ // or if the value at the dataOffset is a pointer to the actual data:
+ dataOffset = tagSize > 4 ?
+ tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8);
+ if (dataOffset + tagSize > dataView.byteLength) {
+ Roo.log('Invalid Exif data: Invalid data offset.');
+ return;
+ }
+ if (length === 1) {
+ return tagType.getValue(dataView, dataOffset, littleEndian);
+ }
+ values = [];
+ for (i = 0; i < length; i += 1) {
+ values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian);
+ }
+
+ if (tagType.ascii) {
+ str = '';
+ // Concatenate the chars:
+ for (i = 0; i < values.length; i += 1) {
+ c = values[i];
+ // Ignore the terminating NULL byte(s):
+ if (c === '\u0000') {
+ break;
+ }
+ str += c;
+ }
+ return str;
+ }
+ return values;
+ }
+
});
-// Private utility class used by Button
-Roo.ButtonToggleMgr = function(){
- var groups = {};
-
- function toggleGroup(btn, state){
- if(state){
- var g = groups[btn.toggleGroup];
- for(var i = 0, l = g.length; i < l; i++){
- if(g[i] != btn){
- g[i].toggle(false);
- }
- }
- }
- }
-
- return {
- register : function(btn){
- if(!btn.toggleGroup){
- return;
- }
- var g = groups[btn.toggleGroup];
- if(!g){
- g = groups[btn.toggleGroup] = [];
- }
- g.push(btn);
- btn.on("toggle", toggleGroup);
- },
-
- unregister : function(btn){
- if(!btn.toggleGroup){
- return;
- }
- var g = groups[btn.toggleGroup];
- if(g){
- g.remove(btn);
- btn.un("toggle", toggleGroup);
- }
- }
- };
-}();/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-/**
- * @class Roo.SplitButton
- * @extends Roo.Button
- * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
- * click event of the button. Typically this would be used to display a dropdown menu that provides additional
- * options to the primary button action, but any custom handler can provide the arrowclick implementation.
- * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
- * @cfg {String} arrowTooltip The title attribute of the arrow
- * @constructor
- * Create a new menu button
- * @param {String/HTMLElement/Element} renderTo The element to append the button to
- * @param {Object} config The config object
- */
-Roo.SplitButton = function(renderTo, config){
- Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
- /**
- * @event arrowclick
- * Fires when this button's arrow is clicked
- * @param {SplitButton} this
- * @param {EventObject} e The click event
- */
- this.addEvents({"arrowclick":true});
-};
-
-Roo.extend(Roo.SplitButton, Roo.Button, {
- render : function(renderTo){
- // this is one sweet looking template!
- var tpl = new Roo.Template(
- '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
- '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
- '<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>',
- "</tbody></table></td><td>",
- '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
- '<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>',
- "</tbody></table></td></tr></table>"
- );
- var btn = tpl.append(renderTo, [this.text, this.type], true);
- var btnEl = btn.child("button");
- if(this.cls){
- btn.addClass(this.cls);
- }
- if(this.icon){
- btnEl.setStyle('background-image', 'url(' +this.icon +')');
- }
- if(this.iconCls){
- btnEl.addClass(this.iconCls);
- if(!this.cls){
- btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
- }
- }
- this.el = btn;
- if(this.handleMouseEvents){
- btn.on("mouseover", this.onMouseOver, this);
- btn.on("mouseout", this.onMouseOut, this);
- btn.on("mousedown", this.onMouseDown, this);
- btn.on("mouseup", this.onMouseUp, this);
- }
- btn.on(this.clickEvent, this.onClick, this);
- if(this.tooltip){
- if(typeof this.tooltip == 'object'){
- Roo.QuickTips.tips(Roo.apply({
- target: btnEl.id
- }, this.tooltip));
- } else {
- btnEl.dom[this.tooltipType] = this.tooltip;
- }
- }
- if(this.arrowTooltip){
- btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
- }
- if(this.hidden){
- this.hide();
- }
- if(this.disabled){
- this.disable();
- }
- if(this.pressed){
- this.el.addClass("x-btn-pressed");
- }
- if(Roo.isIE && !Roo.isIE7){
- this.autoWidth.defer(1, this);
- }else{
- this.autoWidth();
- }
- if(this.menu){
- this.menu.on("show", this.onMenuShow, this);
- this.menu.on("hide", this.onMenuHide, this);
- }
- this.fireEvent('render', this);
- },
-
- // private
- autoWidth : function(){
- if(this.el){
- var tbl = this.el.child("table:first");
- var tbl2 = this.el.child("table:last");
- this.el.setWidth("auto");
- tbl.setWidth("auto");
- if(Roo.isIE7 && Roo.isStrict){
- var ib = this.el.child('button:first');
- if(ib && ib.getWidth() > 20){
- ib.clip();
- ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
- }
- }
- if(this.minWidth){
- if(this.hidden){
- this.el.beginMeasure();
- }
- if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
- tbl.setWidth(this.minWidth-tbl2.getWidth());
- }
- if(this.hidden){
- this.el.endMeasure();
- }
- }
- this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
- }
- },
- /**
- * Sets this button's click handler
- * @param {Function} handler The function to call when the button is clicked
- * @param {Object} scope (optional) Scope for the function passed above
- */
- setHandler : function(handler, scope){
- this.handler = handler;
- this.scope = scope;
+Roo.apply(Roo.panel.Cropbox, {
+ tags : {
+ 'Orientation': 0x0112
},
- /**
- * Sets this button's arrow click handler
- * @param {Function} handler The function to call when the arrow is clicked
- * @param {Object} scope (optional) Scope for the function passed above
- */
- setArrowHandler : function(handler, scope){
- this.arrowHandler = handler;
- this.scope = scope;
+ Orientation: {
+ 1: 0, //'top-left',
+// 2: 'top-right',
+ 3: 180, //'bottom-right',
+// 4: 'bottom-left',
+// 5: 'left-top',
+ 6: 90, //'right-top',
+// 7: 'right-bottom',
+ 8: 270 //'left-bottom'
},
- /**
- * Focus the button
- */
- focus : function(){
- if(this.el){
- this.el.child("button:first").focus();
+ exifTagTypes : {
+ // byte, 8-bit unsigned int:
+ 1: {
+ getValue: function (dataView, dataOffset) {
+ return dataView.getUint8(dataOffset);
+ },
+ size: 1
+ },
+ // ascii, 8-bit byte:
+ 2: {
+ getValue: function (dataView, dataOffset) {
+ return String.fromCharCode(dataView.getUint8(dataOffset));
+ },
+ size: 1,
+ ascii: true
+ },
+ // short, 16 bit int:
+ 3: {
+ getValue: function (dataView, dataOffset, littleEndian) {
+ return dataView.getUint16(dataOffset, littleEndian);
+ },
+ size: 2
+ },
+ // long, 32 bit int:
+ 4: {
+ getValue: function (dataView, dataOffset, littleEndian) {
+ return dataView.getUint32(dataOffset, littleEndian);
+ },
+ size: 4
+ },
+ // rational = two long values, first is numerator, second is denominator:
+ 5: {
+ getValue: function (dataView, dataOffset, littleEndian) {
+ return dataView.getUint32(dataOffset, littleEndian) /
+ dataView.getUint32(dataOffset + 4, littleEndian);
+ },
+ size: 8
+ },
+ // slong, 32 bit signed int:
+ 9: {
+ getValue: function (dataView, dataOffset, littleEndian) {
+ return dataView.getInt32(dataOffset, littleEndian);
+ },
+ size: 4
+ },
+ // srational, two slongs, first is numerator, second is denominator:
+ 10: {
+ getValue: function (dataView, dataOffset, littleEndian) {
+ return dataView.getInt32(dataOffset, littleEndian) /
+ dataView.getInt32(dataOffset + 4, littleEndian);
+ },
+ size: 8
}
},
-
- // private
- onClick : function(e){
- e.preventDefault();
- if(!this.disabled){
- if(e.getTarget(".x-btn-menu-arrow-wrap")){
- if(this.menu && !this.menu.isVisible()){
- this.menu.show(this.el, this.menuAlign);
- }
- this.fireEvent("arrowclick", this, e);
- if(this.arrowHandler){
- this.arrowHandler.call(this.scope || this, this, e);
- }
- }else{
- this.fireEvent("click", this, e);
- if(this.handler){
- this.handler.call(this.scope || this, this, e);
- }
+
+ footer : {
+ STANDARD : [
+ {
+ tag : 'div',
+ cls : 'btn-group roo-upload-cropbox-rotate-left',
+ action : 'rotate-left',
+ cn : [
+ {
+ tag : 'button',
+ cls : 'btn btn-default',
+ html : '<i class="fa fa-undo"></i>'
+ }
+ ]
+ },
+ {
+ tag : 'div',
+ cls : 'btn-group roo-upload-cropbox-picture',
+ action : 'picture',
+ cn : [
+ {
+ tag : 'button',
+ cls : 'btn btn-default',
+ html : '<i class="fa fa-picture-o"></i>'
+ }
+ ]
+ },
+ {
+ tag : 'div',
+ cls : 'btn-group roo-upload-cropbox-rotate-right',
+ action : 'rotate-right',
+ cn : [
+ {
+ tag : 'button',
+ cls : 'btn btn-default',
+ html : '<i class="fa fa-repeat"></i>'
+ }
+ ]
}
- }
- },
- // private
- onMouseDown : function(e){
- if(!this.disabled){
- Roo.fly(e.getTarget("table")).addClass("x-btn-click");
- }
- },
- // private
- onMouseUp : function(e){
- Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
- }
+ ],
+ DOCUMENT : [
+ {
+ tag : 'div',
+ cls : 'btn-group roo-upload-cropbox-rotate-left',
+ action : 'rotate-left',
+ cn : [
+ {
+ tag : 'button',
+ cls : 'btn btn-default',
+ html : '<i class="fa fa-undo"></i>'
+ }
+ ]
+ },
+ {
+ tag : 'div',
+ cls : 'btn-group roo-upload-cropbox-download',
+ action : 'download',
+ cn : [
+ {
+ tag : 'button',
+ cls : 'btn btn-default',
+ html : '<i class="fa fa-download"></i>'
+ }
+ ]
+ },
+ {
+ tag : 'div',
+ cls : 'btn-group roo-upload-cropbox-crop',
+ action : 'crop',
+ cn : [
+ {
+ tag : 'button',
+ cls : 'btn btn-default',
+ html : '<i class="fa fa-crop"></i>'
+ }
+ ]
+ },
+ {
+ tag : 'div',
+ cls : 'btn-group roo-upload-cropbox-trash',
+ action : 'trash',
+ cn : [
+ {
+ tag : 'button',
+ cls : 'btn btn-default',
+ html : '<i class="fa fa-trash"></i>'
+ }
+ ]
+ },
+ {
+ tag : 'div',
+ cls : 'btn-group roo-upload-cropbox-rotate-right',
+ action : 'rotate-right',
+ cn : [
+ {
+ tag : 'button',
+ cls : 'btn btn-default',
+ html : '<i class="fa fa-repeat"></i>'
+ }
+ ]
+ }
+ ],
+ ROTATOR : [
+ {
+ tag : 'div',
+ cls : 'btn-group roo-upload-cropbox-rotate-left',
+ action : 'rotate-left',
+ cn : [
+ {
+ tag : 'button',
+ cls : 'btn btn-default',
+ html : '<i class="fa fa-undo"></i>'
+ }
+ ]
+ },
+ {
+ tag : 'div',
+ cls : 'btn-group roo-upload-cropbox-rotate-right',
+ action : 'rotate-right',
+ cn : [
+ {
+ tag : 'button',
+ cls : 'btn btn-default',
+ html : '<i class="fa fa-repeat"></i>'
+ }
+ ]
+ }
+ ],
+ CENTER : [
+ {
+ tag : 'div',
+ cls : 'btn-group roo-upload-cropbox-center',
+ action : 'center',
+ cn : [
+ {
+ tag : 'button',
+ cls : 'btn btn-default',
+ html : 'CENTER'
+ }
+ ]
+ }
+ ]
+ }
});
-
-
-// backwards compat
-Roo.MenuButton = Roo.SplitButton;/*
+ /*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* Fork - LGPL
* <script type="text/javascript">
*/
-
/**
- * @class Roo.Toolbar
- * @children Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
- * Basic Toolbar class.
+ * @class Roo.panel.Tab
+ * @extends Roo.util.Observable
+ * A lightweight tab container.
+ * <br><br>
+ * Usage:
+ * <pre><code>
+// basic tabs 1, built from existing content
+var tabs = new Roo.panel.Tab("tabs1");
+tabs.addTab("script", "View Script");
+tabs.addTab("markup", "View Markup");
+tabs.activate("script");
+
+// more advanced tabs, built from javascript
+var jtabs = new Roo.panel.Tab("jtabs");
+jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
+
+// set up the UpdateManager
+var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
+var updater = tab2.getUpdateManager();
+updater.setDefaultUrl("ajax1.htm");
+tab2.on('activate', updater.refresh, updater, true);
+
+// Use setUrl for Ajax loading
+var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
+tab3.setUrl("ajax2.htm", null, true);
+
+// Disabled tab
+var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
+tab4.disable();
+
+jtabs.activate("jtabs-1");
+ * </code></pre>
* @constructor
- * Creates a new Toolbar
- * @param {Object} container The config object
- */
-Roo.Toolbar = function(container, buttons, config)
-{
- /// old consturctor format still supported..
- if(container instanceof Array){ // omit the container for later rendering
- buttons = container;
- config = buttons;
- container = null;
+ * Create a new TabPanel.
+ * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
+ * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
+ */
+Roo.panel.Tab = function(container, config){
+ /**
+ * The container element for this TabPanel.
+ * @type Roo.Element
+ */
+ this.el = Roo.get(container, true);
+ if(config){
+ if(typeof config == "boolean"){
+ this.tabPosition = config ? "bottom" : "top";
+ }else{
+ Roo.apply(this, config);
+ }
}
- if (typeof(container) == 'object' && container.xtype) {
- config = container;
- container = config.container;
- buttons = config.buttons || []; // not really - use items!!
+ if(this.tabPosition == "bottom"){
+ this.bodyEl = Roo.get(this.createBody(this.el.dom));
+ this.el.addClass("x-tabs-bottom");
}
- var xitems = [];
- if (config && config.items) {
- xitems = config.items;
- delete config.items;
+ this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
+ this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
+ this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
+ if(Roo.isIE){
+ Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
}
- Roo.apply(this, config);
- this.buttons = buttons;
-
- if(container){
- this.render(container);
+ if(this.tabPosition != "bottom"){
+ /** The body element that contains {@link Roo.panel.TabItem} bodies. +
+ * @type Roo.Element
+ */
+ this.bodyEl = Roo.get(this.createBody(this.el.dom));
+ this.el.addClass("x-tabs-top");
}
- this.xitems = xitems;
- Roo.each(xitems, function(b) {
- this.add(b);
- }, this);
-
+ this.items = [];
+
+ this.bodyEl.setStyle("position", "relative");
+
+ this.active = null;
+ this.activateDelegate = this.activate.createDelegate(this);
+
+ this.addEvents({
+ /**
+ * @event tabchange
+ * Fires when the active tab changes
+ * @param {Roo.panel.Tab} this
+ * @param {Roo.panel.TabItem} activePanel The new active tab
+ */
+ "tabchange": true,
+ /**
+ * @event beforetabchange
+ * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
+ * @param {Roo.panel.Tab} this
+ * @param {Object} e Set cancel to true on this object to cancel the tab change
+ * @param {Roo.panel.TabItem} tab The tab being changed to
+ */
+ "beforetabchange" : true
+ });
+
+ Roo.EventManager.onWindowResize(this.onResize, this);
+ this.cpad = this.el.getPadding("lr");
+ this.hiddenCount = 0;
+
+
+ // toolbar on the tabbar support...
+ if (this.toolbar) {
+ var tcfg = this.toolbar;
+ tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');
+ this.toolbar = new Roo.Toolbar(tcfg);
+ if (Roo.isSafari) {
+ var tbl = tcfg.container.child('table', true);
+ tbl.setAttribute('width', '100%');
+ }
+
+ }
+
+
+
+ Roo.panel.Tab.superclass.constructor.call(this);
};
-Roo.Toolbar.prototype = {
- /**
- * @cfg {Array} items
- * array of button configs or elements to add (will be converted to a MixedCollection)
+Roo.extend(Roo.panel.Tab, Roo.util.Observable, {
+ /*
+ *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
*/
- items: false,
+ tabPosition : "top",
+ /*
+ *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
+ */
+ currentTabWidth : 0,
+ /*
+ *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
+ */
+ minTabWidth : 40,
+ /*
+ *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
+ */
+ maxTabWidth : 250,
+ /*
+ *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
+ */
+ preferredTabWidth : 175,
+ /*
+ *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
+ */
+ resizeTabs : false,
+ /*
+ *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
+ */
+ monitorResize : true,
+ /*
+ *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar.
+ */
+ toolbar : false,
+
/**
- * @cfg {String/HTMLElement/Element} container
- * The id or element that will contain the toolbar
+ * 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.
+ * @param {String} id The id of the div to use <b>or create</b>
+ * @param {String} text The text for the tab
+ * @param {String} content (optional) Content to put in the TabPanelItem body
+ * @param {Boolean} closable (optional) True to create a close icon on the tab
+ * @return {Roo.panel.TabItem} The created TabPanelItem
*/
- // private
- render : function(ct){
- this.el = Roo.get(ct);
- if(this.cls){
- this.el.addClass(this.cls);
- }
- // using a table allows for vertical alignment
- // 100% width is needed by Safari...
- this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
- this.tr = this.el.child("tr", true);
- var autoId = 0;
- this.items = new Roo.util.MixedCollection(false, function(o){
- return o.id || ("item" + (++autoId));
- });
- if(this.buttons){
- this.add.apply(this, this.buttons);
- delete this.buttons;
+ addTab : function(id, text, content, closable){
+ var item = new Roo.panel.TabItem(this, id, text, closable);
+ this.addTabItem(item);
+ if(content){
+ item.setContent(content);
}
+ return item;
},
/**
- * Adds element(s) to the toolbar -- this function takes a variable number of
- * arguments of mixed type and adds them to the toolbar.
- * @param {Mixed} arg1 The following types of arguments are all valid:<br />
- * <ul>
- * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
- * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
- * <li>Field: Any form field (equivalent to {@link #addField})</li>
- * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
- * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
- * Note that there are a few special strings that are treated differently as explained nRoo.</li>
- * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
- * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
- * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
- * </ul>
- * @param {Mixed} arg2
- * @param {Mixed} etc.
+ * Returns the {@link Roo.panel.TabItem} with the specified id/index
+ * @param {String/Number} id The id or index of the TabPanelItem to fetch.
+ * @return {Roo.panel.TabItem}
*/
- add : function(){
- var a = arguments, l = a.length;
- for(var i = 0; i < l; i++){
- this._add(a[i]);
- }
+ getTab : function(id){
+ return this.items[id];
},
- // private..
- _add : function(el) {
-
- if (el.xtype) {
- el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
- }
-
- if (el.applyTo){ // some kind of form field
- return this.addField(el);
- }
- if (el.render){ // some kind of Toolbar.Item
- return this.addItem(el);
- }
- if (typeof el == "string"){ // string
- if(el == "separator" || el == "-"){
- return this.addSeparator();
- }
- if (el == " "){
- return this.addSpacer();
- }
- if(el == "->"){
- return this.addFill();
- }
- return this.addText(el);
-
- }
- if(el.tagName){ // element
- return this.addElement(el);
- }
- if(typeof el == "object"){ // must be button config?
- return this.addButton(el);
+
+ /**
+ * Hides the {@link Roo.panel.TabItem} with the specified id/index
+ * @param {String/Number} id The id or index of the TabPanelItem to hide.
+ */
+ hideTab : function(id){
+ var t = this.items[id];
+ if(!t.isHidden()){
+ t.setHidden(true);
+ this.hiddenCount++;
+ this.autoSizeTabs();
}
- // and now what?!?!
- return false;
-
},
-
+
/**
- * Add an Xtype element
- * @param {Object} xtype Xtype Object
- * @return {Object} created Object
+ * "Unhides" the {@link Roo.panel.TabItem} with the specified id/index.
+ * @param {String/Number} id The id or index of the TabPanelItem to unhide.
*/
- addxtype : function(e){
- return this.add(e);
+ unhideTab : function(id){
+ var t = this.items[id];
+ if(t.isHidden()){
+ t.setHidden(false);
+ this.hiddenCount--;
+ this.autoSizeTabs();
+ }
},
-
+
/**
- * Returns the Element for this toolbar.
- * @return {Roo.Element}
+ * Adds an existing {@link Roo.panel.TabItem}.
+ * @param {Roo.panel.TabItem} item The TabPanelItem to add
*/
- getEl : function(){
- return this.el;
- },
-
- /**
- * Adds a separator
- * @return {Roo.Toolbar.Item} The separator item
- */
- addSeparator : function(){
- return this.addItem(new Roo.Toolbar.Separator());
+ addTabItem : function(item){
+ this.items[item.id] = item;
+ this.items.push(item);
+ if(this.resizeTabs){
+ item.setWidth(this.currentTabWidth || this.preferredTabWidth);
+ this.autoSizeTabs();
+ }else{
+ item.autoSize();
+ }
},
/**
- * Adds a spacer element
- * @return {Roo.Toolbar.Spacer} The spacer item
+ * Removes a {@link Roo.panel.TabItem}.
+ * @param {String/Number} id The id or index of the TabPanelItem to remove.
*/
- addSpacer : function(){
- return this.addItem(new Roo.Toolbar.Spacer());
+ removeTab : function(id){
+ var items = this.items;
+ var tab = items[id];
+ if(!tab) { return; }
+ var index = items.indexOf(tab);
+ if(this.active == tab && items.length > 1){
+ var newTab = this.getNextAvailable(index);
+ if(newTab) {
+ newTab.activate();
+ }
+ }
+ this.stripEl.dom.removeChild(tab.pnode.dom);
+ if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
+ this.bodyEl.dom.removeChild(tab.bodyEl.dom);
+ }
+ items.splice(index, 1);
+ delete this.items[tab.id];
+ tab.fireEvent("close", tab);
+ tab.purgeListeners();
+ this.autoSizeTabs();
},
- /**
- * Adds a fill element that forces subsequent additions to the right side of the toolbar
- * @return {Roo.Toolbar.Fill} The fill item
- */
- addFill : function(){
- return this.addItem(new Roo.Toolbar.Fill());
+ getNextAvailable : function(start){
+ var items = this.items;
+ var index = start;
+ // look for a next tab that will slide over to
+ // replace the one being removed
+ while(index < items.length){
+ var item = items[++index];
+ if(item && !item.isHidden()){
+ return item;
+ }
+ }
+ // if one isn't found select the previous tab (on the left)
+ index = start;
+ while(index >= 0){
+ var item = items[--index];
+ if(item && !item.isHidden()){
+ return item;
+ }
+ }
+ return null;
},
/**
- * Adds any standard HTML element to the toolbar
- * @param {String/HTMLElement/Element} el The element or id of the element to add
- * @return {Roo.Toolbar.Item} The element's item
+ * Disables a {@link Roo.panel.TabItem}. It cannot be the active tab, if it is this call is ignored.
+ * @param {String/Number} id The id or index of the TabPanelItem to disable.
*/
- addElement : function(el){
- return this.addItem(new Roo.Toolbar.Item(el));
+ disableTab : function(id){
+ var tab = this.items[id];
+ if(tab && this.active != tab){
+ tab.disable();
+ }
},
+
/**
- * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
- * @type Roo.util.MixedCollection
- */
- items : false,
-
- /**
- * Adds any Toolbar.Item or subclass
- * @param {Roo.Toolbar.Item} item
- * @return {Roo.Toolbar.Item} The item
+ * Enables a {@link Roo.panel.TabItem} that is disabled.
+ * @param {String/Number} id The id or index of the TabPanelItem to enable.
*/
- addItem : function(item){
- var td = this.nextBlock();
- item.render(td);
- this.items.add(item);
- return item;
+ enableTab : function(id){
+ var tab = this.items[id];
+ tab.enable();
},
-
+
/**
- * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
- * @param {Object/Array} config A button config or array of configs
- * @return {Roo.Toolbar.Button/Array}
+ * Activates a {@link Roo.panel.TabItem}. The currently active one will be deactivated.
+ * @param {String/Number} id The id or index of the TabPanelItem to activate.
+ * @return {Roo.panel.TabItem} The TabPanelItem.
*/
- addButton : function(config){
- if(config instanceof Array){
- var buttons = [];
- for(var i = 0, len = config.length; i < len; i++) {
- buttons.push(this.addButton(config[i]));
- }
- return buttons;
+ activate : function(id){
+ var tab = this.items[id];
+ if(!tab){
+ return null;
}
- var b = config;
- if(!(config instanceof Roo.Toolbar.Button)){
- b = config.split ?
- new Roo.Toolbar.SplitButton(config) :
- new Roo.Toolbar.Button(config);
+ if(tab == this.active || tab.disabled){
+ return tab;
}
- var td = this.nextBlock();
- b.render(td);
- this.items.add(b);
- return b;
+ var e = {};
+ this.fireEvent("beforetabchange", this, e, tab);
+ if(e.cancel !== true && !tab.disabled){
+ if(this.active){
+ this.active.hide();
+ }
+ this.active = this.items[id];
+ this.active.show();
+ this.fireEvent("tabchange", this, this.active);
+ }
+ return tab;
},
-
+
/**
- * Adds text to the toolbar
- * @param {String} text The text to add
- * @return {Roo.Toolbar.Item} The element's item
+ * Gets the active {@link Roo.panel.TabItem}.
+ * @return {Roo.panel.TabItem} The active TabPanelItem or null if none are active.
*/
- addText : function(text){
- return this.addItem(new Roo.Toolbar.TextItem(text));
+ getActiveTab : function(){
+ return this.active;
},
-
+
/**
- * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
- * @param {Number} index The index where the item is to be inserted
- * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
- * @return {Roo.Toolbar.Button/Item}
+ * Updates the tab body element to fit the height of the container element
+ * for overflow scrolling
+ * @param {Number} targetHeight (optional) Override the starting height from the elements height
*/
- insertButton : function(index, item){
- if(item instanceof Array){
- var buttons = [];
- for(var i = 0, len = item.length; i < len; i++) {
- buttons.push(this.insertButton(index + i, item[i]));
- }
- return buttons;
- }
- if (!(item instanceof Roo.Toolbar.Button)){
- item = new Roo.Toolbar.Button(item);
+ syncHeight : function(targetHeight){
+ var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
+ var bm = this.bodyEl.getMargins();
+ var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
+ this.bodyEl.setHeight(newHeight);
+ return newHeight;
+ },
+
+ onResize : function(){
+ if(this.monitorResize){
+ this.autoSizeTabs();
}
- var td = document.createElement("td");
- this.tr.insertBefore(td, this.tr.childNodes[index]);
- item.render(td);
- this.items.insert(index, item);
- return item;
},
-
+
/**
- * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
- * @param {Object} config
- * @return {Roo.Toolbar.Item} The element's item
+ * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
*/
- addDom : function(config, returnEl){
- var td = this.nextBlock();
- Roo.DomHelper.overwrite(td, config);
- var ti = new Roo.Toolbar.Item(td.firstChild);
- ti.render(td);
- this.items.add(ti);
- return ti;
+ beginUpdate : function(){
+ this.updating = true;
},
/**
- * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
- * @type Roo.util.MixedCollection
+ * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
*/
- fields : false,
-
+ endUpdate : function(){
+ this.updating = false;
+ this.autoSizeTabs();
+ },
+
/**
- * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
- * Note: the field should not have been rendered yet. For a field that has already been
- * rendered, use {@link #addElement}.
- * @param {Roo.form.Field} field
- * @return {Roo.ToolbarItem}
+ * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
*/
-
-
- addField : function(field) {
- if (!this.fields) {
- var autoId = 0;
- this.fields = new Roo.util.MixedCollection(false, function(o){
- return o.id || ("item" + (++autoId));
- });
-
+ autoSizeTabs : function(){
+ var count = this.items.length;
+ var vcount = count - this.hiddenCount;
+ if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
+ return;
+ }
+ var w = Math.max(this.el.getWidth() - this.cpad, 10);
+ var availWidth = Math.floor(w / vcount);
+ var b = this.stripBody;
+ if(b.getWidth() > w){
+ var tabs = this.items;
+ this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
+ if(availWidth < this.minTabWidth){
+ /*if(!this.sleft){ // incomplete scrolling code
+ this.createScrollButtons();
+ }
+ this.showScroll();
+ this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
+ }
+ }else{
+ if(this.currentTabWidth < this.preferredTabWidth){
+ this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
+ }
}
-
- var td = this.nextBlock();
- field.render(td);
- var ti = new Roo.Toolbar.Item(td.firstChild);
- ti.render(td);
- this.items.add(ti);
- this.fields.add(field);
- return ti;
},
+
/**
- * Hide the toolbar
- * @method hide
+ * Returns the number of tabs in this TabPanel.
+ * @return {Number}
*/
-
-
- hide : function()
- {
- this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
- this.el.child('div').hide();
- },
+ getCount : function(){
+ return this.items.length;
+ },
+
/**
- * Show the toolbar
- * @method show
+ * Resizes all the tabs to the passed width
+ * @param {Number} The new width
*/
- show : function()
- {
- this.el.child('div').show();
- },
-
- // private
- nextBlock : function(){
- var td = document.createElement("td");
- this.tr.appendChild(td);
- return td;
+ setTabWidth : function(width){
+ this.currentTabWidth = width;
+ for(var i = 0, len = this.items.length; i < len; i++) {
+ if(!this.items[i].isHidden()) {
+ this.items[i].setWidth(width);
+ }
+ }
},
- // private
- destroy : function(){
- if(this.items){ // rendered?
- Roo.destroy.apply(Roo, this.items.items);
+ /**
+ * Destroys this TabPanel
+ * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
+ */
+ destroy : function(removeEl){
+ Roo.EventManager.removeResizeListener(this.onResize, this);
+ for(var i = 0, len = this.items.length; i < len; i++){
+ this.items[i].purgeListeners();
}
- if(this.fields){ // rendered?
- Roo.destroy.apply(Roo, this.fields.items);
+ if(removeEl === true){
+ this.el.update("");
+ this.el.remove();
}
- Roo.Element.uncache(this.el, this.tr);
}
-};
+});
-/**
- * @class Roo.Toolbar.Item
- * The base class that other classes should extend in order to get some basic common toolbar item functionality.
- * @constructor
- * Creates a new Item
- * @param {HTMLElement} el
- */
-Roo.Toolbar.Item = function(el){
- var cfg = {};
- if (typeof (el.xtype) != 'undefined') {
- cfg = el;
- el = cfg.el;
+
+/** @private */
+Roo.panel.Tab.prototype.createStripList = function(strip){
+ // div wrapper for retard IE
+ // returns the "tr" element.
+ strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
+ '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
+ '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
+ return strip.firstChild.firstChild.firstChild.firstChild;
+};
+/** @private */
+Roo.panel.Tab.prototype.createBody = function(container){
+ var body = document.createElement("div");
+ Roo.id(body, "tab-body");
+ Roo.fly(body).addClass("x-tabs-body");
+ container.appendChild(body);
+ return body;
+};
+/** @private */
+Roo.panel.Tab.prototype.createItemBody = function(bodyEl, id){
+ var body = Roo.getDom(id);
+ if(!body){
+ body = document.createElement("div");
+ body.id = id;
}
-
- this.el = Roo.getDom(el);
- this.id = Roo.id(this.el);
- this.hidden = false;
-
- this.addEvents({
- /**
- * @event render
- * Fires when the button is rendered
- * @param {Button} this
- */
- 'render': true
- });
- Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
+ Roo.fly(body).addClass("x-tabs-item-body");
+ bodyEl.insertBefore(body, bodyEl.firstChild);
+ return body;
};
-Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
-//Roo.Toolbar.Item.prototype = {
-
+/** @private */
+Roo.panel.Tab.prototype.createStripElements = function(stripEl, text, closable){
+ var td = document.createElement("td");
+ stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
+ //stripEl.appendChild(td);
+ if(closable){
+ td.className = "x-tabs-closable";
+ if(!this.closeTpl){
+ this.closeTpl = new Roo.Template(
+ '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
+ '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
+ '<div unselectable="on" class="close-icon"> </div></em></span></a>'
+ );
+ }
+ var el = this.closeTpl.overwrite(td, {"text": text});
+ var close = el.getElementsByTagName("div")[0];
+ var inner = el.getElementsByTagName("em")[0];
+ return {"el": el, "close": close, "inner": inner};
+ } else {
+ if(!this.tabTpl){
+ this.tabTpl = new Roo.Template(
+ '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
+ '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
+ );
+ }
+ var el = this.tabTpl.overwrite(td, {"text": text});
+ var inner = el.getElementsByTagName("em")[0];
+ return {"el": el, "inner": inner};
+ }
+};/**
+ * @class Roo.panel.TabItem
+ * @extends Roo.util.Observable
+ * Represents an individual item (tab plus body) in a TabPanel.
+ * @param {Roo.panel.Tab} tabPanel The {@link Roo.panel.Tab} this TabPanelItem belongs to
+ * @param {String} id The id of this TabPanelItem
+ * @param {String} text The text for the tab of this TabPanelItem
+ * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
+ */
+ Roo.panel.TabItem = function(tabPanel, id, text, closable){
/**
- * Get this item's HTML Element
- * @return {HTMLElement}
+ * The {@link Roo.panel.Tab} this TabPanelItem belongs to
+ * @type Roo.panel.Tab
*/
- getEl : function(){
- return this.el;
- },
+ this.tabPanel = tabPanel;
+ /**
+ * The id for this TabPanelItem
+ * @type String
+ */
+ this.id = id;
+ /** @private */
+ this.disabled = false;
+ /** @private */
+ this.text = text;
+ /** @private */
+ this.loaded = false;
+ this.closable = closable;
- // private
- render : function(td){
-
- this.td = td;
- td.appendChild(this.el);
-
- this.fireEvent('render', this);
- },
-
/**
- * Removes and destroys this item.
+ * The body element for this TabPanelItem.
+ * @type Roo.Element
*/
- destroy : function(){
- this.td.parentNode.removeChild(this.td);
+ this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
+ this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
+ this.bodyEl.setStyle("display", "block");
+ this.bodyEl.setStyle("zoom", "1");
+ this.hideAction();
+
+ var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
+ /** @private */
+ this.el = Roo.get(els.el, true);
+ this.inner = Roo.get(els.inner, true);
+ this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
+ this.pnode = Roo.get(els.el.parentNode, true);
+ this.el.on("mousedown", this.onTabMouseDown, this);
+ this.el.on("click", this.onTabClick, this);
+ /** @private */
+ if(closable){
+ var c = Roo.get(els.close, true);
+ c.dom.title = this.closeText;
+ c.addClassOnOver("close-over");
+ c.on("click", this.closeClick, this);
+ }
+
+ this.addEvents({
+ /**
+ * @event activate
+ * Fires when this tab becomes the active tab.
+ * @param {Roo.panel.Tab} tabPanel The parent TabPanel
+ * @param {Roo.panel.TabItem} this
+ */
+ "activate": true,
+ /**
+ * @event beforeclose
+ * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
+ * @param {Roo.panel.TabItem} this
+ * @param {Object} e Set cancel to true on this object to cancel the close.
+ */
+ "beforeclose": true,
+ /**
+ * @event close
+ * Fires when this tab is closed.
+ * @param {Roo.panel.TabItem} this
+ */
+ "close": true,
+ /**
+ * @event deactivate
+ * Fires when this tab is no longer the active tab.
+ * @param {Roo.panel.Tab} tabPanel The parent TabPanel
+ * @param {Roo.panel.TabItem} this
+ */
+ "deactivate" : true
+ });
+ this.hidden = false;
+
+ Roo.panel.TabItem.superclass.constructor.call(this);
+};
+
+Roo.extend(Roo.panel.TabItem, Roo.util.Observable, {
+ purgeListeners : function(){
+ Roo.util.Observable.prototype.purgeListeners.call(this);
+ this.el.removeAllListeners();
},
-
/**
- * Shows this item.
+ * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
*/
- show: function(){
- this.hidden = false;
- this.td.style.display = "";
+ show : function(){
+ this.pnode.addClass("on");
+ this.showAction();
+ if(Roo.isOpera){
+ this.tabPanel.stripWrap.repaint();
+ }
+ this.fireEvent("activate", this.tabPanel, this);
},
-
+
/**
- * Hides this item.
+ * Returns true if this tab is the active tab.
+ * @return {Boolean}
*/
- hide: function(){
- this.hidden = true;
- this.td.style.display = "none";
+ isActive : function(){
+ return this.tabPanel.getActiveTab() == this;
},
-
+
/**
- * Convenience function for boolean show/hide.
- * @param {Boolean} visible true to show/false to hide
+ * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
*/
- setVisible: function(visible){
- if(visible) {
- this.show();
- }else{
- this.hide();
- }
+ hide : function(){
+ this.pnode.removeClass("on");
+ this.hideAction();
+ this.fireEvent("deactivate", this.tabPanel, this);
},
-
- /**
- * Try to focus this item.
- */
- focus : function(){
- Roo.fly(this.el).focus();
+
+ hideAction : function(){
+ this.bodyEl.hide();
+ this.bodyEl.setStyle("position", "absolute");
+ this.bodyEl.setLeft("-20000px");
+ this.bodyEl.setTop("-20000px");
},
-
- /**
- * Disables this item.
- */
- disable : function(){
- Roo.fly(this.td).addClass("x-item-disabled");
- this.disabled = true;
- this.el.disabled = true;
+
+ showAction : function(){
+ this.bodyEl.setStyle("position", "relative");
+ this.bodyEl.setTop("");
+ this.bodyEl.setLeft("");
+ this.bodyEl.show();
},
-
+
/**
- * Enables this item.
+ * Set the tooltip for the tab.
+ * @param {String} tooltip The tab's tooltip
*/
- enable : function(){
- Roo.fly(this.td).removeClass("x-item-disabled");
- this.disabled = false;
- this.el.disabled = false;
- }
-});
+ setTooltip : function(text){
+ if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
+ this.textEl.dom.qtip = text;
+ this.textEl.dom.removeAttribute('title');
+ }else{
+ this.textEl.dom.title = text;
+ }
+ },
+ onTabClick : function(e){
+ e.preventDefault();
+ this.tabPanel.activate(this.id);
+ },
-/**
- * @class Roo.Toolbar.Separator
- * @extends Roo.Toolbar.Item
- * A simple toolbar separator class
- * @constructor
- * Creates a new Separator
- */
-Roo.Toolbar.Separator = function(cfg){
-
- var s = document.createElement("span");
- s.className = "ytb-sep";
- if (cfg) {
- cfg.el = s;
- }
-
- Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
-};
-Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
- enable:Roo.emptyFn,
- disable:Roo.emptyFn,
- focus:Roo.emptyFn
-});
+ onTabMouseDown : function(e){
+ e.preventDefault();
+ this.tabPanel.activate(this.id);
+ },
-/**
- * @class Roo.Toolbar.Spacer
- * @extends Roo.Toolbar.Item
- * A simple element that adds extra horizontal space to a toolbar.
- * @constructor
- * Creates a new Spacer
- */
-Roo.Toolbar.Spacer = function(cfg){
- var s = document.createElement("div");
- s.className = "ytb-spacer";
- if (cfg) {
- cfg.el = s;
- }
- Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
-};
-Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
- enable:Roo.emptyFn,
- disable:Roo.emptyFn,
- focus:Roo.emptyFn
-});
+ getWidth : function(){
+ return this.inner.getWidth();
+ },
-/**
- * @class Roo.Toolbar.Fill
- * @extends Roo.Toolbar.Spacer
- * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
- * @constructor
- * Creates a new Spacer
- */
-Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
- // private
- render : function(td){
- td.style.width = '100%';
- Roo.Toolbar.Fill.superclass.render.call(this, td);
- }
-});
+ setWidth : function(width){
+ var iwidth = width - this.pnode.getPadding("lr");
+ this.inner.setWidth(iwidth);
+ this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
+ this.pnode.setWidth(width);
+ },
-/**
- * @class Roo.Toolbar.TextItem
- * @extends Roo.Toolbar.Item
- * A simple class that renders text directly into a toolbar.
- * @constructor
- * Creates a new TextItem
- * @cfg {string} text
- */
-Roo.Toolbar.TextItem = function(cfg){
- var text = cfg || "";
- if (typeof(cfg) == 'object') {
- text = cfg.text || "";
- } else {
- cfg = null;
- }
- var s = document.createElement("span");
- s.className = "ytb-text";
- s.innerHTML = text;
- if (cfg) {
- cfg.el = s;
- }
-
- Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg || s);
-};
-Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
-
-
- enable:Roo.emptyFn,
- disable:Roo.emptyFn,
- focus:Roo.emptyFn,
- /**
- * Shows this button
+ /**
+ * Show or hide the tab
+ * @param {Boolean} hidden True to hide or false to show.
*/
- show: function(){
- this.hidden = false;
- this.el.style.display = "";
+ setHidden : function(hidden){
+ this.hidden = hidden;
+ this.pnode.setStyle("display", hidden ? "none" : "");
},
-
+
/**
- * Hides this button
+ * Returns true if this tab is "hidden"
+ * @return {Boolean}
*/
- hide: function(){
- this.hidden = true;
- this.el.style.display = "none";
- }
-
-});
-
-/**
- * @class Roo.Toolbar.Button
- * @extends Roo.Button
- * A button that renders into a toolbar.
- * @constructor
- * Creates a new Button
- * @param {Object} config A standard {@link Roo.Button} config object
- */
-Roo.Toolbar.Button = function(config){
- Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
-};
-Roo.extend(Roo.Toolbar.Button, Roo.Button,
-{
-
-
- render : function(td){
- this.td = td;
- Roo.Toolbar.Button.superclass.render.call(this, td);
+ isHidden : function(){
+ return this.hidden;
},
-
+
/**
- * Removes and destroys this button
+ * Returns the text for this tab
+ * @return {String}
*/
- destroy : function(){
- Roo.Toolbar.Button.superclass.destroy.call(this);
- this.td.parentNode.removeChild(this.td);
+ getText : function(){
+ return this.text;
},
-
+
+ autoSize : function(){
+ //this.el.beginMeasure();
+ this.textEl.setWidth(1);
+ /*
+ * #2804 [new] Tabs in Roojs
+ * increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
+ */
+ this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
+ //this.el.endMeasure();
+ },
+
/**
- * Shows this button
+ * Sets the text for the tab (Note: this also sets the tooltip text)
+ * @param {String} text The tab's text and tooltip
*/
- show: function(){
- this.hidden = false;
- this.td.style.display = "";
+ setText : function(text){
+ this.text = text;
+ this.textEl.update(text);
+ this.setTooltip(text);
+ if(!this.tabPanel.resizeTabs){
+ this.autoSize();
+ }
},
-
/**
- * Hides this button
+ * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
*/
- hide: function(){
- this.hidden = true;
- this.td.style.display = "none";
+ activate : function(){
+ this.tabPanel.activate(this.id);
},
/**
- * Disables this item
+ * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
*/
disable : function(){
- Roo.fly(this.td).addClass("x-item-disabled");
- this.disabled = true;
+ if(this.tabPanel.active != this){
+ this.disabled = true;
+ this.pnode.addClass("disabled");
+ }
},
/**
- * Enables this item
+ * Enables this TabPanelItem if it was previously disabled.
*/
enable : function(){
- Roo.fly(this.td).removeClass("x-item-disabled");
this.disabled = false;
- }
-});
-// backwards compat
-Roo.ToolbarButton = Roo.Toolbar.Button;
+ this.pnode.removeClass("disabled");
+ },
-/**
- * @class Roo.Toolbar.SplitButton
- * @extends Roo.SplitButton
- * A menu button that renders into a toolbar.
- * @constructor
- * Creates a new SplitButton
- * @param {Object} config A standard {@link Roo.SplitButton} config object
- */
-Roo.Toolbar.SplitButton = function(config){
- Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
-};
-Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
- render : function(td){
- this.td = td;
- Roo.Toolbar.SplitButton.superclass.render.call(this, td);
+ /**
+ * Sets the content for this TabPanelItem.
+ * @param {String} content The content
+ * @param {Boolean} loadScripts true to look for and load scripts
+ */
+ setContent : function(content, loadScripts){
+ this.bodyEl.update(content, loadScripts);
},
-
+
/**
- * Removes and destroys this button
+ * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
+ * @return {Roo.UpdateManager} The UpdateManager
*/
- destroy : function(){
- Roo.Toolbar.SplitButton.superclass.destroy.call(this);
- this.td.parentNode.removeChild(this.td);
+ getUpdateManager : function(){
+ return this.bodyEl.getUpdateManager();
},
-
+
/**
- * Shows this button
+ * Set a URL to be used to load the content for this TabPanelItem.
+ * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
+ * @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)
+ * @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)
+ * @return {Roo.UpdateManager} The UpdateManager
*/
- show: function(){
- this.hidden = false;
- this.td.style.display = "";
+ setUrl : function(url, params, loadOnce){
+ if(this.refreshDelegate){
+ this.un('activate', this.refreshDelegate);
+ }
+ this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
+ this.on("activate", this.refreshDelegate);
+ return this.bodyEl.getUpdateManager();
},
-
+
+ /** @private */
+ _handleRefresh : function(url, params, loadOnce){
+ if(!loadOnce || !this.loaded){
+ var updater = this.bodyEl.getUpdateManager();
+ updater.update(url, params, this._setLoaded.createDelegate(this));
+ }
+ },
+
/**
- * Hides this button
+ * Forces a content refresh from the URL specified in the {@link #setUrl} method.
+ * Will fail silently if the setUrl method has not been called.
+ * This does not activate the panel, just updates its content.
*/
- hide: function(){
- this.hidden = true;
- this.td.style.display = "none";
- }
+ refresh : function(){
+ if(this.refreshDelegate){
+ this.loaded = false;
+ this.refreshDelegate();
+ }
+ },
+
+ /** @private */
+ _setLoaded : function(){
+ this.loaded = true;
+ },
+
+ /** @private */
+ closeClick : function(e){
+ var o = {};
+ e.stopEvent();
+ this.fireEvent("beforeclose", this, o);
+ if(o.cancel !== true){
+ this.tabPanel.removeTab(this.id);
+ }
+ },
+ /**
+ * The text displayed in the tooltip for the close icon.
+ * @type String
+ */
+ closeText : "Close this tab"
});
-// backwards compat
-Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
+/** @private */
+Roo.panel.Tab.prototype.createStrip = function(container){
+ var strip = document.createElement("div");
+ strip.className = "x-tabs-wrap";
+ container.appendChild(strip);
+ return strip;
+};/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* Fork - LGPL
* <script type="text/javascript">
*/
-
+
/**
- * @class Roo.PagingToolbar
- * @extends Roo.Toolbar
- * @children Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
- * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
+ * @class Roo.Button
+ * @extends Roo.util.Observable
+ * Simple Button class
+ * @cfg {String} text The button text
+ * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
+ * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
+ * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
+ * @cfg {Object} scope The scope of the handler
+ * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
+ * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
+ * @cfg {Boolean} hidden True to start hidden (defaults to false)
+ * @cfg {Boolean} disabled True to start disabled (defaults to false)
+ * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
+ * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
+ applies if enableToggle = true)
+ * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
+ * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
+ an {@link Roo.util.ClickRepeater} config object (defaults to false).
* @constructor
- * Create a new PagingToolbar
+ * Create a new button
* @param {Object} config The config object
*/
-Roo.PagingToolbar = function(el, ds, config)
+Roo.Button = function(renderTo, config)
{
- // old args format still supported... - xtype is prefered..
- if (typeof(el) == 'object' && el.xtype) {
- // created from xtype...
- config = el;
- ds = el.dataSource;
- el = config.container;
- }
- var items = [];
- if (config.items) {
- items = config.items;
- config.items = [];
+ if (!config) {
+ config = renderTo;
+ renderTo = config.renderTo || false;
}
- Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
- this.ds = ds;
- this.cursor = 0;
- this.renderButtons(this.el);
- this.bind(ds);
-
- // supprot items array.
-
- Roo.each(items, function(e) {
- this.add(Roo.factory(e));
- },this);
+ Roo.apply(this, config);
+ this.addEvents({
+ /**
+ * @event click
+ * Fires when this button is clicked
+ * @param {Button} this
+ * @param {EventObject} e The click event
+ */
+ "click" : true,
+ /**
+ * @event toggle
+ * Fires when the "pressed" state of this button changes (only if enableToggle = true)
+ * @param {Button} this
+ * @param {Boolean} pressed
+ */
+ "toggle" : true,
+ /**
+ * @event mouseover
+ * Fires when the mouse hovers over the button
+ * @param {Button} this
+ * @param {Event} e The event object
+ */
+ 'mouseover' : true,
+ /**
+ * @event mouseout
+ * Fires when the mouse exits the button
+ * @param {Button} this
+ * @param {Event} e The event object
+ */
+ 'mouseout': true,
+ /**
+ * @event render
+ * Fires when the button is rendered
+ * @param {Button} this
+ */
+ 'render': true
+ });
+ if(this.menu){
+ this.menu = Roo.menu.MenuMgr.get(this.menu);
+ }
+ // register listeners first!! - so render can be captured..
+ Roo.util.Observable.call(this);
+ if(renderTo){
+ this.render(renderTo);
+ }
+
};
-Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
-
- /**
- * @cfg {String/HTMLElement/Element} container
- * container The id or element that will contain the toolbar
- */
+Roo.extend(Roo.Button, Roo.util.Observable, {
/**
- * @cfg {Boolean} displayInfo
- * True to display the displayMsg (defaults to false)
+ *
*/
-
/**
- * @cfg {Number} pageSize
- * The number of records to display per page (defaults to 20)
+ * Read-only. True if this button is hidden
+ * @type Boolean
*/
- pageSize: 20,
+ hidden : false,
/**
- * @cfg {String} displayMsg
- * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
+ * Read-only. True if this button is disabled
+ * @type Boolean
*/
- displayMsg : 'Displaying {0} - {1} of {2}',
+ disabled : false,
/**
- * @cfg {String} emptyMsg
- * The message to display when no records are found (defaults to "No data to display")
+ * Read-only. True if this button is pressed (only if enableToggle = true)
+ * @type Boolean
*/
- emptyMsg : 'No data to display',
+ pressed : false,
+
/**
- * Customizable piece of the default paging text (defaults to "Page")
- * @type String
+ * @cfg {Number} tabIndex
+ * The DOM tabIndex for this button (defaults to undefined)
*/
- beforePageText : "Page",
+ tabIndex : undefined,
+
/**
- * Customizable piece of the default paging text (defaults to "of %0")
- * @type String
+ * @cfg {Boolean} enableToggle
+ * True to enable pressed/not pressed toggling (defaults to false)
*/
- afterPageText : "of {0}",
+ enableToggle: false,
/**
- * Customizable piece of the default paging text (defaults to "First Page")
- * @type String
+ * @cfg {Roo.menu.Menu} menu
+ * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
*/
- firstText : "First Page",
+ menu : undefined,
/**
- * Customizable piece of the default paging text (defaults to "Previous Page")
- * @type String
+ * @cfg {String} menuAlign
+ * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
*/
- prevText : "Previous Page",
+ menuAlign : "tl-bl?",
+
/**
- * Customizable piece of the default paging text (defaults to "Next Page")
- * @type String
+ * @cfg {String} iconCls
+ * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
*/
- nextText : "Next Page",
+ iconCls : undefined,
/**
- * Customizable piece of the default paging text (defaults to "Last Page")
- * @type String
+ * @cfg {String} type
+ * The button's type, corresponding to the DOM input element type attribute. Either "submit," "reset" or "button" (default).
*/
- lastText : "Last Page",
+ type : 'button',
+
+ // private
+ menuClassTarget: 'tr',
+
/**
- * Customizable piece of the default paging text (defaults to "Refresh")
- * @type String
+ * @cfg {String} clickEvent
+ * The type of event to map to the button's event handler (defaults to 'click')
*/
- refreshText : "Refresh",
+ clickEvent : 'click',
- // private
- renderButtons : function(el){
- Roo.PagingToolbar.superclass.render.call(this, el);
- this.first = this.addButton({
- tooltip: this.firstText,
- cls: "x-btn-icon x-grid-page-first",
- disabled: true,
- handler: this.onClick.createDelegate(this, ["first"])
- });
- this.prev = this.addButton({
- tooltip: this.prevText,
- cls: "x-btn-icon x-grid-page-prev",
- disabled: true,
- handler: this.onClick.createDelegate(this, ["prev"])
- });
- //this.addSeparator();
- this.add(this.beforePageText);
- this.field = Roo.get(this.addDom({
- tag: "input",
- type: "text",
- size: "3",
- value: "1",
- cls: "x-grid-page-number"
- }).el);
- this.field.on("keydown", this.onPagingKeydown, this);
- this.field.on("focus", function(){this.dom.select();});
- this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
- this.field.setHeight(18);
- //this.addSeparator();
- this.next = this.addButton({
- tooltip: this.nextText,
- cls: "x-btn-icon x-grid-page-next",
- disabled: true,
- handler: this.onClick.createDelegate(this, ["next"])
- });
- this.last = this.addButton({
- tooltip: this.lastText,
- cls: "x-btn-icon x-grid-page-last",
- disabled: true,
- handler: this.onClick.createDelegate(this, ["last"])
- });
- //this.addSeparator();
- this.loading = this.addButton({
- tooltip: this.refreshText,
- cls: "x-btn-icon x-grid-loading",
- handler: this.onClick.createDelegate(this, ["refresh"])
- });
+ /**
+ * @cfg {Boolean} handleMouseEvents
+ * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
+ */
+ handleMouseEvents : true,
- if(this.displayInfo){
- this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
- }
- },
+ /**
+ * @cfg {String} tooltipType
+ * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
+ */
+ tooltipType : 'qtip',
+
+ /**
+ * @cfg {String} cls
+ * A CSS class to apply to the button's main element.
+ */
+
+ /**
+ * @cfg {Roo.Template} template (Optional)
+ * An {@link Roo.Template} with which to create the Button's main element. This Template must
+ * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
+ * require code modifications if required elements (e.g. a button) aren't present.
+ */
// private
- updateInfo : function(){
- if(this.displayEl){
- var count = this.ds.getCount();
- var msg = count == 0 ?
- this.emptyMsg :
- String.format(
- this.displayMsg,
- this.cursor+1, this.cursor+count, this.ds.getTotalCount()
- );
- this.displayEl.update(msg);
+ render : function(renderTo){
+ var btn;
+ if(this.hideParent){
+ this.parentEl = Roo.get(renderTo);
+ }
+ if(!this.dhconfig){
+ if(!this.template){
+ if(!Roo.Button.buttonTemplate){
+ // hideous table template
+ Roo.Button.buttonTemplate = new Roo.Template(
+ '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
+ '<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>',
+ "</tr></tbody></table>");
+ }
+ this.template = Roo.Button.buttonTemplate;
+ }
+ btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
+ var btnEl = btn.child("button:first");
+ btnEl.on('focus', this.onFocus, this);
+ btnEl.on('blur', this.onBlur, this);
+ if(this.cls){
+ btn.addClass(this.cls);
+ }
+ if(this.icon){
+ btnEl.setStyle('background-image', 'url(' +this.icon +')');
+ }
+ if(this.iconCls){
+ btnEl.addClass(this.iconCls);
+ if(!this.cls){
+ btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
+ }
+ }
+ if(this.tabIndex !== undefined){
+ btnEl.dom.tabIndex = this.tabIndex;
+ }
+ if(this.tooltip){
+ if(typeof this.tooltip == 'object'){
+ Roo.QuickTips.tips(Roo.apply({
+ target: btnEl.id
+ }, this.tooltip));
+ } else {
+ btnEl.dom[this.tooltipType] = this.tooltip;
+ }
+ }
+ }else{
+ btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
+ }
+ this.el = btn;
+ if(this.id){
+ this.el.dom.id = this.el.id = this.id;
+ }
+ if(this.menu){
+ this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
+ this.menu.on("show", this.onMenuShow, this);
+ this.menu.on("hide", this.onMenuHide, this);
+ }
+ btn.addClass("x-btn");
+ if(Roo.isIE && !Roo.isIE7){
+ this.autoWidth.defer(1, this);
+ }else{
+ this.autoWidth();
+ }
+ if(this.handleMouseEvents){
+ btn.on("mouseover", this.onMouseOver, this);
+ btn.on("mouseout", this.onMouseOut, this);
+ btn.on("mousedown", this.onMouseDown, this);
+ }
+ btn.on(this.clickEvent, this.onClick, this);
+ //btn.on("mouseup", this.onMouseUp, this);
+ if(this.hidden){
+ this.hide();
+ }
+ if(this.disabled){
+ this.disable();
+ }
+ Roo.ButtonToggleMgr.register(this);
+ if(this.pressed){
+ this.el.addClass("x-btn-pressed");
+ }
+ if(this.repeat){
+ var repeater = new Roo.util.ClickRepeater(btn,
+ typeof this.repeat == "object" ? this.repeat : {}
+ );
+ repeater.on("click", this.onClick, this);
}
+
+ this.fireEvent('render', this);
+
},
-
- // private
- onLoad : function(ds, r, o){
- this.cursor = o.params ? o.params.start : 0;
- var d = this.getPageData(), ap = d.activePage, ps = d.pages;
-
- this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
- this.field.dom.value = ap;
- this.first.setDisabled(ap == 1);
- this.prev.setDisabled(ap == 1);
- this.next.setDisabled(ap == ps);
- this.last.setDisabled(ap == ps);
- this.loading.enable();
- this.updateInfo();
+ /**
+ * Returns the button's underlying element
+ * @return {Roo.Element} The element
+ */
+ getEl : function(){
+ return this.el;
},
-
- // private
- getPageData : function(){
- var total = this.ds.getTotalCount();
- return {
- total : total,
- activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
- pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
- };
+
+ /**
+ * Destroys this Button and removes any listeners.
+ */
+ destroy : function(){
+ Roo.ButtonToggleMgr.unregister(this);
+ this.el.removeAllListeners();
+ this.purgeListeners();
+ this.el.remove();
},
// private
- onLoadError : function(){
- this.loading.enable();
+ autoWidth : function(){
+ if(this.el){
+ this.el.setWidth("auto");
+ if(Roo.isIE7 && Roo.isStrict){
+ var ib = this.el.child('button');
+ if(ib && ib.getWidth() > 20){
+ ib.clip();
+ ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
+ }
+ }
+ if(this.minWidth){
+ if(this.hidden){
+ this.el.beginMeasure();
+ }
+ if(this.el.getWidth() < this.minWidth){
+ this.el.setWidth(this.minWidth);
+ }
+ if(this.hidden){
+ this.el.endMeasure();
+ }
+ }
+ }
},
- // private
- onPagingKeydown : function(e){
- var k = e.getKey();
- var d = this.getPageData();
- if(k == e.RETURN){
- var v = this.field.dom.value, pageNum;
- if(!v || isNaN(pageNum = parseInt(v, 10))){
- this.field.dom.value = d.activePage;
- return;
- }
- pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
- this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
- e.stopEvent();
+ /**
+ * Assigns this button's click handler
+ * @param {Function} handler The function to call when the button is clicked
+ * @param {Object} scope (optional) Scope for the function passed in
+ */
+ setHandler : function(handler, scope){
+ this.handler = handler;
+ this.scope = scope;
+ },
+
+ /**
+ * Sets this button's text
+ * @param {String} text The button text
+ */
+ setText : function(text){
+ this.text = text;
+ if(this.el){
+ this.el.child("td.x-btn-center button.x-btn-text").update(text);
}
- 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))
- {
- var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
- this.field.dom.value = pageNum;
- this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
- e.stopEvent();
+ this.autoWidth();
+ },
+
+ /**
+ * Gets the text for this button
+ * @return {String} The button text
+ */
+ getText : function(){
+ return this.text;
+ },
+
+ /**
+ * Show this button
+ */
+ show: function(){
+ this.hidden = false;
+ if(this.el){
+ this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
}
- else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
- {
- var v = this.field.dom.value, pageNum;
- var increment = (e.shiftKey) ? 10 : 1;
- if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
- increment *= -1;
- }
- if(!v || isNaN(pageNum = parseInt(v, 10))) {
- this.field.dom.value = d.activePage;
- return;
- }
- else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
- {
- this.field.dom.value = parseInt(v, 10) + increment;
- pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
- this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
- }
- e.stopEvent();
+ },
+
+ /**
+ * Hide this button
+ */
+ hide: function(){
+ this.hidden = true;
+ if(this.el){
+ this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
}
},
-
- // private
- beforeLoad : function(){
- if(this.loading){
- this.loading.disable();
+
+ /**
+ * Convenience function for boolean show/hide
+ * @param {Boolean} visible True to show, false to hide
+ */
+ setVisible: function(visible){
+ if(visible) {
+ this.show();
+ }else{
+ this.hide();
}
},
/**
- * event that occurs when you click on the navigation buttons - can be used to trigger load of a grid.
- * @param {String} which (first|prev|next|last|refresh) which button to press.
- *
+ * Similar to toggle, but does not trigger event.
+ * @param {Boolean} state [required] Force a particular state
+ */
+ setPressed : function(state)
+ {
+ if(state != this.pressed){
+ if(state){
+ this.el.addClass("x-btn-pressed");
+ this.pressed = true;
+ }else{
+ this.el.removeClass("x-btn-pressed");
+ this.pressed = false;
+ }
+ }
+ },
+
+ /**
+ * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
+ * @param {Boolean} state (optional) Force a particular state
*/
- // private
- onClick : function(which){
- var ds = this.ds;
- switch(which){
- case "first":
- ds.load({params:{start: 0, limit: this.pageSize}});
- break;
- case "prev":
- ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
- break;
- case "next":
- ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
- break;
- case "last":
- var total = ds.getTotalCount();
- var extra = total % this.pageSize;
- var lastStart = extra ? (total - extra) : total-this.pageSize;
- ds.load({params:{start: lastStart, limit: this.pageSize}});
- break;
- case "refresh":
- ds.load({params:{start: this.cursor, limit: this.pageSize}});
- break;
+ toggle : function(state){
+ state = state === undefined ? !this.pressed : state;
+ if(state != this.pressed){
+ if(state){
+ this.el.addClass("x-btn-pressed");
+ this.pressed = true;
+ this.fireEvent("toggle", this, true);
+ }else{
+ this.el.removeClass("x-btn-pressed");
+ this.pressed = false;
+ this.fireEvent("toggle", this, false);
+ }
+ if(this.toggleHandler){
+ this.toggleHandler.call(this.scope || this, this, state);
+ }
}
},
-
+
+
+
/**
- * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
- * @param {Roo.data.Store} store The data store to unbind
+ * Focus the button
*/
- unbind : function(ds){
- ds.un("beforeload", this.beforeLoad, this);
- ds.un("load", this.onLoad, this);
- ds.un("loadexception", this.onLoadError, this);
- ds.un("remove", this.updateInfo, this);
- ds.un("add", this.updateInfo, this);
- this.ds = undefined;
+ focus : function(){
+ this.el.child('button:first').focus();
+ },
+
+ /**
+ * Disable this button
+ */
+ disable : function(){
+ if(this.el){
+ this.el.addClass("x-btn-disabled");
+ }
+ this.disabled = true;
+ },
+
+ /**
+ * Enable this button
+ */
+ enable : function(){
+ if(this.el){
+ this.el.removeClass("x-btn-disabled");
+ }
+ this.disabled = false;
},
/**
- * Binds the paging toolbar to the specified {@link Roo.data.Store}
- * @param {Roo.data.Store} store The data store to bind
+ * Convenience function for boolean enable/disable
+ * @param {Boolean} enabled True to enable, false to disable
*/
- bind : function(ds){
- ds.on("beforeload", this.beforeLoad, this);
- ds.on("load", this.onLoad, this);
- ds.on("loadexception", this.onLoadError, this);
- ds.on("remove", this.updateInfo, this);
- ds.on("add", this.updateInfo, this);
- this.ds = ds;
- }
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
+ setDisabled : function(v){
+ this[v !== true ? "enable" : "disable"]();
+ },
-/**
- * @class Roo.Resizable
- * @extends Roo.util.Observable
- * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
- * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
- * 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
- * the element will be wrapped for you automatically.</p>
- * <p>Here is the list of valid resize handles:</p>
- * <pre>
-Value Description
------- -------------------
- 'n' north
- 's' south
- 'e' east
- 'w' west
- 'nw' northwest
- 'sw' southwest
- 'se' southeast
- 'ne' northeast
- 'hd' horizontal drag
- 'all' all
-</pre>
- * <p>Here's an example showing the creation of a typical Resizable:</p>
- * <pre><code>
-var resizer = new Roo.Resizable("element-id", {
- handles: 'all',
- minWidth: 200,
- minHeight: 100,
- maxWidth: 500,
- maxHeight: 400,
- pinned: true
-});
-resizer.on("resize", myHandler);
-</code></pre>
- * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
- * resizer.east.setDisplayed(false);</p>
- * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
- * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
- * resize operation's new size (defaults to [0, 0])
- * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
- * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
- * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
- * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
- * @cfg {Boolean} enabled False to disable resizing (defaults to true)
- * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
- * @cfg {Number} width The width of the element in pixels (defaults to null)
- * @cfg {Number} height The height of the element in pixels (defaults to null)
- * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
- * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
- * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
- * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
- * @cfg {Boolean} multiDirectional <b>Deprecated</b>. The old style of adding multi-direction resize handles, deprecated
- * in favor of the handles config option (defaults to false)
- * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
- * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
- * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
- * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
- * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
- * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
- * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
- * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
- * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
- * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
- * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
- * @constructor
- * Create a new resizable component
- * @param {String/HTMLElement/Roo.Element} el The id or element to resize
- * @param {Object} config configuration options
- */
-Roo.Resizable = function(el, config)
-{
- this.el = Roo.get(el);
-
- if(config && config.wrap){
- config.resizeChild = this.el;
- this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
- this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
- this.el.setStyle("overflow", "hidden");
- this.el.setPositioning(config.resizeChild.getPositioning());
- config.resizeChild.clearPositioning();
- if(!config.width || !config.height){
- var csize = config.resizeChild.getSize();
- this.el.setSize(csize.width, csize.height);
- }
- if(config.pinned && !config.adjustments){
- config.adjustments = "auto";
- }
- }
-
- this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
- this.proxy.unselectable();
- this.proxy.enableDisplayMode('block');
-
- Roo.apply(this, config);
-
- if(this.pinned){
- this.disableTrackOver = true;
- this.el.addClass("x-resizable-pinned");
- }
- // if the element isn't positioned, make it relative
- var position = this.el.getStyle("position");
- if(position != "absolute" && position != "fixed"){
- this.el.setStyle("position", "relative");
- }
- if(!this.handles){ // no handles passed, must be legacy style
- this.handles = 's,e,se';
- if(this.multiDirectional){
- this.handles += ',n,w';
- }
- }
- if(this.handles == "all"){
- this.handles = "n s e w ne nw se sw";
- }
- var hs = this.handles.split(/\s*?[,;]\s*?| /);
- var ps = Roo.Resizable.positions;
- for(var i = 0, len = hs.length; i < len; i++){
- if(hs[i] && ps[hs[i]]){
- var pos = ps[hs[i]];
- this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
- }
- }
- // legacy
- this.corner = this.southeast;
-
- // updateBox = the box can move..
- if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
- this.updateBox = true;
- }
-
- this.activeHandle = null;
-
- if(this.resizeChild){
- if(typeof this.resizeChild == "boolean"){
- this.resizeChild = Roo.get(this.el.dom.firstChild, true);
- }else{
- this.resizeChild = Roo.get(this.resizeChild, true);
+ // private
+ onClick : function(e)
+ {
+ if(e){
+ e.preventDefault();
}
- }
-
- if(this.adjustments == "auto"){
- var rc = this.resizeChild;
- var hw = this.west, he = this.east, hn = this.north, hs = this.south;
- if(rc && (hw || hn)){
- rc.position("relative");
- rc.setLeft(hw ? hw.el.getWidth() : 0);
- rc.setTop(hn ? hn.el.getHeight() : 0);
+ if(e.button != 0){
+ return;
}
- this.adjustments = [
- (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
- (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
- ];
- }
-
- if(this.draggable){
- this.dd = this.dynamic ?
- this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
- this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
- }
-
- // public events
- this.addEvents({
- /**
- * @event beforeresize
- * Fired before resize is allowed. Set enabled to false to cancel resize.
- * @param {Roo.Resizable} this
- * @param {Roo.EventObject} e The mousedown event
- */
- "beforeresize" : true,
- /**
- * @event resizing
- * Fired a resizing.
- * @param {Roo.Resizable} this
- * @param {Number} x The new x position
- * @param {Number} y The new y position
- * @param {Number} w The new w width
- * @param {Number} h The new h hight
- * @param {Roo.EventObject} e The mouseup event
- */
- "resizing" : true,
- /**
- * @event resize
- * Fired after a resize.
- * @param {Roo.Resizable} this
- * @param {Number} width The new width
- * @param {Number} height The new height
- * @param {Roo.EventObject} e The mouseup event
- */
- "resize" : true
- });
-
- if(this.width !== null && this.height !== null){
- this.resizeTo(this.width, this.height);
- }else{
- this.updateChildSize();
- }
- if(Roo.isIE){
- this.el.dom.style.zoom = 1;
- }
- Roo.Resizable.superclass.constructor.call(this);
-};
-
-Roo.extend(Roo.Resizable, Roo.util.Observable, {
- resizeChild : false,
- adjustments : [0, 0],
- minWidth : 5,
- minHeight : 5,
- maxWidth : 10000,
- maxHeight : 10000,
- enabled : true,
- animate : false,
- duration : .35,
- dynamic : false,
- handles : false,
- multiDirectional : false,
- disableTrackOver : false,
- easing : 'easeOutStrong',
- widthIncrement : 0,
- heightIncrement : 0,
- pinned : false,
- width : null,
- height : null,
- preserveRatio : false,
- transparent: false,
- minX: 0,
- minY: 0,
- draggable: false,
-
- /**
- * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
- */
- constrainTo: undefined,
- /**
- * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
- */
- resizeRegion: undefined,
-
-
- /**
- * Perform a manual resize
- * @param {Number} width
- * @param {Number} height
- */
- resizeTo : function(width, height){
- this.el.setSize(width, height);
- this.updateChildSize();
- this.fireEvent("resize", this, width, height, null);
- },
-
- // private
- startSizing : function(e, handle){
- this.fireEvent("beforeresize", this, e);
- if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
-
- if(!this.overlay){
- this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: " "});
- this.overlay.unselectable();
- this.overlay.enableDisplayMode("block");
- this.overlay.on("mousemove", this.onMouseMove, this);
- this.overlay.on("mouseup", this.onMouseUp, this);
+ if(!this.disabled){
+ if(this.enableToggle){
+ this.toggle();
}
- this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
-
- this.resizing = true;
- this.startBox = this.el.getBox();
- this.startPoint = e.getXY();
- this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
- (this.startBox.y + this.startBox.height) - this.startPoint[1]];
-
- this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
- this.overlay.show();
-
- if(this.constrainTo) {
- var ct = Roo.get(this.constrainTo);
- this.resizeRegion = ct.getRegion().adjust(
- ct.getFrameWidth('t'),
- ct.getFrameWidth('l'),
- -ct.getFrameWidth('b'),
- -ct.getFrameWidth('r')
- );
+ if(this.menu && !this.menu.isVisible()){
+ this.menu.show(this.el, this.menuAlign);
}
-
- this.proxy.setStyle('visibility', 'hidden'); // workaround display none
- this.proxy.show();
- this.proxy.setBox(this.startBox);
- if(!this.dynamic){
- this.proxy.setStyle('visibility', 'visible');
+ this.fireEvent("click", this, e);
+ if(this.handler){
+ this.el.removeClass("x-btn-over");
+ this.handler.call(this.scope || this, this, e);
}
}
},
-
// private
- onMouseDown : function(handle, e){
- if(this.enabled){
- e.stopEvent();
- this.activeHandle = handle;
- this.startSizing(e, handle);
+ onMouseOver : function(e){
+ if(!this.disabled){
+ this.el.addClass("x-btn-over");
+ this.fireEvent('mouseover', this, e);
}
},
-
// private
- onMouseUp : function(e){
- var size = this.resizeElement();
- this.resizing = false;
- this.handleOut();
- this.overlay.hide();
- this.proxy.hide();
- this.fireEvent("resize", this, size.width, size.height, e);
+ onMouseOut : function(e){
+ if(!e.within(this.el, true)){
+ this.el.removeClass("x-btn-over");
+ this.fireEvent('mouseout', this, e);
+ }
},
-
// private
- updateChildSize : function(){
-
- if(this.resizeChild){
- var el = this.el;
- var child = this.resizeChild;
- var adj = this.adjustments;
- if(el.dom.offsetWidth){
- var b = el.getSize(true);
- child.setSize(b.width+adj[0], b.height+adj[1]);
- }
- // Second call here for IE
- // The first call enables instant resizing and
- // the second call corrects scroll bars if they
- // exist
- if(Roo.isIE){
- setTimeout(function(){
- if(el.dom.offsetWidth){
- var b = el.getSize(true);
- child.setSize(b.width+adj[0], b.height+adj[1]);
- }
- }, 10);
- }
+ onFocus : function(e){
+ if(!this.disabled){
+ this.el.addClass("x-btn-focus");
}
},
-
// private
- snap : function(value, inc, min){
- if(!inc || !value) {
- return value;
- }
- var newValue = value;
- var m = value % inc;
- if(m > 0){
- if(m > (inc/2)){
- newValue = value + (inc-m);
- }else{
- newValue = value - m;
- }
- }
- return Math.max(min, newValue);
+ onBlur : function(e){
+ this.el.removeClass("x-btn-focus");
},
-
// private
- resizeElement : function(){
- var box = this.proxy.getBox();
- if(this.updateBox){
- this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
- }else{
- this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
- }
- this.updateChildSize();
- if(!this.dynamic){
- this.proxy.hide();
+ onMouseDown : function(e){
+ if(!this.disabled && e.button == 0){
+ this.el.addClass("x-btn-click");
+ Roo.get(document).on('mouseup', this.onMouseUp, this);
}
- return box;
},
-
// private
- constrain : function(v, diff, m, mx){
- if(v - diff < m){
- diff = v - m;
- }else if(v - diff > mx){
- diff = mx - v;
+ onMouseUp : function(e){
+ if(e.button == 0){
+ this.el.removeClass("x-btn-click");
+ Roo.get(document).un('mouseup', this.onMouseUp, this);
}
- return diff;
},
-
// private
- onMouseMove : function(e){
-
- if(this.enabled){
- try{// try catch so if something goes wrong the user doesn't get hung
+ onMenuShow : function(e){
+ this.el.addClass("x-btn-menu-active");
+ },
+ // private
+ onMenuHide : function(e){
+ this.el.removeClass("x-btn-menu-active");
+ }
+});
- if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
- return;
+// Private utility class used by Button
+Roo.ButtonToggleMgr = function(){
+ var groups = {};
+
+ function toggleGroup(btn, state){
+ if(state){
+ var g = groups[btn.toggleGroup];
+ for(var i = 0, l = g.length; i < l; i++){
+ if(g[i] != btn){
+ g[i].toggle(false);
+ }
+ }
+ }
+ }
+
+ return {
+ register : function(btn){
+ if(!btn.toggleGroup){
+ return;
+ }
+ var g = groups[btn.toggleGroup];
+ if(!g){
+ g = groups[btn.toggleGroup] = [];
+ }
+ g.push(btn);
+ btn.on("toggle", toggleGroup);
+ },
+
+ unregister : function(btn){
+ if(!btn.toggleGroup){
+ return;
+ }
+ var g = groups[btn.toggleGroup];
+ if(g){
+ g.remove(btn);
+ btn.un("toggle", toggleGroup);
+ }
+ }
+ };
+}();/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.SplitButton
+ * @extends Roo.Button
+ * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
+ * click event of the button. Typically this would be used to display a dropdown menu that provides additional
+ * options to the primary button action, but any custom handler can provide the arrowclick implementation.
+ * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
+ * @cfg {String} arrowTooltip The title attribute of the arrow
+ * @constructor
+ * Create a new menu button
+ * @param {String/HTMLElement/Element} renderTo The element to append the button to
+ * @param {Object} config The config object
+ */
+Roo.SplitButton = function(renderTo, config){
+ Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
+ /**
+ * @event arrowclick
+ * Fires when this button's arrow is clicked
+ * @param {SplitButton} this
+ * @param {EventObject} e The click event
+ */
+ this.addEvents({"arrowclick":true});
+};
+
+Roo.extend(Roo.SplitButton, Roo.Button, {
+ render : function(renderTo){
+ // this is one sweet looking template!
+ var tpl = new Roo.Template(
+ '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
+ '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
+ '<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>',
+ "</tbody></table></td><td>",
+ '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
+ '<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>',
+ "</tbody></table></td></tr></table>"
+ );
+ var btn = tpl.append(renderTo, [this.text, this.type], true);
+ var btnEl = btn.child("button");
+ if(this.cls){
+ btn.addClass(this.cls);
+ }
+ if(this.icon){
+ btnEl.setStyle('background-image', 'url(' +this.icon +')');
+ }
+ if(this.iconCls){
+ btnEl.addClass(this.iconCls);
+ if(!this.cls){
+ btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
+ }
+ }
+ this.el = btn;
+ if(this.handleMouseEvents){
+ btn.on("mouseover", this.onMouseOver, this);
+ btn.on("mouseout", this.onMouseOut, this);
+ btn.on("mousedown", this.onMouseDown, this);
+ btn.on("mouseup", this.onMouseUp, this);
+ }
+ btn.on(this.clickEvent, this.onClick, this);
+ if(this.tooltip){
+ if(typeof this.tooltip == 'object'){
+ Roo.QuickTips.tips(Roo.apply({
+ target: btnEl.id
+ }, this.tooltip));
+ } else {
+ btnEl.dom[this.tooltipType] = this.tooltip;
}
+ }
+ if(this.arrowTooltip){
+ btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
+ }
+ if(this.hidden){
+ this.hide();
+ }
+ if(this.disabled){
+ this.disable();
+ }
+ if(this.pressed){
+ this.el.addClass("x-btn-pressed");
+ }
+ if(Roo.isIE && !Roo.isIE7){
+ this.autoWidth.defer(1, this);
+ }else{
+ this.autoWidth();
+ }
+ if(this.menu){
+ this.menu.on("show", this.onMenuShow, this);
+ this.menu.on("hide", this.onMenuHide, this);
+ }
+ this.fireEvent('render', this);
+ },
- //var curXY = this.startPoint;
- var curSize = this.curSize || this.startBox;
- var x = this.startBox.x, y = this.startBox.y;
- var ox = x, oy = y;
- var w = curSize.width, h = curSize.height;
- var ow = w, oh = h;
- var mw = this.minWidth, mh = this.minHeight;
- var mxw = this.maxWidth, mxh = this.maxHeight;
- var wi = this.widthIncrement;
- var hi = this.heightIncrement;
-
- var eventXY = e.getXY();
- var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
- var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
-
- var pos = this.activeHandle.position;
-
- switch(pos){
- case "east":
- w += diffX;
- w = Math.min(Math.max(mw, w), mxw);
- break;
-
- case "south":
- h += diffY;
- h = Math.min(Math.max(mh, h), mxh);
- break;
- case "southeast":
- w += diffX;
- h += diffY;
- w = Math.min(Math.max(mw, w), mxw);
- h = Math.min(Math.max(mh, h), mxh);
- break;
- case "north":
- diffY = this.constrain(h, diffY, mh, mxh);
- y += diffY;
- h -= diffY;
- break;
- case "hdrag":
-
- if (wi) {
- var adiffX = Math.abs(diffX);
- var sub = (adiffX % wi); // how much
- if (sub > (wi/2)) { // far enough to snap
- diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
- } else {
- // remove difference..
- diffX = (diffX > 0) ? diffX-sub : diffX+sub;
- }
- }
- x += diffX;
- x = Math.max(this.minX, x);
- break;
- case "west":
- diffX = this.constrain(w, diffX, mw, mxw);
- x += diffX;
- w -= diffX;
- break;
- case "northeast":
- w += diffX;
- w = Math.min(Math.max(mw, w), mxw);
- diffY = this.constrain(h, diffY, mh, mxh);
- y += diffY;
- h -= diffY;
- break;
- case "northwest":
- diffX = this.constrain(w, diffX, mw, mxw);
- diffY = this.constrain(h, diffY, mh, mxh);
- y += diffY;
- h -= diffY;
- x += diffX;
- w -= diffX;
- break;
- case "southwest":
- diffX = this.constrain(w, diffX, mw, mxw);
- h += diffY;
- h = Math.min(Math.max(mh, h), mxh);
- x += diffX;
- w -= diffX;
- break;
- }
-
- var sw = this.snap(w, wi, mw);
- var sh = this.snap(h, hi, mh);
- if(sw != w || sh != h){
- switch(pos){
- case "northeast":
- y -= sh - h;
- break;
- case "north":
- y -= sh - h;
- break;
- case "southwest":
- x -= sw - w;
- break;
- case "west":
- x -= sw - w;
- break;
- case "northwest":
- x -= sw - w;
- y -= sh - h;
- break;
+ // private
+ autoWidth : function(){
+ if(this.el){
+ var tbl = this.el.child("table:first");
+ var tbl2 = this.el.child("table:last");
+ this.el.setWidth("auto");
+ tbl.setWidth("auto");
+ if(Roo.isIE7 && Roo.isStrict){
+ var ib = this.el.child('button:first');
+ if(ib && ib.getWidth() > 20){
+ ib.clip();
+ ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
}
- w = sw;
- h = sh;
}
-
- if(this.preserveRatio){
- switch(pos){
- case "southeast":
- case "east":
- h = oh * (w/ow);
- h = Math.min(Math.max(mh, h), mxh);
- w = ow * (h/oh);
- break;
- case "south":
- w = ow * (h/oh);
- w = Math.min(Math.max(mw, w), mxw);
- h = oh * (w/ow);
- break;
- case "northeast":
- w = ow * (h/oh);
- w = Math.min(Math.max(mw, w), mxw);
- h = oh * (w/ow);
- break;
- case "north":
- var tw = w;
- w = ow * (h/oh);
- w = Math.min(Math.max(mw, w), mxw);
- h = oh * (w/ow);
- x += (tw - w) / 2;
- break;
- case "southwest":
- h = oh * (w/ow);
- h = Math.min(Math.max(mh, h), mxh);
- var tw = w;
- w = ow * (h/oh);
- x += tw - w;
- break;
- case "west":
- var th = h;
- h = oh * (w/ow);
- h = Math.min(Math.max(mh, h), mxh);
- y += (th - h) / 2;
- var tw = w;
- w = ow * (h/oh);
- x += tw - w;
- break;
- case "northwest":
- var tw = w;
- var th = h;
- h = oh * (w/ow);
- h = Math.min(Math.max(mh, h), mxh);
- w = ow * (h/oh);
- y += th - h;
- x += tw - w;
- break;
-
+ if(this.minWidth){
+ if(this.hidden){
+ this.el.beginMeasure();
+ }
+ if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
+ tbl.setWidth(this.minWidth-tbl2.getWidth());
+ }
+ if(this.hidden){
+ this.el.endMeasure();
}
}
- if (pos == 'hdrag') {
- w = ow;
- }
- this.proxy.setBounds(x, y, w, h);
- if(this.dynamic){
- this.resizeElement();
- }
- }catch(e){}
- }
- this.fireEvent("resizing", this, x, y, w, h, e);
- },
-
- // private
- handleOver : function(){
- if(this.enabled){
- this.el.addClass("x-resizable-over");
- }
- },
-
- // private
- handleOut : function(){
- if(!this.resizing){
- this.el.removeClass("x-resizable-over");
- }
+ this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
+ }
},
-
/**
- * Returns the element this component is bound to.
- * @return {Roo.Element}
+ * Sets this button's click handler
+ * @param {Function} handler The function to call when the button is clicked
+ * @param {Object} scope (optional) Scope for the function passed above
*/
- getEl : function(){
- return this.el;
+ setHandler : function(handler, scope){
+ this.handler = handler;
+ this.scope = scope;
},
-
+
/**
- * Returns the resizeChild element (or null).
- * @return {Roo.Element}
+ * Sets this button's arrow click handler
+ * @param {Function} handler The function to call when the arrow is clicked
+ * @param {Object} scope (optional) Scope for the function passed above
*/
- getResizeChild : function(){
- return this.resizeChild;
- },
- groupHandler : function()
- {
-
+ setArrowHandler : function(handler, scope){
+ this.arrowHandler = handler;
+ this.scope = scope;
},
+
/**
- * Destroys this resizable. If the element was wrapped and
- * removeEl is not true then the element remains.
- * @param {Boolean} removeEl (optional) true to remove the element from the DOM
+ * Focus the button
*/
- destroy : function(removeEl){
- this.proxy.remove();
- if(this.overlay){
- this.overlay.removeAllListeners();
- this.overlay.remove();
+ focus : function(){
+ if(this.el){
+ this.el.child("button:first").focus();
}
- var ps = Roo.Resizable.positions;
- for(var k in ps){
- if(typeof ps[k] != "function" && this[ps[k]]){
- var h = this[ps[k]];
- h.el.removeAllListeners();
- h.el.remove();
+ },
+
+ // private
+ onClick : function(e){
+ e.preventDefault();
+ if(!this.disabled){
+ if(e.getTarget(".x-btn-menu-arrow-wrap")){
+ if(this.menu && !this.menu.isVisible()){
+ this.menu.show(this.el, this.menuAlign);
+ }
+ this.fireEvent("arrowclick", this, e);
+ if(this.arrowHandler){
+ this.arrowHandler.call(this.scope || this, this, e);
+ }
+ }else{
+ this.fireEvent("click", this, e);
+ if(this.handler){
+ this.handler.call(this.scope || this, this, e);
+ }
}
}
- if(removeEl){
- this.el.update("");
- this.el.remove();
- }
- }
-});
-
-// private
-// hash to map config positions to true positions
-Roo.Resizable.positions = {
- n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast",
- hd: "hdrag"
-};
-
-// private
-Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
- if(!this.tpl){
- // only initialize the template if resizable is used
- var tpl = Roo.DomHelper.createTemplate(
- {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
- );
- tpl.compile();
- Roo.Resizable.Handle.prototype.tpl = tpl;
- }
- this.position = pos;
- this.rz = rz;
- // show north drag fro topdra
- var handlepos = pos == 'hdrag' ? 'north' : pos;
-
- this.el = this.tpl.append(rz.el.dom, [handlepos], true);
- if (pos == 'hdrag') {
- this.el.setStyle('cursor', 'pointer');
- }
- this.el.unselectable();
- if(transparent){
- this.el.setOpacity(0);
- }
- this.el.on("mousedown", this.onMouseDown, this);
- if(!disableTrackOver){
- this.el.on("mouseover", this.onMouseOver, this);
- this.el.on("mouseout", this.onMouseOut, this);
- }
-};
-
-// private
-Roo.Resizable.Handle.prototype = {
- afterResize : function(rz){
- Roo.log('after?');
- // do nothing
},
// private
onMouseDown : function(e){
- this.rz.onMouseDown(this, e);
- },
- // private
- onMouseOver : function(e){
- this.rz.handleOver(this, e);
+ if(!this.disabled){
+ Roo.fly(e.getTarget("table")).addClass("x-btn-click");
+ }
},
// private
- onMouseOut : function(e){
- this.rz.handleOut(this, e);
- }
-};/*
+ onMouseUp : function(e){
+ Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
+ }
+});
+
+
+// backwards compat
+Roo.MenuButton = Roo.SplitButton;/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
*/
/**
- * @class Roo.Editor
- * @extends Roo.Component
- * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
+ * @class Roo.Toolbar
+ * @children Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
+ * Basic Toolbar class.
* @constructor
- * Create a new Editor
- * @param {Roo.form.Field} field The Field object (or descendant)
- * @param {Object} config The config object
- */
-Roo.Editor = function(field, config){
- Roo.Editor.superclass.constructor.call(this, config);
- this.field = field;
- this.addEvents({
- /**
- * @event beforestartedit
- * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
- * false from the handler of this event.
- * @param {Editor} this
- * @param {Roo.Element} boundEl The underlying element bound to this editor
- * @param {Mixed} value The field value being set
- */
- "beforestartedit" : true,
- /**
- * @event startedit
- * Fires when this editor is displayed
- * @param {Roo.Element} boundEl The underlying element bound to this editor
- * @param {Mixed} value The starting field value
- */
- "startedit" : true,
- /**
- * @event beforecomplete
- * Fires after a change has been made to the field, but before the change is reflected in the underlying
- * field. Saving the change to the field can be canceled by returning false from the handler of this event.
- * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
- * event will not fire since no edit actually occurred.
- * @param {Editor} this
- * @param {Mixed} value The current field value
- * @param {Mixed} startValue The original field value
- */
- "beforecomplete" : true,
- /**
- * @event complete
- * Fires after editing is complete and any changed value has been written to the underlying field.
- * @param {Editor} this
- * @param {Mixed} value The current field value
- * @param {Mixed} startValue The original field value
- */
- "complete" : true,
- /**
- * @event specialkey
- * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
- * {@link Roo.EventObject#getKey} to determine which key was pressed.
- * @param {Roo.form.Field} this
- * @param {Roo.EventObject} e The event object
- */
- "specialkey" : true
- });
+ * Creates a new Toolbar
+ * @param {Object} container The config object
+ */
+Roo.Toolbar = function(container, buttons, config)
+{
+ /// old consturctor format still supported..
+ if(container instanceof Array){ // omit the container for later rendering
+ buttons = container;
+ config = buttons;
+ container = null;
+ }
+ if (typeof(container) == 'object' && container.xtype) {
+ config = container;
+ container = config.container;
+ buttons = config.buttons || []; // not really - use items!!
+ }
+ var xitems = [];
+ if (config && config.items) {
+ xitems = config.items;
+ delete config.items;
+ }
+ Roo.apply(this, config);
+ this.buttons = buttons;
+
+ if(container){
+ this.render(container);
+ }
+ this.xitems = xitems;
+ Roo.each(xitems, function(b) {
+ this.add(b);
+ }, this);
+
};
-Roo.extend(Roo.Editor, Roo.Component, {
- /**
- * @cfg {Boolean/String} autosize
- * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
- * or "height" to adopt the height only (defaults to false)
- */
- /**
- * @cfg {Boolean} revertInvalid
- * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
- * validation fails (defaults to true)
- */
- /**
- * @cfg {Boolean} ignoreNoChange
- * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
- * the value has not changed (defaults to false). Applies only to string values - edits for other data types
- * will never be ignored.
- */
- /**
- * @cfg {Boolean} hideEl
- * False to keep the bound element visible while the editor is displayed (defaults to true)
- */
- /**
- * @cfg {Mixed} value
- * The data value of the underlying field (defaults to "")
- */
- value : "",
- /**
- * @cfg {String} alignment
- * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
- */
- alignment: "c-c?",
- /**
- * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
- * for bottom-right shadow (defaults to "frame")
- */
- shadow : "frame",
- /**
- * @cfg {Boolean} constrain True to constrain the editor to the viewport
- */
- constrain : false,
- /**
- * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
- */
- completeOnEnter : false,
+Roo.Toolbar.prototype = {
/**
- * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
+ * @cfg {Array} items
+ * array of button configs or elements to add (will be converted to a MixedCollection)
*/
- cancelOnEsc : false,
+ items: false,
/**
- * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
+ * @cfg {String/HTMLElement/Element} container
+ * The id or element that will contain the toolbar
*/
- updateEl : false,
-
// private
- onRender : function(ct, position){
- this.el = new Roo.Layer({
- shadow: this.shadow,
- cls: "x-editor",
- parentEl : ct,
- shim : this.shim,
- shadowOffset:4,
- id: this.id,
- constrain: this.constrain
- });
- this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
- if(this.field.msgTarget != 'title'){
- this.field.msgTarget = 'qtip';
- }
- this.field.render(this.el);
- if(Roo.isGecko){
- this.field.el.dom.setAttribute('autocomplete', 'off');
- }
- this.field.on("specialkey", this.onSpecialKey, this);
- if(this.swallowKeys){
- this.field.el.swallowEvent(['keydown','keypress']);
+ render : function(ct){
+ this.el = Roo.get(ct);
+ if(this.cls){
+ this.el.addClass(this.cls);
}
- this.field.show();
- this.field.on("blur", this.onBlur, this);
- if(this.field.grow){
- this.field.on("autosize", this.el.sync, this.el, {delay:1});
+ // using a table allows for vertical alignment
+ // 100% width is needed by Safari...
+ this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
+ this.tr = this.el.child("tr", true);
+ var autoId = 0;
+ this.items = new Roo.util.MixedCollection(false, function(o){
+ return o.id || ("item" + (++autoId));
+ });
+ if(this.buttons){
+ this.add.apply(this, this.buttons);
+ delete this.buttons;
}
},
- onSpecialKey : function(field, e)
- {
- //Roo.log('editor onSpecialKey');
- if(this.completeOnEnter && e.getKey() == e.ENTER){
- e.stopEvent();
- this.completeEdit();
- return;
- }
- // do not fire special key otherwise it might hide close the editor...
- if(e.getKey() == e.ENTER){
- return;
- }
- if(this.cancelOnEsc && e.getKey() == e.ESC){
- this.cancelEdit();
- return;
- }
- this.fireEvent('specialkey', field, e);
-
- },
-
/**
- * Starts the editing process and shows the editor.
- * @param {String/HTMLElement/Element} el The element to edit
- * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
- * to the innerHTML of el.
+ * Adds element(s) to the toolbar -- this function takes a variable number of
+ * arguments of mixed type and adds them to the toolbar.
+ * @param {Mixed} arg1 The following types of arguments are all valid:<br />
+ * <ul>
+ * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
+ * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
+ * <li>Field: Any form field (equivalent to {@link #addField})</li>
+ * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
+ * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
+ * Note that there are a few special strings that are treated differently as explained nRoo.</li>
+ * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
+ * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
+ * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
+ * </ul>
+ * @param {Mixed} arg2
+ * @param {Mixed} etc.
*/
- startEdit : function(el, value){
- if(this.editing){
- this.completeEdit();
+ add : function(){
+ var a = arguments, l = a.length;
+ for(var i = 0; i < l; i++){
+ this._add(a[i]);
}
- this.boundEl = Roo.get(el);
- var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
- if(!this.rendered){
- this.render(this.parentEl || document.body);
+ },
+ // private..
+ _add : function(el) {
+
+ if (el.xtype) {
+ el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
}
- if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
- return;
+
+ if (el.applyTo){ // some kind of form field
+ return this.addField(el);
+ }
+ if (el.render){ // some kind of Toolbar.Item
+ return this.addItem(el);
}
- this.startValue = v;
- this.field.setValue(v);
- if(this.autoSize){
- var sz = this.boundEl.getSize();
- switch(this.autoSize){
- case "width":
- this.setSize(sz.width, "");
- break;
- case "height":
- this.setSize("", sz.height);
- break;
- default:
- this.setSize(sz.width, sz.height);
+ if (typeof el == "string"){ // string
+ if(el == "separator" || el == "-"){
+ return this.addSeparator();
+ }
+ if (el == " "){
+ return this.addSpacer();
}
+ if(el == "->"){
+ return this.addFill();
+ }
+ return this.addText(el);
+
}
- this.el.alignTo(this.boundEl, this.alignment);
- this.editing = true;
- if(Roo.QuickTips){
- Roo.QuickTips.disable();
+ if(el.tagName){ // element
+ return this.addElement(el);
}
- this.show();
+ if(typeof el == "object"){ // must be button config?
+ return this.addButton(el);
+ }
+ // and now what?!?!
+ return false;
+
+ },
+
+ /**
+ * Add an Xtype element
+ * @param {Object} xtype Xtype Object
+ * @return {Object} created Object
+ */
+ addxtype : function(e){
+ return this.add(e);
+ },
+
+ /**
+ * Returns the Element for this toolbar.
+ * @return {Roo.Element}
+ */
+ getEl : function(){
+ return this.el;
+ },
+
+ /**
+ * Adds a separator
+ * @return {Roo.Toolbar.Item} The separator item
+ */
+ addSeparator : function(){
+ return this.addItem(new Roo.Toolbar.Separator());
},
/**
- * Sets the height and width of this editor.
- * @param {Number} width The new width
- * @param {Number} height The new height
+ * Adds a spacer element
+ * @return {Roo.Toolbar.Spacer} The spacer item
*/
- setSize : function(w, h){
- this.field.setSize(w, h);
- if(this.el){
- this.el.sync();
- }
+ addSpacer : function(){
+ return this.addItem(new Roo.Toolbar.Spacer());
},
/**
- * Realigns the editor to the bound field based on the current alignment config value.
+ * Adds a fill element that forces subsequent additions to the right side of the toolbar
+ * @return {Roo.Toolbar.Fill} The fill item
*/
- realign : function(){
- this.el.alignTo(this.boundEl, this.alignment);
+ addFill : function(){
+ return this.addItem(new Roo.Toolbar.Fill());
},
/**
- * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
- * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
+ * Adds any standard HTML element to the toolbar
+ * @param {String/HTMLElement/Element} el The element or id of the element to add
+ * @return {Roo.Toolbar.Item} The element's item
*/
- completeEdit : function(remainVisible){
- if(!this.editing){
- return;
- }
- var v = this.getValue();
- if(this.revertInvalid !== false && !this.field.isValid()){
- v = this.startValue;
- this.cancelEdit(true);
- }
- if(String(v) === String(this.startValue) && this.ignoreNoChange){
- this.editing = false;
- this.hide();
- return;
- }
- if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
- this.editing = false;
- if(this.updateEl && this.boundEl){
- this.boundEl.update(v);
- }
- if(remainVisible !== true){
- this.hide();
+ addElement : function(el){
+ return this.addItem(new Roo.Toolbar.Item(el));
+ },
+ /**
+ * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
+ * @type Roo.util.MixedCollection
+ */
+ items : false,
+
+ /**
+ * Adds any Toolbar.Item or subclass
+ * @param {Roo.Toolbar.Item} item
+ * @return {Roo.Toolbar.Item} The item
+ */
+ addItem : function(item){
+ var td = this.nextBlock();
+ item.render(td);
+ this.items.add(item);
+ return item;
+ },
+
+ /**
+ * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
+ * @param {Object/Array} config A button config or array of configs
+ * @return {Roo.Toolbar.Button/Array}
+ */
+ addButton : function(config){
+ if(config instanceof Array){
+ var buttons = [];
+ for(var i = 0, len = config.length; i < len; i++) {
+ buttons.push(this.addButton(config[i]));
}
- this.fireEvent("complete", this, v, this.startValue);
+ return buttons;
+ }
+ var b = config;
+ if(!(config instanceof Roo.Toolbar.Button)){
+ b = config.split ?
+ new Roo.Toolbar.SplitButton(config) :
+ new Roo.Toolbar.Button(config);
}
+ var td = this.nextBlock();
+ b.render(td);
+ this.items.add(b);
+ return b;
},
-
- // private
- onShow : function(){
- this.el.show();
- if(this.hideEl !== false){
- this.boundEl.hide();
+
+ /**
+ * Adds text to the toolbar
+ * @param {String} text The text to add
+ * @return {Roo.Toolbar.Item} The element's item
+ */
+ addText : function(text){
+ return this.addItem(new Roo.Toolbar.TextItem(text));
+ },
+
+ /**
+ * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
+ * @param {Number} index The index where the item is to be inserted
+ * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
+ * @return {Roo.Toolbar.Button/Item}
+ */
+ insertButton : function(index, item){
+ if(item instanceof Array){
+ var buttons = [];
+ for(var i = 0, len = item.length; i < len; i++) {
+ buttons.push(this.insertButton(index + i, item[i]));
+ }
+ return buttons;
}
- this.field.show();
- if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
- this.fixIEFocus = true;
- this.deferredFocus.defer(50, this);
- }else{
- this.field.focus();
+ if (!(item instanceof Roo.Toolbar.Button)){
+ item = new Roo.Toolbar.Button(item);
}
- this.fireEvent("startedit", this.boundEl, this.startValue);
+ var td = document.createElement("td");
+ this.tr.insertBefore(td, this.tr.childNodes[index]);
+ item.render(td);
+ this.items.insert(index, item);
+ return item;
},
-
- deferredFocus : function(){
- if(this.editing){
- this.field.focus();
- }
+
+ /**
+ * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
+ * @param {Object} config
+ * @return {Roo.Toolbar.Item} The element's item
+ */
+ addDom : function(config, returnEl){
+ var td = this.nextBlock();
+ Roo.DomHelper.overwrite(td, config);
+ var ti = new Roo.Toolbar.Item(td.firstChild);
+ ti.render(td);
+ this.items.add(ti);
+ return ti;
},
/**
- * Cancels the editing process and hides the editor without persisting any changes. The field value will be
- * reverted to the original starting value.
- * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
- * cancel (defaults to false)
+ * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
+ * @type Roo.util.MixedCollection
*/
- cancelEdit : function(remainVisible){
- if(this.editing){
- this.setValue(this.startValue);
- if(remainVisible !== true){
- this.hide();
- }
+ fields : false,
+
+ /**
+ * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
+ * Note: the field should not have been rendered yet. For a field that has already been
+ * rendered, use {@link #addElement}.
+ * @param {Roo.form.Field} field
+ * @return {Roo.ToolbarItem}
+ */
+
+
+ addField : function(field) {
+ if (!this.fields) {
+ var autoId = 0;
+ this.fields = new Roo.util.MixedCollection(false, function(o){
+ return o.id || ("item" + (++autoId));
+ });
+
}
+
+ var td = this.nextBlock();
+ field.render(td);
+ var ti = new Roo.Toolbar.Item(td.firstChild);
+ ti.render(td);
+ this.items.add(ti);
+ this.fields.add(field);
+ return ti;
},
-
+ /**
+ * Hide the toolbar
+ * @method hide
+ */
+
+
+ hide : function()
+ {
+ this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
+ this.el.child('div').hide();
+ },
+ /**
+ * Show the toolbar
+ * @method show
+ */
+ show : function()
+ {
+ this.el.child('div').show();
+ },
+
// private
- onBlur : function(){
- if(this.allowBlur !== true && this.editing){
- this.completeEdit();
- }
+ nextBlock : function(){
+ var td = document.createElement("td");
+ this.tr.appendChild(td);
+ return td;
},
// private
- onHide : function(){
- if(this.editing){
- this.completeEdit();
- return;
- }
- this.field.blur();
- if(this.field.collapse){
- this.field.collapse();
- }
- this.el.hide();
- if(this.hideEl !== false){
- this.boundEl.show();
+ destroy : function(){
+ if(this.items){ // rendered?
+ Roo.destroy.apply(Roo, this.items.items);
}
- if(Roo.QuickTips){
- Roo.QuickTips.enable();
+ if(this.fields){ // rendered?
+ Roo.destroy.apply(Roo, this.fields.items);
}
- },
+ Roo.Element.uncache(this.el, this.tr);
+ }
+};
+/**
+ * @class Roo.Toolbar.Item
+ * The base class that other classes should extend in order to get some basic common toolbar item functionality.
+ * @constructor
+ * Creates a new Item
+ * @param {HTMLElement} el
+ */
+Roo.Toolbar.Item = function(el){
+ var cfg = {};
+ if (typeof (el.xtype) != 'undefined') {
+ cfg = el;
+ el = cfg.el;
+ }
+
+ this.el = Roo.getDom(el);
+ this.id = Roo.id(this.el);
+ this.hidden = false;
+
+ this.addEvents({
+ /**
+ * @event render
+ * Fires when the button is rendered
+ * @param {Button} this
+ */
+ 'render': true
+ });
+ Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
+};
+Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
+//Roo.Toolbar.Item.prototype = {
+
/**
- * Sets the data value of the editor
- * @param {Mixed} value Any valid value supported by the underlying field
+ * Get this item's HTML Element
+ * @return {HTMLElement}
*/
- setValue : function(v){
- this.field.setValue(v);
+ getEl : function(){
+ return this.el;
},
+ // private
+ render : function(td){
+
+ this.td = td;
+ td.appendChild(this.el);
+
+ this.fireEvent('render', this);
+ },
+
/**
- * Gets the data value of the editor
- * @return {Mixed} The data value
+ * Removes and destroys this item.
*/
- getValue : function(){
- return this.field.getValue();
+ destroy : function(){
+ this.td.parentNode.removeChild(this.td);
+ },
+
+ /**
+ * Shows this item.
+ */
+ show: function(){
+ this.hidden = false;
+ this.td.style.display = "";
+ },
+
+ /**
+ * Hides this item.
+ */
+ hide: function(){
+ this.hidden = true;
+ this.td.style.display = "none";
+ },
+
+ /**
+ * Convenience function for boolean show/hide.
+ * @param {Boolean} visible true to show/false to hide
+ */
+ setVisible: function(visible){
+ if(visible) {
+ this.show();
+ }else{
+ this.hide();
+ }
+ },
+
+ /**
+ * Try to focus this item.
+ */
+ focus : function(){
+ Roo.fly(this.el).focus();
+ },
+
+ /**
+ * Disables this item.
+ */
+ disable : function(){
+ Roo.fly(this.td).addClass("x-item-disabled");
+ this.disabled = true;
+ this.el.disabled = true;
+ },
+
+ /**
+ * Enables this item.
+ */
+ enable : function(){
+ Roo.fly(this.td).removeClass("x-item-disabled");
+ this.disabled = false;
+ this.el.disabled = false;
}
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
+});
+
+
+/**
+ * @class Roo.Toolbar.Separator
+ * @extends Roo.Toolbar.Item
+ * A simple toolbar separator class
+ * @constructor
+ * Creates a new Separator
*/
-
+Roo.Toolbar.Separator = function(cfg){
+
+ var s = document.createElement("span");
+ s.className = "ytb-sep";
+ if (cfg) {
+ cfg.el = s;
+ }
+
+ Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
+};
+Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
+ enable:Roo.emptyFn,
+ disable:Roo.emptyFn,
+ focus:Roo.emptyFn
+});
+
/**
- * @class Roo.BasicDialog
- * @extends Roo.util.Observable
- * @parent none builder
- * Lightweight Dialog Class. The code below shows the creation of a typical dialog using existing HTML markup:
- * <pre><code>
-var dlg = new Roo.BasicDialog("my-dlg", {
- height: 200,
- width: 300,
- minHeight: 100,
- minWidth: 150,
- modal: true,
- proxyDrag: true,
- shadow: true
-});
-dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
-dlg.addButton('OK', dlg.hide, dlg); // Could call a save function instead of hiding
-dlg.addButton('Cancel', dlg.hide, dlg);
-dlg.show();
-</code></pre>
- <b>A Dialog should always be a direct child of the body element.</b>
- * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
- * @cfg {String} title Default text to display in the title bar (defaults to null)
- * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
- * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
- * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
- * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
- * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
- * (defaults to null with no animation)
- * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
- * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
- * property for valid values (defaults to 'all')
- * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
- * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
- * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
- * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
- * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
- * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
- * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
- * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
- * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
- * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
- * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
- * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
- * draggable = true (defaults to false)
- * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
- * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
- * shadow (defaults to false)
- * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
- * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
- * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
- * @cfg {Array} buttons Array of buttons
- * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
+ * @class Roo.Toolbar.Spacer
+ * @extends Roo.Toolbar.Item
+ * A simple element that adds extra horizontal space to a toolbar.
* @constructor
- * Create a new BasicDialog.
- * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
- * @param {Object} config Configuration options
+ * Creates a new Spacer
*/
-Roo.BasicDialog = function(el, config){
- this.el = Roo.get(el);
- var dh = Roo.DomHelper;
- if(!this.el && config && config.autoCreate){
- if(typeof config.autoCreate == "object"){
- if(!config.autoCreate.id){
- config.autoCreate.id = el;
- }
- this.el = dh.append(document.body,
- config.autoCreate, true);
- }else{
- this.el = dh.append(document.body,
- {tag: "div", id: el, style:'visibility:hidden;'}, true);
- }
- }
- el = this.el;
- el.setDisplayed(true);
- el.hide = this.hideAction;
- this.id = el.id;
- el.addClass("x-dlg");
-
- Roo.apply(this, config);
-
- this.proxy = el.createProxy("x-dlg-proxy");
- this.proxy.hide = this.hideAction;
- this.proxy.setOpacity(.5);
- this.proxy.hide();
-
- if(config.width){
- el.setWidth(config.width);
- }
- if(config.height){
- el.setHeight(config.height);
- }
- this.size = el.getSize();
- if(typeof config.x != "undefined" && typeof config.y != "undefined"){
- this.xy = [config.x,config.y];
- }else{
- this.xy = el.getCenterXY(true);
- }
- /** The header element @type Roo.Element */
- this.header = el.child("> .x-dlg-hd");
- /** The body element @type Roo.Element */
- this.body = el.child("> .x-dlg-bd");
- /** The footer element @type Roo.Element */
- this.footer = el.child("> .x-dlg-ft");
-
- if(!this.header){
- this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
- }
- if(!this.body){
- this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
- }
-
- this.header.unselectable();
- if(this.title){
- this.header.update(this.title);
- }
- // this element allows the dialog to be focused for keyboard event
- this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
- this.focusEl.swallowEvent("click", true);
-
- this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
-
- // wrap the body and footer for special rendering
- this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
- if(this.footer){
- this.bwrap.dom.appendChild(this.footer.dom);
+Roo.Toolbar.Spacer = function(cfg){
+ var s = document.createElement("div");
+ s.className = "ytb-spacer";
+ if (cfg) {
+ cfg.el = s;
}
+ Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
+};
+Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
+ enable:Roo.emptyFn,
+ disable:Roo.emptyFn,
+ focus:Roo.emptyFn
+});
- this.bg = this.el.createChild({
- tag: "div", cls:"x-dlg-bg",
- html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
- });
- this.centerBg = this.bg.child("div.x-dlg-bg-center");
-
-
- if(this.autoScroll !== false && !this.autoTabs){
- this.body.setStyle("overflow", "auto");
+/**
+ * @class Roo.Toolbar.Fill
+ * @extends Roo.Toolbar.Spacer
+ * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
+ * @constructor
+ * Creates a new Spacer
+ */
+Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
+ // private
+ render : function(td){
+ td.style.width = '100%';
+ Roo.Toolbar.Fill.superclass.render.call(this, td);
}
+});
- this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
-
- if(this.closable !== false){
- this.el.addClass("x-dlg-closable");
- this.close = this.toolbox.createChild({cls:"x-dlg-close"});
- this.close.on("click", this.closeClick, this);
- this.close.addClassOnOver("x-dlg-close-over");
- }
- if(this.collapsible !== false){
- this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
- this.collapseBtn.on("click", this.collapseClick, this);
- this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
- this.header.on("dblclick", this.collapseClick, this);
- }
- if(this.resizable !== false){
- this.el.addClass("x-dlg-resizable");
- this.resizer = new Roo.Resizable(el, {
- minWidth: this.minWidth || 80,
- minHeight:this.minHeight || 80,
- handles: this.resizeHandles || "all",
- pinned: true
- });
- this.resizer.on("beforeresize", this.beforeResize, this);
- this.resizer.on("resize", this.onResize, this);
- }
- if(this.draggable !== false){
- el.addClass("x-dlg-draggable");
- if (!this.proxyDrag) {
- var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
- }
- else {
- var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
- }
- dd.setHandleElId(this.header.id);
- dd.endDrag = this.endMove.createDelegate(this);
- dd.startDrag = this.startMove.createDelegate(this);
- dd.onDrag = this.onDrag.createDelegate(this);
- dd.scroll = false;
- this.dd = dd;
- }
- if(this.modal){
- this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
- this.mask.enableDisplayMode("block");
- this.mask.hide();
- this.el.addClass("x-dlg-modal");
- }
- if(this.shadow){
- this.shadow = new Roo.Shadow({
- mode : typeof this.shadow == "string" ? this.shadow : "sides",
- offset : this.shadowOffset
- });
- }else{
- this.shadowOffset = 0;
- }
- if(Roo.useShims && this.shim !== false){
- this.shim = this.el.createShim();
- this.shim.hide = this.hideAction;
- this.shim.hide();
- }else{
- this.shim = false;
- }
- if(this.autoTabs){
- this.initTabs();
+/**
+ * @class Roo.Toolbar.TextItem
+ * @extends Roo.Toolbar.Item
+ * A simple class that renders text directly into a toolbar.
+ * @constructor
+ * Creates a new TextItem
+ * @cfg {string} text
+ */
+Roo.Toolbar.TextItem = function(cfg){
+ var text = cfg || "";
+ if (typeof(cfg) == 'object') {
+ text = cfg.text || "";
+ } else {
+ cfg = null;
}
- if (this.buttons) {
- var bts= this.buttons;
- this.buttons = [];
- Roo.each(bts, function(b) {
- this.addButton(b);
- }, this);
+ var s = document.createElement("span");
+ s.className = "ytb-text";
+ s.innerHTML = text;
+ if (cfg) {
+ cfg.el = s;
}
-
- this.addEvents({
- /**
- * @event keydown
- * Fires when a key is pressed
- * @param {Roo.BasicDialog} this
- * @param {Roo.EventObject} e
- */
- "keydown" : true,
- /**
- * @event move
- * Fires when this dialog is moved by the user.
- * @param {Roo.BasicDialog} this
- * @param {Number} x The new page X
- * @param {Number} y The new page Y
- */
- "move" : true,
- /**
- * @event resize
- * Fires when this dialog is resized by the user.
- * @param {Roo.BasicDialog} this
- * @param {Number} width The new width
- * @param {Number} height The new height
- */
- "resize" : true,
- /**
- * @event beforehide
- * Fires before this dialog is hidden.
- * @param {Roo.BasicDialog} this
- */
- "beforehide" : true,
- /**
- * @event hide
- * Fires when this dialog is hidden.
- * @param {Roo.BasicDialog} this
- */
- "hide" : true,
- /**
- * @event beforeshow
- * Fires before this dialog is shown.
- * @param {Roo.BasicDialog} this
- */
- "beforeshow" : true,
- /**
- * @event show
- * Fires when this dialog is shown.
- * @param {Roo.BasicDialog} this
- */
- "show" : true
- });
- el.on("keydown", this.onKeyDown, this);
- el.on("mousedown", this.toFront, this);
- Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
- this.el.hide();
- Roo.DialogManager.register(this);
- Roo.BasicDialog.superclass.constructor.call(this);
+ Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg || s);
};
-
-Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
- shadowOffset: Roo.isIE ? 6 : 5,
- minHeight: 80,
- minWidth: 200,
- minButtonWidth: 75,
- defaultButton: null,
- buttonAlign: "right",
- tabTag: 'div',
- firstShow: true,
-
- /**
- * Sets the dialog title text
- * @param {String} text The title text to display
- * @return {Roo.BasicDialog} this
+Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
+
+
+ enable:Roo.emptyFn,
+ disable:Roo.emptyFn,
+ focus:Roo.emptyFn,
+ /**
+ * Shows this button
*/
- setTitle : function(text){
- this.header.update(text);
- return this;
- },
-
- // private
- closeClick : function(){
- this.hide();
+ show: function(){
+ this.hidden = false;
+ this.el.style.display = "";
},
+
+ /**
+ * Hides this button
+ */
+ hide: function(){
+ this.hidden = true;
+ this.el.style.display = "none";
+ }
+
+});
- // private
- collapseClick : function(){
- this[this.collapsed ? "expand" : "collapse"]();
+/**
+ * @class Roo.Toolbar.Button
+ * @extends Roo.Button
+ * A button that renders into a toolbar.
+ * @constructor
+ * Creates a new Button
+ * @param {Object} config A standard {@link Roo.Button} config object
+ */
+Roo.Toolbar.Button = function(config){
+ Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
+};
+Roo.extend(Roo.Toolbar.Button, Roo.Button,
+{
+
+
+ render : function(td){
+ this.td = td;
+ Roo.Toolbar.Button.superclass.render.call(this, td);
},
-
+
/**
- * Collapses the dialog to its minimized state (only the title bar is visible).
- * Equivalent to the user clicking the collapse dialog button.
+ * Removes and destroys this button
*/
- collapse : function(){
- if(!this.collapsed){
- this.collapsed = true;
- this.el.addClass("x-dlg-collapsed");
- this.restoreHeight = this.el.getHeight();
- this.resizeTo(this.el.getWidth(), this.header.getHeight());
- }
+ destroy : function(){
+ Roo.Toolbar.Button.superclass.destroy.call(this);
+ this.td.parentNode.removeChild(this.td);
},
-
+
/**
- * Expands a collapsed dialog back to its normal state. Equivalent to the user
- * clicking the expand dialog button.
+ * Shows this button
*/
- expand : function(){
- if(this.collapsed){
- this.collapsed = false;
- this.el.removeClass("x-dlg-collapsed");
- this.resizeTo(this.el.getWidth(), this.restoreHeight);
- }
+ show: function(){
+ this.hidden = false;
+ this.td.style.display = "";
},
-
+
/**
- * Reinitializes the tabs component, clearing out old tabs and finding new ones.
- * @return {Roo.TabPanel} The tabs component
+ * Hides this button
*/
- initTabs : function(){
- var tabs = this.getTabs();
- while(tabs.getTab(0)){
- tabs.removeTab(0);
- }
- this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
- var dom = el.dom;
- tabs.addTab(Roo.id(dom), dom.title);
- dom.title = "";
- });
- tabs.activate(0);
- return tabs;
+ hide: function(){
+ this.hidden = true;
+ this.td.style.display = "none";
},
- // private
- beforeResize : function(){
- this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
+ /**
+ * Disables this item
+ */
+ disable : function(){
+ Roo.fly(this.td).addClass("x-item-disabled");
+ this.disabled = true;
},
- // private
- onResize : function(){
- this.refreshSize();
- this.syncBodyHeight();
- this.adjustAssets();
- this.focus();
- this.fireEvent("resize", this, this.size.width, this.size.height);
- },
+ /**
+ * Enables this item
+ */
+ enable : function(){
+ Roo.fly(this.td).removeClass("x-item-disabled");
+ this.disabled = false;
+ }
+});
+// backwards compat
+Roo.ToolbarButton = Roo.Toolbar.Button;
- // private
- onKeyDown : function(e){
- if(this.isVisible()){
- this.fireEvent("keydown", this, e);
- }
+/**
+ * @class Roo.Toolbar.SplitButton
+ * @extends Roo.SplitButton
+ * A menu button that renders into a toolbar.
+ * @constructor
+ * Creates a new SplitButton
+ * @param {Object} config A standard {@link Roo.SplitButton} config object
+ */
+Roo.Toolbar.SplitButton = function(config){
+ Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
+};
+Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
+ render : function(td){
+ this.td = td;
+ Roo.Toolbar.SplitButton.superclass.render.call(this, td);
},
-
+
/**
- * Resizes the dialog.
- * @param {Number} width
- * @param {Number} height
- * @return {Roo.BasicDialog} this
+ * Removes and destroys this button
*/
- resizeTo : function(width, height){
- this.el.setSize(width, height);
- this.size = {width: width, height: height};
- this.syncBodyHeight();
- if(this.fixedcenter){
- this.center();
- }
- if(this.isVisible()){
- this.constrainXY();
- this.adjustAssets();
- }
- this.fireEvent("resize", this, width, height);
- return this;
+ destroy : function(){
+ Roo.Toolbar.SplitButton.superclass.destroy.call(this);
+ this.td.parentNode.removeChild(this.td);
},
-
-
+
/**
- * Resizes the dialog to fit the specified content size.
- * @param {Number} width
- * @param {Number} height
- * @return {Roo.BasicDialog} this
+ * Shows this button
*/
- setContentSize : function(w, h){
- h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
- w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
- //if(!this.el.isBorderBox()){
- h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
- w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
- //}
- if(this.tabs){
- h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
- w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
- }
- this.resizeTo(w, h);
- return this;
+ show: function(){
+ this.hidden = false;
+ this.td.style.display = "";
},
-
+
/**
- * Adds a key listener for when this dialog is displayed. This allows you to hook in a function that will be
- * executed in response to a particular key being pressed while the dialog is active.
- * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
- * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
- * @param {Function} fn The function to call
- * @param {Object} scope (optional) The scope of the function
- * @return {Roo.BasicDialog} this
+ * Hides this button
*/
- addKeyListener : function(key, fn, scope){
- var keyCode, shift, ctrl, alt;
- if(typeof key == "object" && !(key instanceof Array)){
- keyCode = key["key"];
- shift = key["shift"];
- ctrl = key["ctrl"];
- alt = key["alt"];
- }else{
- keyCode = key;
- }
- var handler = function(dlg, e){
- if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
- var k = e.getKey();
- if(keyCode instanceof Array){
- for(var i = 0, len = keyCode.length; i < len; i++){
- if(keyCode[i] == k){
- fn.call(scope || window, dlg, k, e);
- return;
- }
- }
- }else{
- if(k == keyCode){
- fn.call(scope || window, dlg, k, e);
- }
- }
- }
- };
- this.on("keydown", handler);
- return this;
- },
+ hide: function(){
+ this.hidden = true;
+ this.td.style.display = "none";
+ }
+});
+
+// backwards compat
+Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.PagingToolbar
+ * @extends Roo.Toolbar
+ * @children Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
+ * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
+ * @constructor
+ * Create a new PagingToolbar
+ * @param {Object} config The config object
+ */
+Roo.PagingToolbar = function(el, ds, config)
+{
+ // old args format still supported... - xtype is prefered..
+ if (typeof(el) == 'object' && el.xtype) {
+ // created from xtype...
+ config = el;
+ ds = el.dataSource;
+ el = config.container;
+ }
+ var items = [];
+ if (config.items) {
+ items = config.items;
+ config.items = [];
+ }
+
+ Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
+ this.ds = ds;
+ this.cursor = 0;
+ this.renderButtons(this.el);
+ this.bind(ds);
+
+ // supprot items array.
+
+ Roo.each(items, function(e) {
+ this.add(Roo.factory(e));
+ },this);
+
+};
+Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
+
/**
- * Returns the TabPanel component (creates it if it doesn't exist).
- * Note: If you wish to simply check for the existence of tabs without creating them,
- * check for a null 'tabs' property.
- * @return {Roo.TabPanel} The tabs component
+ * @cfg {String/HTMLElement/Element} container
+ * container The id or element that will contain the toolbar
*/
- getTabs : function(){
- if(!this.tabs){
- this.el.addClass("x-dlg-auto-tabs");
- this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
- this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
- }
- return this.tabs;
- },
-
/**
- * Adds a button to the footer section of the dialog.
- * @param {String/Object} config A string becomes the button text, an object can either be a Button config
- * object or a valid Roo.DomHelper element config
- * @param {Function} handler The function called when the button is clicked
- * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
- * @return {Roo.Button} The new button
+ * @cfg {Boolean} displayInfo
+ * True to display the displayMsg (defaults to false)
*/
- addButton : function(config, handler, scope){
- var dh = Roo.DomHelper;
- if(!this.footer){
- this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
- }
- if(!this.btnContainer){
- var tb = this.footer.createChild({
-
- cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
- html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
- }, null, true);
- this.btnContainer = tb.firstChild.firstChild.firstChild;
- }
- var bconfig = {
- handler: handler,
- scope: scope,
- minWidth: this.minButtonWidth,
- hideParent:true
- };
- if(typeof config == "string"){
- bconfig.text = config;
- }else{
- if(config.tag){
- bconfig.dhconfig = config;
- }else{
- Roo.apply(bconfig, config);
- }
- }
- var fc = false;
- if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
- bconfig.position = Math.max(0, bconfig.position);
- fc = this.btnContainer.childNodes[bconfig.position];
- }
-
- var btn = new Roo.Button(
- fc ?
- this.btnContainer.insertBefore(document.createElement("td"),fc)
- : this.btnContainer.appendChild(document.createElement("td")),
- //Roo.get(this.btnContainer).createChild( { tag: 'td'}, fc ),
- bconfig
- );
- this.syncBodyHeight();
- if(!this.buttons){
- /**
- * Array of all the buttons that have been added to this dialog via addButton
- * @type Array
- */
- this.buttons = [];
- }
- this.buttons.push(btn);
- return btn;
- },
-
+
+
/**
- * Sets the default button to be focused when the dialog is displayed.
- * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
- * @return {Roo.BasicDialog} this
+ * @cfg {Number} pageSize
+ * The number of records to display per page (defaults to 20)
*/
- setDefaultButton : function(btn){
- this.defaultButton = btn;
- return this;
- },
+ pageSize: 20,
+ /**
+ * @cfg {String} displayMsg
+ * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
+ */
+ displayMsg : 'Displaying {0} - {1} of {2}',
+ /**
+ * @cfg {String} emptyMsg
+ * The message to display when no records are found (defaults to "No data to display")
+ */
+ emptyMsg : 'No data to display',
+ /**
+ * Customizable piece of the default paging text (defaults to "Page")
+ * @type String
+ */
+ beforePageText : "Page",
+ /**
+ * Customizable piece of the default paging text (defaults to "of %0")
+ * @type String
+ */
+ afterPageText : "of {0}",
+ /**
+ * Customizable piece of the default paging text (defaults to "First Page")
+ * @type String
+ */
+ firstText : "First Page",
+ /**
+ * Customizable piece of the default paging text (defaults to "Previous Page")
+ * @type String
+ */
+ prevText : "Previous Page",
+ /**
+ * Customizable piece of the default paging text (defaults to "Next Page")
+ * @type String
+ */
+ nextText : "Next Page",
+ /**
+ * Customizable piece of the default paging text (defaults to "Last Page")
+ * @type String
+ */
+ lastText : "Last Page",
+ /**
+ * Customizable piece of the default paging text (defaults to "Refresh")
+ * @type String
+ */
+ refreshText : "Refresh",
// private
- getHeaderFooterHeight : function(safe){
- var height = 0;
- if(this.header){
- height += this.header.getHeight();
- }
- if(this.footer){
- var fm = this.footer.getMargins();
- height += (this.footer.getHeight()+fm.top+fm.bottom);
+ renderButtons : function(el){
+ Roo.PagingToolbar.superclass.render.call(this, el);
+ this.first = this.addButton({
+ tooltip: this.firstText,
+ cls: "x-btn-icon x-grid-page-first",
+ disabled: true,
+ handler: this.onClick.createDelegate(this, ["first"])
+ });
+ this.prev = this.addButton({
+ tooltip: this.prevText,
+ cls: "x-btn-icon x-grid-page-prev",
+ disabled: true,
+ handler: this.onClick.createDelegate(this, ["prev"])
+ });
+ //this.addSeparator();
+ this.add(this.beforePageText);
+ this.field = Roo.get(this.addDom({
+ tag: "input",
+ type: "text",
+ size: "3",
+ value: "1",
+ cls: "x-grid-page-number"
+ }).el);
+ this.field.on("keydown", this.onPagingKeydown, this);
+ this.field.on("focus", function(){this.dom.select();});
+ this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
+ this.field.setHeight(18);
+ //this.addSeparator();
+ this.next = this.addButton({
+ tooltip: this.nextText,
+ cls: "x-btn-icon x-grid-page-next",
+ disabled: true,
+ handler: this.onClick.createDelegate(this, ["next"])
+ });
+ this.last = this.addButton({
+ tooltip: this.lastText,
+ cls: "x-btn-icon x-grid-page-last",
+ disabled: true,
+ handler: this.onClick.createDelegate(this, ["last"])
+ });
+ //this.addSeparator();
+ this.loading = this.addButton({
+ tooltip: this.refreshText,
+ cls: "x-btn-icon x-grid-loading",
+ handler: this.onClick.createDelegate(this, ["refresh"])
+ });
+
+ if(this.displayInfo){
+ this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
}
- height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
- height += this.centerBg.getPadding("tb");
- return height;
},
// private
- syncBodyHeight : function()
- {
- var bd = this.body, // the text
- cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
- bw = this.bwrap;
- var height = this.size.height - this.getHeaderFooterHeight(false);
- bd.setHeight(height-bd.getMargins("tb"));
- var hh = this.header.getHeight();
- var h = this.size.height-hh;
- cb.setHeight(h);
-
- bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
- bw.setHeight(h-cb.getPadding("tb"));
-
- bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
- bd.setWidth(bw.getWidth(true));
- if(this.tabs){
- this.tabs.syncHeight();
- if(Roo.isIE){
- this.tabs.el.repaint();
- }
+ updateInfo : function(){
+ if(this.displayEl){
+ var count = this.ds.getCount();
+ var msg = count == 0 ?
+ this.emptyMsg :
+ String.format(
+ this.displayMsg,
+ this.cursor+1, this.cursor+count, this.ds.getTotalCount()
+ );
+ this.displayEl.update(msg);
}
},
- /**
- * Restores the previous state of the dialog if Roo.state is configured.
- * @return {Roo.BasicDialog} this
- */
- restoreState : function(){
- var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
- if(box && box.width){
- this.xy = [box.x, box.y];
- this.resizeTo(box.width, box.height);
- }
- return this;
+ // private
+ onLoad : function(ds, r, o){
+ this.cursor = o.params ? o.params.start : 0;
+ var d = this.getPageData(), ap = d.activePage, ps = d.pages;
+
+ this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
+ this.field.dom.value = ap;
+ this.first.setDisabled(ap == 1);
+ this.prev.setDisabled(ap == 1);
+ this.next.setDisabled(ap == ps);
+ this.last.setDisabled(ap == ps);
+ this.loading.enable();
+ this.updateInfo();
},
// private
- beforeShow : function(){
- this.expand();
- if(this.fixedcenter){
- this.xy = this.el.getCenterXY(true);
- }
- if(this.modal){
- Roo.get(document.body).addClass("x-body-masked");
- this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
- this.mask.show();
- }
- this.constrainXY();
+ getPageData : function(){
+ var total = this.ds.getTotalCount();
+ return {
+ total : total,
+ activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
+ pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
+ };
},
// private
- animShow : function(){
- var b = Roo.get(this.animateTarget).getBox();
- this.proxy.setSize(b.width, b.height);
- this.proxy.setLocation(b.x, b.y);
- this.proxy.show();
- this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
- true, .35, this.showEl.createDelegate(this));
+ onLoadError : function(){
+ this.loading.enable();
},
- /**
- * Shows the dialog.
- * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
- * @return {Roo.BasicDialog} this
- */
- show : function(animateTarget){
- if (this.fireEvent("beforeshow", this) === false){
- return;
+ // private
+ onPagingKeydown : function(e){
+ var k = e.getKey();
+ var d = this.getPageData();
+ if(k == e.RETURN){
+ var v = this.field.dom.value, pageNum;
+ if(!v || isNaN(pageNum = parseInt(v, 10))){
+ this.field.dom.value = d.activePage;
+ return;
+ }
+ pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
+ this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
+ e.stopEvent();
}
- if(this.syncHeightBeforeShow){
- this.syncBodyHeight();
- }else if(this.firstShow){
- this.firstShow = false;
- this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
+ 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))
+ {
+ var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
+ this.field.dom.value = pageNum;
+ this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
+ e.stopEvent();
}
- this.animateTarget = animateTarget || this.animateTarget;
- if(!this.el.isVisible()){
- this.beforeShow();
- if(this.animateTarget && Roo.get(this.animateTarget)){
- this.animShow();
- }else{
- this.showEl();
- }
+ else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
+ {
+ var v = this.field.dom.value, pageNum;
+ var increment = (e.shiftKey) ? 10 : 1;
+ if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
+ increment *= -1;
+ }
+ if(!v || isNaN(pageNum = parseInt(v, 10))) {
+ this.field.dom.value = d.activePage;
+ return;
+ }
+ else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
+ {
+ this.field.dom.value = parseInt(v, 10) + increment;
+ pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
+ this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
+ }
+ e.stopEvent();
}
- return this;
},
// private
- showEl : function(){
- this.proxy.hide();
- this.el.setXY(this.xy);
- this.el.show();
- this.adjustAssets(true);
- this.toFront();
- this.focus();
- // IE peekaboo bug - fix found by Dave Fenwick
- if(Roo.isIE){
- this.el.repaint();
+ beforeLoad : function(){
+ if(this.loading){
+ this.loading.disable();
}
- this.fireEvent("show", this);
},
-
/**
- * Focuses the dialog. If a defaultButton is set, it will receive focus, otherwise the
- * dialog itself will receive focus.
+ * event that occurs when you click on the navigation buttons - can be used to trigger load of a grid.
+ * @param {String} which (first|prev|next|last|refresh) which button to press.
+ *
*/
- focus : function(){
- if(this.defaultButton){
- this.defaultButton.focus();
- }else{
- this.focusEl.focus();
+ // private
+ onClick : function(which){
+ var ds = this.ds;
+ switch(which){
+ case "first":
+ ds.load({params:{start: 0, limit: this.pageSize}});
+ break;
+ case "prev":
+ ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
+ break;
+ case "next":
+ ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
+ break;
+ case "last":
+ var total = ds.getTotalCount();
+ var extra = total % this.pageSize;
+ var lastStart = extra ? (total - extra) : total-this.pageSize;
+ ds.load({params:{start: lastStart, limit: this.pageSize}});
+ break;
+ case "refresh":
+ ds.load({params:{start: this.cursor, limit: this.pageSize}});
+ break;
}
},
- // private
- constrainXY : function(){
- if(this.constraintoviewport !== false){
- if(!this.viewSize){
- if(this.container){
- var s = this.container.getSize();
- this.viewSize = [s.width, s.height];
- }else{
- this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
- }
- }
- var s = Roo.get(this.container||document).getScroll();
+ /**
+ * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
+ * @param {Roo.data.Store} store The data store to unbind
+ */
+ unbind : function(ds){
+ ds.un("beforeload", this.beforeLoad, this);
+ ds.un("load", this.onLoad, this);
+ ds.un("loadexception", this.onLoadError, this);
+ ds.un("remove", this.updateInfo, this);
+ ds.un("add", this.updateInfo, this);
+ this.ds = undefined;
+ },
- var x = this.xy[0], y = this.xy[1];
- var w = this.size.width, h = this.size.height;
- var vw = this.viewSize[0], vh = this.viewSize[1];
- // only move it if it needs it
- var moved = false;
- // first validate right/bottom
- if(x + w > vw+s.left){
- x = vw - w;
- moved = true;
- }
- if(y + h > vh+s.top){
- y = vh - h;
- moved = true;
- }
- // then make sure top/left isn't negative
- if(x < s.left){
- x = s.left;
- moved = true;
+ /**
+ * Binds the paging toolbar to the specified {@link Roo.data.Store}
+ * @param {Roo.data.Store} store The data store to bind
+ */
+ bind : function(ds){
+ ds.on("beforeload", this.beforeLoad, this);
+ ds.on("load", this.onLoad, this);
+ ds.on("loadexception", this.onLoadError, this);
+ ds.on("remove", this.updateInfo, this);
+ ds.on("add", this.updateInfo, this);
+ this.ds = ds;
+ }
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.Resizable
+ * @extends Roo.util.Observable
+ * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
+ * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
+ * 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
+ * the element will be wrapped for you automatically.</p>
+ * <p>Here is the list of valid resize handles:</p>
+ * <pre>
+Value Description
+------ -------------------
+ 'n' north
+ 's' south
+ 'e' east
+ 'w' west
+ 'nw' northwest
+ 'sw' southwest
+ 'se' southeast
+ 'ne' northeast
+ 'hd' horizontal drag
+ 'all' all
+</pre>
+ * <p>Here's an example showing the creation of a typical Resizable:</p>
+ * <pre><code>
+var resizer = new Roo.Resizable("element-id", {
+ handles: 'all',
+ minWidth: 200,
+ minHeight: 100,
+ maxWidth: 500,
+ maxHeight: 400,
+ pinned: true
+});
+resizer.on("resize", myHandler);
+</code></pre>
+ * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
+ * resizer.east.setDisplayed(false);</p>
+ * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
+ * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
+ * resize operation's new size (defaults to [0, 0])
+ * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
+ * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
+ * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
+ * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
+ * @cfg {Boolean} enabled False to disable resizing (defaults to true)
+ * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
+ * @cfg {Number} width The width of the element in pixels (defaults to null)
+ * @cfg {Number} height The height of the element in pixels (defaults to null)
+ * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
+ * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
+ * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
+ * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
+ * @cfg {Boolean} multiDirectional <b>Deprecated</b>. The old style of adding multi-direction resize handles, deprecated
+ * in favor of the handles config option (defaults to false)
+ * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
+ * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
+ * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
+ * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
+ * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
+ * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
+ * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
+ * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
+ * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
+ * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
+ * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
+ * @constructor
+ * Create a new resizable component
+ * @param {String/HTMLElement/Roo.Element} el The id or element to resize
+ * @param {Object} config configuration options
+ */
+Roo.Resizable = function(el, config)
+{
+ this.el = Roo.get(el);
+
+ if(config && config.wrap){
+ config.resizeChild = this.el;
+ this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
+ this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
+ this.el.setStyle("overflow", "hidden");
+ this.el.setPositioning(config.resizeChild.getPositioning());
+ config.resizeChild.clearPositioning();
+ if(!config.width || !config.height){
+ var csize = config.resizeChild.getSize();
+ this.el.setSize(csize.width, csize.height);
+ }
+ if(config.pinned && !config.adjustments){
+ config.adjustments = "auto";
+ }
+ }
+
+ this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
+ this.proxy.unselectable();
+ this.proxy.enableDisplayMode('block');
+
+ Roo.apply(this, config);
+
+ if(this.pinned){
+ this.disableTrackOver = true;
+ this.el.addClass("x-resizable-pinned");
+ }
+ // if the element isn't positioned, make it relative
+ var position = this.el.getStyle("position");
+ if(position != "absolute" && position != "fixed"){
+ this.el.setStyle("position", "relative");
+ }
+ if(!this.handles){ // no handles passed, must be legacy style
+ this.handles = 's,e,se';
+ if(this.multiDirectional){
+ this.handles += ',n,w';
+ }
+ }
+ if(this.handles == "all"){
+ this.handles = "n s e w ne nw se sw";
+ }
+ var hs = this.handles.split(/\s*?[,;]\s*?| /);
+ var ps = Roo.Resizable.positions;
+ for(var i = 0, len = hs.length; i < len; i++){
+ if(hs[i] && ps[hs[i]]){
+ var pos = ps[hs[i]];
+ this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
+ }
+ }
+ // legacy
+ this.corner = this.southeast;
+
+ // updateBox = the box can move..
+ if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
+ this.updateBox = true;
+ }
+
+ this.activeHandle = null;
+
+ if(this.resizeChild){
+ if(typeof this.resizeChild == "boolean"){
+ this.resizeChild = Roo.get(this.el.dom.firstChild, true);
+ }else{
+ this.resizeChild = Roo.get(this.resizeChild, true);
+ }
+ }
+
+ if(this.adjustments == "auto"){
+ var rc = this.resizeChild;
+ var hw = this.west, he = this.east, hn = this.north, hs = this.south;
+ if(rc && (hw || hn)){
+ rc.position("relative");
+ rc.setLeft(hw ? hw.el.getWidth() : 0);
+ rc.setTop(hn ? hn.el.getHeight() : 0);
+ }
+ this.adjustments = [
+ (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
+ (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
+ ];
+ }
+
+ if(this.draggable){
+ this.dd = this.dynamic ?
+ this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
+ this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
+ }
+
+ // public events
+ this.addEvents({
+ /**
+ * @event beforeresize
+ * Fired before resize is allowed. Set enabled to false to cancel resize.
+ * @param {Roo.Resizable} this
+ * @param {Roo.EventObject} e The mousedown event
+ */
+ "beforeresize" : true,
+ /**
+ * @event resizing
+ * Fired a resizing.
+ * @param {Roo.Resizable} this
+ * @param {Number} x The new x position
+ * @param {Number} y The new y position
+ * @param {Number} w The new w width
+ * @param {Number} h The new h hight
+ * @param {Roo.EventObject} e The mouseup event
+ */
+ "resizing" : true,
+ /**
+ * @event resize
+ * Fired after a resize.
+ * @param {Roo.Resizable} this
+ * @param {Number} width The new width
+ * @param {Number} height The new height
+ * @param {Roo.EventObject} e The mouseup event
+ */
+ "resize" : true
+ });
+
+ if(this.width !== null && this.height !== null){
+ this.resizeTo(this.width, this.height);
+ }else{
+ this.updateChildSize();
+ }
+ if(Roo.isIE){
+ this.el.dom.style.zoom = 1;
+ }
+ Roo.Resizable.superclass.constructor.call(this);
+};
+
+Roo.extend(Roo.Resizable, Roo.util.Observable, {
+ resizeChild : false,
+ adjustments : [0, 0],
+ minWidth : 5,
+ minHeight : 5,
+ maxWidth : 10000,
+ maxHeight : 10000,
+ enabled : true,
+ animate : false,
+ duration : .35,
+ dynamic : false,
+ handles : false,
+ multiDirectional : false,
+ disableTrackOver : false,
+ easing : 'easeOutStrong',
+ widthIncrement : 0,
+ heightIncrement : 0,
+ pinned : false,
+ width : null,
+ height : null,
+ preserveRatio : false,
+ transparent: false,
+ minX: 0,
+ minY: 0,
+ draggable: false,
+
+ /**
+ * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
+ */
+ constrainTo: undefined,
+ /**
+ * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
+ */
+ resizeRegion: undefined,
+
+
+ /**
+ * Perform a manual resize
+ * @param {Number} width
+ * @param {Number} height
+ */
+ resizeTo : function(width, height){
+ this.el.setSize(width, height);
+ this.updateChildSize();
+ this.fireEvent("resize", this, width, height, null);
+ },
+
+ // private
+ startSizing : function(e, handle){
+ this.fireEvent("beforeresize", this, e);
+ if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
+
+ if(!this.overlay){
+ this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: " "});
+ this.overlay.unselectable();
+ this.overlay.enableDisplayMode("block");
+ this.overlay.on("mousemove", this.onMouseMove, this);
+ this.overlay.on("mouseup", this.onMouseUp, this);
}
- if(y < s.top){
- y = s.top;
- moved = true;
+ this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
+
+ this.resizing = true;
+ this.startBox = this.el.getBox();
+ this.startPoint = e.getXY();
+ this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
+ (this.startBox.y + this.startBox.height) - this.startPoint[1]];
+
+ this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
+ this.overlay.show();
+
+ if(this.constrainTo) {
+ var ct = Roo.get(this.constrainTo);
+ this.resizeRegion = ct.getRegion().adjust(
+ ct.getFrameWidth('t'),
+ ct.getFrameWidth('l'),
+ -ct.getFrameWidth('b'),
+ -ct.getFrameWidth('r')
+ );
}
- if(moved){
- // cache xy
- this.xy = [x, y];
- if(this.isVisible()){
- this.el.setLocation(x, y);
- this.adjustAssets();
- }
+
+ this.proxy.setStyle('visibility', 'hidden'); // workaround display none
+ this.proxy.show();
+ this.proxy.setBox(this.startBox);
+ if(!this.dynamic){
+ this.proxy.setStyle('visibility', 'visible');
}
}
},
// private
- onDrag : function(){
- if(!this.proxyDrag){
- this.xy = this.el.getXY();
- this.adjustAssets();
+ onMouseDown : function(handle, e){
+ if(this.enabled){
+ e.stopEvent();
+ this.activeHandle = handle;
+ this.startSizing(e, handle);
}
},
// private
- adjustAssets : function(doShow){
- var x = this.xy[0], y = this.xy[1];
- var w = this.size.width, h = this.size.height;
- if(doShow === true){
- if(this.shadow){
- this.shadow.show(this.el);
+ onMouseUp : function(e){
+ var size = this.resizeElement();
+ this.resizing = false;
+ this.handleOut();
+ this.overlay.hide();
+ this.proxy.hide();
+ this.fireEvent("resize", this, size.width, size.height, e);
+ },
+
+ // private
+ updateChildSize : function(){
+
+ if(this.resizeChild){
+ var el = this.el;
+ var child = this.resizeChild;
+ var adj = this.adjustments;
+ if(el.dom.offsetWidth){
+ var b = el.getSize(true);
+ child.setSize(b.width+adj[0], b.height+adj[1]);
}
- if(this.shim){
- this.shim.show();
+ // Second call here for IE
+ // The first call enables instant resizing and
+ // the second call corrects scroll bars if they
+ // exist
+ if(Roo.isIE){
+ setTimeout(function(){
+ if(el.dom.offsetWidth){
+ var b = el.getSize(true);
+ child.setSize(b.width+adj[0], b.height+adj[1]);
+ }
+ }, 10);
}
}
- if(this.shadow && this.shadow.isVisible()){
- this.shadow.show(this.el);
- }
- if(this.shim && this.shim.isVisible()){
- this.shim.setBounds(x, y, w, h);
- }
},
// private
- adjustViewport : function(w, h){
- if(!w || !h){
- w = Roo.lib.Dom.getViewWidth();
- h = Roo.lib.Dom.getViewHeight();
- }
- // cache the size
- this.viewSize = [w, h];
- if(this.modal && this.mask.isVisible()){
- this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
- this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
+ snap : function(value, inc, min){
+ if(!inc || !value) {
+ return value;
}
- if(this.isVisible()){
- this.constrainXY();
+ var newValue = value;
+ var m = value % inc;
+ if(m > 0){
+ if(m > (inc/2)){
+ newValue = value + (inc-m);
+ }else{
+ newValue = value - m;
+ }
}
+ return Math.max(min, newValue);
},
- /**
- * Destroys this dialog and all its supporting elements (including any tabs, shim,
- * shadow, proxy, mask, etc.) Also removes all event listeners.
- * @param {Boolean} removeEl (optional) true to remove the element from the DOM
- */
- destroy : function(removeEl){
- if(this.isVisible()){
- this.animateTarget = null;
- this.hide();
- }
- Roo.EventManager.removeResizeListener(this.adjustViewport, this);
- if(this.tabs){
- this.tabs.destroy(removeEl);
- }
- Roo.destroy(
- this.shim,
- this.proxy,
- this.resizer,
- this.close,
- this.mask
- );
- if(this.dd){
- this.dd.unreg();
- }
- if(this.buttons){
- for(var i = 0, len = this.buttons.length; i < len; i++){
- this.buttons[i].destroy();
- }
+ // private
+ resizeElement : function(){
+ var box = this.proxy.getBox();
+ if(this.updateBox){
+ this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
+ }else{
+ this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
}
- this.el.removeAllListeners();
- if(removeEl === true){
- this.el.update("");
- this.el.remove();
+ this.updateChildSize();
+ if(!this.dynamic){
+ this.proxy.hide();
}
- Roo.DialogManager.unregister(this);
+ return box;
},
// private
- startMove : function(){
- if(this.proxyDrag){
- this.proxy.show();
- }
- if(this.constraintoviewport !== false){
- this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
+ constrain : function(v, diff, m, mx){
+ if(v - diff < m){
+ diff = v - m;
+ }else if(v - diff > mx){
+ diff = mx - v;
}
+ return diff;
},
// private
- endMove : function(){
- if(!this.proxyDrag){
- Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
- }else{
- Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
- this.proxy.hide();
- }
- this.refreshSize();
- this.adjustAssets();
- this.focus();
- this.fireEvent("move", this, this.xy[0], this.xy[1]);
- },
+ onMouseMove : function(e){
+
+ if(this.enabled){
+ try{// try catch so if something goes wrong the user doesn't get hung
- /**
- * Brings this dialog to the front of any other visible dialogs
- * @return {Roo.BasicDialog} this
- */
- toFront : function(){
- Roo.DialogManager.bringToFront(this);
- return this;
- },
+ if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
+ return;
+ }
- /**
- * Sends this dialog to the back (under) of any other visible dialogs
- * @return {Roo.BasicDialog} this
- */
- toBack : function(){
- Roo.DialogManager.sendToBack(this);
- return this;
- },
+ //var curXY = this.startPoint;
+ var curSize = this.curSize || this.startBox;
+ var x = this.startBox.x, y = this.startBox.y;
+ var ox = x, oy = y;
+ var w = curSize.width, h = curSize.height;
+ var ow = w, oh = h;
+ var mw = this.minWidth, mh = this.minHeight;
+ var mxw = this.maxWidth, mxh = this.maxHeight;
+ var wi = this.widthIncrement;
+ var hi = this.heightIncrement;
- /**
- * Centers this dialog in the viewport
- * @return {Roo.BasicDialog} this
- */
- center : function(){
- var xy = this.el.getCenterXY(true);
- this.moveTo(xy[0], xy[1]);
- return this;
- },
+ var eventXY = e.getXY();
+ var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
+ var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
- /**
- * Moves the dialog's top-left corner to the specified point
- * @param {Number} x
- * @param {Number} y
- * @return {Roo.BasicDialog} this
- */
- moveTo : function(x, y){
- this.xy = [x,y];
- if(this.isVisible()){
- this.el.setXY(this.xy);
- this.adjustAssets();
+ var pos = this.activeHandle.position;
+
+ switch(pos){
+ case "east":
+ w += diffX;
+ w = Math.min(Math.max(mw, w), mxw);
+ break;
+
+ case "south":
+ h += diffY;
+ h = Math.min(Math.max(mh, h), mxh);
+ break;
+ case "southeast":
+ w += diffX;
+ h += diffY;
+ w = Math.min(Math.max(mw, w), mxw);
+ h = Math.min(Math.max(mh, h), mxh);
+ break;
+ case "north":
+ diffY = this.constrain(h, diffY, mh, mxh);
+ y += diffY;
+ h -= diffY;
+ break;
+ case "hdrag":
+
+ if (wi) {
+ var adiffX = Math.abs(diffX);
+ var sub = (adiffX % wi); // how much
+ if (sub > (wi/2)) { // far enough to snap
+ diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
+ } else {
+ // remove difference..
+ diffX = (diffX > 0) ? diffX-sub : diffX+sub;
+ }
+ }
+ x += diffX;
+ x = Math.max(this.minX, x);
+ break;
+ case "west":
+ diffX = this.constrain(w, diffX, mw, mxw);
+ x += diffX;
+ w -= diffX;
+ break;
+ case "northeast":
+ w += diffX;
+ w = Math.min(Math.max(mw, w), mxw);
+ diffY = this.constrain(h, diffY, mh, mxh);
+ y += diffY;
+ h -= diffY;
+ break;
+ case "northwest":
+ diffX = this.constrain(w, diffX, mw, mxw);
+ diffY = this.constrain(h, diffY, mh, mxh);
+ y += diffY;
+ h -= diffY;
+ x += diffX;
+ w -= diffX;
+ break;
+ case "southwest":
+ diffX = this.constrain(w, diffX, mw, mxw);
+ h += diffY;
+ h = Math.min(Math.max(mh, h), mxh);
+ x += diffX;
+ w -= diffX;
+ break;
+ }
+
+ var sw = this.snap(w, wi, mw);
+ var sh = this.snap(h, hi, mh);
+ if(sw != w || sh != h){
+ switch(pos){
+ case "northeast":
+ y -= sh - h;
+ break;
+ case "north":
+ y -= sh - h;
+ break;
+ case "southwest":
+ x -= sw - w;
+ break;
+ case "west":
+ x -= sw - w;
+ break;
+ case "northwest":
+ x -= sw - w;
+ y -= sh - h;
+ break;
+ }
+ w = sw;
+ h = sh;
+ }
+
+ if(this.preserveRatio){
+ switch(pos){
+ case "southeast":
+ case "east":
+ h = oh * (w/ow);
+ h = Math.min(Math.max(mh, h), mxh);
+ w = ow * (h/oh);
+ break;
+ case "south":
+ w = ow * (h/oh);
+ w = Math.min(Math.max(mw, w), mxw);
+ h = oh * (w/ow);
+ break;
+ case "northeast":
+ w = ow * (h/oh);
+ w = Math.min(Math.max(mw, w), mxw);
+ h = oh * (w/ow);
+ break;
+ case "north":
+ var tw = w;
+ w = ow * (h/oh);
+ w = Math.min(Math.max(mw, w), mxw);
+ h = oh * (w/ow);
+ x += (tw - w) / 2;
+ break;
+ case "southwest":
+ h = oh * (w/ow);
+ h = Math.min(Math.max(mh, h), mxh);
+ var tw = w;
+ w = ow * (h/oh);
+ x += tw - w;
+ break;
+ case "west":
+ var th = h;
+ h = oh * (w/ow);
+ h = Math.min(Math.max(mh, h), mxh);
+ y += (th - h) / 2;
+ var tw = w;
+ w = ow * (h/oh);
+ x += tw - w;
+ break;
+ case "northwest":
+ var tw = w;
+ var th = h;
+ h = oh * (w/ow);
+ h = Math.min(Math.max(mh, h), mxh);
+ w = ow * (h/oh);
+ y += th - h;
+ x += tw - w;
+ break;
+
+ }
+ }
+ if (pos == 'hdrag') {
+ w = ow;
+ }
+ this.proxy.setBounds(x, y, w, h);
+ if(this.dynamic){
+ this.resizeElement();
+ }
+ }catch(e){}
}
- return this;
+ this.fireEvent("resizing", this, x, y, w, h, e);
},
- /**
- * Aligns the dialog to the specified element
- * @param {String/HTMLElement/Roo.Element} element The element to align to.
- * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
- * @param {Array} offsets (optional) Offset the positioning by [x, y]
- * @return {Roo.BasicDialog} this
- */
- alignTo : function(element, position, offsets){
- this.xy = this.el.getAlignToXY(element, position, offsets);
- if(this.isVisible()){
- this.el.setXY(this.xy);
- this.adjustAssets();
+ // private
+ handleOver : function(){
+ if(this.enabled){
+ this.el.addClass("x-resizable-over");
}
- return this;
},
- /**
- * Anchors an element to another element and realigns it when the window is resized.
- * @param {String/HTMLElement/Roo.Element} element The element to align to.
- * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
- * @param {Array} offsets (optional) Offset the positioning by [x, y]
- * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
- * is a number, it is used as the buffer delay (defaults to 50ms).
- * @return {Roo.BasicDialog} this
- */
- anchorTo : function(el, alignment, offsets, monitorScroll){
- var action = function(){
- this.alignTo(el, alignment, offsets);
- };
- Roo.EventManager.onWindowResize(action, this);
- var tm = typeof monitorScroll;
- if(tm != 'undefined'){
- Roo.EventManager.on(window, 'scroll', action, this,
- {buffer: tm == 'number' ? monitorScroll : 50});
+ // private
+ handleOut : function(){
+ if(!this.resizing){
+ this.el.removeClass("x-resizable-over");
}
- action.call(this);
- return this;
},
/**
- * Returns true if the dialog is visible
- * @return {Boolean}
+ * Returns the element this component is bound to.
+ * @return {Roo.Element}
*/
- isVisible : function(){
- return this.el.isVisible();
+ getEl : function(){
+ return this.el;
},
- // private
- animHide : function(callback){
- var b = Roo.get(this.animateTarget).getBox();
- this.proxy.show();
- this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
- this.el.hide();
- this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
- this.hideEl.createDelegate(this, [callback]));
+ /**
+ * Returns the resizeChild element (or null).
+ * @return {Roo.Element}
+ */
+ getResizeChild : function(){
+ return this.resizeChild;
+ },
+ groupHandler : function()
+ {
+
},
-
/**
- * Hides the dialog.
- * @param {Function} callback (optional) Function to call when the dialog is hidden
- * @return {Roo.BasicDialog} this
+ * Destroys this resizable. If the element was wrapped and
+ * removeEl is not true then the element remains.
+ * @param {Boolean} removeEl (optional) true to remove the element from the DOM
*/
- hide : function(callback){
- if (this.fireEvent("beforehide", this) === false){
- return;
- }
- if(this.shadow){
- this.shadow.hide();
+ destroy : function(removeEl){
+ this.proxy.remove();
+ if(this.overlay){
+ this.overlay.removeAllListeners();
+ this.overlay.remove();
}
- if(this.shim) {
- this.shim.hide();
+ var ps = Roo.Resizable.positions;
+ for(var k in ps){
+ if(typeof ps[k] != "function" && this[ps[k]]){
+ var h = this[ps[k]];
+ h.el.removeAllListeners();
+ h.el.remove();
+ }
}
- // sometimes animateTarget seems to get set.. causing problems...
- // this just double checks..
- if(this.animateTarget && Roo.get(this.animateTarget)) {
- this.animHide(callback);
- }else{
- this.el.hide();
- this.hideEl(callback);
+ if(removeEl){
+ this.el.update("");
+ this.el.remove();
}
- return this;
- },
+ }
+});
- // private
- hideEl : function(callback){
- this.proxy.hide();
- if(this.modal){
- this.mask.hide();
- Roo.get(document.body).removeClass("x-body-masked");
- }
- this.fireEvent("hide", this);
- if(typeof callback == "function"){
- callback();
- }
- },
+// private
+// hash to map config positions to true positions
+Roo.Resizable.positions = {
+ n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast",
+ hd: "hdrag"
+};
- // private
- hideAction : function(){
- this.setLeft("-10000px");
- this.setTop("-10000px");
- this.setStyle("visibility", "hidden");
- },
+// private
+Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
+ if(!this.tpl){
+ // only initialize the template if resizable is used
+ var tpl = Roo.DomHelper.createTemplate(
+ {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
+ );
+ tpl.compile();
+ Roo.Resizable.Handle.prototype.tpl = tpl;
+ }
+ this.position = pos;
+ this.rz = rz;
+ // show north drag fro topdra
+ var handlepos = pos == 'hdrag' ? 'north' : pos;
+
+ this.el = this.tpl.append(rz.el.dom, [handlepos], true);
+ if (pos == 'hdrag') {
+ this.el.setStyle('cursor', 'pointer');
+ }
+ this.el.unselectable();
+ if(transparent){
+ this.el.setOpacity(0);
+ }
+ this.el.on("mousedown", this.onMouseDown, this);
+ if(!disableTrackOver){
+ this.el.on("mouseover", this.onMouseOver, this);
+ this.el.on("mouseout", this.onMouseOut, this);
+ }
+};
+// private
+Roo.Resizable.Handle.prototype = {
+ afterResize : function(rz){
+ Roo.log('after?');
+ // do nothing
+ },
// private
- refreshSize : function(){
- this.size = this.el.getSize();
- this.xy = this.el.getXY();
- Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
+ onMouseDown : function(e){
+ this.rz.onMouseDown(this, e);
},
-
// private
- // z-index is managed by the DialogManager and may be overwritten at any time
- setZIndex : function(index){
- if(this.modal){
- this.mask.setStyle("z-index", index);
- }
- if(this.shim){
- this.shim.setStyle("z-index", ++index);
- }
- if(this.shadow){
- this.shadow.setZIndex(++index);
- }
- this.el.setStyle("z-index", ++index);
- if(this.proxy){
- this.proxy.setStyle("z-index", ++index);
- }
- if(this.resizer){
- this.resizer.proxy.setStyle("z-index", ++index);
- }
-
- this.lastZIndex = index;
+ onMouseOver : function(e){
+ this.rz.handleOver(this, e);
},
-
- /**
- * Returns the element for this dialog
- * @return {Roo.Element} The underlying dialog Element
- */
- getEl : function(){
- return this.el;
+ // private
+ onMouseOut : function(e){
+ this.rz.handleOut(this, e);
}
-});
+};/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
/**
- * @class Roo.DialogManager
- * Provides global access to BasicDialogs that have been created and
- * support for z-indexing (layering) multiple open dialogs.
+ * @class Roo.Editor
+ * @extends Roo.Component
+ * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
+ * @constructor
+ * Create a new Editor
+ * @param {Roo.form.Field} field The Field object (or descendant)
+ * @param {Object} config The config object
*/
-Roo.DialogManager = function(){
- var list = {};
- var accessList = [];
- var front = null;
-
- // private
- var sortDialogs = function(d1, d2){
- return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
- };
-
- // private
- var orderDialogs = function(){
- accessList.sort(sortDialogs);
- var seed = Roo.DialogManager.zseed;
- for(var i = 0, len = accessList.length; i < len; i++){
- var dlg = accessList[i];
- if(dlg){
- dlg.setZIndex(seed + (i*10));
- }
- }
- };
-
- return {
+Roo.Editor = function(field, config){
+ Roo.Editor.superclass.constructor.call(this, config);
+ this.field = field;
+ this.addEvents({
/**
- * The starting z-index for BasicDialogs (defaults to 9000)
- * @type Number The z-index value
- */
- zseed : 9000,
-
- // private
- register : function(dlg){
- list[dlg.id] = dlg;
- accessList.push(dlg);
- },
-
- // private
- unregister : function(dlg){
- delete list[dlg.id];
- var i=0;
- var len=0;
- if(!accessList.indexOf){
- for( i = 0, len = accessList.length; i < len; i++){
- if(accessList[i] == dlg){
- accessList.splice(i, 1);
- return;
- }
- }
- }else{
- i = accessList.indexOf(dlg);
- if(i != -1){
- accessList.splice(i, 1);
- }
- }
- },
-
+ * @event beforestartedit
+ * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
+ * false from the handler of this event.
+ * @param {Editor} this
+ * @param {Roo.Element} boundEl The underlying element bound to this editor
+ * @param {Mixed} value The field value being set
+ */
+ "beforestartedit" : true,
/**
- * Gets a registered dialog by id
- * @param {String/Object} id The id of the dialog or a dialog
- * @return {Roo.BasicDialog} this
- */
- get : function(id){
- return typeof id == "object" ? id : list[id];
- },
-
+ * @event startedit
+ * Fires when this editor is displayed
+ * @param {Roo.Element} boundEl The underlying element bound to this editor
+ * @param {Mixed} value The starting field value
+ */
+ "startedit" : true,
/**
- * Brings the specified dialog to the front
- * @param {String/Object} dlg The id of the dialog or a dialog
- * @return {Roo.BasicDialog} this
- */
- bringToFront : function(dlg){
- dlg = this.get(dlg);
- if(dlg != front){
- front = dlg;
- dlg._lastAccess = new Date().getTime();
- orderDialogs();
- }
- return dlg;
- },
-
+ * @event beforecomplete
+ * Fires after a change has been made to the field, but before the change is reflected in the underlying
+ * field. Saving the change to the field can be canceled by returning false from the handler of this event.
+ * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
+ * event will not fire since no edit actually occurred.
+ * @param {Editor} this
+ * @param {Mixed} value The current field value
+ * @param {Mixed} startValue The original field value
+ */
+ "beforecomplete" : true,
/**
- * Sends the specified dialog to the back
- * @param {String/Object} dlg The id of the dialog or a dialog
- * @return {Roo.BasicDialog} this
+ * @event complete
+ * Fires after editing is complete and any changed value has been written to the underlying field.
+ * @param {Editor} this
+ * @param {Mixed} value The current field value
+ * @param {Mixed} startValue The original field value
+ */
+ "complete" : true,
+ /**
+ * @event specialkey
+ * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
+ * {@link Roo.EventObject#getKey} to determine which key was pressed.
+ * @param {Roo.form.Field} this
+ * @param {Roo.EventObject} e The event object
*/
- sendToBack : function(dlg){
- dlg = this.get(dlg);
- dlg._lastAccess = -(new Date().getTime());
- orderDialogs();
- return dlg;
- },
-
- /**
- * Hides all dialogs
- */
- hideAll : function(){
- for(var id in list){
- if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
- list[id].hide();
- }
- }
- }
- };
-}();
-
-/**
- * @class Roo.LayoutDialog
- * @extends Roo.BasicDialog
- * @children Roo.ContentPanel
- * @parent builder none
- * Dialog which provides adjustments for working with a layout in a Dialog.
- * Add your necessary layout config options to the dialog's config.<br>
- * Example usage (including a nested layout):
- * <pre><code>
-if(!dialog){
- dialog = new Roo.LayoutDialog("download-dlg", {
- modal: true,
- width:600,
- height:450,
- shadow:true,
- minWidth:500,
- minHeight:350,
- autoTabs:true,
- proxyDrag:true,
- // layout config merges with the dialog config
- center:{
- tabPosition: "top",
- alwaysShowTabs: true
- }
- });
- dialog.addKeyListener(27, dialog.hide, dialog);
- dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
- dialog.addButton("Build It!", this.getDownload, this);
-
- // we can even add nested layouts
- var innerLayout = new Roo.BorderLayout("dl-inner", {
- east: {
- initialSize: 200,
- autoScroll:true,
- split:true
- },
- center: {
- autoScroll:true
- }
+ "specialkey" : true
});
- innerLayout.beginUpdate();
- innerLayout.add("east", new Roo.ContentPanel("dl-details"));
- innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
- innerLayout.endUpdate(true);
-
- var layout = dialog.getLayout();
- layout.beginUpdate();
- layout.add("center", new Roo.ContentPanel("standard-panel",
- {title: "Download the Source", fitToFrame:true}));
- layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
- {title: "Build your own roo.js"}));
- layout.getRegion("center").showPanel(sp);
- layout.endUpdate();
-}
-</code></pre>
- * @constructor
- * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
- * @param {Object} config configuration options
- */
-Roo.LayoutDialog = function(el, cfg){
-
- var config= cfg;
- if (typeof(cfg) == 'undefined') {
- config = Roo.apply({}, el);
- // not sure why we use documentElement here.. - it should always be body.
- // IE7 borks horribly if we use documentElement.
- // webkit also does not like documentElement - it creates a body element...
- el = Roo.get( document.body || document.documentElement ).createChild();
- //config.autoCreate = true;
- }
-
-
- config.autoTabs = false;
- Roo.LayoutDialog.superclass.constructor.call(this, el, config);
- this.body.setStyle({overflow:"hidden", position:"relative"});
- this.layout = new Roo.BorderLayout(this.body.dom, config);
- this.layout.monitorWindowResize = false;
- this.el.addClass("x-dlg-auto-layout");
- // fix case when center region overwrites center function
- this.center = Roo.BasicDialog.prototype.center;
- this.on("show", this.layout.layout, this.layout, true);
- if (config.items) {
- var xitems = config.items;
- delete config.items;
- Roo.each(xitems, this.addxtype, this);
- }
-
-
};
-Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
-
-
+
+Roo.extend(Roo.Editor, Roo.Component, {
/**
- * @cfg {Roo.LayoutRegion} east
+ * @cfg {Boolean/String} autosize
+ * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
+ * or "height" to adopt the height only (defaults to false)
*/
/**
- * @cfg {Roo.LayoutRegion} west
+ * @cfg {Boolean} revertInvalid
+ * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
+ * validation fails (defaults to true)
*/
/**
- * @cfg {Roo.LayoutRegion} south
+ * @cfg {Boolean} ignoreNoChange
+ * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
+ * the value has not changed (defaults to false). Applies only to string values - edits for other data types
+ * will never be ignored.
*/
/**
- * @cfg {Roo.LayoutRegion} north
+ * @cfg {Boolean} hideEl
+ * False to keep the bound element visible while the editor is displayed (defaults to true)
*/
/**
- * @cfg {Roo.LayoutRegion} center
+ * @cfg {Mixed} value
+ * The data value of the underlying field (defaults to "")
*/
+ value : "",
/**
- * @cfg {Roo.Button} buttons[] Bottom buttons..
+ * @cfg {String} alignment
+ * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
*/
+ alignment: "c-c?",
+ /**
+ * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
+ * for bottom-right shadow (defaults to "frame")
+ */
+ shadow : "frame",
+ /**
+ * @cfg {Boolean} constrain True to constrain the editor to the viewport
+ */
+ constrain : false,
+ /**
+ * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
+ */
+ completeOnEnter : false,
+ /**
+ * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
+ */
+ cancelOnEsc : false,
+ /**
+ * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
+ */
+ updateEl : false,
+
+ // private
+ onRender : function(ct, position){
+ this.el = new Roo.Layer({
+ shadow: this.shadow,
+ cls: "x-editor",
+ parentEl : ct,
+ shim : this.shim,
+ shadowOffset:4,
+ id: this.id,
+ constrain: this.constrain
+ });
+ this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
+ if(this.field.msgTarget != 'title'){
+ this.field.msgTarget = 'qtip';
+ }
+ this.field.render(this.el);
+ if(Roo.isGecko){
+ this.field.el.dom.setAttribute('autocomplete', 'off');
+ }
+ this.field.on("specialkey", this.onSpecialKey, this);
+ if(this.swallowKeys){
+ this.field.el.swallowEvent(['keydown','keypress']);
+ }
+ this.field.show();
+ this.field.on("blur", this.onBlur, this);
+ if(this.field.grow){
+ this.field.on("autosize", this.el.sync, this.el, {delay:1});
+ }
+ },
+
+ onSpecialKey : function(field, e)
+ {
+ //Roo.log('editor onSpecialKey');
+ if(this.completeOnEnter && e.getKey() == e.ENTER){
+ e.stopEvent();
+ this.completeEdit();
+ return;
+ }
+ // do not fire special key otherwise it might hide close the editor...
+ if(e.getKey() == e.ENTER){
+ return;
+ }
+ if(this.cancelOnEsc && e.getKey() == e.ESC){
+ this.cancelEdit();
+ return;
+ }
+ this.fireEvent('specialkey', field, e);
-
+ },
+
/**
- * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
- * @deprecated
+ * Starts the editing process and shows the editor.
+ * @param {String/HTMLElement/Element} el The element to edit
+ * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
+ * to the innerHTML of el.
*/
- endUpdate : function(){
- this.layout.endUpdate();
+ startEdit : function(el, value){
+ if(this.editing){
+ this.completeEdit();
+ }
+ this.boundEl = Roo.get(el);
+ var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
+ if(!this.rendered){
+ this.render(this.parentEl || document.body);
+ }
+ if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
+ return;
+ }
+ this.startValue = v;
+ this.field.setValue(v);
+ if(this.autoSize){
+ var sz = this.boundEl.getSize();
+ switch(this.autoSize){
+ case "width":
+ this.setSize(sz.width, "");
+ break;
+ case "height":
+ this.setSize("", sz.height);
+ break;
+ default:
+ this.setSize(sz.width, sz.height);
+ }
+ }
+ this.el.alignTo(this.boundEl, this.alignment);
+ this.editing = true;
+ if(Roo.QuickTips){
+ Roo.QuickTips.disable();
+ }
+ this.show();
},
/**
- * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
- * @deprecated
+ * Sets the height and width of this editor.
+ * @param {Number} width The new width
+ * @param {Number} height The new height
*/
- beginUpdate : function(){
- this.layout.beginUpdate();
+ setSize : function(w, h){
+ this.field.setSize(w, h);
+ if(this.el){
+ this.el.sync();
+ }
},
/**
- * Get the BorderLayout for this dialog
- * @return {Roo.BorderLayout}
+ * Realigns the editor to the bound field based on the current alignment config value.
*/
- getLayout : function(){
- return this.layout;
+ realign : function(){
+ this.el.alignTo(this.boundEl, this.alignment);
},
- showEl : function(){
- Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
- if(Roo.isIE7){
- this.layout.layout();
+ /**
+ * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
+ * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
+ */
+ completeEdit : function(remainVisible){
+ if(!this.editing){
+ return;
+ }
+ var v = this.getValue();
+ if(this.revertInvalid !== false && !this.field.isValid()){
+ v = this.startValue;
+ this.cancelEdit(true);
+ }
+ if(String(v) === String(this.startValue) && this.ignoreNoChange){
+ this.editing = false;
+ this.hide();
+ return;
+ }
+ if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
+ this.editing = false;
+ if(this.updateEl && this.boundEl){
+ this.boundEl.update(v);
+ }
+ if(remainVisible !== true){
+ this.hide();
+ }
+ this.fireEvent("complete", this, v, this.startValue);
}
},
// private
- // Use the syncHeightBeforeShow config option to control this automatically
- syncBodyHeight : function(){
- Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
- if(this.layout){this.layout.layout();}
+ onShow : function(){
+ this.el.show();
+ if(this.hideEl !== false){
+ this.boundEl.hide();
+ }
+ this.field.show();
+ if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
+ this.fixIEFocus = true;
+ this.deferredFocus.defer(50, this);
+ }else{
+ this.field.focus();
+ }
+ this.fireEvent("startedit", this.boundEl, this.startValue);
},
-
- /**
- * Add an xtype element (actually adds to the layout.)
- * @return {Object} xdata xtype object data.
+
+ deferredFocus : function(){
+ if(this.editing){
+ this.field.focus();
+ }
+ },
+
+ /**
+ * Cancels the editing process and hides the editor without persisting any changes. The field value will be
+ * reverted to the original starting value.
+ * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
+ * cancel (defaults to false)
*/
-
- addxtype : function(c) {
- return this.layout.addxtype(c);
+ cancelEdit : function(remainVisible){
+ if(this.editing){
+ this.setValue(this.startValue);
+ if(remainVisible !== true){
+ this.hide();
+ }
+ }
+ },
+
+ // private
+ onBlur : function(){
+ if(this.allowBlur !== true && this.editing){
+ this.completeEdit();
+ }
+ },
+
+ // private
+ onHide : function(){
+ if(this.editing){
+ this.completeEdit();
+ return;
+ }
+ this.field.blur();
+ if(this.field.collapse){
+ this.field.collapse();
+ }
+ this.el.hide();
+ if(this.hideEl !== false){
+ this.boundEl.show();
+ }
+ if(Roo.QuickTips){
+ Roo.QuickTips.enable();
+ }
+ },
+
+ /**
+ * Sets the data value of the editor
+ * @param {Mixed} value Any valid value supported by the underlying field
+ */
+ setValue : function(v){
+ this.field.setValue(v);
+ },
+
+ /**
+ * Gets the data value of the editor
+ * @return {Mixed} The data value
+ */
+ getValue : function(){
+ return this.field.getValue();
}
});/*
* Based on:
*/
/**
- * @class Roo.MessageBox
- * @static
- * Utility class for generating different styles of message boxes. The alias Roo.Msg can also be used.
- * Example usage:
- *<pre><code>
-// Basic alert:
-Roo.Msg.alert('Status', 'Changes saved successfully.');
-
-// Prompt for user data:
-Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
- if (btn == 'ok'){
- // process text value...
- }
-});
-
-// Show a dialog using config options:
-Roo.Msg.show({
- title:'Save Changes?',
- msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
- buttons: Roo.Msg.YESNOCANCEL,
- fn: processResult,
- animEl: 'elId'
+ * @class Roo.BasicDialog
+ * @extends Roo.util.Observable
+ * @parent none builder
+ * Lightweight Dialog Class. The code below shows the creation of a typical dialog using existing HTML markup:
+ * <pre><code>
+var dlg = new Roo.BasicDialog("my-dlg", {
+ height: 200,
+ width: 300,
+ minHeight: 100,
+ minWidth: 150,
+ modal: true,
+ proxyDrag: true,
+ shadow: true
});
+dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
+dlg.addButton('OK', dlg.hide, dlg); // Could call a save function instead of hiding
+dlg.addButton('Cancel', dlg.hide, dlg);
+dlg.show();
</code></pre>
- * @static
+ <b>A Dialog should always be a direct child of the body element.</b>
+ * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
+ * @cfg {String} title Default text to display in the title bar (defaults to null)
+ * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
+ * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
+ * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
+ * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
+ * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
+ * (defaults to null with no animation)
+ * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
+ * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
+ * property for valid values (defaults to 'all')
+ * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
+ * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
+ * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
+ * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
+ * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
+ * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
+ * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
+ * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
+ * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
+ * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
+ * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
+ * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
+ * draggable = true (defaults to false)
+ * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
+ * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
+ * shadow (defaults to false)
+ * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
+ * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
+ * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
+ * @cfg {Array} buttons Array of buttons
+ * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
+ * @constructor
+ * Create a new BasicDialog.
+ * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
+ * @param {Object} config Configuration options
*/
-Roo.MessageBox = function(){
- var dlg, opt, mask, waitTimer;
- var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
- var buttons, activeTextEl, bwidth;
-
- // private
- var handleButton = function(button){
- dlg.hide();
- Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
- };
-
- // private
- var handleHide = function(){
- if(opt && opt.cls){
- dlg.el.removeClass(opt.cls);
- }
- if(waitTimer){
- Roo.TaskMgr.stop(waitTimer);
- waitTimer = null;
- }
- };
-
- // private
- var updateButtons = function(b){
- var width = 0;
- if(!b){
- buttons["ok"].hide();
- buttons["cancel"].hide();
- buttons["yes"].hide();
- buttons["no"].hide();
- dlg.footer.dom.style.display = 'none';
- return width;
- }
- dlg.footer.dom.style.display = '';
- for(var k in buttons){
- if(typeof buttons[k] != "function"){
- if(b[k]){
- buttons[k].show();
- buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
- width += buttons[k].el.getWidth()+15;
- }else{
- buttons[k].hide();
- }
+Roo.BasicDialog = function(el, config){
+ this.el = Roo.get(el);
+ var dh = Roo.DomHelper;
+ if(!this.el && config && config.autoCreate){
+ if(typeof config.autoCreate == "object"){
+ if(!config.autoCreate.id){
+ config.autoCreate.id = el;
}
+ this.el = dh.append(document.body,
+ config.autoCreate, true);
+ }else{
+ this.el = dh.append(document.body,
+ {tag: "div", id: el, style:'visibility:hidden;'}, true);
}
- return width;
- };
+ }
+ el = this.el;
+ el.setDisplayed(true);
+ el.hide = this.hideAction;
+ this.id = el.id;
+ el.addClass("x-dlg");
- // private
- var handleEsc = function(d, k, e){
- if(opt && opt.closable !== false){
- dlg.hide();
+ Roo.apply(this, config);
+
+ this.proxy = el.createProxy("x-dlg-proxy");
+ this.proxy.hide = this.hideAction;
+ this.proxy.setOpacity(.5);
+ this.proxy.hide();
+
+ if(config.width){
+ el.setWidth(config.width);
+ }
+ if(config.height){
+ el.setHeight(config.height);
+ }
+ this.size = el.getSize();
+ if(typeof config.x != "undefined" && typeof config.y != "undefined"){
+ this.xy = [config.x,config.y];
+ }else{
+ this.xy = el.getCenterXY(true);
+ }
+ /** The header element @type Roo.Element */
+ this.header = el.child("> .x-dlg-hd");
+ /** The body element @type Roo.Element */
+ this.body = el.child("> .x-dlg-bd");
+ /** The footer element @type Roo.Element */
+ this.footer = el.child("> .x-dlg-ft");
+
+ if(!this.header){
+ this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
+ }
+ if(!this.body){
+ this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
+ }
+
+ this.header.unselectable();
+ if(this.title){
+ this.header.update(this.title);
+ }
+ // this element allows the dialog to be focused for keyboard event
+ this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
+ this.focusEl.swallowEvent("click", true);
+
+ this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
+
+ // wrap the body and footer for special rendering
+ this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
+ if(this.footer){
+ this.bwrap.dom.appendChild(this.footer.dom);
+ }
+
+ this.bg = this.el.createChild({
+ tag: "div", cls:"x-dlg-bg",
+ html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
+ });
+ this.centerBg = this.bg.child("div.x-dlg-bg-center");
+
+
+ if(this.autoScroll !== false && !this.autoTabs){
+ this.body.setStyle("overflow", "auto");
+ }
+
+ this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
+
+ if(this.closable !== false){
+ this.el.addClass("x-dlg-closable");
+ this.close = this.toolbox.createChild({cls:"x-dlg-close"});
+ this.close.on("click", this.closeClick, this);
+ this.close.addClassOnOver("x-dlg-close-over");
+ }
+ if(this.collapsible !== false){
+ this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
+ this.collapseBtn.on("click", this.collapseClick, this);
+ this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
+ this.header.on("dblclick", this.collapseClick, this);
+ }
+ if(this.resizable !== false){
+ this.el.addClass("x-dlg-resizable");
+ this.resizer = new Roo.Resizable(el, {
+ minWidth: this.minWidth || 80,
+ minHeight:this.minHeight || 80,
+ handles: this.resizeHandles || "all",
+ pinned: true
+ });
+ this.resizer.on("beforeresize", this.beforeResize, this);
+ this.resizer.on("resize", this.onResize, this);
+ }
+ if(this.draggable !== false){
+ el.addClass("x-dlg-draggable");
+ if (!this.proxyDrag) {
+ var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
}
- if(e){
- e.stopEvent();
+ else {
+ var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
}
- };
-
- return {
+ dd.setHandleElId(this.header.id);
+ dd.endDrag = this.endMove.createDelegate(this);
+ dd.startDrag = this.startMove.createDelegate(this);
+ dd.onDrag = this.onDrag.createDelegate(this);
+ dd.scroll = false;
+ this.dd = dd;
+ }
+ if(this.modal){
+ this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
+ this.mask.enableDisplayMode("block");
+ this.mask.hide();
+ this.el.addClass("x-dlg-modal");
+ }
+ if(this.shadow){
+ this.shadow = new Roo.Shadow({
+ mode : typeof this.shadow == "string" ? this.shadow : "sides",
+ offset : this.shadowOffset
+ });
+ }else{
+ this.shadowOffset = 0;
+ }
+ if(Roo.useShims && this.shim !== false){
+ this.shim = this.el.createShim();
+ this.shim.hide = this.hideAction;
+ this.shim.hide();
+ }else{
+ this.shim = false;
+ }
+ if(this.autoTabs){
+ this.initTabs();
+ }
+ if (this.buttons) {
+ var bts= this.buttons;
+ this.buttons = [];
+ Roo.each(bts, function(b) {
+ this.addButton(b);
+ }, this);
+ }
+
+
+ this.addEvents({
/**
- * Returns a reference to the underlying {@link Roo.BasicDialog} element
- * @return {Roo.BasicDialog} The BasicDialog element
+ * @event keydown
+ * Fires when a key is pressed
+ * @param {Roo.BasicDialog} this
+ * @param {Roo.EventObject} e
*/
- getDialog : function(){
- if(!dlg){
- dlg = new Roo.BasicDialog("x-msg-box", {
- autoCreate : true,
- shadow: true,
- draggable: true,
- resizable:false,
- constraintoviewport:false,
- fixedcenter:true,
- collapsible : false,
- shim:true,
- modal: true,
- width:400, height:100,
- buttonAlign:"center",
- closeClick : function(){
- if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
- handleButton("no");
- }else{
- handleButton("cancel");
- }
- }
- });
-
- dlg.on("hide", handleHide);
- mask = dlg.mask;
- dlg.addKeyListener(27, handleEsc);
- buttons = {};
- var bt = this.buttonText;
- buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
- buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
- buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
- buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
- bodyEl = dlg.body.createChild({
+ "keydown" : true,
+ /**
+ * @event move
+ * Fires when this dialog is moved by the user.
+ * @param {Roo.BasicDialog} this
+ * @param {Number} x The new page X
+ * @param {Number} y The new page Y
+ */
+ "move" : true,
+ /**
+ * @event resize
+ * Fires when this dialog is resized by the user.
+ * @param {Roo.BasicDialog} this
+ * @param {Number} width The new width
+ * @param {Number} height The new height
+ */
+ "resize" : true,
+ /**
+ * @event beforehide
+ * Fires before this dialog is hidden.
+ * @param {Roo.BasicDialog} this
+ */
+ "beforehide" : true,
+ /**
+ * @event hide
+ * Fires when this dialog is hidden.
+ * @param {Roo.BasicDialog} this
+ */
+ "hide" : true,
+ /**
+ * @event beforeshow
+ * Fires before this dialog is shown.
+ * @param {Roo.BasicDialog} this
+ */
+ "beforeshow" : true,
+ /**
+ * @event show
+ * Fires when this dialog is shown.
+ * @param {Roo.BasicDialog} this
+ */
+ "show" : true
+ });
+ el.on("keydown", this.onKeyDown, this);
+ el.on("mousedown", this.toFront, this);
+ Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
+ this.el.hide();
+ Roo.DialogManager.register(this);
+ Roo.BasicDialog.superclass.constructor.call(this);
+};
- 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>'
- });
- msgEl = bodyEl.dom.firstChild;
- textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
- textboxEl.enableDisplayMode();
- textboxEl.addKeyListener([10,13], function(){
- if(dlg.isVisible() && opt && opt.buttons){
- if(opt.buttons.ok){
- handleButton("ok");
- }else if(opt.buttons.yes){
- handleButton("yes");
+Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
+ shadowOffset: Roo.isIE ? 6 : 5,
+ minHeight: 80,
+ minWidth: 200,
+ minButtonWidth: 75,
+ defaultButton: null,
+ buttonAlign: "right",
+ tabTag: 'div',
+ firstShow: true,
+
+ /**
+ * Sets the dialog title text
+ * @param {String} text The title text to display
+ * @return {Roo.BasicDialog} this
+ */
+ setTitle : function(text){
+ this.header.update(text);
+ return this;
+ },
+
+ // private
+ closeClick : function(){
+ this.hide();
+ },
+
+ // private
+ collapseClick : function(){
+ this[this.collapsed ? "expand" : "collapse"]();
+ },
+
+ /**
+ * Collapses the dialog to its minimized state (only the title bar is visible).
+ * Equivalent to the user clicking the collapse dialog button.
+ */
+ collapse : function(){
+ if(!this.collapsed){
+ this.collapsed = true;
+ this.el.addClass("x-dlg-collapsed");
+ this.restoreHeight = this.el.getHeight();
+ this.resizeTo(this.el.getWidth(), this.header.getHeight());
+ }
+ },
+
+ /**
+ * Expands a collapsed dialog back to its normal state. Equivalent to the user
+ * clicking the expand dialog button.
+ */
+ expand : function(){
+ if(this.collapsed){
+ this.collapsed = false;
+ this.el.removeClass("x-dlg-collapsed");
+ this.resizeTo(this.el.getWidth(), this.restoreHeight);
+ }
+ },
+
+ /**
+ * Reinitializes the tabs component, clearing out old tabs and finding new ones.
+ * @return {Roo.panel.Tab} The tabs component
+ */
+ initTabs : function(){
+ var tabs = this.getTabs();
+ while(tabs.getTab(0)){
+ tabs.removeTab(0);
+ }
+ this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
+ var dom = el.dom;
+ tabs.addTab(Roo.id(dom), dom.title);
+ dom.title = "";
+ });
+ tabs.activate(0);
+ return tabs;
+ },
+
+ // private
+ beforeResize : function(){
+ this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
+ },
+
+ // private
+ onResize : function(){
+ this.refreshSize();
+ this.syncBodyHeight();
+ this.adjustAssets();
+ this.focus();
+ this.fireEvent("resize", this, this.size.width, this.size.height);
+ },
+
+ // private
+ onKeyDown : function(e){
+ if(this.isVisible()){
+ this.fireEvent("keydown", this, e);
+ }
+ },
+
+ /**
+ * Resizes the dialog.
+ * @param {Number} width
+ * @param {Number} height
+ * @return {Roo.BasicDialog} this
+ */
+ resizeTo : function(width, height){
+ this.el.setSize(width, height);
+ this.size = {width: width, height: height};
+ this.syncBodyHeight();
+ if(this.fixedcenter){
+ this.center();
+ }
+ if(this.isVisible()){
+ this.constrainXY();
+ this.adjustAssets();
+ }
+ this.fireEvent("resize", this, width, height);
+ return this;
+ },
+
+
+ /**
+ * Resizes the dialog to fit the specified content size.
+ * @param {Number} width
+ * @param {Number} height
+ * @return {Roo.BasicDialog} this
+ */
+ setContentSize : function(w, h){
+ h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
+ w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
+ //if(!this.el.isBorderBox()){
+ h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
+ w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
+ //}
+ if(this.tabs){
+ h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
+ w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
+ }
+ this.resizeTo(w, h);
+ return this;
+ },
+
+ /**
+ * Adds a key listener for when this dialog is displayed. This allows you to hook in a function that will be
+ * executed in response to a particular key being pressed while the dialog is active.
+ * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
+ * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
+ * @param {Function} fn The function to call
+ * @param {Object} scope (optional) The scope of the function
+ * @return {Roo.BasicDialog} this
+ */
+ addKeyListener : function(key, fn, scope){
+ var keyCode, shift, ctrl, alt;
+ if(typeof key == "object" && !(key instanceof Array)){
+ keyCode = key["key"];
+ shift = key["shift"];
+ ctrl = key["ctrl"];
+ alt = key["alt"];
+ }else{
+ keyCode = key;
+ }
+ var handler = function(dlg, e){
+ if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
+ var k = e.getKey();
+ if(keyCode instanceof Array){
+ for(var i = 0, len = keyCode.length; i < len; i++){
+ if(keyCode[i] == k){
+ fn.call(scope || window, dlg, k, e);
+ return;
}
}
- });
- textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
- textareaEl.enableDisplayMode();
- progressEl = Roo.get(bodyEl.dom.childNodes[4]);
- progressEl.enableDisplayMode();
- var pf = progressEl.dom.firstChild;
- if (pf) {
- pp = Roo.get(pf.firstChild);
- pp.setHeight(pf.offsetHeight);
+ }else{
+ if(k == keyCode){
+ fn.call(scope || window, dlg, k, e);
+ }
+ }
+ }
+ };
+ this.on("keydown", handler);
+ return this;
+ },
+
+ /**
+ * Returns the panel.Tab component (creates it if it doesn't exist).
+ * Note: If you wish to simply check for the existence of tabs without creating them,
+ * check for a null 'tabs' property.
+ * @return {Roo.panel.Tab} The tabs component
+ */
+ getTabs : function(){
+ if(!this.tabs){
+ this.el.addClass("x-dlg-auto-tabs");
+ this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
+ this.tabs = new Roo.panel.Tab(this.body.dom, this.tabPosition == "bottom");
+ }
+ return this.tabs;
+ },
+
+ /**
+ * Adds a button to the footer section of the dialog.
+ * @param {String/Object} config A string becomes the button text, an object can either be a Button config
+ * object or a valid Roo.DomHelper element config
+ * @param {Function} handler The function called when the button is clicked
+ * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
+ * @return {Roo.Button} The new button
+ */
+ addButton : function(config, handler, scope){
+ var dh = Roo.DomHelper;
+ if(!this.footer){
+ this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
+ }
+ if(!this.btnContainer){
+ var tb = this.footer.createChild({
+
+ cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
+ html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
+ }, null, true);
+ this.btnContainer = tb.firstChild.firstChild.firstChild;
+ }
+ var bconfig = {
+ handler: handler,
+ scope: scope,
+ minWidth: this.minButtonWidth,
+ hideParent:true
+ };
+ if(typeof config == "string"){
+ bconfig.text = config;
+ }else{
+ if(config.tag){
+ bconfig.dhconfig = config;
+ }else{
+ Roo.apply(bconfig, config);
+ }
+ }
+ var fc = false;
+ if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
+ bconfig.position = Math.max(0, bconfig.position);
+ fc = this.btnContainer.childNodes[bconfig.position];
+ }
+
+ var btn = new Roo.Button(
+ fc ?
+ this.btnContainer.insertBefore(document.createElement("td"),fc)
+ : this.btnContainer.appendChild(document.createElement("td")),
+ //Roo.get(this.btnContainer).createChild( { tag: 'td'}, fc ),
+ bconfig
+ );
+ this.syncBodyHeight();
+ if(!this.buttons){
+ /**
+ * Array of all the buttons that have been added to this dialog via addButton
+ * @type Array
+ */
+ this.buttons = [];
+ }
+ this.buttons.push(btn);
+ return btn;
+ },
+
+ /**
+ * Sets the default button to be focused when the dialog is displayed.
+ * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
+ * @return {Roo.BasicDialog} this
+ */
+ setDefaultButton : function(btn){
+ this.defaultButton = btn;
+ return this;
+ },
+
+ // private
+ getHeaderFooterHeight : function(safe){
+ var height = 0;
+ if(this.header){
+ height += this.header.getHeight();
+ }
+ if(this.footer){
+ var fm = this.footer.getMargins();
+ height += (this.footer.getHeight()+fm.top+fm.bottom);
+ }
+ height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
+ height += this.centerBg.getPadding("tb");
+ return height;
+ },
+
+ // private
+ syncBodyHeight : function()
+ {
+ var bd = this.body, // the text
+ cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
+ bw = this.bwrap;
+ var height = this.size.height - this.getHeaderFooterHeight(false);
+ bd.setHeight(height-bd.getMargins("tb"));
+ var hh = this.header.getHeight();
+ var h = this.size.height-hh;
+ cb.setHeight(h);
+
+ bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
+ bw.setHeight(h-cb.getPadding("tb"));
+
+ bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
+ bd.setWidth(bw.getWidth(true));
+ if(this.tabs){
+ this.tabs.syncHeight();
+ if(Roo.isIE){
+ this.tabs.el.repaint();
+ }
+ }
+ },
+
+ /**
+ * Restores the previous state of the dialog if Roo.state is configured.
+ * @return {Roo.BasicDialog} this
+ */
+ restoreState : function(){
+ var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
+ if(box && box.width){
+ this.xy = [box.x, box.y];
+ this.resizeTo(box.width, box.height);
+ }
+ return this;
+ },
+
+ // private
+ beforeShow : function(){
+ this.expand();
+ if(this.fixedcenter){
+ this.xy = this.el.getCenterXY(true);
+ }
+ if(this.modal){
+ Roo.get(document.body).addClass("x-body-masked");
+ this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
+ this.mask.show();
+ }
+ this.constrainXY();
+ },
+
+ // private
+ animShow : function(){
+ var b = Roo.get(this.animateTarget).getBox();
+ this.proxy.setSize(b.width, b.height);
+ this.proxy.setLocation(b.x, b.y);
+ this.proxy.show();
+ this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
+ true, .35, this.showEl.createDelegate(this));
+ },
+
+ /**
+ * Shows the dialog.
+ * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
+ * @return {Roo.BasicDialog} this
+ */
+ show : function(animateTarget){
+ if (this.fireEvent("beforeshow", this) === false){
+ return;
+ }
+ if(this.syncHeightBeforeShow){
+ this.syncBodyHeight();
+ }else if(this.firstShow){
+ this.firstShow = false;
+ this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
+ }
+ this.animateTarget = animateTarget || this.animateTarget;
+ if(!this.el.isVisible()){
+ this.beforeShow();
+ if(this.animateTarget && Roo.get(this.animateTarget)){
+ this.animShow();
+ }else{
+ this.showEl();
+ }
+ }
+ return this;
+ },
+
+ // private
+ showEl : function(){
+ this.proxy.hide();
+ this.el.setXY(this.xy);
+ this.el.show();
+ this.adjustAssets(true);
+ this.toFront();
+ this.focus();
+ // IE peekaboo bug - fix found by Dave Fenwick
+ if(Roo.isIE){
+ this.el.repaint();
+ }
+ this.fireEvent("show", this);
+ },
+
+ /**
+ * Focuses the dialog. If a defaultButton is set, it will receive focus, otherwise the
+ * dialog itself will receive focus.
+ */
+ focus : function(){
+ if(this.defaultButton){
+ this.defaultButton.focus();
+ }else{
+ this.focusEl.focus();
+ }
+ },
+
+ // private
+ constrainXY : function(){
+ if(this.constraintoviewport !== false){
+ if(!this.viewSize){
+ if(this.container){
+ var s = this.container.getSize();
+ this.viewSize = [s.width, s.height];
+ }else{
+ this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
+ }
+ }
+ var s = Roo.get(this.container||document).getScroll();
+
+ var x = this.xy[0], y = this.xy[1];
+ var w = this.size.width, h = this.size.height;
+ var vw = this.viewSize[0], vh = this.viewSize[1];
+ // only move it if it needs it
+ var moved = false;
+ // first validate right/bottom
+ if(x + w > vw+s.left){
+ x = vw - w;
+ moved = true;
+ }
+ if(y + h > vh+s.top){
+ y = vh - h;
+ moved = true;
+ }
+ // then make sure top/left isn't negative
+ if(x < s.left){
+ x = s.left;
+ moved = true;
+ }
+ if(y < s.top){
+ y = s.top;
+ moved = true;
+ }
+ if(moved){
+ // cache xy
+ this.xy = [x, y];
+ if(this.isVisible()){
+ this.el.setLocation(x, y);
+ this.adjustAssets();
+ }
+ }
+ }
+ },
+
+ // private
+ onDrag : function(){
+ if(!this.proxyDrag){
+ this.xy = this.el.getXY();
+ this.adjustAssets();
+ }
+ },
+
+ // private
+ adjustAssets : function(doShow){
+ var x = this.xy[0], y = this.xy[1];
+ var w = this.size.width, h = this.size.height;
+ if(doShow === true){
+ if(this.shadow){
+ this.shadow.show(this.el);
+ }
+ if(this.shim){
+ this.shim.show();
+ }
+ }
+ if(this.shadow && this.shadow.isVisible()){
+ this.shadow.show(this.el);
+ }
+ if(this.shim && this.shim.isVisible()){
+ this.shim.setBounds(x, y, w, h);
+ }
+ },
+
+ // private
+ adjustViewport : function(w, h){
+ if(!w || !h){
+ w = Roo.lib.Dom.getViewWidth();
+ h = Roo.lib.Dom.getViewHeight();
+ }
+ // cache the size
+ this.viewSize = [w, h];
+ if(this.modal && this.mask.isVisible()){
+ this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
+ this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
+ }
+ if(this.isVisible()){
+ this.constrainXY();
+ }
+ },
+
+ /**
+ * Destroys this dialog and all its supporting elements (including any tabs, shim,
+ * shadow, proxy, mask, etc.) Also removes all event listeners.
+ * @param {Boolean} removeEl (optional) true to remove the element from the DOM
+ */
+ destroy : function(removeEl){
+ if(this.isVisible()){
+ this.animateTarget = null;
+ this.hide();
+ }
+ Roo.EventManager.removeResizeListener(this.adjustViewport, this);
+ if(this.tabs){
+ this.tabs.destroy(removeEl);
+ }
+ Roo.destroy(
+ this.shim,
+ this.proxy,
+ this.resizer,
+ this.close,
+ this.mask
+ );
+ if(this.dd){
+ this.dd.unreg();
+ }
+ if(this.buttons){
+ for(var i = 0, len = this.buttons.length; i < len; i++){
+ this.buttons[i].destroy();
+ }
+ }
+ this.el.removeAllListeners();
+ if(removeEl === true){
+ this.el.update("");
+ this.el.remove();
+ }
+ Roo.DialogManager.unregister(this);
+ },
+
+ // private
+ startMove : function(){
+ if(this.proxyDrag){
+ this.proxy.show();
+ }
+ if(this.constraintoviewport !== false){
+ this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
+ }
+ },
+
+ // private
+ endMove : function(){
+ if(!this.proxyDrag){
+ Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
+ }else{
+ Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
+ this.proxy.hide();
+ }
+ this.refreshSize();
+ this.adjustAssets();
+ this.focus();
+ this.fireEvent("move", this, this.xy[0], this.xy[1]);
+ },
+
+ /**
+ * Brings this dialog to the front of any other visible dialogs
+ * @return {Roo.BasicDialog} this
+ */
+ toFront : function(){
+ Roo.DialogManager.bringToFront(this);
+ return this;
+ },
+
+ /**
+ * Sends this dialog to the back (under) of any other visible dialogs
+ * @return {Roo.BasicDialog} this
+ */
+ toBack : function(){
+ Roo.DialogManager.sendToBack(this);
+ return this;
+ },
+
+ /**
+ * Centers this dialog in the viewport
+ * @return {Roo.BasicDialog} this
+ */
+ center : function(){
+ var xy = this.el.getCenterXY(true);
+ this.moveTo(xy[0], xy[1]);
+ return this;
+ },
+
+ /**
+ * Moves the dialog's top-left corner to the specified point
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Roo.BasicDialog} this
+ */
+ moveTo : function(x, y){
+ this.xy = [x,y];
+ if(this.isVisible()){
+ this.el.setXY(this.xy);
+ this.adjustAssets();
+ }
+ return this;
+ },
+
+ /**
+ * Aligns the dialog to the specified element
+ * @param {String/HTMLElement/Roo.Element} element The element to align to.
+ * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
+ * @param {Array} offsets (optional) Offset the positioning by [x, y]
+ * @return {Roo.BasicDialog} this
+ */
+ alignTo : function(element, position, offsets){
+ this.xy = this.el.getAlignToXY(element, position, offsets);
+ if(this.isVisible()){
+ this.el.setXY(this.xy);
+ this.adjustAssets();
+ }
+ return this;
+ },
+
+ /**
+ * Anchors an element to another element and realigns it when the window is resized.
+ * @param {String/HTMLElement/Roo.Element} element The element to align to.
+ * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
+ * @param {Array} offsets (optional) Offset the positioning by [x, y]
+ * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
+ * is a number, it is used as the buffer delay (defaults to 50ms).
+ * @return {Roo.BasicDialog} this
+ */
+ anchorTo : function(el, alignment, offsets, monitorScroll){
+ var action = function(){
+ this.alignTo(el, alignment, offsets);
+ };
+ Roo.EventManager.onWindowResize(action, this);
+ var tm = typeof monitorScroll;
+ if(tm != 'undefined'){
+ Roo.EventManager.on(window, 'scroll', action, this,
+ {buffer: tm == 'number' ? monitorScroll : 50});
+ }
+ action.call(this);
+ return this;
+ },
+
+ /**
+ * Returns true if the dialog is visible
+ * @return {Boolean}
+ */
+ isVisible : function(){
+ return this.el.isVisible();
+ },
+
+ // private
+ animHide : function(callback){
+ var b = Roo.get(this.animateTarget).getBox();
+ this.proxy.show();
+ this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
+ this.el.hide();
+ this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
+ this.hideEl.createDelegate(this, [callback]));
+ },
+
+ /**
+ * Hides the dialog.
+ * @param {Function} callback (optional) Function to call when the dialog is hidden
+ * @return {Roo.BasicDialog} this
+ */
+ hide : function(callback){
+ if (this.fireEvent("beforehide", this) === false){
+ return;
+ }
+ if(this.shadow){
+ this.shadow.hide();
+ }
+ if(this.shim) {
+ this.shim.hide();
+ }
+ // sometimes animateTarget seems to get set.. causing problems...
+ // this just double checks..
+ if(this.animateTarget && Roo.get(this.animateTarget)) {
+ this.animHide(callback);
+ }else{
+ this.el.hide();
+ this.hideEl(callback);
+ }
+ return this;
+ },
+
+ // private
+ hideEl : function(callback){
+ this.proxy.hide();
+ if(this.modal){
+ this.mask.hide();
+ Roo.get(document.body).removeClass("x-body-masked");
+ }
+ this.fireEvent("hide", this);
+ if(typeof callback == "function"){
+ callback();
+ }
+ },
+
+ // private
+ hideAction : function(){
+ this.setLeft("-10000px");
+ this.setTop("-10000px");
+ this.setStyle("visibility", "hidden");
+ },
+
+ // private
+ refreshSize : function(){
+ this.size = this.el.getSize();
+ this.xy = this.el.getXY();
+ Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
+ },
+
+ // private
+ // z-index is managed by the DialogManager and may be overwritten at any time
+ setZIndex : function(index){
+ if(this.modal){
+ this.mask.setStyle("z-index", index);
+ }
+ if(this.shim){
+ this.shim.setStyle("z-index", ++index);
+ }
+ if(this.shadow){
+ this.shadow.setZIndex(++index);
+ }
+ this.el.setStyle("z-index", ++index);
+ if(this.proxy){
+ this.proxy.setStyle("z-index", ++index);
+ }
+ if(this.resizer){
+ this.resizer.proxy.setStyle("z-index", ++index);
+ }
+
+ this.lastZIndex = index;
+ },
+
+ /**
+ * Returns the element for this dialog
+ * @return {Roo.Element} The underlying dialog Element
+ */
+ getEl : function(){
+ return this.el;
+ }
+});
+
+/**
+ * @class Roo.DialogManager
+ * Provides global access to BasicDialogs that have been created and
+ * support for z-indexing (layering) multiple open dialogs.
+ */
+Roo.DialogManager = function(){
+ var list = {};
+ var accessList = [];
+ var front = null;
+
+ // private
+ var sortDialogs = function(d1, d2){
+ return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
+ };
+
+ // private
+ var orderDialogs = function(){
+ accessList.sort(sortDialogs);
+ var seed = Roo.DialogManager.zseed;
+ for(var i = 0, len = accessList.length; i < len; i++){
+ var dlg = accessList[i];
+ if(dlg){
+ dlg.setZIndex(seed + (i*10));
+ }
+ }
+ };
+
+ return {
+ /**
+ * The starting z-index for BasicDialogs (defaults to 9000)
+ * @type Number The z-index value
+ */
+ zseed : 9000,
+
+ // private
+ register : function(dlg){
+ list[dlg.id] = dlg;
+ accessList.push(dlg);
+ },
+
+ // private
+ unregister : function(dlg){
+ delete list[dlg.id];
+ var i=0;
+ var len=0;
+ if(!accessList.indexOf){
+ for( i = 0, len = accessList.length; i < len; i++){
+ if(accessList[i] == dlg){
+ accessList.splice(i, 1);
+ return;
+ }
+ }
+ }else{
+ i = accessList.indexOf(dlg);
+ if(i != -1){
+ accessList.splice(i, 1);
+ }
+ }
+ },
+
+ /**
+ * Gets a registered dialog by id
+ * @param {String/Object} id The id of the dialog or a dialog
+ * @return {Roo.BasicDialog} this
+ */
+ get : function(id){
+ return typeof id == "object" ? id : list[id];
+ },
+
+ /**
+ * Brings the specified dialog to the front
+ * @param {String/Object} dlg The id of the dialog or a dialog
+ * @return {Roo.BasicDialog} this
+ */
+ bringToFront : function(dlg){
+ dlg = this.get(dlg);
+ if(dlg != front){
+ front = dlg;
+ dlg._lastAccess = new Date().getTime();
+ orderDialogs();
+ }
+ return dlg;
+ },
+
+ /**
+ * Sends the specified dialog to the back
+ * @param {String/Object} dlg The id of the dialog or a dialog
+ * @return {Roo.BasicDialog} this
+ */
+ sendToBack : function(dlg){
+ dlg = this.get(dlg);
+ dlg._lastAccess = -(new Date().getTime());
+ orderDialogs();
+ return dlg;
+ },
+
+ /**
+ * Hides all dialogs
+ */
+ hideAll : function(){
+ for(var id in list){
+ if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
+ list[id].hide();
+ }
+ }
+ }
+ };
+}();
+
+/**
+ * @class Roo.LayoutDialog
+ * @extends Roo.BasicDialog
+ * @children Roo.panel.Content
+ * @parent builder none
+ * Dialog which provides adjustments for working with a layout in a Dialog.
+ * Add your necessary layout config options to the dialog's config.<br>
+ * Example usage (including a nested layout):
+ * <pre><code>
+if(!dialog){
+ dialog = new Roo.LayoutDialog("download-dlg", {
+ modal: true,
+ width:600,
+ height:450,
+ shadow:true,
+ minWidth:500,
+ minHeight:350,
+ autoTabs:true,
+ proxyDrag:true,
+ // layout config merges with the dialog config
+ center:{
+ tabPosition: "top",
+ alwaysShowTabs: true
+ }
+ });
+ dialog.addKeyListener(27, dialog.hide, dialog);
+ dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
+ dialog.addButton("Build It!", this.getDownload, this);
+
+ // we can even add nested layouts
+ var innerLayout = new Roo.layout.Border("dl-inner", {
+ east: {
+ initialSize: 200,
+ autoScroll:true,
+ split:true
+ },
+ center: {
+ autoScroll:true
+ }
+ });
+ innerLayout.beginUpdate();
+ innerLayout.add("east", new Roo.panel.Content("dl-details"));
+ innerLayout.add("center", new Roo.panel.Content("selection-panel"));
+ innerLayout.endUpdate(true);
+
+ var layout = dialog.getLayout();
+ layout.beginUpdate();
+ layout.add("center", new Roo.panel.Content("standard-panel",
+ {title: "Download the Source", fitToFrame:true}));
+ layout.add("center", new Roo.panel.NestedLayout(innerLayout,
+ {title: "Build your own roo.js"}));
+ layout.getRegion("center").showPanel(sp);
+ layout.endUpdate();
+}
+</code></pre>
+ * @constructor
+ * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
+ * @param {Object} config configuration options
+ */
+Roo.LayoutDialog = function(el, cfg){
+
+ var config= cfg;
+ if (typeof(cfg) == 'undefined') {
+ config = Roo.apply({}, el);
+ // not sure why we use documentElement here.. - it should always be body.
+ // IE7 borks horribly if we use documentElement.
+ // webkit also does not like documentElement - it creates a body element...
+ el = Roo.get( document.body || document.documentElement ).createChild();
+ //config.autoCreate = true;
+ }
+
+
+ config.autoTabs = false;
+ Roo.LayoutDialog.superclass.constructor.call(this, el, config);
+ this.body.setStyle({overflow:"hidden", position:"relative"});
+ this.layout = new Roo.layout.Border(this.body.dom, config);
+ this.layout.monitorWindowResize = false;
+ this.el.addClass("x-dlg-auto-layout");
+ // fix case when center region overwrites center function
+ this.center = Roo.BasicDialog.prototype.center;
+ this.on("show", this.layout.layout, this.layout, true);
+ if (config.items) {
+ var xitems = config.items;
+ delete config.items;
+ Roo.each(xitems, this.addxtype, this);
+ }
+
+
+};
+Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
+
+
+ /**
+ * @cfg {Roo.layout.Region} east
+ */
+ /**
+ * @cfg {Roo.layout.Region} west
+ */
+ /**
+ * @cfg {Roo.layout.Region} south
+ */
+ /**
+ * @cfg {Roo.layout.Region} north
+ */
+ /**
+ * @cfg {Roo.layout.Region} center
+ */
+ /**
+ * @cfg {Roo.Button} buttons[] Bottom buttons..
+ */
+
+
+ /**
+ * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
+ * @deprecated
+ */
+ endUpdate : function(){
+ this.layout.endUpdate();
+ },
+
+ /**
+ * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
+ * @deprecated
+ */
+ beginUpdate : function(){
+ this.layout.beginUpdate();
+ },
+
+ /**
+ * Get the BorderLayout for this dialog
+ * @return {Roo.layout.Border}
+ */
+ getLayout : function(){
+ return this.layout;
+ },
+
+ showEl : function(){
+ Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
+ if(Roo.isIE7){
+ this.layout.layout();
+ }
+ },
+
+ // private
+ // Use the syncHeightBeforeShow config option to control this automatically
+ syncBodyHeight : function(){
+ Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
+ if(this.layout){this.layout.layout();}
+ },
+
+ /**
+ * Add an xtype element (actually adds to the layout.)
+ * @return {Object} xdata xtype object data.
+ */
+
+ addxtype : function(c) {
+ return this.layout.addxtype(c);
+ }
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.MessageBox
+ * @static
+ * Utility class for generating different styles of message boxes. The alias Roo.Msg can also be used.
+ * Example usage:
+ *<pre><code>
+// Basic alert:
+Roo.Msg.alert('Status', 'Changes saved successfully.');
+
+// Prompt for user data:
+Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
+ if (btn == 'ok'){
+ // process text value...
+ }
+});
+
+// Show a dialog using config options:
+Roo.Msg.show({
+ title:'Save Changes?',
+ msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
+ buttons: Roo.Msg.YESNOCANCEL,
+ fn: processResult,
+ animEl: 'elId'
+});
+</code></pre>
+ * @static
+ */
+Roo.MessageBox = function(){
+ var dlg, opt, mask, waitTimer;
+ var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
+ var buttons, activeTextEl, bwidth;
+
+ // private
+ var handleButton = function(button){
+ dlg.hide();
+ Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
+ };
+
+ // private
+ var handleHide = function(){
+ if(opt && opt.cls){
+ dlg.el.removeClass(opt.cls);
+ }
+ if(waitTimer){
+ Roo.TaskMgr.stop(waitTimer);
+ waitTimer = null;
+ }
+ };
+
+ // private
+ var updateButtons = function(b){
+ var width = 0;
+ if(!b){
+ buttons["ok"].hide();
+ buttons["cancel"].hide();
+ buttons["yes"].hide();
+ buttons["no"].hide();
+ dlg.footer.dom.style.display = 'none';
+ return width;
+ }
+ dlg.footer.dom.style.display = '';
+ for(var k in buttons){
+ if(typeof buttons[k] != "function"){
+ if(b[k]){
+ buttons[k].show();
+ buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
+ width += buttons[k].el.getWidth()+15;
+ }else{
+ buttons[k].hide();
+ }
+ }
+ }
+ return width;
+ };
+
+ // private
+ var handleEsc = function(d, k, e){
+ if(opt && opt.closable !== false){
+ dlg.hide();
+ }
+ if(e){
+ e.stopEvent();
+ }
+ };
+
+ return {
+ /**
+ * Returns a reference to the underlying {@link Roo.BasicDialog} element
+ * @return {Roo.BasicDialog} The BasicDialog element
+ */
+ getDialog : function(){
+ if(!dlg){
+ dlg = new Roo.BasicDialog("x-msg-box", {
+ autoCreate : true,
+ shadow: true,
+ draggable: true,
+ resizable:false,
+ constraintoviewport:false,
+ fixedcenter:true,
+ collapsible : false,
+ shim:true,
+ modal: true,
+ width:400, height:100,
+ buttonAlign:"center",
+ closeClick : function(){
+ if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
+ handleButton("no");
+ }else{
+ handleButton("cancel");
+ }
+ }
+ });
+
+ dlg.on("hide", handleHide);
+ mask = dlg.mask;
+ dlg.addKeyListener(27, handleEsc);
+ buttons = {};
+ var bt = this.buttonText;
+ buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
+ buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
+ buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
+ buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
+ bodyEl = dlg.body.createChild({
+
+ 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>'
+ });
+ msgEl = bodyEl.dom.firstChild;
+ textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
+ textboxEl.enableDisplayMode();
+ textboxEl.addKeyListener([10,13], function(){
+ if(dlg.isVisible() && opt && opt.buttons){
+ if(opt.buttons.ok){
+ handleButton("ok");
+ }else if(opt.buttons.yes){
+ handleButton("yes");
+ }
+ }
+ });
+ textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
+ textareaEl.enableDisplayMode();
+ progressEl = Roo.get(bodyEl.dom.childNodes[4]);
+ progressEl.enableDisplayMode();
+ var pf = progressEl.dom.firstChild;
+ if (pf) {
+ pp = Roo.get(pf.firstChild);
+ pp.setHeight(pf.offsetHeight);
+ }
+
+ }
+ return dlg;
+ },
+
+ /**
+ * Updates the message box body text
+ * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
+ * the XHTML-compliant non-breaking space character '&#160;')
+ * @return {Roo.MessageBox} This message box
+ */
+ updateText : function(text){
+ if(!dlg.isVisible() && !opt.width){
+ dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
+ }
+ msgEl.innerHTML = text || ' ';
+
+ var cw = Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
+ //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
+ var w = Math.max(
+ Math.min(opt.width || cw , this.maxWidth),
+ Math.max(opt.minWidth || this.minWidth, bwidth)
+ );
+ if(opt.prompt){
+ activeTextEl.setWidth(w);
+ }
+ if(dlg.isVisible()){
+ dlg.fixedcenter = false;
+ }
+ // to big, make it scroll. = But as usual stupid IE does not support
+ // !important..
+
+ if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
+ bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
+ bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
+ } else {
+ bodyEl.dom.style.height = '';
+ bodyEl.dom.style.overflowY = '';
+ }
+ if (cw > w) {
+ bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
+ } else {
+ bodyEl.dom.style.overflowX = '';
+ }
+
+ dlg.setContentSize(w, bodyEl.getHeight());
+ if(dlg.isVisible()){
+ dlg.fixedcenter = true;
+ }
+ return this;
+ },
+
+ /**
+ * Updates a progress-style message box's text and progress bar. Only relevant on message boxes
+ * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
+ * @param {Number} value Any number between 0 and 1 (e.g., .5)
+ * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
+ * @return {Roo.MessageBox} This message box
+ */
+ updateProgress : function(value, text){
+ if(text){
+ this.updateText(text);
+ }
+ if (pp) { // weird bug on my firefox - for some reason this is not defined
+ pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
+ }
+ return this;
+ },
+
+ /**
+ * Returns true if the message box is currently displayed
+ * @return {Boolean} True if the message box is visible, else false
+ */
+ isVisible : function(){
+ return dlg && dlg.isVisible();
+ },
+
+ /**
+ * Hides the message box if it is displayed
+ */
+ hide : function(){
+ if(this.isVisible()){
+ dlg.hide();
+ }
+ },
+
+ /**
+ * Displays a new message box, or reinitializes an existing message box, based on the config options
+ * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
+ * The following config object properties are supported:
+ * <pre>
+Property Type Description
+---------- --------------- ------------------------------------------------------------------------------------
+animEl String/Element An id or Element from which the message box should animate as it opens and
+ closes (defaults to undefined)
+buttons Object/Boolean A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
+ cancel:'Bar'}), or false to not show any buttons (defaults to false)
+closable Boolean False to hide the top-right close button (defaults to true). Note that
+ progress and wait dialogs will ignore this property and always hide the
+ close button as they can only be closed programmatically.
+cls String A custom CSS class to apply to the message box element
+defaultTextHeight Number The default height in pixels of the message box's multiline textarea if
+ displayed (defaults to 75)
+fn Function A callback function to execute after closing the dialog. The arguments to the
+ function will be btn (the name of the button that was clicked, if applicable,
+ e.g. "ok"), and text (the value of the active text field, if applicable).
+ Progress and wait dialogs will ignore this option since they do not respond to
+ user actions and can only be closed programmatically, so any required function
+ should be called by the same code after it closes the dialog.
+icon String A CSS class that provides a background image to be used as an icon for
+ the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
+maxWidth Number The maximum width in pixels of the message box (defaults to 600)
+minWidth Number The minimum width in pixels of the message box (defaults to 100)
+modal Boolean False to allow user interaction with the page while the message box is
+ displayed (defaults to true)
+msg String A string that will replace the existing message box body text (defaults
+ to the XHTML-compliant non-breaking space character ' ')
+multiline Boolean True to prompt the user to enter multi-line text (defaults to false)
+progress Boolean True to display a progress bar (defaults to false)
+progressText String The text to display inside the progress bar if progress = true (defaults to '')
+prompt Boolean True to prompt the user to enter single-line text (defaults to false)
+proxyDrag Boolean True to display a lightweight proxy while dragging (defaults to false)
+title String The title text
+value String The string value to set into the active textbox element if displayed
+wait Boolean True to display a progress bar (defaults to false)
+width Number The width of the dialog in pixels
+</pre>
+ *
+ * Example usage:
+ * <pre><code>
+Roo.Msg.show({
+ title: 'Address',
+ msg: 'Please enter your address:',
+ width: 300,
+ buttons: Roo.MessageBox.OKCANCEL,
+ multiline: true,
+ fn: saveAddress,
+ animEl: 'addAddressBtn'
+});
+</code></pre>
+ * @param {Object} config Configuration options
+ * @return {Roo.MessageBox} This message box
+ */
+ show : function(options)
+ {
+
+ // this causes nightmares if you show one dialog after another
+ // especially on callbacks..
+
+ if(this.isVisible()){
+
+ this.hide();
+ Roo.log("[Roo.Messagebox] Show called while message displayed:" );
+ Roo.log("Old Dialog Message:" + msgEl.innerHTML );
+ Roo.log("New Dialog Message:" + options.msg )
+ //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
+ //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
+
+ }
+ var d = this.getDialog();
+ opt = options;
+ d.setTitle(opt.title || " ");
+ d.close.setDisplayed(opt.closable !== false);
+ activeTextEl = textboxEl;
+ opt.prompt = opt.prompt || (opt.multiline ? true : false);
+ if(opt.prompt){
+ if(opt.multiline){
+ textboxEl.hide();
+ textareaEl.show();
+ textareaEl.setHeight(typeof opt.multiline == "number" ?
+ opt.multiline : this.defaultTextHeight);
+ activeTextEl = textareaEl;
+ }else{
+ textboxEl.show();
+ textareaEl.hide();
+ }
+ }else{
+ textboxEl.hide();
+ textareaEl.hide();
+ }
+ progressEl.setDisplayed(opt.progress === true);
+ this.updateProgress(0);
+ activeTextEl.dom.value = opt.value || "";
+ if(opt.prompt){
+ dlg.setDefaultButton(activeTextEl);
+ }else{
+ var bs = opt.buttons;
+ var db = null;
+ if(bs && bs.ok){
+ db = buttons["ok"];
+ }else if(bs && bs.yes){
+ db = buttons["yes"];
+ }
+ dlg.setDefaultButton(db);
+ }
+ bwidth = updateButtons(opt.buttons);
+ this.updateText(opt.msg);
+ if(opt.cls){
+ d.el.addClass(opt.cls);
+ }
+ d.proxyDrag = opt.proxyDrag === true;
+ d.modal = opt.modal !== false;
+ d.mask = opt.modal !== false ? mask : false;
+ if(!d.isVisible()){
+ // force it to the end of the z-index stack so it gets a cursor in FF
+ document.body.appendChild(dlg.el.dom);
+ d.animateTarget = null;
+ d.show(options.animEl);
+ }
+ dlg.toFront();
+ return this;
+ },
+
+ /**
+ * Displays a message box with a progress bar. This message box has no buttons and is not closeable by
+ * the user. You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
+ * and closing the message box when the process is complete.
+ * @param {String} title The title bar text
+ * @param {String} msg The message box body text
+ * @return {Roo.MessageBox} This message box
+ */
+ progress : function(title, msg){
+ this.show({
+ title : title,
+ msg : msg,
+ buttons: false,
+ progress:true,
+ closable:false,
+ minWidth: this.minProgressWidth,
+ modal : true
+ });
+ return this;
+ },
+
+ /**
+ * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
+ * If a callback function is passed it will be called after the user clicks the button, and the
+ * id of the button that was clicked will be passed as the only parameter to the callback
+ * (could also be the top-right close button).
+ * @param {String} title The title bar text
+ * @param {String} msg The message box body text
+ * @param {Function} fn (optional) The callback function invoked after the message box is closed
+ * @param {Object} scope (optional) The scope of the callback function
+ * @return {Roo.MessageBox} This message box
+ */
+ alert : function(title, msg, fn, scope){
+ this.show({
+ title : title,
+ msg : msg,
+ buttons: this.OK,
+ fn: fn,
+ scope : scope,
+ modal : true
+ });
+ return this;
+ },
+
+ /**
+ * Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
+ * interaction while waiting for a long-running process to complete that does not have defined intervals.
+ * You are responsible for closing the message box when the process is complete.
+ * @param {String} msg The message box body text
+ * @param {String} title (optional) The title bar text
+ * @return {Roo.MessageBox} This message box
+ */
+ wait : function(msg, title){
+ this.show({
+ title : title,
+ msg : msg,
+ buttons: false,
+ closable:false,
+ progress:true,
+ modal:true,
+ width:300,
+ wait:true
+ });
+ waitTimer = Roo.TaskMgr.start({
+ run: function(i){
+ Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
+ },
+ interval: 1000
+ });
+ return this;
+ },
+
+ /**
+ * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
+ * If a callback function is passed it will be called after the user clicks either button, and the id of the
+ * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
+ * @param {String} title The title bar text
+ * @param {String} msg The message box body text
+ * @param {Function} fn (optional) The callback function invoked after the message box is closed
+ * @param {Object} scope (optional) The scope of the callback function
+ * @return {Roo.MessageBox} This message box
+ */
+ confirm : function(title, msg, fn, scope){
+ this.show({
+ title : title,
+ msg : msg,
+ buttons: this.YESNO,
+ fn: fn,
+ scope : scope,
+ modal : true
+ });
+ return this;
+ },
+
+ /**
+ * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
+ * JavaScript's Window.prompt). The prompt can be a single-line or multi-line textbox. If a callback function
+ * is passed it will be called after the user clicks either button, and the id of the button that was clicked
+ * (could also be the top-right close button) and the text that was entered will be passed as the two
+ * parameters to the callback.
+ * @param {String} title The title bar text
+ * @param {String} msg The message box body text
+ * @param {Function} fn (optional) The callback function invoked after the message box is closed
+ * @param {Object} scope (optional) The scope of the callback function
+ * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
+ * property, or the height in pixels to create the textbox (defaults to false / single-line)
+ * @return {Roo.MessageBox} This message box
+ */
+ prompt : function(title, msg, fn, scope, multiline){
+ this.show({
+ title : title,
+ msg : msg,
+ buttons: this.OKCANCEL,
+ fn: fn,
+ minWidth:250,
+ scope : scope,
+ prompt:true,
+ multiline: multiline,
+ modal : true
+ });
+ return this;
+ },
+
+ /**
+ * Button config that displays a single OK button
+ * @type Object
+ */
+ OK : {ok:true},
+ /**
+ * Button config that displays Yes and No buttons
+ * @type Object
+ */
+ YESNO : {yes:true, no:true},
+ /**
+ * Button config that displays OK and Cancel buttons
+ * @type Object
+ */
+ OKCANCEL : {ok:true, cancel:true},
+ /**
+ * Button config that displays Yes, No and Cancel buttons
+ * @type Object
+ */
+ YESNOCANCEL : {yes:true, no:true, cancel:true},
+
+ /**
+ * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
+ * @type Number
+ */
+ defaultTextHeight : 75,
+ /**
+ * The maximum width in pixels of the message box (defaults to 600)
+ * @type Number
+ */
+ maxWidth : 600,
+ /**
+ * The minimum width in pixels of the message box (defaults to 100)
+ * @type Number
+ */
+ minWidth : 100,
+ /**
+ * The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
+ * for setting a different minimum width than text-only dialogs may need (defaults to 250)
+ * @type Number
+ */
+ minProgressWidth : 250,
+ /**
+ * An object containing the default button text strings that can be overriden for localized language support.
+ * Supported properties are: ok, cancel, yes and no.
+ * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
+ * @type Object
+ */
+ buttonText : {
+ ok : "OK",
+ cancel : "Cancel",
+ yes : "Yes",
+ no : "No"
+ }
+ };
+}();
+
+/**
+ * Shorthand for {@link Roo.MessageBox}
+ */
+Roo.Msg = Roo.MessageBox;/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+/**
+ * @class Roo.QuickTips
+ * Provides attractive and customizable tooltips for any element.
+ * @static
+ */
+Roo.QuickTips = function(){
+ var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
+ var ce, bd, xy, dd;
+ var visible = false, disabled = true, inited = false;
+ var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
+
+ var onOver = function(e){
+ if(disabled){
+ return;
+ }
+ var t = e.getTarget();
+ if(!t || t.nodeType !== 1 || t == document || t == document.body){
+ return;
+ }
+ if(ce && t == ce.el){
+ clearTimeout(hideProc);
+ return;
+ }
+ if(t && tagEls[t.id]){
+ tagEls[t.id].el = t;
+ showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
+ return;
+ }
+ var ttp, et = Roo.fly(t);
+ var ns = cfg.namespace;
+ if(tm.interceptTitles && t.title){
+ ttp = t.title;
+ t.qtip = ttp;
+ t.removeAttribute("title");
+ e.preventDefault();
+ }else{
+ ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
+ }
+ if(ttp){
+ showProc = show.defer(tm.showDelay, tm, [{
+ el: t,
+ text: ttp.replace(/\\n/g,'<br/>'),
+ width: et.getAttributeNS(ns, cfg.width),
+ autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
+ title: et.getAttributeNS(ns, cfg.title),
+ cls: et.getAttributeNS(ns, cfg.cls)
+ }]);
+ }
+ };
+
+ var onOut = function(e){
+ clearTimeout(showProc);
+ var t = e.getTarget();
+ if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
+ hideProc = setTimeout(hide, tm.hideDelay);
+ }
+ };
+
+ var onMove = function(e){
+ if(disabled){
+ return;
+ }
+ xy = e.getXY();
+ xy[1] += 18;
+ if(tm.trackMouse && ce){
+ el.setXY(xy);
+ }
+ };
+
+ var onDown = function(e){
+ clearTimeout(showProc);
+ clearTimeout(hideProc);
+ if(!e.within(el)){
+ if(tm.hideOnClick){
+ hide();
+ tm.disable();
+ tm.enable.defer(100, tm);
+ }
+ }
+ };
+
+ var getPad = function(){
+ return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
+ };
+
+ var show = function(o){
+ if(disabled){
+ return;
+ }
+ clearTimeout(dismissProc);
+ ce = o;
+ if(removeCls){ // in case manually hidden
+ el.removeClass(removeCls);
+ removeCls = null;
+ }
+ if(ce.cls){
+ el.addClass(ce.cls);
+ removeCls = ce.cls;
+ }
+ if(ce.title){
+ tipTitle.update(ce.title);
+ tipTitle.show();
+ }else{
+ tipTitle.update('');
+ tipTitle.hide();
+ }
+ el.dom.style.width = tm.maxWidth+'px';
+ //tipBody.dom.style.width = '';
+ tipBodyText.update(o.text);
+ var p = getPad(), w = ce.width;
+ if(!w){
+ var td = tipBodyText.dom;
+ var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
+ if(aw > tm.maxWidth){
+ w = tm.maxWidth;
+ }else if(aw < tm.minWidth){
+ w = tm.minWidth;
+ }else{
+ w = aw;
+ }
+ }
+ //tipBody.setWidth(w);
+ el.setWidth(parseInt(w, 10) + p);
+ if(ce.autoHide === false){
+ close.setDisplayed(true);
+ if(dd){
+ dd.unlock();
+ }
+ }else{
+ close.setDisplayed(false);
+ if(dd){
+ dd.lock();
+ }
+ }
+ if(xy){
+ el.avoidY = xy[1]-18;
+ el.setXY(xy);
+ }
+ if(tm.animate){
+ el.setOpacity(.1);
+ el.setStyle("visibility", "visible");
+ el.fadeIn({callback: afterShow});
+ }else{
+ afterShow();
+ }
+ };
+
+ var afterShow = function(){
+ if(ce){
+ el.show();
+ esc.enable();
+ if(tm.autoDismiss && ce.autoHide !== false){
+ dismissProc = setTimeout(hide, tm.autoDismissDelay);
+ }
+ }
+ };
+
+ var hide = function(noanim){
+ clearTimeout(dismissProc);
+ clearTimeout(hideProc);
+ ce = null;
+ if(el.isVisible()){
+ esc.disable();
+ if(noanim !== true && tm.animate){
+ el.fadeOut({callback: afterHide});
+ }else{
+ afterHide();
+ }
+ }
+ };
+
+ var afterHide = function(){
+ el.hide();
+ if(removeCls){
+ el.removeClass(removeCls);
+ removeCls = null;
+ }
+ };
+
+ return {
+ /**
+ * @cfg {Number} minWidth
+ * The minimum width of the quick tip (defaults to 40)
+ */
+ minWidth : 40,
+ /**
+ * @cfg {Number} maxWidth
+ * The maximum width of the quick tip (defaults to 300)
+ */
+ maxWidth : 300,
+ /**
+ * @cfg {Boolean} interceptTitles
+ * True to automatically use the element's DOM title value if available (defaults to false)
+ */
+ interceptTitles : false,
+ /**
+ * @cfg {Boolean} trackMouse
+ * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
+ */
+ trackMouse : false,
+ /**
+ * @cfg {Boolean} hideOnClick
+ * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
+ */
+ hideOnClick : true,
+ /**
+ * @cfg {Number} showDelay
+ * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
+ */
+ showDelay : 500,
+ /**
+ * @cfg {Number} hideDelay
+ * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
+ */
+ hideDelay : 200,
+ /**
+ * @cfg {Boolean} autoHide
+ * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
+ * Used in conjunction with hideDelay.
+ */
+ autoHide : true,
+ /**
+ * @cfg {Boolean}
+ * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
+ * (defaults to true). Used in conjunction with autoDismissDelay.
+ */
+ autoDismiss : true,
+ /**
+ * @cfg {Number}
+ * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
+ */
+ autoDismissDelay : 5000,
+ /**
+ * @cfg {Boolean} animate
+ * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
+ */
+ animate : false,
+
+ /**
+ * @cfg {String} title
+ * Title text to display (defaults to ''). This can be any valid HTML markup.
+ */
+ title: '',
+ /**
+ * @cfg {String} text
+ * Body text to display (defaults to ''). This can be any valid HTML markup.
+ */
+ text : '',
+ /**
+ * @cfg {String} cls
+ * A CSS class to apply to the base quick tip element (defaults to '').
+ */
+ cls : '',
+ /**
+ * @cfg {Number} width
+ * Width in pixels of the quick tip (defaults to auto). Width will be ignored if it exceeds the bounds of
+ * minWidth or maxWidth.
+ */
+ width : null,
+
+ /**
+ * Initialize and enable QuickTips for first use. This should be called once before the first attempt to access
+ * or display QuickTips in a page.
+ */
+ init : function(){
+ tm = Roo.QuickTips;
+ cfg = tm.tagConfig;
+ if(!inited){
+ if(!Roo.isReady){ // allow calling of init() before onReady
+ Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
+ return;
+ }
+ el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
+ el.fxDefaults = {stopFx: true};
+ // maximum custom styling
+ //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>');
+ 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>');
+ tipTitle = el.child('h3');
+ tipTitle.enableDisplayMode("block");
+ tipBody = el.child('div.x-tip-bd');
+ tipBodyText = el.child('div.x-tip-bd-inner');
+ //bdLeft = el.child('div.x-tip-bd-left');
+ //bdRight = el.child('div.x-tip-bd-right');
+ close = el.child('div.x-tip-close');
+ close.enableDisplayMode("block");
+ close.on("click", hide);
+ var d = Roo.get(document);
+ d.on("mousedown", onDown);
+ d.on("mouseover", onOver);
+ d.on("mouseout", onOut);
+ d.on("mousemove", onMove);
+ esc = d.addKeyListener(27, hide);
+ esc.disable();
+ if(Roo.dd.DD){
+ dd = el.initDD("default", null, {
+ onDrag : function(){
+ el.sync();
+ }
+ });
+ dd.setHandleElId(tipTitle.id);
+ dd.lock();
+ }
+ inited = true;
+ }
+ this.enable();
+ },
+
+ /**
+ * Configures a new quick tip instance and assigns it to a target element. The following config options
+ * are supported:
+ * <pre>
+Property Type Description
+---------- --------------------- ------------------------------------------------------------------------
+target Element/String/Array An Element, id or array of ids that this quick tip should be tied to
+ * </ul>
+ * @param {Object} config The config object
+ */
+ register : function(config){
+ var cs = config instanceof Array ? config : arguments;
+ for(var i = 0, len = cs.length; i < len; i++) {
+ var c = cs[i];
+ var target = c.target;
+ if(target){
+ if(target instanceof Array){
+ for(var j = 0, jlen = target.length; j < jlen; j++){
+ tagEls[target[j]] = c;
+ }
+ }else{
+ tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
+ }
+ }
+ }
+ },
+
+ /**
+ * Removes this quick tip from its element and destroys it.
+ * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
+ */
+ unregister : function(el){
+ delete tagEls[Roo.id(el)];
+ },
+
+ /**
+ * Enable this quick tip.
+ */
+ enable : function(){
+ if(inited && disabled){
+ locks.pop();
+ if(locks.length < 1){
+ disabled = false;
+ }
+ }
+ },
+
+ /**
+ * Disable this quick tip.
+ */
+ disable : function(){
+ disabled = true;
+ clearTimeout(showProc);
+ clearTimeout(hideProc);
+ clearTimeout(dismissProc);
+ if(ce){
+ hide(true);
+ }
+ locks.push(1);
+ },
+
+ /**
+ * Returns true if the quick tip is enabled, else false.
+ */
+ isEnabled : function(){
+ return !disabled;
+ },
+
+ // private
+ tagConfig : {
+ namespace : "roo", // was ext?? this may break..
+ alt_namespace : "ext",
+ attribute : "qtip",
+ width : "width",
+ target : "target",
+ title : "qtitle",
+ hide : "hide",
+ cls : "qclass"
+ }
+ };
+}();
+
+// backwards compat
+Roo.QuickTips.tips = Roo.QuickTips.register;/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+
+/**
+ * @class Roo.tree.TreePanel
+ * @extends Roo.data.Tree
+ * @cfg {Roo.tree.TreeNode} root The root node
+ * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
+ * @cfg {Boolean} lines false to disable tree lines (defaults to true)
+ * @cfg {Boolean} enableDD true to enable drag and drop
+ * @cfg {Boolean} enableDrag true to enable just drag
+ * @cfg {Boolean} enableDrop true to enable just drop
+ * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
+ * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
+ * @cfg {String} ddGroup The DD group this TreePanel belongs to
+ * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
+ * @cfg {Boolean} ddScroll true to enable YUI body scrolling
+ * @cfg {Boolean} containerScroll true to register this container with ScrollManager
+ * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
+ * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
+ * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
+ * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
+ * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
+ * @cfg {Roo.tree.TreeLoader} loader A TreeLoader for use with this TreePanel
+ * @cfg {Roo.tree.TreeEditor} editor The TreeEditor to display when clicked.
+ * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
+ * @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>
+ * @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>
+ *
+ * @constructor
+ * @param {String/HTMLElement/Element} el The container element
+ * @param {Object} config
+ */
+Roo.tree.TreePanel = function(el, config){
+ var root = false;
+ var loader = false;
+ if (config.root) {
+ root = config.root;
+ delete config.root;
+ }
+ if (config.loader) {
+ loader = config.loader;
+ delete config.loader;
+ }
+
+ Roo.apply(this, config);
+ Roo.tree.TreePanel.superclass.constructor.call(this);
+ this.el = Roo.get(el);
+ this.el.addClass('x-tree');
+ //console.log(root);
+ if (root) {
+ this.setRootNode( Roo.factory(root, Roo.tree));
+ }
+ if (loader) {
+ this.loader = Roo.factory(loader, Roo.tree);
+ }
+ /**
+ * Read-only. The id of the container element becomes this TreePanel's id.
+ */
+ this.id = this.el.id;
+ this.addEvents({
+ /**
+ * @event beforeload
+ * Fires before a node is loaded, return false to cancel
+ * @param {Node} node The node being loaded
+ */
+ "beforeload" : true,
+ /**
+ * @event load
+ * Fires when a node is loaded
+ * @param {Node} node The node that was loaded
+ */
+ "load" : true,
+ /**
+ * @event textchange
+ * Fires when the text for a node is changed
+ * @param {Node} node The node
+ * @param {String} text The new text
+ * @param {String} oldText The old text
+ */
+ "textchange" : true,
+ /**
+ * @event beforeexpand
+ * Fires before a node is expanded, return false to cancel.
+ * @param {Node} node The node
+ * @param {Boolean} deep
+ * @param {Boolean} anim
+ */
+ "beforeexpand" : true,
+ /**
+ * @event beforecollapse
+ * Fires before a node is collapsed, return false to cancel.
+ * @param {Node} node The node
+ * @param {Boolean} deep
+ * @param {Boolean} anim
+ */
+ "beforecollapse" : true,
+ /**
+ * @event expand
+ * Fires when a node is expanded
+ * @param {Node} node The node
+ */
+ "expand" : true,
+ /**
+ * @event disabledchange
+ * Fires when the disabled status of a node changes
+ * @param {Node} node The node
+ * @param {Boolean} disabled
+ */
+ "disabledchange" : true,
+ /**
+ * @event collapse
+ * Fires when a node is collapsed
+ * @param {Node} node The node
+ */
+ "collapse" : true,
+ /**
+ * @event beforeclick
+ * Fires before click processing on a node. Return false to cancel the default action.
+ * @param {Node} node The node
+ * @param {Roo.EventObject} e The event object
+ */
+ "beforeclick":true,
+ /**
+ * @event checkchange
+ * Fires when a node with a checkbox's checked property changes
+ * @param {Node} this This node
+ * @param {Boolean} checked
+ */
+ "checkchange":true,
+ /**
+ * @event click
+ * Fires when a node is clicked
+ * @param {Node} node The node
+ * @param {Roo.EventObject} e The event object
+ */
+ "click":true,
+ /**
+ * @event dblclick
+ * Fires when a node is double clicked
+ * @param {Node} node The node
+ * @param {Roo.EventObject} e The event object
+ */
+ "dblclick":true,
+ /**
+ * @event contextmenu
+ * Fires when a node is right clicked
+ * @param {Node} node The node
+ * @param {Roo.EventObject} e The event object
+ */
+ "contextmenu":true,
+ /**
+ * @event beforechildrenrendered
+ * Fires right before the child nodes for a node are rendered
+ * @param {Node} node The node
+ */
+ "beforechildrenrendered":true,
+ /**
+ * @event startdrag
+ * Fires when a node starts being dragged
+ * @param {Roo.tree.TreePanel} this
+ * @param {Roo.tree.TreeNode} node
+ * @param {event} e The raw browser event
+ */
+ "startdrag" : true,
+ /**
+ * @event enddrag
+ * Fires when a drag operation is complete
+ * @param {Roo.tree.TreePanel} this
+ * @param {Roo.tree.TreeNode} node
+ * @param {event} e The raw browser event
+ */
+ "enddrag" : true,
+ /**
+ * @event dragdrop
+ * Fires when a dragged node is dropped on a valid DD target
+ * @param {Roo.tree.TreePanel} this
+ * @param {Roo.tree.TreeNode} node
+ * @param {DD} dd The dd it was dropped on
+ * @param {event} e The raw browser event
+ */
+ "dragdrop" : true,
+ /**
+ * @event beforenodedrop
+ * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
+ * passed to handlers has the following properties:<br />
+ * <ul style="padding:5px;padding-left:16px;">
+ * <li>tree - The TreePanel</li>
+ * <li>target - The node being targeted for the drop</li>
+ * <li>data - The drag data from the drag source</li>
+ * <li>point - The point of the drop - append, above or below</li>
+ * <li>source - The drag source</li>
+ * <li>rawEvent - Raw mouse event</li>
+ * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
+ * to be inserted by setting them on this object.</li>
+ * <li>cancel - Set this to true to cancel the drop.</li>
+ * </ul>
+ * @param {Object} dropEvent
+ */
+ "beforenodedrop" : true,
+ /**
+ * @event nodedrop
+ * Fires after a DD object is dropped on a node in this tree. The dropEvent
+ * passed to handlers has the following properties:<br />
+ * <ul style="padding:5px;padding-left:16px;">
+ * <li>tree - The TreePanel</li>
+ * <li>target - The node being targeted for the drop</li>
+ * <li>data - The drag data from the drag source</li>
+ * <li>point - The point of the drop - append, above or below</li>
+ * <li>source - The drag source</li>
+ * <li>rawEvent - Raw mouse event</li>
+ * <li>dropNode - Dropped node(s).</li>
+ * </ul>
+ * @param {Object} dropEvent
+ */
+ "nodedrop" : true,
+ /**
+ * @event nodedragover
+ * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
+ * passed to handlers has the following properties:<br />
+ * <ul style="padding:5px;padding-left:16px;">
+ * <li>tree - The TreePanel</li>
+ * <li>target - The node being targeted for the drop</li>
+ * <li>data - The drag data from the drag source</li>
+ * <li>point - The point of the drop - append, above or below</li>
+ * <li>source - The drag source</li>
+ * <li>rawEvent - Raw mouse event</li>
+ * <li>dropNode - Drop node(s) provided by the source.</li>
+ * <li>cancel - Set this to true to signal drop not allowed.</li>
+ * </ul>
+ * @param {Object} dragOverEvent
+ */
+ "nodedragover" : true,
+ /**
+ * @event appendnode
+ * Fires when append node to the tree
+ * @param {Roo.tree.TreePanel} this
+ * @param {Roo.tree.TreeNode} node
+ * @param {Number} index The index of the newly appended node
+ */
+ "appendnode" : true
+
+ });
+ if(this.singleExpand){
+ this.on("beforeexpand", this.restrictExpand, this);
+ }
+ if (this.editor) {
+ this.editor.tree = this;
+ this.editor = Roo.factory(this.editor, Roo.tree);
+ }
+
+ if (this.selModel) {
+ this.selModel = Roo.factory(this.selModel, Roo.tree);
+ }
+
+};
+Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
+ rootVisible : true,
+ animate: Roo.enableFx,
+ lines : true,
+ enableDD : false,
+ hlDrop : Roo.enableFx,
+
+ renderer: false,
+
+ rendererTip: false,
+ // private
+ restrictExpand : function(node){
+ var p = node.parentNode;
+ if(p){
+ if(p.expandedChild && p.expandedChild.parentNode == p){
+ p.expandedChild.collapse();
+ }
+ p.expandedChild = node;
+ }
+ },
+
+ // private override
+ setRootNode : function(node){
+ Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
+ if(!this.rootVisible){
+ node.ui = new Roo.tree.RootTreeNodeUI(node);
+ }
+ return node;
+ },
+
+ /**
+ * Returns the container element for this TreePanel
+ */
+ getEl : function(){
+ return this.el;
+ },
+
+ /**
+ * Returns the default TreeLoader for this TreePanel
+ */
+ getLoader : function(){
+ return this.loader;
+ },
+
+ /**
+ * Expand all nodes
+ */
+ expandAll : function(){
+ this.root.expand(true);
+ },
+
+ /**
+ * Collapse all nodes
+ */
+ collapseAll : function(){
+ this.root.collapse(true);
+ },
+
+ /**
+ * Returns the selection model used by this TreePanel
+ */
+ getSelectionModel : function(){
+ if(!this.selModel){
+ this.selModel = new Roo.tree.DefaultSelectionModel();
+ }
+ return this.selModel;
+ },
+
+ /**
+ * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
+ * @param {String} attribute (optional) Defaults to null (return the actual nodes)
+ * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
+ * @return {Array}
+ */
+ getChecked : function(a, startNode){
+ startNode = startNode || this.root;
+ var r = [];
+ var f = function(){
+ if(this.attributes.checked){
+ r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
+ }
+ }
+ startNode.cascade(f);
+ return r;
+ },
+
+ /**
+ * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
+ * @param {String} path
+ * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
+ * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
+ * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
+ */
+ expandPath : function(path, attr, callback){
+ attr = attr || "id";
+ var keys = path.split(this.pathSeparator);
+ var curNode = this.root;
+ if(curNode.attributes[attr] != keys[1]){ // invalid root
+ if(callback){
+ callback(false, null);
+ }
+ return;
+ }
+ var index = 1;
+ var f = function(){
+ if(++index == keys.length){
+ if(callback){
+ callback(true, curNode);
+ }
+ return;
+ }
+ var c = curNode.findChild(attr, keys[index]);
+ if(!c){
+ if(callback){
+ callback(false, curNode);
+ }
+ return;
+ }
+ curNode = c;
+ c.expand(false, false, f);
+ };
+ curNode.expand(false, false, f);
+ },
+
+ /**
+ * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
+ * @param {String} path
+ * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
+ * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
+ * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
+ */
+ selectPath : function(path, attr, callback){
+ attr = attr || "id";
+ var keys = path.split(this.pathSeparator);
+ var v = keys.pop();
+ if(keys.length > 0){
+ var f = function(success, node){
+ if(success && node){
+ var n = node.findChild(attr, v);
+ if(n){
+ n.select();
+ if(callback){
+ callback(true, n);
+ }
+ }else if(callback){
+ callback(false, n);
+ }
+ }else{
+ if(callback){
+ callback(false, n);
+ }
+ }
+ };
+ this.expandPath(keys.join(this.pathSeparator), attr, f);
+ }else{
+ this.root.select();
+ if(callback){
+ callback(true, this.root);
+ }
+ }
+ },
+
+ getTreeEl : function(){
+ return this.el;
+ },
+
+ /**
+ * Trigger rendering of this TreePanel
+ */
+ render : function(){
+ if (this.innerCt) {
+ return this; // stop it rendering more than once!!
+ }
+
+ this.innerCt = this.el.createChild({tag:"ul",
+ cls:"x-tree-root-ct " +
+ (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
+
+ if(this.containerScroll){
+ Roo.dd.ScrollManager.register(this.el);
+ }
+ if((this.enableDD || this.enableDrop) && !this.dropZone){
+ /**
+ * The dropZone used by this tree if drop is enabled
+ * @type Roo.tree.TreeDropZone
+ */
+ this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
+ ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
+ });
+ }
+ if((this.enableDD || this.enableDrag) && !this.dragZone){
+ /**
+ * The dragZone used by this tree if drag is enabled
+ * @type Roo.tree.TreeDragZone
+ */
+ this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
+ ddGroup: this.ddGroup || "TreeDD",
+ scroll: this.ddScroll
+ });
+ }
+ this.getSelectionModel().init(this);
+ if (!this.root) {
+ Roo.log("ROOT not set in tree");
+ return this;
+ }
+ this.root.render();
+ if(!this.rootVisible){
+ this.root.renderChildren();
+ }
+ return this;
+ }
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+
+/**
+ * @class Roo.tree.DefaultSelectionModel
+ * @extends Roo.util.Observable
+ * The default single selection for a TreePanel.
+ * @param {Object} cfg Configuration
+ */
+Roo.tree.DefaultSelectionModel = function(cfg){
+ this.selNode = null;
+
+
+
+ this.addEvents({
+ /**
+ * @event selectionchange
+ * Fires when the selected node changes
+ * @param {DefaultSelectionModel} this
+ * @param {TreeNode} node the new selection
+ */
+ "selectionchange" : true,
+
+ /**
+ * @event beforeselect
+ * Fires before the selected node changes, return false to cancel the change
+ * @param {DefaultSelectionModel} this
+ * @param {TreeNode} node the new selection
+ * @param {TreeNode} node the old selection
+ */
+ "beforeselect" : true
+ });
+
+ Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
+};
+
+Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
+ init : function(tree){
+ this.tree = tree;
+ tree.getTreeEl().on("keydown", this.onKeyDown, this);
+ tree.on("click", this.onNodeClick, this);
+ },
+
+ onNodeClick : function(node, e){
+ if (e.ctrlKey && this.selNode == node) {
+ this.unselect(node);
+ return;
+ }
+ this.select(node);
+ },
+
+ /**
+ * Select a node.
+ * @param {TreeNode} node The node to select
+ * @return {TreeNode} The selected node
+ */
+ select : function(node){
+ var last = this.selNode;
+ if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
+ if(last){
+ last.ui.onSelectedChange(false);
+ }
+ this.selNode = node;
+ node.ui.onSelectedChange(true);
+ this.fireEvent("selectionchange", this, node, last);
+ }
+ return node;
+ },
+
+ /**
+ * Deselect a node.
+ * @param {TreeNode} node The node to unselect
+ */
+ unselect : function(node){
+ if(this.selNode == node){
+ this.clearSelections();
+ }
+ },
+
+ /**
+ * Clear all selections
+ */
+ clearSelections : function(){
+ var n = this.selNode;
+ if(n){
+ n.ui.onSelectedChange(false);
+ this.selNode = null;
+ this.fireEvent("selectionchange", this, null);
+ }
+ return n;
+ },
+
+ /**
+ * Get the selected node
+ * @return {TreeNode} The selected node
+ */
+ getSelectedNode : function(){
+ return this.selNode;
+ },
+
+ /**
+ * Returns true if the node is selected
+ * @param {TreeNode} node The node to check
+ * @return {Boolean}
+ */
+ isSelected : function(node){
+ return this.selNode == node;
+ },
+
+ /**
+ * Selects the node above the selected node in the tree, intelligently walking the nodes
+ * @return TreeNode The new selection
+ */
+ selectPrevious : function(){
+ var s = this.selNode || this.lastSelNode;
+ if(!s){
+ return null;
+ }
+ var ps = s.previousSibling;
+ if(ps){
+ if(!ps.isExpanded() || ps.childNodes.length < 1){
+ return this.select(ps);
+ } else{
+ var lc = ps.lastChild;
+ while(lc && lc.isExpanded() && lc.childNodes.length > 0){
+ lc = lc.lastChild;
+ }
+ return this.select(lc);
+ }
+ } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
+ return this.select(s.parentNode);
+ }
+ return null;
+ },
+
+ /**
+ * Selects the node above the selected node in the tree, intelligently walking the nodes
+ * @return TreeNode The new selection
+ */
+ selectNext : function(){
+ var s = this.selNode || this.lastSelNode;
+ if(!s){
+ return null;
+ }
+ if(s.firstChild && s.isExpanded()){
+ return this.select(s.firstChild);
+ }else if(s.nextSibling){
+ return this.select(s.nextSibling);
+ }else if(s.parentNode){
+ var newS = null;
+ s.parentNode.bubble(function(){
+ if(this.nextSibling){
+ newS = this.getOwnerTree().selModel.select(this.nextSibling);
+ return false;
+ }
+ });
+ return newS;
+ }
+ return null;
+ },
+
+ onKeyDown : function(e){
+ var s = this.selNode || this.lastSelNode;
+ // undesirable, but required
+ var sm = this;
+ if(!s){
+ return;
+ }
+ var k = e.getKey();
+ switch(k){
+ case e.DOWN:
+ e.stopEvent();
+ this.selectNext();
+ break;
+ case e.UP:
+ e.stopEvent();
+ this.selectPrevious();
+ break;
+ case e.RIGHT:
+ e.preventDefault();
+ if(s.hasChildNodes()){
+ if(!s.isExpanded()){
+ s.expand();
+ }else if(s.firstChild){
+ this.select(s.firstChild, e);
+ }
+ }
+ break;
+ case e.LEFT:
+ e.preventDefault();
+ if(s.hasChildNodes() && s.isExpanded()){
+ s.collapse();
+ }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
+ this.select(s.parentNode, e);
+ }
+ break;
+ };
+ }
+});
+
+/**
+ * @class Roo.tree.MultiSelectionModel
+ * @extends Roo.util.Observable
+ * Multi selection for a TreePanel.
+ * @param {Object} cfg Configuration
+ */
+Roo.tree.MultiSelectionModel = function(){
+ this.selNodes = [];
+ this.selMap = {};
+ this.addEvents({
+ /**
+ * @event selectionchange
+ * Fires when the selected nodes change
+ * @param {MultiSelectionModel} this
+ * @param {Array} nodes Array of the selected nodes
+ */
+ "selectionchange" : true
+ });
+ Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
+
+};
+
+Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
+ init : function(tree){
+ this.tree = tree;
+ tree.getTreeEl().on("keydown", this.onKeyDown, this);
+ tree.on("click", this.onNodeClick, this);
+ },
+
+ onNodeClick : function(node, e){
+ this.select(node, e, e.ctrlKey);
+ },
+
+ /**
+ * Select a node.
+ * @param {TreeNode} node The node to select
+ * @param {EventObject} e (optional) An event associated with the selection
+ * @param {Boolean} keepExisting True to retain existing selections
+ * @return {TreeNode} The selected node
+ */
+ select : function(node, e, keepExisting){
+ if(keepExisting !== true){
+ this.clearSelections(true);
+ }
+ if(this.isSelected(node)){
+ this.lastSelNode = node;
+ return node;
+ }
+ this.selNodes.push(node);
+ this.selMap[node.id] = node;
+ this.lastSelNode = node;
+ node.ui.onSelectedChange(true);
+ this.fireEvent("selectionchange", this, this.selNodes);
+ return node;
+ },
+
+ /**
+ * Deselect a node.
+ * @param {TreeNode} node The node to unselect
+ */
+ unselect : function(node){
+ if(this.selMap[node.id]){
+ node.ui.onSelectedChange(false);
+ var sn = this.selNodes;
+ var index = -1;
+ if(sn.indexOf){
+ index = sn.indexOf(node);
+ }else{
+ for(var i = 0, len = sn.length; i < len; i++){
+ if(sn[i] == node){
+ index = i;
+ break;
+ }
+ }
+ }
+ if(index != -1){
+ this.selNodes.splice(index, 1);
+ }
+ delete this.selMap[node.id];
+ this.fireEvent("selectionchange", this, this.selNodes);
+ }
+ },
+
+ /**
+ * Clear all selections
+ */
+ clearSelections : function(suppressEvent){
+ var sn = this.selNodes;
+ if(sn.length > 0){
+ for(var i = 0, len = sn.length; i < len; i++){
+ sn[i].ui.onSelectedChange(false);
+ }
+ this.selNodes = [];
+ this.selMap = {};
+ if(suppressEvent !== true){
+ this.fireEvent("selectionchange", this, this.selNodes);
+ }
+ }
+ },
+
+ /**
+ * Returns true if the node is selected
+ * @param {TreeNode} node The node to check
+ * @return {Boolean}
+ */
+ isSelected : function(node){
+ return this.selMap[node.id] ? true : false;
+ },
+
+ /**
+ * Returns an array of the selected nodes
+ * @return {Array}
+ */
+ getSelectedNodes : function(){
+ return this.selNodes;
+ },
+
+ onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
+
+ selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
+
+ selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.tree.TreeNode
+ * @extends Roo.data.Node
+ * @cfg {String} text The text for this node
+ * @cfg {Boolean} expanded true to start the node expanded
+ * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
+ * @cfg {Boolean} allowDrop false if this node cannot be drop on
+ * @cfg {Boolean} disabled true to start the node disabled
+ * @cfg {String} icon The path to an icon for the node. The preferred way to do this
+ * is to use the cls or iconCls attributes and add the icon via a CSS background image.
+ * @cfg {String} cls A css class to be added to the node
+ * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
+ * @cfg {String} href URL of the link used for the node (defaults to #)
+ * @cfg {String} hrefTarget target frame for the link
+ * @cfg {String} qtip An Ext QuickTip for the node
+ * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
+ * @cfg {Boolean} singleClickExpand True for single click expand on this node
+ * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
+ * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
+ * (defaults to undefined with no checkbox rendered)
+ * @constructor
+ * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
+ */
+Roo.tree.TreeNode = function(attributes){
+ attributes = attributes || {};
+ if(typeof attributes == "string"){
+ attributes = {text: attributes};
+ }
+ this.childrenRendered = false;
+ this.rendered = false;
+ Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
+ this.expanded = attributes.expanded === true;
+ this.isTarget = attributes.isTarget !== false;
+ this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
+ this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
+
+ /**
+ * Read-only. The text for this node. To change it use setText().
+ * @type String
+ */
+ this.text = attributes.text;
+ /**
+ * True if this node is disabled.
+ * @type Boolean
+ */
+ this.disabled = attributes.disabled === true;
+
+ this.addEvents({
+ /**
+ * @event textchange
+ * Fires when the text for this node is changed
+ * @param {Node} this This node
+ * @param {String} text The new text
+ * @param {String} oldText The old text
+ */
+ "textchange" : true,
+ /**
+ * @event beforeexpand
+ * Fires before this node is expanded, return false to cancel.
+ * @param {Node} this This node
+ * @param {Boolean} deep
+ * @param {Boolean} anim
+ */
+ "beforeexpand" : true,
+ /**
+ * @event beforecollapse
+ * Fires before this node is collapsed, return false to cancel.
+ * @param {Node} this This node
+ * @param {Boolean} deep
+ * @param {Boolean} anim
+ */
+ "beforecollapse" : true,
+ /**
+ * @event expand
+ * Fires when this node is expanded
+ * @param {Node} this This node
+ */
+ "expand" : true,
+ /**
+ * @event disabledchange
+ * Fires when the disabled status of this node changes
+ * @param {Node} this This node
+ * @param {Boolean} disabled
+ */
+ "disabledchange" : true,
+ /**
+ * @event collapse
+ * Fires when this node is collapsed
+ * @param {Node} this This node
+ */
+ "collapse" : true,
+ /**
+ * @event beforeclick
+ * Fires before click processing. Return false to cancel the default action.
+ * @param {Node} this This node
+ * @param {Roo.EventObject} e The event object
+ */
+ "beforeclick":true,
+ /**
+ * @event checkchange
+ * Fires when a node with a checkbox's checked property changes
+ * @param {Node} this This node
+ * @param {Boolean} checked
+ */
+ "checkchange":true,
+ /**
+ * @event click
+ * Fires when this node is clicked
+ * @param {Node} this This node
+ * @param {Roo.EventObject} e The event object
+ */
+ "click":true,
+ /**
+ * @event dblclick
+ * Fires when this node is double clicked
+ * @param {Node} this This node
+ * @param {Roo.EventObject} e The event object
+ */
+ "dblclick":true,
+ /**
+ * @event contextmenu
+ * Fires when this node is right clicked
+ * @param {Node} this This node
+ * @param {Roo.EventObject} e The event object
+ */
+ "contextmenu":true,
+ /**
+ * @event beforechildrenrendered
+ * Fires right before the child nodes for this node are rendered
+ * @param {Node} this This node
+ */
+ "beforechildrenrendered":true
+ });
+
+ var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
+
+ /**
+ * Read-only. The UI for this node
+ * @type TreeNodeUI
+ */
+ this.ui = new uiClass(this);
+
+ // finally support items[]
+ if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
+ return;
+ }
+
+
+ Roo.each(this.attributes.items, function(c) {
+ this.appendChild(Roo.factory(c,Roo.Tree));
+ }, this);
+ delete this.attributes.items;
+
+
+
+};
+Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
+ preventHScroll: true,
+ /**
+ * Returns true if this node is expanded
+ * @return {Boolean}
+ */
+ isExpanded : function(){
+ return this.expanded;
+ },
+
+ /**
+ * Returns the UI object for this node
+ * @return {TreeNodeUI}
+ */
+ getUI : function(){
+ return this.ui;
+ },
+
+ // private override
+ setFirstChild : function(node){
+ var of = this.firstChild;
+ Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
+ if(this.childrenRendered && of && node != of){
+ of.renderIndent(true, true);
+ }
+ if(this.rendered){
+ this.renderIndent(true, true);
+ }
+ },
+
+ // private override
+ setLastChild : function(node){
+ var ol = this.lastChild;
+ Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
+ if(this.childrenRendered && ol && node != ol){
+ ol.renderIndent(true, true);
+ }
+ if(this.rendered){
+ this.renderIndent(true, true);
+ }
+ },
+
+ // these methods are overridden to provide lazy rendering support
+ // private override
+ appendChild : function()
+ {
+ var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
+ if(node && this.childrenRendered){
+ node.render();
+ }
+ this.ui.updateExpandIcon();
+ return node;
+ },
+
+ // private override
+ removeChild : function(node){
+ this.ownerTree.getSelectionModel().unselect(node);
+ Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
+ // if it's been rendered remove dom node
+ if(this.childrenRendered){
+ node.ui.remove();
+ }
+ if(this.childNodes.length < 1){
+ this.collapse(false, false);
+ }else{
+ this.ui.updateExpandIcon();
+ }
+ if(!this.firstChild) {
+ this.childrenRendered = false;
+ }
+ return node;
+ },
+
+ // private override
+ insertBefore : function(node, refNode){
+ var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
+ if(newNode && refNode && this.childrenRendered){
+ node.render();
+ }
+ this.ui.updateExpandIcon();
+ return newNode;
+ },
+
+ /**
+ * Sets the text for this node
+ * @param {String} text
+ */
+ setText : function(text){
+ var oldText = this.text;
+ this.text = text;
+ this.attributes.text = text;
+ if(this.rendered){ // event without subscribing
+ this.ui.onTextChange(this, text, oldText);
+ }
+ this.fireEvent("textchange", this, text, oldText);
+ },
+
+ /**
+ * Triggers selection of this node
+ */
+ select : function(){
+ this.getOwnerTree().getSelectionModel().select(this);
+ },
+
+ /**
+ * Triggers deselection of this node
+ */
+ unselect : function(){
+ this.getOwnerTree().getSelectionModel().unselect(this);
+ },
+
+ /**
+ * Returns true if this node is selected
+ * @return {Boolean}
+ */
+ isSelected : function(){
+ return this.getOwnerTree().getSelectionModel().isSelected(this);
+ },
+
+ /**
+ * Expand this node.
+ * @param {Boolean} deep (optional) True to expand all children as well
+ * @param {Boolean} anim (optional) false to cancel the default animation
+ * @param {Function} callback (optional) A callback to be called when
+ * expanding this node completes (does not wait for deep expand to complete).
+ * Called with 1 parameter, this node.
+ */
+ expand : function(deep, anim, callback){
+ if(!this.expanded){
+ if(this.fireEvent("beforeexpand", this, deep, anim) === false){
+ return;
+ }
+ if(!this.childrenRendered){
+ this.renderChildren();
+ }
+ this.expanded = true;
+
+ if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
+ this.ui.animExpand(function(){
+ this.fireEvent("expand", this);
+ if(typeof callback == "function"){
+ callback(this);
+ }
+ if(deep === true){
+ this.expandChildNodes(true);
+ }
+ }.createDelegate(this));
+ return;
+ }else{
+ this.ui.expand();
+ this.fireEvent("expand", this);
+ if(typeof callback == "function"){
+ callback(this);
+ }
+ }
+ }else{
+ if(typeof callback == "function"){
+ callback(this);
+ }
+ }
+ if(deep === true){
+ this.expandChildNodes(true);
+ }
+ },
+
+ isHiddenRoot : function(){
+ return this.isRoot && !this.getOwnerTree().rootVisible;
+ },
+
+ /**
+ * Collapse this node.
+ * @param {Boolean} deep (optional) True to collapse all children as well
+ * @param {Boolean} anim (optional) false to cancel the default animation
+ */
+ collapse : function(deep, anim){
+ if(this.expanded && !this.isHiddenRoot()){
+ if(this.fireEvent("beforecollapse", this, deep, anim) === false){
+ return;
+ }
+ this.expanded = false;
+ if((this.getOwnerTree().animate && anim !== false) || anim){
+ this.ui.animCollapse(function(){
+ this.fireEvent("collapse", this);
+ if(deep === true){
+ this.collapseChildNodes(true);
+ }
+ }.createDelegate(this));
+ return;
+ }else{
+ this.ui.collapse();
+ this.fireEvent("collapse", this);
+ }
+ }
+ if(deep === true){
+ var cs = this.childNodes;
+ for(var i = 0, len = cs.length; i < len; i++) {
+ cs[i].collapse(true, false);
+ }
+ }
+ },
+
+ // private
+ delayedExpand : function(delay){
+ if(!this.expandProcId){
+ this.expandProcId = this.expand.defer(delay, this);
+ }
+ },
+
+ // private
+ cancelExpand : function(){
+ if(this.expandProcId){
+ clearTimeout(this.expandProcId);
+ }
+ this.expandProcId = false;
+ },
+
+ /**
+ * Toggles expanded/collapsed state of the node
+ */
+ toggle : function(){
+ if(this.expanded){
+ this.collapse();
+ }else{
+ this.expand();
+ }
+ },
+
+ /**
+ * Ensures all parent nodes are expanded
+ */
+ ensureVisible : function(callback){
+ var tree = this.getOwnerTree();
+ tree.expandPath(this.parentNode.getPath(), false, function(){
+ tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
+ Roo.callback(callback);
+ }.createDelegate(this));
+ },
+
+ /**
+ * Expand all child nodes
+ * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
+ */
+ expandChildNodes : function(deep){
+ var cs = this.childNodes;
+ for(var i = 0, len = cs.length; i < len; i++) {
+ cs[i].expand(deep);
+ }
+ },
+
+ /**
+ * Collapse all child nodes
+ * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
+ */
+ collapseChildNodes : function(deep){
+ var cs = this.childNodes;
+ for(var i = 0, len = cs.length; i < len; i++) {
+ cs[i].collapse(deep);
+ }
+ },
+
+ /**
+ * Disables this node
+ */
+ disable : function(){
+ this.disabled = true;
+ this.unselect();
+ if(this.rendered && this.ui.onDisableChange){ // event without subscribing
+ this.ui.onDisableChange(this, true);
+ }
+ this.fireEvent("disabledchange", this, true);
+ },
+
+ /**
+ * Enables this node
+ */
+ enable : function(){
+ this.disabled = false;
+ if(this.rendered && this.ui.onDisableChange){ // event without subscribing
+ this.ui.onDisableChange(this, false);
+ }
+ this.fireEvent("disabledchange", this, false);
+ },
+
+ // private
+ renderChildren : function(suppressEvent){
+ if(suppressEvent !== false){
+ this.fireEvent("beforechildrenrendered", this);
+ }
+ var cs = this.childNodes;
+ for(var i = 0, len = cs.length; i < len; i++){
+ cs[i].render(true);
+ }
+ this.childrenRendered = true;
+ },
+
+ // private
+ sort : function(fn, scope){
+ Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
+ if(this.childrenRendered){
+ var cs = this.childNodes;
+ for(var i = 0, len = cs.length; i < len; i++){
+ cs[i].render(true);
+ }
+ }
+ },
+
+ // private
+ render : function(bulkRender){
+ this.ui.render(bulkRender);
+ if(!this.rendered){
+ this.rendered = true;
+ if(this.expanded){
+ this.expanded = false;
+ this.expand(false, false);
+ }
+ }
+ },
+
+ // private
+ renderIndent : function(deep, refresh){
+ if(refresh){
+ this.ui.childIndent = null;
+ }
+ this.ui.renderIndent();
+ if(deep === true && this.childrenRendered){
+ var cs = this.childNodes;
+ for(var i = 0, len = cs.length; i < len; i++){
+ cs[i].renderIndent(true, refresh);
+ }
+ }
+ }
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.tree.AsyncTreeNode
+ * @extends Roo.tree.TreeNode
+ * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
+ * @constructor
+ * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
+ */
+ Roo.tree.AsyncTreeNode = function(config){
+ this.loaded = false;
+ this.loading = false;
+ Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
+ /**
+ * @event beforeload
+ * Fires before this node is loaded, return false to cancel
+ * @param {Node} this This node
+ */
+ this.addEvents({'beforeload':true, 'load': true});
+ /**
+ * @event load
+ * Fires when this node is loaded
+ * @param {Node} this This node
+ */
+ /**
+ * The loader used by this node (defaults to using the tree's defined loader)
+ * @type TreeLoader
+ * @property loader
+ */
+};
+Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
+ expand : function(deep, anim, callback){
+ if(this.loading){ // if an async load is already running, waiting til it's done
+ var timer;
+ var f = function(){
+ if(!this.loading){ // done loading
+ clearInterval(timer);
+ this.expand(deep, anim, callback);
+ }
+ }.createDelegate(this);
+ timer = setInterval(f, 200);
+ return;
+ }
+ if(!this.loaded){
+ if(this.fireEvent("beforeload", this) === false){
+ return;
+ }
+ this.loading = true;
+ this.ui.beforeLoad(this);
+ var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
+ if(loader){
+ loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
+ return;
+ }
+ }
+ Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
+ },
+
+ /**
+ * Returns true if this node is currently loading
+ * @return {Boolean}
+ */
+ isLoading : function(){
+ return this.loading;
+ },
+
+ loadComplete : function(deep, anim, callback){
+ this.loading = false;
+ this.loaded = true;
+ this.ui.afterLoad(this);
+ this.fireEvent("load", this);
+ this.expand(deep, anim, callback);
+ },
+
+ /**
+ * Returns true if this node has been loaded
+ * @return {Boolean}
+ */
+ isLoaded : function(){
+ return this.loaded;
+ },
+
+ hasChildNodes : function(){
+ if(!this.isLeaf() && !this.loaded){
+ return true;
+ }else{
+ return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
+ }
+ },
+
+ /**
+ * Trigger a reload for this node
+ * @param {Function} callback
+ */
+ reload : function(callback){
+ this.collapse(false, false);
+ while(this.firstChild){
+ this.removeChild(this.firstChild);
+ }
+ this.childrenRendered = false;
+ this.loaded = false;
+ if(this.isHiddenRoot()){
+ this.expanded = false;
+ }
+ this.expand(false, false, callback);
+ }
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.tree.TreeNodeUI
+ * @constructor
+ * @param {Object} node The node to render
+ * The TreeNode UI implementation is separate from the
+ * tree implementation. Unless you are customizing the tree UI,
+ * you should never have to use this directly.
+ */
+Roo.tree.TreeNodeUI = function(node){
+ this.node = node;
+ this.rendered = false;
+ this.animating = false;
+ this.emptyIcon = Roo.BLANK_IMAGE_URL;
+};
+
+Roo.tree.TreeNodeUI.prototype = {
+ removeChild : function(node){
+ if(this.rendered){
+ this.ctNode.removeChild(node.ui.getEl());
+ }
+ },
+
+ beforeLoad : function(){
+ this.addClass("x-tree-node-loading");
+ },
+
+ afterLoad : function(){
+ this.removeClass("x-tree-node-loading");
+ },
+
+ onTextChange : function(node, text, oldText){
+ if(this.rendered){
+ this.textNode.innerHTML = text;
+ }
+ },
+
+ onDisableChange : function(node, state){
+ this.disabled = state;
+ if(state){
+ this.addClass("x-tree-node-disabled");
+ }else{
+ this.removeClass("x-tree-node-disabled");
+ }
+ },
+
+ onSelectedChange : function(state){
+ if(state){
+ this.focus();
+ this.addClass("x-tree-selected");
+ }else{
+ //this.blur();
+ this.removeClass("x-tree-selected");
+ }
+ },
+
+ onMove : function(tree, node, oldParent, newParent, index, refNode){
+ this.childIndent = null;
+ if(this.rendered){
+ var targetNode = newParent.ui.getContainer();
+ if(!targetNode){//target not rendered
+ this.holder = document.createElement("div");
+ this.holder.appendChild(this.wrap);
+ return;
+ }
+ var insertBefore = refNode ? refNode.ui.getEl() : null;
+ if(insertBefore){
+ targetNode.insertBefore(this.wrap, insertBefore);
+ }else{
+ targetNode.appendChild(this.wrap);
+ }
+ this.node.renderIndent(true);
+ }
+ },
+
+ addClass : function(cls){
+ if(this.elNode){
+ Roo.fly(this.elNode).addClass(cls);
+ }
+ },
+
+ removeClass : function(cls){
+ if(this.elNode){
+ Roo.fly(this.elNode).removeClass(cls);
+ }
+ },
+
+ remove : function(){
+ if(this.rendered){
+ this.holder = document.createElement("div");
+ this.holder.appendChild(this.wrap);
+ }
+ },
+
+ fireEvent : function(){
+ return this.node.fireEvent.apply(this.node, arguments);
+ },
+
+ initEvents : function(){
+ this.node.on("move", this.onMove, this);
+ var E = Roo.EventManager;
+ var a = this.anchor;
+
+ var el = Roo.fly(a, '_treeui');
+
+ if(Roo.isOpera){ // opera render bug ignores the CSS
+ el.setStyle("text-decoration", "none");
+ }
+
+ el.on("click", this.onClick, this);
+ el.on("dblclick", this.onDblClick, this);
+
+ if(this.checkbox){
+ Roo.EventManager.on(this.checkbox,
+ Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
+ }
+
+ el.on("contextmenu", this.onContextMenu, this);
+
+ var icon = Roo.fly(this.iconNode);
+ icon.on("click", this.onClick, this);
+ icon.on("dblclick", this.onDblClick, this);
+ icon.on("contextmenu", this.onContextMenu, this);
+ E.on(this.ecNode, "click", this.ecClick, this, true);
+
+ if(this.node.disabled){
+ this.addClass("x-tree-node-disabled");
+ }
+ if(this.node.hidden){
+ this.addClass("x-tree-node-disabled");
+ }
+ var ot = this.node.getOwnerTree();
+ var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
+ if(dd && (!this.node.isRoot || ot.rootVisible)){
+ Roo.dd.Registry.register(this.elNode, {
+ node: this.node,
+ handles: this.getDDHandles(),
+ isHandle: false
+ });
+ }
+ },
+
+ getDDHandles : function(){
+ return [this.iconNode, this.textNode];
+ },
+
+ hide : function(){
+ if(this.rendered){
+ this.wrap.style.display = "none";
+ }
+ },
+
+ show : function(){
+ if(this.rendered){
+ this.wrap.style.display = "";
+ }
+ },
+
+ onContextMenu : function(e){
+ if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
+ e.preventDefault();
+ this.focus();
+ this.fireEvent("contextmenu", this.node, e);
+ }
+ },
+
+ onClick : function(e){
+ if(this.dropping){
+ e.stopEvent();
+ return;
+ }
+ if(this.fireEvent("beforeclick", this.node, e) !== false){
+ if(!this.disabled && this.node.attributes.href){
+ this.fireEvent("click", this.node, e);
+ return;
+ }
+ e.preventDefault();
+ if(this.disabled){
+ return;
+ }
+
+ if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
+ this.node.toggle();
+ }
+
+ this.fireEvent("click", this.node, e);
+ }else{
+ e.stopEvent();
+ }
+ },
+
+ onDblClick : function(e){
+ e.preventDefault();
+ if(this.disabled){
+ return;
+ }
+ if(this.checkbox){
+ this.toggleCheck();
+ }
+ if(!this.animating && this.node.hasChildNodes()){
+ this.node.toggle();
+ }
+ this.fireEvent("dblclick", this.node, e);
+ },
+
+ onCheckChange : function(){
+ var checked = this.checkbox.checked;
+ this.node.attributes.checked = checked;
+ this.fireEvent('checkchange', this.node, checked);
+ },
+
+ ecClick : function(e){
+ if(!this.animating && this.node.hasChildNodes()){
+ this.node.toggle();
+ }
+ },
+
+ startDrop : function(){
+ this.dropping = true;
+ },
+
+ // delayed drop so the click event doesn't get fired on a drop
+ endDrop : function(){
+ setTimeout(function(){
+ this.dropping = false;
+ }.createDelegate(this), 50);
+ },
+
+ expand : function(){
+ this.updateExpandIcon();
+ this.ctNode.style.display = "";
+ },
+
+ focus : function(){
+ if(!this.node.preventHScroll){
+ try{this.anchor.focus();
+ }catch(e){}
+ }else if(!Roo.isIE){
+ try{
+ var noscroll = this.node.getOwnerTree().getTreeEl().dom;
+ var l = noscroll.scrollLeft;
+ this.anchor.focus();
+ noscroll.scrollLeft = l;
+ }catch(e){}
+ }
+ },
+
+ toggleCheck : function(value){
+ var cb = this.checkbox;
+ if(cb){
+ cb.checked = (value === undefined ? !cb.checked : value);
+ }
+ },
+
+ blur : function(){
+ try{
+ this.anchor.blur();
+ }catch(e){}
+ },
+
+ animExpand : function(callback){
+ var ct = Roo.get(this.ctNode);
+ ct.stopFx();
+ if(!this.node.hasChildNodes()){
+ this.updateExpandIcon();
+ this.ctNode.style.display = "";
+ Roo.callback(callback);
+ return;
+ }
+ this.animating = true;
+ this.updateExpandIcon();
+
+ ct.slideIn('t', {
+ callback : function(){
+ this.animating = false;
+ Roo.callback(callback);
+ },
+ scope: this,
+ duration: this.node.ownerTree.duration || .25
+ });
+ },
+
+ highlight : function(){
+ var tree = this.node.getOwnerTree();
+ Roo.fly(this.wrap).highlight(
+ tree.hlColor || "C3DAF9",
+ {endColor: tree.hlBaseColor}
+ );
+ },
+
+ collapse : function(){
+ this.updateExpandIcon();
+ this.ctNode.style.display = "none";
+ },
+
+ animCollapse : function(callback){
+ var ct = Roo.get(this.ctNode);
+ ct.enableDisplayMode('block');
+ ct.stopFx();
+
+ this.animating = true;
+ this.updateExpandIcon();
+
+ ct.slideOut('t', {
+ callback : function(){
+ this.animating = false;
+ Roo.callback(callback);
+ },
+ scope: this,
+ duration: this.node.ownerTree.duration || .25
+ });
+ },
+
+ getContainer : function(){
+ return this.ctNode;
+ },
+
+ getEl : function(){
+ return this.wrap;
+ },
+
+ appendDDGhost : function(ghostNode){
+ ghostNode.appendChild(this.elNode.cloneNode(true));
+ },
+
+ getDDRepairXY : function(){
+ return Roo.lib.Dom.getXY(this.iconNode);
+ },
+
+ onRender : function(){
+ this.render();
+ },
+
+ render : function(bulkRender){
+ var n = this.node, a = n.attributes;
+ var targetNode = n.parentNode ?
+ n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
+
+ if(!this.rendered){
+ this.rendered = true;
+
+ this.renderElements(n, a, targetNode, bulkRender);
+
+ if(a.qtip){
+ if(this.textNode.setAttributeNS){
+ this.textNode.setAttributeNS("ext", "qtip", a.qtip);
+ if(a.qtipTitle){
+ this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
+ }
+ }else{
+ this.textNode.setAttribute("ext:qtip", a.qtip);
+ if(a.qtipTitle){
+ this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
+ }
+ }
+ }else if(a.qtipCfg){
+ a.qtipCfg.target = Roo.id(this.textNode);
+ Roo.QuickTips.register(a.qtipCfg);
+ }
+ this.initEvents();
+ if(!this.node.expanded){
+ this.updateExpandIcon();
+ }
+ }else{
+ if(bulkRender === true) {
+ targetNode.appendChild(this.wrap);
+ }
+ }
+ },
+
+ renderElements : function(n, a, targetNode, bulkRender)
+ {
+ // add some indent caching, this helps performance when rendering a large tree
+ this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
+ var t = n.getOwnerTree();
+ var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
+ if (typeof(n.attributes.html) != 'undefined') {
+ txt = n.attributes.html;
+ }
+ var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
+ var cb = typeof a.checked == 'boolean';
+ var href = a.href ? a.href : Roo.isGecko ? "" : "#";
+ var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
+ '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
+ '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
+ '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
+ cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
+ '<a hidefocus="on" href="',href,'" tabIndex="1" ',
+ a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "",
+ '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
+ '<ul class="x-tree-node-ct" style="display:none;"></ul>',
+ "</li>"];
+
+ if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
+ this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
+ n.nextSibling.ui.getEl(), buf.join(""));
+ }else{
+ this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
+ }
+
+ this.elNode = this.wrap.childNodes[0];
+ this.ctNode = this.wrap.childNodes[1];
+ var cs = this.elNode.childNodes;
+ this.indentNode = cs[0];
+ this.ecNode = cs[1];
+ this.iconNode = cs[2];
+ var index = 3;
+ if(cb){
+ this.checkbox = cs[3];
+ index++;
+ }
+ this.anchor = cs[index];
+ this.textNode = cs[index].firstChild;
+ },
+
+ getAnchor : function(){
+ return this.anchor;
+ },
+
+ getTextEl : function(){
+ return this.textNode;
+ },
+
+ getIconEl : function(){
+ return this.iconNode;
+ },
+
+ isChecked : function(){
+ return this.checkbox ? this.checkbox.checked : false;
+ },
+
+ updateExpandIcon : function(){
+ if(this.rendered){
+ var n = this.node, c1, c2;
+ var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
+ var hasChild = n.hasChildNodes();
+ if(hasChild){
+ if(n.expanded){
+ cls += "-minus";
+ c1 = "x-tree-node-collapsed";
+ c2 = "x-tree-node-expanded";
+ }else{
+ cls += "-plus";
+ c1 = "x-tree-node-expanded";
+ c2 = "x-tree-node-collapsed";
+ }
+ if(this.wasLeaf){
+ this.removeClass("x-tree-node-leaf");
+ this.wasLeaf = false;
}
+ if(this.c1 != c1 || this.c2 != c2){
+ Roo.fly(this.elNode).replaceClass(c1, c2);
+ this.c1 = c1; this.c2 = c2;
+ }
+ }else{
+ // this changes non-leafs into leafs if they have no children.
+ // it's not very rational behaviour..
+ if(!this.wasLeaf && this.node.leaf){
+ Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
+ delete this.c1;
+ delete this.c2;
+ this.wasLeaf = true;
+ }
}
- return dlg;
- },
-
- /**
- * Updates the message box body text
- * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
- * the XHTML-compliant non-breaking space character '&#160;')
- * @return {Roo.MessageBox} This message box
- */
- updateText : function(text){
- if(!dlg.isVisible() && !opt.width){
- dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
- }
- msgEl.innerHTML = text || ' ';
-
- var cw = Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
- //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
- var w = Math.max(
- Math.min(opt.width || cw , this.maxWidth),
- Math.max(opt.minWidth || this.minWidth, bwidth)
- );
- if(opt.prompt){
- activeTextEl.setWidth(w);
- }
- if(dlg.isVisible()){
- dlg.fixedcenter = false;
+ var ecc = "x-tree-ec-icon "+cls;
+ if(this.ecc != ecc){
+ this.ecNode.className = ecc;
+ this.ecc = ecc;
}
- // to big, make it scroll. = But as usual stupid IE does not support
- // !important..
-
- if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
- bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
- bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
- } else {
- bodyEl.dom.style.height = '';
- bodyEl.dom.style.overflowY = '';
+ }
+ },
+
+ getChildIndent : function(){
+ if(!this.childIndent){
+ var buf = [];
+ var p = this.node;
+ while(p){
+ if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
+ if(!p.isLast()) {
+ buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
+ } else {
+ buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
+ }
+ }
+ p = p.parentNode;
}
- if (cw > w) {
- bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
- } else {
- bodyEl.dom.style.overflowX = '';
+ this.childIndent = buf.join("");
+ }
+ return this.childIndent;
+ },
+
+ renderIndent : function(){
+ if(this.rendered){
+ var indent = "";
+ var p = this.node.parentNode;
+ if(p){
+ indent = p.ui.getChildIndent();
}
-
- dlg.setContentSize(w, bodyEl.getHeight());
- if(dlg.isVisible()){
- dlg.fixedcenter = true;
+ if(this.indentMarkup != indent){ // don't rerender if not required
+ this.indentNode.innerHTML = indent;
+ this.indentMarkup = indent;
}
- return this;
- },
+ this.updateExpandIcon();
+ }
+ }
+};
+
+Roo.tree.RootTreeNodeUI = function(){
+ Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
+};
+Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
+ render : function(){
+ if(!this.rendered){
+ var targetNode = this.node.ownerTree.innerCt.dom;
+ this.node.expanded = true;
+ targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
+ this.wrap = this.ctNode = targetNode.firstChild;
+ }
+ },
+ collapse : function(){
+ },
+ expand : function(){
+ }
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+/**
+ * @class Roo.tree.TreeLoader
+ * @extends Roo.util.Observable
+ * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
+ * nodes from a specified URL. The response must be a javascript Array definition
+ * who's elements are node definition objects. eg:
+ * <pre><code>
+{ success : true,
+ data : [
+
+ { 'id': 1, 'text': 'A folder Node', 'leaf': false },
+ { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
+ ]
+}
+
+
+</code></pre>
+ * <br><br>
+ * The old style respose with just an array is still supported, but not recommended.
+ * <br><br>
+ *
+ * A server request is sent, and child nodes are loaded only when a node is expanded.
+ * The loading node's id is passed to the server under the parameter name "node" to
+ * enable the server to produce the correct child nodes.
+ * <br><br>
+ * To pass extra parameters, an event handler may be attached to the "beforeload"
+ * event, and the parameters specified in the TreeLoader's baseParams property:
+ * <pre><code>
+ myTreeLoader.on("beforeload", function(treeLoader, node) {
+ this.baseParams.category = node.attributes.category;
+ }, this);
+
+</code></pre>
+ *
+ * This would pass an HTTP parameter called "category" to the server containing
+ * the value of the Node's "category" attribute.
+ * @constructor
+ * Creates a new Treeloader.
+ * @param {Object} config A config object containing config properties.
+ */
+Roo.tree.TreeLoader = function(config){
+ this.baseParams = {};
+ this.requestMethod = "POST";
+ Roo.apply(this, config);
+ this.addEvents({
+
/**
- * Updates a progress-style message box's text and progress bar. Only relevant on message boxes
- * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
- * @param {Number} value Any number between 0 and 1 (e.g., .5)
- * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
- * @return {Roo.MessageBox} This message box
+ * @event beforeload
+ * Fires before a network request is made to retrieve the Json text which specifies a node's children.
+ * @param {Object} This TreeLoader object.
+ * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
+ * @param {Object} callback The callback function specified in the {@link #load} call.
*/
- updateProgress : function(value, text){
- if(text){
- this.updateText(text);
- }
- if (pp) { // weird bug on my firefox - for some reason this is not defined
- pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
- }
- return this;
- },
-
+ beforeload : true,
/**
- * Returns true if the message box is currently displayed
- * @return {Boolean} True if the message box is visible, else false
+ * @event load
+ * Fires when the node has been successfuly loaded.
+ * @param {Object} This TreeLoader object.
+ * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
+ * @param {Object} response The response object containing the data from the server.
*/
- isVisible : function(){
- return dlg && dlg.isVisible();
- },
-
+ load : true,
/**
- * Hides the message box if it is displayed
+ * @event loadexception
+ * Fires if the network request failed.
+ * @param {Object} This TreeLoader object.
+ * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
+ * @param {Object} response The response object containing the data from the server.
*/
- hide : function(){
- if(this.isVisible()){
- dlg.hide();
- }
- },
-
+ loadexception : true,
/**
- * Displays a new message box, or reinitializes an existing message box, based on the config options
- * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
- * The following config object properties are supported:
- * <pre>
-Property Type Description
----------- --------------- ------------------------------------------------------------------------------------
-animEl String/Element An id or Element from which the message box should animate as it opens and
- closes (defaults to undefined)
-buttons Object/Boolean A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
- cancel:'Bar'}), or false to not show any buttons (defaults to false)
-closable Boolean False to hide the top-right close button (defaults to true). Note that
- progress and wait dialogs will ignore this property and always hide the
- close button as they can only be closed programmatically.
-cls String A custom CSS class to apply to the message box element
-defaultTextHeight Number The default height in pixels of the message box's multiline textarea if
- displayed (defaults to 75)
-fn Function A callback function to execute after closing the dialog. The arguments to the
- function will be btn (the name of the button that was clicked, if applicable,
- e.g. "ok"), and text (the value of the active text field, if applicable).
- Progress and wait dialogs will ignore this option since they do not respond to
- user actions and can only be closed programmatically, so any required function
- should be called by the same code after it closes the dialog.
-icon String A CSS class that provides a background image to be used as an icon for
- the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
-maxWidth Number The maximum width in pixels of the message box (defaults to 600)
-minWidth Number The minimum width in pixels of the message box (defaults to 100)
-modal Boolean False to allow user interaction with the page while the message box is
- displayed (defaults to true)
-msg String A string that will replace the existing message box body text (defaults
- to the XHTML-compliant non-breaking space character ' ')
-multiline Boolean True to prompt the user to enter multi-line text (defaults to false)
-progress Boolean True to display a progress bar (defaults to false)
-progressText String The text to display inside the progress bar if progress = true (defaults to '')
-prompt Boolean True to prompt the user to enter single-line text (defaults to false)
-proxyDrag Boolean True to display a lightweight proxy while dragging (defaults to false)
-title String The title text
-value String The string value to set into the active textbox element if displayed
-wait Boolean True to display a progress bar (defaults to false)
-width Number The width of the dialog in pixels
-</pre>
- *
- * Example usage:
- * <pre><code>
-Roo.Msg.show({
- title: 'Address',
- msg: 'Please enter your address:',
- width: 300,
- buttons: Roo.MessageBox.OKCANCEL,
- multiline: true,
- fn: saveAddress,
- animEl: 'addAddressBtn'
-});
-</code></pre>
- * @param {Object} config Configuration options
- * @return {Roo.MessageBox} This message box
+ * @event create
+ * Fires before a node is created, enabling you to return custom Node types
+ * @param {Object} This TreeLoader object.
+ * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
*/
- show : function(options)
- {
-
- // this causes nightmares if you show one dialog after another
- // especially on callbacks..
-
- if(this.isVisible()){
-
- this.hide();
- Roo.log("[Roo.Messagebox] Show called while message displayed:" );
- Roo.log("Old Dialog Message:" + msgEl.innerHTML );
- Roo.log("New Dialog Message:" + options.msg )
- //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
- //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
-
+ create : true
+ });
+
+ Roo.tree.TreeLoader.superclass.constructor.call(this);
+};
+
+Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
+ /**
+ * @cfg {String} dataUrl The URL from which to request a Json string which
+ * specifies an array of node definition object representing the child nodes
+ * to be loaded.
+ */
+ /**
+ * @cfg {String} requestMethod either GET or POST
+ * defaults to POST (due to BC)
+ * to be loaded.
+ */
+ /**
+ * @cfg {Object} baseParams (optional) An object containing properties which
+ * specify HTTP parameters to be passed to each request for child nodes.
+ */
+ /**
+ * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
+ * created by this loader. If the attributes sent by the server have an attribute in this object,
+ * they take priority.
+ */
+ /**
+ * @cfg {Object} uiProviders (optional) An object containing properties which
+ *
+ * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
+ * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
+ * <i>uiProvider</i> attribute of a returned child node is a string rather
+ * than a reference to a TreeNodeUI implementation, this that string value
+ * is used as a property name in the uiProviders object. You can define the provider named
+ * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
+ */
+ uiProviders : {},
+
+ /**
+ * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
+ * child nodes before loading.
+ */
+ clearOnLoad : true,
+
+ /**
+ * @cfg {String} root (optional) Default to false. Use this to read data from an object
+ * property on loading, rather than expecting an array. (eg. more compatible to a standard
+ * Grid query { data : [ .....] }
+ */
+
+ root : false,
+ /**
+ * @cfg {String} queryParam (optional)
+ * Name of the query as it will be passed on the querystring (defaults to 'node')
+ * eg. the request will be ?node=[id]
+ */
+
+
+ queryParam: false,
+
+ /**
+ * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
+ * This is called automatically when a node is expanded, but may be used to reload
+ * a node (or append new children if the {@link #clearOnLoad} option is false.)
+ * @param {Roo.tree.TreeNode} node
+ * @param {Function} callback
+ */
+ load : function(node, callback){
+ if(this.clearOnLoad){
+ while(node.firstChild){
+ node.removeChild(node.firstChild);
}
- var d = this.getDialog();
- opt = options;
- d.setTitle(opt.title || " ");
- d.close.setDisplayed(opt.closable !== false);
- activeTextEl = textboxEl;
- opt.prompt = opt.prompt || (opt.multiline ? true : false);
- if(opt.prompt){
- if(opt.multiline){
- textboxEl.hide();
- textareaEl.show();
- textareaEl.setHeight(typeof opt.multiline == "number" ?
- opt.multiline : this.defaultTextHeight);
- activeTextEl = textareaEl;
- }else{
- textboxEl.show();
- textareaEl.hide();
- }
- }else{
- textboxEl.hide();
- textareaEl.hide();
+ }
+ if(node.attributes.children){ // preloaded json children
+ var cs = node.attributes.children;
+ for(var i = 0, len = cs.length; i < len; i++){
+ node.appendChild(this.createNode(cs[i]));
}
- progressEl.setDisplayed(opt.progress === true);
- this.updateProgress(0);
- activeTextEl.dom.value = opt.value || "";
- if(opt.prompt){
- dlg.setDefaultButton(activeTextEl);
- }else{
- var bs = opt.buttons;
- var db = null;
- if(bs && bs.ok){
- db = buttons["ok"];
- }else if(bs && bs.yes){
- db = buttons["yes"];
+ if(typeof callback == "function"){
+ callback();
+ }
+ }else if(this.dataUrl){
+ this.requestData(node, callback);
+ }
+ },
+
+ getParams: function(node){
+ var buf = [], bp = this.baseParams;
+ for(var key in bp){
+ if(typeof bp[key] != "function"){
+ buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
+ }
+ }
+ var n = this.queryParam === false ? 'node' : this.queryParam;
+ buf.push(n + "=", encodeURIComponent(node.id));
+ return buf.join("");
+ },
+
+ requestData : function(node, callback){
+ if(this.fireEvent("beforeload", this, node, callback) !== false){
+ this.transId = Roo.Ajax.request({
+ method:this.requestMethod,
+ url: this.dataUrl||this.url,
+ success: this.handleResponse,
+ failure: this.handleFailure,
+ scope: this,
+ argument: {callback: callback, node: node},
+ params: this.getParams(node)
+ });
+ }else{
+ // if the load is cancelled, make sure we notify
+ // the node that we are done
+ if(typeof callback == "function"){
+ callback();
+ }
+ }
+ },
+
+ isLoading : function(){
+ return this.transId ? true : false;
+ },
+
+ abort : function(){
+ if(this.isLoading()){
+ Roo.Ajax.abort(this.transId);
+ }
+ },
+
+ // private
+ createNode : function(attr)
+ {
+ // apply baseAttrs, nice idea Corey!
+ if(this.baseAttrs){
+ Roo.applyIf(attr, this.baseAttrs);
+ }
+ if(this.applyLoader !== false){
+ attr.loader = this;
+ }
+ // uiProvider = depreciated..
+
+ if(typeof(attr.uiProvider) == 'string'){
+ attr.uiProvider = this.uiProviders[attr.uiProvider] ||
+ /** eval:var:attr */ eval(attr.uiProvider);
+ }
+ if(typeof(this.uiProviders['default']) != 'undefined') {
+ attr.uiProvider = this.uiProviders['default'];
+ }
+
+ this.fireEvent('create', this, attr);
+
+ attr.leaf = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
+ return(attr.leaf ?
+ new Roo.tree.TreeNode(attr) :
+ new Roo.tree.AsyncTreeNode(attr));
+ },
+
+ processResponse : function(response, node, callback)
+ {
+ var json = response.responseText;
+ try {
+
+ var o = Roo.decode(json);
+
+ if (this.root === false && typeof(o.success) != undefined) {
+ this.root = 'data'; // the default behaviour for list like data..
}
- dlg.setDefaultButton(db);
+
+ if (this.root !== false && !o.success) {
+ // it's a failure condition.
+ var a = response.argument;
+ this.fireEvent("loadexception", this, a.node, response);
+ Roo.log("Load failed - should have a handler really");
+ return;
}
- bwidth = updateButtons(opt.buttons);
- this.updateText(opt.msg);
- if(opt.cls){
- d.el.addClass(opt.cls);
+
+
+
+ if (this.root !== false) {
+ o = o[this.root];
+ }
+
+ for(var i = 0, len = o.length; i < len; i++){
+ var n = this.createNode(o[i]);
+ if(n){
+ node.appendChild(n);
+ }
}
- d.proxyDrag = opt.proxyDrag === true;
- d.modal = opt.modal !== false;
- d.mask = opt.modal !== false ? mask : false;
- if(!d.isVisible()){
- // force it to the end of the z-index stack so it gets a cursor in FF
- document.body.appendChild(dlg.el.dom);
- d.animateTarget = null;
- d.show(options.animEl);
+ if(typeof callback == "function"){
+ callback(this, node);
}
- dlg.toFront();
- return this;
- },
+ }catch(e){
+ this.handleFailure(response);
+ }
+ },
- /**
- * Displays a message box with a progress bar. This message box has no buttons and is not closeable by
- * the user. You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
- * and closing the message box when the process is complete.
- * @param {String} title The title bar text
- * @param {String} msg The message box body text
- * @return {Roo.MessageBox} This message box
- */
- progress : function(title, msg){
- this.show({
- title : title,
- msg : msg,
- buttons: false,
- progress:true,
- closable:false,
- minWidth: this.minProgressWidth,
- modal : true
- });
- return this;
- },
+ handleResponse : function(response){
+ this.transId = false;
+ var a = response.argument;
+ this.processResponse(response, a.node, a.callback);
+ this.fireEvent("load", this, a.node, response);
+ },
- /**
- * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
- * If a callback function is passed it will be called after the user clicks the button, and the
- * id of the button that was clicked will be passed as the only parameter to the callback
- * (could also be the top-right close button).
- * @param {String} title The title bar text
- * @param {String} msg The message box body text
- * @param {Function} fn (optional) The callback function invoked after the message box is closed
- * @param {Object} scope (optional) The scope of the callback function
- * @return {Roo.MessageBox} This message box
- */
- alert : function(title, msg, fn, scope){
- this.show({
- title : title,
- msg : msg,
- buttons: this.OK,
- fn: fn,
- scope : scope,
- modal : true
- });
- return this;
- },
+ handleFailure : function(response)
+ {
+ // should handle failure better..
+ this.transId = false;
+ var a = response.argument;
+ this.fireEvent("loadexception", this, a.node, response);
+ if(typeof a.callback == "function"){
+ a.callback(this, a.node);
+ }
+ }
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
- /**
- * Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
- * interaction while waiting for a long-running process to complete that does not have defined intervals.
- * You are responsible for closing the message box when the process is complete.
- * @param {String} msg The message box body text
- * @param {String} title (optional) The title bar text
- * @return {Roo.MessageBox} This message box
- */
- wait : function(msg, title){
- this.show({
- title : title,
- msg : msg,
- buttons: false,
- closable:false,
- progress:true,
- modal:true,
- width:300,
- wait:true
- });
- waitTimer = Roo.TaskMgr.start({
- run: function(i){
- Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
- },
- interval: 1000
- });
- return this;
- },
+/**
+* @class Roo.tree.TreeFilter
+* Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
+* @param {TreePanel} tree
+* @param {Object} config (optional)
+ */
+Roo.tree.TreeFilter = function(tree, config){
+ this.tree = tree;
+ this.filtered = {};
+ Roo.apply(this, config);
+};
- /**
- * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
- * If a callback function is passed it will be called after the user clicks either button, and the id of the
- * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
- * @param {String} title The title bar text
- * @param {String} msg The message box body text
- * @param {Function} fn (optional) The callback function invoked after the message box is closed
- * @param {Object} scope (optional) The scope of the callback function
- * @return {Roo.MessageBox} This message box
- */
- confirm : function(title, msg, fn, scope){
- this.show({
- title : title,
- msg : msg,
- buttons: this.YESNO,
- fn: fn,
- scope : scope,
- modal : true
- });
- return this;
- },
+Roo.tree.TreeFilter.prototype = {
+ clearBlank:false,
+ reverse:false,
+ autoClear:false,
+ remove:false,
- /**
- * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
- * JavaScript's Window.prompt). The prompt can be a single-line or multi-line textbox. If a callback function
- * is passed it will be called after the user clicks either button, and the id of the button that was clicked
- * (could also be the top-right close button) and the text that was entered will be passed as the two
- * parameters to the callback.
- * @param {String} title The title bar text
- * @param {String} msg The message box body text
- * @param {Function} fn (optional) The callback function invoked after the message box is closed
- * @param {Object} scope (optional) The scope of the callback function
- * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
- * property, or the height in pixels to create the textbox (defaults to false / single-line)
- * @return {Roo.MessageBox} This message box
- */
- prompt : function(title, msg, fn, scope, multiline){
- this.show({
- title : title,
- msg : msg,
- buttons: this.OKCANCEL,
- fn: fn,
- minWidth:250,
- scope : scope,
- prompt:true,
- multiline: multiline,
- modal : true
- });
- return this;
- },
+ /**
+ * Filter the data by a specific attribute.
+ * @param {String/RegExp} value Either string that the attribute value
+ * should start with or a RegExp to test against the attribute
+ * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
+ * @param {TreeNode} startNode (optional) The node to start the filter at.
+ */
+ filter : function(value, attr, startNode){
+ attr = attr || "text";
+ var f;
+ if(typeof value == "string"){
+ var vlen = value.length;
+ // auto clear empty filter
+ if(vlen == 0 && this.clearBlank){
+ this.clear();
+ return;
+ }
+ value = value.toLowerCase();
+ f = function(n){
+ return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
+ };
+ }else if(value.exec){ // regex?
+ f = function(n){
+ return value.test(n.attributes[attr]);
+ };
+ }else{
+ throw 'Illegal filter type, must be string or regex';
+ }
+ this.filterBy(f, null, startNode);
+ },
- /**
- * Button config that displays a single OK button
- * @type Object
- */
- OK : {ok:true},
- /**
- * Button config that displays Yes and No buttons
- * @type Object
- */
- YESNO : {yes:true, no:true},
- /**
- * Button config that displays OK and Cancel buttons
- * @type Object
- */
- OKCANCEL : {ok:true, cancel:true},
- /**
- * Button config that displays Yes, No and Cancel buttons
- * @type Object
- */
- YESNOCANCEL : {yes:true, no:true, cancel:true},
+ /**
+ * Filter by a function. The passed function will be called with each
+ * node in the tree (or from the startNode). If the function returns true, the node is kept
+ * otherwise it is filtered. If a node is filtered, its children are also filtered.
+ * @param {Function} fn The filter function
+ * @param {Object} scope (optional) The scope of the function (defaults to the current node)
+ */
+ filterBy : function(fn, scope, startNode){
+ startNode = startNode || this.tree.root;
+ if(this.autoClear){
+ this.clear();
+ }
+ var af = this.filtered, rv = this.reverse;
+ var f = function(n){
+ if(n == startNode){
+ return true;
+ }
+ if(af[n.id]){
+ return false;
+ }
+ var m = fn.call(scope || n, n);
+ if(!m || rv){
+ af[n.id] = n;
+ n.ui.hide();
+ return false;
+ }
+ return true;
+ };
+ startNode.cascade(f);
+ if(this.remove){
+ for(var id in af){
+ if(typeof id != "function"){
+ var n = af[id];
+ if(n && n.parentNode){
+ n.parentNode.removeChild(n);
+ }
+ }
+ }
+ }
+ },
- /**
- * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
- * @type Number
- */
- defaultTextHeight : 75,
- /**
- * The maximum width in pixels of the message box (defaults to 600)
- * @type Number
- */
- maxWidth : 600,
- /**
- * The minimum width in pixels of the message box (defaults to 100)
- * @type Number
- */
- minWidth : 100,
- /**
- * The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
- * for setting a different minimum width than text-only dialogs may need (defaults to 250)
- * @type Number
- */
- minProgressWidth : 250,
- /**
- * An object containing the default button text strings that can be overriden for localized language support.
- * Supported properties are: ok, cancel, yes and no.
- * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
- * @type Object
- */
- buttonText : {
- ok : "OK",
- cancel : "Cancel",
- yes : "Yes",
- no : "No"
+ /**
+ * Clears the current filter. Note: with the "remove" option
+ * set a filter cannot be cleared.
+ */
+ clear : function(){
+ var t = this.tree;
+ var af = this.filtered;
+ for(var id in af){
+ if(typeof id != "function"){
+ var n = af[id];
+ if(n){
+ n.ui.show();
+ }
+ }
}
- };
-}();
+ this.filtered = {};
+ }
+};
+/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
/**
- * Shorthand for {@link Roo.MessageBox}
+ * @class Roo.tree.TreeSorter
+ * Provides sorting of nodes in a TreePanel
+ *
+ * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
+ * @cfg {String} property The named attribute on the node to sort by (defaults to text)
+ * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
+ * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
+ * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
+ * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
+ * @constructor
+ * @param {TreePanel} tree
+ * @param {Object} config
*/
-Roo.Msg = Roo.MessageBox;/*
+Roo.tree.TreeSorter = function(tree, config){
+ Roo.apply(this, config);
+ tree.on("beforechildrenrendered", this.doSort, this);
+ tree.on("append", this.updateSort, this);
+ tree.on("insert", this.updateSort, this);
+
+ var dsc = this.dir && this.dir.toLowerCase() == "desc";
+ var p = this.property || "text";
+ var sortType = this.sortType;
+ var fs = this.folderSort;
+ var cs = this.caseSensitive === true;
+ var leafAttr = this.leafAttr || 'leaf';
+
+ this.sortFn = function(n1, n2){
+ if(fs){
+ if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
+ return 1;
+ }
+ if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
+ return -1;
+ }
+ }
+ var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
+ var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
+ if(v1 < v2){
+ return dsc ? +1 : -1;
+ }else if(v1 > v2){
+ return dsc ? -1 : +1;
+ }else{
+ return 0;
+ }
+ };
+};
+
+Roo.tree.TreeSorter.prototype = {
+ doSort : function(node){
+ node.sort(this.sortFn);
+ },
+
+ compareNodes : function(n1, n2){
+ return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
+ },
+
+ updateSort : function(tree, node){
+ if(node.childrenRendered){
+ this.doSort.defer(1, this, [node]);
+ }
+ }
+};/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* Fork - LGPL
* <script type="text/javascript">
*/
-/**
- * @class Roo.QuickTips
- * Provides attractive and customizable tooltips for any element.
- * @static
- */
-Roo.QuickTips = function(){
- var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
- var ce, bd, xy, dd;
- var visible = false, disabled = true, inited = false;
- var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
+
+if(Roo.dd.DropZone){
- var onOver = function(e){
- if(disabled){
- return;
+Roo.tree.TreeDropZone = function(tree, config){
+ this.allowParentInsert = false;
+ this.allowContainerDrop = false;
+ this.appendOnly = false;
+ Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
+ this.tree = tree;
+ this.lastInsertClass = "x-tree-no-status";
+ this.dragOverData = {};
+};
+
+Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
+ ddGroup : "TreeDD",
+ scroll: true,
+
+ expandDelay : 1000,
+
+ expandNode : function(node){
+ if(node.hasChildNodes() && !node.isExpanded()){
+ node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
}
- var t = e.getTarget();
- if(!t || t.nodeType !== 1 || t == document || t == document.body){
- return;
+ },
+
+ queueExpand : function(node){
+ this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
+ },
+
+ cancelExpand : function(){
+ if(this.expandProcId){
+ clearTimeout(this.expandProcId);
+ this.expandProcId = false;
}
- if(ce && t == ce.el){
- clearTimeout(hideProc);
- return;
+ },
+
+ isValidDropPoint : function(n, pt, dd, e, data){
+ if(!n || !data){ return false; }
+ var targetNode = n.node;
+ var dropNode = data.node;
+ // default drop rules
+ if(!(targetNode && targetNode.isTarget && pt)){
+ return false;
}
- if(t && tagEls[t.id]){
- tagEls[t.id].el = t;
- showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
- return;
+ if(pt == "append" && targetNode.allowChildren === false){
+ return false;
}
- var ttp, et = Roo.fly(t);
- var ns = cfg.namespace;
- if(tm.interceptTitles && t.title){
- ttp = t.title;
- t.qtip = ttp;
- t.removeAttribute("title");
- e.preventDefault();
- }else{
- ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
+ if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
+ return false;
}
- if(ttp){
- showProc = show.defer(tm.showDelay, tm, [{
- el: t,
- text: ttp.replace(/\\n/g,'<br/>'),
- width: et.getAttributeNS(ns, cfg.width),
- autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
- title: et.getAttributeNS(ns, cfg.title),
- cls: et.getAttributeNS(ns, cfg.cls)
- }]);
+ if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
+ return false;
}
- };
+ // reuse the object
+ var overEvent = this.dragOverData;
+ overEvent.tree = this.tree;
+ overEvent.target = targetNode;
+ overEvent.data = data;
+ overEvent.point = pt;
+ overEvent.source = dd;
+ overEvent.rawEvent = e;
+ overEvent.dropNode = dropNode;
+ overEvent.cancel = false;
+ var result = this.tree.fireEvent("nodedragover", overEvent);
+ return overEvent.cancel === false && result !== false;
+ },
- var onOut = function(e){
- clearTimeout(showProc);
- var t = e.getTarget();
- if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
- hideProc = setTimeout(hide, tm.hideDelay);
+ getDropPoint : function(e, n, dd)
+ {
+ var tn = n.node;
+ if(tn.isRoot){
+ return tn.allowChildren !== false ? "append" : false; // always append for root
+ }
+ var dragEl = n.ddel;
+ var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
+ var y = Roo.lib.Event.getPageY(e);
+ //var noAppend = tn.allowChildren === false || tn.isLeaf();
+
+ // we may drop nodes anywhere, as long as allowChildren has not been set to false..
+ var noAppend = tn.allowChildren === false;
+ if(this.appendOnly || tn.parentNode.allowChildren === false){
+ return noAppend ? false : "append";
}
- };
-
- var onMove = function(e){
- if(disabled){
- return;
+ var noBelow = false;
+ if(!this.allowParentInsert){
+ noBelow = tn.hasChildNodes() && tn.isExpanded();
}
- xy = e.getXY();
- xy[1] += 18;
- if(tm.trackMouse && ce){
- el.setXY(xy);
+ var q = (b - t) / (noAppend ? 2 : 3);
+ if(y >= t && y < (t + q)){
+ return "above";
+ }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
+ return "below";
+ }else{
+ return "append";
}
- };
+ },
- var onDown = function(e){
- clearTimeout(showProc);
- clearTimeout(hideProc);
- if(!e.within(el)){
- if(tm.hideOnClick){
- hide();
- tm.disable();
- tm.enable.defer(100, tm);
- }
- }
- };
+ onNodeEnter : function(n, dd, e, data)
+ {
+ this.cancelExpand();
+ },
- var getPad = function(){
- return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
- };
-
- var show = function(o){
- if(disabled){
- return;
+ onNodeOver : function(n, dd, e, data)
+ {
+
+ var pt = this.getDropPoint(e, n, dd);
+ var node = n.node;
+
+ // auto node expand check
+ if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
+ this.queueExpand(node);
+ }else if(pt != "append"){
+ this.cancelExpand();
}
- clearTimeout(dismissProc);
- ce = o;
- if(removeCls){ // in case manually hidden
- el.removeClass(removeCls);
- removeCls = null;
+
+ // set the insert point style on the target node
+ var returnCls = this.dropNotAllowed;
+ if(this.isValidDropPoint(n, pt, dd, e, data)){
+ if(pt){
+ var el = n.ddel;
+ var cls;
+ if(pt == "above"){
+ returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
+ cls = "x-tree-drag-insert-above";
+ }else if(pt == "below"){
+ returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
+ cls = "x-tree-drag-insert-below";
+ }else{
+ returnCls = "x-tree-drop-ok-append";
+ cls = "x-tree-drag-append";
+ }
+ if(this.lastInsertClass != cls){
+ Roo.fly(el).replaceClass(this.lastInsertClass, cls);
+ this.lastInsertClass = cls;
+ }
+ }
+ }
+ return returnCls;
+ },
+
+ onNodeOut : function(n, dd, e, data){
+
+ this.cancelExpand();
+ this.removeDropIndicators(n);
+ },
+
+ onNodeDrop : function(n, dd, e, data){
+ var point = this.getDropPoint(e, n, dd);
+ var targetNode = n.node;
+ targetNode.ui.startDrop();
+ if(!this.isValidDropPoint(n, point, dd, e, data)){
+ targetNode.ui.endDrop();
+ return false;
}
- if(ce.cls){
- el.addClass(ce.cls);
- removeCls = ce.cls;
+ // first try to find the drop node
+ var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
+ var dropEvent = {
+ tree : this.tree,
+ target: targetNode,
+ data: data,
+ point: point,
+ source: dd,
+ rawEvent: e,
+ dropNode: dropNode,
+ cancel: !dropNode
+ };
+ var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
+ if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
+ targetNode.ui.endDrop();
+ return false;
}
- if(ce.title){
- tipTitle.update(ce.title);
- tipTitle.show();
+ // allow target changing
+ targetNode = dropEvent.target;
+ if(point == "append" && !targetNode.isExpanded()){
+ targetNode.expand(false, null, function(){
+ this.completeDrop(dropEvent);
+ }.createDelegate(this));
}else{
- tipTitle.update('');
- tipTitle.hide();
+ this.completeDrop(dropEvent);
}
- el.dom.style.width = tm.maxWidth+'px';
- //tipBody.dom.style.width = '';
- tipBodyText.update(o.text);
- var p = getPad(), w = ce.width;
- if(!w){
- var td = tipBodyText.dom;
- var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
- if(aw > tm.maxWidth){
- w = tm.maxWidth;
- }else if(aw < tm.minWidth){
- w = tm.minWidth;
- }else{
- w = aw;
- }
+ return true;
+ },
+
+ completeDrop : function(de){
+ var ns = de.dropNode, p = de.point, t = de.target;
+ if(!(ns instanceof Array)){
+ ns = [ns];
}
- //tipBody.setWidth(w);
- el.setWidth(parseInt(w, 10) + p);
- if(ce.autoHide === false){
- close.setDisplayed(true);
- if(dd){
- dd.unlock();
- }
- }else{
- close.setDisplayed(false);
- if(dd){
- dd.lock();
+ var n;
+ for(var i = 0, len = ns.length; i < len; i++){
+ n = ns[i];
+ if(p == "above"){
+ t.parentNode.insertBefore(n, t);
+ }else if(p == "below"){
+ t.parentNode.insertBefore(n, t.nextSibling);
+ }else{
+ t.appendChild(n);
}
}
- if(xy){
- el.avoidY = xy[1]-18;
- el.setXY(xy);
- }
- if(tm.animate){
- el.setOpacity(.1);
- el.setStyle("visibility", "visible");
- el.fadeIn({callback: afterShow});
- }else{
- afterShow();
+ n.ui.focus();
+ if(this.tree.hlDrop){
+ n.ui.highlight();
}
- };
+ t.ui.endDrop();
+ this.tree.fireEvent("nodedrop", de);
+ },
- var afterShow = function(){
- if(ce){
- el.show();
- esc.enable();
- if(tm.autoDismiss && ce.autoHide !== false){
- dismissProc = setTimeout(hide, tm.autoDismissDelay);
- }
+ afterNodeMoved : function(dd, data, e, targetNode, dropNode){
+ if(this.tree.hlDrop){
+ dropNode.ui.focus();
+ dropNode.ui.highlight();
}
- };
+ this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
+ },
- var hide = function(noanim){
- clearTimeout(dismissProc);
- clearTimeout(hideProc);
- ce = null;
- if(el.isVisible()){
- esc.disable();
- if(noanim !== true && tm.animate){
- el.fadeOut({callback: afterHide});
- }else{
- afterHide();
- }
+ getTree : function(){
+ return this.tree;
+ },
+
+ removeDropIndicators : function(n){
+ if(n && n.ddel){
+ var el = n.ddel;
+ Roo.fly(el).removeClass([
+ "x-tree-drag-insert-above",
+ "x-tree-drag-insert-below",
+ "x-tree-drag-append"]);
+ this.lastInsertClass = "_noclass";
}
- };
+ },
- var afterHide = function(){
- el.hide();
- if(removeCls){
- el.removeClass(removeCls);
- removeCls = null;
+ beforeDragDrop : function(target, e, id){
+ this.cancelExpand();
+ return true;
+ },
+
+ afterRepair : function(data){
+ if(data && Roo.enableFx){
+ data.node.ui.highlight();
}
- };
+ this.hideProxy();
+ }
- return {
- /**
- * @cfg {Number} minWidth
- * The minimum width of the quick tip (defaults to 40)
- */
- minWidth : 40,
- /**
- * @cfg {Number} maxWidth
- * The maximum width of the quick tip (defaults to 300)
- */
- maxWidth : 300,
- /**
- * @cfg {Boolean} interceptTitles
- * True to automatically use the element's DOM title value if available (defaults to false)
- */
- interceptTitles : false,
- /**
- * @cfg {Boolean} trackMouse
- * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
- */
- trackMouse : false,
- /**
- * @cfg {Boolean} hideOnClick
- * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
- */
- hideOnClick : true,
- /**
- * @cfg {Number} showDelay
- * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
- */
- showDelay : 500,
- /**
- * @cfg {Number} hideDelay
- * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
- */
- hideDelay : 200,
- /**
- * @cfg {Boolean} autoHide
- * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
- * Used in conjunction with hideDelay.
- */
- autoHide : true,
- /**
- * @cfg {Boolean}
- * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
- * (defaults to true). Used in conjunction with autoDismissDelay.
- */
- autoDismiss : true,
- /**
- * @cfg {Number}
- * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
- */
- autoDismissDelay : 5000,
- /**
- * @cfg {Boolean} animate
- * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
- */
- animate : false,
-
- /**
- * @cfg {String} title
- * Title text to display (defaults to ''). This can be any valid HTML markup.
- */
- title: '',
- /**
- * @cfg {String} text
- * Body text to display (defaults to ''). This can be any valid HTML markup.
- */
- text : '',
- /**
- * @cfg {String} cls
- * A CSS class to apply to the base quick tip element (defaults to '').
- */
- cls : '',
- /**
- * @cfg {Number} width
- * Width in pixels of the quick tip (defaults to auto). Width will be ignored if it exceeds the bounds of
- * minWidth or maxWidth.
- */
- width : null,
-
- /**
- * Initialize and enable QuickTips for first use. This should be called once before the first attempt to access
- * or display QuickTips in a page.
- */
- init : function(){
- tm = Roo.QuickTips;
- cfg = tm.tagConfig;
- if(!inited){
- if(!Roo.isReady){ // allow calling of init() before onReady
- Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
- return;
- }
- el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
- el.fxDefaults = {stopFx: true};
- // maximum custom styling
- //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>');
- 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>');
- tipTitle = el.child('h3');
- tipTitle.enableDisplayMode("block");
- tipBody = el.child('div.x-tip-bd');
- tipBodyText = el.child('div.x-tip-bd-inner');
- //bdLeft = el.child('div.x-tip-bd-left');
- //bdRight = el.child('div.x-tip-bd-right');
- close = el.child('div.x-tip-close');
- close.enableDisplayMode("block");
- close.on("click", hide);
- var d = Roo.get(document);
- d.on("mousedown", onDown);
- d.on("mouseover", onOver);
- d.on("mouseout", onOut);
- d.on("mousemove", onMove);
- esc = d.addKeyListener(27, hide);
- esc.disable();
- if(Roo.dd.DD){
- dd = el.initDD("default", null, {
- onDrag : function(){
- el.sync();
- }
- });
- dd.setHandleElId(tipTitle.id);
- dd.lock();
- }
- inited = true;
- }
- this.enable();
- },
-
- /**
- * Configures a new quick tip instance and assigns it to a target element. The following config options
- * are supported:
- * <pre>
-Property Type Description
----------- --------------------- ------------------------------------------------------------------------
-target Element/String/Array An Element, id or array of ids that this quick tip should be tied to
- * </ul>
- * @param {Object} config The config object
- */
- register : function(config){
- var cs = config instanceof Array ? config : arguments;
- for(var i = 0, len = cs.length; i < len; i++) {
- var c = cs[i];
- var target = c.target;
- if(target){
- if(target instanceof Array){
- for(var j = 0, jlen = target.length; j < jlen; j++){
- tagEls[target[j]] = c;
- }
- }else{
- tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
- }
- }
- }
- },
-
- /**
- * Removes this quick tip from its element and destroys it.
- * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
- */
- unregister : function(el){
- delete tagEls[Roo.id(el)];
- },
-
- /**
- * Enable this quick tip.
- */
- enable : function(){
- if(inited && disabled){
- locks.pop();
- if(locks.length < 1){
- disabled = false;
- }
- }
- },
-
- /**
- * Disable this quick tip.
- */
- disable : function(){
- disabled = true;
- clearTimeout(showProc);
- clearTimeout(hideProc);
- clearTimeout(dismissProc);
- if(ce){
- hide(true);
- }
- locks.push(1);
- },
+});
- /**
- * Returns true if the quick tip is enabled, else false.
- */
- isEnabled : function(){
- return !disabled;
- },
+}
+/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
- // private
- tagConfig : {
- namespace : "roo", // was ext?? this may break..
- alt_namespace : "ext",
- attribute : "qtip",
- width : "width",
- target : "target",
- title : "qtitle",
- hide : "hide",
- cls : "qclass"
- }
- };
-}();
+if(Roo.dd.DragZone){
+Roo.tree.TreeDragZone = function(tree, config){
+ Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
+ this.tree = tree;
+};
-// backwards compat
-Roo.QuickTips.tips = Roo.QuickTips.register;/*
+Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
+ ddGroup : "TreeDD",
+
+ onBeforeDrag : function(data, e){
+ var n = data.node;
+ return n && n.draggable && !n.disabled;
+ },
+
+
+ onInitDrag : function(e){
+ var data = this.dragData;
+ this.tree.getSelectionModel().select(data.node);
+ this.proxy.update("");
+ data.node.ui.appendDDGhost(this.proxy.ghost.dom);
+ this.tree.fireEvent("startdrag", this.tree, data.node, e);
+ },
+
+ getRepairXY : function(e, data){
+ return data.node.ui.getDDRepairXY();
+ },
+
+ onEndDrag : function(data, e){
+ this.tree.fireEvent("enddrag", this.tree, data.node, e);
+
+
+ },
+
+ onValidDrop : function(dd, e, id){
+ this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
+ this.hideProxy();
+ },
+
+ beforeInvalidDrop : function(e, id){
+ // this scrolls the original position back into view
+ var sm = this.tree.getSelectionModel();
+ sm.clearSelections();
+ sm.select(this.dragData.node);
+ }
+});
+}/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* Fork - LGPL
* <script type="text/javascript">
*/
-
-
/**
- * @class Roo.tree.TreePanel
- * @extends Roo.data.Tree
- * @cfg {Roo.tree.TreeNode} root The root node
- * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
- * @cfg {Boolean} lines false to disable tree lines (defaults to true)
- * @cfg {Boolean} enableDD true to enable drag and drop
- * @cfg {Boolean} enableDrag true to enable just drag
- * @cfg {Boolean} enableDrop true to enable just drop
- * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
- * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
- * @cfg {String} ddGroup The DD group this TreePanel belongs to
- * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
- * @cfg {Boolean} ddScroll true to enable YUI body scrolling
- * @cfg {Boolean} containerScroll true to register this container with ScrollManager
- * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
- * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
- * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
- * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
- * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
- * @cfg {Roo.tree.TreeLoader} loader A TreeLoader for use with this TreePanel
- * @cfg {Roo.tree.TreeEditor} editor The TreeEditor to display when clicked.
- * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
- * @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>
- * @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>
- *
+ * @class Roo.tree.TreeEditor
+ * @extends Roo.Editor
+ * Provides editor functionality for inline tree node editing. Any valid {@link Roo.form.Field} can be used
+ * as the editor field.
* @constructor
- * @param {String/HTMLElement/Element} el The container element
- * @param {Object} config
+ * @param {Object} config (used to be the tree panel.)
+ * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
+ *
+ * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
+ * @cfg {Roo.form.TextField} field [required] The field configuration
+ *
+ *
*/
-Roo.tree.TreePanel = function(el, config){
- var root = false;
- var loader = false;
- if (config.root) {
- root = config.root;
- delete config.root;
- }
- if (config.loader) {
- loader = config.loader;
- delete config.loader;
+Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
+ var tree = config;
+ var field;
+ if (oldconfig) { // old style..
+ field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
+ } else {
+ // new style..
+ tree = config.tree;
+ config.field = config.field || {};
+ config.field.xtype = 'TextField';
+ field = Roo.factory(config.field, Roo.form);
}
+ config = config || {};
+
- Roo.apply(this, config);
- Roo.tree.TreePanel.superclass.constructor.call(this);
- this.el = Roo.get(el);
- this.el.addClass('x-tree');
- //console.log(root);
- if (root) {
- this.setRootNode( Roo.factory(root, Roo.tree));
- }
- if (loader) {
- this.loader = Roo.factory(loader, Roo.tree);
- }
- /**
- * Read-only. The id of the container element becomes this TreePanel's id.
- */
- this.id = this.el.id;
this.addEvents({
/**
- * @event beforeload
- * Fires before a node is loaded, return false to cancel
- * @param {Node} node The node being loaded
- */
- "beforeload" : true,
- /**
- * @event load
- * Fires when a node is loaded
- * @param {Node} node The node that was loaded
- */
- "load" : true,
- /**
- * @event textchange
- * Fires when the text for a node is changed
- * @param {Node} node The node
- * @param {String} text The new text
- * @param {String} oldText The old text
- */
- "textchange" : true,
- /**
- * @event beforeexpand
- * Fires before a node is expanded, return false to cancel.
- * @param {Node} node The node
- * @param {Boolean} deep
- * @param {Boolean} anim
- */
- "beforeexpand" : true,
- /**
- * @event beforecollapse
- * Fires before a node is collapsed, return false to cancel.
- * @param {Node} node The node
- * @param {Boolean} deep
- * @param {Boolean} anim
- */
- "beforecollapse" : true,
- /**
- * @event expand
- * Fires when a node is expanded
- * @param {Node} node The node
- */
- "expand" : true,
- /**
- * @event disabledchange
- * Fires when the disabled status of a node changes
- * @param {Node} node The node
- * @param {Boolean} disabled
- */
- "disabledchange" : true,
- /**
- * @event collapse
- * Fires when a node is collapsed
- * @param {Node} node The node
- */
- "collapse" : true,
- /**
- * @event beforeclick
- * Fires before click processing on a node. Return false to cancel the default action.
- * @param {Node} node The node
- * @param {Roo.EventObject} e The event object
- */
- "beforeclick":true,
- /**
- * @event checkchange
- * Fires when a node with a checkbox's checked property changes
- * @param {Node} this This node
- * @param {Boolean} checked
- */
- "checkchange":true,
- /**
- * @event click
- * Fires when a node is clicked
- * @param {Node} node The node
- * @param {Roo.EventObject} e The event object
- */
- "click":true,
- /**
- * @event dblclick
- * Fires when a node is double clicked
- * @param {Node} node The node
- * @param {Roo.EventObject} e The event object
- */
- "dblclick":true,
- /**
- * @event contextmenu
- * Fires when a node is right clicked
- * @param {Node} node The node
- * @param {Roo.EventObject} e The event object
- */
- "contextmenu":true,
- /**
- * @event beforechildrenrendered
- * Fires right before the child nodes for a node are rendered
- * @param {Node} node The node
- */
- "beforechildrenrendered":true,
- /**
- * @event startdrag
- * Fires when a node starts being dragged
- * @param {Roo.tree.TreePanel} this
- * @param {Roo.tree.TreeNode} node
- * @param {event} e The raw browser event
- */
- "startdrag" : true,
- /**
- * @event enddrag
- * Fires when a drag operation is complete
- * @param {Roo.tree.TreePanel} this
- * @param {Roo.tree.TreeNode} node
- * @param {event} e The raw browser event
- */
- "enddrag" : true,
- /**
- * @event dragdrop
- * Fires when a dragged node is dropped on a valid DD target
- * @param {Roo.tree.TreePanel} this
- * @param {Roo.tree.TreeNode} node
- * @param {DD} dd The dd it was dropped on
- * @param {event} e The raw browser event
- */
- "dragdrop" : true,
- /**
- * @event beforenodedrop
- * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
- * passed to handlers has the following properties:<br />
- * <ul style="padding:5px;padding-left:16px;">
- * <li>tree - The TreePanel</li>
- * <li>target - The node being targeted for the drop</li>
- * <li>data - The drag data from the drag source</li>
- * <li>point - The point of the drop - append, above or below</li>
- * <li>source - The drag source</li>
- * <li>rawEvent - Raw mouse event</li>
- * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
- * to be inserted by setting them on this object.</li>
- * <li>cancel - Set this to true to cancel the drop.</li>
- * </ul>
- * @param {Object} dropEvent
- */
- "beforenodedrop" : true,
- /**
- * @event nodedrop
- * Fires after a DD object is dropped on a node in this tree. The dropEvent
- * passed to handlers has the following properties:<br />
- * <ul style="padding:5px;padding-left:16px;">
- * <li>tree - The TreePanel</li>
- * <li>target - The node being targeted for the drop</li>
- * <li>data - The drag data from the drag source</li>
- * <li>point - The point of the drop - append, above or below</li>
- * <li>source - The drag source</li>
- * <li>rawEvent - Raw mouse event</li>
- * <li>dropNode - Dropped node(s).</li>
- * </ul>
- * @param {Object} dropEvent
- */
- "nodedrop" : true,
- /**
- * @event nodedragover
- * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
- * passed to handlers has the following properties:<br />
- * <ul style="padding:5px;padding-left:16px;">
- * <li>tree - The TreePanel</li>
- * <li>target - The node being targeted for the drop</li>
- * <li>data - The drag data from the drag source</li>
- * <li>point - The point of the drop - append, above or below</li>
- * <li>source - The drag source</li>
- * <li>rawEvent - Raw mouse event</li>
- * <li>dropNode - Drop node(s) provided by the source.</li>
- * <li>cancel - Set this to true to signal drop not allowed.</li>
- * </ul>
- * @param {Object} dragOverEvent
- */
- "nodedragover" : true,
- /**
- * @event appendnode
- * Fires when append node to the tree
- * @param {Roo.tree.TreePanel} this
- * @param {Roo.tree.TreeNode} node
- * @param {Number} index The index of the newly appended node
- */
- "appendnode" : true
-
+ * @event beforenodeedit
+ * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
+ * false from the handler of this event.
+ * @param {Editor} this
+ * @param {Roo.tree.Node} node
+ */
+ "beforenodeedit" : true
});
- if(this.singleExpand){
- this.on("beforeexpand", this.restrictExpand, this);
- }
- if (this.editor) {
- this.editor.tree = this;
- this.editor = Roo.factory(this.editor, Roo.tree);
- }
-
- if (this.selModel) {
- this.selModel = Roo.factory(this.selModel, Roo.tree);
- }
-
-};
-Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
- rootVisible : true,
- animate: Roo.enableFx,
- lines : true,
- enableDD : false,
- hlDrop : Roo.enableFx,
-
- renderer: false,
- rendererTip: false,
- // private
- restrictExpand : function(node){
- var p = node.parentNode;
- if(p){
- if(p.expandedChild && p.expandedChild.parentNode == p){
- p.expandedChild.collapse();
- }
- p.expandedChild = node;
- }
- },
+ //Roo.log(config);
+ Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
- // private override
- setRootNode : function(node){
- Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
- if(!this.rootVisible){
- node.ui = new Roo.tree.RootTreeNodeUI(node);
- }
- return node;
- },
+ this.tree = tree;
- /**
- * Returns the container element for this TreePanel
- */
- getEl : function(){
- return this.el;
- },
+ tree.on('beforeclick', this.beforeNodeClick, this);
+ tree.getTreeEl().on('mousedown', this.hide, this);
+ this.on('complete', this.updateNode, this);
+ this.on('beforestartedit', this.fitToTree, this);
+ this.on('startedit', this.bindScroll, this, {delay:10});
+ this.on('specialkey', this.onSpecialKey, this);
+};
+Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
/**
- * Returns the default TreeLoader for this TreePanel
+ * @cfg {String} alignment
+ * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
*/
- getLoader : function(){
- return this.loader;
- },
-
+ alignment: "l-l",
+ // inherit
+ autoSize: false,
/**
- * Expand all nodes
+ * @cfg {Boolean} hideEl
+ * True to hide the bound element while the editor is displayed (defaults to false)
*/
- expandAll : function(){
- this.root.expand(true);
- },
-
+ hideEl : false,
/**
- * Collapse all nodes
+ * @cfg {String} cls
+ * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
*/
- collapseAll : function(){
- this.root.collapse(true);
- },
-
+ cls: "x-small-editor x-tree-editor",
/**
- * Returns the selection model used by this TreePanel
+ * @cfg {Boolean} shim
+ * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
*/
- getSelectionModel : function(){
- if(!this.selModel){
- this.selModel = new Roo.tree.DefaultSelectionModel();
- }
- return this.selModel;
- },
-
+ shim:false,
+ // inherit
+ shadow:"frame",
/**
- * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
- * @param {String} attribute (optional) Defaults to null (return the actual nodes)
- * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
- * @return {Array}
+ * @cfg {Number} maxWidth
+ * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed
+ * the containing tree element's size, it will be automatically limited for you to the container width, taking
+ * scroll and client offsets into account prior to each edit.
*/
- getChecked : function(a, startNode){
- startNode = startNode || this.root;
- var r = [];
- var f = function(){
- if(this.attributes.checked){
- r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
- }
- }
- startNode.cascade(f);
- return r;
- },
+ maxWidth: 250,
- /**
- * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
- * @param {String} path
- * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
- * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
- * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
- */
- expandPath : function(path, attr, callback){
- attr = attr || "id";
- var keys = path.split(this.pathSeparator);
- var curNode = this.root;
- if(curNode.attributes[attr] != keys[1]){ // invalid root
- if(callback){
- callback(false, null);
- }
- return;
- }
- var index = 1;
- var f = function(){
- if(++index == keys.length){
- if(callback){
- callback(true, curNode);
- }
- return;
- }
- var c = curNode.findChild(attr, keys[index]);
- if(!c){
- if(callback){
- callback(false, curNode);
- }
- return;
- }
- curNode = c;
- c.expand(false, false, f);
- };
- curNode.expand(false, false, f);
- },
+ editDelay : 350,
- /**
- * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
- * @param {String} path
- * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
- * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
- * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
- */
- selectPath : function(path, attr, callback){
- attr = attr || "id";
- var keys = path.split(this.pathSeparator);
- var v = keys.pop();
- if(keys.length > 0){
- var f = function(success, node){
- if(success && node){
- var n = node.findChild(attr, v);
- if(n){
- n.select();
- if(callback){
- callback(true, n);
- }
- }else if(callback){
- callback(false, n);
- }
- }else{
- if(callback){
- callback(false, n);
- }
- }
- };
- this.expandPath(keys.join(this.pathSeparator), attr, f);
- }else{
- this.root.select();
- if(callback){
- callback(true, this.root);
- }
+ // private
+ fitToTree : function(ed, el){
+ var td = this.tree.getTreeEl().dom, nd = el.dom;
+ if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible
+ td.scrollLeft = nd.offsetLeft;
}
+ var w = Math.min(
+ this.maxWidth,
+ (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
+ this.setSize(w, '');
+
+ return this.fireEvent('beforenodeedit', this, this.editNode);
+
},
- getTreeEl : function(){
- return this.el;
+ // private
+ triggerEdit : function(node){
+ this.completeEdit();
+ this.editNode = node;
+ this.startEdit(node.ui.textNode, node.text);
},
- /**
- * Trigger rendering of this TreePanel
- */
- render : function(){
- if (this.innerCt) {
- return this; // stop it rendering more than once!!
- }
-
- this.innerCt = this.el.createChild({tag:"ul",
- cls:"x-tree-root-ct " +
- (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
-
- if(this.containerScroll){
- Roo.dd.ScrollManager.register(this.el);
- }
- if((this.enableDD || this.enableDrop) && !this.dropZone){
- /**
- * The dropZone used by this tree if drop is enabled
- * @type Roo.tree.TreeDropZone
- */
- this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
- ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
- });
- }
- if((this.enableDD || this.enableDrag) && !this.dragZone){
- /**
- * The dragZone used by this tree if drag is enabled
- * @type Roo.tree.TreeDragZone
- */
- this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
- ddGroup: this.ddGroup || "TreeDD",
- scroll: this.ddScroll
- });
+ // private
+ bindScroll : function(){
+ this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
+ },
+
+ // private
+ beforeNodeClick : function(node, e){
+ var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
+ this.lastClick = new Date();
+ if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
+ e.stopEvent();
+ this.triggerEdit(node);
+ return false;
}
- this.getSelectionModel().init(this);
- if (!this.root) {
- Roo.log("ROOT not set in tree");
- return this;
+ return true;
+ },
+
+ // private
+ updateNode : function(ed, value){
+ this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
+ this.editNode.setText(value);
+ },
+
+ // private
+ onHide : function(){
+ Roo.tree.TreeEditor.superclass.onHide.call(this);
+ if(this.editNode){
+ this.editNode.ui.focus();
}
- this.root.render();
- if(!this.rootVisible){
- this.root.renderChildren();
+ },
+
+ // private
+ onSpecialKey : function(field, e){
+ var k = e.getKey();
+ if(k == e.ESC){
+ e.stopEvent();
+ this.cancelEdit();
+ }else if(k == e.ENTER && !e.hasModifier()){
+ e.stopEvent();
+ this.completeEdit();
}
- return this;
}
-});/*
+});//<Script type="text/javascript">
+/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* <script type="text/javascript">
*/
-
/**
- * @class Roo.tree.DefaultSelectionModel
- * @extends Roo.util.Observable
- * The default single selection for a TreePanel.
- * @param {Object} cfg Configuration
+ * Not documented??? - probably should be...
*/
-Roo.tree.DefaultSelectionModel = function(cfg){
- this.selNode = null;
-
-
-
- this.addEvents({
- /**
- * @event selectionchange
- * Fires when the selected node changes
- * @param {DefaultSelectionModel} this
- * @param {TreeNode} node the new selection
- */
- "selectionchange" : true,
- /**
- * @event beforeselect
- * Fires before the selected node changes, return false to cancel the change
- * @param {DefaultSelectionModel} this
- * @param {TreeNode} node the new selection
- * @param {TreeNode} node the old selection
- */
- "beforeselect" : true
- });
-
- Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
-};
-
-Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
- init : function(tree){
- this.tree = tree;
- tree.getTreeEl().on("keydown", this.onKeyDown, this);
- tree.on("click", this.onNodeClick, this);
- },
+Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
+ //focus: Roo.emptyFn, // prevent odd scrolling behavior
- onNodeClick : function(node, e){
- if (e.ctrlKey && this.selNode == node) {
- this.unselect(node);
- return;
+ renderElements : function(n, a, targetNode, bulkRender){
+ //consel.log("renderElements?");
+ this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
+
+ var t = n.getOwnerTree();
+ var tid = Pman.Tab.Document_TypesTree.tree.el.id;
+
+ var cols = t.columns;
+ var bw = t.borderWidth;
+ var c = cols[0];
+ var href = a.href ? a.href : Roo.isGecko ? "" : "#";
+ var cb = typeof a.checked == "boolean";
+ var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
+ var colcls = 'x-t-' + tid + '-c0';
+ var buf = [
+ '<li class="x-tree-node">',
+
+
+ '<div class="x-tree-node-el ', a.cls,'">',
+ // extran...
+ '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
+
+
+ '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
+ '<img src="', this.emptyIcon, '" class="x-tree-ec-icon " />',
+ '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
+ (a.icon ? ' x-tree-node-inline-icon' : ''),
+ (a.iconCls ? ' '+a.iconCls : ''),
+ '" unselectable="on" />',
+ (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' +
+ (a.checked ? 'checked="checked" />' : ' />')) : ''),
+
+ '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
+ (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
+ '<span unselectable="on" qtip="' + tx + '">',
+ tx,
+ '</span></a>' ,
+ '</div>',
+ '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
+ (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
+ ];
+ for(var i = 1, len = cols.length; i < len; i++){
+ c = cols[i];
+ colcls = 'x-t-' + tid + '-c' +i;
+ tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
+ buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
+ '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
+ "</div>");
+ }
+
+ buf.push(
+ '</a>',
+ '<div class="x-clear"></div></div>',
+ '<ul class="x-tree-node-ct" style="display:none;"></ul>',
+ "</li>");
+
+ if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
+ this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
+ n.nextSibling.ui.getEl(), buf.join(""));
+ }else{
+ this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
}
- this.select(node);
- },
-
- /**
- * Select a node.
- * @param {TreeNode} node The node to select
- * @return {TreeNode} The selected node
- */
- select : function(node){
- var last = this.selNode;
- if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
- if(last){
- last.ui.onSelectedChange(false);
- }
- this.selNode = node;
- node.ui.onSelectedChange(true);
- this.fireEvent("selectionchange", this, node, last);
+ var el = this.wrap.firstChild;
+ this.elRow = el;
+ this.elNode = el.firstChild;
+ this.ranchor = el.childNodes[1];
+ this.ctNode = this.wrap.childNodes[1];
+ var cs = el.firstChild.childNodes;
+ this.indentNode = cs[0];
+ this.ecNode = cs[1];
+ this.iconNode = cs[2];
+ var index = 3;
+ if(cb){
+ this.checkbox = cs[3];
+ index++;
}
- return node;
+ this.anchor = cs[index];
+
+ this.textNode = cs[index].firstChild;
+
+ //el.on("click", this.onClick, this);
+ //el.on("dblclick", this.onDblClick, this);
+
+
+ // console.log(this);
},
-
- /**
- * Deselect a node.
- * @param {TreeNode} node The node to unselect
- */
- unselect : function(node){
- if(this.selNode == node){
- this.clearSelections();
- }
+ initEvents : function(){
+ Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
+
+
+ var a = this.ranchor;
+
+ var el = Roo.get(a);
+
+ if(Roo.isOpera){ // opera render bug ignores the CSS
+ el.setStyle("text-decoration", "none");
+ }
+
+ el.on("click", this.onClick, this);
+ el.on("dblclick", this.onDblClick, this);
+ el.on("contextmenu", this.onContextMenu, this);
+
},
- /**
- * Clear all selections
- */
- clearSelections : function(){
- var n = this.selNode;
- if(n){
- n.ui.onSelectedChange(false);
- this.selNode = null;
- this.fireEvent("selectionchange", this, null);
+ /*onSelectedChange : function(state){
+ if(state){
+ this.focus();
+ this.addClass("x-tree-selected");
+ }else{
+ //this.blur();
+ this.removeClass("x-tree-selected");
}
- return n;
+ },*/
+ addClass : function(cls){
+ if(this.elRow){
+ Roo.fly(this.elRow).addClass(cls);
+ }
+
},
- /**
- * Get the selected node
- * @return {TreeNode} The selected node
- */
- getSelectedNode : function(){
- return this.selNode;
- },
- /**
- * Returns true if the node is selected
- * @param {TreeNode} node The node to check
- * @return {Boolean}
- */
- isSelected : function(node){
- return this.selNode == node;
- },
-
- /**
- * Selects the node above the selected node in the tree, intelligently walking the nodes
- * @return TreeNode The new selection
- */
- selectPrevious : function(){
- var s = this.selNode || this.lastSelNode;
- if(!s){
- return null;
- }
- var ps = s.previousSibling;
- if(ps){
- if(!ps.isExpanded() || ps.childNodes.length < 1){
- return this.select(ps);
- } else{
- var lc = ps.lastChild;
- while(lc && lc.isExpanded() && lc.childNodes.length > 0){
- lc = lc.lastChild;
- }
- return this.select(lc);
- }
- } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
- return this.select(s.parentNode);
+ removeClass : function(cls){
+ if(this.elRow){
+ Roo.fly(this.elRow).removeClass(cls);
}
- return null;
- },
+ }
- /**
- * Selects the node above the selected node in the tree, intelligently walking the nodes
- * @return TreeNode The new selection
- */
- selectNext : function(){
- var s = this.selNode || this.lastSelNode;
- if(!s){
- return null;
- }
- if(s.firstChild && s.isExpanded()){
- return this.select(s.firstChild);
- }else if(s.nextSibling){
- return this.select(s.nextSibling);
- }else if(s.parentNode){
- var newS = null;
- s.parentNode.bubble(function(){
- if(this.nextSibling){
- newS = this.getOwnerTree().selModel.select(this.nextSibling);
- return false;
- }
- });
- return newS;
- }
- return null;
- },
+
+
+});//<Script type="text/javascript">
- onKeyDown : function(e){
- var s = this.selNode || this.lastSelNode;
- // undesirable, but required
- var sm = this;
- if(!s){
- return;
- }
- var k = e.getKey();
- switch(k){
- case e.DOWN:
- e.stopEvent();
- this.selectNext();
- break;
- case e.UP:
- e.stopEvent();
- this.selectPrevious();
- break;
- case e.RIGHT:
- e.preventDefault();
- if(s.hasChildNodes()){
- if(!s.isExpanded()){
- s.expand();
- }else if(s.firstChild){
- this.select(s.firstChild, e);
- }
- }
- break;
- case e.LEFT:
- e.preventDefault();
- if(s.hasChildNodes() && s.isExpanded()){
- s.collapse();
- }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
- this.select(s.parentNode, e);
- }
- break;
- };
- }
-});
+/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
/**
- * @class Roo.tree.MultiSelectionModel
- * @extends Roo.util.Observable
- * Multi selection for a TreePanel.
- * @param {Object} cfg Configuration
+ * @class Roo.tree.ColumnTree
+ * @extends Roo.tree.TreePanel
+ * @cfg {Object} columns Including width, header, renderer, cls, dataIndex
+ * @cfg {int} borderWidth compined right/left border allowance
+ * @constructor
+ * @param {String/HTMLElement/Element} el The container element
+ * @param {Object} config
*/
-Roo.tree.MultiSelectionModel = function(){
- this.selNodes = [];
- this.selMap = {};
+Roo.tree.ColumnTree = function(el, config)
+{
+ Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
this.addEvents({
- /**
- * @event selectionchange
- * Fires when the selected nodes change
- * @param {MultiSelectionModel} this
- * @param {Array} nodes Array of the selected nodes
+ /**
+ * @event resize
+ * Fire this event on a container when it resizes
+ * @param {int} w Width
+ * @param {int} h Height
*/
- "selectionchange" : true
- });
- Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
-
+ "resize" : true
+ });
+ this.on('resize', this.onResize, this);
};
-Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
- init : function(tree){
- this.tree = tree;
- tree.getTreeEl().on("keydown", this.onKeyDown, this);
- tree.on("click", this.onNodeClick, this);
- },
+Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
+ //lines:false,
- onNodeClick : function(node, e){
- this.select(node, e, e.ctrlKey);
- },
- /**
- * Select a node.
- * @param {TreeNode} node The node to select
- * @param {EventObject} e (optional) An event associated with the selection
- * @param {Boolean} keepExisting True to retain existing selections
- * @return {TreeNode} The selected node
- */
- select : function(node, e, keepExisting){
- if(keepExisting !== true){
- this.clearSelections(true);
- }
- if(this.isSelected(node)){
- this.lastSelNode = node;
- return node;
- }
- this.selNodes.push(node);
- this.selMap[node.id] = node;
- this.lastSelNode = node;
- node.ui.onSelectedChange(true);
- this.fireEvent("selectionchange", this, this.selNodes);
- return node;
- },
+ borderWidth: Roo.isBorderBox ? 0 : 2,
+ headEls : false,
- /**
- * Deselect a node.
- * @param {TreeNode} node The node to unselect
- */
- unselect : function(node){
- if(this.selMap[node.id]){
- node.ui.onSelectedChange(false);
- var sn = this.selNodes;
- var index = -1;
- if(sn.indexOf){
- index = sn.indexOf(node);
- }else{
- for(var i = 0, len = sn.length; i < len; i++){
- if(sn[i] == node){
- index = i;
- break;
- }
- }
- }
- if(index != -1){
- this.selNodes.splice(index, 1);
- }
- delete this.selMap[node.id];
- this.fireEvent("selectionchange", this, this.selNodes);
+ render : function(){
+ // add the header.....
+
+ Roo.tree.ColumnTree.superclass.render.apply(this);
+
+ this.el.addClass('x-column-tree');
+
+ this.headers = this.el.createChild(
+ {cls:'x-tree-headers'},this.innerCt.dom);
+
+ var cols = this.columns, c;
+ var totalWidth = 0;
+ this.headEls = [];
+ var len = cols.length;
+ for(var i = 0; i < len; i++){
+ c = cols[i];
+ totalWidth += c.width;
+ this.headEls.push(this.headers.createChild({
+ cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
+ cn: {
+ cls:'x-tree-hd-text',
+ html: c.header
+ },
+ style:'width:'+(c.width-this.borderWidth)+'px;'
+ }));
}
+ this.headers.createChild({cls:'x-clear'});
+ // prevent floats from wrapping when clipped
+ this.headers.setWidth(totalWidth);
+ //this.innerCt.setWidth(totalWidth);
+ this.innerCt.setStyle({ overflow: 'auto' });
+ this.onResize(this.width, this.height);
+
+
},
-
- /**
- * Clear all selections
- */
- clearSelections : function(suppressEvent){
- var sn = this.selNodes;
- if(sn.length > 0){
- for(var i = 0, len = sn.length; i < len; i++){
- sn[i].ui.onSelectedChange(false);
- }
- this.selNodes = [];
- this.selMap = {};
- if(suppressEvent !== true){
- this.fireEvent("selectionchange", this, this.selNodes);
+ onResize : function(w,h)
+ {
+ this.height = h;
+ this.width = w;
+ // resize cols..
+ this.innerCt.setWidth(this.width);
+ this.innerCt.setHeight(this.height-20);
+
+ // headers...
+ var cols = this.columns, c;
+ var totalWidth = 0;
+ var expEl = false;
+ var len = cols.length;
+ for(var i = 0; i < len; i++){
+ c = cols[i];
+ if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
+ // it's the expander..
+ expEl = this.headEls[i];
+ continue;
}
+ totalWidth += c.width;
+
}
- },
-
- /**
- * Returns true if the node is selected
- * @param {TreeNode} node The node to check
- * @return {Boolean}
- */
- isSelected : function(node){
- return this.selMap[node.id] ? true : false;
- },
-
- /**
- * Returns an array of the selected nodes
- * @return {Array}
- */
- getSelectedNodes : function(){
- return this.selNodes;
- },
-
- onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
-
- selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
+ if (expEl) {
+ expEl.setWidth( ((w - totalWidth)-this.borderWidth - 20));
+ }
+ this.headers.setWidth(w-20);
- selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
-});/*
+
+
+
+ }
+});
+/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
*/
/**
- * @class Roo.tree.TreeNode
- * @extends Roo.data.Node
- * @cfg {String} text The text for this node
- * @cfg {Boolean} expanded true to start the node expanded
- * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
- * @cfg {Boolean} allowDrop false if this node cannot be drop on
- * @cfg {Boolean} disabled true to start the node disabled
- * @cfg {String} icon The path to an icon for the node. The preferred way to do this
- * is to use the cls or iconCls attributes and add the icon via a CSS background image.
- * @cfg {String} cls A css class to be added to the node
- * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
- * @cfg {String} href URL of the link used for the node (defaults to #)
- * @cfg {String} hrefTarget target frame for the link
- * @cfg {String} qtip An Ext QuickTip for the node
- * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
- * @cfg {Boolean} singleClickExpand True for single click expand on this node
- * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
- * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
- * (defaults to undefined with no checkbox rendered)
+ * @class Roo.menu.Menu
+ * @extends Roo.util.Observable
+ * @children Roo.menu.Item Roo.menu.Separator Roo.menu.TextItem
+ * A menu object. This is the container to which you add all other menu items. Menu can also serve a as a base class
+ * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
* @constructor
- * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
+ * Creates a new Menu
+ * @param {Object} config Configuration options
*/
-Roo.tree.TreeNode = function(attributes){
- attributes = attributes || {};
- if(typeof attributes == "string"){
- attributes = {text: attributes};
- }
- this.childrenRendered = false;
- this.rendered = false;
- Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
- this.expanded = attributes.expanded === true;
- this.isTarget = attributes.isTarget !== false;
- this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
- this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
-
- /**
- * Read-only. The text for this node. To change it use setText().
- * @type String
- */
- this.text = attributes.text;
- /**
- * True if this node is disabled.
- * @type Boolean
- */
- this.disabled = attributes.disabled === true;
-
+Roo.menu.Menu = function(config){
+
+ Roo.menu.Menu.superclass.constructor.call(this, config);
+
+ this.id = this.id || Roo.id();
this.addEvents({
/**
- * @event textchange
- * Fires when the text for this node is changed
- * @param {Node} this This node
- * @param {String} text The new text
- * @param {String} oldText The old text
- */
- "textchange" : true,
- /**
- * @event beforeexpand
- * Fires before this node is expanded, return false to cancel.
- * @param {Node} this This node
- * @param {Boolean} deep
- * @param {Boolean} anim
- */
- "beforeexpand" : true,
- /**
- * @event beforecollapse
- * Fires before this node is collapsed, return false to cancel.
- * @param {Node} this This node
- * @param {Boolean} deep
- * @param {Boolean} anim
- */
- "beforecollapse" : true,
- /**
- * @event expand
- * Fires when this node is expanded
- * @param {Node} this This node
- */
- "expand" : true,
- /**
- * @event disabledchange
- * Fires when the disabled status of this node changes
- * @param {Node} this This node
- * @param {Boolean} disabled
- */
- "disabledchange" : true,
+ * @event beforeshow
+ * Fires before this menu is displayed
+ * @param {Roo.menu.Menu} this
+ */
+ beforeshow : true,
/**
- * @event collapse
- * Fires when this node is collapsed
- * @param {Node} this This node
- */
- "collapse" : true,
+ * @event beforehide
+ * Fires before this menu is hidden
+ * @param {Roo.menu.Menu} this
+ */
+ beforehide : true,
/**
- * @event beforeclick
- * Fires before click processing. Return false to cancel the default action.
- * @param {Node} this This node
- * @param {Roo.EventObject} e The event object
- */
- "beforeclick":true,
+ * @event show
+ * Fires after this menu is displayed
+ * @param {Roo.menu.Menu} this
+ */
+ show : true,
/**
- * @event checkchange
- * Fires when a node with a checkbox's checked property changes
- * @param {Node} this This node
- * @param {Boolean} checked
- */
- "checkchange":true,
+ * @event hide
+ * Fires after this menu is hidden
+ * @param {Roo.menu.Menu} this
+ */
+ hide : true,
/**
- * @event click
- * Fires when this node is clicked
- * @param {Node} this This node
- * @param {Roo.EventObject} e The event object
- */
- "click":true,
+ * @event click
+ * Fires when this menu is clicked (or when the enter key is pressed while it is active)
+ * @param {Roo.menu.Menu} this
+ * @param {Roo.menu.Item} menuItem The menu item that was clicked
+ * @param {Roo.EventObject} e
+ */
+ click : true,
/**
- * @event dblclick
- * Fires when this node is double clicked
- * @param {Node} this This node
- * @param {Roo.EventObject} e The event object
- */
- "dblclick":true,
+ * @event mouseover
+ * Fires when the mouse is hovering over this menu
+ * @param {Roo.menu.Menu} this
+ * @param {Roo.EventObject} e
+ * @param {Roo.menu.Item} menuItem The menu item that was clicked
+ */
+ mouseover : true,
/**
- * @event contextmenu
- * Fires when this node is right clicked
- * @param {Node} this This node
- * @param {Roo.EventObject} e The event object
- */
- "contextmenu":true,
+ * @event mouseout
+ * Fires when the mouse exits this menu
+ * @param {Roo.menu.Menu} this
+ * @param {Roo.EventObject} e
+ * @param {Roo.menu.Item} menuItem The menu item that was clicked
+ */
+ mouseout : true,
/**
- * @event beforechildrenrendered
- * Fires right before the child nodes for this node are rendered
- * @param {Node} this This node
- */
- "beforechildrenrendered":true
+ * @event itemclick
+ * Fires when a menu item contained in this menu is clicked
+ * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
+ * @param {Roo.EventObject} e
+ */
+ itemclick: true
});
-
- var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
-
- /**
- * Read-only. The UI for this node
- * @type TreeNodeUI
- */
- this.ui = new uiClass(this);
-
- // finally support items[]
- if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
- return;
+ if (this.registerMenu) {
+ Roo.menu.MenuMgr.register(this);
}
-
- Roo.each(this.attributes.items, function(c) {
- this.appendChild(Roo.factory(c,Roo.Tree));
- }, this);
- delete this.attributes.items;
-
-
-
+ var mis = this.items;
+ this.items = new Roo.util.MixedCollection();
+ if(mis){
+ this.add.apply(this, mis);
+ }
};
-Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
- preventHScroll: true,
- /**
- * Returns true if this node is expanded
- * @return {Boolean}
- */
- isExpanded : function(){
- return this.expanded;
- },
+Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
/**
- * Returns the UI object for this node
- * @return {TreeNodeUI}
+ * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
*/
- getUI : function(){
- return this.ui;
- },
-
- // private override
- setFirstChild : function(node){
- var of = this.firstChild;
- Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
- if(this.childrenRendered && of && node != of){
- of.renderIndent(true, true);
- }
- if(this.rendered){
- this.renderIndent(true, true);
- }
- },
-
- // private override
- setLastChild : function(node){
- var ol = this.lastChild;
- Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
- if(this.childrenRendered && ol && node != ol){
- ol.renderIndent(true, true);
- }
- if(this.rendered){
- this.renderIndent(true, true);
- }
- },
-
- // these methods are overridden to provide lazy rendering support
- // private override
- appendChild : function()
- {
- var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
- if(node && this.childrenRendered){
- node.render();
- }
- this.ui.updateExpandIcon();
- return node;
- },
-
- // private override
- removeChild : function(node){
- this.ownerTree.getSelectionModel().unselect(node);
- Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
- // if it's been rendered remove dom node
- if(this.childrenRendered){
- node.ui.remove();
- }
- if(this.childNodes.length < 1){
- this.collapse(false, false);
- }else{
- this.ui.updateExpandIcon();
- }
- if(!this.firstChild) {
- this.childrenRendered = false;
- }
- return node;
- },
-
- // private override
- insertBefore : function(node, refNode){
- var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
- if(newNode && refNode && this.childrenRendered){
- node.render();
- }
- this.ui.updateExpandIcon();
- return newNode;
- },
-
+ minWidth : 120,
/**
- * Sets the text for this node
- * @param {String} text
+ * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
+ * for bottom-right shadow (defaults to "sides")
*/
- setText : function(text){
- var oldText = this.text;
- this.text = text;
- this.attributes.text = text;
- if(this.rendered){ // event without subscribing
- this.ui.onTextChange(this, text, oldText);
- }
- this.fireEvent("textchange", this, text, oldText);
- },
-
+ shadow : "sides",
/**
- * Triggers selection of this node
+ * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
+ * this menu (defaults to "tl-tr?")
*/
- select : function(){
- this.getOwnerTree().getSelectionModel().select(this);
- },
-
+ subMenuAlign : "tl-tr?",
/**
- * Triggers deselection of this node
+ * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
+ * relative to its element of origin (defaults to "tl-bl?")
*/
- unselect : function(){
- this.getOwnerTree().getSelectionModel().unselect(this);
- },
-
+ defaultAlign : "tl-bl?",
/**
- * Returns true if this node is selected
- * @return {Boolean}
+ * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
*/
- isSelected : function(){
- return this.getOwnerTree().getSelectionModel().isSelected(this);
- },
-
+ allowOtherMenus : false,
/**
- * Expand this node.
- * @param {Boolean} deep (optional) True to expand all children as well
- * @param {Boolean} anim (optional) false to cancel the default animation
- * @param {Function} callback (optional) A callback to be called when
- * expanding this node completes (does not wait for deep expand to complete).
- * Called with 1 parameter, this node.
+ * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
*/
- expand : function(deep, anim, callback){
- if(!this.expanded){
- if(this.fireEvent("beforeexpand", this, deep, anim) === false){
- return;
- }
- if(!this.childrenRendered){
- this.renderChildren();
- }
- this.expanded = true;
-
- if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
- this.ui.animExpand(function(){
- this.fireEvent("expand", this);
- if(typeof callback == "function"){
- callback(this);
- }
- if(deep === true){
- this.expandChildNodes(true);
- }
- }.createDelegate(this));
- return;
- }else{
- this.ui.expand();
- this.fireEvent("expand", this);
- if(typeof callback == "function"){
- callback(this);
- }
- }
- }else{
- if(typeof callback == "function"){
- callback(this);
- }
- }
- if(deep === true){
- this.expandChildNodes(true);
- }
- },
-
- isHiddenRoot : function(){
- return this.isRoot && !this.getOwnerTree().rootVisible;
- },
+ registerMenu : true,
- /**
- * Collapse this node.
- * @param {Boolean} deep (optional) True to collapse all children as well
- * @param {Boolean} anim (optional) false to cancel the default animation
- */
- collapse : function(deep, anim){
- if(this.expanded && !this.isHiddenRoot()){
- if(this.fireEvent("beforecollapse", this, deep, anim) === false){
- return;
- }
- this.expanded = false;
- if((this.getOwnerTree().animate && anim !== false) || anim){
- this.ui.animCollapse(function(){
- this.fireEvent("collapse", this);
- if(deep === true){
- this.collapseChildNodes(true);
- }
- }.createDelegate(this));
- return;
- }else{
- this.ui.collapse();
- this.fireEvent("collapse", this);
- }
- }
- if(deep === true){
- var cs = this.childNodes;
- for(var i = 0, len = cs.length; i < len; i++) {
- cs[i].collapse(true, false);
- }
- }
- },
+ hidden:true,
// private
- delayedExpand : function(delay){
- if(!this.expandProcId){
- this.expandProcId = this.expand.defer(delay, this);
+ render : function(){
+ if(this.el){
+ return;
}
- },
+ var el = this.el = new Roo.Layer({
+ cls: "x-menu",
+ shadow:this.shadow,
+ constrain: false,
+ parentEl: this.parentEl || document.body,
+ zindex:15000
+ });
- // private
- cancelExpand : function(){
- if(this.expandProcId){
- clearTimeout(this.expandProcId);
- }
- this.expandProcId = false;
- },
+ this.keyNav = new Roo.menu.MenuNav(this);
- /**
- * Toggles expanded/collapsed state of the node
- */
- toggle : function(){
- if(this.expanded){
- this.collapse();
- }else{
- this.expand();
+ if(this.plain){
+ el.addClass("x-menu-plain");
}
+ if(this.cls){
+ el.addClass(this.cls);
+ }
+ // generic focus element
+ this.focusEl = el.createChild({
+ tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
+ });
+ var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
+ //disabling touch- as it's causing issues ..
+ //ul.on(Roo.isTouch ? 'touchstart' : 'click' , this.onClick, this);
+ ul.on('click' , this.onClick, this);
+
+
+ ul.on("mouseover", this.onMouseOver, this);
+ ul.on("mouseout", this.onMouseOut, this);
+ this.items.each(function(item){
+ if (item.hidden) {
+ return;
+ }
+
+ var li = document.createElement("li");
+ li.className = "x-menu-list-item";
+ ul.dom.appendChild(li);
+ item.render(li, this);
+ }, this);
+ this.ul = ul;
+ this.autoWidth();
},
- /**
- * Ensures all parent nodes are expanded
- */
- ensureVisible : function(callback){
- var tree = this.getOwnerTree();
- tree.expandPath(this.parentNode.getPath(), false, function(){
- tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
- Roo.callback(callback);
- }.createDelegate(this));
- },
-
- /**
- * Expand all child nodes
- * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
- */
- expandChildNodes : function(deep){
- var cs = this.childNodes;
- for(var i = 0, len = cs.length; i < len; i++) {
- cs[i].expand(deep);
+ // private
+ autoWidth : function(){
+ var el = this.el, ul = this.ul;
+ if(!el){
+ return;
}
- },
-
- /**
- * Collapse all child nodes
- * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
- */
- collapseChildNodes : function(deep){
- var cs = this.childNodes;
- for(var i = 0, len = cs.length; i < len; i++) {
- cs[i].collapse(deep);
+ var w = this.width;
+ if(w){
+ el.setWidth(w);
+ }else if(Roo.isIE){
+ el.setWidth(this.minWidth);
+ var t = el.dom.offsetWidth; // force recalc
+ el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
}
},
- /**
- * Disables this node
- */
- disable : function(){
- this.disabled = true;
- this.unselect();
- if(this.rendered && this.ui.onDisableChange){ // event without subscribing
- this.ui.onDisableChange(this, true);
+ // private
+ delayAutoWidth : function(){
+ if(this.rendered){
+ if(!this.awTask){
+ this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
+ }
+ this.awTask.delay(20);
}
- this.fireEvent("disabledchange", this, true);
},
- /**
- * Enables this node
- */
- enable : function(){
- this.disabled = false;
- if(this.rendered && this.ui.onDisableChange){ // event without subscribing
- this.ui.onDisableChange(this, false);
+ // private
+ findTargetItem : function(e){
+ var t = e.getTarget(".x-menu-list-item", this.ul, true);
+ if(t && t.menuItemId){
+ return this.items.get(t.menuItemId);
}
- this.fireEvent("disabledchange", this, false);
},
// private
- renderChildren : function(suppressEvent){
- if(suppressEvent !== false){
- this.fireEvent("beforechildrenrendered", this);
+ onClick : function(e){
+ Roo.log("menu.onClick");
+ var t = this.findTargetItem(e);
+ if(!t){
+ return;
}
- var cs = this.childNodes;
- for(var i = 0, len = cs.length; i < len; i++){
- cs[i].render(true);
+ Roo.log(e);
+ if (Roo.isTouch && e.type == 'touchstart' && t.menu && !t.disabled) {
+ if(t == this.activeItem && t.shouldDeactivate(e)){
+ this.activeItem.deactivate();
+ delete this.activeItem;
+ return;
+ }
+ if(t.canActivate){
+ this.setActiveItem(t, true);
+ }
+ return;
+
+
}
- this.childrenRendered = true;
+
+ t.onClick(e);
+ this.fireEvent("click", this, t, e);
},
// private
- sort : function(fn, scope){
- Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
- if(this.childrenRendered){
- var cs = this.childNodes;
- for(var i = 0, len = cs.length; i < len; i++){
- cs[i].render(true);
+ setActiveItem : function(item, autoExpand){
+ if(item != this.activeItem){
+ if(this.activeItem){
+ this.activeItem.deactivate();
}
+ this.activeItem = item;
+ item.activate(autoExpand);
+ }else if(autoExpand){
+ item.expandMenu();
}
},
// private
- render : function(bulkRender){
- this.ui.render(bulkRender);
- if(!this.rendered){
- this.rendered = true;
- if(this.expanded){
- this.expanded = false;
- this.expand(false, false);
+ tryActivate : function(start, step){
+ var items = this.items;
+ for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
+ var item = items.get(i);
+ if(!item.disabled && item.canActivate){
+ this.setActiveItem(item, false);
+ return item;
}
}
+ return false;
},
// private
- renderIndent : function(deep, refresh){
- if(refresh){
- this.ui.childIndent = null;
- }
- this.ui.renderIndent();
- if(deep === true && this.childrenRendered){
- var cs = this.childNodes;
- for(var i = 0, len = cs.length; i < len; i++){
- cs[i].renderIndent(true, refresh);
+ onMouseOver : function(e){
+ var t;
+ if(t = this.findTargetItem(e)){
+ if(t.canActivate && !t.disabled){
+ this.setActiveItem(t, true);
}
}
- }
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-/**
- * @class Roo.tree.AsyncTreeNode
- * @extends Roo.tree.TreeNode
- * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
- * @constructor
- * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
- */
- Roo.tree.AsyncTreeNode = function(config){
- this.loaded = false;
- this.loading = false;
- Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
- /**
- * @event beforeload
- * Fires before this node is loaded, return false to cancel
- * @param {Node} this This node
- */
- this.addEvents({'beforeload':true, 'load': true});
- /**
- * @event load
- * Fires when this node is loaded
- * @param {Node} this This node
- */
- /**
- * The loader used by this node (defaults to using the tree's defined loader)
- * @type TreeLoader
- * @property loader
- */
-};
-Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
- expand : function(deep, anim, callback){
- if(this.loading){ // if an async load is already running, waiting til it's done
- var timer;
- var f = function(){
- if(!this.loading){ // done loading
- clearInterval(timer);
- this.expand(deep, anim, callback);
- }
- }.createDelegate(this);
- timer = setInterval(f, 200);
- return;
- }
- if(!this.loaded){
- if(this.fireEvent("beforeload", this) === false){
- return;
- }
- this.loading = true;
- this.ui.beforeLoad(this);
- var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
- if(loader){
- loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
- return;
+ this.fireEvent("mouseover", this, e, t);
+ },
+
+ // private
+ onMouseOut : function(e){
+ var t;
+ if(t = this.findTargetItem(e)){
+ if(t == this.activeItem && t.shouldDeactivate(e)){
+ this.activeItem.deactivate();
+ delete this.activeItem;
}
}
- Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
+ this.fireEvent("mouseout", this, e, t);
},
-
+
/**
- * Returns true if this node is currently loading
- * @return {Boolean}
+ * Read-only. Returns true if the menu is currently displayed, else false.
+ * @type Boolean
*/
- isLoading : function(){
- return this.loading;
- },
-
- loadComplete : function(deep, anim, callback){
- this.loading = false;
- this.loaded = true;
- this.ui.afterLoad(this);
- this.fireEvent("load", this);
- this.expand(deep, anim, callback);
+ isVisible : function(){
+ return this.el && !this.hidden;
},
-
+
/**
- * Returns true if this node has been loaded
- * @return {Boolean}
+ * Displays this menu relative to another element
+ * @param {String/HTMLElement/Roo.Element} element The element to align to
+ * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
+ * the element (defaults to this.defaultAlign)
+ * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
*/
- isLoaded : function(){
- return this.loaded;
- },
-
- hasChildNodes : function(){
- if(!this.isLeaf() && !this.loaded){
- return true;
- }else{
- return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
+ show : function(el, pos, parentMenu){
+ this.parentMenu = parentMenu;
+ if(!this.el){
+ this.render();
}
+ this.fireEvent("beforeshow", this);
+ this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
},
/**
- * Trigger a reload for this node
- * @param {Function} callback
+ * Displays this menu at a specific xy position
+ * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
+ * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
*/
- reload : function(callback){
- this.collapse(false, false);
- while(this.firstChild){
- this.removeChild(this.firstChild);
- }
- this.childrenRendered = false;
- this.loaded = false;
- if(this.isHiddenRoot()){
- this.expanded = false;
+ showAt : function(xy, parentMenu, /* private: */_e){
+ this.parentMenu = parentMenu;
+ if(!this.el){
+ this.render();
}
- this.expand(false, false, callback);
- }
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-/**
- * @class Roo.tree.TreeNodeUI
- * @constructor
- * @param {Object} node The node to render
- * The TreeNode UI implementation is separate from the
- * tree implementation. Unless you are customizing the tree UI,
- * you should never have to use this directly.
- */
-Roo.tree.TreeNodeUI = function(node){
- this.node = node;
- this.rendered = false;
- this.animating = false;
- this.emptyIcon = Roo.BLANK_IMAGE_URL;
-};
-
-Roo.tree.TreeNodeUI.prototype = {
- removeChild : function(node){
- if(this.rendered){
- this.ctNode.removeChild(node.ui.getEl());
+ if(_e !== false){
+ this.fireEvent("beforeshow", this);
+ xy = this.el.adjustForConstraints(xy);
}
+ this.el.setXY(xy);
+ this.el.show();
+ this.hidden = false;
+ this.focus();
+ this.fireEvent("show", this);
},
- beforeLoad : function(){
- this.addClass("x-tree-node-loading");
- },
-
- afterLoad : function(){
- this.removeClass("x-tree-node-loading");
- },
-
- onTextChange : function(node, text, oldText){
- if(this.rendered){
- this.textNode.innerHTML = text;
+ focus : function(){
+ if(!this.hidden){
+ this.doFocus.defer(50, this);
}
},
- onDisableChange : function(node, state){
- this.disabled = state;
- if(state){
- this.addClass("x-tree-node-disabled");
- }else{
- this.removeClass("x-tree-node-disabled");
+ doFocus : function(){
+ if(!this.hidden){
+ this.focusEl.focus();
}
},
- onSelectedChange : function(state){
- if(state){
- this.focus();
- this.addClass("x-tree-selected");
- }else{
- //this.blur();
- this.removeClass("x-tree-selected");
+ /**
+ * Hides this menu and optionally all parent menus
+ * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
+ */
+ hide : function(deep){
+ if(this.el && this.isVisible()){
+ this.fireEvent("beforehide", this);
+ if(this.activeItem){
+ this.activeItem.deactivate();
+ this.activeItem = null;
+ }
+ this.el.hide();
+ this.hidden = true;
+ this.fireEvent("hide", this);
+ }
+ if(deep === true && this.parentMenu){
+ this.parentMenu.hide(true);
}
},
- onMove : function(tree, node, oldParent, newParent, index, refNode){
- this.childIndent = null;
- if(this.rendered){
- var targetNode = newParent.ui.getContainer();
- if(!targetNode){//target not rendered
- this.holder = document.createElement("div");
- this.holder.appendChild(this.wrap);
- return;
+ /**
+ * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
+ * Any of the following are valid:
+ * <ul>
+ * <li>Any menu item object based on {@link Roo.menu.Item}</li>
+ * <li>An HTMLElement object which will be converted to a menu item</li>
+ * <li>A menu item config object that will be created as a new menu item</li>
+ * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
+ * it will be converted into a {@link Roo.menu.TextItem} and added</li>
+ * </ul>
+ * Usage:
+ * <pre><code>
+// Create the menu
+var menu = new Roo.menu.Menu();
+
+// Create a menu item to add by reference
+var menuItem = new Roo.menu.Item({ text: 'New Item!' });
+
+// Add a bunch of items at once using different methods.
+// Only the last item added will be returned.
+var item = menu.add(
+ menuItem, // add existing item by ref
+ 'Dynamic Item', // new TextItem
+ '-', // new separator
+ { text: 'Config Item' } // new item by config
+);
+</code></pre>
+ * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
+ * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
+ */
+ add : function(){
+ var a = arguments, l = a.length, item;
+ for(var i = 0; i < l; i++){
+ var el = a[i];
+ if ((typeof(el) == "object") && el.xtype && el.xns) {
+ el = Roo.factory(el, Roo.menu);
}
- var insertBefore = refNode ? refNode.ui.getEl() : null;
- if(insertBefore){
- targetNode.insertBefore(this.wrap, insertBefore);
- }else{
- targetNode.appendChild(this.wrap);
+
+ if(el.render){ // some kind of Item
+ item = this.addItem(el);
+ }else if(typeof el == "string"){ // string
+ if(el == "separator" || el == "-"){
+ item = this.addSeparator();
+ }else{
+ item = this.addText(el);
+ }
+ }else if(el.tagName || el.el){ // element
+ item = this.addElement(el);
+ }else if(typeof el == "object"){ // must be menu item config?
+ item = this.addMenuItem(el);
}
- this.node.renderIndent(true);
- }
- },
-
- addClass : function(cls){
- if(this.elNode){
- Roo.fly(this.elNode).addClass(cls);
}
+ return item;
},
- removeClass : function(cls){
- if(this.elNode){
- Roo.fly(this.elNode).removeClass(cls);
+ /**
+ * Returns this menu's underlying {@link Roo.Element} object
+ * @return {Roo.Element} The element
+ */
+ getEl : function(){
+ if(!this.el){
+ this.render();
}
+ return this.el;
},
- remove : function(){
- if(this.rendered){
- this.holder = document.createElement("div");
- this.holder.appendChild(this.wrap);
- }
+ /**
+ * Adds a separator bar to the menu
+ * @return {Roo.menu.Item} The menu item that was added
+ */
+ addSeparator : function(){
+ return this.addItem(new Roo.menu.Separator());
},
- fireEvent : function(){
- return this.node.fireEvent.apply(this.node, arguments);
+ /**
+ * Adds an {@link Roo.Element} object to the menu
+ * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
+ * @return {Roo.menu.Item} The menu item that was added
+ */
+ addElement : function(el){
+ return this.addItem(new Roo.menu.BaseItem(el));
},
- initEvents : function(){
- this.node.on("move", this.onMove, this);
- var E = Roo.EventManager;
- var a = this.anchor;
-
- var el = Roo.fly(a, '_treeui');
-
- if(Roo.isOpera){ // opera render bug ignores the CSS
- el.setStyle("text-decoration", "none");
- }
-
- el.on("click", this.onClick, this);
- el.on("dblclick", this.onDblClick, this);
-
- if(this.checkbox){
- Roo.EventManager.on(this.checkbox,
- Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
- }
-
- el.on("contextmenu", this.onContextMenu, this);
-
- var icon = Roo.fly(this.iconNode);
- icon.on("click", this.onClick, this);
- icon.on("dblclick", this.onDblClick, this);
- icon.on("contextmenu", this.onContextMenu, this);
- E.on(this.ecNode, "click", this.ecClick, this, true);
-
- if(this.node.disabled){
- this.addClass("x-tree-node-disabled");
- }
- if(this.node.hidden){
- this.addClass("x-tree-node-disabled");
- }
- var ot = this.node.getOwnerTree();
- var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
- if(dd && (!this.node.isRoot || ot.rootVisible)){
- Roo.dd.Registry.register(this.elNode, {
- node: this.node,
- handles: this.getDDHandles(),
- isHandle: false
- });
+ /**
+ * Adds an existing object based on {@link Roo.menu.Item} to the menu
+ * @param {Roo.menu.Item} item The menu item to add
+ * @return {Roo.menu.Item} The menu item that was added
+ */
+ addItem : function(item){
+ this.items.add(item);
+ if(this.ul){
+ var li = document.createElement("li");
+ li.className = "x-menu-list-item";
+ this.ul.dom.appendChild(li);
+ item.render(li, this);
+ this.delayAutoWidth();
}
+ return item;
},
- getDDHandles : function(){
- return [this.iconNode, this.textNode];
+ /**
+ * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
+ * @param {Object} config A MenuItem config object
+ * @return {Roo.menu.Item} The menu item that was added
+ */
+ addMenuItem : function(config){
+ if(!(config instanceof Roo.menu.Item)){
+ if(typeof config.checked == "boolean"){ // must be check menu item config?
+ config = new Roo.menu.CheckItem(config);
+ }else{
+ config = new Roo.menu.Item(config);
+ }
+ }
+ return this.addItem(config);
},
- hide : function(){
- if(this.rendered){
- this.wrap.style.display = "none";
- }
+ /**
+ * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
+ * @param {String} text The text to display in the menu item
+ * @return {Roo.menu.Item} The menu item that was added
+ */
+ addText : function(text){
+ return this.addItem(new Roo.menu.TextItem({ text : text }));
},
- show : function(){
- if(this.rendered){
- this.wrap.style.display = "";
+ /**
+ * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
+ * @param {Number} index The index in the menu's list of current items where the new item should be inserted
+ * @param {Roo.menu.Item} item The menu item to add
+ * @return {Roo.menu.Item} The menu item that was added
+ */
+ insert : function(index, item){
+ this.items.insert(index, item);
+ if(this.ul){
+ var li = document.createElement("li");
+ li.className = "x-menu-list-item";
+ this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
+ item.render(li, this);
+ this.delayAutoWidth();
}
+ return item;
},
- onContextMenu : function(e){
- if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
- e.preventDefault();
- this.focus();
- this.fireEvent("contextmenu", this.node, e);
- }
+ /**
+ * Removes an {@link Roo.menu.Item} from the menu and destroys the object
+ * @param {Roo.menu.Item} item The menu item to remove
+ */
+ remove : function(item){
+ this.items.removeKey(item.id);
+ item.destroy();
},
- onClick : function(e){
- if(this.dropping){
- e.stopEvent();
- return;
+ /**
+ * Removes and destroys all items in the menu
+ */
+ removeAll : function(){
+ var f;
+ while(f = this.items.first()){
+ this.remove(f);
}
- if(this.fireEvent("beforeclick", this.node, e) !== false){
- if(!this.disabled && this.node.attributes.href){
- this.fireEvent("click", this.node, e);
- return;
- }
- e.preventDefault();
- if(this.disabled){
- return;
- }
+ }
+});
- if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
- this.node.toggle();
- }
+// MenuNav is a private utility class used internally by the Menu
+Roo.menu.MenuNav = function(menu){
+ Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
+ this.scope = this.menu = menu;
+};
- this.fireEvent("click", this.node, e);
- }else{
- e.stopEvent();
+Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
+ doRelay : function(e, h){
+ var k = e.getKey();
+ if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
+ this.menu.tryActivate(0, 1);
+ return false;
}
+ return h.call(this.scope || this, e, this.menu);
},
- onDblClick : function(e){
- e.preventDefault();
- if(this.disabled){
- return;
- }
- if(this.checkbox){
- this.toggleCheck();
- }
- if(!this.animating && this.node.hasChildNodes()){
- this.node.toggle();
+ up : function(e, m){
+ if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
+ m.tryActivate(m.items.length-1, -1);
}
- this.fireEvent("dblclick", this.node, e);
- },
-
- onCheckChange : function(){
- var checked = this.checkbox.checked;
- this.node.attributes.checked = checked;
- this.fireEvent('checkchange', this.node, checked);
},
- ecClick : function(e){
- if(!this.animating && this.node.hasChildNodes()){
- this.node.toggle();
+ down : function(e, m){
+ if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
+ m.tryActivate(0, 1);
}
},
- startDrop : function(){
- this.dropping = true;
- },
-
- // delayed drop so the click event doesn't get fired on a drop
- endDrop : function(){
- setTimeout(function(){
- this.dropping = false;
- }.createDelegate(this), 50);
- },
-
- expand : function(){
- this.updateExpandIcon();
- this.ctNode.style.display = "";
+ right : function(e, m){
+ if(m.activeItem){
+ m.activeItem.expandMenu(true);
+ }
},
- focus : function(){
- if(!this.node.preventHScroll){
- try{this.anchor.focus();
- }catch(e){}
- }else if(!Roo.isIE){
- try{
- var noscroll = this.node.getOwnerTree().getTreeEl().dom;
- var l = noscroll.scrollLeft;
- this.anchor.focus();
- noscroll.scrollLeft = l;
- }catch(e){}
+ left : function(e, m){
+ m.hide();
+ if(m.parentMenu && m.parentMenu.activeItem){
+ m.parentMenu.activeItem.activate();
}
},
- toggleCheck : function(value){
- var cb = this.checkbox;
- if(cb){
- cb.checked = (value === undefined ? !cb.checked : value);
+ enter : function(e, m){
+ if(m.activeItem){
+ e.stopPropagation();
+ m.activeItem.onClick(e);
+ m.fireEvent("click", this, m.activeItem);
+ return true;
}
- },
+ }
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.menu.MenuMgr
+ * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
+ * @static
+ */
+Roo.menu.MenuMgr = function(){
+ var menus, active, groups = {}, attached = false, lastShow = new Date();
- blur : function(){
- try{
- this.anchor.blur();
- }catch(e){}
- },
+ // private - called when first menu is created
+ function init(){
+ menus = {};
+ active = new Roo.util.MixedCollection();
+ Roo.get(document).addKeyListener(27, function(){
+ if(active.length > 0){
+ hideAll();
+ }
+ });
+ }
- animExpand : function(callback){
- var ct = Roo.get(this.ctNode);
- ct.stopFx();
- if(!this.node.hasChildNodes()){
- this.updateExpandIcon();
- this.ctNode.style.display = "";
- Roo.callback(callback);
- return;
- }
- this.animating = true;
- this.updateExpandIcon();
+ // private
+ function hideAll(){
+ if(active && active.length > 0){
+ var c = active.clone();
+ c.each(function(m){
+ m.hide();
+ });
+ }
+ }
- ct.slideIn('t', {
- callback : function(){
- this.animating = false;
- Roo.callback(callback);
- },
- scope: this,
- duration: this.node.ownerTree.duration || .25
- });
- },
+ // private
+ function onHide(m){
+ active.remove(m);
+ if(active.length < 1){
+ Roo.get(document).un("mousedown", onMouseDown);
+ attached = false;
+ }
+ }
- highlight : function(){
- var tree = this.node.getOwnerTree();
- Roo.fly(this.wrap).highlight(
- tree.hlColor || "C3DAF9",
- {endColor: tree.hlBaseColor}
- );
- },
+ // private
+ function onShow(m){
+ var last = active.last();
+ lastShow = new Date();
+ active.add(m);
+ if(!attached){
+ Roo.get(document).on("mousedown", onMouseDown);
+ attached = true;
+ }
+ if(m.parentMenu){
+ m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
+ m.parentMenu.activeChild = m;
+ }else if(last && last.isVisible()){
+ m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
+ }
+ }
- collapse : function(){
- this.updateExpandIcon();
- this.ctNode.style.display = "none";
- },
+ // private
+ function onBeforeHide(m){
+ if(m.activeChild){
+ m.activeChild.hide();
+ }
+ if(m.autoHideTimer){
+ clearTimeout(m.autoHideTimer);
+ delete m.autoHideTimer;
+ }
+ }
- animCollapse : function(callback){
- var ct = Roo.get(this.ctNode);
- ct.enableDisplayMode('block');
- ct.stopFx();
+ // private
+ function onBeforeShow(m){
+ var pm = m.parentMenu;
+ if(!pm && !m.allowOtherMenus){
+ hideAll();
+ }else if(pm && pm.activeChild && active != m){
+ pm.activeChild.hide();
+ }
+ }
- this.animating = true;
- this.updateExpandIcon();
+ // private
+ function onMouseDown(e){
+ if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
+ hideAll();
+ }
+ }
- ct.slideOut('t', {
- callback : function(){
- this.animating = false;
- Roo.callback(callback);
- },
- scope: this,
- duration: this.node.ownerTree.duration || .25
- });
- },
+ // private
+ function onBeforeCheck(mi, state){
+ if(state){
+ var g = groups[mi.group];
+ for(var i = 0, l = g.length; i < l; i++){
+ if(g[i] != mi){
+ g[i].setChecked(false);
+ }
+ }
+ }
+ }
- getContainer : function(){
- return this.ctNode;
- },
+ return {
- getEl : function(){
- return this.wrap;
- },
+ /**
+ * Hides all menus that are currently visible
+ */
+ hideAll : function(){
+ hideAll();
+ },
- appendDDGhost : function(ghostNode){
- ghostNode.appendChild(this.elNode.cloneNode(true));
- },
+ // private
+ register : function(menu){
+ if(!menus){
+ init();
+ }
+ menus[menu.id] = menu;
+ menu.on("beforehide", onBeforeHide);
+ menu.on("hide", onHide);
+ menu.on("beforeshow", onBeforeShow);
+ menu.on("show", onShow);
+ var g = menu.group;
+ if(g && menu.events["checkchange"]){
+ if(!groups[g]){
+ groups[g] = [];
+ }
+ groups[g].push(menu);
+ menu.on("checkchange", onCheck);
+ }
+ },
- getDDRepairXY : function(){
- return Roo.lib.Dom.getXY(this.iconNode);
- },
+ /**
+ * Returns a {@link Roo.menu.Menu} object
+ * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
+ * be used to generate and return a new Menu instance.
+ */
+ get : function(menu){
+ if(typeof menu == "string"){ // menu id
+ return menus[menu];
+ }else if(menu.events){ // menu instance
+ return menu;
+ }else if(typeof menu.length == 'number'){ // array of menu items?
+ return new Roo.menu.Menu({items:menu});
+ }else{ // otherwise, must be a config
+ return new Roo.menu.Menu(menu);
+ }
+ },
- onRender : function(){
- this.render();
- },
+ // private
+ unregister : function(menu){
+ delete menus[menu.id];
+ menu.un("beforehide", onBeforeHide);
+ menu.un("hide", onHide);
+ menu.un("beforeshow", onBeforeShow);
+ menu.un("show", onShow);
+ var g = menu.group;
+ if(g && menu.events["checkchange"]){
+ groups[g].remove(menu);
+ menu.un("checkchange", onCheck);
+ }
+ },
- render : function(bulkRender){
- var n = this.node, a = n.attributes;
- var targetNode = n.parentNode ?
- n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
+ // private
+ registerCheckable : function(menuItem){
+ var g = menuItem.group;
+ if(g){
+ if(!groups[g]){
+ groups[g] = [];
+ }
+ groups[g].push(menuItem);
+ menuItem.on("beforecheckchange", onBeforeCheck);
+ }
+ },
- if(!this.rendered){
- this.rendered = true;
+ // private
+ unregisterCheckable : function(menuItem){
+ var g = menuItem.group;
+ if(g){
+ groups[g].remove(menuItem);
+ menuItem.un("beforecheckchange", onBeforeCheck);
+ }
+ }
+ };
+}();/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
- this.renderElements(n, a, targetNode, bulkRender);
+/**
+ * @class Roo.menu.BaseItem
+ * @extends Roo.Component
+ * @abstract
+ * The base class for all items that render into menus. BaseItem provides default rendering, activated state
+ * management and base configuration options shared by all menu components.
+ * @constructor
+ * Creates a new BaseItem
+ * @param {Object} config Configuration options
+ */
+Roo.menu.BaseItem = function(config){
+ Roo.menu.BaseItem.superclass.constructor.call(this, config);
- if(a.qtip){
- if(this.textNode.setAttributeNS){
- this.textNode.setAttributeNS("ext", "qtip", a.qtip);
- if(a.qtipTitle){
- this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
- }
- }else{
- this.textNode.setAttribute("ext:qtip", a.qtip);
- if(a.qtipTitle){
- this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
- }
- }
- }else if(a.qtipCfg){
- a.qtipCfg.target = Roo.id(this.textNode);
- Roo.QuickTips.register(a.qtipCfg);
- }
- this.initEvents();
- if(!this.node.expanded){
- this.updateExpandIcon();
- }
- }else{
- if(bulkRender === true) {
- targetNode.appendChild(this.wrap);
- }
- }
- },
+ this.addEvents({
+ /**
+ * @event click
+ * Fires when this item is clicked
+ * @param {Roo.menu.BaseItem} this
+ * @param {Roo.EventObject} e
+ */
+ click: true,
+ /**
+ * @event activate
+ * Fires when this item is activated
+ * @param {Roo.menu.BaseItem} this
+ */
+ activate : true,
+ /**
+ * @event deactivate
+ * Fires when this item is deactivated
+ * @param {Roo.menu.BaseItem} this
+ */
+ deactivate : true
+ });
+
+ if(this.handler){
+ this.on("click", this.handler, this.scope, true);
+ }
+};
+
+Roo.extend(Roo.menu.BaseItem, Roo.Component, {
+ /**
+ * @cfg {Function} handler
+ * A function that will handle the click event of this menu item (defaults to undefined)
+ */
+ /**
+ * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
+ */
+ canActivate : false,
+
+ /**
+ * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
+ */
+ hidden: false,
+
+ /**
+ * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
+ */
+ activeClass : "x-menu-item-active",
+ /**
+ * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
+ */
+ hideOnClick : true,
+ /**
+ * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
+ */
+ hideDelay : 100,
- renderElements : function(n, a, targetNode, bulkRender)
- {
- // add some indent caching, this helps performance when rendering a large tree
- this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
- var t = n.getOwnerTree();
- var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
- if (typeof(n.attributes.html) != 'undefined') {
- txt = n.attributes.html;
- }
- var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
- var cb = typeof a.checked == 'boolean';
- var href = a.href ? a.href : Roo.isGecko ? "" : "#";
- var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
- '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
- '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
- '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
- cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
- '<a hidefocus="on" href="',href,'" tabIndex="1" ',
- a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "",
- '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
- '<ul class="x-tree-node-ct" style="display:none;"></ul>',
- "</li>"];
+ // private
+ ctype: "Roo.menu.BaseItem",
- if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
- this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
- n.nextSibling.ui.getEl(), buf.join(""));
- }else{
- this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
- }
+ // private
+ actionMode : "container",
- this.elNode = this.wrap.childNodes[0];
- this.ctNode = this.wrap.childNodes[1];
- var cs = this.elNode.childNodes;
- this.indentNode = cs[0];
- this.ecNode = cs[1];
- this.iconNode = cs[2];
- var index = 3;
- if(cb){
- this.checkbox = cs[3];
- index++;
- }
- this.anchor = cs[index];
- this.textNode = cs[index].firstChild;
+ // private
+ render : function(container, parentMenu){
+ this.parentMenu = parentMenu;
+ Roo.menu.BaseItem.superclass.render.call(this, container);
+ this.container.menuItemId = this.id;
},
- getAnchor : function(){
- return this.anchor;
+ // private
+ onRender : function(container, position){
+ this.el = Roo.get(this.el);
+ container.dom.appendChild(this.el.dom);
},
- getTextEl : function(){
- return this.textNode;
+ // private
+ onClick : function(e){
+ if(!this.disabled && this.fireEvent("click", this, e) !== false
+ && this.parentMenu.fireEvent("itemclick", this, e) !== false){
+ this.handleClick(e);
+ }else{
+ e.stopEvent();
+ }
},
- getIconEl : function(){
- return this.iconNode;
+ // private
+ activate : function(){
+ if(this.disabled){
+ return false;
+ }
+ var li = this.container;
+ li.addClass(this.activeClass);
+ this.region = li.getRegion().adjust(2, 2, -2, -2);
+ this.fireEvent("activate", this);
+ return true;
},
- isChecked : function(){
- return this.checkbox ? this.checkbox.checked : false;
+ // private
+ deactivate : function(){
+ this.container.removeClass(this.activeClass);
+ this.fireEvent("deactivate", this);
},
- updateExpandIcon : function(){
- if(this.rendered){
- var n = this.node, c1, c2;
- var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
- var hasChild = n.hasChildNodes();
- if(hasChild){
- if(n.expanded){
- cls += "-minus";
- c1 = "x-tree-node-collapsed";
- c2 = "x-tree-node-expanded";
- }else{
- cls += "-plus";
- c1 = "x-tree-node-expanded";
- c2 = "x-tree-node-collapsed";
- }
- if(this.wasLeaf){
- this.removeClass("x-tree-node-leaf");
- this.wasLeaf = false;
- }
- if(this.c1 != c1 || this.c2 != c2){
- Roo.fly(this.elNode).replaceClass(c1, c2);
- this.c1 = c1; this.c2 = c2;
- }
- }else{
- // this changes non-leafs into leafs if they have no children.
- // it's not very rational behaviour..
-
- if(!this.wasLeaf && this.node.leaf){
- Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
- delete this.c1;
- delete this.c2;
- this.wasLeaf = true;
- }
- }
- var ecc = "x-tree-ec-icon "+cls;
- if(this.ecc != ecc){
- this.ecNode.className = ecc;
- this.ecc = ecc;
- }
- }
+ // private
+ shouldDeactivate : function(e){
+ return !this.region || !this.region.contains(e.getPoint());
},
- getChildIndent : function(){
- if(!this.childIndent){
- var buf = [];
- var p = this.node;
- while(p){
- if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
- if(!p.isLast()) {
- buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
- } else {
- buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
- }
- }
- p = p.parentNode;
- }
- this.childIndent = buf.join("");
+ // private
+ handleClick : function(e){
+ if(this.hideOnClick){
+ this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
}
- return this.childIndent;
},
- renderIndent : function(){
- if(this.rendered){
- var indent = "";
- var p = this.node.parentNode;
- if(p){
- indent = p.ui.getChildIndent();
- }
- if(this.indentMarkup != indent){ // don't rerender if not required
- this.indentNode.innerHTML = indent;
- this.indentMarkup = indent;
- }
- this.updateExpandIcon();
- }
+ // private
+ expandMenu : function(autoActivate){
+ // do nothing
+ },
+
+ // private
+ hideMenu : function(){
+ // do nothing
}
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.menu.Adapter
+ * @extends Roo.menu.BaseItem
+ * @abstract
+ * 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.
+ * It provides basic rendering, activation management and enable/disable logic required to work in menus.
+ * @constructor
+ * Creates a new Adapter
+ * @param {Object} config Configuration options
+ */
+Roo.menu.Adapter = function(component, config){
+ Roo.menu.Adapter.superclass.constructor.call(this, config);
+ this.component = component;
};
+Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
+ // private
+ canActivate : true,
-Roo.tree.RootTreeNodeUI = function(){
- Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
-};
-Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
- render : function(){
- if(!this.rendered){
- var targetNode = this.node.ownerTree.innerCt.dom;
- this.node.expanded = true;
- targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
- this.wrap = this.ctNode = targetNode.firstChild;
+ // private
+ onRender : function(container, position){
+ this.component.render(container);
+ this.el = this.component.getEl();
+ },
+
+ // private
+ activate : function(){
+ if(this.disabled){
+ return false;
}
+ this.component.focus();
+ this.fireEvent("activate", this);
+ return true;
},
- collapse : function(){
+
+ // private
+ deactivate : function(){
+ this.fireEvent("deactivate", this);
},
- expand : function(){
+
+ // private
+ disable : function(){
+ this.component.disable();
+ Roo.menu.Adapter.superclass.disable.call(this);
+ },
+
+ // private
+ enable : function(){
+ this.component.enable();
+ Roo.menu.Adapter.superclass.enable.call(this);
}
});/*
* Based on:
* Fork - LGPL
* <script type="text/javascript">
*/
+
/**
- * @class Roo.tree.TreeLoader
- * @extends Roo.util.Observable
- * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
- * nodes from a specified URL. The response must be a javascript Array definition
- * who's elements are node definition objects. eg:
- * <pre><code>
-{ success : true,
- data : [
-
- { 'id': 1, 'text': 'A folder Node', 'leaf': false },
- { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
- ]
-}
+ * @class Roo.menu.TextItem
+ * @extends Roo.menu.BaseItem
+ * Adds a static text string to a menu, usually used as either a heading or group separator.
+ * Note: old style constructor with text is still supported.
+ *
+ * @constructor
+ * Creates a new TextItem
+ * @param {Object} cfg Configuration
+ */
+Roo.menu.TextItem = function(cfg){
+ if (typeof(cfg) == 'string') {
+ this.text = cfg;
+ } else {
+ Roo.apply(this,cfg);
+ }
+
+ Roo.menu.TextItem.superclass.constructor.call(this);
+};
+Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
+ /**
+ * @cfg {String} text Text to show on item.
+ */
+ text : '',
+
+ /**
+ * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
+ */
+ hideOnClick : false,
+ /**
+ * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
+ */
+ itemCls : "x-menu-text",
-</code></pre>
- * <br><br>
- * The old style respose with just an array is still supported, but not recommended.
- * <br><br>
+ // private
+ onRender : function(){
+ var s = document.createElement("span");
+ s.className = this.itemCls;
+ s.innerHTML = this.text;
+ this.el = s;
+ Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
+ }
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
*
- * A server request is sent, and child nodes are loaded only when a node is expanded.
- * The loading node's id is passed to the server under the parameter name "node" to
- * enable the server to produce the correct child nodes.
- * <br><br>
- * To pass extra parameters, an event handler may be attached to the "beforeload"
- * event, and the parameters specified in the TreeLoader's baseParams property:
- * <pre><code>
- myTreeLoader.on("beforeload", function(treeLoader, node) {
- this.baseParams.category = node.attributes.category;
- }, this);
-
-</code></pre>
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
*
- * This would pass an HTTP parameter called "category" to the server containing
- * the value of the Node's "category" attribute.
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.menu.Separator
+ * @extends Roo.menu.BaseItem
+ * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
+ * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
* @constructor
- * Creates a new Treeloader.
- * @param {Object} config A config object containing config properties.
+ * @param {Object} config Configuration options
*/
-Roo.tree.TreeLoader = function(config){
- this.baseParams = {};
- this.requestMethod = "POST";
- Roo.apply(this, config);
+Roo.menu.Separator = function(config){
+ Roo.menu.Separator.superclass.constructor.call(this, config);
+};
- this.addEvents({
-
- /**
- * @event beforeload
- * Fires before a network request is made to retrieve the Json text which specifies a node's children.
- * @param {Object} This TreeLoader object.
- * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
- * @param {Object} callback The callback function specified in the {@link #load} call.
- */
- beforeload : true,
- /**
- * @event load
- * Fires when the node has been successfuly loaded.
- * @param {Object} This TreeLoader object.
- * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
- * @param {Object} response The response object containing the data from the server.
- */
- load : true,
- /**
- * @event loadexception
- * Fires if the network request failed.
- * @param {Object} This TreeLoader object.
- * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
- * @param {Object} response The response object containing the data from the server.
- */
- loadexception : true,
- /**
- * @event create
- * Fires before a node is created, enabling you to return custom Node types
- * @param {Object} This TreeLoader object.
- * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
- */
- create : true
- });
+Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
+ /**
+ * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
+ */
+ itemCls : "x-menu-sep",
+ /**
+ * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
+ */
+ hideOnClick : false,
- Roo.tree.TreeLoader.superclass.constructor.call(this);
+ // private
+ onRender : function(li){
+ var s = document.createElement("span");
+ s.className = this.itemCls;
+ s.innerHTML = " ";
+ this.el = s;
+ li.addClass("x-menu-sep-li");
+ Roo.menu.Separator.superclass.onRender.apply(this, arguments);
+ }
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+/**
+ * @class Roo.menu.Item
+ * @extends Roo.menu.BaseItem
+ * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
+ * display items. Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
+ * activation and click handling.
+ * @constructor
+ * Creates a new Item
+ * @param {Object} config Configuration options
+ */
+Roo.menu.Item = function(config){
+ Roo.menu.Item.superclass.constructor.call(this, config);
+ if(this.menu){
+ this.menu = Roo.menu.MenuMgr.get(this.menu);
+ }
};
-
-Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
+Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
/**
- * @cfg {String} dataUrl The URL from which to request a Json string which
- * specifies an array of node definition object representing the child nodes
- * to be loaded.
- */
+ * @cfg {Roo.menu.Menu} menu
+ * A Sub menu
+ */
/**
- * @cfg {String} requestMethod either GET or POST
- * defaults to POST (due to BC)
- * to be loaded.
- */
+ * @cfg {String} text
+ * The text to show on the menu item.
+ */
+ text: '',
+ /**
+ * @cfg {String} html to render in menu
+ * The text to show on the menu item (HTML version).
+ */
+ html: '',
/**
- * @cfg {Object} baseParams (optional) An object containing properties which
- * specify HTTP parameters to be passed to each request for child nodes.
- */
+ * @cfg {String} icon
+ * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
+ */
+ icon: undefined,
/**
- * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
- * created by this loader. If the attributes sent by the server have an attribute in this object,
- * they take priority.
- */
+ * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
+ */
+ itemCls : "x-menu-item",
/**
- * @cfg {Object} uiProviders (optional) An object containing properties which
- *
- * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
- * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
- * <i>uiProvider</i> attribute of a returned child node is a string rather
- * than a reference to a TreeNodeUI implementation, this that string value
- * is used as a property name in the uiProviders object. You can define the provider named
- * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
- */
- uiProviders : {},
-
+ * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
+ */
+ canActivate : true,
/**
- * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
- * child nodes before loading.
- */
- clearOnLoad : true,
+ * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
+ */
+ showDelay: 200,
+ // doc'd in BaseItem
+ hideDelay: 200,
- /**
- * @cfg {String} root (optional) Default to false. Use this to read data from an object
- * property on loading, rather than expecting an array. (eg. more compatible to a standard
- * Grid query { data : [ .....] }
- */
-
- root : false,
- /**
- * @cfg {String} queryParam (optional)
- * Name of the query as it will be passed on the querystring (defaults to 'node')
- * eg. the request will be ?node=[id]
- */
-
-
- queryParam: false,
+ // private
+ ctype: "Roo.menu.Item",
+ // private
+ onRender : function(container, position){
+ var el = document.createElement("a");
+ el.hideFocus = true;
+ el.unselectable = "on";
+ el.href = this.href || "#";
+ if(this.hrefTarget){
+ el.target = this.hrefTarget;
+ }
+ el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : "");
+
+ var html = this.html.length ? this.html : String.format('{0}',this.text);
+
+ el.innerHTML = String.format(
+ '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
+ this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
+ this.el = el;
+ Roo.menu.Item.superclass.onRender.call(this, container, position);
+ },
+
/**
- * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
- * This is called automatically when a node is expanded, but may be used to reload
- * a node (or append new children if the {@link #clearOnLoad} option is false.)
- * @param {Roo.tree.TreeNode} node
- * @param {Function} callback
+ * Sets the text to display in this menu item
+ * @param {String} text The text to display
+ * @param {Boolean} isHTML true to indicate text is pure html.
*/
- load : function(node, callback){
- if(this.clearOnLoad){
- while(node.firstChild){
- node.removeChild(node.firstChild);
- }
+ setText : function(text, isHTML){
+ if (isHTML) {
+ this.html = text;
+ } else {
+ this.text = text;
+ this.html = '';
}
- if(node.attributes.children){ // preloaded json children
- var cs = node.attributes.children;
- for(var i = 0, len = cs.length; i < len; i++){
- node.appendChild(this.createNode(cs[i]));
- }
- if(typeof callback == "function"){
- callback();
- }
- }else if(this.dataUrl){
- this.requestData(node, callback);
+ if(this.rendered){
+ var html = this.html.length ? this.html : String.format('{0}',this.text);
+
+ this.el.update(String.format(
+ '<img src="{0}" class="x-menu-item-icon {2}">' + html,
+ this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
+ this.parentMenu.autoWidth();
}
},
- getParams: function(node){
- var buf = [], bp = this.baseParams;
- for(var key in bp){
- if(typeof bp[key] != "function"){
- buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
- }
+ // private
+ handleClick : function(e){
+ if(!this.href){ // if no link defined, stop the event automatically
+ e.stopEvent();
}
- var n = this.queryParam === false ? 'node' : this.queryParam;
- buf.push(n + "=", encodeURIComponent(node.id));
- return buf.join("");
+ Roo.menu.Item.superclass.handleClick.apply(this, arguments);
},
- requestData : function(node, callback){
- if(this.fireEvent("beforeload", this, node, callback) !== false){
- this.transId = Roo.Ajax.request({
- method:this.requestMethod,
- url: this.dataUrl||this.url,
- success: this.handleResponse,
- failure: this.handleFailure,
- scope: this,
- argument: {callback: callback, node: node},
- params: this.getParams(node)
- });
- }else{
- // if the load is cancelled, make sure we notify
- // the node that we are done
- if(typeof callback == "function"){
- callback();
+ // private
+ activate : function(autoExpand){
+ if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
+ this.focus();
+ if(autoExpand){
+ this.expandMenu();
}
}
+ return true;
},
- isLoading : function(){
- return this.transId ? true : false;
- },
-
- abort : function(){
- if(this.isLoading()){
- Roo.Ajax.abort(this.transId);
+ // private
+ shouldDeactivate : function(e){
+ if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
+ if(this.menu && this.menu.isVisible()){
+ return !this.menu.getEl().getRegion().contains(e.getPoint());
+ }
+ return true;
}
+ return false;
},
// private
- createNode : function(attr)
- {
- // apply baseAttrs, nice idea Corey!
- if(this.baseAttrs){
- Roo.applyIf(attr, this.baseAttrs);
- }
- if(this.applyLoader !== false){
- attr.loader = this;
- }
- // uiProvider = depreciated..
-
- if(typeof(attr.uiProvider) == 'string'){
- attr.uiProvider = this.uiProviders[attr.uiProvider] ||
- /** eval:var:attr */ eval(attr.uiProvider);
- }
- if(typeof(this.uiProviders['default']) != 'undefined') {
- attr.uiProvider = this.uiProviders['default'];
- }
-
- this.fireEvent('create', this, attr);
-
- attr.leaf = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
- return(attr.leaf ?
- new Roo.tree.TreeNode(attr) :
- new Roo.tree.AsyncTreeNode(attr));
+ deactivate : function(){
+ Roo.menu.Item.superclass.deactivate.apply(this, arguments);
+ this.hideMenu();
},
- processResponse : function(response, node, callback)
- {
- var json = response.responseText;
- try {
-
- var o = Roo.decode(json);
-
- if (this.root === false && typeof(o.success) != undefined) {
- this.root = 'data'; // the default behaviour for list like data..
- }
-
- if (this.root !== false && !o.success) {
- // it's a failure condition.
- var a = response.argument;
- this.fireEvent("loadexception", this, a.node, response);
- Roo.log("Load failed - should have a handler really");
- return;
- }
-
-
-
- if (this.root !== false) {
- o = o[this.root];
- }
-
- for(var i = 0, len = o.length; i < len; i++){
- var n = this.createNode(o[i]);
- if(n){
- node.appendChild(n);
- }
- }
- if(typeof callback == "function"){
- callback(this, node);
+ // private
+ expandMenu : function(autoActivate){
+ if(!this.disabled && this.menu){
+ clearTimeout(this.hideTimer);
+ delete this.hideTimer;
+ if(!this.menu.isVisible() && !this.showTimer){
+ this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
+ }else if (this.menu.isVisible() && autoActivate){
+ this.menu.tryActivate(0, 1);
}
- }catch(e){
- this.handleFailure(response);
}
},
- handleResponse : function(response){
- this.transId = false;
- var a = response.argument;
- this.processResponse(response, a.node, a.callback);
- this.fireEvent("load", this, a.node, response);
+ // private
+ deferExpand : function(autoActivate){
+ delete this.showTimer;
+ this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
+ if(autoActivate){
+ this.menu.tryActivate(0, 1);
+ }
},
- handleFailure : function(response)
- {
- // should handle failure better..
- this.transId = false;
- var a = response.argument;
- this.fireEvent("loadexception", this, a.node, response);
- if(typeof a.callback == "function"){
- a.callback(this, a.node);
+ // private
+ hideMenu : function(){
+ clearTimeout(this.showTimer);
+ delete this.showTimer;
+ if(!this.hideTimer && this.menu && this.menu.isVisible()){
+ this.hideTimer = this.deferHide.defer(this.hideDelay, this);
}
+ },
+
+ // private
+ deferHide : function(){
+ delete this.hideTimer;
+ this.menu.hide();
}
});/*
* Based on:
* Fork - LGPL
* <script type="text/javascript">
*/
-
+
/**
-* @class Roo.tree.TreeFilter
-* Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
-* @param {TreePanel} tree
-* @param {Object} config (optional)
+ * @class Roo.menu.CheckItem
+ * @extends Roo.menu.Item
+ * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
+ * @constructor
+ * Creates a new CheckItem
+ * @param {Object} config Configuration options
*/
-Roo.tree.TreeFilter = function(tree, config){
- this.tree = tree;
- this.filtered = {};
- Roo.apply(this, config);
+Roo.menu.CheckItem = function(config){
+ Roo.menu.CheckItem.superclass.constructor.call(this, config);
+ this.addEvents({
+ /**
+ * @event beforecheckchange
+ * Fires before the checked value is set, providing an opportunity to cancel if needed
+ * @param {Roo.menu.CheckItem} this
+ * @param {Boolean} checked The new checked value that will be set
+ */
+ "beforecheckchange" : true,
+ /**
+ * @event checkchange
+ * Fires after the checked value has been set
+ * @param {Roo.menu.CheckItem} this
+ * @param {Boolean} checked The checked value that was set
+ */
+ "checkchange" : true
+ });
+ if(this.checkHandler){
+ this.on('checkchange', this.checkHandler, this.scope);
+ }
};
+Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
+ /**
+ * @cfg {String} group
+ * All check items with the same group name will automatically be grouped into a single-select
+ * radio button group (defaults to '')
+ */
+ /**
+ * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
+ */
+ itemCls : "x-menu-item x-menu-check-item",
+ /**
+ * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
+ */
+ groupClass : "x-menu-group-item",
-Roo.tree.TreeFilter.prototype = {
- clearBlank:false,
- reverse:false,
- autoClear:false,
- remove:false,
-
- /**
- * Filter the data by a specific attribute.
- * @param {String/RegExp} value Either string that the attribute value
- * should start with or a RegExp to test against the attribute
- * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
- * @param {TreeNode} startNode (optional) The node to start the filter at.
+ /**
+ * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false). Note that
+ * if this checkbox is part of a radio group (group = true) only the last item in the group that is
+ * initialized with checked = true will be rendered as checked.
*/
- filter : function(value, attr, startNode){
- attr = attr || "text";
- var f;
- if(typeof value == "string"){
- var vlen = value.length;
- // auto clear empty filter
- if(vlen == 0 && this.clearBlank){
- this.clear();
- return;
- }
- value = value.toLowerCase();
- f = function(n){
- return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
- };
- }else if(value.exec){ // regex?
- f = function(n){
- return value.test(n.attributes[attr]);
- };
- }else{
- throw 'Illegal filter type, must be string or regex';
+ checked: false,
+
+ // private
+ ctype: "Roo.menu.CheckItem",
+
+ // private
+ onRender : function(c){
+ Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
+ if(this.group){
+ this.el.addClass(this.groupClass);
}
- this.filterBy(f, null, startNode);
- },
+ Roo.menu.MenuMgr.registerCheckable(this);
+ if(this.checked){
+ this.checked = false;
+ this.setChecked(true, true);
+ }
+ },
+
+ // private
+ destroy : function(){
+ if(this.rendered){
+ Roo.menu.MenuMgr.unregisterCheckable(this);
+ }
+ Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
+ },
/**
- * Filter by a function. The passed function will be called with each
- * node in the tree (or from the startNode). If the function returns true, the node is kept
- * otherwise it is filtered. If a node is filtered, its children are also filtered.
- * @param {Function} fn The filter function
- * @param {Object} scope (optional) The scope of the function (defaults to the current node)
+ * Set the checked state of this item
+ * @param {Boolean} checked The new checked value
+ * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
*/
- filterBy : function(fn, scope, startNode){
- startNode = startNode || this.tree.root;
- if(this.autoClear){
- this.clear();
- }
- var af = this.filtered, rv = this.reverse;
- var f = function(n){
- if(n == startNode){
- return true;
- }
- if(af[n.id]){
- return false;
+ setChecked : function(state, suppressEvent){
+ if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
+ if(this.container){
+ this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
}
- var m = fn.call(scope || n, n);
- if(!m || rv){
- af[n.id] = n;
- n.ui.hide();
- return false;
+ this.checked = state;
+ if(suppressEvent !== true){
+ this.fireEvent("checkchange", this, state);
}
- return true;
- };
- startNode.cascade(f);
- if(this.remove){
- for(var id in af){
- if(typeof id != "function"){
- var n = af[id];
- if(n && n.parentNode){
- n.parentNode.removeChild(n);
- }
- }
- }
}
},
+ // private
+ handleClick : function(e){
+ if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
+ this.setChecked(!this.checked);
+ }
+ Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
+ }
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.menu.DateItem
+ * @extends Roo.menu.Adapter
+ * A menu item that wraps the {@link Roo.DatPicker} component.
+ * @constructor
+ * Creates a new DateItem
+ * @param {Object} config Configuration options
+ */
+Roo.menu.DateItem = function(config){
+ Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
+ /** The Roo.DatePicker object @type Roo.DatePicker */
+ this.picker = this.component;
+ this.addEvents({select: true});
+
+ this.picker.on("render", function(picker){
+ picker.getEl().swallowEvent("click");
+ picker.container.addClass("x-menu-date-item");
+ });
+
+ this.picker.on("select", this.onSelect, this);
+};
+
+Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
+ // private
+ onSelect : function(picker, date){
+ this.fireEvent("select", this, date, picker);
+ Roo.menu.DateItem.superclass.handleClick.call(this);
+ }
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.menu.ColorItem
+ * @extends Roo.menu.Adapter
+ * A menu item that wraps the {@link Roo.ColorPalette} component.
+ * @constructor
+ * Creates a new ColorItem
+ * @param {Object} config Configuration options
+ */
+Roo.menu.ColorItem = function(config){
+ Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
+ /** The Roo.ColorPalette object @type Roo.ColorPalette */
+ this.palette = this.component;
+ this.relayEvents(this.palette, ["select"]);
+ if(this.selectHandler){
+ this.on('select', this.selectHandler, this.scope);
+ }
+};
+Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+
+/**
+ * @class Roo.menu.DateMenu
+ * @extends Roo.menu.Menu
+ * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
+ * @constructor
+ * Creates a new DateMenu
+ * @param {Object} config Configuration options
+ */
+Roo.menu.DateMenu = function(config){
+ Roo.menu.DateMenu.superclass.constructor.call(this, config);
+ this.plain = true;
+ var di = new Roo.menu.DateItem(config);
+ this.add(di);
/**
- * Clears the current filter. Note: with the "remove" option
- * set a filter cannot be cleared.
+ * The {@link Roo.DatePicker} instance for this DateMenu
+ * @type DatePicker
*/
- clear : function(){
- var t = this.tree;
- var af = this.filtered;
- for(var id in af){
- if(typeof id != "function"){
- var n = af[id];
- if(n){
- n.ui.show();
- }
- }
+ this.picker = di.picker;
+ /**
+ * @event select
+ * @param {DatePicker} picker
+ * @param {Date} date
+ */
+ this.relayEvents(di, ["select"]);
+ this.on('beforeshow', function(){
+ if(this.picker){
+ this.picker.hideMonthPicker(false);
}
- this.filtered = {};
- }
+ }, this);
+};
+Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
+ cls:'x-date-menu'
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+
+/**
+ * @class Roo.menu.ColorMenu
+ * @extends Roo.menu.Menu
+ * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
+ * @constructor
+ * Creates a new ColorMenu
+ * @param {Object} config Configuration options
+ */
+Roo.menu.ColorMenu = function(config){
+ Roo.menu.ColorMenu.superclass.constructor.call(this, config);
+ this.plain = true;
+ var ci = new Roo.menu.ColorItem(config);
+ this.add(ci);
+ /**
+ * The {@link Roo.ColorPalette} instance for this ColorMenu
+ * @type ColorPalette
+ */
+ this.palette = ci.palette;
+ /**
+ * @event select
+ * @param {ColorPalette} palette
+ * @param {String} color
+ */
+ this.relayEvents(ci, ["select"]);
};
-/*
+Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* <script type="text/javascript">
*/
-
/**
- * @class Roo.tree.TreeSorter
- * Provides sorting of nodes in a TreePanel
- *
- * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
- * @cfg {String} property The named attribute on the node to sort by (defaults to text)
- * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
- * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
- * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
- * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
+ * @class Roo.form.TextItem
+ * @extends Roo.BoxComponent
+ * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
* @constructor
- * @param {TreePanel} tree
- * @param {Object} config
+ * Creates a new TextItem
+ * @param {Object} config Configuration options
*/
-Roo.tree.TreeSorter = function(tree, config){
- Roo.apply(this, config);
- tree.on("beforechildrenrendered", this.doSort, this);
- tree.on("append", this.updateSort, this);
- tree.on("insert", this.updateSort, this);
-
- var dsc = this.dir && this.dir.toLowerCase() == "desc";
- var p = this.property || "text";
- var sortType = this.sortType;
- var fs = this.folderSort;
- var cs = this.caseSensitive === true;
- var leafAttr = this.leafAttr || 'leaf';
-
- this.sortFn = function(n1, n2){
- if(fs){
- if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
- return 1;
- }
- if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
- return -1;
- }
- }
- var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
- var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
- if(v1 < v2){
- return dsc ? +1 : -1;
- }else if(v1 > v2){
- return dsc ? -1 : +1;
- }else{
- return 0;
- }
- };
+Roo.form.TextItem = function(config){
+ Roo.form.TextItem.superclass.constructor.call(this, config);
};
-Roo.tree.TreeSorter.prototype = {
- doSort : function(node){
- node.sort(this.sortFn);
- },
+Roo.extend(Roo.form.TextItem, Roo.BoxComponent, {
- compareNodes : function(n1, n2){
- return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
+ /**
+ * @cfg {String} tag the tag for this item (default div)
+ */
+ tag : 'div',
+ /**
+ * @cfg {String} html the content for this item
+ */
+ html : '',
+
+ getAutoCreate : function()
+ {
+ var cfg = {
+ id: this.id,
+ tag: this.tag,
+ html: this.html,
+ cls: 'x-form-item'
+ };
+
+ return cfg;
+
},
- updateSort : function(tree, node){
- if(node.childrenRendered){
- this.doSort.defer(1, this, [node]);
+ onRender : function(ct, position)
+ {
+ Roo.form.TextItem.superclass.onRender.call(this, ct, position);
+
+ if(!this.el){
+ var cfg = this.getAutoCreate();
+ if(!cfg.name){
+ cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
+ }
+ if (!cfg.name.length) {
+ delete cfg.name;
+ }
+ this.el = ct.createChild(cfg, position);
}
+ },
+ /*
+ * setHTML
+ * @param {String} html update the Contents of the element.
+ */
+ setHTML : function(html)
+ {
+ this.fieldEl.dom.innerHTML = html;
}
-};/*
+
+});/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* Fork - LGPL
* <script type="text/javascript">
*/
-
-if(Roo.dd.DropZone){
-
-Roo.tree.TreeDropZone = function(tree, config){
- this.allowParentInsert = false;
- this.allowContainerDrop = false;
- this.appendOnly = false;
- Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
- this.tree = tree;
- this.lastInsertClass = "x-tree-no-status";
- this.dragOverData = {};
+
+/**
+ * @class Roo.form.Field
+ * @extends Roo.BoxComponent
+ * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
+ * @constructor
+ * Creates a new Field
+ * @param {Object} config Configuration options
+ */
+Roo.form.Field = function(config){
+ Roo.form.Field.superclass.constructor.call(this, config);
};
-Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
- ddGroup : "TreeDD",
- scroll: true,
-
- expandDelay : 1000,
-
- expandNode : function(node){
- if(node.hasChildNodes() && !node.isExpanded()){
- node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
- }
- },
-
- queueExpand : function(node){
- this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
- },
+Roo.extend(Roo.form.Field, Roo.BoxComponent, {
+ /**
+ * @cfg {String} fieldLabel Label to use when rendering a form.
+ */
+ /**
+ * @cfg {String} labelSeparator the ':' after a field label (default :) = set it to empty string to hide the field label.
+ */
+ /**
+ * @cfg {String} qtip Mouse over tip
+ */
+
+ /**
+ * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
+ */
+ invalidClass : "x-form-invalid",
+ /**
+ * @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")
+ */
+ invalidText : "The value in this field is invalid",
+ /**
+ * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
+ */
+ focusClass : "x-form-focus",
+ /**
+ * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
+ automatic validation (defaults to "keyup").
+ */
+ validationEvent : "keyup",
+ /**
+ * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
+ */
+ validateOnBlur : true,
+ /**
+ * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
+ */
+ validationDelay : 250,
+ /**
+ * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
+ * {tag: "input", type: "text", size: "20", autocomplete: "off"})
+ */
+ defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
+ /**
+ * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
+ */
+ fieldClass : "x-form-field",
+ /**
+ * @cfg {String} msgTarget The location where error text should display. Should be one of the following values (defaults to 'qtip'):
+ *<pre>
+Value Description
+----------- ----------------------------------------------------------------------
+qtip Display a quick tip when the user hovers over the field
+title Display a default browser title attribute popup
+under Add a block div beneath the field containing the error text
+side Add an error icon to the right of the field with a popup on hover
+[element id] Add the error text directly to the innerHTML of the specified element
+</pre>
+ */
+ msgTarget : 'qtip',
+ /**
+ * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
+ */
+ msgFx : 'normal',
+
+ /**
+ * @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.
+ */
+ readOnly : false,
+
+ /**
+ * @cfg {Boolean} disabled True to disable the field (defaults to false).
+ */
+ disabled : false,
+
+ /**
+ * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
+ */
+ inputType : undefined,
- cancelExpand : function(){
- if(this.expandProcId){
- clearTimeout(this.expandProcId);
- this.expandProcId = false;
- }
+ /**
+ * @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).
+ */
+ tabIndex : undefined,
+
+ // private
+ isFormField : true,
+
+ // private
+ hasFocus : false,
+ /**
+ * @property {Roo.Element} fieldEl
+ * Element Containing the rendered Field (with label etc.)
+ */
+ /**
+ * @cfg {Mixed} value A value to initialize this field with.
+ */
+ value : undefined,
+
+ /**
+ * @cfg {String} name The field's HTML name attribute.
+ */
+ /**
+ * @cfg {String} cls A CSS class to apply to the field's underlying element.
+ */
+ // private
+ loadedValue : false,
+
+
+ // private ??
+ initComponent : function(){
+ Roo.form.Field.superclass.initComponent.call(this);
+ this.addEvents({
+ /**
+ * @event focus
+ * Fires when this field receives input focus.
+ * @param {Roo.form.Field} this
+ */
+ focus : true,
+ /**
+ * @event blur
+ * Fires when this field loses input focus.
+ * @param {Roo.form.Field} this
+ */
+ blur : true,
+ /**
+ * @event specialkey
+ * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
+ * {@link Roo.EventObject#getKey} to determine which key was pressed.
+ * @param {Roo.form.Field} this
+ * @param {Roo.EventObject} e The event object
+ */
+ specialkey : true,
+ /**
+ * @event change
+ * Fires just before the field blurs if the field value has changed.
+ * @param {Roo.form.Field} this
+ * @param {Mixed} newValue The new value
+ * @param {Mixed} oldValue The original value
+ */
+ change : true,
+ /**
+ * @event invalid
+ * Fires after the field has been marked as invalid.
+ * @param {Roo.form.Field} this
+ * @param {String} msg The validation message
+ */
+ invalid : true,
+ /**
+ * @event valid
+ * Fires after the field has been validated with no errors.
+ * @param {Roo.form.Field} this
+ */
+ valid : true,
+ /**
+ * @event keyup
+ * Fires after the key up
+ * @param {Roo.form.Field} this
+ * @param {Roo.EventObject} e The event Object
+ */
+ keyup : true
+ });
},
-
- isValidDropPoint : function(n, pt, dd, e, data){
- if(!n || !data){ return false; }
- var targetNode = n.node;
- var dropNode = data.node;
- // default drop rules
- if(!(targetNode && targetNode.isTarget && pt)){
- return false;
- }
- if(pt == "append" && targetNode.allowChildren === false){
- return false;
- }
- if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
- return false;
- }
- if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
- return false;
- }
- // reuse the object
- var overEvent = this.dragOverData;
- overEvent.tree = this.tree;
- overEvent.target = targetNode;
- overEvent.data = data;
- overEvent.point = pt;
- overEvent.source = dd;
- overEvent.rawEvent = e;
- overEvent.dropNode = dropNode;
- overEvent.cancel = false;
- var result = this.tree.fireEvent("nodedragover", overEvent);
- return overEvent.cancel === false && result !== false;
+
+ /**
+ * Returns the name attribute of the field if available
+ * @return {String} name The field name
+ */
+ getName: function(){
+ return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
},
-
- getDropPoint : function(e, n, dd)
- {
- var tn = n.node;
- if(tn.isRoot){
- return tn.allowChildren !== false ? "append" : false; // always append for root
+
+ // private
+ onRender : function(ct, position){
+ Roo.form.Field.superclass.onRender.call(this, ct, position);
+ if(!this.el){
+ var cfg = this.getAutoCreate();
+ if(!cfg.name){
+ cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
+ }
+ if (!cfg.name.length) {
+ delete cfg.name;
+ }
+ if(this.inputType){
+ cfg.type = this.inputType;
+ }
+ this.el = ct.createChild(cfg, position);
}
- var dragEl = n.ddel;
- var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
- var y = Roo.lib.Event.getPageY(e);
- //var noAppend = tn.allowChildren === false || tn.isLeaf();
-
- // we may drop nodes anywhere, as long as allowChildren has not been set to false..
- var noAppend = tn.allowChildren === false;
- if(this.appendOnly || tn.parentNode.allowChildren === false){
- return noAppend ? false : "append";
+ var type = this.el.dom.type;
+ if(type){
+ if(type == 'password'){
+ type = 'text';
+ }
+ this.el.addClass('x-form-'+type);
}
- var noBelow = false;
- if(!this.allowParentInsert){
- noBelow = tn.hasChildNodes() && tn.isExpanded();
+ if(this.readOnly){
+ this.el.dom.readOnly = true;
}
- var q = (b - t) / (noAppend ? 2 : 3);
- if(y >= t && y < (t + q)){
- return "above";
- }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
- return "below";
- }else{
- return "append";
+ if(this.tabIndex !== undefined){
+ this.el.dom.setAttribute('tabIndex', this.tabIndex);
}
+
+ this.el.addClass([this.fieldClass, this.cls]);
+ this.initValue();
},
-
- onNodeEnter : function(n, dd, e, data)
- {
- this.cancelExpand();
+
+ /**
+ * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
+ * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
+ * @return {Roo.form.Field} this
+ */
+ applyTo : function(target){
+ this.allowDomMove = false;
+ this.el = Roo.get(target);
+ this.render(this.el.dom.parentNode);
+ return this;
},
-
- onNodeOver : function(n, dd, e, data)
- {
-
- var pt = this.getDropPoint(e, n, dd);
- var node = n.node;
-
- // auto node expand check
- if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
- this.queueExpand(node);
- }else if(pt != "append"){
- this.cancelExpand();
+
+ // private
+ initValue : function(){
+ if(this.value !== undefined){
+ this.setValue(this.value);
+ }else if(this.el.dom.value.length > 0){
+ this.setValue(this.el.dom.value);
}
-
- // set the insert point style on the target node
- var returnCls = this.dropNotAllowed;
- if(this.isValidDropPoint(n, pt, dd, e, data)){
- if(pt){
- var el = n.ddel;
- var cls;
- if(pt == "above"){
- returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
- cls = "x-tree-drag-insert-above";
- }else if(pt == "below"){
- returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
- cls = "x-tree-drag-insert-below";
- }else{
- returnCls = "x-tree-drop-ok-append";
- cls = "x-tree-drag-append";
- }
- if(this.lastInsertClass != cls){
- Roo.fly(el).replaceClass(this.lastInsertClass, cls);
- this.lastInsertClass = cls;
- }
- }
- }
- return returnCls;
- },
-
- onNodeOut : function(n, dd, e, data){
-
- this.cancelExpand();
- this.removeDropIndicators(n);
},
-
- onNodeDrop : function(n, dd, e, data){
- var point = this.getDropPoint(e, n, dd);
- var targetNode = n.node;
- targetNode.ui.startDrop();
- if(!this.isValidDropPoint(n, point, dd, e, data)){
- targetNode.ui.endDrop();
+
+ /**
+ * Returns true if this field has been changed since it was originally loaded and is not disabled.
+ * DEPRICATED - it never worked well - use hasChanged/resetHasChanged.
+ */
+ isDirty : function() {
+ if(this.disabled) {
return false;
}
- // first try to find the drop node
- var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
- var dropEvent = {
- tree : this.tree,
- target: targetNode,
- data: data,
- point: point,
- source: dd,
- rawEvent: e,
- dropNode: dropNode,
- cancel: !dropNode
- };
- var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
- if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
- targetNode.ui.endDrop();
+ return String(this.getValue()) !== String(this.originalValue);
+ },
+
+ /**
+ * stores the current value in loadedValue
+ */
+ resetHasChanged : function()
+ {
+ this.loadedValue = String(this.getValue());
+ },
+ /**
+ * checks the current value against the 'loaded' value.
+ * Note - will return false if 'resetHasChanged' has not been called first.
+ */
+ hasChanged : function()
+ {
+ if(this.disabled || this.readOnly) {
return false;
}
- // allow target changing
- targetNode = dropEvent.target;
- if(point == "append" && !targetNode.isExpanded()){
- targetNode.expand(false, null, function(){
- this.completeDrop(dropEvent);
- }.createDelegate(this));
- }else{
- this.completeDrop(dropEvent);
- }
- return true;
+ return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
},
- completeDrop : function(de){
- var ns = de.dropNode, p = de.point, t = de.target;
- if(!(ns instanceof Array)){
- ns = [ns];
+
+
+ // private
+ afterRender : function(){
+ Roo.form.Field.superclass.afterRender.call(this);
+ this.initEvents();
+ },
+
+ // private
+ fireKey : function(e){
+ //Roo.log('field ' + e.getKey());
+ if(e.isNavKeyPress()){
+ this.fireEvent("specialkey", this, e);
}
- var n;
- for(var i = 0, len = ns.length; i < len; i++){
- n = ns[i];
- if(p == "above"){
- t.parentNode.insertBefore(n, t);
- }else if(p == "below"){
- t.parentNode.insertBefore(n, t.nextSibling);
- }else{
- t.appendChild(n);
- }
+ },
+
+ /**
+ * Resets the current field value to the originally loaded value and clears any validation messages
+ */
+ reset : function(){
+ this.setValue(this.resetValue);
+ this.originalValue = this.getValue();
+ this.clearInvalid();
+ },
+
+ // private
+ initEvents : function(){
+ // safari killled keypress - so keydown is now used..
+ this.el.on("keydown" , this.fireKey, this);
+ this.el.on("focus", this.onFocus, this);
+ this.el.on("blur", this.onBlur, this);
+ this.el.relayEvent('keyup', this);
+
+ // reference to original value for reset
+ this.originalValue = this.getValue();
+ this.resetValue = this.getValue();
+ },
+
+ // private
+ onFocus : function(){
+ if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
+ this.el.addClass(this.focusClass);
}
- n.ui.focus();
- if(this.tree.hlDrop){
- n.ui.highlight();
+ if(!this.hasFocus){
+ this.hasFocus = true;
+ this.startValue = this.getValue();
+ this.fireEvent("focus", this);
}
- t.ui.endDrop();
- this.tree.fireEvent("nodedrop", de);
},
-
- afterNodeMoved : function(dd, data, e, targetNode, dropNode){
- if(this.tree.hlDrop){
- dropNode.ui.focus();
- dropNode.ui.highlight();
+
+ beforeBlur : Roo.emptyFn,
+
+ // private
+ onBlur : function(){
+ this.beforeBlur();
+ if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
+ this.el.removeClass(this.focusClass);
}
- this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
+ this.hasFocus = false;
+ if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
+ this.validate();
+ }
+ var v = this.getValue();
+ if(String(v) !== String(this.startValue)){
+ this.fireEvent('change', this, v, this.startValue);
+ }
+ this.fireEvent("blur", this);
},
-
- getTree : function(){
- return this.tree;
+
+ /**
+ * Returns whether or not the field value is currently valid
+ * @param {Boolean} preventMark True to disable marking the field invalid
+ * @return {Boolean} True if the value is valid, else false
+ */
+ isValid : function(preventMark){
+ if(this.disabled){
+ return true;
+ }
+ var restore = this.preventMark;
+ this.preventMark = preventMark === true;
+ var v = this.validateValue(this.processValue(this.getRawValue()));
+ this.preventMark = restore;
+ return v;
},
-
- removeDropIndicators : function(n){
- if(n && n.ddel){
- var el = n.ddel;
- Roo.fly(el).removeClass([
- "x-tree-drag-insert-above",
- "x-tree-drag-insert-below",
- "x-tree-drag-append"]);
- this.lastInsertClass = "_noclass";
+
+ /**
+ * Validates the field value
+ * @return {Boolean} True if the value is valid, else false
+ */
+ validate : function(){
+ if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
+ this.clearInvalid();
+ return true;
}
+ return false;
},
-
- beforeDragDrop : function(target, e, id){
- this.cancelExpand();
+
+ processValue : function(value){
+ return value;
+ },
+
+ // private
+ // Subclasses should provide the validation implementation by overriding this
+ validateValue : function(value){
return true;
},
-
- afterRepair : function(data){
- if(data && Roo.enableFx){
- data.node.ui.highlight();
+
+ /**
+ * Mark this field as invalid
+ * @param {String} msg The validation message
+ */
+ markInvalid : function(msg){
+ if(!this.rendered || this.preventMark){ // not rendered
+ return;
}
- this.hideProxy();
- }
-
-});
+
+ var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
+
+ obj.el.addClass(this.invalidClass);
+ msg = msg || this.invalidText;
+ switch(this.msgTarget){
+ case 'qtip':
+ obj.el.dom.qtip = msg;
+ obj.el.dom.qclass = 'x-form-invalid-tip';
+ if(Roo.QuickTips){ // fix for floating editors interacting with DND
+ Roo.QuickTips.enable();
+ }
+ break;
+ case 'title':
+ this.el.dom.title = msg;
+ break;
+ case 'under':
+ if(!this.errorEl){
+ var elp = this.el.findParent('.x-form-element', 5, true);
+ this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
+ this.errorEl.setWidth(elp.getWidth(true)-20);
+ }
+ this.errorEl.update(msg);
+ Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
+ break;
+ case 'side':
+ if(!this.errorIcon){
+ var elp = this.el.findParent('.x-form-element', 5, true);
+ this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
+ }
+ this.alignErrorIcon();
+ this.errorIcon.dom.qtip = msg;
+ this.errorIcon.dom.qclass = 'x-form-invalid-tip';
+ this.errorIcon.show();
+ this.on('resize', this.alignErrorIcon, this);
+ break;
+ default:
+ var t = Roo.getDom(this.msgTarget);
+ t.innerHTML = msg;
+ t.style.display = this.msgDisplay;
+ break;
+ }
+ this.fireEvent('invalid', this, msg);
+ },
-}
-/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
+ // private
+ alignErrorIcon : function(){
+ this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
+ },
-if(Roo.dd.DragZone){
-Roo.tree.TreeDragZone = function(tree, config){
- Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
- this.tree = tree;
-};
+ /**
+ * Clear any invalid styles/messages for this field
+ */
+ clearInvalid : function(){
+ if(!this.rendered || this.preventMark){ // not rendered
+ return;
+ }
+ var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
+
+ obj.el.removeClass(this.invalidClass);
+ switch(this.msgTarget){
+ case 'qtip':
+ obj.el.dom.qtip = '';
+ break;
+ case 'title':
+ this.el.dom.title = '';
+ break;
+ case 'under':
+ if(this.errorEl){
+ Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
+ }
+ break;
+ case 'side':
+ if(this.errorIcon){
+ this.errorIcon.dom.qtip = '';
+ this.errorIcon.hide();
+ this.un('resize', this.alignErrorIcon, this);
+ }
+ break;
+ default:
+ var t = Roo.getDom(this.msgTarget);
+ t.innerHTML = '';
+ t.style.display = 'none';
+ break;
+ }
+ this.fireEvent('valid', this);
+ },
-Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
- ddGroup : "TreeDD",
-
- onBeforeDrag : function(data, e){
- var n = data.node;
- return n && n.draggable && !n.disabled;
+ /**
+ * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
+ * @return {Mixed} value The field value
+ */
+ getRawValue : function(){
+ var v = this.el.getValue();
+
+ return v;
},
-
-
- onInitDrag : function(e){
- var data = this.dragData;
- this.tree.getSelectionModel().select(data.node);
- this.proxy.update("");
- data.node.ui.appendDDGhost(this.proxy.ghost.dom);
- this.tree.fireEvent("startdrag", this.tree, data.node, e);
+
+ /**
+ * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
+ * @return {Mixed} value The field value
+ */
+ getValue : function(){
+ var v = this.el.getValue();
+
+ return v;
},
-
- getRepairXY : function(e, data){
- return data.node.ui.getDDRepairXY();
+
+ /**
+ * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
+ * @param {Mixed} value The value to set
+ */
+ setRawValue : function(v){
+ return this.el.dom.value = (v === null || v === undefined ? '' : v);
},
-
- onEndDrag : function(data, e){
- this.tree.fireEvent("enddrag", this.tree, data.node, e);
-
-
+
+ /**
+ * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
+ * @param {Mixed} value The value to set
+ */
+ setValue : function(v){
+ this.value = v;
+ if(this.rendered){
+ this.el.dom.value = (v === null || v === undefined ? '' : v);
+ this.validate();
+ }
},
-
- onValidDrop : function(dd, e, id){
- this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
- this.hideProxy();
+
+ adjustSize : function(w, h){
+ var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
+ s.width = this.adjustWidth(this.el.dom.tagName, s.width);
+ return s;
},
-
- beforeInvalidDrop : function(e, id){
- // this scrolls the original position back into view
- var sm = this.tree.getSelectionModel();
- sm.clearSelections();
- sm.select(this.dragData.node);
+
+ adjustWidth : function(tag, w){
+ tag = tag.toLowerCase();
+ if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
+ if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
+ if(tag == 'input'){
+ return w + 2;
+ }
+ if(tag == 'textarea'){
+ return w-2;
+ }
+ }else if(Roo.isOpera){
+ if(tag == 'input'){
+ return w + 2;
+ }
+ if(tag == 'textarea'){
+ return w-2;
+ }
+ }
+ }
+ return w;
}
});
-}/*
+
+
+// anything other than normal should be considered experimental
+Roo.form.Field.msgFx = {
+ normal : {
+ show: function(msgEl, f){
+ msgEl.setDisplayed('block');
+ },
+
+ hide : function(msgEl, f){
+ msgEl.setDisplayed(false).update('');
+ }
+ },
+
+ slide : {
+ show: function(msgEl, f){
+ msgEl.slideIn('t', {stopFx:true});
+ },
+
+ hide : function(msgEl, f){
+ msgEl.slideOut('t', {stopFx:true,useDisplay:true});
+ }
+ },
+
+ slideRight : {
+ show: function(msgEl, f){
+ msgEl.fixDisplay();
+ msgEl.alignTo(f.el, 'tl-tr');
+ msgEl.slideIn('l', {stopFx:true});
+ },
+
+ hide : function(msgEl, f){
+ msgEl.slideOut('l', {stopFx:true,useDisplay:true});
+ }
+ }
+};/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* Fork - LGPL
* <script type="text/javascript">
*/
+
+
/**
- * @class Roo.tree.TreeEditor
- * @extends Roo.Editor
- * Provides editor functionality for inline tree node editing. Any valid {@link Roo.form.Field} can be used
- * as the editor field.
+ * @class Roo.form.TextField
+ * @extends Roo.form.Field
+ * Basic text field. Can be used as a direct replacement for traditional text inputs, or as the base
+ * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
* @constructor
- * @param {Object} config (used to be the tree panel.)
- * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
- *
- * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
- * @cfg {Roo.form.TextField} field [required] The field configuration
- *
- *
+ * Creates a new TextField
+ * @param {Object} config Configuration options
*/
-Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
- var tree = config;
- var field;
- if (oldconfig) { // old style..
- field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
- } else {
- // new style..
- tree = config.tree;
- config.field = config.field || {};
- config.field.xtype = 'TextField';
- field = Roo.factory(config.field, Roo.form);
- }
- config = config || {};
-
-
+Roo.form.TextField = function(config){
+ Roo.form.TextField.superclass.constructor.call(this, config);
this.addEvents({
/**
- * @event beforenodeedit
- * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
- * false from the handler of this event.
- * @param {Editor} this
- * @param {Roo.tree.Node} node
- */
- "beforenodeedit" : true
+ * @event autosize
+ * Fires when the autosize function is triggered. The field may or may not have actually changed size
+ * according to the default logic, but this event provides a hook for the developer to apply additional
+ * logic at runtime to resize the field if needed.
+ * @param {Roo.form.Field} this This text field
+ * @param {Number} width The new field width
+ */
+ autosize : true
});
-
- //Roo.log(config);
- Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
-
- this.tree = tree;
-
- tree.on('beforeclick', this.beforeNodeClick, this);
- tree.getTreeEl().on('mousedown', this.hide, this);
- this.on('complete', this.updateNode, this);
- this.on('beforestartedit', this.fitToTree, this);
- this.on('startedit', this.bindScroll, this, {delay:10});
- this.on('specialkey', this.onSpecialKey, this);
};
-Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
+Roo.extend(Roo.form.TextField, Roo.form.Field, {
+ /**
+ * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
+ */
+ grow : false,
+ /**
+ * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
+ */
+ growMin : 30,
+ /**
+ * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
+ */
+ growMax : 800,
+ /**
+ * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
+ */
+ vtype : null,
+ /**
+ * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
+ */
+ maskRe : null,
+ /**
+ * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
+ */
+ disableKeyFilter : false,
+ /**
+ * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
+ */
+ allowBlank : true,
+ /**
+ * @cfg {Number} minLength Minimum input field length required (defaults to 0)
+ */
+ minLength : 0,
+ /**
+ * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
+ */
+ maxLength : Number.MAX_VALUE,
+ /**
+ * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
+ */
+ minLengthText : "The minimum length for this field is {0}",
+ /**
+ * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
+ */
+ maxLengthText : "The maximum length for this field is {0}",
+ /**
+ * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
+ */
+ selectOnFocus : false,
+ /**
+ * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space
+ */
+ allowLeadingSpace : false,
/**
- * @cfg {String} alignment
- * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
+ * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
*/
- alignment: "l-l",
- // inherit
- autoSize: false,
+ blankText : "This field is required",
/**
- * @cfg {Boolean} hideEl
- * True to hide the bound element while the editor is displayed (defaults to false)
+ * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
+ * If available, this function will be called only after the basic validators all return true, and will be passed the
+ * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
*/
- hideEl : false,
+ validator : null,
/**
- * @cfg {String} cls
- * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
+ * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
+ * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
+ * current field value. If the test fails, the field will be marked invalid using {@link #regexText}.
*/
- cls: "x-small-editor x-tree-editor",
+ regex : null,
/**
- * @cfg {Boolean} shim
- * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
+ * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
*/
- shim:false,
- // inherit
- shadow:"frame",
+ regexText : "",
/**
- * @cfg {Number} maxWidth
- * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed
- * the containing tree element's size, it will be automatically limited for you to the container width, taking
- * scroll and client offsets into account prior to each edit.
+ * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
*/
- maxWidth: 250,
-
- editDelay : 350,
+ emptyText : null,
+
// private
- fitToTree : function(ed, el){
- var td = this.tree.getTreeEl().dom, nd = el.dom;
- if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible
- td.scrollLeft = nd.offsetLeft;
+ initEvents : function()
+ {
+ if (this.emptyText) {
+ this.el.attr('placeholder', this.emptyText);
}
- var w = Math.min(
- this.maxWidth,
- (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
- this.setSize(w, '');
- return this.fireEvent('beforenodeedit', this, this.editNode);
+ Roo.form.TextField.superclass.initEvents.call(this);
+ if(this.validationEvent == 'keyup'){
+ this.validationTask = new Roo.util.DelayedTask(this.validate, this);
+ this.el.on('keyup', this.filterValidation, this);
+ }
+ else if(this.validationEvent !== false){
+ this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
+ }
+ if(this.selectOnFocus){
+ this.on("focus", this.preFocus, this);
+ }
+ if (!this.allowLeadingSpace) {
+ this.on('blur', this.cleanLeadingSpace, this);
+ }
+
+ if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
+ this.el.on("keypress", this.filterKeys, this);
+ }
+ if(this.grow){
+ this.el.on("keyup", this.onKeyUp, this, {buffer:50});
+ this.el.on("click", this.autoSize, this);
+ }
+ if(this.el.is('input[type=password]') && Roo.isSafari){
+ this.el.on('keydown', this.SafariOnKeyDown, this);
+ }
},
- // private
- triggerEdit : function(node){
- this.completeEdit();
- this.editNode = node;
- this.startEdit(node.ui.textNode, node.text);
+ processValue : function(value){
+ if(this.stripCharsRe){
+ var newValue = value.replace(this.stripCharsRe, '');
+ if(newValue !== value){
+ this.setRawValue(newValue);
+ return newValue;
+ }
+ }
+ return value;
},
- // private
- bindScroll : function(){
- this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
+ filterValidation : function(e){
+ if(!e.isNavKeyPress()){
+ this.validationTask.delay(this.validationDelay);
+ }
},
// private
- beforeNodeClick : function(node, e){
- var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
- this.lastClick = new Date();
- if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
- e.stopEvent();
- this.triggerEdit(node);
- return false;
+ onKeyUp : function(e){
+ if(!e.isNavKeyPress()){
+ this.autoSize();
}
- return true;
},
-
- // private
- updateNode : function(ed, value){
- this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
- this.editNode.setText(value);
+ // private - clean the leading white space
+ cleanLeadingSpace : function(e)
+ {
+ if ( this.inputType == 'file') {
+ return;
+ }
+
+ this.setValue((this.getValue() + '').replace(/^\s+/,''));
},
-
+ /**
+ * Resets the current field value to the originally-loaded value and clears any validation messages.
+ *
+ */
+ reset : function(){
+ Roo.form.TextField.superclass.reset.call(this);
+
+ },
// private
- onHide : function(){
- Roo.tree.TreeEditor.superclass.onHide.call(this);
- if(this.editNode){
- this.editNode.ui.focus();
+ preFocus : function(){
+
+ if(this.selectOnFocus){
+ this.el.dom.select();
}
},
+
// private
- onSpecialKey : function(field, e){
+ filterKeys : function(e){
var k = e.getKey();
- if(k == e.ESC){
- e.stopEvent();
- this.cancelEdit();
- }else if(k == e.ENTER && !e.hasModifier()){
+ if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
+ return;
+ }
+ var c = e.getCharCode(), cc = String.fromCharCode(c);
+ if(Roo.isIE && (e.isSpecialKey() || !cc)){
+ return;
+ }
+ if(!this.maskRe.test(cc)){
e.stopEvent();
- this.completeEdit();
}
- }
-});//<Script type="text/javascript">
-/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-/**
- * Not documented??? - probably should be...
- */
-
-Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
- //focus: Roo.emptyFn, // prevent odd scrolling behavior
-
- renderElements : function(n, a, targetNode, bulkRender){
- //consel.log("renderElements?");
- this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
+ },
- var t = n.getOwnerTree();
- var tid = Pman.Tab.Document_TypesTree.tree.el.id;
+ setValue : function(v){
- var cols = t.columns;
- var bw = t.borderWidth;
- var c = cols[0];
- var href = a.href ? a.href : Roo.isGecko ? "" : "#";
- var cb = typeof a.checked == "boolean";
- var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
- var colcls = 'x-t-' + tid + '-c0';
- var buf = [
- '<li class="x-tree-node">',
-
-
- '<div class="x-tree-node-el ', a.cls,'">',
- // extran...
- '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
-
-
- '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
- '<img src="', this.emptyIcon, '" class="x-tree-ec-icon " />',
- '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
- (a.icon ? ' x-tree-node-inline-icon' : ''),
- (a.iconCls ? ' '+a.iconCls : ''),
- '" unselectable="on" />',
- (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' +
- (a.checked ? 'checked="checked" />' : ' />')) : ''),
-
- '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
- (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
- '<span unselectable="on" qtip="' + tx + '">',
- tx,
- '</span></a>' ,
- '</div>',
- '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
- (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
- ];
- for(var i = 1, len = cols.length; i < len; i++){
- c = cols[i];
- colcls = 'x-t-' + tid + '-c' +i;
- tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
- buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
- '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
- "</div>");
- }
-
- buf.push(
- '</a>',
- '<div class="x-clear"></div></div>',
- '<ul class="x-tree-node-ct" style="display:none;"></ul>',
- "</li>");
+ Roo.form.TextField.superclass.setValue.apply(this, arguments);
- if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
- this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
- n.nextSibling.ui.getEl(), buf.join(""));
- }else{
- this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
+ this.autoSize();
+ },
+
+ /**
+ * Validates a value according to the field's validation rules and marks the field as invalid
+ * if the validation fails
+ * @param {Mixed} value The value to validate
+ * @return {Boolean} True if the value is valid, else false
+ */
+ validateValue : function(value){
+ if(value.length < 1) { // if it's blank
+ if(this.allowBlank){
+ this.clearInvalid();
+ return true;
+ }else{
+ this.markInvalid(this.blankText);
+ return false;
+ }
}
- var el = this.wrap.firstChild;
- this.elRow = el;
- this.elNode = el.firstChild;
- this.ranchor = el.childNodes[1];
- this.ctNode = this.wrap.childNodes[1];
- var cs = el.firstChild.childNodes;
- this.indentNode = cs[0];
- this.ecNode = cs[1];
- this.iconNode = cs[2];
- var index = 3;
- if(cb){
- this.checkbox = cs[3];
- index++;
+ if(value.length < this.minLength){
+ this.markInvalid(String.format(this.minLengthText, this.minLength));
+ return false;
}
- this.anchor = cs[index];
-
- this.textNode = cs[index].firstChild;
-
- //el.on("click", this.onClick, this);
- //el.on("dblclick", this.onDblClick, this);
-
-
- // console.log(this);
+ if(value.length > this.maxLength){
+ this.markInvalid(String.format(this.maxLengthText, this.maxLength));
+ return false;
+ }
+ if(this.vtype){
+ var vt = Roo.form.VTypes;
+ if (value.trim() != value) { // trim before checking email (and other stuf??)
+ value = value.trim();
+ this.el.dom.value = value;
+ }
+
+ if(!vt[this.vtype](value, this)){
+ this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
+ return false;
+ }
+ }
+ if(typeof this.validator == "function"){
+ var msg = this.validator(value);
+ if(msg !== true){
+ this.markInvalid(msg);
+ return false;
+ }
+ }
+ if(this.regex && !this.regex.test(value)){
+ this.markInvalid(this.regexText);
+ return false;
+ }
+ return true;
},
- initEvents : function(){
- Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
-
-
- var a = this.ranchor;
-
- var el = Roo.get(a);
- if(Roo.isOpera){ // opera render bug ignores the CSS
- el.setStyle("text-decoration", "none");
+ /**
+ * Selects text in this field
+ * @param {Number} start (optional) The index where the selection should start (defaults to 0)
+ * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
+ */
+ selectText : function(start, end){
+ var v = this.getRawValue();
+ if(v.length > 0){
+ start = start === undefined ? 0 : start;
+ end = end === undefined ? v.length : end;
+ var d = this.el.dom;
+ if(d.setSelectionRange){
+ d.setSelectionRange(start, end);
+ }else if(d.createTextRange){
+ var range = d.createTextRange();
+ range.moveStart("character", start);
+ range.moveEnd("character", v.length-end);
+ range.select();
+ }
}
+ },
- el.on("click", this.onClick, this);
- el.on("dblclick", this.onDblClick, this);
- el.on("contextmenu", this.onContextMenu, this);
-
+ /**
+ * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
+ * This only takes effect if grow = true, and fires the autosize event.
+ */
+ autoSize : function(){
+ if(!this.grow || !this.rendered){
+ return;
+ }
+ if(!this.metrics){
+ this.metrics = Roo.util.TextMetrics.createInstance(this.el);
+ }
+ var el = this.el;
+ var v = el.dom.value;
+ var d = document.createElement('div');
+ d.appendChild(document.createTextNode(v));
+ v = d.innerHTML;
+ d = null;
+ v += " ";
+ var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
+ this.el.setWidth(w);
+ this.fireEvent("autosize", this, w);
},
- /*onSelectedChange : function(state){
- if(state){
- this.focus();
- this.addClass("x-tree-selected");
- }else{
- //this.blur();
- this.removeClass("x-tree-selected");
+ // private
+ SafariOnKeyDown : function(event)
+ {
+ // this is a workaround for a password hang bug on chrome/ webkit.
+
+ var isSelectAll = false;
+
+ if(this.el.dom.selectionEnd > 0){
+ isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
}
- },*/
- addClass : function(cls){
- if(this.elRow){
- Roo.fly(this.elRow).addClass(cls);
+ if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
+ event.preventDefault();
+ this.setValue('');
+ return;
}
- },
-
-
- removeClass : function(cls){
- if(this.elRow){
- Roo.fly(this.elRow).removeClass(cls);
+ // skip handling paste
+ if(isSelectAll && event.getCharCode() > 31 && !(event.ctrlKey && event.getCharCode() == 86)){ // backspace and delete key
+
+ event.preventDefault();
+ // this is very hacky as keydown always get's upper case.
+
+ var cc = String.fromCharCode(event.getCharCode());
+
+
+ this.setValue( event.shiftKey ? cc : cc.toLowerCase());
+
}
+
+
}
+});Roo.form.Password = function(config){
+ Roo.form.Password.superclass.constructor.call(this, config);
-
-
-});//<Script type="text/javascript">
+ this.inputType = 'password';
+};
-/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
+Roo.extend(Roo.form.Password, Roo.form.TextField, {
+ onRender : function(ct, position)
+ {
+ Roo.form.Password.superclass.onRender.call(this, ct, position);
-/**
- * @class Roo.tree.ColumnTree
- * @extends Roo.tree.TreePanel
- * @cfg {Object} columns Including width, header, renderer, cls, dataIndex
- * @cfg {int} borderWidth compined right/left border allowance
- * @constructor
- * @param {String/HTMLElement/Element} el The container element
- * @param {Object} config
- */
-Roo.tree.ColumnTree = function(el, config)
-{
- Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
- this.addEvents({
- /**
- * @event resize
- * Fire this event on a container when it resizes
- * @param {int} w Width
- * @param {int} h Height
- */
- "resize" : true
- });
- this.on('resize', this.onResize, this);
-};
+ this.parentEl().addClass('form-password');
-Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
- //lines:false,
-
-
- borderWidth: Roo.isBorderBox ? 0 : 2,
- headEls : false,
+ this.wrap = this.el.wrap({
+ cls : 'password-wrap'
+ });
+
+ this.toggle = this.wrap.createChild({
+ tag : 'Button',
+ cls : 'password-toggle'
+ });
+
+
+ this.toggleEl().addClass('password-hidden');
+
+ this.toggleEl().on('click', this.onToggleClick, this);;
+ },
- render : function(){
- // add the header.....
-
- Roo.tree.ColumnTree.superclass.render.apply(this);
-
- this.el.addClass('x-column-tree');
-
- this.headers = this.el.createChild(
- {cls:'x-tree-headers'},this.innerCt.dom);
-
- var cols = this.columns, c;
- var totalWidth = 0;
- this.headEls = [];
- var len = cols.length;
- for(var i = 0; i < len; i++){
- c = cols[i];
- totalWidth += c.width;
- this.headEls.push(this.headers.createChild({
- cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
- cn: {
- cls:'x-tree-hd-text',
- html: c.header
- },
- style:'width:'+(c.width-this.borderWidth)+'px;'
- }));
- }
- this.headers.createChild({cls:'x-clear'});
- // prevent floats from wrapping when clipped
- this.headers.setWidth(totalWidth);
- //this.innerCt.setWidth(totalWidth);
- this.innerCt.setStyle({ overflow: 'auto' });
- this.onResize(this.width, this.height);
-
-
+ parentEl : function()
+ {
+ return this.el.findParent('.x-form-element', 5, true);
},
- onResize : function(w,h)
+
+ toggleEl: function()
{
- this.height = h;
- this.width = w;
- // resize cols..
- this.innerCt.setWidth(this.width);
- this.innerCt.setHeight(this.height-20);
-
- // headers...
- var cols = this.columns, c;
- var totalWidth = 0;
- var expEl = false;
- var len = cols.length;
- for(var i = 0; i < len; i++){
- c = cols[i];
- if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
- // it's the expander..
- expEl = this.headEls[i];
- continue;
- }
- totalWidth += c.width;
-
+ return this.parentEl().select('button.password-toggle',true).first();
+ },
+
+ onToggleClick : function(e)
+ {
+ var input = this.el;
+ var toggle = this.toggleEl();
+
+ toggle.removeClass(['password-visible', 'password-hidden']);
+
+ if(input.attr('type') == 'password') {
+ input.attr('type', 'text');
+ toggle.addClass('password-visible');
}
- if (expEl) {
- expEl.setWidth( ((w - totalWidth)-this.borderWidth - 20));
+ else {
+ input.attr('type', 'password');
+ toggle.addClass('password-hidden');
}
- this.headers.setWidth(w-20);
-
-
-
-
}
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.form.Hidden
+ * @extends Roo.form.TextField
+ * Simple Hidden element used on forms
+ *
+ * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
+ *
+ * @constructor
+ * Creates a new Hidden form element.
+ * @param {Object} config Configuration options
+ */
+
+
+
+// easy hidden field...
+Roo.form.Hidden = function(config){
+ Roo.form.Hidden.superclass.constructor.call(this, config);
+};
+
+Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
+ fieldLabel: '',
+ inputType: 'hidden',
+ width: 50,
+ allowBlank: true,
+ labelSeparator: '',
+ hidden: true,
+ itemCls : 'x-form-item-display-none'
+
+
});
+
+
/*
* Based on:
* Ext JS Library 1.1.1
*/
/**
- * @class Roo.menu.Menu
- * @extends Roo.util.Observable
- * @children Roo.menu.Item Roo.menu.Separator Roo.menu.TextItem
- * A menu object. This is the container to which you add all other menu items. Menu can also serve a as a base class
- * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
+ * @class Roo.form.TriggerField
+ * @extends Roo.form.TextField
+ * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
+ * The trigger has no default action, so you must assign a function to implement the trigger click handler by
+ * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
+ * for which you can provide a custom implementation. For example:
+ * <pre><code>
+var trigger = new Roo.form.TriggerField();
+trigger.onTriggerClick = myTriggerFn;
+trigger.applyTo('my-field');
+</code></pre>
+ *
+ * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
+ * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
+ * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
+ * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
* @constructor
- * Creates a new Menu
- * @param {Object} config Configuration options
+ * Create a new TriggerField.
+ * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
+ * to the base TextField)
*/
-Roo.menu.Menu = function(config){
-
- Roo.menu.Menu.superclass.constructor.call(this, config);
-
- this.id = this.id || Roo.id();
- this.addEvents({
- /**
- * @event beforeshow
- * Fires before this menu is displayed
- * @param {Roo.menu.Menu} this
- */
- beforeshow : true,
- /**
- * @event beforehide
- * Fires before this menu is hidden
- * @param {Roo.menu.Menu} this
- */
- beforehide : true,
- /**
- * @event show
- * Fires after this menu is displayed
- * @param {Roo.menu.Menu} this
- */
- show : true,
- /**
- * @event hide
- * Fires after this menu is hidden
- * @param {Roo.menu.Menu} this
- */
- hide : true,
- /**
- * @event click
- * Fires when this menu is clicked (or when the enter key is pressed while it is active)
- * @param {Roo.menu.Menu} this
- * @param {Roo.menu.Item} menuItem The menu item that was clicked
- * @param {Roo.EventObject} e
- */
- click : true,
- /**
- * @event mouseover
- * Fires when the mouse is hovering over this menu
- * @param {Roo.menu.Menu} this
- * @param {Roo.EventObject} e
- * @param {Roo.menu.Item} menuItem The menu item that was clicked
- */
- mouseover : true,
- /**
- * @event mouseout
- * Fires when the mouse exits this menu
- * @param {Roo.menu.Menu} this
- * @param {Roo.EventObject} e
- * @param {Roo.menu.Item} menuItem The menu item that was clicked
- */
- mouseout : true,
- /**
- * @event itemclick
- * Fires when a menu item contained in this menu is clicked
- * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
- * @param {Roo.EventObject} e
- */
- itemclick: true
- });
- if (this.registerMenu) {
- Roo.menu.MenuMgr.register(this);
- }
-
- var mis = this.items;
- this.items = new Roo.util.MixedCollection();
- if(mis){
- this.add.apply(this, mis);
- }
+Roo.form.TriggerField = function(config){
+ this.mimicing = false;
+ Roo.form.TriggerField.superclass.constructor.call(this, config);
};
-Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
- /**
- * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
- */
- minWidth : 120,
- /**
- * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
- * for bottom-right shadow (defaults to "sides")
- */
- shadow : "sides",
- /**
- * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
- * this menu (defaults to "tl-tr?")
- */
- subMenuAlign : "tl-tr?",
+Roo.extend(Roo.form.TriggerField, Roo.form.TextField, {
/**
- * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
- * relative to its element of origin (defaults to "tl-bl?")
+ * @cfg {String} triggerClass A CSS class to apply to the trigger
*/
- defaultAlign : "tl-bl?",
/**
- * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
+ * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
+ * {tag: "input", type: "text", size: "16", autocomplete: "off"})
*/
- allowOtherMenus : false,
+ defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
/**
- * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
+ * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
*/
- registerMenu : true,
+ hideTrigger:false,
- hidden:true,
+ /** @cfg {Boolean} grow @hide */
+ /** @cfg {Number} growMin @hide */
+ /** @cfg {Number} growMax @hide */
+ /**
+ * @hide
+ * @method
+ */
+ autoSize: Roo.emptyFn,
// private
- render : function(){
- if(this.el){
- return;
- }
- var el = this.el = new Roo.Layer({
- cls: "x-menu",
- shadow:this.shadow,
- constrain: false,
- parentEl: this.parentEl || document.body,
- zindex:15000
- });
-
- this.keyNav = new Roo.menu.MenuNav(this);
+ monitorTab : true,
+ // private
+ deferHeight : true,
- if(this.plain){
- el.addClass("x-menu-plain");
- }
- if(this.cls){
- el.addClass(this.cls);
+
+ actionMode : 'wrap',
+ // private
+ onResize : function(w, h){
+ Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
+ if(typeof w == 'number'){
+ var x = w - this.trigger.getWidth();
+ this.el.setWidth(this.adjustWidth('input', x));
+ this.trigger.setStyle('left', x+'px');
}
- // generic focus element
- this.focusEl = el.createChild({
- tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
- });
- var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
- //disabling touch- as it's causing issues ..
- //ul.on(Roo.isTouch ? 'touchstart' : 'click' , this.onClick, this);
- ul.on('click' , this.onClick, this);
-
-
- ul.on("mouseover", this.onMouseOver, this);
- ul.on("mouseout", this.onMouseOut, this);
- this.items.each(function(item){
- if (item.hidden) {
- return;
- }
-
- var li = document.createElement("li");
- li.className = "x-menu-list-item";
- ul.dom.appendChild(li);
- item.render(li, this);
- }, this);
- this.ul = ul;
- this.autoWidth();
},
// private
- autoWidth : function(){
- var el = this.el, ul = this.ul;
- if(!el){
- return;
- }
- var w = this.width;
- if(w){
- el.setWidth(w);
- }else if(Roo.isIE){
- el.setWidth(this.minWidth);
- var t = el.dom.offsetWidth; // force recalc
- el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
- }
+ adjustSize : Roo.BoxComponent.prototype.adjustSize,
+
+ // private
+ getResizeEl : function(){
+ return this.wrap;
},
// private
- delayAutoWidth : function(){
- if(this.rendered){
- if(!this.awTask){
- this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
- }
- this.awTask.delay(20);
- }
+ getPositionEl : function(){
+ return this.wrap;
},
// private
- findTargetItem : function(e){
- var t = e.getTarget(".x-menu-list-item", this.ul, true);
- if(t && t.menuItemId){
- return this.items.get(t.menuItemId);
- }
+ alignErrorIcon : function(){
+ this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
},
// private
- onClick : function(e){
- Roo.log("menu.onClick");
- var t = this.findTargetItem(e);
- if(!t){
- return;
+ onRender : function(ct, position){
+ Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
+ this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
+ this.trigger = this.wrap.createChild(this.triggerConfig ||
+ {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
+ if(this.hideTrigger){
+ this.trigger.setDisplayed(false);
}
- Roo.log(e);
- if (Roo.isTouch && e.type == 'touchstart' && t.menu && !t.disabled) {
- if(t == this.activeItem && t.shouldDeactivate(e)){
- this.activeItem.deactivate();
- delete this.activeItem;
- return;
- }
- if(t.canActivate){
- this.setActiveItem(t, true);
- }
- return;
-
-
+ this.initTrigger();
+ if(!this.width){
+ this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
}
-
- t.onClick(e);
- this.fireEvent("click", this, t, e);
},
// private
- setActiveItem : function(item, autoExpand){
- if(item != this.activeItem){
- if(this.activeItem){
- this.activeItem.deactivate();
- }
- this.activeItem = item;
- item.activate(autoExpand);
- }else if(autoExpand){
- item.expandMenu();
- }
+ initTrigger : function(){
+ this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
+ this.trigger.addClassOnOver('x-form-trigger-over');
+ this.trigger.addClassOnClick('x-form-trigger-click');
},
// private
- tryActivate : function(start, step){
- var items = this.items;
- for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
- var item = items.get(i);
- if(!item.disabled && item.canActivate){
- this.setActiveItem(item, false);
- return item;
- }
+ onDestroy : function(){
+ if(this.trigger){
+ this.trigger.removeAllListeners();
+ this.trigger.remove();
}
- return false;
+ if(this.wrap){
+ this.wrap.remove();
+ }
+ Roo.form.TriggerField.superclass.onDestroy.call(this);
},
// private
- onMouseOver : function(e){
- var t;
- if(t = this.findTargetItem(e)){
- if(t.canActivate && !t.disabled){
- this.setActiveItem(t, true);
+ onFocus : function(){
+ Roo.form.TriggerField.superclass.onFocus.call(this);
+ if(!this.mimicing){
+ this.wrap.addClass('x-trigger-wrap-focus');
+ this.mimicing = true;
+ Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
+ if(this.monitorTab){
+ this.el.on("keydown", this.checkTab, this);
}
}
- this.fireEvent("mouseover", this, e, t);
},
// private
- onMouseOut : function(e){
- var t;
- if(t = this.findTargetItem(e)){
- if(t == this.activeItem && t.shouldDeactivate(e)){
- this.activeItem.deactivate();
- delete this.activeItem;
- }
+ checkTab : function(e){
+ if(e.getKey() == e.TAB){
+ this.triggerBlur();
}
- this.fireEvent("mouseout", this, e, t);
},
- /**
- * Read-only. Returns true if the menu is currently displayed, else false.
- * @type Boolean
- */
- isVisible : function(){
- return this.el && !this.hidden;
+ // private
+ onBlur : function(){
+ // do nothing
},
- /**
- * Displays this menu relative to another element
- * @param {String/HTMLElement/Roo.Element} element The element to align to
- * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
- * the element (defaults to this.defaultAlign)
- * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
- */
- show : function(el, pos, parentMenu){
- this.parentMenu = parentMenu;
- if(!this.el){
- this.render();
+ // private
+ mimicBlur : function(e, t){
+ if(!this.wrap.contains(t) && this.validateBlur()){
+ this.triggerBlur();
}
- this.fireEvent("beforeshow", this);
- this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
},
- /**
- * Displays this menu at a specific xy position
- * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
- * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
- */
- showAt : function(xy, parentMenu, /* private: */_e){
- this.parentMenu = parentMenu;
- if(!this.el){
- this.render();
- }
- if(_e !== false){
- this.fireEvent("beforeshow", this);
- xy = this.el.adjustForConstraints(xy);
+ // private
+ triggerBlur : function(){
+ this.mimicing = false;
+ Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
+ if(this.monitorTab){
+ this.el.un("keydown", this.checkTab, this);
}
- this.el.setXY(xy);
- this.el.show();
- this.hidden = false;
- this.focus();
- this.fireEvent("show", this);
+ this.wrap.removeClass('x-trigger-wrap-focus');
+ Roo.form.TriggerField.superclass.onBlur.call(this);
},
- focus : function(){
- if(!this.hidden){
- this.doFocus.defer(50, this);
- }
+ // private
+ // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
+ validateBlur : function(e, t){
+ return true;
},
- doFocus : function(){
- if(!this.hidden){
- this.focusEl.focus();
+ // private
+ onDisable : function(){
+ Roo.form.TriggerField.superclass.onDisable.call(this);
+ if(this.wrap){
+ this.wrap.addClass('x-item-disabled');
}
},
- /**
- * Hides this menu and optionally all parent menus
- * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
- */
- hide : function(deep){
- if(this.el && this.isVisible()){
- this.fireEvent("beforehide", this);
- if(this.activeItem){
- this.activeItem.deactivate();
- this.activeItem = null;
- }
- this.el.hide();
- this.hidden = true;
- this.fireEvent("hide", this);
- }
- if(deep === true && this.parentMenu){
- this.parentMenu.hide(true);
+ // private
+ onEnable : function(){
+ Roo.form.TriggerField.superclass.onEnable.call(this);
+ if(this.wrap){
+ this.wrap.removeClass('x-item-disabled');
}
},
- /**
- * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
- * Any of the following are valid:
- * <ul>
- * <li>Any menu item object based on {@link Roo.menu.Item}</li>
- * <li>An HTMLElement object which will be converted to a menu item</li>
- * <li>A menu item config object that will be created as a new menu item</li>
- * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
- * it will be converted into a {@link Roo.menu.TextItem} and added</li>
- * </ul>
- * Usage:
- * <pre><code>
-// Create the menu
-var menu = new Roo.menu.Menu();
-
-// Create a menu item to add by reference
-var menuItem = new Roo.menu.Item({ text: 'New Item!' });
-
-// Add a bunch of items at once using different methods.
-// Only the last item added will be returned.
-var item = menu.add(
- menuItem, // add existing item by ref
- 'Dynamic Item', // new TextItem
- '-', // new separator
- { text: 'Config Item' } // new item by config
-);
-</code></pre>
- * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
- * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
- */
- add : function(){
- var a = arguments, l = a.length, item;
- for(var i = 0; i < l; i++){
- var el = a[i];
- if ((typeof(el) == "object") && el.xtype && el.xns) {
- el = Roo.factory(el, Roo.menu);
- }
-
- if(el.render){ // some kind of Item
- item = this.addItem(el);
- }else if(typeof el == "string"){ // string
- if(el == "separator" || el == "-"){
- item = this.addSeparator();
- }else{
- item = this.addText(el);
- }
- }else if(el.tagName || el.el){ // element
- item = this.addElement(el);
- }else if(typeof el == "object"){ // must be menu item config?
- item = this.addMenuItem(el);
- }
+ // private
+ onShow : function(){
+ var ae = this.getActionEl();
+
+ if(ae){
+ ae.dom.style.display = '';
+ ae.dom.style.visibility = 'visible';
}
- return item;
},
- /**
- * Returns this menu's underlying {@link Roo.Element} object
- * @return {Roo.Element} The element
- */
- getEl : function(){
- if(!this.el){
- this.render();
- }
- return this.el;
+ // private
+
+ onHide : function(){
+ var ae = this.getActionEl();
+ ae.dom.style.display = 'none';
},
/**
- * Adds a separator bar to the menu
- * @return {Roo.menu.Item} The menu item that was added
+ * The function that should handle the trigger's click event. This method does nothing by default until overridden
+ * by an implementing function.
+ * @method
+ * @param {EventObject} e
*/
- addSeparator : function(){
- return this.addItem(new Roo.menu.Separator());
- },
+ onTriggerClick : Roo.emptyFn
+});
- /**
- * Adds an {@link Roo.Element} object to the menu
- * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
- * @return {Roo.menu.Item} The menu item that was added
- */
- addElement : function(el){
- return this.addItem(new Roo.menu.BaseItem(el));
+// TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
+// to be extended by an implementing class. For an example of implementing this class, see the custom
+// SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
+Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
+ initComponent : function(){
+ Roo.form.TwinTriggerField.superclass.initComponent.call(this);
+
+ this.triggerConfig = {
+ tag:'span', cls:'x-form-twin-triggers', cn:[
+ {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
+ {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
+ ]};
},
- /**
- * Adds an existing object based on {@link Roo.menu.Item} to the menu
- * @param {Roo.menu.Item} item The menu item to add
- * @return {Roo.menu.Item} The menu item that was added
- */
- addItem : function(item){
- this.items.add(item);
- if(this.ul){
- var li = document.createElement("li");
- li.className = "x-menu-list-item";
- this.ul.dom.appendChild(li);
- item.render(li, this);
- this.delayAutoWidth();
- }
- return item;
+ getTrigger : function(index){
+ return this.triggers[index];
},
- /**
- * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
- * @param {Object} config A MenuItem config object
- * @return {Roo.menu.Item} The menu item that was added
- */
- addMenuItem : function(config){
- if(!(config instanceof Roo.menu.Item)){
- if(typeof config.checked == "boolean"){ // must be check menu item config?
- config = new Roo.menu.CheckItem(config);
- }else{
- config = new Roo.menu.Item(config);
+ initTrigger : function(){
+ var ts = this.trigger.select('.x-form-trigger', true);
+ this.wrap.setStyle('overflow', 'hidden');
+ var triggerField = this;
+ ts.each(function(t, all, index){
+ t.hide = function(){
+ var w = triggerField.wrap.getWidth();
+ this.dom.style.display = 'none';
+ triggerField.el.setWidth(w-triggerField.trigger.getWidth());
+ };
+ t.show = function(){
+ var w = triggerField.wrap.getWidth();
+ this.dom.style.display = '';
+ triggerField.el.setWidth(w-triggerField.trigger.getWidth());
+ };
+ var triggerIndex = 'Trigger'+(index+1);
+
+ if(this['hide'+triggerIndex]){
+ t.dom.style.display = 'none';
}
- }
- return this.addItem(config);
+ t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
+ t.addClassOnOver('x-form-trigger-over');
+ t.addClassOnClick('x-form-trigger-click');
+ }, this);
+ this.triggers = ts.elements;
},
+ onTrigger1Click : Roo.emptyFn,
+ onTrigger2Click : Roo.emptyFn
+});/*
+ * Based on:
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ *
+ * Originally Released Under LGPL - original licence link has changed is not relivant.
+ *
+ * Fork - LGPL
+ * <script type="text/javascript">
+ */
+
+/**
+ * @class Roo.form.TextArea
+ * @extends Roo.form.TextField
+ * Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
+ * support for auto-sizing.
+ * @constructor
+ * Creates a new TextArea
+ * @param {Object} config Configuration options
+ */
+Roo.form.TextArea = function(config){
+ Roo.form.TextArea.superclass.constructor.call(this, config);
+ // these are provided exchanges for backwards compat
+ // minHeight/maxHeight were replaced by growMin/growMax to be
+ // compatible with TextField growing config values
+ if(this.minHeight !== undefined){
+ this.growMin = this.minHeight;
+ }
+ if(this.maxHeight !== undefined){
+ this.growMax = this.maxHeight;
+ }
+};
+
+Roo.extend(Roo.form.TextArea, Roo.form.TextField, {
/**
- * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
- * @param {String} text The text to display in the menu item
- * @return {Roo.menu.Item} The menu item that was added
+ * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
*/
- addText : function(text){
- return this.addItem(new Roo.menu.TextItem({ text : text }));
- },
-
+ growMin : 60,
/**
- * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
- * @param {Number} index The index in the menu's list of current items where the new item should be inserted
- * @param {Roo.menu.Item} item The menu item to add
- * @return {Roo.menu.Item} The menu item that was added
+ * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
*/
- insert : function(index, item){
- this.items.insert(index, item);
- if(this.ul){
- var li = document.createElement("li");
- li.className = "x-menu-list-item";
- this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
- item.render(li, this);
- this.delayAutoWidth();
- }
- return item;
- },
-
+ growMax: 1000,
/**
- * Removes an {@link Roo.menu.Item} from the menu and destroys the object
- * @param {Roo.menu.Item} item The menu item to remove
+ * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
+ * in the field (equivalent to setting overflow: hidden, defaults to false)
*/
- remove : function(item){
- this.items.removeKey(item.id);
- item.destroy();
- },
-
+ preventScrollbars: false,
/**
- * Removes and destroys all items in the menu
+ * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
+ * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
*/
- removeAll : function(){
- var f;
- while(f = this.items.first()){
- this.remove(f);
- }
- }
-});
-// MenuNav is a private utility class used internally by the Menu
-Roo.menu.MenuNav = function(menu){
- Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
- this.scope = this.menu = menu;
-};
-
-Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
- doRelay : function(e, h){
- var k = e.getKey();
- if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
- this.menu.tryActivate(0, 1);
- return false;
+ // private
+ onRender : function(ct, position){
+ if(!this.el){
+ this.defaultAutoCreate = {
+ tag: "textarea",
+ style:"width:300px;height:60px;",
+ autocomplete: "new-password"
+ };
}
- return h.call(this.scope || this, e, this.menu);
- },
-
- up : function(e, m){
- if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
- m.tryActivate(m.items.length-1, -1);
+ Roo.form.TextArea.superclass.onRender.call(this, ct, position);
+ if(this.grow){
+ this.textSizeEl = Roo.DomHelper.append(document.body, {
+ tag: "pre", cls: "x-form-grow-sizer"
+ });
+ if(this.preventScrollbars){
+ this.el.setStyle("overflow", "hidden");
+ }
+ this.el.setHeight(this.growMin);
}
},
- down : function(e, m){
- if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
- m.tryActivate(0, 1);
+ onDestroy : function(){
+ if(this.textSizeEl){
+ this.textSizeEl.parentNode.removeChild(this.textSizeEl);
}
+ Roo.form.TextArea.superclass.onDestroy.call(this);
},
- right : function(e, m){
- if(m.activeItem){
- m.activeItem.expandMenu(true);
+ // private
+ onKeyUp : function(e){
+ if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
+ this.autoSize();
}
},
- left : function(e, m){
- m.hide();
- if(m.parentMenu && m.parentMenu.activeItem){
- m.parentMenu.activeItem.activate();
+ /**
+ * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
+ * This only takes effect if grow = true, and fires the autosize event if the height changes.
+ */
+ autoSize : function(){
+ if(!this.grow || !this.textSizeEl){
+ return;
}
- },
+ var el = this.el;
+ var v = el.dom.value;
+ var ts = this.textSizeEl;
- enter : function(e, m){
- if(m.activeItem){
- e.stopPropagation();
- m.activeItem.onClick(e);
- m.fireEvent("click", this, m.activeItem);
- return true;
+ ts.innerHTML = '';
+ ts.appendChild(document.createTextNode(v));
+ v = ts.innerHTML;
+
+ Roo.fly(ts).setWidth(this.el.getWidth());
+ if(v.length < 1){
+ v = "  ";
+ }else{
+ if(Roo.isIE){
+ v = v.replace(/\n/g, '<p> </p>');
+ }
+ v += " \n ";
+ }
+ ts.innerHTML = v;
+ var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
+ if(h != this.lastHeight){
+ this.lastHeight = h;
+ this.el.setHeight(h);
+ this.fireEvent("autosize", this, h);
}
}
});/*
* <script type="text/javascript">
*/
+
/**
- * @class Roo.menu.MenuMgr
- * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
- * @static
+ * @class Roo.form.NumberField
+ * @extends Roo.form.TextField
+ * Numeric text field that provides automatic keystroke filtering and numeric validation.
+ * @constructor
+ * Creates a new NumberField
+ * @param {Object} config Configuration options
*/
-Roo.menu.MenuMgr = function(){
- var menus, active, groups = {}, attached = false, lastShow = new Date();
-
- // private - called when first menu is created
- function init(){
- menus = {};
- active = new Roo.util.MixedCollection();
- Roo.get(document).addKeyListener(27, function(){
- if(active.length > 0){
- hideAll();
- }
- });
- }
-
- // private
- function hideAll(){
- if(active && active.length > 0){
- var c = active.clone();
- c.each(function(m){
- m.hide();
- });
- }
- }
-
- // private
- function onHide(m){
- active.remove(m);
- if(active.length < 1){
- Roo.get(document).un("mousedown", onMouseDown);
- attached = false;
- }
- }
-
- // private
- function onShow(m){
- var last = active.last();
- lastShow = new Date();
- active.add(m);
- if(!attached){
- Roo.get(document).on("mousedown", onMouseDown);
- attached = true;
- }
- if(m.parentMenu){
- m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
- m.parentMenu.activeChild = m;
- }else if(last && last.isVisible()){
- m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
- }
- }
-
- // private
- function onBeforeHide(m){
- if(m.activeChild){
- m.activeChild.hide();
- }
- if(m.autoHideTimer){
- clearTimeout(m.autoHideTimer);
- delete m.autoHideTimer;
- }
- }
-
- // private
- function onBeforeShow(m){
- var pm = m.parentMenu;
- if(!pm && !m.allowOtherMenus){
- hideAll();
- }else if(pm && pm.activeChild && active != m){
- pm.activeChild.hide();
- }
- }
-
- // private
- function onMouseDown(e){
- if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
- hideAll();
- }
- }
+Roo.form.NumberField = function(config){
+ Roo.form.NumberField.superclass.constructor.call(this, config);
+};
- // private
- function onBeforeCheck(mi, state){
- if(state){
- var g = groups[mi.group];
- for(var i = 0, l = g.length; i < l; i++){
- if(g[i] != mi){
- g[i].setChecked(false);
- }
- }
- }
- }
+Roo.extend(Roo.form.NumberField, Roo.form.TextField, {
+ /**
+ * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
+ */
+ fieldClass: "x-form-field x-form-num-field",
+ /**
+ * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
+ */
+ allowDecimals : true,
+ /**
+ * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
+ */
+ decimalSeparator : ".",
+ /**
+ * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
+ */
+ decimalPrecision : 2,
+ /**
+ * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
+ */
+ allowNegative : true,
+ /**
+ * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
+ */
+ minValue : Number.NEGATIVE_INFINITY,
+ /**
+ * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
+ */
+ maxValue : Number.MAX_VALUE,
+ /**
+ * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
+ */
+ minText : "The minimum value for this field is {0}",
+ /**
+ * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
+ */
+ maxText : "The maximum value for this field is {0}",
+ /**
+ * @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
+ * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
+ */
+ nanText : "{0} is not a valid number",
- return {
+ // private
+ initEvents : function(){
+ Roo.form.NumberField.superclass.initEvents.call(this);
+ var allowed = "0123456789";
+ if(this.allowDecimals){
+ allowed += this.decimalSeparator;
+ }
+ if(this.allowNegative){
+ allowed += "-";
+ }
+ this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
+ var keyPress = function(e){
+ var k = e.getKey();
+ if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
+ return;
+ }
+ var c = e.getCharCode();
+ if(allowed.indexOf(String.fromCharCode(c)) === -1){
+ e.stopEvent();
+ }
+ };
+ this.el.on("keypress", keyPress, this);
+ },
- /**
- * Hides all menus that are currently visible
- */
- hideAll : function(){
- hideAll();
- },
+ // private
+ validateValue : function(value){
+ if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
+ return false;
+ }
+ if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
+ return true;
+ }
+ var num = this.parseValue(value);
+ if(isNaN(num)){
+ this.markInvalid(String.format(this.nanText, value));
+ return false;
+ }
+ if(num < this.minValue){
+ this.markInvalid(String.format(this.minText, this.minValue));
+ return false;
+ }
+ if(num > this.maxValue){
+ this.markInvalid(String.format(this.maxText, this.maxValue));
+ return false;
+ }
+ return true;
+ },
- // private
- register : function(menu){
- if(!menus){
- init();
- }
- menus[menu.id] = menu;
- menu.on("beforehide", onBeforeHide);
- menu.on("hide", onHide);
- menu.on("beforeshow", onBeforeShow);
- menu.on("show", onShow);
- var g = menu.group;
- if(g && menu.events["checkchange"]){
- if(!groups[g]){
- groups[g] = [];
- }
- groups[g].push(menu);
- menu.on("checkchange", onCheck);
- }
- },
+ getValue : function(){
+ return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
+ },
- /**
- * Returns a {@link Roo.menu.Menu} object
- * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
- * be used to generate and return a new Menu instance.
- */
- get : function(menu){
- if(typeof menu == "string"){ // menu id
- return menus[menu];
- }else if(menu.events){ // menu instance
- return menu;
- }else if(typeof menu.length == 'number'){ // array of menu items?
- return new Roo.menu.Menu({items:menu});
- }else{ // otherwise, must be a config
- return new Roo.menu.Menu(menu);
- }
- },
+ // private
+ parseValue : function(value){
+ value = parseFloat(String(value).replace(this.decimalSeparator, "."));
+ return isNaN(value) ? '' : value;
+ },
- // private
- unregister : function(menu){
- delete menus[menu.id];
- menu.un("beforehide", onBeforeHide);
- menu.un("hide", onHide);
- menu.un("beforeshow", onBeforeShow);
- menu.un("show", onShow);
- var g = menu.group;
- if(g && menu.events["checkchange"]){
- groups[g].remove(menu);
- menu.un("checkchange", onCheck);
- }
- },
+ // private
+ fixPrecision : function(value){
+ var nan = isNaN(value);
+ if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
+ return nan ? '' : value;
+ }
+ return parseFloat(value).toFixed(this.decimalPrecision);
+ },
- // private
- registerCheckable : function(menuItem){
- var g = menuItem.group;
- if(g){
- if(!groups[g]){
- groups[g] = [];
- }
- groups[g].push(menuItem);
- menuItem.on("beforecheckchange", onBeforeCheck);
- }
- },
+ setValue : function(v){
+ v = this.fixPrecision(v);
+ Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
+ },
- // private
- unregisterCheckable : function(menuItem){
- var g = menuItem.group;
- if(g){
- groups[g].remove(menuItem);
- menuItem.un("beforecheckchange", onBeforeCheck);
- }
- }
- };
-}();/*
+ // private
+ decimalPrecisionFcn : function(v){
+ return Math.floor(v);
+ },
+
+ beforeBlur : function(){
+ var v = this.parseValue(this.getRawValue());
+ if(v){
+ this.setValue(v);
+ }
+ }
+});/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* <script type="text/javascript">
*/
-
/**
- * @class Roo.menu.BaseItem
- * @extends Roo.Component
- * @abstract
- * The base class for all items that render into menus. BaseItem provides default rendering, activated state
- * management and base configuration options shared by all menu components.
- * @constructor
- * Creates a new BaseItem
- * @param {Object} config Configuration options
+ * @class Roo.form.DateField
+ * @extends Roo.form.TriggerField
+ * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
+* @constructor
+* Create a new DateField
+* @param {Object} config
*/
-Roo.menu.BaseItem = function(config){
- Roo.menu.BaseItem.superclass.constructor.call(this, config);
-
- this.addEvents({
- /**
- * @event click
- * Fires when this item is clicked
- * @param {Roo.menu.BaseItem} this
- * @param {Roo.EventObject} e
- */
- click: true,
- /**
- * @event activate
- * Fires when this item is activated
- * @param {Roo.menu.BaseItem} this
- */
- activate : true,
+Roo.form.DateField = function(config)
+{
+ Roo.form.DateField.superclass.constructor.call(this, config);
+
+ this.addEvents({
+
/**
- * @event deactivate
- * Fires when this item is deactivated
- * @param {Roo.menu.BaseItem} this
- */
- deactivate : true
+ * @event select
+ * Fires when a date is selected
+ * @param {Roo.form.DateField} combo This combo box
+ * @param {Date} date The date selected
+ */
+ 'select' : true
+
});
-
- if(this.handler){
- this.on("click", this.handler, this.scope, true);
+
+
+ if(typeof this.minValue == "string") {
+ this.minValue = this.parseDate(this.minValue);
+ }
+ if(typeof this.maxValue == "string") {
+ this.maxValue = this.parseDate(this.maxValue);
+ }
+ this.ddMatch = null;
+ if(this.disabledDates){
+ var dd = this.disabledDates;
+ var re = "(?:";
+ for(var i = 0; i < dd.length; i++){
+ re += dd[i];
+ if(i != dd.length-1) {
+ re += "|";
+ }
+ }
+ this.ddMatch = new RegExp(re + ")");
}
};
-Roo.extend(Roo.menu.BaseItem, Roo.Component, {
+Roo.extend(Roo.form.DateField, Roo.form.TriggerField, {
/**
- * @cfg {Function} handler
- * A function that will handle the click event of this menu item (defaults to undefined)
+ * @cfg {String} format
+ * The default date format string which can be overriden for localization support. The format must be
+ * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
*/
+ format : "m/d/y",
/**
- * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
+ * @cfg {String} altFormats
+ * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
+ * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
*/
- canActivate : false,
-
- /**
- * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
+ altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
+ /**
+ * @cfg {Array} disabledDays
+ * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
*/
- hidden: false,
-
+ disabledDays : null,
/**
- * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
+ * @cfg {String} disabledDaysText
+ * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
*/
- activeClass : "x-menu-item-active",
+ disabledDaysText : "Disabled",
/**
- * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
+ * @cfg {Array} disabledDates
+ * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
+ * expression so they are very powerful. Some examples:
+ * <ul>
+ * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
+ * <li>["03/08", "09/16"] would disable those days for every year</li>
+ * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
+ * <li>["03/../2006"] would disable every day in March 2006</li>
+ * <li>["^03"] would disable every day in every March</li>
+ * </ul>
+ * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
+ * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
*/
- hideOnClick : true,
+ disabledDates : null,
/**
- * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
+ * @cfg {String} disabledDatesText
+ * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
*/
- hideDelay : 100,
-
- // private
- ctype: "Roo.menu.BaseItem",
-
- // private
- actionMode : "container",
-
- // private
- render : function(container, parentMenu){
- this.parentMenu = parentMenu;
- Roo.menu.BaseItem.superclass.render.call(this, container);
- this.container.menuItemId = this.id;
- },
+ disabledDatesText : "Disabled",
+
+
+ /**
+ * @cfg {Date/String} zeroValue
+ * if the date is less that this number, then the field is rendered as empty
+ * default is 1800
+ */
+ zeroValue : '1800-01-01',
+
+
+ /**
+ * @cfg {Date/String} minValue
+ * The minimum allowed date. Can be either a Javascript date object or a string date in a
+ * valid format (defaults to null).
+ */
+ minValue : null,
+ /**
+ * @cfg {Date/String} maxValue
+ * The maximum allowed date. Can be either a Javascript date object or a string date in a
+ * valid format (defaults to null).
+ */
+ maxValue : null,
+ /**
+ * @cfg {String} minText
+ * The error text to display when the date in the cell is before minValue (defaults to
+ * 'The date in this field must be after {minValue}').
+ */
+ minText : "The date in this field must be equal to or after {0}",
+ /**
+ * @cfg {String} maxText
+ * The error text to display when the date in the cell is after maxValue (defaults to
+ * 'The date in this field must be before {maxValue}').
+ */
+ maxText : "The date in this field must be equal to or before {0}",
+ /**
+ * @cfg {String} invalidText
+ * The error text to display when the date in the field is invalid (defaults to
+ * '{value} is not a valid date - it must be in the format {format}').
+ */
+ invalidText : "{0} is not a valid date - it must be in the format {1}",
+ /**
+ * @cfg {String} triggerClass
+ * An additional CSS class used to style the trigger button. The trigger will always get the
+ * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
+ * which displays a calendar icon).
+ */
+ triggerClass : 'x-form-date-trigger',
+
+ /**
+ * @cfg {Boolean} useIso
+ * if enabled, then the date field will use a hidden field to store the
+ * real value as iso formated date. default (false)
+ */
+ useIso : false,
+ /**
+ * @cfg {String/Object} autoCreate
+ * A DomHelper element spec, or true for a default element spec (defaults to
+ * {tag: "input", type: "text", size: "10", autocomplete: "off"})
+ */
// private
- onRender : function(container, position){
- this.el = Roo.get(this.el);
- container.dom.appendChild(this.el.dom);
- },
-
+ defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
+
// private
- onClick : function(e){
- if(!this.disabled && this.fireEvent("click", this, e) !== false
- && this.parentMenu.fireEvent("itemclick", this, e) !== false){
- this.handleClick(e);
- }else{
- e.stopEvent();
+ hiddenField: false,
+
+ onRender : function(ct, position)
+ {
+ Roo.form.DateField.superclass.onRender.call(this, ct, position);
+ if (this.useIso) {
+ //this.el.dom.removeAttribute('name');
+ Roo.log("Changing name?");
+ this.el.dom.setAttribute('name', this.name + '____hidden___' );
+ this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
+ 'before', true);
+ this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
+ // prevent input submission
+ this.hiddenName = this.name;
}
+
+
},
-
+
// private
- activate : function(){
- if(this.disabled){
+ validateValue : function(value)
+ {
+ value = this.formatDate(value);
+ if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
+ Roo.log('super failed');
+ return false;
+ }
+ if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
+ return true;
+ }
+ var svalue = value;
+ value = this.parseDate(value);
+ if(!value){
+ Roo.log('parse date failed' + svalue);
+ this.markInvalid(String.format(this.invalidText, svalue, this.format));
+ return false;
+ }
+ var time = value.getTime();
+ if(this.minValue && time < this.minValue.getTime()){
+ this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
+ return false;
+ }
+ if(this.maxValue && time > this.maxValue.getTime()){
+ this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
+ return false;
+ }
+ if(this.disabledDays){
+ var day = value.getDay();
+ for(var i = 0; i < this.disabledDays.length; i++) {
+ if(day === this.disabledDays[i]){
+ this.markInvalid(this.disabledDaysText);
+ return false;
+ }
+ }
+ }
+ var fvalue = this.formatDate(value);
+ if(this.ddMatch && this.ddMatch.test(fvalue)){
+ this.markInvalid(String.format(this.disabledDatesText, fvalue));
return false;
}
- var li = this.container;
- li.addClass(this.activeClass);
- this.region = li.getRegion().adjust(2, 2, -2, -2);
- this.fireEvent("activate", this);
return true;
},
// private
- deactivate : function(){
- this.container.removeClass(this.activeClass);
- this.fireEvent("deactivate", this);
+ // Provides logic to override the default TriggerField.validateBlur which just returns true
+ validateBlur : function(){
+ return !this.menu || !this.menu.isVisible();
+ },
+
+ getName: function()
+ {
+ // returns hidden if it's set..
+ if (!this.rendered) {return ''};
+ return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
+
},
- // private
- shouldDeactivate : function(e){
- return !this.region || !this.region.contains(e.getPoint());
+ /**
+ * Returns the current date value of the date field.
+ * @return {Date} The date value
+ */
+ getValue : function(){
+
+ return this.hiddenField ?
+ this.hiddenField.value :
+ this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
},
- // private
- handleClick : function(e){
- if(this.hideOnClick){
- this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
+ /**
+ * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
+ * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
+ * (the default format used is "m/d/y").
+ * <br />Usage:
+ * <pre><code>
+//All of these calls set the same date value (May 4, 2006)
+
+//Pass a date object:
+var dt = new Date('5/4/06');
+dateField.setValue(dt);
+
+//Pass a date string (default format):
+dateField.setValue('5/4/06');
+
+//Pass a date string (custom format):
+dateField.format = 'Y-m-d';
+dateField.setValue('2006-5-4');
+</code></pre>
+ * @param {String/Date} date The date or valid date string
+ */
+ setValue : function(date){
+ if (this.hiddenField) {
+ this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
}
+ Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
+ // make sure the value field is always stored as a date..
+ this.value = this.parseDate(date);
+
+
},
// private
- expandMenu : function(autoActivate){
- // do nothing
+ parseDate : function(value){
+
+ if (value instanceof Date) {
+ if (value < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
+ return '';
+ }
+ return value;
+ }
+
+
+ if(!value || value instanceof Date){
+ return value;
+ }
+ var v = Date.parseDate(value, this.format);
+ if (!v && this.useIso) {
+ v = Date.parseDate(value, 'Y-m-d');
+ }
+ if(!v && this.altFormats){
+ if(!this.altFormatsArray){
+ this.altFormatsArray = this.altFormats.split("|");
+ }
+ for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
+ v = Date.parseDate(value, this.altFormatsArray[i]);
+ }
+ }
+ if (v < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
+ v = '';
+ }
+ return v;
},
// private
- hideMenu : function(){
- // do nothing
- }
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-/**
- * @class Roo.menu.Adapter
- * @extends Roo.menu.BaseItem
- * @abstract
- * 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.
- * It provides basic rendering, activation management and enable/disable logic required to work in menus.
- * @constructor
- * Creates a new Adapter
- * @param {Object} config Configuration options
- */
-Roo.menu.Adapter = function(component, config){
- Roo.menu.Adapter.superclass.constructor.call(this, config);
- this.component = component;
-};
-Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
- // private
- canActivate : true,
+ formatDate : function(date, fmt){
+ return (!date || !(date instanceof Date)) ?
+ date : date.dateFormat(fmt || this.format);
+ },
// private
- onRender : function(container, position){
- this.component.render(container);
- this.el = this.component.getEl();
+ menuListeners : {
+ select: function(m, d){
+
+ this.setValue(d);
+ this.fireEvent('select', this, d);
+ },
+ show : function(){ // retain focus styling
+ this.onFocus();
+ },
+ hide : function(){
+ this.focus.defer(10, this);
+ var ml = this.menuListeners;
+ this.menu.un("select", ml.select, this);
+ this.menu.un("show", ml.show, this);
+ this.menu.un("hide", ml.hide, this);
+ }
},
// private
- activate : function(){
+ // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
+ onTriggerClick : function(){
if(this.disabled){
+ return;
+ }
+ if(this.menu == null){
+ this.menu = new Roo.menu.DateMenu();
+ }
+ Roo.apply(this.menu.picker, {
+ showClear: this.allowBlank,
+ minDate : this.minValue,
+ maxDate : this.maxValue,
+ disabledDatesRE : this.ddMatch,
+ disabledDatesText : this.disabledDatesText,
+ disabledDays : this.disabledDays,
+ disabledDaysText : this.disabledDaysText,
+ format : this.useIso ? 'Y-m-d' : this.format,
+ minText : String.format(this.minText, this.formatDate(this.minValue)),
+ maxText : String.format(this.maxText, this.formatDate(this.maxValue))
+ });
+ this.menu.on(Roo.apply({}, this.menuListeners, {
+ scope:this
+ }));
+ this.menu.picker.setValue(this.getValue() || new Date());
+ this.menu.show(this.el, "tl-bl?");
+ },
+
+ beforeBlur : function(){
+ var v = this.parseDate(this.getRawValue());
+ if(v){
+ this.setValue(v);
+ }
+ },
+
+ /*@
+ * overide
+ *
+ */
+ isDirty : function() {
+ if(this.disabled) {
+ return false;
+ }
+
+ if(typeof(this.startValue) === 'undefined'){
return false;
}
- this.component.focus();
- this.fireEvent("activate", this);
- return true;
- },
-
- // private
- deactivate : function(){
- this.fireEvent("deactivate", this);
- },
-
- // private
- disable : function(){
- this.component.disable();
- Roo.menu.Adapter.superclass.disable.call(this);
+
+ return String(this.getValue()) !== String(this.startValue);
+
},
-
- // private
- enable : function(){
- this.component.enable();
- Roo.menu.Adapter.superclass.enable.call(this);
+ // @overide
+ cleanLeadingSpace : function(e)
+ {
+ return;
}
+
});/*
* Based on:
* Ext JS Library 1.1.1
* Fork - LGPL
* <script type="text/javascript">
*/
-
+
/**
- * @class Roo.menu.TextItem
- * @extends Roo.menu.BaseItem
- * Adds a static text string to a menu, usually used as either a heading or group separator.
- * Note: old style constructor with text is still supported.
- *
- * @constructor
- * Creates a new TextItem
- * @param {Object} cfg Configuration
+ * @class Roo.form.MonthField
+ * @extends Roo.form.TriggerField
+ * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
+* @constructor
+* Create a new MonthField
+* @param {Object} config
*/
-Roo.menu.TextItem = function(cfg){
- if (typeof(cfg) == 'string') {
- this.text = cfg;
- } else {
- Roo.apply(this,cfg);
- }
+Roo.form.MonthField = function(config){
- Roo.menu.TextItem.superclass.constructor.call(this);
+ Roo.form.MonthField.superclass.constructor.call(this, config);
+
+ this.addEvents({
+
+ /**
+ * @event select
+ * Fires when a date is selected
+ * @param {Roo.form.MonthFieeld} combo This combo box
+ * @param {Date} date The date selected
+ */
+ 'select' : true
+
+ });
+
+
+ if(typeof this.minValue == "string") {
+ this.minValue = this.parseDate(this.minValue);
+ }
+ if(typeof this.maxValue == "string") {
+ this.maxValue = this.parseDate(this.maxValue);
+ }
+ this.ddMatch = null;
+ if(this.disabledDates){
+ var dd = this.disabledDates;
+ var re = "(?:";
+ for(var i = 0; i < dd.length; i++){
+ re += dd[i];
+ if(i != dd.length-1) {
+ re += "|";
+ }
+ }
+ this.ddMatch = new RegExp(re + ")");
+ }
};
-Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
+Roo.extend(Roo.form.MonthField, Roo.form.TriggerField, {
/**
- * @cfg {String} text Text to show on item.
+ * @cfg {String} format
+ * The default date format string which can be overriden for localization support. The format must be
+ * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
*/
- text : '',
-
+ format : "M Y",
/**
- * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
+ * @cfg {String} altFormats
+ * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
+ * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
*/
- hideOnClick : false,
+ altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
/**
- * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
+ * @cfg {Array} disabledDays
+ * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
*/
- itemCls : "x-menu-text",
-
- // private
- onRender : function(){
- var s = document.createElement("span");
- s.className = this.itemCls;
- s.innerHTML = this.text;
- this.el = s;
- Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
- }
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-/**
- * @class Roo.menu.Separator
- * @extends Roo.menu.BaseItem
- * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
- * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
- * @constructor
- * @param {Object} config Configuration options
- */
-Roo.menu.Separator = function(config){
- Roo.menu.Separator.superclass.constructor.call(this, config);
-};
-
-Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
+ disabledDays : [0,1,2,3,4,5,6],
/**
- * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
+ * @cfg {String} disabledDaysText
+ * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
*/
- itemCls : "x-menu-sep",
+ disabledDaysText : "Disabled",
/**
- * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
+ * @cfg {Array} disabledDates
+ * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
+ * expression so they are very powerful. Some examples:
+ * <ul>
+ * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
+ * <li>["03/08", "09/16"] would disable those days for every year</li>
+ * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
+ * <li>["03/../2006"] would disable every day in March 2006</li>
+ * <li>["^03"] would disable every day in every March</li>
+ * </ul>
+ * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
+ * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
*/
- hideOnClick : false,
-
- // private
- onRender : function(li){
- var s = document.createElement("span");
- s.className = this.itemCls;
- s.innerHTML = " ";
- this.el = s;
- li.addClass("x-menu-sep-li");
- Roo.menu.Separator.superclass.onRender.apply(this, arguments);
- }
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-/**
- * @class Roo.menu.Item
- * @extends Roo.menu.BaseItem
- * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
- * display items. Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
- * activation and click handling.
- * @constructor
- * Creates a new Item
- * @param {Object} config Configuration options
- */
-Roo.menu.Item = function(config){
- Roo.menu.Item.superclass.constructor.call(this, config);
- if(this.menu){
- this.menu = Roo.menu.MenuMgr.get(this.menu);
- }
-};
-Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
+ disabledDates : null,
/**
- * @cfg {Roo.menu.Menu} menu
- * A Sub menu
+ * @cfg {String} disabledDatesText
+ * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
*/
+ disabledDatesText : "Disabled",
/**
- * @cfg {String} text
- * The text to show on the menu item.
+ * @cfg {Date/String} minValue
+ * The minimum allowed date. Can be either a Javascript date object or a string date in a
+ * valid format (defaults to null).
*/
- text: '',
- /**
- * @cfg {String} html to render in menu
- * The text to show on the menu item (HTML version).
+ minValue : null,
+ /**
+ * @cfg {Date/String} maxValue
+ * The maximum allowed date. Can be either a Javascript date object or a string date in a
+ * valid format (defaults to null).
*/
- html: '',
+ maxValue : null,
/**
- * @cfg {String} icon
- * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
+ * @cfg {String} minText
+ * The error text to display when the date in the cell is before minValue (defaults to
+ * 'The date in this field must be after {minValue}').
*/
- icon: undefined,
+ minText : "The date in this field must be equal to or after {0}",
/**
- * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
+ * @cfg {String} maxTextf
+ * The error text to display when the date in the cell is after maxValue (defaults to
+ * 'The date in this field must be before {maxValue}').
*/
- itemCls : "x-menu-item",
+ maxText : "The date in this field must be equal to or before {0}",
/**
- * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
+ * @cfg {String} invalidText
+ * The error text to display when the date in the field is invalid (defaults to
+ * '{value} is not a valid date - it must be in the format {format}').
*/
- canActivate : true,
+ invalidText : "{0} is not a valid date - it must be in the format {1}",
/**
- * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
+ * @cfg {String} triggerClass
+ * An additional CSS class used to style the trigger button. The trigger will always get the
+ * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
+ * which displays a calendar icon).
*/
- showDelay: 200,
- // doc'd in BaseItem
- hideDelay: 200,
+ triggerClass : 'x-form-date-trigger',
+
+ /**
+ * @cfg {Boolean} useIso
+ * if enabled, then the date field will use a hidden field to store the
+ * real value as iso formated date. default (true)
+ */
+ useIso : true,
+ /**
+ * @cfg {String/Object} autoCreate
+ * A DomHelper element spec, or true for a default element spec (defaults to
+ * {tag: "input", type: "text", size: "10", autocomplete: "off"})
+ */
// private
- ctype: "Roo.menu.Item",
+ defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
// private
- onRender : function(container, position){
- var el = document.createElement("a");
- el.hideFocus = true;
- el.unselectable = "on";
- el.href = this.href || "#";
- if(this.hrefTarget){
- el.target = this.hrefTarget;
+ hiddenField: false,
+
+ hideMonthPicker : false,
+
+ onRender : function(ct, position)
+ {
+ Roo.form.MonthField.superclass.onRender.call(this, ct, position);
+ if (this.useIso) {
+ this.el.dom.removeAttribute('name');
+ this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
+ 'before', true);
+ this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
+ // prevent input submission
+ this.hiddenName = this.name;
}
- el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : "");
+
+
+ },
+
+ // private
+ validateValue : function(value)
+ {
+ value = this.formatDate(value);
+ if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
+ return false;
+ }
+ if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
+ return true;
+ }
+ var svalue = value;
+ value = this.parseDate(value);
+ if(!value){
+ this.markInvalid(String.format(this.invalidText, svalue, this.format));
+ return false;
+ }
+ var time = value.getTime();
+ if(this.minValue && time < this.minValue.getTime()){
+ this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
+ return false;
+ }
+ if(this.maxValue && time > this.maxValue.getTime()){
+ this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
+ return false;
+ }
+ /*if(this.disabledDays){
+ var day = value.getDay();
+ for(var i = 0; i < this.disabledDays.length; i++) {
+ if(day === this.disabledDays[i]){
+ this.markInvalid(this.disabledDaysText);
+ return false;
+ }
+ }
+ }
+ */
+ var fvalue = this.formatDate(value);
+ /*if(this.ddMatch && this.ddMatch.test(fvalue)){
+ this.markInvalid(String.format(this.disabledDatesText, fvalue));
+ return false;
+ }
+ */
+ return true;
+ },
+
+ // private
+ // Provides logic to override the default TriggerField.validateBlur which just returns true
+ validateBlur : function(){
+ return !this.menu || !this.menu.isVisible();
+ },
+
+ /**
+ * Returns the current date value of the date field.
+ * @return {Date} The date value
+ */
+ getValue : function(){
- var html = this.html.length ? this.html : String.format('{0}',this.text);
- el.innerHTML = String.format(
- '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
- this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
- this.el = el;
- Roo.menu.Item.superclass.onRender.call(this, container, position);
+
+ return this.hiddenField ?
+ this.hiddenField.value :
+ this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
},
/**
- * Sets the text to display in this menu item
- * @param {String} text The text to display
- * @param {Boolean} isHTML true to indicate text is pure html.
+ * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
+ * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
+ * (the default format used is "m/d/y").
+ * <br />Usage:
+ * <pre><code>
+//All of these calls set the same date value (May 4, 2006)
+
+//Pass a date object:
+var dt = new Date('5/4/06');
+monthField.setValue(dt);
+
+//Pass a date string (default format):
+monthField.setValue('5/4/06');
+
+//Pass a date string (custom format):
+monthField.format = 'Y-m-d';
+monthField.setValue('2006-5-4');
+</code></pre>
+ * @param {String/Date} date The date or valid date string
*/
- setText : function(text, isHTML){
- if (isHTML) {
- this.html = text;
- } else {
- this.text = text;
- this.html = '';
- }
- if(this.rendered){
- var html = this.html.length ? this.html : String.format('{0}',this.text);
-
- this.el.update(String.format(
- '<img src="{0}" class="x-menu-item-icon {2}">' + html,
- this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
- this.parentMenu.autoWidth();
+ setValue : function(date){
+ Roo.log('month setValue' + date);
+ // can only be first of month..
+
+ var val = this.parseDate(date);
+
+ if (this.hiddenField) {
+ this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
}
+ Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
+ this.value = this.parseDate(date);
},
// private
- handleClick : function(e){
- if(!this.href){ // if no link defined, stop the event automatically
- e.stopEvent();
+ parseDate : function(value){
+ if(!value || value instanceof Date){
+ value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
+ return value;
}
- Roo.menu.Item.superclass.handleClick.apply(this, arguments);
- },
-
- // private
- activate : function(autoExpand){
- if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
- this.focus();
- if(autoExpand){
- this.expandMenu();
+ var v = Date.parseDate(value, this.format);
+ if (!v && this.useIso) {
+ v = Date.parseDate(value, 'Y-m-d');
+ }
+ if (v) {
+ //
+ v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
+ }
+
+
+ if(!v && this.altFormats){
+ if(!this.altFormatsArray){
+ this.altFormatsArray = this.altFormats.split("|");
+ }
+ for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
+ v = Date.parseDate(value, this.altFormatsArray[i]);
}
}
- return true;
+ return v;
},
// private
- shouldDeactivate : function(e){
- if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
- if(this.menu && this.menu.isVisible()){
- return !this.menu.getEl().getRegion().contains(e.getPoint());
- }
- return true;
- }
- return false;
+ formatDate : function(date, fmt){
+ return (!date || !(date instanceof Date)) ?
+ date : date.dateFormat(fmt || this.format);
},
// private
- deactivate : function(){
- Roo.menu.Item.superclass.deactivate.apply(this, arguments);
- this.hideMenu();
+ menuListeners : {
+ select: function(m, d){
+ this.setValue(d);
+ this.fireEvent('select', this, d);
+ },
+ show : function(){ // retain focus styling
+ this.onFocus();
+ },
+ hide : function(){
+ this.focus.defer(10, this);
+ var ml = this.menuListeners;
+ this.menu.un("select", ml.select, this);
+ this.menu.un("show", ml.show, this);
+ this.menu.un("hide", ml.hide, this);
+ }
},
-
// private
- expandMenu : function(autoActivate){
- if(!this.disabled && this.menu){
- clearTimeout(this.hideTimer);
- delete this.hideTimer;
- if(!this.menu.isVisible() && !this.showTimer){
- this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
- }else if (this.menu.isVisible() && autoActivate){
- this.menu.tryActivate(0, 1);
+ // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
+ onTriggerClick : function(){
+ if(this.disabled){
+ return;
+ }
+ if(this.menu == null){
+ this.menu = new Roo.menu.DateMenu();
+
+ }
+
+ Roo.apply(this.menu.picker, {
+
+ showClear: this.allowBlank,
+ minDate : this.minValue,
+ maxDate : this.maxValue,
+ disabledDatesRE : this.ddMatch,
+ disabledDatesText : this.disabledDatesText,
+
+ format : this.useIso ? 'Y-m-d' : this.format,
+ minText : String.format(this.minText, this.formatDate(this.minValue)),
+ maxText : String.format(this.maxText, this.formatDate(this.maxValue))
+
+ });
+ this.menu.on(Roo.apply({}, this.menuListeners, {
+ scope:this
+ }));
+
+
+ var m = this.menu;
+ var p = m.picker;
+
+ // hide month picker get's called when we called by 'before hide';
+
+ var ignorehide = true;
+ p.hideMonthPicker = function(disableAnim){
+ if (ignorehide) {
+ return;
+ }
+ if(this.monthPicker){
+ Roo.log("hideMonthPicker called");
+ if(disableAnim === true){
+ this.monthPicker.hide();
+ }else{
+ this.monthPicker.slideOut('t', {duration:.2});
+ p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
+ p.fireEvent("select", this, this.value);
+ m.hide();
+ }
}
}
+
+ Roo.log('picker set value');
+ Roo.log(this.getValue());
+ p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
+ m.show(this.el, 'tl-bl?');
+ ignorehide = false;
+ // this will trigger hideMonthPicker..
+
+
+ // hidden the day picker
+ Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
+
+
+
+
+
+ p.showMonthPicker.defer(100, p);
+
+
+
},
- // private
- deferExpand : function(autoActivate){
- delete this.showTimer;
- this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
- if(autoActivate){
- this.menu.tryActivate(0, 1);
- }
- },
-
- // private
- hideMenu : function(){
- clearTimeout(this.showTimer);
- delete this.showTimer;
- if(!this.hideTimer && this.menu && this.menu.isVisible()){
- this.hideTimer = this.deferHide.defer(this.hideDelay, this);
+ beforeBlur : function(){
+ var v = this.parseDate(this.getRawValue());
+ if(v){
+ this.setValue(v);
}
- },
-
- // private
- deferHide : function(){
- delete this.hideTimer;
- this.menu.hide();
}
+
+ /** @cfg {Boolean} grow @hide */
+ /** @cfg {Number} growMin @hide */
+ /** @cfg {Number} growMax @hide */
+ /**
+ * @hide
+ * @method autoSize
+ */
});/*
* Based on:
* Ext JS Library 1.1.1
* <script type="text/javascript">
*/
+
/**
- * @class Roo.menu.CheckItem
- * @extends Roo.menu.Item
- * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
+ * @class Roo.form.ComboBox
+ * @extends Roo.form.TriggerField
+ * A combobox control with support for autocomplete, remote-loading, paging and many other features.
* @constructor
- * Creates a new CheckItem
+ * Create a new ComboBox.
* @param {Object} config Configuration options
*/
-Roo.menu.CheckItem = function(config){
- Roo.menu.CheckItem.superclass.constructor.call(this, config);
+Roo.form.ComboBox = function(config){
+ Roo.form.ComboBox.superclass.constructor.call(this, config);
this.addEvents({
/**
- * @event beforecheckchange
- * Fires before the checked value is set, providing an opportunity to cancel if needed
- * @param {Roo.menu.CheckItem} this
- * @param {Boolean} checked The new checked value that will be set
- */
- "beforecheckchange" : true,
+ * @event expand
+ * Fires when the dropdown list is expanded
+ * @param {Roo.form.ComboBox} combo This combo box
+ */
+ 'expand' : true,
/**
- * @event checkchange
- * Fires after the checked value has been set
- * @param {Roo.menu.CheckItem} this
- * @param {Boolean} checked The checked value that was set
- */
- "checkchange" : true
+ * @event collapse
+ * Fires when the dropdown list is collapsed
+ * @param {Roo.form.ComboBox} combo This combo box
+ */
+ 'collapse' : true,
+ /**
+ * @event beforeselect
+ * Fires before a list item is selected. Return false to cancel the selection.
+ * @param {Roo.form.ComboBox} combo This combo box
+ * @param {Roo.data.Record} record The data record returned from the underlying store
+ * @param {Number} index The index of the selected item in the dropdown list
+ */
+ 'beforeselect' : true,
+ /**
+ * @event select
+ * Fires when a list item is selected
+ * @param {Roo.form.ComboBox} combo This combo box
+ * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
+ * @param {Number} index The index of the selected item in the dropdown list
+ */
+ 'select' : true,
+ /**
+ * @event beforequery
+ * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
+ * The event object passed has these properties:
+ * @param {Roo.form.ComboBox} combo This combo box
+ * @param {String} query The query
+ * @param {Boolean} forceAll true to force "all" query
+ * @param {Boolean} cancel true to cancel the query
+ * @param {Object} e The query event object
+ */
+ 'beforequery': true,
+ /**
+ * @event add
+ * Fires when the 'add' icon is pressed (add a listener to enable add button)
+ * @param {Roo.form.ComboBox} combo This combo box
+ */
+ 'add' : true,
+ /**
+ * @event edit
+ * Fires when the 'edit' icon is pressed (add a listener to enable add button)
+ * @param {Roo.form.ComboBox} combo This combo box
+ * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
+ */
+ 'edit' : true
+
+
});
- if(this.checkHandler){
- this.on('checkchange', this.checkHandler, this.scope);
+ if(this.transform){
+ this.allowDomMove = false;
+ var s = Roo.getDom(this.transform);
+ if(!this.hiddenName){
+ this.hiddenName = s.name;
+ }
+ if(!this.store){
+ this.mode = 'local';
+ var d = [], opts = s.options;
+ for(var i = 0, len = opts.length;i < len; i++){
+ var o = opts[i];
+ var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
+ if(o.selected) {
+ this.value = value;
+ }
+ d.push([value, o.text]);
+ }
+ this.store = new Roo.data.SimpleStore({
+ 'id': 0,
+ fields: ['value', 'text'],
+ data : d
+ });
+ this.valueField = 'value';
+ this.displayField = 'text';
+ }
+ s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
+ if(!this.lazyRender){
+ this.target = true;
+ this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
+ s.parentNode.removeChild(s); // remove it
+ this.render(this.el.parentNode);
+ }else{
+ s.parentNode.removeChild(s); // remove it
+ }
+
+ }
+ if (this.store) {
+ this.store = Roo.factory(this.store, Roo.data);
+ }
+
+ this.selectedIndex = -1;
+ if(this.mode == 'local'){
+ if(config.queryDelay === undefined){
+ this.queryDelay = 10;
+ }
+ if(config.minChars === undefined){
+ this.minChars = 0;
+ }
}
};
-Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
+
+Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
/**
- * @cfg {String} group
- * All check items with the same group name will automatically be grouped into a single-select
- * radio button group (defaults to '')
+ * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
*/
/**
- * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
+ * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
+ * rendering into an Roo.Editor, defaults to false)
*/
- itemCls : "x-menu-item x-menu-check-item",
/**
- * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
+ * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
+ * {tag: "input", type: "text", size: "24", autocomplete: "off"})
*/
- groupClass : "x-menu-group-item",
-
/**
- * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false). Note that
- * if this checkbox is part of a radio group (group = true) only the last item in the group that is
- * initialized with checked = true will be rendered as checked.
+ * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
*/
- checked: false,
-
- // private
- ctype: "Roo.menu.CheckItem",
-
- // private
- onRender : function(c){
- Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
- if(this.group){
- this.el.addClass(this.groupClass);
- }
- Roo.menu.MenuMgr.registerCheckable(this);
- if(this.checked){
- this.checked = false;
- this.setChecked(true, true);
- }
- },
-
- // private
- destroy : function(){
- if(this.rendered){
- Roo.menu.MenuMgr.unregisterCheckable(this);
- }
- Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
- },
-
/**
- * Set the checked state of this item
- * @param {Boolean} checked The new checked value
- * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
+ * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
+ * the dropdown list (defaults to undefined, with no header element)
*/
- setChecked : function(state, suppressEvent){
- if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
- if(this.container){
- this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
- }
- this.checked = state;
- if(suppressEvent !== true){
- this.fireEvent("checkchange", this, state);
- }
- }
- },
-
- // private
- handleClick : function(e){
- if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
- this.setChecked(!this.checked);
- }
- Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
- }
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-/**
- * @class Roo.menu.DateItem
- * @extends Roo.menu.Adapter
- * A menu item that wraps the {@link Roo.DatPicker} component.
- * @constructor
- * Creates a new DateItem
- * @param {Object} config Configuration options
- */
-Roo.menu.DateItem = function(config){
- Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
- /** The Roo.DatePicker object @type Roo.DatePicker */
- this.picker = this.component;
- this.addEvents({select: true});
-
- this.picker.on("render", function(picker){
- picker.getEl().swallowEvent("click");
- picker.container.addClass("x-menu-date-item");
- });
-
- this.picker.on("select", this.onSelect, this);
-};
-Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
+ /**
+ * @cfg {String/Roo.Template} tpl The template to use to render the output
+ */
+
// private
- onSelect : function(picker, date){
- this.fireEvent("select", this, date, picker);
- Roo.menu.DateItem.superclass.handleClick.call(this);
- }
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-/**
- * @class Roo.menu.ColorItem
- * @extends Roo.menu.Adapter
- * A menu item that wraps the {@link Roo.ColorPalette} component.
- * @constructor
- * Creates a new ColorItem
- * @param {Object} config Configuration options
- */
-Roo.menu.ColorItem = function(config){
- Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
- /** The Roo.ColorPalette object @type Roo.ColorPalette */
- this.palette = this.component;
- this.relayEvents(this.palette, ["select"]);
- if(this.selectHandler){
- this.on('select', this.selectHandler, this.scope);
- }
-};
-Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-
-/**
- * @class Roo.menu.DateMenu
- * @extends Roo.menu.Menu
- * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
- * @constructor
- * Creates a new DateMenu
- * @param {Object} config Configuration options
- */
-Roo.menu.DateMenu = function(config){
- Roo.menu.DateMenu.superclass.constructor.call(this, config);
- this.plain = true;
- var di = new Roo.menu.DateItem(config);
- this.add(di);
+ defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
/**
- * The {@link Roo.DatePicker} instance for this DateMenu
- * @type DatePicker
+ * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
*/
- this.picker = di.picker;
+ listWidth: undefined,
/**
- * @event select
- * @param {DatePicker} picker
- * @param {Date} date
+ * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
+ * mode = 'remote' or 'text' if mode = 'local')
*/
- this.relayEvents(di, ["select"]);
- this.on('beforeshow', function(){
- if(this.picker){
- this.picker.hideMonthPicker(false);
- }
- }, this);
-};
-Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
- cls:'x-date-menu'
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-
-/**
- * @class Roo.menu.ColorMenu
- * @extends Roo.menu.Menu
- * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
- * @constructor
- * Creates a new ColorMenu
- * @param {Object} config Configuration options
- */
-Roo.menu.ColorMenu = function(config){
- Roo.menu.ColorMenu.superclass.constructor.call(this, config);
- this.plain = true;
- var ci = new Roo.menu.ColorItem(config);
- this.add(ci);
+ displayField: undefined,
/**
- * The {@link Roo.ColorPalette} instance for this ColorMenu
- * @type ColorPalette
+ * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
+ * mode = 'remote' or 'value' if mode = 'local').
+ * Note: use of a valueField requires the user make a selection
+ * in order for a value to be mapped.
*/
- this.palette = ci.palette;
+ valueField: undefined,
+
+
/**
- * @event select
- * @param {ColorPalette} palette
- * @param {String} color
+ * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
+ * field's data value (defaults to the underlying DOM element's name)
*/
- this.relayEvents(ci, ["select"]);
-};
-Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-/**
- * @class Roo.form.TextItem
- * @extends Roo.BoxComponent
- * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
- * @constructor
- * Creates a new TextItem
- * @param {Object} config Configuration options
- */
-Roo.form.TextItem = function(config){
- Roo.form.TextItem.superclass.constructor.call(this, config);
-};
-
-Roo.extend(Roo.form.TextItem, Roo.BoxComponent, {
-
+ hiddenName: undefined,
/**
- * @cfg {String} tag the tag for this item (default div)
+ * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
*/
- tag : 'div',
+ listClass: '',
/**
- * @cfg {String} html the content for this item
+ * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
*/
- html : '',
-
- getAutoCreate : function()
- {
- var cfg = {
- id: this.id,
- tag: this.tag,
- html: this.html,
- cls: 'x-form-item'
- };
-
- return cfg;
-
- },
-
- onRender : function(ct, position)
- {
- Roo.form.TextItem.superclass.onRender.call(this, ct, position);
-
- if(!this.el){
- var cfg = this.getAutoCreate();
- if(!cfg.name){
- cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
- }
- if (!cfg.name.length) {
- delete cfg.name;
- }
- this.el = ct.createChild(cfg, position);
- }
- },
- /*
- * setHTML
- * @param {String} html update the Contents of the element.
+ selectedClass: 'x-combo-selected',
+ /**
+ * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
+ * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
+ * which displays a downward arrow icon).
*/
- setHTML : function(html)
- {
- this.fieldEl.dom.innerHTML = html;
- }
-
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-/**
- * @class Roo.form.Field
- * @extends Roo.BoxComponent
- * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
- * @constructor
- * Creates a new Field
- * @param {Object} config Configuration options
- */
-Roo.form.Field = function(config){
- Roo.form.Field.superclass.constructor.call(this, config);
-};
-
-Roo.extend(Roo.form.Field, Roo.BoxComponent, {
+ triggerClass : 'x-form-arrow-trigger',
+ /**
+ * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
+ */
+ shadow:'sides',
/**
- * @cfg {String} fieldLabel Label to use when rendering a form.
+ * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
+ * anchor positions (defaults to 'tl-bl')
*/
- /**
- * @cfg {String} qtip Mouse over tip
+ listAlign: 'tl-bl?',
+ /**
+ * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
*/
-
+ maxHeight: 300,
/**
- * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
+ * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
+ * query specified by the allQuery config option (defaults to 'query')
*/
- invalidClass : "x-form-invalid",
+ triggerAction: 'query',
/**
- * @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")
+ * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
+ * (defaults to 4, does not apply if editable = false)
*/
- invalidText : "The value in this field is invalid",
+ minChars : 4,
/**
- * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
+ * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
+ * delay (typeAheadDelay) if it matches a known value (defaults to false)
*/
- focusClass : "x-form-focus",
+ typeAhead: false,
/**
- * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
- automatic validation (defaults to "keyup").
+ * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
+ * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
*/
- validationEvent : "keyup",
+ queryDelay: 500,
/**
- * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
+ * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
+ * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
*/
- validateOnBlur : true,
+ pageSize: 0,
/**
- * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
+ * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
+ * when editable = true (defaults to false)
*/
- validationDelay : 250,
+ selectOnFocus:false,
/**
- * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
- * {tag: "input", type: "text", size: "20", autocomplete: "off"})
+ * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
*/
- defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
+ queryParam: 'query',
/**
- * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
+ * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
+ * when mode = 'remote' (defaults to 'Loading...')
*/
- fieldClass : "x-form-field",
+ loadingText: 'Loading...',
/**
- * @cfg {String} msgTarget The location where error text should display. Should be one of the following values (defaults to 'qtip'):
- *<pre>
-Value Description
------------ ----------------------------------------------------------------------
-qtip Display a quick tip when the user hovers over the field
-title Display a default browser title attribute popup
-under Add a block div beneath the field containing the error text
-side Add an error icon to the right of the field with a popup on hover
-[element id] Add the error text directly to the innerHTML of the specified element
-</pre>
+ * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
*/
- msgTarget : 'qtip',
+ resizable: false,
/**
- * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
+ * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
*/
- msgFx : 'normal',
-
+ handleHeight : 8,
/**
- * @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.
+ * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
+ * traditional select (defaults to true)
*/
- readOnly : false,
-
+ editable: true,
/**
- * @cfg {Boolean} disabled True to disable the field (defaults to false).
+ * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
*/
- disabled : false,
-
+ allQuery: '',
/**
- * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
+ * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
*/
- inputType : undefined,
-
+ mode: 'remote',
/**
- * @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).
- */
- tabIndex : undefined,
-
- // private
- isFormField : true,
-
- // private
- hasFocus : false,
+ * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
+ * listWidth has a higher value)
+ */
+ minListWidth : 70,
/**
- * @property {Roo.Element} fieldEl
- * Element Containing the rendered Field (with label etc.)
+ * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
+ * allow the user to set arbitrary text into the field (defaults to false)
*/
+ forceSelection:false,
/**
- * @cfg {Mixed} value A value to initialize this field with.
+ * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
+ * if typeAhead = true (defaults to 250)
*/
- value : undefined,
-
+ typeAheadDelay : 250,
/**
- * @cfg {String} name The field's HTML name attribute.
+ * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
+ * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
*/
+ valueNotFoundText : undefined,
/**
- * @cfg {String} cls A CSS class to apply to the field's underlying element.
+ * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
*/
- // private
- loadedValue : false,
-
+ blockFocus : false,
+
+ /**
+ * @cfg {Boolean} disableClear Disable showing of clear button.
+ */
+ disableClear : false,
+ /**
+ * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
+ */
+ alwaysQuery : false,
+
+ //private
+ addicon : false,
+ editicon: false,
+
+ // element that contains real text value.. (when hidden is used..)
- // private ??
- initComponent : function(){
- Roo.form.Field.superclass.initComponent.call(this);
- this.addEvents({
- /**
- * @event focus
- * Fires when this field receives input focus.
- * @param {Roo.form.Field} this
- */
- focus : true,
- /**
- * @event blur
- * Fires when this field loses input focus.
- * @param {Roo.form.Field} this
- */
- blur : true,
- /**
- * @event specialkey
- * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
- * {@link Roo.EventObject#getKey} to determine which key was pressed.
- * @param {Roo.form.Field} this
- * @param {Roo.EventObject} e The event object
- */
- specialkey : true,
- /**
- * @event change
- * Fires just before the field blurs if the field value has changed.
- * @param {Roo.form.Field} this
- * @param {Mixed} newValue The new value
- * @param {Mixed} oldValue The original value
- */
- change : true,
- /**
- * @event invalid
- * Fires after the field has been marked as invalid.
- * @param {Roo.form.Field} this
- * @param {String} msg The validation message
- */
- invalid : true,
- /**
- * @event valid
- * Fires after the field has been validated with no errors.
- * @param {Roo.form.Field} this
- */
- valid : true,
- /**
- * @event keyup
- * Fires after the key up
- * @param {Roo.form.Field} this
- * @param {Roo.EventObject} e The event Object
- */
- keyup : true
+ // private
+ onRender : function(ct, position)
+ {
+ Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
+
+ if(this.hiddenName){
+ this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
+ 'before', true);
+ this.hiddenField.value =
+ this.hiddenValue !== undefined ? this.hiddenValue :
+ this.value !== undefined ? this.value : '';
+
+ // prevent input submission
+ this.el.dom.removeAttribute('name');
+
+
+ }
+
+ if(Roo.isGecko){
+ this.el.dom.setAttribute('autocomplete', 'off');
+ }
+
+ var cls = 'x-combo-list';
+
+ this.list = new Roo.Layer({
+ shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
+ });
+
+ var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
+ this.list.setWidth(lw);
+ this.list.swallowEvent('mousewheel');
+ this.assetHeight = 0;
+
+ if(this.title){
+ this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
+ this.assetHeight += this.header.getHeight();
+ }
+
+ this.innerList = this.list.createChild({cls:cls+'-inner'});
+ this.innerList.on('mouseover', this.onViewOver, this);
+ this.innerList.on('mousemove', this.onViewMove, this);
+ this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
+
+ if(this.allowBlank && !this.pageSize && !this.disableClear){
+ this.footer = this.list.createChild({cls:cls+'-ft'});
+ this.pageTb = new Roo.Toolbar(this.footer);
+
+ }
+ if(this.pageSize){
+ this.footer = this.list.createChild({cls:cls+'-ft'});
+ this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
+ {pageSize: this.pageSize});
+
+ }
+
+ if (this.pageTb && this.allowBlank && !this.disableClear) {
+ var _this = this;
+ this.pageTb.add(new Roo.Toolbar.Fill(), {
+ cls: 'x-btn-icon x-btn-clear',
+ text: ' ',
+ handler: function()
+ {
+ _this.collapse();
+ _this.clearValue();
+ _this.onSelect(false, -1);
+ }
+ });
+ }
+ if (this.footer) {
+ this.assetHeight += this.footer.getHeight();
+ }
+
+
+ if(!this.tpl){
+ this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
+ }
+
+ this.view = new Roo.View(this.innerList, this.tpl, {
+ singleSelect:true,
+ store: this.store,
+ selectedClass: this.selectedClass
+ });
+
+ this.view.on('click', this.onViewClick, this);
+
+ this.store.on('beforeload', this.onBeforeLoad, this);
+ this.store.on('load', this.onLoad, this);
+ this.store.on('loadexception', this.onLoadException, this);
+
+ if(this.resizable){
+ this.resizer = new Roo.Resizable(this.list, {
+ pinned:true, handles:'se'
+ });
+ this.resizer.on('resize', function(r, w, h){
+ this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
+ this.listWidth = w;
+ this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
+ this.restrictHeight();
+ }, this);
+ this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
+ }
+ if(!this.editable){
+ this.editable = true;
+ this.setEditable(false);
+ }
+
+
+ if (typeof(this.events.add.listeners) != 'undefined') {
+
+ this.addicon = this.wrap.createChild(
+ {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });
+
+ this.addicon.on('click', function(e) {
+ this.fireEvent('add', this);
+ }, this);
+ }
+ if (typeof(this.events.edit.listeners) != 'undefined') {
+
+ this.editicon = this.wrap.createChild(
+ {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });
+ if (this.addicon) {
+ this.editicon.setStyle('margin-left', '40px');
+ }
+ this.editicon.on('click', function(e) {
+
+ // we fire even if inothing is selected..
+ this.fireEvent('edit', this, this.lastData );
+
+ }, this);
+ }
+
+
+
+ },
+
+ // private
+ initEvents : function(){
+ Roo.form.ComboBox.superclass.initEvents.call(this);
+
+ this.keyNav = new Roo.KeyNav(this.el, {
+ "up" : function(e){
+ this.inKeyMode = true;
+ this.selectPrev();
+ },
+
+ "down" : function(e){
+ if(!this.isExpanded()){
+ this.onTriggerClick();
+ }else{
+ this.inKeyMode = true;
+ this.selectNext();
+ }
+ },
+
+ "enter" : function(e){
+ this.onViewClick();
+ //return true;
+ },
+
+ "esc" : function(e){
+ this.collapse();
+ },
+
+ "tab" : function(e){
+ this.onViewClick(false);
+ this.fireEvent("specialkey", this, e);
+ return true;
+ },
+
+ scope : this,
+
+ doRelay : function(foo, bar, hname){
+ if(hname == 'down' || this.scope.isExpanded()){
+ return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
+ }
+ return true;
+ },
+
+ forceKeyDown: true
});
+ this.queryDelay = Math.max(this.queryDelay || 10,
+ this.mode == 'local' ? 10 : 250);
+ this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
+ if(this.typeAhead){
+ this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
+ }
+ if(this.editable !== false){
+ this.el.on("keyup", this.onKeyUp, this);
+ }
+ if(this.forceSelection){
+ this.on('blur', this.doForce, this);
+ }
+ },
+
+ onDestroy : function(){
+ if(this.view){
+ this.view.setStore(null);
+ this.view.el.removeAllListeners();
+ this.view.el.remove();
+ this.view.purgeListeners();
+ }
+ if(this.list){
+ this.list.destroy();
+ }
+ if(this.store){
+ this.store.un('beforeload', this.onBeforeLoad, this);
+ this.store.un('load', this.onLoad, this);
+ this.store.un('loadexception', this.onLoadException, this);
+ }
+ Roo.form.ComboBox.superclass.onDestroy.call(this);
+ },
+
+ // private
+ fireKey : function(e){
+ if(e.isNavKeyPress() && !this.list.isVisible()){
+ this.fireEvent("specialkey", this, e);
+ }
+ },
+
+ // private
+ onResize: function(w, h){
+ Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
+
+ if(typeof w != 'number'){
+ // we do not handle it!?!?
+ return;
+ }
+ var tw = this.trigger.getWidth();
+ tw += this.addicon ? this.addicon.getWidth() : 0;
+ tw += this.editicon ? this.editicon.getWidth() : 0;
+ var x = w - tw;
+ this.el.setWidth( this.adjustWidth('input', x));
+
+ this.trigger.setStyle('left', x+'px');
+
+ if(this.list && this.listWidth === undefined){
+ var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
+ this.list.setWidth(lw);
+ this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
+ }
+
+
+
},
/**
- * Returns the name attribute of the field if available
- * @return {String} name The field name
+ * Allow or prevent the user from directly editing the field text. If false is passed,
+ * the user will only be able to select from the items defined in the dropdown list. This method
+ * is the runtime equivalent of setting the 'editable' config option at config time.
+ * @param {Boolean} value True to allow the user to directly edit the field text
*/
- getName: function(){
- return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
+ setEditable : function(value){
+ if(value == this.editable){
+ return;
+ }
+ this.editable = value;
+ if(!value){
+ this.el.dom.setAttribute('readOnly', true);
+ this.el.on('mousedown', this.onTriggerClick, this);
+ this.el.addClass('x-combo-noedit');
+ }else{
+ this.el.dom.setAttribute('readOnly', false);
+ this.el.un('mousedown', this.onTriggerClick, this);
+ this.el.removeClass('x-combo-noedit');
+ }
},
// private
- onRender : function(ct, position){
- Roo.form.Field.superclass.onRender.call(this, ct, position);
- if(!this.el){
- var cfg = this.getAutoCreate();
- if(!cfg.name){
- cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
- }
- if (!cfg.name.length) {
- delete cfg.name;
- }
- if(this.inputType){
- cfg.type = this.inputType;
- }
- this.el = ct.createChild(cfg, position);
+ onBeforeLoad : function(){
+ if(!this.hasFocus){
+ return;
}
- var type = this.el.dom.type;
- if(type){
- if(type == 'password'){
- type = 'text';
- }
- this.el.addClass('x-form-'+type);
+ this.innerList.update(this.loadingText ?
+ '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
+ this.restrictHeight();
+ this.selectedIndex = -1;
+ },
+
+ // private
+ onLoad : function(){
+ if(!this.hasFocus){
+ return;
}
- if(this.readOnly){
- this.el.dom.readOnly = true;
+ if(this.store.getCount() > 0){
+ this.expand();
+ this.restrictHeight();
+ if(this.lastQuery == this.allQuery){
+ if(this.editable){
+ this.el.dom.select();
+ }
+ if(!this.selectByValue(this.value, true)){
+ this.select(0, true);
+ }
+ }else{
+ this.selectNext();
+ if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
+ this.taTask.delay(this.typeAheadDelay);
+ }
+ }
+ }else{
+ this.onEmptyResults();
}
- if(this.tabIndex !== undefined){
- this.el.dom.setAttribute('tabIndex', this.tabIndex);
+ //this.el.focus();
+ },
+ // private
+ onLoadException : function()
+ {
+ this.collapse();
+ Roo.log(this.store.reader.jsonData);
+ if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
+ Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
}
-
- this.el.addClass([this.fieldClass, this.cls]);
- this.initValue();
+
+
},
-
- /**
- * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
- * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
- * @return {Roo.form.Field} this
- */
- applyTo : function(target){
- this.allowDomMove = false;
- this.el = Roo.get(target);
- this.render(this.el.dom.parentNode);
- return this;
+ // private
+ onTypeAhead : function(){
+ if(this.store.getCount() > 0){
+ var r = this.store.getAt(0);
+ var newValue = r.data[this.displayField];
+ var len = newValue.length;
+ var selStart = this.getRawValue().length;
+ if(selStart != len){
+ this.setRawValue(newValue);
+ this.selectText(selStart, newValue.length);
+ }
+ }
},
// private
- initValue : function(){
- if(this.value !== undefined){
- this.setValue(this.value);
- }else if(this.el.dom.value.length > 0){
- this.setValue(this.el.dom.value);
+ onSelect : function(record, index){
+ if(this.fireEvent('beforeselect', this, record, index) !== false){
+ this.setFromData(index > -1 ? record.data : false);
+ this.collapse();
+ this.fireEvent('select', this, record, index);
}
},
/**
- * Returns true if this field has been changed since it was originally loaded and is not disabled.
- * DEPRICATED - it never worked well - use hasChanged/resetHasChanged.
+ * Returns the currently selected field value or empty string if no value is set.
+ * @return {String} value The selected value
*/
- isDirty : function() {
- if(this.disabled) {
- return false;
+ getValue : function(){
+ if(this.valueField){
+ return typeof this.value != 'undefined' ? this.value : '';
}
- return String(this.getValue()) !== String(this.originalValue);
+ return Roo.form.ComboBox.superclass.getValue.call(this);
},
/**
- * stores the current value in loadedValue
+ * Clears any text/value currently set in the field
*/
- resetHasChanged : function()
- {
- this.loadedValue = String(this.getValue());
+ clearValue : function(){
+ if(this.hiddenField){
+ this.hiddenField.value = '';
+ }
+ this.value = '';
+ this.setRawValue('');
+ this.lastSelectionText = '';
+
},
+
/**
- * checks the current value against the 'loaded' value.
- * Note - will return false if 'resetHasChanged' has not been called first.
+ * Sets the specified value into the field. If the value finds a match, the corresponding record text
+ * will be displayed in the field. If the value does not match the data value of an existing item,
+ * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
+ * Otherwise the field will be blank (although the value will still be set).
+ * @param {String} value The value to match
*/
- hasChanged : function()
- {
- if(this.disabled || this.readOnly) {
- return false;
+ setValue : function(v){
+ var text = v;
+ if(this.valueField){
+ var r = this.findRecord(this.valueField, v);
+ if(r){
+ text = r.data[this.displayField];
+ }else if(this.valueNotFoundText !== undefined){
+ text = this.valueNotFoundText;
+ }
}
- return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
- },
-
-
-
- // private
- afterRender : function(){
- Roo.form.Field.superclass.afterRender.call(this);
- this.initEvents();
- },
-
- // private
- fireKey : function(e){
- //Roo.log('field ' + e.getKey());
- if(e.isNavKeyPress()){
- this.fireEvent("specialkey", this, e);
+ this.lastSelectionText = text;
+ if(this.hiddenField){
+ this.hiddenField.value = v;
}
+ Roo.form.ComboBox.superclass.setValue.call(this, text);
+ this.value = v;
},
-
/**
- * Resets the current field value to the originally loaded value and clears any validation messages
+ * @property {Object} the last set data for the element
+ */
+
+ lastData : false,
+ /**
+ * Sets the value of the field based on a object which is related to the record format for the store.
+ * @param {Object} value the value to set as. or false on reset?
*/
+ setFromData : function(o){
+ var dv = ''; // display value
+ var vv = ''; // value value..
+ this.lastData = o;
+ if (this.displayField) {
+ dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
+ } else {
+ // this is an error condition!!!
+ Roo.log('no displayField value set for '+ (this.name ? this.name : this.id));
+ }
+
+ if(this.valueField){
+ vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
+ }
+ if(this.hiddenField){
+ this.hiddenField.value = vv;
+
+ this.lastSelectionText = dv;
+ Roo.form.ComboBox.superclass.setValue.call(this, dv);
+ this.value = vv;
+ return;
+ }
+ // no hidden field.. - we store the value in 'value', but still display
+ // display field!!!!
+ this.lastSelectionText = dv;
+ Roo.form.ComboBox.superclass.setValue.call(this, dv);
+ this.value = vv;
+
+
+ },
+ // private
reset : function(){
+ // overridden so that last data is reset..
this.setValue(this.resetValue);
this.originalValue = this.getValue();
this.clearInvalid();
+ this.lastData = false;
+ if (this.view) {
+ this.view.clearSelections();
+ }
},
-
// private
- initEvents : function(){
- // safari killled keypress - so keydown is now used..
- this.el.on("keydown" , this.fireKey, this);
- this.el.on("focus", this.onFocus, this);
- this.el.on("blur", this.onBlur, this);
- this.el.relayEvent('keyup', this);
-
- // reference to original value for reset
- this.originalValue = this.getValue();
- this.resetValue = this.getValue();
+ findRecord : function(prop, value){
+ var record;
+ if(this.store.getCount() > 0){
+ this.store.each(function(r){
+ if(r.data[prop] == value){
+ record = r;
+ return false;
+ }
+ return true;
+ });
+ }
+ return record;
+ },
+
+ getName: function()
+ {
+ // returns hidden if it's set..
+ if (!this.rendered) {return ''};
+ return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
+
+ },
+ // private
+ onViewMove : function(e, t){
+ this.inKeyMode = false;
},
// private
- onFocus : function(){
- if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
- this.el.addClass(this.focusClass);
+ onViewOver : function(e, t){
+ if(this.inKeyMode){ // prevent key nav and mouse over conflicts
+ return;
}
- if(!this.hasFocus){
- this.hasFocus = true;
- this.startValue = this.getValue();
- this.fireEvent("focus", this);
+ var item = this.view.findItemFromChild(t);
+ if(item){
+ var index = this.view.indexOf(item);
+ this.select(index, false);
}
},
- beforeBlur : Roo.emptyFn,
-
// private
- onBlur : function(){
- this.beforeBlur();
- if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
- this.el.removeClass(this.focusClass);
- }
- this.hasFocus = false;
- if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
- this.validate();
+ onViewClick : function(doFocus)
+ {
+ var index = this.view.getSelectedIndexes()[0];
+ var r = this.store.getAt(index);
+ if(r){
+ this.onSelect(r, index);
}
- var v = this.getValue();
- if(String(v) !== String(this.startValue)){
- this.fireEvent('change', this, v, this.startValue);
+ if(doFocus !== false && !this.blockFocus){
+ this.el.focus();
}
- this.fireEvent("blur", this);
+ },
+
+ // private
+ restrictHeight : function(){
+ this.innerList.dom.style.height = '';
+ var inner = this.innerList.dom;
+ var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
+ this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
+ this.list.beginUpdate();
+ this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
+ this.list.alignTo(this.el, this.listAlign);
+ this.list.endUpdate();
+ },
+
+ // private
+ onEmptyResults : function(){
+ this.collapse();
},
/**
- * Returns whether or not the field value is currently valid
- * @param {Boolean} preventMark True to disable marking the field invalid
- * @return {Boolean} True if the value is valid, else false
+ * Returns true if the dropdown list is expanded, else false.
*/
- isValid : function(preventMark){
- if(this.disabled){
- return true;
- }
- var restore = this.preventMark;
- this.preventMark = preventMark === true;
- var v = this.validateValue(this.processValue(this.getRawValue()));
- this.preventMark = restore;
- return v;
+ isExpanded : function(){
+ return this.list.isVisible();
},
/**
- * Validates the field value
- * @return {Boolean} True if the value is valid, else false
+ * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
+ * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
+ * @param {String} value The data value of the item to select
+ * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
+ * selected item if it is not currently in view (defaults to true)
+ * @return {Boolean} True if the value matched an item in the list, else false
*/
- validate : function(){
- if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
- this.clearInvalid();
- return true;
+ selectByValue : function(v, scrollIntoView){
+ if(v !== undefined && v !== null){
+ var r = this.findRecord(this.valueField || this.displayField, v);
+ if(r){
+ this.select(this.store.indexOf(r), scrollIntoView);
+ return true;
+ }
}
return false;
},
- processValue : function(value){
- return value;
+ /**
+ * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
+ * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
+ * @param {Number} index The zero-based index of the list item to select
+ * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
+ * selected item if it is not currently in view (defaults to true)
+ */
+ select : function(index, scrollIntoView){
+ this.selectedIndex = index;
+ this.view.select(index);
+ if(scrollIntoView !== false){
+ var el = this.view.getNode(index);
+ if(el){
+ this.innerList.scrollChildIntoView(el, false);
+ }
+ }
},
// private
- // Subclasses should provide the validation implementation by overriding this
- validateValue : function(value){
- return true;
+ selectNext : function(){
+ var ct = this.store.getCount();
+ if(ct > 0){
+ if(this.selectedIndex == -1){
+ this.select(0);
+ }else if(this.selectedIndex < ct-1){
+ this.select(this.selectedIndex+1);
+ }
+ }
},
- /**
- * Mark this field as invalid
- * @param {String} msg The validation message
- */
- markInvalid : function(msg){
- if(!this.rendered || this.preventMark){ // not rendered
- return;
+ // private
+ selectPrev : function(){
+ var ct = this.store.getCount();
+ if(ct > 0){
+ if(this.selectedIndex == -1){
+ this.select(0);
+ }else if(this.selectedIndex != 0){
+ this.select(this.selectedIndex-1);
+ }
}
-
- var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
-
- obj.el.addClass(this.invalidClass);
- msg = msg || this.invalidText;
- switch(this.msgTarget){
- case 'qtip':
- obj.el.dom.qtip = msg;
- obj.el.dom.qclass = 'x-form-invalid-tip';
- if(Roo.QuickTips){ // fix for floating editors interacting with DND
- Roo.QuickTips.enable();
- }
- break;
- case 'title':
- this.el.dom.title = msg;
- break;
- case 'under':
- if(!this.errorEl){
- var elp = this.el.findParent('.x-form-element', 5, true);
- this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
- this.errorEl.setWidth(elp.getWidth(true)-20);
- }
- this.errorEl.update(msg);
- Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
- break;
- case 'side':
- if(!this.errorIcon){
- var elp = this.el.findParent('.x-form-element', 5, true);
- this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
- }
- this.alignErrorIcon();
- this.errorIcon.dom.qtip = msg;
- this.errorIcon.dom.qclass = 'x-form-invalid-tip';
- this.errorIcon.show();
- this.on('resize', this.alignErrorIcon, this);
- break;
- default:
- var t = Roo.getDom(this.msgTarget);
- t.innerHTML = msg;
- t.style.display = this.msgDisplay;
- break;
+ },
+
+ // private
+ onKeyUp : function(e){
+ if(this.editable !== false && !e.isSpecialKey()){
+ this.lastKey = e.getKey();
+ this.dqTask.delay(this.queryDelay);
}
- this.fireEvent('invalid', this, msg);
},
// private
- alignErrorIcon : function(){
- this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
+ validateBlur : function(){
+ return !this.list || !this.list.isVisible();
},
- /**
- * Clear any invalid styles/messages for this field
- */
- clearInvalid : function(){
- if(!this.rendered || this.preventMark){ // not rendered
- return;
- }
- var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
-
- obj.el.removeClass(this.invalidClass);
- switch(this.msgTarget){
- case 'qtip':
- obj.el.dom.qtip = '';
- break;
- case 'title':
- this.el.dom.title = '';
- break;
- case 'under':
- if(this.errorEl){
- Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
- }
- break;
- case 'side':
- if(this.errorIcon){
- this.errorIcon.dom.qtip = '';
- this.errorIcon.hide();
- this.un('resize', this.alignErrorIcon, this);
- }
- break;
- default:
- var t = Roo.getDom(this.msgTarget);
- t.innerHTML = '';
- t.style.display = 'none';
- break;
+ // private
+ initQuery : function(){
+ this.doQuery(this.getRawValue());
+ },
+
+ // private
+ doForce : function(){
+ if(this.el.dom.value.length > 0){
+ this.el.dom.value =
+ this.lastSelectionText === undefined ? '' : this.lastSelectionText;
+
}
- this.fireEvent('valid', this);
},
/**
- * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
- * @return {Mixed} value The field value
+ * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
+ * query allowing the query action to be canceled if needed.
+ * @param {String} query The SQL query to execute
+ * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
+ * in the field than the minimum specified by the minChars config option. It also clears any filter previously
+ * saved in the current store (defaults to false)
*/
- getRawValue : function(){
- var v = this.el.getValue();
-
- return v;
+ doQuery : function(q, forceAll){
+ if(q === undefined || q === null){
+ q = '';
+ }
+ var qe = {
+ query: q,
+ forceAll: forceAll,
+ combo: this,
+ cancel:false
+ };
+ if(this.fireEvent('beforequery', qe)===false || qe.cancel){
+ return false;
+ }
+ q = qe.query;
+ forceAll = qe.forceAll;
+ if(forceAll === true || (q.length >= this.minChars)){
+ if(this.lastQuery != q || this.alwaysQuery){
+ this.lastQuery = q;
+ if(this.mode == 'local'){
+ this.selectedIndex = -1;
+ if(forceAll){
+ this.store.clearFilter();
+ }else{
+ this.store.filter(this.displayField, q);
+ }
+ this.onLoad();
+ }else{
+ this.store.baseParams[this.queryParam] = q;
+ this.store.load({
+ params: this.getParams(q)
+ });
+ this.expand();
+ }
+ }else{
+ this.selectedIndex = -1;
+ this.onLoad();
+ }
+ }
},
- /**
- * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
- * @return {Mixed} value The field value
- */
- getValue : function(){
- var v = this.el.getValue();
-
- return v;
+ // private
+ getParams : function(q){
+ var p = {};
+ //p[this.queryParam] = q;
+ if(this.pageSize){
+ p.start = 0;
+ p.limit = this.pageSize;
+ }
+ return p;
},
/**
- * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
- * @param {Mixed} value The value to set
+ * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
*/
- setRawValue : function(v){
- return this.el.dom.value = (v === null || v === undefined ? '' : v);
+ collapse : function(){
+ if(!this.isExpanded()){
+ return;
+ }
+ this.list.hide();
+ Roo.get(document).un('mousedown', this.collapseIf, this);
+ Roo.get(document).un('mousewheel', this.collapseIf, this);
+ if (!this.editable) {
+ Roo.get(document).un('keydown', this.listKeyPress, this);
+ }
+ this.fireEvent('collapse', this);
},
- /**
- * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
- * @param {Mixed} value The value to set
- */
- setValue : function(v){
- this.value = v;
- if(this.rendered){
- this.el.dom.value = (v === null || v === undefined ? '' : v);
- this.validate();
+ // private
+ collapseIf : function(e){
+ if(!e.within(this.wrap) && !e.within(this.list)){
+ this.collapse();
}
},
- adjustSize : function(w, h){
- var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
- s.width = this.adjustWidth(this.el.dom.tagName, s.width);
- return s;
+ /**
+ * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
+ */
+ expand : function(){
+ if(this.isExpanded() || !this.hasFocus){
+ return;
+ }
+ this.list.alignTo(this.el, this.listAlign);
+ this.list.show();
+ Roo.get(document).on('mousedown', this.collapseIf, this);
+ Roo.get(document).on('mousewheel', this.collapseIf, this);
+ if (!this.editable) {
+ Roo.get(document).on('keydown', this.listKeyPress, this);
+ }
+
+ this.fireEvent('expand', this);
},
- adjustWidth : function(tag, w){
- tag = tag.toLowerCase();
- if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
- if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
- if(tag == 'input'){
- return w + 2;
- }
- if(tag == 'textarea'){
- return w-2;
- }
- }else if(Roo.isOpera){
- if(tag == 'input'){
- return w + 2;
- }
- if(tag == 'textarea'){
- return w-2;
- }
- }
+ // private
+ // Implements the default empty TriggerField.onTriggerClick function
+ onTriggerClick : function(){
+ if(this.disabled){
+ return;
}
- return w;
- }
-});
-
-
-// anything other than normal should be considered experimental
-Roo.form.Field.msgFx = {
- normal : {
- show: function(msgEl, f){
- msgEl.setDisplayed('block');
- },
-
- hide : function(msgEl, f){
- msgEl.setDisplayed(false).update('');
+ if(this.isExpanded()){
+ this.collapse();
+ if (!this.blockFocus) {
+ this.el.focus();
+ }
+
+ }else {
+ this.hasFocus = true;
+ if(this.triggerAction == 'all') {
+ this.doQuery(this.allQuery, true);
+ } else {
+ this.doQuery(this.getRawValue());
+ }
+ if (!this.blockFocus) {
+ this.el.focus();
+ }
}
},
-
- slide : {
- show: function(msgEl, f){
- msgEl.slideIn('t', {stopFx:true});
- },
-
- hide : function(msgEl, f){
- msgEl.slideOut('t', {stopFx:true,useDisplay:true});
+ listKeyPress : function(e)
+ {
+ //Roo.log('listkeypress');
+ // scroll to first matching element based on key pres..
+ if (e.isSpecialKey()) {
+ return false;
+ }
+ var k = String.fromCharCode(e.getKey()).toUpperCase();
+ //Roo.log(k);
+ var match = false;
+ var csel = this.view.getSelectedNodes();
+ var cselitem = false;
+ if (csel.length) {
+ var ix = this.view.indexOf(csel[0]);
+ cselitem = this.store.getAt(ix);
+ if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
+ cselitem = false;
+ }
+
+ }
+
+ this.store.each(function(v) {
+ if (cselitem) {
+ // start at existing selection.
+ if (cselitem.id == v.id) {
+ cselitem = false;
+ }
+ return;
+ }
+
+ if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
+ match = this.store.indexOf(v);
+ return false;
+ }
+ }, this);
+
+ if (match === false) {
+ return true; // no more action?
}
+ // scroll to?
+ this.view.select(match);
+ var sn = Roo.get(this.view.getSelectedNodes()[0]);
+ sn.scrollIntoView(sn.dom.parentNode, false);
},
+ cleanLeadingSpace : function()
+ {
+ // override textfield strip white space (trigers set on blur)
+ }
- slideRight : {
- show: function(msgEl, f){
- msgEl.fixDisplay();
- msgEl.alignTo(f.el, 'tl-tr');
- msgEl.slideIn('l', {stopFx:true});
- },
-
- hide : function(msgEl, f){
- msgEl.slideOut('l', {stopFx:true,useDisplay:true});
- }
- }
-};/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
+ /**
+ * @cfg {Boolean} grow
+ * @hide
+ */
+ /**
+ * @cfg {Number} growMin
+ * @hide
+ */
+ /**
+ * @cfg {Number} growMax
+ * @hide
+ */
+ /**
+ * @hide
+ * @method autoSize
+ */
+});/*
+ * Copyright(c) 2010-2012, Roo J Solutions Limited
*
- * Originally Released Under LGPL - original licence link has changed is not relivant.
+ * Licence LGPL
*
- * Fork - LGPL
- * <script type="text/javascript">
*/
-
/**
- * @class Roo.form.TextField
- * @extends Roo.form.Field
- * Basic text field. Can be used as a direct replacement for traditional text inputs, or as the base
- * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
+ * @class Roo.form.ComboBoxArray
+ * @extends Roo.form.TextField
+ * A facebook style adder... for lists of email / people / countries etc...
+ * pick multiple items from a combo box, and shows each one.
+ *
+ * Fred [x] Brian [x] [Pick another |v]
+ *
+ *
+ * For this to work: it needs various extra information
+ * - normal combo problay has
+ * name, hiddenName
+ * + displayField, valueField
+ *
+ * For our purpose...
+ *
+ *
+ * If we change from 'extends' to wrapping...
+ *
+ *
+ *
+
+
* @constructor
- * Creates a new TextField
+ * Create a new ComboBoxArray.
* @param {Object} config Configuration options
*/
-Roo.form.TextField = function(config){
- Roo.form.TextField.superclass.constructor.call(this, config);
+
+
+Roo.form.ComboBoxArray = function(config)
+{
this.addEvents({
/**
- * @event autosize
- * Fires when the autosize function is triggered. The field may or may not have actually changed size
- * according to the default logic, but this event provides a hook for the developer to apply additional
- * logic at runtime to resize the field if needed.
- * @param {Roo.form.Field} this This text field
- * @param {Number} width The new field width
+ * @event beforeremove
+ * Fires before remove the value from the list
+ * @param {Roo.form.ComboBoxArray} _self This combo box array
+ * @param {Roo.form.ComboBoxArray.Item} item removed item
*/
- autosize : true
+ 'beforeremove' : true,
+ /**
+ * @event remove
+ * Fires when remove the value from the list
+ * @param {Roo.form.ComboBoxArray} _self This combo box array
+ * @param {Roo.form.ComboBoxArray.Item} item removed item
+ */
+ 'remove' : true
+
+
});
-};
+
+ Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
+
+ this.items = new Roo.util.MixedCollection(false);
+
+ // construct the child combo...
+
+
+
+
+
+
+}
-Roo.extend(Roo.form.TextField, Roo.form.Field, {
- /**
- * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
- */
- grow : false,
- /**
- * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
- */
- growMin : 30,
- /**
- * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
- */
- growMax : 800,
- /**
- * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
- */
- vtype : null,
- /**
- * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
- */
- maskRe : null,
- /**
- * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
- */
- disableKeyFilter : false,
- /**
- * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
- */
- allowBlank : true,
- /**
- * @cfg {Number} minLength Minimum input field length required (defaults to 0)
- */
- minLength : 0,
- /**
- * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
- */
- maxLength : Number.MAX_VALUE,
- /**
- * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
- */
- minLengthText : "The minimum length for this field is {0}",
- /**
- * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
- */
- maxLengthText : "The maximum length for this field is {0}",
- /**
- * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
- */
- selectOnFocus : false,
- /**
- * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space
- */
- allowLeadingSpace : false,
+
+Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
+{
/**
- * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
+ * @cfg {Roo.form.ComboBox} combo [required] The combo box that is wrapped
*/
- blankText : "This field is required",
+
+ lastData : false,
+
+ // behavies liek a hiddne field
+ inputType: 'hidden',
/**
- * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
- * If available, this function will be called only after the basic validators all return true, and will be passed the
- * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
- */
- validator : null,
+ * @cfg {Number} width The width of the box that displays the selected element
+ */
+ width: 300,
+
+
+
/**
- * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
- * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
- * current field value. If the test fails, the field will be marked invalid using {@link #regexText}.
+ * @cfg {String} name The name of the visable items on this form (eg. titles not ids)
*/
- regex : null,
+ name : false,
/**
- * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
+ * @cfg {String} hiddenName The hidden name of the field, often contains an comma seperated list of names
*/
- regexText : "",
- /**
- * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
+ hiddenName : false,
+ /**
+ * @cfg {String} seperator The value seperator normally ','
*/
- emptyText : null,
-
-
- // private
- initEvents : function()
+ seperator : ',',
+
+
+ // private the array of items that are displayed..
+ items : false,
+ // private - the hidden field el.
+ hiddenEl : false,
+ // private - the filed el..
+ el : false,
+
+ //validateValue : function() { return true; }, // all values are ok!
+ //onAddClick: function() { },
+
+ onRender : function(ct, position)
+ {
+
+ // create the standard hidden element
+ //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
+
+
+ // give fake names to child combo;
+ this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
+ this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
+
+ this.combo = Roo.factory(this.combo, Roo.form);
+ this.combo.onRender(ct, position);
+ if (typeof(this.combo.width) != 'undefined') {
+ this.combo.onResize(this.combo.width,0);
+ }
+
+ this.combo.initEvents();
+
+ // assigned so form know we need to do this..
+ this.store = this.combo.store;
+ this.valueField = this.combo.valueField;
+ this.displayField = this.combo.displayField ;
+
+
+ this.combo.wrap.addClass('x-cbarray-grp');
+
+ var cbwrap = this.combo.wrap.createChild(
+ {tag: 'div', cls: 'x-cbarray-cb'},
+ this.combo.el.dom
+ );
+
+
+ this.hiddenEl = this.combo.wrap.createChild({
+ tag: 'input', type:'hidden' , name: this.hiddenName, value : ''
+ });
+ this.el = this.combo.wrap.createChild({
+ tag: 'input', type:'hidden' , name: this.name, value : ''
+ });
+ // this.el.dom.removeAttribute("name");
+
+
+ this.outerWrap = this.combo.wrap;
+ this.wrap = cbwrap;
+
+ this.outerWrap.setWidth(this.width);
+ this.outerWrap.dom.removeChild(this.el.dom);
+
+ this.wrap.dom.appendChild(this.el.dom);
+ this.outerWrap.dom.removeChild(this.combo.trigger.dom);
+ this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
+
+ this.combo.trigger.setStyle('position','relative');
+ this.combo.trigger.setStyle('left', '0px');
+ this.combo.trigger.setStyle('top', '2px');
+
+ this.combo.el.setStyle('vertical-align', 'text-bottom');
+
+ //this.trigger.setStyle('vertical-align', 'top');
+
+ // this should use the code from combo really... on('add' ....)
+ if (this.adder) {
+
+
+ this.adder = this.outerWrap.createChild(
+ {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});
+ var _t = this;
+ this.adder.on('click', function(e) {
+ _t.fireEvent('adderclick', this, e);
+ }, _t);
+ }
+ //var _t = this;
+ //this.adder.on('click', this.onAddClick, _t);
+
+
+ this.combo.on('select', function(cb, rec, ix) {
+ this.addItem(rec.data);
+
+ cb.setValue('');
+ cb.el.dom.value = '';
+ //cb.lastData = rec.data;
+ // add to list
+
+ }, this);
+
+
+
+
+ },
+
+
+ getName: function()
+ {
+ // returns hidden if it's set..
+ if (!this.rendered) {return ''};
+ return this.hiddenName ? this.hiddenName : this.name;
+
+ },
+
+
+ onResize: function(w, h){
+
+ return;
+ // not sure if this is needed..
+ //this.combo.onResize(w,h);
+
+ if(typeof w != 'number'){
+ // we do not handle it!?!?
+ return;
+ }
+ var tw = this.combo.trigger.getWidth();
+ tw += this.addicon ? this.addicon.getWidth() : 0;
+ tw += this.editicon ? this.editicon.getWidth() : 0;
+ var x = w - tw;
+ this.combo.el.setWidth( this.combo.adjustWidth('input', x));
+
+ this.combo.trigger.setStyle('left', '0px');
+
+ if(this.list && this.listWidth === undefined){
+ var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
+ this.list.setWidth(lw);
+ this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
+ }
+
+
+
+ },
+
+ addItem: function(rec)
+ {
+ var valueField = this.combo.valueField;
+ var displayField = this.combo.displayField;
+
+ if (this.items.indexOfKey(rec[valueField]) > -1) {
+ //console.log("GOT " + rec.data.id);
+ return;
+ }
+
+ var x = new Roo.form.ComboBoxArray.Item({
+ //id : rec[this.idField],
+ data : rec,
+ displayField : displayField ,
+ tipField : displayField ,
+ cb : this
+ });
+ // use the
+ this.items.add(rec[valueField],x);
+ // add it before the element..
+ this.updateHiddenEl();
+ x.render(this.outerWrap, this.wrap.dom);
+ // add the image handler..
+ },
+
+ updateHiddenEl : function()
+ {
+ this.validate();
+ if (!this.hiddenEl) {
+ return;
+ }
+ var ar = [];
+ var idField = this.combo.valueField;
+
+ this.items.each(function(f) {
+ ar.push(f.data[idField]);
+ });
+ this.hiddenEl.dom.value = ar.join(this.seperator);
+ this.validate();
+ },
+
+ reset : function()
{
- if (this.emptyText) {
- this.el.attr('placeholder', this.emptyText);
- }
+ this.items.clear();
- Roo.form.TextField.superclass.initEvents.call(this);
- if(this.validationEvent == 'keyup'){
- this.validationTask = new Roo.util.DelayedTask(this.validate, this);
- this.el.on('keyup', this.filterValidation, this);
- }
- else if(this.validationEvent !== false){
- this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
- }
+ Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
+ el.remove();
+ });
- if(this.selectOnFocus){
- this.on("focus", this.preFocus, this);
- }
- if (!this.allowLeadingSpace) {
- this.on('blur', this.cleanLeadingSpace, this);
- }
-
- if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
- this.el.on("keypress", this.filterKeys, this);
- }
- if(this.grow){
- this.el.on("keyup", this.onKeyUp, this, {buffer:50});
- this.el.on("click", this.autoSize, this);
- }
- if(this.el.is('input[type=password]') && Roo.isSafari){
- this.el.on('keydown', this.SafariOnKeyDown, this);
+ this.el.dom.value = '';
+ if (this.hiddenEl) {
+ this.hiddenEl.dom.value = '';
}
+
},
-
- processValue : function(value){
- if(this.stripCharsRe){
- var newValue = value.replace(this.stripCharsRe, '');
- if(newValue !== value){
- this.setRawValue(newValue);
- return newValue;
- }
- }
- return value;
+ getValue: function()
+ {
+ return this.hiddenEl ? this.hiddenEl.dom.value : '';
},
-
- filterValidation : function(e){
- if(!e.isNavKeyPress()){
- this.validationTask.delay(this.validationDelay);
+ setValue: function(v) // not a valid action - must use addItems..
+ {
+
+ this.reset();
+
+ if (this.store.isLocal && (typeof(v) == 'string')) {
+ // then we can use the store to find the values..
+ // comma seperated at present.. this needs to allow JSON based encoding..
+ this.hiddenEl.value = v;
+ var v_ar = [];
+ Roo.each(v.split(this.seperator), function(k) {
+ Roo.log("CHECK " + this.valueField + ',' + k);
+ var li = this.store.query(this.valueField, k);
+ if (!li.length) {
+ return;
+ }
+ var add = {};
+ add[this.valueField] = k;
+ add[this.displayField] = li.item(0).data[this.displayField];
+
+ this.addItem(add);
+ }, this)
+
}
- },
-
- // private
- onKeyUp : function(e){
- if(!e.isNavKeyPress()){
- this.autoSize();
+ if (typeof(v) == 'object' ) {
+ // then let's assume it's an array of objects..
+ Roo.each(v, function(l) {
+ var add = l;
+ if (typeof(l) == 'string') {
+ add = {};
+ add[this.valueField] = l;
+ add[this.displayField] = l
+ }
+ this.addItem(add);
+ }, this);
+
}
+
+
},
- // private - clean the leading white space
- cleanLeadingSpace : function(e)
+ setFromData: function(v)
{
- if ( this.inputType == 'file') {
+ // this recieves an object, if setValues is called.
+ this.reset();
+ this.el.dom.value = v[this.displayField];
+ this.hiddenEl.dom.value = v[this.valueField];
+ if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
return;
}
+ var kv = v[this.valueField];
+ var dv = v[this.displayField];
+ kv = typeof(kv) != 'string' ? '' : kv;
+ dv = typeof(dv) != 'string' ? '' : dv;
- this.setValue((this.getValue() + '').replace(/^\s+/,''));
- },
- /**
- * Resets the current field value to the originally-loaded value and clears any validation messages.
- *
- */
- reset : function(){
- Roo.form.TextField.superclass.reset.call(this);
-
- },
- // private
- preFocus : function(){
- if(this.selectOnFocus){
- this.el.dom.select();
+ var keys = kv.split(this.seperator);
+ var display = dv.split(this.seperator);
+ for (var i = 0 ; i < keys.length; i++) {
+ add = {};
+ add[this.valueField] = keys[i];
+ add[this.displayField] = display[i];
+ this.addItem(add);
}
+
+
},
-
- // private
- filterKeys : function(e){
- var k = e.getKey();
- if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
- return;
- }
- var c = e.getCharCode(), cc = String.fromCharCode(c);
- if(Roo.isIE && (e.isSpecialKey() || !cc)){
- return;
- }
- if(!this.maskRe.test(cc)){
- e.stopEvent();
+ /**
+ * Validates the combox array value
+ * @return {Boolean} True if the value is valid, else false
+ */
+ validate : function(){
+ if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
+ this.clearInvalid();
+ return true;
}
+ return false;
},
-
- setValue : function(v){
-
- Roo.form.TextField.superclass.setValue.apply(this, arguments);
+
+ validateValue : function(value){
+ return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
- this.autoSize();
},
-
- /**
- * Validates a value according to the field's validation rules and marks the field as invalid
- * if the validation fails
- * @param {Mixed} value The value to validate
- * @return {Boolean} True if the value is valid, else false
+
+ /*@
+ * overide
+ *
*/
- validateValue : function(value){
- if(value.length < 1) { // if it's blank
- if(this.allowBlank){
- this.clearInvalid();
- return true;
- }else{
- this.markInvalid(this.blankText);
- return false;
- }
- }
- if(value.length < this.minLength){
- this.markInvalid(String.format(this.minLengthText, this.minLength));
- return false;
- }
- if(value.length > this.maxLength){
- this.markInvalid(String.format(this.maxLengthText, this.maxLength));
+ isDirty : function() {
+ if(this.disabled) {
return false;
}
- if(this.vtype){
- var vt = Roo.form.VTypes;
- if(!vt[this.vtype](value, this)){
- this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
- return false;
- }
- }
- if(typeof this.validator == "function"){
- var msg = this.validator(value);
- if(msg !== true){
- this.markInvalid(msg);
- return false;
- }
+
+ try {
+ var d = Roo.decode(String(this.originalValue));
+ } catch (e) {
+ return String(this.getValue()) !== String(this.originalValue);
}
- if(this.regex && !this.regex.test(value)){
- this.markInvalid(this.regexText);
- return false;
+
+ var originalValue = [];
+
+ for (var i = 0; i < d.length; i++){
+ originalValue.push(d[i][this.valueField]);
}
- return true;
- },
+
+ return String(this.getValue()) !== String(originalValue.join(this.seperator));
+
+ }
+
+});
- /**
- * Selects text in this field
- * @param {Number} start (optional) The index where the selection should start (defaults to 0)
- * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
- */
- selectText : function(start, end){
- var v = this.getRawValue();
- if(v.length > 0){
- start = start === undefined ? 0 : start;
- end = end === undefined ? v.length : end;
- var d = this.el.dom;
- if(d.setSelectionRange){
- d.setSelectionRange(start, end);
- }else if(d.createTextRange){
- var range = d.createTextRange();
- range.moveStart("character", start);
- range.moveEnd("character", v.length-end);
- range.select();
- }
- }
- },
- /**
- * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
- * This only takes effect if grow = true, and fires the autosize event.
- */
- autoSize : function(){
- if(!this.grow || !this.rendered){
- return;
- }
- if(!this.metrics){
- this.metrics = Roo.util.TextMetrics.createInstance(this.el);
- }
- var el = this.el;
- var v = el.dom.value;
- var d = document.createElement('div');
- d.appendChild(document.createTextNode(v));
- v = d.innerHTML;
- d = null;
- v += " ";
- var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
- this.el.setWidth(w);
- this.fireEvent("autosize", this, w);
+
+/**
+ * @class Roo.form.ComboBoxArray.Item
+ * @extends Roo.BoxComponent
+ * A selected item in the list
+ * Fred [x] Brian [x] [Pick another |v]
+ *
+ * @constructor
+ * Create a new item.
+ * @param {Object} config Configuration options
+ */
+
+Roo.form.ComboBoxArray.Item = function(config) {
+ config.id = Roo.id();
+ Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
+}
+
+Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
+ data : {},
+ cb: false,
+ displayField : false,
+ tipField : false,
+
+
+ defaultAutoCreate : {
+ tag: 'div',
+ cls: 'x-cbarray-item',
+ cn : [
+ { tag: 'div' },
+ {
+ tag: 'img',
+ width:16,
+ height : 16,
+ src : Roo.BLANK_IMAGE_URL ,
+ align: 'center'
+ }
+ ]
+
},
- // private
- SafariOnKeyDown : function(event)
+
+ onRender : function(ct, position)
{
- // this is a workaround for a password hang bug on chrome/ webkit.
-
- var isSelectAll = false;
+ Roo.form.Field.superclass.onRender.call(this, ct, position);
- if(this.el.dom.selectionEnd > 0){
- isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
- }
- if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
- event.preventDefault();
- this.setValue('');
- return;
+ if(!this.el){
+ var cfg = this.getAutoCreate();
+ this.el = ct.createChild(cfg, position);
}
- if(isSelectAll && event.getCharCode() > 31){ // backspace and delete key
-
- event.preventDefault();
- // this is very hacky as keydown always get's upper case.
-
- var cc = String.fromCharCode(event.getCharCode());
-
-
- this.setValue( event.shiftKey ? cc : cc.toLowerCase());
+ this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
+
+ this.el.child('div').dom.innerHTML = this.cb.renderer ?
+ this.cb.renderer(this.data) :
+ String.format('{0}',this.data[this.displayField]);
+
+ this.el.child('div').dom.setAttribute('qtip',
+ String.format('{0}',this.data[this.tipField])
+ );
+
+ this.el.child('img').on('click', this.remove, this);
+
+ },
+
+ remove : function()
+ {
+ if(this.cb.disabled){
+ return;
}
+ if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
+ this.cb.items.remove(this);
+ this.el.child('img').un('click', this.remove, this);
+ this.el.remove();
+ this.cb.updateHiddenEl();
+
+ this.cb.fireEvent('remove', this.cb, this);
+ }
}
});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
+ * RooJS Library 1.1.1
+ * Copyright(c) 2008-2011 Alan Knowles
*
- * Fork - LGPL
- * <script type="text/javascript">
+ * License - LGPL
*/
-/**
- * @class Roo.form.Hidden
- * @extends Roo.form.TextField
- * Simple Hidden element used on forms
- *
- * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
- *
- * @constructor
- * Creates a new Hidden form element.
- * @param {Object} config Configuration options
- */
-
-
-
-// easy hidden field...
-Roo.form.Hidden = function(config){
- Roo.form.Hidden.superclass.constructor.call(this, config);
-};
-
-Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
- fieldLabel: '',
- inputType: 'hidden',
- width: 50,
- allowBlank: true,
- labelSeparator: '',
- hidden: true,
- itemCls : 'x-form-item-display-none'
-
-});
-
-
-/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
/**
- * @class Roo.form.TriggerField
- * @extends Roo.form.TextField
- * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
- * The trigger has no default action, so you must assign a function to implement the trigger click handler by
- * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
- * for which you can provide a custom implementation. For example:
- * <pre><code>
-var trigger = new Roo.form.TriggerField();
-trigger.onTriggerClick = myTriggerFn;
-trigger.applyTo('my-field');
-</code></pre>
+ * @class Roo.form.ComboNested
+ * @extends Roo.form.ComboBox
+ * A combobox for that allows selection of nested items in a list,
+ * eg.
*
- * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
- * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
- * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
- * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
+ * Book
+ * -> red
+ * -> green
+ * Table
+ * -> square
+ * ->red
+ * ->green
+ * -> rectangle
+ * ->green
+ *
+ *
* @constructor
- * Create a new TriggerField.
- * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
- * to the base TextField)
+ * Create a new ComboNested
+ * @param {Object} config Configuration options
*/
-Roo.form.TriggerField = function(config){
- this.mimicing = false;
- Roo.form.TriggerField.superclass.constructor.call(this, config);
+Roo.form.ComboNested = function(config){
+ Roo.form.ComboCheck.superclass.constructor.call(this, config);
+ // should verify some data...
+ // like
+ // hiddenName = required..
+ // displayField = required
+ // valudField == required
+ var req= [ 'hiddenName', 'displayField', 'valueField' ];
+ var _t = this;
+ Roo.each(req, function(e) {
+ if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
+ throw "Roo.form.ComboNested : missing value for: " + e;
+ }
+ });
+
+
};
-Roo.extend(Roo.form.TriggerField, Roo.form.TextField, {
- /**
- * @cfg {String} triggerClass A CSS class to apply to the trigger
- */
- /**
- * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
- * {tag: "input", type: "text", size: "16", autocomplete: "off"})
- */
- defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
- /**
- * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
- */
- hideTrigger:false,
-
- /** @cfg {Boolean} grow @hide */
- /** @cfg {Number} growMin @hide */
- /** @cfg {Number} growMax @hide */
-
- /**
- * @hide
- * @method
+Roo.extend(Roo.form.ComboNested, Roo.form.ComboBox, {
+
+ /*
+ * @config {Number} max Number of columns to show
*/
- autoSize: Roo.emptyFn,
- // private
- monitorTab : true,
- // private
- deferHeight : true,
-
- actionMode : 'wrap',
+ maxColumns : 3,
+
+ list : null, // the outermost div..
+ innerLists : null, // the
+ views : null,
+ stores : null,
// private
- onResize : function(w, h){
- Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
- if(typeof w == 'number'){
- var x = w - this.trigger.getWidth();
- this.el.setWidth(this.adjustWidth('input', x));
- this.trigger.setStyle('left', x+'px');
- }
- },
+ loadingChildren : false,
+
+ onRender : function(ct, position)
+ {
+ Roo.form.ComboBox.superclass.onRender.call(this, ct, position); // skip parent call - got to above..
+
+ if(this.hiddenName){
+ this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
+ 'before', true);
+ this.hiddenField.value =
+ this.hiddenValue !== undefined ? this.hiddenValue :
+ this.value !== undefined ? this.value : '';
- // private
- adjustSize : Roo.BoxComponent.prototype.adjustSize,
+ // prevent input submission
+ this.el.dom.removeAttribute('name');
+
+
+ }
+
+ if(Roo.isGecko){
+ this.el.dom.setAttribute('autocomplete', 'off');
+ }
- // private
- getResizeEl : function(){
- return this.wrap;
- },
+ var cls = 'x-combo-list';
- // private
- getPositionEl : function(){
- return this.wrap;
- },
+ this.list = new Roo.Layer({
+ shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
+ });
- // private
- alignErrorIcon : function(){
- this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
- },
+ var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
+ this.list.setWidth(lw);
+ this.list.swallowEvent('mousewheel');
+ this.assetHeight = 0;
- // private
- onRender : function(ct, position){
- Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
- this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
- this.trigger = this.wrap.createChild(this.triggerConfig ||
- {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
- if(this.hideTrigger){
- this.trigger.setDisplayed(false);
+ if(this.title){
+ this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
+ this.assetHeight += this.header.getHeight();
}
- this.initTrigger();
- if(!this.width){
- this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
+ this.innerLists = [];
+ this.views = [];
+ this.stores = [];
+ for (var i =0 ; i < this.maxColumns; i++) {
+ this.onRenderList( cls, i);
+ }
+
+ // always needs footer, as we are going to have an 'OK' button.
+ this.footer = this.list.createChild({cls:cls+'-ft'});
+ this.pageTb = new Roo.Toolbar(this.footer);
+ var _this = this;
+ this.pageTb.add( {
+
+ text: 'Done',
+ handler: function()
+ {
+ _this.collapse();
+ }
+ });
+
+ if ( this.allowBlank && !this.disableClear) {
+
+ this.pageTb.add(new Roo.Toolbar.Fill(), {
+ cls: 'x-btn-icon x-btn-clear',
+ text: ' ',
+ handler: function()
+ {
+ _this.collapse();
+ _this.clearValue();
+ _this.onSelect(false, -1);
+ }
+ });
}
+ if (this.footer) {
+ this.assetHeight += this.footer.getHeight();
+ }
+
},
+ onRenderList : function ( cls, i)
+ {
+
+ var lw = Math.floor(
+ ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
+ );
+
+ this.list.setWidth(lw); // default to '1'
- // private
- initTrigger : function(){
- this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
- this.trigger.addClassOnOver('x-form-trigger-over');
- this.trigger.addClassOnClick('x-form-trigger-click');
- },
+ var il = this.innerLists[i] = this.list.createChild({cls:cls+'-inner'});
+ //il.on('mouseover', this.onViewOver, this, { list: i });
+ //il.on('mousemove', this.onViewMove, this, { list: i });
+ il.setWidth(lw);
+ il.setStyle({ 'overflow-x' : 'hidden'});
- // private
- onDestroy : function(){
- if(this.trigger){
- this.trigger.removeAllListeners();
- this.trigger.remove();
+ if(!this.tpl){
+ this.tpl = new Roo.Template({
+ html : '<div class="'+cls+'-item '+cls+'-item-{cn:this.isEmpty}">{' + this.displayField + '}</div>',
+ isEmpty: function (value, allValues) {
+ //Roo.log(value);
+ var dl = typeof(value.data) != 'undefined' ? value.data.length : value.length; ///json is a nested response..
+ return dl ? 'has-children' : 'no-children'
+ }
+ });
}
- if(this.wrap){
- this.wrap.remove();
+
+ var store = this.store;
+ if (i > 0) {
+ store = new Roo.data.SimpleStore({
+ //fields : this.store.reader.meta.fields,
+ reader : this.store.reader,
+ data : [ ]
+ });
}
- Roo.form.TriggerField.superclass.onDestroy.call(this);
- },
+ this.stores[i] = store;
+
+ var view = this.views[i] = new Roo.View(
+ il,
+ this.tpl,
+ {
+ singleSelect:true,
+ store: store,
+ selectedClass: this.selectedClass
+ }
+ );
+ view.getEl().setWidth(lw);
+ view.getEl().setStyle({
+ position: i < 1 ? 'relative' : 'absolute',
+ top: 0,
+ left: (i * lw ) + 'px',
+ display : i > 0 ? 'none' : 'block'
+ });
+ view.on('selectionchange', this.onSelectChange.createDelegate(this, {list : i }, true));
+ view.on('dblclick', this.onDoubleClick.createDelegate(this, {list : i }, true));
+ //view.on('click', this.onViewClick, this, { list : i });
- // private
- onFocus : function(){
- Roo.form.TriggerField.superclass.onFocus.call(this);
- if(!this.mimicing){
- this.wrap.addClass('x-trigger-wrap-focus');
- this.mimicing = true;
- Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
- if(this.monitorTab){
- this.el.on("keydown", this.checkTab, this);
+ store.on('beforeload', this.onBeforeLoad, this);
+ store.on('load', this.onLoad, this, { list : i});
+ store.on('loadexception', this.onLoadException, this);
+
+ // hide the other vies..
+
+
+
+ },
+
+ restrictHeight : function()
+ {
+ var mh = 0;
+ Roo.each(this.innerLists, function(il,i) {
+ var el = this.views[i].getEl();
+ el.dom.style.height = '';
+ var inner = el.dom;
+ var h = Math.max(il.clientHeight, il.offsetHeight, il.scrollHeight);
+ // only adjust heights on other ones..
+ mh = Math.max(h, mh);
+ if (i < 1) {
+
+ el.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
+ il.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
+
}
- }
+
+
+ }, this);
+
+ this.list.beginUpdate();
+ this.list.setHeight(mh+this.list.getFrameWidth('tb')+this.assetHeight);
+ this.list.alignTo(this.el, this.listAlign);
+ this.list.endUpdate();
+
},
-
+
+
+ // -- store handlers..
// private
- checkTab : function(e){
- if(e.getKey() == e.TAB){
- this.triggerBlur();
+ onBeforeLoad : function()
+ {
+ if(!this.hasFocus){
+ return;
}
+ this.innerLists[0].update(this.loadingText ?
+ '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
+ this.restrictHeight();
+ this.selectedIndex = -1;
},
-
// private
- onBlur : function(){
- // do nothing
- },
+ onLoad : function(a,b,c,d)
+ {
+ if (!this.loadingChildren) {
+ // then we are loading the top level. - hide the children
+ for (var i = 1;i < this.views.length; i++) {
+ this.views[i].getEl().setStyle({ display : 'none' });
+ }
+ var lw = Math.floor(
+ ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
+ );
+
+ this.list.setWidth(lw); // default to '1'
- // private
- mimicBlur : function(e, t){
- if(!this.wrap.contains(t) && this.validateBlur()){
- this.triggerBlur();
+
+ }
+ if(!this.hasFocus){
+ return;
+ }
+
+ if(this.store.getCount() > 0) {
+ this.expand();
+ this.restrictHeight();
+ } else {
+ this.onEmptyResults();
+ }
+
+ if (!this.loadingChildren) {
+ this.selectActive();
}
+ /*
+ this.stores[1].loadData([]);
+ this.stores[2].loadData([]);
+ this.views
+ */
+
+ //this.el.focus();
},
-
+
+
// private
- triggerBlur : function(){
- this.mimicing = false;
- Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
- if(this.monitorTab){
- this.el.un("keydown", this.checkTab, this);
+ onLoadException : function()
+ {
+ this.collapse();
+ Roo.log(this.store.reader.jsonData);
+ if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
+ Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
}
- this.wrap.removeClass('x-trigger-wrap-focus');
- Roo.form.TriggerField.superclass.onBlur.call(this);
+
+
},
+ // no cleaning of leading spaces on blur here.
+ cleanLeadingSpace : function(e) { },
+
- // private
- // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
- validateBlur : function(e, t){
- return true;
- },
+ onSelectChange : function (view, sels, opts )
+ {
+ var ix = view.getSelectedIndexes();
+
+ if (opts.list > this.maxColumns - 2) {
+ if (view.store.getCount()< 1) {
+ this.views[opts.list ].getEl().setStyle({ display : 'none' });
- // private
- onDisable : function(){
- Roo.form.TriggerField.superclass.onDisable.call(this);
- if(this.wrap){
- this.wrap.addClass('x-item-disabled');
+ } else {
+ if (ix.length) {
+ // used to clear ?? but if we are loading unselected
+ this.setFromData(view.store.getAt(ix[0]).data);
+ }
+
+ }
+
+ return;
}
- },
-
- // private
- onEnable : function(){
- Roo.form.TriggerField.superclass.onEnable.call(this);
- if(this.wrap){
- this.wrap.removeClass('x-item-disabled');
+
+ if (!ix.length) {
+ // this get's fired when trigger opens..
+ // this.setFromData({});
+ var str = this.stores[opts.list+1];
+ str.data.clear(); // removeall wihtout the fire events..
+ return;
}
- },
-
- // private
- onShow : function(){
- var ae = this.getActionEl();
- if(ae){
- ae.dom.style.display = '';
- ae.dom.style.visibility = 'visible';
+ var rec = view.store.getAt(ix[0]);
+
+ this.setFromData(rec.data);
+ this.fireEvent('select', this, rec, ix[0]);
+
+ var lw = Math.floor(
+ (
+ (this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')
+ ) / this.maxColumns
+ );
+ this.loadingChildren = true;
+ this.stores[opts.list+1].loadDataFromChildren( rec );
+ this.loadingChildren = false;
+ var dl = this.stores[opts.list+1]. getTotalCount();
+
+ this.views[opts.list+1].getEl().setHeight( this.innerLists[0].getHeight());
+
+ this.views[opts.list+1].getEl().setStyle({ display : dl ? 'block' : 'none' });
+ for (var i = opts.list+2; i < this.views.length;i++) {
+ this.views[i].getEl().setStyle({ display : 'none' });
}
+
+ this.innerLists[opts.list+1].setHeight( this.innerLists[0].getHeight());
+ this.list.setWidth(lw * (opts.list + (dl ? 2 : 1)));
+
+ if (this.isLoading) {
+ // this.selectActive(opts.list);
+ }
+
},
-
- // private
- onHide : function(){
- var ae = this.getActionEl();
- ae.dom.style.display = 'none';
- },
-
- /**
- * The function that should handle the trigger's click event. This method does nothing by default until overridden
- * by an implementing function.
- * @method
- * @param {EventObject} e
- */
- onTriggerClick : Roo.emptyFn
-});
-
-// TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
-// to be extended by an implementing class. For an example of implementing this class, see the custom
-// SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
-Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
- initComponent : function(){
- Roo.form.TwinTriggerField.superclass.initComponent.call(this);
-
- this.triggerConfig = {
- tag:'span', cls:'x-form-twin-triggers', cn:[
- {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
- {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
- ]};
- },
-
- getTrigger : function(index){
- return this.triggers[index];
+
+
+
+ onDoubleClick : function()
+ {
+ this.collapse(); //??
},
-
- initTrigger : function(){
- var ts = this.trigger.select('.x-form-trigger', true);
- this.wrap.setStyle('overflow', 'hidden');
- var triggerField = this;
- ts.each(function(t, all, index){
- t.hide = function(){
- var w = triggerField.wrap.getWidth();
- this.dom.style.display = 'none';
- triggerField.el.setWidth(w-triggerField.trigger.getWidth());
- };
- t.show = function(){
- var w = triggerField.wrap.getWidth();
- this.dom.style.display = '';
- triggerField.el.setWidth(w-triggerField.trigger.getWidth());
- };
- var triggerIndex = 'Trigger'+(index+1);
-
- if(this['hide'+triggerIndex]){
- t.dom.style.display = 'none';
+
+
+
+
+
+ // private
+ recordToStack : function(store, prop, value, stack)
+ {
+ var cstore = new Roo.data.SimpleStore({
+ //fields : this.store.reader.meta.fields, // we need array reader.. for
+ reader : this.store.reader,
+ data : [ ]
+ });
+ var _this = this;
+ var record = false;
+ var srec = false;
+ if(store.getCount() < 1){
+ return false;
+ }
+ store.each(function(r){
+ if(r.data[prop] == value){
+ record = r;
+ srec = r;
+ return false;
}
- t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
- t.addClassOnOver('x-form-trigger-over');
- t.addClassOnClick('x-form-trigger-click');
- }, this);
- this.triggers = ts.elements;
+ if (r.data.cn && r.data.cn.length) {
+ cstore.loadDataFromChildren( r);
+ var cret = _this.recordToStack(cstore, prop, value, stack);
+ if (cret !== false) {
+ record = cret;
+ srec = r;
+ return false;
+ }
+ }
+
+ return true;
+ });
+ if (record == false) {
+ return false
+ }
+ stack.unshift(srec);
+ return record;
},
-
- onTrigger1Click : Roo.emptyFn,
- onTrigger2Click : Roo.emptyFn
+
+ /*
+ * find the stack of stores that match our value.
+ *
+ *
+ */
+
+ selectActive : function ()
+ {
+ // if store is not loaded, then we will need to wait for that to happen first.
+ var stack = [];
+ this.recordToStack(this.store, this.valueField, this.getValue(), stack);
+ for (var i = 0; i < stack.length; i++ ) {
+ this.views[i].select(stack[i].store.indexOf(stack[i]), false, false );
+ }
+
+ }
+
+
+
+
+
+
});/*
* Based on:
* Ext JS Library 1.1.1
* Fork - LGPL
* <script type="text/javascript">
*/
-
/**
- * @class Roo.form.TextArea
- * @extends Roo.form.TextField
- * Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
- * support for auto-sizing.
+ * @class Roo.form.Checkbox
+ * @extends Roo.form.Field
+ * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
* @constructor
- * Creates a new TextArea
+ * Creates a new Checkbox
* @param {Object} config Configuration options
*/
-Roo.form.TextArea = function(config){
- Roo.form.TextArea.superclass.constructor.call(this, config);
- // these are provided exchanges for backwards compat
- // minHeight/maxHeight were replaced by growMin/growMax to be
- // compatible with TextField growing config values
- if(this.minHeight !== undefined){
- this.growMin = this.minHeight;
- }
- if(this.maxHeight !== undefined){
- this.growMax = this.maxHeight;
- }
+Roo.form.Checkbox = function(config){
+ Roo.form.Checkbox.superclass.constructor.call(this, config);
+ this.addEvents({
+ /**
+ * @event check
+ * Fires when the checkbox is checked or unchecked.
+ * @param {Roo.form.Checkbox} this This checkbox
+ * @param {Boolean} checked The new checked value
+ */
+ check : true
+ });
};
-Roo.extend(Roo.form.TextArea, Roo.form.TextField, {
+Roo.extend(Roo.form.Checkbox, Roo.form.Field, {
/**
- * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
+ * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
*/
- growMin : 60,
+ focusClass : undefined,
/**
- * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
+ * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
*/
- growMax: 1000,
+ fieldClass: "x-form-field",
/**
- * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
- * in the field (equivalent to setting overflow: hidden, defaults to false)
+ * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
*/
- preventScrollbars: false,
+ checked: false,
/**
* @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
- * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
+ * {tag: "input", type: "checkbox", autocomplete: "off"})
+ */
+ defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
+ /**
+ * @cfg {String} boxLabel The text that appears beside the checkbox
+ */
+ boxLabel : "",
+ /**
+ * @cfg {String} inputValue The value that should go into the generated input element's value attribute
+ */
+ inputValue : '1',
+ /**
+ * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
*/
+ valueOff: '0', // value when not checked..
+ actionMode : 'viewEl',
+ //
// private
- onRender : function(ct, position){
- if(!this.el){
- this.defaultAutoCreate = {
- tag: "textarea",
- style:"width:300px;height:60px;",
- autocomplete: "new-password"
- };
- }
- Roo.form.TextArea.superclass.onRender.call(this, ct, position);
- if(this.grow){
- this.textSizeEl = Roo.DomHelper.append(document.body, {
- tag: "pre", cls: "x-form-grow-sizer"
- });
- if(this.preventScrollbars){
- this.el.setStyle("overflow", "hidden");
- }
- this.el.setHeight(this.growMin);
+ itemCls : 'x-menu-check-item x-form-item',
+ groupClass : 'x-menu-group-item',
+ inputType : 'hidden',
+
+
+ inSetChecked: false, // check that we are not calling self...
+
+ inputElement: false, // real input element?
+ basedOn: false, // ????
+
+ isFormField: true, // not sure where this is needed!!!!
+
+ onResize : function(){
+ Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
+ if(!this.boxLabel){
+ this.el.alignTo(this.wrap, 'c-c');
}
},
- onDestroy : function(){
- if(this.textSizeEl){
- this.textSizeEl.parentNode.removeChild(this.textSizeEl);
- }
- Roo.form.TextArea.superclass.onDestroy.call(this);
+ initEvents : function(){
+ Roo.form.Checkbox.superclass.initEvents.call(this);
+ this.el.on("click", this.onClick, this);
+ this.el.on("change", this.onClick, this);
+ },
+
+
+ getResizeEl : function(){
+ return this.wrap;
+ },
+
+ getPositionEl : function(){
+ return this.wrap;
},
// private
- onKeyUp : function(e){
- if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
- this.autoSize();
+ onRender : function(ct, position){
+ Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
+ /*
+ if(this.inputValue !== undefined){
+ this.el.dom.value = this.inputValue;
+ }
+ */
+ //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
+ this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
+ var viewEl = this.wrap.createChild({
+ tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
+ this.viewEl = viewEl;
+ this.wrap.on('click', this.onClick, this);
+
+ this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
+ this.el.on('propertychange', this.setFromHidden, this); //ie
+
+
+
+ if(this.boxLabel){
+ this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
+ // viewEl.on('click', this.onClick, this);
}
+ //if(this.checked){
+ this.setChecked(this.checked);
+ //}else{
+ //this.checked = this.el.dom;
+ //}
+
},
+ // private
+ initValue : Roo.emptyFn,
+
/**
- * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
- * This only takes effect if grow = true, and fires the autosize event if the height changes.
+ * Returns the checked state of the checkbox.
+ * @return {Boolean} True if checked, else false
*/
- autoSize : function(){
- if(!this.grow || !this.textSizeEl){
+ getValue : function(){
+ if(this.el){
+ return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
+ }
+ return this.valueOff;
+
+ },
+
+ // private
+ onClick : function(){
+ if (this.disabled) {
return;
}
- var el = this.el;
- var v = el.dom.value;
- var ts = this.textSizeEl;
+ this.setChecked(!this.checked);
- ts.innerHTML = '';
- ts.appendChild(document.createTextNode(v));
- v = ts.innerHTML;
+ //if(this.el.dom.checked != this.checked){
+ // this.setValue(this.el.dom.checked);
+ // }
+ },
- Roo.fly(ts).setWidth(this.el.getWidth());
- if(v.length < 1){
- v = "  ";
- }else{
- if(Roo.isIE){
- v = v.replace(/\n/g, '<p> </p>');
- }
- v += " \n ";
+ /**
+ * Sets the checked state of the checkbox.
+ * On is always based on a string comparison between inputValue and the param.
+ * @param {Boolean/String} value - the value to set
+ * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
+ */
+ setValue : function(v,suppressEvent){
+
+
+ //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
+ //if(this.el && this.el.dom){
+ // this.el.dom.checked = this.checked;
+ // this.el.dom.defaultChecked = this.checked;
+ //}
+ this.setChecked(String(v) === String(this.inputValue), suppressEvent);
+ //this.fireEvent("check", this, this.checked);
+ },
+ // private..
+ setChecked : function(state,suppressEvent)
+ {
+ if (this.inSetChecked) {
+ this.checked = state;
+ return;
}
- ts.innerHTML = v;
- var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
- if(h != this.lastHeight){
- this.lastHeight = h;
- this.el.setHeight(h);
- this.fireEvent("autosize", this, h);
+
+
+ if(this.wrap){
+ this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
+ }
+ this.checked = state;
+ if(suppressEvent !== true){
+ this.fireEvent('check', this, state);
}
+ this.inSetChecked = true;
+
+ this.el.dom.value = state ? this.inputValue : this.valueOff;
+
+ this.inSetChecked = false;
+
+ },
+ // handle setting of hidden value by some other method!!?!?
+ setFromHidden: function()
+ {
+ if(!this.el){
+ return;
+ }
+ //console.log("SET FROM HIDDEN");
+ //alert('setFrom hidden');
+ this.setValue(this.el.dom.value);
+ },
+
+ onDestroy : function()
+ {
+ if(this.viewEl){
+ Roo.get(this.viewEl).remove();
+ }
+
+ Roo.form.Checkbox.superclass.onDestroy.call(this);
+ },
+
+ setBoxLabel : function(str)
+ {
+ this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
}
+
});/*
* Based on:
* Ext JS Library 1.1.1
* <script type="text/javascript">
*/
-
/**
- * @class Roo.form.NumberField
- * @extends Roo.form.TextField
- * Numeric text field that provides automatic keystroke filtering and numeric validation.
+ * @class Roo.form.Radio
+ * @extends Roo.form.Checkbox
+ * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
+ * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
* @constructor
- * Creates a new NumberField
+ * Creates a new Radio
* @param {Object} config Configuration options
*/
-Roo.form.NumberField = function(config){
- Roo.form.NumberField.superclass.constructor.call(this, config);
+Roo.form.Radio = function(){
+ Roo.form.Radio.superclass.constructor.apply(this, arguments);
};
+Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
+ inputType: 'radio',
-Roo.extend(Roo.form.NumberField, Roo.form.TextField, {
- /**
- * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
- */
- fieldClass: "x-form-field x-form-num-field",
- /**
- * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
- */
- allowDecimals : true,
- /**
- * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
- */
- decimalSeparator : ".",
- /**
- * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
- */
- decimalPrecision : 2,
- /**
- * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
- */
- allowNegative : true,
- /**
- * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
- */
- minValue : Number.NEGATIVE_INFINITY,
- /**
- * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
- */
- maxValue : Number.MAX_VALUE,
- /**
- * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
- */
- minText : "The minimum value for this field is {0}",
/**
- * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
+ * If this radio is part of a group, it will return the selected value
+ * @return {String}
*/
- maxText : "The maximum value for this field is {0}",
+ getGroupValue : function(){
+ return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
+ },
+
+
+ onRender : function(ct, position){
+ Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
+
+ if(this.inputValue !== undefined){
+ this.el.dom.value = this.inputValue;
+ }
+
+ this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
+ //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
+ //var viewEl = this.wrap.createChild({
+ // tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
+ //this.viewEl = viewEl;
+ //this.wrap.on('click', this.onClick, this);
+
+ //this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
+ //this.el.on('propertychange', this.setFromHidden, this); //ie
+
+
+
+ if(this.boxLabel){
+ this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
+ // viewEl.on('click', this.onClick, this);
+ }
+ if(this.checked){
+ this.el.dom.checked = 'checked' ;
+ }
+
+ },
/**
- * @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
- * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
+ * Sets the checked state of the checkbox.
+ * On is always based on a string comparison between inputValue and the param.
+ * @param {Boolean/String} value - the value to set
+ * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
*/
- nanText : "{0} is not a valid number",
-
- // private
- initEvents : function(){
- Roo.form.NumberField.superclass.initEvents.call(this);
- var allowed = "0123456789";
- if(this.allowDecimals){
- allowed += this.decimalSeparator;
+ setValue : function(v,suppressEvent){
+
+
+ //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
+ //if(this.el && this.el.dom){
+ // this.el.dom.checked = this.checked;
+ // this.el.dom.defaultChecked = this.checked;
+ //}
+ this.setChecked(String(v) === String(this.inputValue), suppressEvent);
+
+ this.el.dom.form[this.name].value = v;
+
+ //this.fireEvent("check", this, this.checked);
+ },
+ // private..
+ setChecked : function(state,suppressEvent)
+ {
+
+ if(this.wrap){
+ this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
}
- if(this.allowNegative){
- allowed += "-";
+ this.checked = state;
+ if(suppressEvent !== true){
+ this.fireEvent('check', this, state);
}
- this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
- var keyPress = function(e){
- var k = e.getKey();
- if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
+
+
+
+
+ },
+ reset : function(){
+ // this.setValue(this.resetValue);
+ //this.originalValue = this.getValue();
+ this.clearInvalid();
+ }
+
+});Roo.rtf = {}; // namespace
+Roo.rtf.Hex = function(hex)
+{
+ this.hexstr = hex;
+};
+Roo.rtf.Paragraph = function(opts)
+{
+ this.content = []; ///??? is that used?
+};Roo.rtf.Span = function(opts)
+{
+ this.value = opts.value;
+};
+
+Roo.rtf.Group = function(parent)
+{
+ // we dont want to acutally store parent - it will make debug a nightmare..
+ this.content = [];
+ this.cn = [];
+
+
+
+};
+
+Roo.rtf.Group.prototype = {
+ ignorable : false,
+ content: false,
+ cn: false,
+ addContent : function(node) {
+ // could set styles...
+ this.content.push(node);
+ },
+ addChild : function(cn)
+ {
+ this.cn.push(cn);
+ },
+ // only for images really...
+ toDataURL : function()
+ {
+ var mimetype = false;
+ switch(true) {
+ case this.content.filter(function(a) { return a.value == 'pngblip' } ).length > 0:
+ mimetype = "image/png";
+ break;
+ case this.content.filter(function(a) { return a.value == 'jpegblip' } ).length > 0:
+ mimetype = "image/jpeg";
+ break;
+ default :
+ return 'about:blank'; // ?? error?
+ }
+
+
+ var hexstring = this.content[this.content.length-1].value;
+
+ return 'data:' + mimetype + ';base64,' + btoa(hexstring.match(/\w{2}/g).map(function(a) {
+ return String.fromCharCode(parseInt(a, 16));
+ }).join(""));
+ }
+
+};
+// this looks like it's normally the {rtf{ .... }}
+Roo.rtf.Document = function()
+{
+ // we dont want to acutally store parent - it will make debug a nightmare..
+ this.rtlch = [];
+ this.content = [];
+ this.cn = [];
+
+};
+Roo.extend(Roo.rtf.Document, Roo.rtf.Group, {
+ addChild : function(cn)
+ {
+ this.cn.push(cn);
+ switch(cn.type) {
+ case 'rtlch': // most content seems to be inside this??
+ case 'listtext':
+ case 'shpinst':
+ this.rtlch.push(cn);
return;
+ default:
+ this[cn.type] = cn;
+ }
+
+ },
+
+ getElementsByType : function(type)
+ {
+ var ret = [];
+ this._getElementsByType(type, ret, this.cn, 'rtf');
+ return ret;
+ },
+ _getElementsByType : function (type, ret, search_array, path)
+ {
+ search_array.forEach(function(n,i) {
+ if (n.type == type) {
+ n.path = path + '/' + n.type + ':' + i;
+ ret.push(n);
}
- var c = e.getCharCode();
- if(allowed.indexOf(String.fromCharCode(c)) === -1){
- e.stopEvent();
+ if (n.cn.length > 0) {
+ this._getElementsByType(type, ret, n.cn, path + '/' + n.type+':'+i);
}
- };
- this.el.on("keypress", keyPress, this);
- },
+ },this);
+ }
+
+});
+
+Roo.rtf.Ctrl = function(opts)
+{
+ this.value = opts.value;
+ this.param = opts.param;
+};
+/**
+ *
+ *
+ * based on this https://github.com/iarna/rtf-parser
+ * it's really only designed to extract pict from pasted RTF
+ *
+ * usage:
+ *
+ * var images = new Roo.rtf.Parser().parse(a_string).filter(function(g) { return g.type == 'pict'; });
+ *
+ *
+ */
- // private
- validateValue : function(value){
- if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
- return false;
+
+
+
+
+Roo.rtf.Parser = function(text) {
+ //super({objectMode: true})
+ this.text = '';
+ this.parserState = this.parseText;
+
+ // these are for interpeter...
+ this.doc = {};
+ ///this.parserState = this.parseTop
+ this.groupStack = [];
+ this.hexStore = [];
+ this.doc = false;
+
+ this.groups = []; // where we put the return.
+
+ for (var ii = 0; ii < text.length; ++ii) {
+ ++this.cpos;
+
+ if (text[ii] === '\n') {
+ ++this.row;
+ this.col = 1;
+ } else {
+ ++this.col;
+ }
+ this.parserState(text[ii]);
+ }
+
+
+
+};
+Roo.rtf.Parser.prototype = {
+ text : '', // string being parsed..
+ controlWord : '',
+ controlWordParam : '',
+ hexChar : '',
+ doc : false,
+ group: false,
+ groupStack : false,
+ hexStore : false,
+
+
+ cpos : 0,
+ row : 1, // reportin?
+ col : 1, //
+
+
+ push : function (el)
+ {
+ var m = 'cmd'+ el.type;
+ if (typeof(this[m]) == 'undefined') {
+ Roo.log('invalid cmd:' + el.type);
+ return;
+ }
+ this[m](el);
+ //Roo.log(el);
+ },
+ flushHexStore : function()
+ {
+ if (this.hexStore.length < 1) {
+ return;
+ }
+ var hexstr = this.hexStore.map(
+ function(cmd) {
+ return cmd.value;
+ }).join('');
+
+ this.group.addContent( new Roo.rtf.Hex( hexstr ));
+
+
+ this.hexStore.splice(0)
+
+ },
+
+ cmdgroupstart : function()
+ {
+ this.flushHexStore();
+ if (this.group) {
+ this.groupStack.push(this.group);
+ }
+ // parent..
+ if (this.doc === false) {
+ this.group = this.doc = new Roo.rtf.Document();
+ return;
+
+ }
+ this.group = new Roo.rtf.Group(this.group);
+ },
+ cmdignorable : function()
+ {
+ this.flushHexStore();
+ this.group.ignorable = true;
+ },
+ cmdendparagraph : function()
+ {
+ this.flushHexStore();
+ this.group.addContent(new Roo.rtf.Paragraph());
+ },
+ cmdgroupend : function ()
+ {
+ this.flushHexStore();
+ var endingGroup = this.group;
+
+
+ this.group = this.groupStack.pop();
+ if (this.group) {
+ this.group.addChild(endingGroup);
+ }
+
+
+
+ var doc = this.group || this.doc;
+ //if (endingGroup instanceof FontTable) {
+ // doc.fonts = endingGroup.table
+ //} else if (endingGroup instanceof ColorTable) {
+ // doc.colors = endingGroup.table
+ //} else if (endingGroup !== this.doc && !endingGroup.get('ignorable')) {
+ if (endingGroup.ignorable === false) {
+ //code
+ this.groups.push(endingGroup);
+ // Roo.log( endingGroup );
+ }
+ //Roo.each(endingGroup.content, function(item)) {
+ // doc.addContent(item);
+ //}
+ //process.emit('debug', 'GROUP END', endingGroup.type, endingGroup.get('ignorable'))
+ //}
+ },
+ cmdtext : function (cmd)
+ {
+ this.flushHexStore();
+ if (!this.group) { // an RTF fragment, missing the {\rtf1 header
+ //this.group = this.doc
+ return; // we really don't care about stray text...
+ }
+ this.group.addContent(new Roo.rtf.Span(cmd));
+ },
+ cmdcontrolword : function (cmd)
+ {
+ this.flushHexStore();
+ if (!this.group.type) {
+ this.group.type = cmd.value;
+ return;
+ }
+ this.group.addContent(new Roo.rtf.Ctrl(cmd));
+ // we actually don't care about ctrl words...
+ return ;
+ /*
+ var method = 'ctrl$' + cmd.value.replace(/-(.)/g, (_, char) => char.toUpperCase())
+ if (this[method]) {
+ this[method](cmd.param)
+ } else {
+ if (!this.group.get('ignorable')) process.emit('debug', method, cmd.param)
+ }
+ */
+ },
+ cmdhexchar : function(cmd) {
+ this.hexStore.push(cmd);
+ },
+ cmderror : function(cmd) {
+ throw cmd.value;
+ },
+
+ /*
+ _flush (done) {
+ if (this.text !== '\u0000') this.emitText()
+ done()
+ }
+ */
+
+
+ parseText : function(c)
+ {
+ if (c === '\\') {
+ this.parserState = this.parseEscapes;
+ } else if (c === '{') {
+ this.emitStartGroup();
+ } else if (c === '}') {
+ this.emitEndGroup();
+ } else if (c === '\x0A' || c === '\x0D') {
+ // cr/lf are noise chars
+ } else {
+ this.text += c;
+ }
+ },
+
+ parseEscapes: function (c)
+ {
+ if (c === '\\' || c === '{' || c === '}') {
+ this.text += c;
+ this.parserState = this.parseText;
+ } else {
+ this.parserState = this.parseControlSymbol;
+ this.parseControlSymbol(c);
+ }
+ },
+ parseControlSymbol: function(c)
+ {
+ if (c === '~') {
+ this.text += '\u00a0'; // nbsp
+ this.parserState = this.parseText
+ } else if (c === '-') {
+ this.text += '\u00ad'; // soft hyphen
+ } else if (c === '_') {
+ this.text += '\u2011'; // non-breaking hyphen
+ } else if (c === '*') {
+ this.emitIgnorable();
+ this.parserState = this.parseText;
+ } else if (c === "'") {
+ this.parserState = this.parseHexChar;
+ } else if (c === '|') { // formula cacter
+ this.emitFormula();
+ this.parserState = this.parseText;
+ } else if (c === ':') { // subentry in an index entry
+ this.emitIndexSubEntry();
+ this.parserState = this.parseText;
+ } else if (c === '\x0a') {
+ this.emitEndParagraph();
+ this.parserState = this.parseText;
+ } else if (c === '\x0d') {
+ this.emitEndParagraph();
+ this.parserState = this.parseText;
+ } else {
+ this.parserState = this.parseControlWord;
+ this.parseControlWord(c);
+ }
+ },
+ parseHexChar: function (c)
+ {
+ if (/^[A-Fa-f0-9]$/.test(c)) {
+ this.hexChar += c;
+ if (this.hexChar.length >= 2) {
+ this.emitHexChar();
+ this.parserState = this.parseText;
+ }
+ return;
}
- if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
- return true;
+ this.emitError("Invalid character \"" + c + "\" in hex literal.");
+ this.parserState = this.parseText;
+
+ },
+ parseControlWord : function(c)
+ {
+ if (c === ' ') {
+ this.emitControlWord();
+ this.parserState = this.parseText;
+ } else if (/^[-\d]$/.test(c)) {
+ this.parserState = this.parseControlWordParam;
+ this.controlWordParam += c;
+ } else if (/^[A-Za-z]$/.test(c)) {
+ this.controlWord += c;
+ } else {
+ this.emitControlWord();
+ this.parserState = this.parseText;
+ this.parseText(c);
}
- var num = this.parseValue(value);
- if(isNaN(num)){
- this.markInvalid(String.format(this.nanText, value));
- return false;
+ },
+ parseControlWordParam : function (c) {
+ if (/^\d$/.test(c)) {
+ this.controlWordParam += c;
+ } else if (c === ' ') {
+ this.emitControlWord();
+ this.parserState = this.parseText;
+ } else {
+ this.emitControlWord();
+ this.parserState = this.parseText;
+ this.parseText(c);
}
- if(num < this.minValue){
- this.markInvalid(String.format(this.minText, this.minValue));
- return false;
+ },
+
+
+
+
+ emitText : function () {
+ if (this.text === '') {
+ return;
}
- if(num > this.maxValue){
- this.markInvalid(String.format(this.maxText, this.maxValue));
- return false;
+ this.push({
+ type: 'text',
+ value: this.text,
+ pos: this.cpos,
+ row: this.row,
+ col: this.col
+ });
+ this.text = ''
+ },
+ emitControlWord : function ()
+ {
+ this.emitText();
+ if (this.controlWord === '') {
+ // do we want to track this - it seems just to cause problems.
+ //this.emitError('empty control word');
+ } else {
+ this.push({
+ type: 'controlword',
+ value: this.controlWord,
+ param: this.controlWordParam !== '' && Number(this.controlWordParam),
+ pos: this.cpos,
+ row: this.row,
+ col: this.col
+ });
}
- return true;
+ this.controlWord = '';
+ this.controlWordParam = '';
},
-
- getValue : function(){
- return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
+ emitStartGroup : function ()
+ {
+ this.emitText();
+ this.push({
+ type: 'groupstart',
+ pos: this.cpos,
+ row: this.row,
+ col: this.col
+ });
},
-
- // private
- parseValue : function(value){
- value = parseFloat(String(value).replace(this.decimalSeparator, "."));
- return isNaN(value) ? '' : value;
+ emitEndGroup : function ()
+ {
+ this.emitText();
+ this.push({
+ type: 'groupend',
+ pos: this.cpos,
+ row: this.row,
+ col: this.col
+ });
},
-
- // private
- fixPrecision : function(value){
- var nan = isNaN(value);
- if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
- return nan ? '' : value;
- }
- return parseFloat(value).toFixed(this.decimalPrecision);
+ emitIgnorable : function ()
+ {
+ this.emitText();
+ this.push({
+ type: 'ignorable',
+ pos: this.cpos,
+ row: this.row,
+ col: this.col
+ });
},
-
- setValue : function(v){
- v = this.fixPrecision(v);
- Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
+ emitHexChar : function ()
+ {
+ this.emitText();
+ this.push({
+ type: 'hexchar',
+ value: this.hexChar,
+ pos: this.cpos,
+ row: this.row,
+ col: this.col
+ });
+ this.hexChar = ''
},
-
- // private
- decimalPrecisionFcn : function(v){
- return Math.floor(v);
+ emitError : function (message)
+ {
+ this.emitText();
+ this.push({
+ type: 'error',
+ value: message,
+ row: this.row,
+ col: this.col,
+ char: this.cpos //,
+ //stack: new Error().stack
+ });
},
-
- beforeBlur : function(){
- var v = this.parseValue(this.getRawValue());
- if(v){
- this.setValue(v);
- }
+ emitEndParagraph : function () {
+ this.emitText();
+ this.push({
+ type: 'endparagraph',
+ pos: this.cpos,
+ row: this.row,
+ col: this.col
+ });
}
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
+
+} ;
+Roo.htmleditor = {};
/**
- * @class Roo.form.DateField
- * @extends Roo.form.TriggerField
- * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
-* @constructor
-* Create a new DateField
-* @param {Object} config
+ * @class Roo.htmleditor.Filter
+ * Base Class for filtering htmleditor stuff. - do not use this directly - extend it.
+ * @cfg {DomElement} node The node to iterate and filter
+ * @cfg {boolean|String|Array} tag Tags to replace
+ * @constructor
+ * Create a new Filter.
+ * @param {Object} config Configuration options
*/
-Roo.form.DateField = function(config)
-{
- Roo.form.DateField.superclass.constructor.call(this, config);
-
- this.addEvents({
-
- /**
- * @event select
- * Fires when a date is selected
- * @param {Roo.form.DateField} combo This combo box
- * @param {Date} date The date selected
- */
- 'select' : true
-
- });
-
-
- if(typeof this.minValue == "string") {
- this.minValue = this.parseDate(this.minValue);
- }
- if(typeof this.maxValue == "string") {
- this.maxValue = this.parseDate(this.maxValue);
- }
- this.ddMatch = null;
- if(this.disabledDates){
- var dd = this.disabledDates;
- var re = "(?:";
- for(var i = 0; i < dd.length; i++){
- re += dd[i];
- if(i != dd.length-1) {
- re += "|";
- }
- }
- this.ddMatch = new RegExp(re + ")");
- }
-};
-Roo.extend(Roo.form.DateField, Roo.form.TriggerField, {
- /**
- * @cfg {String} format
- * The default date format string which can be overriden for localization support. The format must be
- * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
- */
- format : "m/d/y",
- /**
- * @cfg {String} altFormats
- * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
- * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
- */
- altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
- /**
- * @cfg {Array} disabledDays
- * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
- */
- disabledDays : null,
- /**
- * @cfg {String} disabledDaysText
- * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
- */
- disabledDaysText : "Disabled",
- /**
- * @cfg {Array} disabledDates
- * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
- * expression so they are very powerful. Some examples:
- * <ul>
- * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
- * <li>["03/08", "09/16"] would disable those days for every year</li>
- * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
- * <li>["03/../2006"] would disable every day in March 2006</li>
- * <li>["^03"] would disable every day in every March</li>
- * </ul>
- * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
- * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
- */
- disabledDates : null,
- /**
- * @cfg {String} disabledDatesText
- * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
- */
- disabledDatesText : "Disabled",
-
-
- /**
- * @cfg {Date/String} zeroValue
- * if the date is less that this number, then the field is rendered as empty
- * default is 1800
- */
- zeroValue : '1800-01-01',
-
-
- /**
- * @cfg {Date/String} minValue
- * The minimum allowed date. Can be either a Javascript date object or a string date in a
- * valid format (defaults to null).
- */
- minValue : null,
- /**
- * @cfg {Date/String} maxValue
- * The maximum allowed date. Can be either a Javascript date object or a string date in a
- * valid format (defaults to null).
- */
- maxValue : null,
- /**
- * @cfg {String} minText
- * The error text to display when the date in the cell is before minValue (defaults to
- * 'The date in this field must be after {minValue}').
- */
- minText : "The date in this field must be equal to or after {0}",
- /**
- * @cfg {String} maxText
- * The error text to display when the date in the cell is after maxValue (defaults to
- * 'The date in this field must be before {maxValue}').
- */
- maxText : "The date in this field must be equal to or before {0}",
- /**
- * @cfg {String} invalidText
- * The error text to display when the date in the field is invalid (defaults to
- * '{value} is not a valid date - it must be in the format {format}').
- */
- invalidText : "{0} is not a valid date - it must be in the format {1}",
- /**
- * @cfg {String} triggerClass
- * An additional CSS class used to style the trigger button. The trigger will always get the
- * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
- * which displays a calendar icon).
- */
- triggerClass : 'x-form-date-trigger',
+
+
+Roo.htmleditor.Filter = function(cfg) {
+ Roo.apply(this.cfg);
+ // this does not actually call walk as it's really just a abstract class
+}
+
+
+Roo.htmleditor.Filter.prototype = {
+ node: false,
+
+ tag: false,
- /**
- * @cfg {Boolean} useIso
- * if enabled, then the date field will use a hidden field to store the
- * real value as iso formated date. default (false)
- */
- useIso : false,
- /**
- * @cfg {String/Object} autoCreate
- * A DomHelper element spec, or true for a default element spec (defaults to
- * {tag: "input", type: "text", size: "10", autocomplete: "off"})
- */
- // private
- defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
+ // overrride to do replace comments.
+ replaceComment : false,
- // private
- hiddenField: false,
+ // overrride to do replace or do stuff with tags..
+ replaceTag : false,
- onRender : function(ct, position)
+ walk : function(dom)
{
- Roo.form.DateField.superclass.onRender.call(this, ct, position);
- if (this.useIso) {
- //this.el.dom.removeAttribute('name');
- Roo.log("Changing name?");
- this.el.dom.setAttribute('name', this.name + '____hidden___' );
- this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
- 'before', true);
- this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
- // prevent input submission
- this.hiddenName = this.name;
- }
-
+ Roo.each( Array.from(dom.childNodes), function( e ) {
+ switch(true) {
+
+ case e.nodeType == 8 && this.replaceComment !== false: // comment
+ this.replaceComment(e);
+ return;
+
+ case e.nodeType != 1: //not a node.
+ return;
+
+ case this.tag === true: // everything
+ case e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1:
+ case e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'string' && this.tag == ":":
+ case typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1: // array and it matches.
+ case typeof(this.tag) == 'string' && this.tag == e.tagName: // array and it matches.
+ if (this.replaceTag && false === this.replaceTag(e)) {
+ return;
+ }
+ if (e.hasChildNodes()) {
+ this.walk(e);
+ }
+ return;
+
+ default: // tags .. that do not match.
+ if (e.hasChildNodes()) {
+ this.walk(e);
+ }
+ }
+ }, this);
+
},
- // private
- validateValue : function(value)
+
+ removeNodeKeepChildren : function( node)
{
- value = this.formatDate(value);
- if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
- Roo.log('super failed');
- return false;
- }
- if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
- return true;
- }
- var svalue = value;
- value = this.parseDate(value);
- if(!value){
- Roo.log('parse date failed' + svalue);
- this.markInvalid(String.format(this.invalidText, svalue, this.format));
- return false;
- }
- var time = value.getTime();
- if(this.minValue && time < this.minValue.getTime()){
- this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
- return false;
- }
- if(this.maxValue && time > this.maxValue.getTime()){
- this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
- return false;
- }
- if(this.disabledDays){
- var day = value.getDay();
- for(var i = 0; i < this.disabledDays.length; i++) {
- if(day === this.disabledDays[i]){
- this.markInvalid(this.disabledDaysText);
- return false;
- }
- }
- }
- var fvalue = this.formatDate(value);
- if(this.ddMatch && this.ddMatch.test(fvalue)){
- this.markInvalid(String.format(this.disabledDatesText, fvalue));
- return false;
+
+ ar = Array.from(node.childNodes);
+ for (var i = 0; i < ar.length; i++) {
+
+ node.removeChild(ar[i]);
+ // what if we need to walk these???
+ node.parentNode.insertBefore(ar[i], node);
+
}
- return true;
+ node.parentNode.removeChild(node);
},
- // private
- // Provides logic to override the default TriggerField.validateBlur which just returns true
- validateBlur : function(){
- return !this.menu || !this.menu.isVisible();
- },
-
- getName: function()
+ searchTag : function(dom)
{
- // returns hidden if it's set..
- if (!this.rendered) {return ''};
- return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
-
- },
+ if(this.tag === false) {
+ return;
+ }
- /**
- * Returns the current date value of the date field.
- * @return {Date} The date value
- */
- getValue : function(){
-
- return this.hiddenField ?
- this.hiddenField.value :
- this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
- },
+ var els = dom.getElementsByTagName(this.tag);
- /**
- * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
- * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
- * (the default format used is "m/d/y").
- * <br />Usage:
- * <pre><code>
-//All of these calls set the same date value (May 4, 2006)
+ Roo.each(Array.from(els), function(e){
+ if(e.parentNode == null) {
+ return;
+ }
+ if(this.replaceTag) {
+ this.replaceTag(e);
+ }
+ }, this);
+ }
+};
-//Pass a date object:
-var dt = new Date('5/4/06');
-dateField.setValue(dt);
+/**
+ * @class Roo.htmleditor.FilterAttributes
+ * clean attributes and styles including http:// etc.. in attribute
+ * @constructor
+* Run a new Attribute Filter
+* @param {Object} config Configuration options
+ */
+Roo.htmleditor.FilterAttributes = function(cfg)
+{
+ Roo.apply(this, cfg);
+ this.attrib_black = this.attrib_black || [];
+ this.attrib_white = this.attrib_white || [];
-//Pass a date string (default format):
-dateField.setValue('5/4/06');
+ this.attrib_clean = this.attrib_clean || [];
+ this.style_white = this.style_white || [];
+ this.style_black = this.style_black || [];
+ this.walk(cfg.node);
+}
-//Pass a date string (custom format):
-dateField.format = 'Y-m-d';
-dateField.setValue('2006-5-4');
-</code></pre>
- * @param {String/Date} date The date or valid date string
- */
- setValue : function(date){
- if (this.hiddenField) {
- this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
+Roo.extend(Roo.htmleditor.FilterAttributes, Roo.htmleditor.Filter,
+{
+ tag: true, // all tags
+
+ attrib_black : false, // array
+ attrib_clean : false,
+ attrib_white : false,
+
+ style_white : false,
+ style_black : false,
+
+
+ replaceTag : function(node)
+ {
+ if (!node.attributes || !node.attributes.length) {
+ return true;
}
- Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
- // make sure the value field is always stored as a date..
- this.value = this.parseDate(date);
-
+ for (var i = node.attributes.length-1; i > -1 ; i--) {
+ var a = node.attributes[i];
+ //console.log(a);
+ if (this.attrib_white.length && this.attrib_white.indexOf(a.name.toLowerCase()) < 0) {
+ node.removeAttribute(a.name);
+ continue;
+ }
+
+
+
+ if (a.name.toLowerCase().substr(0,2)=='on') {
+ node.removeAttribute(a.name);
+ continue;
+ }
+
+
+ if (this.attrib_black.indexOf(a.name.toLowerCase()) > -1) {
+ node.removeAttribute(a.name);
+ continue;
+ }
+ if (this.attrib_clean.indexOf(a.name.toLowerCase()) > -1) {
+ this.cleanAttr(node,a.name,a.value); // fixme..
+ continue;
+ }
+ if (a.name == 'style') {
+ this.cleanStyle(node,a.name,a.value);
+ continue;
+ }
+ /// clean up MS crap..
+ // tecnically this should be a list of valid class'es..
+
+
+ if (a.name == 'class') {
+ if (a.value.match(/^Mso/)) {
+ node.removeAttribute('class');
+ }
+
+ if (a.value.match(/^body$/)) {
+ node.removeAttribute('class');
+ }
+ continue;
+ }
+
+
+ // style cleanup!?
+ // class cleanup?
+
+ }
+ return true; // clean children
},
-
- // private
- parseDate : function(value){
-
- if (value instanceof Date) {
- if (value < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
- return '';
- }
- return value;
- }
-
-
- if(!value || value instanceof Date){
- return value;
+
+ cleanAttr: function(node, n,v)
+ {
+
+ if (v.match(/^\./) || v.match(/^\//)) {
+ return;
}
- var v = Date.parseDate(value, this.format);
- if (!v && this.useIso) {
- v = Date.parseDate(value, 'Y-m-d');
+ if (v.match(/^(http|https):\/\//)
+ || v.match(/^mailto:/)
+ || v.match(/^ftp:/)
+ || v.match(/^data:/)
+ ) {
+ return;
}
- if(!v && this.altFormats){
- if(!this.altFormatsArray){
- this.altFormatsArray = this.altFormats.split("|");
+ if (v.match(/^#/)) {
+ return;
+ }
+ if (v.match(/^\{/)) { // allow template editing.
+ return;
+ }
+// Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
+ node.removeAttribute(n);
+
+ },
+ cleanStyle : function(node, n,v)
+ {
+ if (v.match(/expression/)) { //XSS?? should we even bother..
+ node.removeAttribute(n);
+ return;
+ }
+
+ var parts = v.split(/;/);
+ var clean = [];
+
+ Roo.each(parts, function(p) {
+ p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
+ if (!p.length) {
+ return true;
}
- for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
- v = Date.parseDate(value, this.altFormatsArray[i]);
+ var l = p.split(':').shift().replace(/\s+/g,'');
+ l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
+
+ if ( this.style_black.length && (this.style_black.indexOf(l) > -1 || this.style_black.indexOf(l.toLowerCase()) > -1)) {
+ return true;
+ }
+ //Roo.log()
+ // only allow 'c whitelisted system attributes'
+ if ( this.style_white.length && style_white.indexOf(l) < 0 && style_white.indexOf(l.toLowerCase()) < 0 ) {
+ return true;
}
+
+
+ clean.push(p);
+ return true;
+ },this);
+ if (clean.length) {
+ node.setAttribute(n, clean.join(';'));
+ } else {
+ node.removeAttribute(n);
}
- if (v < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
- v = '';
- }
- return v;
- },
+
+ }
+
+
+
+
+});/**
+ * @class Roo.htmleditor.FilterBlack
+ * remove blacklisted elements.
+ * @constructor
+ * Run a new Blacklisted Filter
+ * @param {Object} config Configuration options
+ */
- // private
- formatDate : function(date, fmt){
- return (!date || !(date instanceof Date)) ?
- date : date.dateFormat(fmt || this.format);
- },
+Roo.htmleditor.FilterBlack = function(cfg)
+{
+ Roo.apply(this, cfg);
+ this.walk(cfg.node);
+}
- // private
- menuListeners : {
- select: function(m, d){
-
- this.setValue(d);
- this.fireEvent('select', this, d);
- },
- show : function(){ // retain focus styling
- this.onFocus();
- },
- hide : function(){
- this.focus.defer(10, this);
- var ml = this.menuListeners;
- this.menu.un("select", ml.select, this);
- this.menu.un("show", ml.show, this);
- this.menu.un("hide", ml.hide, this);
- }
- },
+Roo.extend(Roo.htmleditor.FilterBlack, Roo.htmleditor.Filter,
+{
+ tag : true, // all elements.
+
+ replaceTag : function(n)
+ {
+ n.parentNode.removeChild(n);
+ }
+});
+/**
+ * @class Roo.htmleditor.FilterComment
+ * remove comments.
+ * @constructor
+* Run a new Comments Filter
+* @param {Object} config Configuration options
+ */
+Roo.htmleditor.FilterComment = function(cfg)
+{
+ this.walk(cfg.node);
+}
+
+Roo.extend(Roo.htmleditor.FilterComment, Roo.htmleditor.Filter,
+{
+
+ replaceComment : function(n)
+ {
+ n.parentNode.removeChild(n);
+ }
+});/**
+ * @class Roo.htmleditor.FilterKeepChildren
+ * remove tags but keep children
+ * @constructor
+ * Run a new Keep Children Filter
+ * @param {Object} config Configuration options
+ */
- // private
- // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
- onTriggerClick : function(){
- if(this.disabled){
- return;
- }
- if(this.menu == null){
- this.menu = new Roo.menu.DateMenu();
- }
- Roo.apply(this.menu.picker, {
- showClear: this.allowBlank,
- minDate : this.minValue,
- maxDate : this.maxValue,
- disabledDatesRE : this.ddMatch,
- disabledDatesText : this.disabledDatesText,
- disabledDays : this.disabledDays,
- disabledDaysText : this.disabledDaysText,
- format : this.useIso ? 'Y-m-d' : this.format,
- minText : String.format(this.minText, this.formatDate(this.minValue)),
- maxText : String.format(this.maxText, this.formatDate(this.maxValue))
- });
- this.menu.on(Roo.apply({}, this.menuListeners, {
- scope:this
- }));
- this.menu.picker.setValue(this.getValue() || new Date());
- this.menu.show(this.el, "tl-bl?");
- },
+Roo.htmleditor.FilterKeepChildren = function(cfg)
+{
+ Roo.apply(this, cfg);
+ if (this.tag === false) {
+ return; // dont walk.. (you can use this to use this just to do a child removal on a single tag )
+ }
+ // hacky?
+ if ((typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1)) {
+ this.cleanNamespace = true;
+ }
+
+ this.walk(cfg.node);
+}
- beforeBlur : function(){
- var v = this.parseDate(this.getRawValue());
- if(v){
- this.setValue(v);
+Roo.extend(Roo.htmleditor.FilterKeepChildren, Roo.htmleditor.FilterBlack,
+{
+ cleanNamespace : false, // should really be an option, rather than using ':' inside of this tag.
+
+ replaceTag : function(node)
+ {
+ // walk children...
+ //Roo.log(node.tagName);
+ var ar = Array.from(node.childNodes);
+ //remove first..
+
+ for (var i = 0; i < ar.length; i++) {
+ var e = ar[i];
+ if (e.nodeType == 1) {
+ if (
+ (typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1)
+ || // array and it matches
+ (typeof(this.tag) == 'string' && this.tag == e.tagName)
+ ||
+ (e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1)
+ ||
+ (e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'string' && this.tag == ":")
+ ) {
+ this.replaceTag(ar[i]); // child is blacklisted as well...
+ continue;
+ }
+ }
+ }
+ ar = Array.from(node.childNodes);
+ for (var i = 0; i < ar.length; i++) {
+
+ node.removeChild(ar[i]);
+ // what if we need to walk these???
+ node.parentNode.insertBefore(ar[i], node);
+ if (this.tag !== false) {
+ this.walk(ar[i]);
+
+ }
}
- },
+ //Roo.log("REMOVE:" + node.tagName);
+ node.parentNode.removeChild(node);
+ return false; // don't walk children
+
+
+ }
+});/**
+ * @class Roo.htmleditor.FilterParagraph
+ * paragraphs cause a nightmare for shared content - this filter is designed to be called ? at various points when editing
+ * like on 'push' to remove the <p> tags and replace them with line breaks.
+ * @constructor
+ * Run a new Paragraph Filter
+ * @param {Object} config Configuration options
+ */
- /*@
- * overide
- *
- */
- isDirty : function() {
- if(this.disabled) {
- return false;
- }
+Roo.htmleditor.FilterParagraph = function(cfg)
+{
+ // no need to apply config.
+ this.searchTag(cfg.node);
+}
+
+Roo.extend(Roo.htmleditor.FilterParagraph, Roo.htmleditor.Filter,
+{
+
+
+ tag : 'P',
+
+
+ replaceTag : function(node)
+ {
- if(typeof(this.startValue) === 'undefined'){
- return false;
+ if (node.childNodes.length == 1 &&
+ node.childNodes[0].nodeType == 3 &&
+ node.childNodes[0].textContent.trim().length < 1
+ ) {
+ // remove and replace with '<BR>';
+ node.parentNode.replaceChild(node.ownerDocument.createElement('BR'),node);
+ return false; // no need to walk..
+ }
+
+ var ar = Array.from(node.childNodes);
+ for (var i = 0; i < ar.length; i++) {
+ node.removeChild(ar[i]);
+ // what if we need to walk these???
+ node.parentNode.insertBefore(ar[i], node);
}
+ // now what about this?
+ // <p> </p>
- return String(this.getValue()) !== String(this.startValue);
+ // double BR.
+ node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
+ node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
+ node.parentNode.removeChild(node);
- },
- // @overide
- cleanLeadingSpace : function(e)
- {
- return;
+ return false;
+
}
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
+});/**
+ * @class Roo.htmleditor.FilterHashLink
+ * remove hash link
+ * @constructor
+ * Run a new Hash Link Filter
+ * @param {Object} config Configuration options
*/
+
+ Roo.htmleditor.FilterHashLink = function(cfg)
+ {
+ // no need to apply config.
+ // this.walk(cfg.node);
+ this.searchTag(cfg.node);
+ }
-/**
- * @class Roo.form.MonthField
- * @extends Roo.form.TriggerField
- * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
-* @constructor
-* Create a new MonthField
-* @param {Object} config
+ Roo.extend(Roo.htmleditor.FilterHashLink, Roo.htmleditor.Filter,
+ {
+
+ tag : 'A',
+
+
+ replaceTag : function(node)
+ {
+ for(var i = 0; i < node.attributes.length; i ++) {
+ var a = node.attributes[i];
+
+ if(a.name.toLowerCase() == 'href' && a.value.startsWith('#')) {
+ this.removeNodeKeepChildren(node);
+ }
+ }
+
+ return false;
+
+ }
+
+ });/**
+ * @class Roo.htmleditor.FilterSpan
+ * filter span's with no attributes out..
+ * @constructor
+ * Run a new Span Filter
+ * @param {Object} config Configuration options
*/
-Roo.form.MonthField = function(config){
+
+Roo.htmleditor.FilterSpan = function(cfg)
+{
+ // no need to apply config.
+ this.searchTag(cfg.node);
+}
+
+Roo.extend(Roo.htmleditor.FilterSpan, Roo.htmleditor.FilterKeepChildren,
+{
+
+ tag : 'SPAN',
+
+
+ replaceTag : function(node)
+ {
+ if (node.attributes && node.attributes.length > 0) {
+ return true; // walk if there are any.
+ }
+ Roo.htmleditor.FilterKeepChildren.prototype.replaceTag.call(this, node);
+ return false;
+
+ }
- Roo.form.MonthField.superclass.constructor.call(this, config);
+});/**
+ * @class Roo.htmleditor.FilterTableWidth
+ try and remove table width data - as that frequently messes up other stuff.
+ *
+ * was cleanTableWidths.
+ *
+ * Quite often pasting from word etc.. results in tables with column and widths.
+ * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
+ *
+ * @constructor
+ * Run a new Table Filter
+ * @param {Object} config Configuration options
+ */
+
+Roo.htmleditor.FilterTableWidth = function(cfg)
+{
+ // no need to apply config.
+ this.tag = ['TABLE', 'TD', 'TR', 'TH', 'THEAD', 'TBODY' ];
+ this.walk(cfg.node);
+}
+
+Roo.extend(Roo.htmleditor.FilterTableWidth, Roo.htmleditor.Filter,
+{
+
+
- this.addEvents({
-
- /**
- * @event select
- * Fires when a date is selected
- * @param {Roo.form.MonthFieeld} combo This combo box
- * @param {Date} date The date selected
- */
- 'select' : true
+ replaceTag: function(node) {
+
+
+
+ if (node.hasAttribute('width')) {
+ node.removeAttribute('width');
+ }
+
- });
-
-
- if(typeof this.minValue == "string") {
- this.minValue = this.parseDate(this.minValue);
- }
- if(typeof this.maxValue == "string") {
- this.maxValue = this.parseDate(this.maxValue);
- }
- this.ddMatch = null;
- if(this.disabledDates){
- var dd = this.disabledDates;
- var re = "(?:";
- for(var i = 0; i < dd.length; i++){
- re += dd[i];
- if(i != dd.length-1) {
- re += "|";
+ if (node.hasAttribute("style")) {
+ // pretty basic...
+
+ var styles = node.getAttribute("style").split(";");
+ var nstyle = [];
+ Roo.each(styles, function(s) {
+ if (!s.match(/:/)) {
+ return;
+ }
+ var kv = s.split(":");
+ if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
+ return;
+ }
+ // what ever is left... we allow.
+ nstyle.push(s);
+ });
+ node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
+ if (!nstyle.length) {
+ node.removeAttribute('style');
}
}
- this.ddMatch = new RegExp(re + ")");
+
+ return true; // continue doing children..
}
-};
-
-Roo.extend(Roo.form.MonthField, Roo.form.TriggerField, {
- /**
- * @cfg {String} format
- * The default date format string which can be overriden for localization support. The format must be
- * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
- */
- format : "M Y",
- /**
- * @cfg {String} altFormats
- * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
- * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
- */
- altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
- /**
- * @cfg {Array} disabledDays
- * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
- */
- disabledDays : [0,1,2,3,4,5,6],
- /**
- * @cfg {String} disabledDaysText
- * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
- */
- disabledDaysText : "Disabled",
- /**
- * @cfg {Array} disabledDates
- * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
- * expression so they are very powerful. Some examples:
- * <ul>
- * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
- * <li>["03/08", "09/16"] would disable those days for every year</li>
- * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
- * <li>["03/../2006"] would disable every day in March 2006</li>
- * <li>["^03"] would disable every day in every March</li>
- * </ul>
- * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
- * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
- */
- disabledDates : null,
- /**
- * @cfg {String} disabledDatesText
- * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
- */
- disabledDatesText : "Disabled",
- /**
- * @cfg {Date/String} minValue
- * The minimum allowed date. Can be either a Javascript date object or a string date in a
- * valid format (defaults to null).
- */
- minValue : null,
- /**
- * @cfg {Date/String} maxValue
- * The maximum allowed date. Can be either a Javascript date object or a string date in a
- * valid format (defaults to null).
- */
- maxValue : null,
- /**
- * @cfg {String} minText
- * The error text to display when the date in the cell is before minValue (defaults to
- * 'The date in this field must be after {minValue}').
- */
- minText : "The date in this field must be equal to or after {0}",
- /**
- * @cfg {String} maxTextf
- * The error text to display when the date in the cell is after maxValue (defaults to
- * 'The date in this field must be before {maxValue}').
- */
- maxText : "The date in this field must be equal to or before {0}",
- /**
- * @cfg {String} invalidText
- * The error text to display when the date in the field is invalid (defaults to
- * '{value} is not a valid date - it must be in the format {format}').
- */
- invalidText : "{0} is not a valid date - it must be in the format {1}",
- /**
- * @cfg {String} triggerClass
- * An additional CSS class used to style the trigger button. The trigger will always get the
- * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
- * which displays a calendar icon).
- */
- triggerClass : 'x-form-date-trigger',
-
+});/**
+ * @class Roo.htmleditor.FilterWord
+ * try and clean up all the mess that Word generates.
+ *
+ * This is the 'nice version' - see 'Heavy' that white lists a very short list of elements, and multi-filters
+
+ * @constructor
+ * Run a new Span Filter
+ * @param {Object} config Configuration options
+ */
- /**
- * @cfg {Boolean} useIso
- * if enabled, then the date field will use a hidden field to store the
- * real value as iso formated date. default (true)
- */
- useIso : true,
- /**
- * @cfg {String/Object} autoCreate
- * A DomHelper element spec, or true for a default element spec (defaults to
- * {tag: "input", type: "text", size: "10", autocomplete: "off"})
- */
- // private
- defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
+Roo.htmleditor.FilterWord = function(cfg)
+{
+ // no need to apply config.
+ this.replaceDocBullets(cfg.node);
- // private
- hiddenField: false,
+ this.replaceAname(cfg.node);
+ // this is disabled as the removal is done by other filters;
+ // this.walk(cfg.node);
+ this.replaceImageTable(cfg.node);
- hideMonthPicker : false,
+}
+
+Roo.extend(Roo.htmleditor.FilterWord, Roo.htmleditor.Filter,
+{
+ tag: true,
+
- onRender : function(ct, position)
+ /**
+ * Clean up MS wordisms...
+ */
+ replaceTag : function(node)
{
- Roo.form.MonthField.superclass.onRender.call(this, ct, position);
- if (this.useIso) {
- this.el.dom.removeAttribute('name');
- this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
- 'before', true);
- this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
- // prevent input submission
- this.hiddenName = this.name;
- }
-
+
+ // no idea what this does - span with text, replaceds with just text.
+ if(
+ node.nodeName == 'SPAN' &&
+ !node.hasAttributes() &&
+ node.childNodes.length == 1 &&
+ node.firstChild.nodeName == "#text"
+ ) {
+ var textNode = node.firstChild;
+ node.removeChild(textNode);
+ if (node.getAttribute('lang') != 'zh-CN') { // do not space pad on chinese characters..
+ node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
+ }
+ node.parentNode.insertBefore(textNode, node);
+ if (node.getAttribute('lang') != 'zh-CN') { // do not space pad on chinese characters..
+ node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
+ }
- },
-
- // private
- validateValue : function(value)
- {
- value = this.formatDate(value);
- if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
- return false;
+ node.parentNode.removeChild(node);
+ return false; // dont do chidren - we have remove our node - so no need to do chdhilren?
}
- if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
- return true;
- }
- var svalue = value;
- value = this.parseDate(value);
- if(!value){
- this.markInvalid(String.format(this.invalidText, svalue, this.format));
- return false;
+
+
+
+ if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
+ node.parentNode.removeChild(node);
+ return false; // dont do chidlren
+ }
+ //Roo.log(node.tagName);
+ // remove - but keep children..
+ if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
+ //Roo.log('-- removed');
+ while (node.childNodes.length) {
+ var cn = node.childNodes[0];
+ node.removeChild(cn);
+ node.parentNode.insertBefore(cn, node);
+ // move node to parent - and clean it..
+ if (cn.nodeType == 1) {
+ this.replaceTag(cn);
+ }
+
+ }
+ node.parentNode.removeChild(node);
+ /// no need to iterate chidlren = it's got none..
+ //this.iterateChildren(node, this.cleanWord);
+ return false; // no need to iterate children.
}
- var time = value.getTime();
- if(this.minValue && time < this.minValue.getTime()){
- this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
- return false;
+ // clean styles
+ if (node.className.length) {
+
+ var cn = node.className.split(/\W+/);
+ var cna = [];
+ Roo.each(cn, function(cls) {
+ if (cls.match(/Mso[a-zA-Z]+/)) {
+ return;
+ }
+ cna.push(cls);
+ });
+ node.className = cna.length ? cna.join(' ') : '';
+ if (!cna.length) {
+ node.removeAttribute("class");
+ }
}
- if(this.maxValue && time > this.maxValue.getTime()){
- this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
- return false;
+
+ if (node.hasAttribute("lang")) {
+ node.removeAttribute("lang");
}
- /*if(this.disabledDays){
- var day = value.getDay();
- for(var i = 0; i < this.disabledDays.length; i++) {
- if(day === this.disabledDays[i]){
- this.markInvalid(this.disabledDaysText);
- return false;
- }
+
+ if (node.hasAttribute("style")) {
+
+ var styles = node.getAttribute("style").split(";");
+ var nstyle = [];
+ Roo.each(styles, function(s) {
+ if (!s.match(/:/)) {
+ return;
+ }
+ var kv = s.split(":");
+ if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
+ return;
+ }
+ // what ever is left... we allow.
+ nstyle.push(s);
+ });
+ node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
+ if (!nstyle.length) {
+ node.removeAttribute('style');
}
}
- */
- var fvalue = this.formatDate(value);
- /*if(this.ddMatch && this.ddMatch.test(fvalue)){
- this.markInvalid(String.format(this.disabledDatesText, fvalue));
- return false;
- }
- */
- return true;
+ return true; // do children
+
+
+
},
-
- // private
- // Provides logic to override the default TriggerField.validateBlur which just returns true
- validateBlur : function(){
- return !this.menu || !this.menu.isVisible();
+
+ styleToObject: function(node)
+ {
+ var styles = (node.getAttribute("style") || '').split(";");
+ var ret = {};
+ Roo.each(styles, function(s) {
+ if (!s.match(/:/)) {
+ return;
+ }
+ var kv = s.split(":");
+
+ // what ever is left... we allow.
+ ret[kv[0].trim()] = kv[1];
+ });
+ return ret;
},
-
- /**
- * Returns the current date value of the date field.
- * @return {Date} The date value
- */
- getValue : function(){
+
+
+ replaceAname : function (doc)
+ {
+ // replace all the a/name without..
+ var aa = Array.from(doc.getElementsByTagName('a'));
+ for (var i = 0; i < aa.length; i++) {
+ var a = aa[i];
+ if (a.hasAttribute("name")) {
+ a.removeAttribute("name");
+ }
+ if (a.hasAttribute("href")) {
+ continue;
+ }
+ // reparent children.
+ this.removeNodeKeepChildren(a);
+
+ }
- return this.hiddenField ?
- this.hiddenField.value :
- this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
},
- /**
- * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
- * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
- * (the default format used is "m/d/y").
- * <br />Usage:
- * <pre><code>
-//All of these calls set the same date value (May 4, 2006)
-
-//Pass a date object:
-var dt = new Date('5/4/06');
-monthField.setValue(dt);
-
-//Pass a date string (default format):
-monthField.setValue('5/4/06');
-
-//Pass a date string (custom format):
-monthField.format = 'Y-m-d';
-monthField.setValue('2006-5-4');
-</code></pre>
- * @param {String/Date} date The date or valid date string
- */
- setValue : function(date){
- Roo.log('month setValue' + date);
- // can only be first of month..
-
- var val = this.parseDate(date);
+
+
+ replaceDocBullets : function(doc)
+ {
+ // this is a bit odd - but it appears some indents use ql-indent-1
+ //Roo.log(doc.innerHTML);
- if (this.hiddenField) {
- this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
+ var listpara = Array.from(doc.getElementsByClassName('MsoListParagraphCxSpFirst'));
+ for( var i = 0; i < listpara.length; i ++) {
+ listpara[i].className = "MsoListParagraph";
}
- Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
- this.value = this.parseDate(date);
- },
-
- // private
- parseDate : function(value){
- if(!value || value instanceof Date){
- value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
- return value;
+
+ listpara = Array.from(doc.getElementsByClassName('MsoListParagraphCxSpMiddle'));
+ for( var i = 0; i < listpara.length; i ++) {
+ listpara[i].className = "MsoListParagraph";
}
- var v = Date.parseDate(value, this.format);
- if (!v && this.useIso) {
- v = Date.parseDate(value, 'Y-m-d');
+ listpara = Array.from(doc.getElementsByClassName('MsoListParagraphCxSpLast'));
+ for( var i = 0; i < listpara.length; i ++) {
+ listpara[i].className = "MsoListParagraph";
}
- if (v) {
- //
- v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
+ listpara = Array.from(doc.getElementsByClassName('ql-indent-1'));
+ for( var i = 0; i < listpara.length; i ++) {
+ listpara[i].className = "MsoListParagraph";
}
-
- if(!v && this.altFormats){
- if(!this.altFormatsArray){
- this.altFormatsArray = this.altFormats.split("|");
+ // this is a bit hacky - we had one word document where h2 had a miso-list attribute.
+ var htwo = Array.from(doc.getElementsByTagName('h2'));
+ for( var i = 0; i < htwo.length; i ++) {
+ if (htwo[i].hasAttribute('style') && htwo[i].getAttribute('style').match(/mso-list:/)) {
+ htwo[i].className = "MsoListParagraph";
}
- for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
- v = Date.parseDate(value, this.altFormatsArray[i]);
+ }
+ listpara = Array.from(doc.getElementsByClassName('MsoNormal'));
+ for( var i = 0; i < listpara.length; i ++) {
+ if (listpara[i].hasAttribute('style') && listpara[i].getAttribute('style').match(/mso-list:/)) {
+ listpara[i].className = "MsoListParagraph";
+ } else {
+ listpara[i].className = "MsoNormalx";
}
}
- return v;
- },
-
- // private
- formatDate : function(date, fmt){
- return (!date || !(date instanceof Date)) ?
- date : date.dateFormat(fmt || this.format);
- },
-
- // private
- menuListeners : {
- select: function(m, d){
- this.setValue(d);
- this.fireEvent('select', this, d);
- },
- show : function(){ // retain focus styling
- this.onFocus();
- },
- hide : function(){
- this.focus.defer(10, this);
- var ml = this.menuListeners;
- this.menu.un("select", ml.select, this);
- this.menu.un("show", ml.show, this);
- this.menu.un("hide", ml.hide, this);
+
+ listpara = doc.getElementsByClassName('MsoListParagraph');
+ // Roo.log(doc.innerHTML);
+
+
+
+ while(listpara.length) {
+
+ this.replaceDocBullet(listpara.item(0));
}
+
},
- // private
- // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
- onTriggerClick : function(){
- if(this.disabled){
- return;
- }
- if(this.menu == null){
- this.menu = new Roo.menu.DateMenu();
-
- }
-
- Roo.apply(this.menu.picker, {
+
+
+
+ replaceDocBullet : function(p)
+ {
+ // gather all the siblings.
+ var ns = p,
+ parent = p.parentNode,
+ doc = parent.ownerDocument,
+ items = [];
+
+ //Roo.log("Parsing: " + p.innerText) ;
+ var listtype = 'ul';
+ while (ns) {
+ if (ns.nodeType != 1) {
+ ns = ns.nextSibling;
+ continue;
+ }
+ if (!ns.className.match(/(MsoListParagraph|ql-indent-1)/i)) {
+ //Roo.log("Missing para r q1indent - got:" + ns.className);
+ break;
+ }
+ var spans = ns.getElementsByTagName('span');
+
+ if (ns.hasAttribute('style') && ns.getAttribute('style').match(/mso-list/)) {
+ items.push(ns);
+ ns = ns.nextSibling;
+ has_list = true;
+ if (!spans.length) {
+ continue;
+ }
+ var ff = '';
+ var se = spans[0];
+ for (var i = 0; i < spans.length;i++) {
+ se = spans[i];
+ if (se.hasAttribute('style') && se.hasAttribute('style') && se.style.fontFamily != '') {
+ ff = se.style.fontFamily;
+ break;
+ }
+ }
+
+
+ //Roo.log("got font family: " + ff);
+ if (typeof(ff) != 'undefined' && !ff.match(/(Symbol|Wingdings)/) && "·o".indexOf(se.innerText.trim()) < 0) {
+ listtype = 'ol';
+ }
+
+ continue;
+ }
+ //Roo.log("no mso-list?");
- showClear: this.allowBlank,
- minDate : this.minValue,
- maxDate : this.maxValue,
- disabledDatesRE : this.ddMatch,
- disabledDatesText : this.disabledDatesText,
+ var spans = ns.getElementsByTagName('span');
+ if (!spans.length) {
+ break;
+ }
+ var has_list = false;
+ for(var i = 0; i < spans.length; i++) {
+ if (spans[i].hasAttribute('style') && spans[i].getAttribute('style').match(/mso-list/)) {
+ has_list = true;
+ break;
+ }
+ }
+ if (!has_list) {
+ break;
+ }
+ items.push(ns);
+ ns = ns.nextSibling;
- format : this.useIso ? 'Y-m-d' : this.format,
- minText : String.format(this.minText, this.formatDate(this.minValue)),
- maxText : String.format(this.maxText, this.formatDate(this.maxValue))
- });
- this.menu.on(Roo.apply({}, this.menuListeners, {
- scope:this
- }));
-
+ }
+ if (!items.length) {
+ ns.className = "";
+ return;
+ }
- var m = this.menu;
- var p = m.picker;
+ var ul = parent.ownerDocument.createElement(listtype); // what about number lists...
+ parent.insertBefore(ul, p);
+ var lvl = 0;
+ var stack = [ ul ];
+ var last_li = false;
- // hide month picker get's called when we called by 'before hide';
+ var margin_to_depth = {};
+ max_margins = -1;
- var ignorehide = true;
- p.hideMonthPicker = function(disableAnim){
- if (ignorehide) {
+ items.forEach(function(n, ipos) {
+ //Roo.log("got innertHMLT=" + n.innerHTML);
+
+ var spans = n.getElementsByTagName('span');
+ if (!spans.length) {
+ //Roo.log("No spans found");
+
+ parent.removeChild(n);
+
+
+ return; // skip it...
+ }
+
+
+ var num = 1;
+ var style = {};
+ for(var i = 0; i < spans.length; i++) {
+
+ style = this.styleToObject(spans[i]);
+ if (typeof(style['mso-list']) == 'undefined') {
+ continue;
+ }
+ if (listtype == 'ol') {
+ num = spans[i].innerText.replace(/[^0-9]+]/g,'') * 1;
+ }
+ spans[i].parentNode.removeChild(spans[i]); // remove the fake bullet.
+ break;
+ }
+ //Roo.log("NOW GOT innertHMLT=" + n.innerHTML);
+ style = this.styleToObject(n); // mo-list is from the parent node.
+ if (typeof(style['mso-list']) == 'undefined') {
+ //Roo.log("parent is missing level");
+
+ parent.removeChild(n);
+
return;
}
- if(this.monthPicker){
- Roo.log("hideMonthPicker called");
- if(disableAnim === true){
- this.monthPicker.hide();
- }else{
- this.monthPicker.slideOut('t', {duration:.2});
- p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
- p.fireEvent("select", this, this.value);
- m.hide();
+
+ var margin = style['margin-left'];
+ if (typeof(margin_to_depth[margin]) == 'undefined') {
+ max_margins++;
+ margin_to_depth[margin] = max_margins;
+ }
+ nlvl = margin_to_depth[margin] ;
+
+ if (nlvl > lvl) {
+ //new indent
+ var nul = doc.createElement(listtype); // what about number lists...
+ if (!last_li) {
+ last_li = doc.createElement('li');
+ stack[lvl].appendChild(last_li);
}
+ last_li.appendChild(nul);
+ stack[nlvl] = nul;
+
}
- }
-
- Roo.log('picker set value');
- Roo.log(this.getValue());
- p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
- m.show(this.el, 'tl-bl?');
- ignorehide = false;
- // this will trigger hideMonthPicker..
-
-
- // hidden the day picker
- Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
+ lvl = nlvl;
+
+ // not starting at 1..
+ if (!stack[nlvl].hasAttribute("start") && listtype == "ol") {
+ stack[nlvl].setAttribute("start", num);
+ }
+
+ var nli = stack[nlvl].appendChild(doc.createElement('li'));
+ last_li = nli;
+ nli.innerHTML = n.innerHTML;
+ //Roo.log("innerHTML = " + n.innerHTML);
+ parent.removeChild(n);
+
+
+
+
+ },this);
-
- p.showMonthPicker.defer(100, p);
+ },
+ replaceImageTable : function(doc)
+ {
+ /*
+ <table cellpadding=0 cellspacing=0 align=left>
+ <tr>
+ <td width=423 height=0></td>
+ </tr>
+ <tr>
+ <td></td>
+ <td><img width=601 height=401
+ src="file:///C:/Users/Alan/AppData/Local/Temp/msohtmlclip1/01/clip_image002.jpg"
+ v:shapes="Picture_x0020_2"></td>
+ </tr>
+ </table>
+ */
+ var imgs = Array.from(doc.getElementsByTagName('img'));
+ Roo.each(imgs, function(img) {
+ var td = img.parentNode;
+ if (td.nodeName != 'TD') {
+ return;
+ }
+ var tr = td.parentNode;
+ if (tr.nodeName != 'TR') {
+ return;
+ }
+ var tbody = tr.parentNode;
+ if (tbody.nodeName != 'TBODY') {
+ return;
+ }
+ var table = tbody.parentNode;
+ if (table.nodeName != 'TABLE') {
+ return;
+ }
+ // first row..
+
+ if (table.getElementsByTagName('tr').length != 2) {
+ return;
+ }
+ if (table.getElementsByTagName('td').length != 3) {
+ return;
+ }
+ if (table.innerText.trim() != '') {
+ return;
+ }
+ var p = table.parentNode;
+ img.parentNode.removeChild(img);
+ p.insertBefore(img, table);
+ p.removeChild(table);
+
+
+
+ });
-
- },
-
- beforeBlur : function(){
- var v = this.parseDate(this.getRawValue());
- if(v){
- this.setValue(v);
- }
+
}
-
- /** @cfg {Boolean} grow @hide */
- /** @cfg {Number} growMin @hide */
- /** @cfg {Number} growMax @hide */
- /**
- * @hide
- * @method autoSize
- */
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-
+
+});
/**
- * @class Roo.form.ComboBox
- * @extends Roo.form.TriggerField
- * A combobox control with support for autocomplete, remote-loading, paging and many other features.
+ * @class Roo.htmleditor.FilterStyleToTag
+ * part of the word stuff... - certain 'styles' should be converted to tags.
+ * eg.
+ * font-weight: bold -> bold
+ * ?? super / subscrit etc..
+ *
* @constructor
- * Create a new ComboBox.
- * @param {Object} config Configuration options
+* Run a new style to tag filter.
+* @param {Object} config Configuration options
*/
-Roo.form.ComboBox = function(config){
- Roo.form.ComboBox.superclass.constructor.call(this, config);
- this.addEvents({
- /**
- * @event expand
- * Fires when the dropdown list is expanded
- * @param {Roo.form.ComboBox} combo This combo box
- */
- 'expand' : true,
- /**
- * @event collapse
- * Fires when the dropdown list is collapsed
- * @param {Roo.form.ComboBox} combo This combo box
- */
- 'collapse' : true,
- /**
- * @event beforeselect
- * Fires before a list item is selected. Return false to cancel the selection.
- * @param {Roo.form.ComboBox} combo This combo box
- * @param {Roo.data.Record} record The data record returned from the underlying store
- * @param {Number} index The index of the selected item in the dropdown list
- */
- 'beforeselect' : true,
- /**
- * @event select
- * Fires when a list item is selected
- * @param {Roo.form.ComboBox} combo This combo box
- * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
- * @param {Number} index The index of the selected item in the dropdown list
- */
- 'select' : true,
- /**
- * @event beforequery
- * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
- * The event object passed has these properties:
- * @param {Roo.form.ComboBox} combo This combo box
- * @param {String} query The query
- * @param {Boolean} forceAll true to force "all" query
- * @param {Boolean} cancel true to cancel the query
- * @param {Object} e The query event object
- */
- 'beforequery': true,
- /**
- * @event add
- * Fires when the 'add' icon is pressed (add a listener to enable add button)
- * @param {Roo.form.ComboBox} combo This combo box
- */
- 'add' : true,
- /**
- * @event edit
- * Fires when the 'edit' icon is pressed (add a listener to enable add button)
- * @param {Roo.form.ComboBox} combo This combo box
- * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
- */
- 'edit' : true
+Roo.htmleditor.FilterStyleToTag = function(cfg)
+{
+
+ this.tags = {
+ B : [ 'fontWeight' , 'bold'],
+ I : [ 'fontStyle' , 'italic'],
+ //pre : [ 'font-style' , 'italic'],
+ // h1.. h6 ?? font-size?
+ SUP : [ 'verticalAlign' , 'super' ],
+ SUB : [ 'verticalAlign' , 'sub' ]
- });
- if(this.transform){
- this.allowDomMove = false;
- var s = Roo.getDom(this.transform);
- if(!this.hiddenName){
- this.hiddenName = s.name;
- }
- if(!this.store){
- this.mode = 'local';
- var d = [], opts = s.options;
- for(var i = 0, len = opts.length;i < len; i++){
- var o = opts[i];
- var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
- if(o.selected) {
- this.value = value;
- }
- d.push([value, o.text]);
- }
- this.store = new Roo.data.SimpleStore({
- 'id': 0,
- fields: ['value', 'text'],
- data : d
- });
- this.valueField = 'value';
- this.displayField = 'text';
- }
- s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
- if(!this.lazyRender){
- this.target = true;
- this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
- s.parentNode.removeChild(s); // remove it
- this.render(this.el.parentNode);
- }else{
- s.parentNode.removeChild(s); // remove it
- }
-
- }
- if (this.store) {
- this.store = Roo.factory(this.store, Roo.data);
- }
+ };
- this.selectedIndex = -1;
- if(this.mode == 'local'){
- if(config.queryDelay === undefined){
- this.queryDelay = 10;
- }
- if(config.minChars === undefined){
- this.minChars = 0;
- }
- }
-};
-
-Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
- /**
- * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
- */
- /**
- * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
- * rendering into an Roo.Editor, defaults to false)
- */
- /**
- * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
- * {tag: "input", type: "text", size: "24", autocomplete: "off"})
- */
- /**
- * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
- */
- /**
- * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
- * the dropdown list (defaults to undefined, with no header element)
- */
-
- /**
- * @cfg {String/Roo.Template} tpl The template to use to render the output
- */
+ Roo.apply(this, cfg);
- // private
- defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
- /**
- * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
- */
- listWidth: undefined,
- /**
- * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
- * mode = 'remote' or 'text' if mode = 'local')
- */
- displayField: undefined,
- /**
- * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
- * mode = 'remote' or 'value' if mode = 'local').
- * Note: use of a valueField requires the user make a selection
- * in order for a value to be mapped.
- */
- valueField: undefined,
+ this.walk(cfg.node);
- /**
- * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
- * field's data value (defaults to the underlying DOM element's name)
- */
- hiddenName: undefined,
- /**
- * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
- */
- listClass: '',
- /**
- * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
- */
- selectedClass: 'x-combo-selected',
- /**
- * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
- * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
- * which displays a downward arrow icon).
- */
- triggerClass : 'x-form-arrow-trigger',
- /**
- * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
- */
- shadow:'sides',
- /**
- * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
- * anchor positions (defaults to 'tl-bl')
- */
- listAlign: 'tl-bl?',
- /**
- * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
- */
- maxHeight: 300,
- /**
- * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
- * query specified by the allQuery config option (defaults to 'query')
- */
- triggerAction: 'query',
- /**
- * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
- * (defaults to 4, does not apply if editable = false)
- */
- minChars : 4,
- /**
- * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
- * delay (typeAheadDelay) if it matches a known value (defaults to false)
- */
- typeAhead: false,
- /**
- * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
- * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
- */
- queryDelay: 500,
- /**
- * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
- * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
- */
- pageSize: 0,
- /**
- * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
- * when editable = true (defaults to false)
- */
- selectOnFocus:false,
- /**
- * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
- */
- queryParam: 'query',
- /**
- * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
- * when mode = 'remote' (defaults to 'Loading...')
- */
- loadingText: 'Loading...',
- /**
- * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
- */
- resizable: false,
- /**
- * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
- */
- handleHeight : 8,
- /**
- * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
- * traditional select (defaults to true)
- */
- editable: true,
- /**
- * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
- */
- allQuery: '',
- /**
- * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
- */
- mode: 'remote',
- /**
- * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
- * listWidth has a higher value)
- */
- minListWidth : 70,
- /**
- * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
- * allow the user to set arbitrary text into the field (defaults to false)
- */
- forceSelection:false,
- /**
- * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
- * if typeAhead = true (defaults to 250)
- */
- typeAheadDelay : 250,
- /**
- * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
- * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
- */
- valueNotFoundText : undefined,
- /**
- * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
- */
- blockFocus : false,
- /**
- * @cfg {Boolean} disableClear Disable showing of clear button.
- */
- disableClear : false,
- /**
- * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
- */
- alwaysQuery : false,
- //private
- addicon : false,
- editicon: false,
+}
+
+
+Roo.extend(Roo.htmleditor.FilterStyleToTag, Roo.htmleditor.Filter,
+{
+ tag: true, // all tags
- // element that contains real text value.. (when hidden is used..)
-
- // private
- onRender : function(ct, position)
+ tags : false,
+
+
+ replaceTag : function(node)
{
- Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
- if(this.hiddenName){
- this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
- 'before', true);
- this.hiddenField.value =
- this.hiddenValue !== undefined ? this.hiddenValue :
- this.value !== undefined ? this.value : '';
-
- // prevent input submission
- this.el.dom.removeAttribute('name');
-
-
+
+ if (node.getAttribute("style") === null) {
+ return true;
}
-
- if(Roo.isGecko){
- this.el.dom.setAttribute('autocomplete', 'off');
+ var inject = [];
+ for (var k in this.tags) {
+ if (node.style[this.tags[k][0]] == this.tags[k][1]) {
+ inject.push(k);
+ node.style.removeProperty(this.tags[k][0]);
+ }
}
-
- var cls = 'x-combo-list';
-
- this.list = new Roo.Layer({
- shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
+ if (!inject.length) {
+ return true;
+ }
+ var cn = Array.from(node.childNodes);
+ var nn = node;
+ Roo.each(inject, function(t) {
+ var nc = node.ownerDocument.createElement(t);
+ nn.appendChild(nc);
+ nn = nc;
});
-
- var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
- this.list.setWidth(lw);
- this.list.swallowEvent('mousewheel');
- this.assetHeight = 0;
-
- if(this.title){
- this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
- this.assetHeight += this.header.getHeight();
+ for(var i = 0;i < cn.length;cn++) {
+ node.removeChild(cn[i]);
+ nn.appendChild(cn[i]);
}
+ return true /// iterate thru
+ }
+
+})/**
+ * @class Roo.htmleditor.FilterLongBr
+ * BR/BR/BR - keep a maximum of 2...
+ * @constructor
+ * Run a new Long BR Filter
+ * @param {Object} config Configuration options
+ */
- this.innerList = this.list.createChild({cls:cls+'-inner'});
- this.innerList.on('mouseover', this.onViewOver, this);
- this.innerList.on('mousemove', this.onViewMove, this);
- this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
-
- if(this.allowBlank && !this.pageSize && !this.disableClear){
- this.footer = this.list.createChild({cls:cls+'-ft'});
- this.pageTb = new Roo.Toolbar(this.footer);
-
- }
- if(this.pageSize){
- this.footer = this.list.createChild({cls:cls+'-ft'});
- this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
- {pageSize: this.pageSize});
-
- }
-
- if (this.pageTb && this.allowBlank && !this.disableClear) {
- var _this = this;
- this.pageTb.add(new Roo.Toolbar.Fill(), {
- cls: 'x-btn-icon x-btn-clear',
- text: ' ',
- handler: function()
- {
- _this.collapse();
- _this.clearValue();
- _this.onSelect(false, -1);
- }
- });
+Roo.htmleditor.FilterLongBr = function(cfg)
+{
+ // no need to apply config.
+ this.searchTag(cfg.node);
+}
+
+Roo.extend(Roo.htmleditor.FilterLongBr, Roo.htmleditor.Filter,
+{
+
+
+ tag : 'BR',
+
+
+ replaceTag : function(node)
+ {
+
+ var ps = node.nextSibling;
+ while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
+ ps = ps.nextSibling;
}
- if (this.footer) {
- this.assetHeight += this.footer.getHeight();
+
+ if (!ps && [ 'TD', 'TH', 'LI', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(node.parentNode.tagName) > -1) {
+ node.parentNode.removeChild(node); // remove last BR inside one fo these tags
+ return false;
}
-
- if(!this.tpl){
- this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
+ if (!ps || ps.nodeType != 1) {
+ return false;
}
-
- this.view = new Roo.View(this.innerList, this.tpl, {
- singleSelect:true,
- store: this.store,
- selectedClass: this.selectedClass
- });
-
- this.view.on('click', this.onViewClick, this);
-
- this.store.on('beforeload', this.onBeforeLoad, this);
- this.store.on('load', this.onLoad, this);
- this.store.on('loadexception', this.onLoadException, this);
-
- if(this.resizable){
- this.resizer = new Roo.Resizable(this.list, {
- pinned:true, handles:'se'
- });
- this.resizer.on('resize', function(r, w, h){
- this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
- this.listWidth = w;
- this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
- this.restrictHeight();
- }, this);
- this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
+
+ if (!ps || ps.tagName != 'BR') {
+
+ return false;
}
- if(!this.editable){
- this.editable = true;
- this.setEditable(false);
- }
- if (typeof(this.events.add.listeners) != 'undefined') {
-
- this.addicon = this.wrap.createChild(
- {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });
-
- this.addicon.on('click', function(e) {
- this.fireEvent('add', this);
- }, this);
+
+ if (!node.previousSibling) {
+ return false;
}
- if (typeof(this.events.edit.listeners) != 'undefined') {
-
- this.editicon = this.wrap.createChild(
- {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });
- if (this.addicon) {
- this.editicon.setStyle('margin-left', '40px');
- }
- this.editicon.on('click', function(e) {
-
- // we fire even if inothing is selected..
- this.fireEvent('edit', this, this.lastData );
-
- }, this);
+ var ps = node.previousSibling;
+
+ while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
+ ps = ps.previousSibling;
+ }
+ if (!ps || ps.nodeType != 1) {
+ return false;
+ }
+ // if header or BR before.. then it's a candidate for removal.. - as we only want '2' of these..
+ if (!ps || [ 'BR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(ps.tagName) < 0) {
+ return false;
+ }
+
+ node.parentNode.removeChild(node); // remove me...
+
+ return false; // no need to do children
+
+ }
+
+});
+
+/**
+ * @class Roo.htmleditor.FilterBlock
+ * removes id / data-block and contenteditable that are associated with blocks
+ * usage should be done on a cloned copy of the dom
+ * @constructor
+* Run a new Attribute Filter { node : xxxx }}
+* @param {Object} config Configuration options
+ */
+Roo.htmleditor.FilterBlock = function(cfg)
+{
+ Roo.apply(this, cfg);
+ var qa = cfg.node.querySelectorAll;
+ this.removeAttributes('data-block');
+ this.removeAttributes('contenteditable');
+ this.removeAttributes('id');
+
+}
+
+Roo.apply(Roo.htmleditor.FilterBlock.prototype,
+{
+ node: true, // all tags
+
+
+ removeAttributes : function(attr)
+ {
+ var ar = this.node.querySelectorAll('*[' + attr + ']');
+ for (var i =0;i<ar.length;i++) {
+ ar[i].removeAttribute(attr);
}
+ }
- },
+
+});
+/***
+ * This is based loosely on tinymce
+ * @class Roo.htmleditor.TidySerializer
+ * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
+ * @constructor
+ * @method Serializer
+ * @param {Object} settings Name/value settings object.
+ */
- // private
- initEvents : function(){
- Roo.form.ComboBox.superclass.initEvents.call(this);
- this.keyNav = new Roo.KeyNav(this.el, {
- "up" : function(e){
- this.inKeyMode = true;
- this.selectPrev();
- },
+Roo.htmleditor.TidySerializer = function(settings)
+{
+ Roo.apply(this, settings);
+
+ this.writer = new Roo.htmleditor.TidyWriter(settings);
+
+
- "down" : function(e){
- if(!this.isExpanded()){
- this.onTriggerClick();
- }else{
- this.inKeyMode = true;
- this.selectNext();
- }
+};
+Roo.htmleditor.TidySerializer.prototype = {
+
+ /**
+ * @param {boolean} inner do the inner of the node.
+ */
+ inner : false,
+
+ writer : false,
+
+ /**
+ * Serializes the specified node into a string.
+ *
+ * @example
+ * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('<p>text</p>'));
+ * @method serialize
+ * @param {DomElement} node Node instance to serialize.
+ * @return {String} String with HTML based on DOM tree.
+ */
+ serialize : function(node) {
+
+ // = settings.validate;
+ var writer = this.writer;
+ var self = this;
+ this.handlers = {
+ // #text
+ 3: function(node) {
+
+ writer.text(node.nodeValue, node);
},
-
- "enter" : function(e){
- this.onViewClick();
- //return true;
+ // #comment
+ 8: function(node) {
+ writer.comment(node.nodeValue);
},
-
- "esc" : function(e){
- this.collapse();
+ // Processing instruction
+ 7: function(node) {
+ writer.pi(node.name, node.nodeValue);
},
-
- "tab" : function(e){
- this.onViewClick(false);
- this.fireEvent("specialkey", this, e);
- return true;
+ // Doctype
+ 10: function(node) {
+ writer.doctype(node.nodeValue);
},
-
- scope : this,
-
- doRelay : function(foo, bar, hname){
- if(hname == 'down' || this.scope.isExpanded()){
- return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
- }
- return true;
+ // CDATA
+ 4: function(node) {
+ writer.cdata(node.nodeValue);
},
-
- forceKeyDown: true
- });
- this.queryDelay = Math.max(this.queryDelay || 10,
- this.mode == 'local' ? 10 : 250);
- this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
- if(this.typeAhead){
- this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
- }
- if(this.editable !== false){
- this.el.on("keyup", this.onKeyUp, this);
- }
- if(this.forceSelection){
- this.on('blur', this.doForce, this);
- }
+ // Document fragment
+ 11: function(node) {
+ node = node.firstChild;
+ if (!node) {
+ return;
+ }
+ while(node) {
+ self.walk(node);
+ node = node.nextSibling
+ }
+ }
+ };
+ writer.reset();
+ 1 != node.nodeType || this.inner ? this.handlers[11](node) : this.walk(node);
+ return writer.getContent();
},
- onDestroy : function(){
- if(this.view){
- this.view.setStore(null);
- this.view.el.removeAllListeners();
- this.view.el.remove();
- this.view.purgeListeners();
+ walk: function(node)
+ {
+ var attrName, attrValue, sortedAttrs, i, l, elementRule,
+ handler = this.handlers[node.nodeType];
+
+ if (handler) {
+ handler(node);
+ return;
}
- if(this.list){
- this.list.destroy();
+
+ var name = node.nodeName;
+ var isEmpty = node.childNodes.length < 1;
+
+ var writer = this.writer;
+ var attrs = node.attributes;
+ // Sort attributes
+
+ writer.start(node.nodeName, attrs, isEmpty, node);
+ if (isEmpty) {
+ return;
}
- if(this.store){
- this.store.un('beforeload', this.onBeforeLoad, this);
- this.store.un('load', this.onLoad, this);
- this.store.un('loadexception', this.onLoadException, this);
+ node = node.firstChild;
+ if (!node) {
+ writer.end(name);
+ return;
}
- Roo.form.ComboBox.superclass.onDestroy.call(this);
- },
-
- // private
- fireKey : function(e){
- if(e.isNavKeyPress() && !this.list.isVisible()){
- this.fireEvent("specialkey", this, e);
+ while (node) {
+ this.walk(node);
+ node = node.nextSibling;
}
- },
+ writer.end(name);
+
+
+ }
+ // Serialize element and treat all non elements as fragments
+
+};
- // private
- onResize: function(w, h){
- Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
+/***
+ * This is based loosely on tinymce
+ * @class Roo.htmleditor.TidyWriter
+ * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
+ *
+ * Known issues?
+ * - not tested much with 'PRE' formated elements.
+ *
+ *
+ *
+ */
+
+Roo.htmleditor.TidyWriter = function(settings)
+{
+
+ // indent, indentBefore, indentAfter, encode, htmlOutput, html = [];
+ Roo.apply(this, settings);
+ this.html = [];
+ this.state = [];
+
+ this.encode = Roo.htmleditor.TidyEntities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
+
+}
+Roo.htmleditor.TidyWriter.prototype = {
+
+
+ state : false,
+
+ indent : ' ',
+
+ // part of state...
+ indentstr : '',
+ in_pre: false,
+ in_inline : false,
+ last_inline : false,
+ encode : false,
+
+
+ /**
+ * Writes the a start element such as <p id="a">.
+ *
+ * @method start
+ * @param {String} name Name of the element.
+ * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
+ * @param {Boolean} empty Optional empty state if the tag should end like <br />.
+ */
+ start: function(name, attrs, empty, node)
+ {
+ var i, l, attr, value;
- if(typeof w != 'number'){
- // we do not handle it!?!?
- return;
- }
- var tw = this.trigger.getWidth();
- tw += this.addicon ? this.addicon.getWidth() : 0;
- tw += this.editicon ? this.editicon.getWidth() : 0;
- var x = w - tw;
- this.el.setWidth( this.adjustWidth('input', x));
-
- this.trigger.setStyle('left', x+'px');
+ // there are some situations where adding line break && indentation will not work. will not work.
+ // <span / b / i ... formating?
- if(this.list && this.listWidth === undefined){
- var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
- this.list.setWidth(lw);
- this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
- }
+ var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
+ var in_pre = this.in_pre || Roo.htmleditor.TidyWriter.whitespace_elements.indexOf(name) > -1;
-
+ var is_short = empty ? Roo.htmleditor.TidyWriter.shortend_elements.indexOf(name) > -1 : false;
- },
-
- /**
- * Allow or prevent the user from directly editing the field text. If false is passed,
- * the user will only be able to select from the items defined in the dropdown list. This method
- * is the runtime equivalent of setting the 'editable' config option at config time.
- * @param {Boolean} value True to allow the user to directly edit the field text
- */
- setEditable : function(value){
- if(value == this.editable){
- return;
- }
- this.editable = value;
- if(!value){
- this.el.dom.setAttribute('readOnly', true);
- this.el.on('mousedown', this.onTriggerClick, this);
- this.el.addClass('x-combo-noedit');
- }else{
- this.el.dom.setAttribute('readOnly', false);
- this.el.un('mousedown', this.onTriggerClick, this);
- this.el.removeClass('x-combo-noedit');
+ var add_lb = name == 'BR' ? false : in_inline;
+
+ if (!add_lb && !this.in_pre && this.lastElementEndsWS()) {
+ i_inline = false;
}
- },
- // private
- onBeforeLoad : function(){
- if(!this.hasFocus){
- return;
+ var indentstr = this.indentstr;
+
+ // e_inline = elements that can be inline, but still allow \n before and after?
+ // only 'BR' ??? any others?
+
+ // ADD LINE BEFORE tage
+ if (!this.in_pre) {
+ if (in_inline) {
+ //code
+ if (name == 'BR') {
+ this.addLine();
+ } else if (this.lastElementEndsWS()) {
+ this.addLine();
+ } else{
+ // otherwise - no new line. (and dont indent.)
+ indentstr = '';
+ }
+
+ } else {
+ this.addLine();
+ }
+ } else {
+ indentstr = '';
}
- this.innerList.update(this.loadingText ?
- '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
- this.restrictHeight();
- this.selectedIndex = -1;
- },
-
- // private
- onLoad : function(){
- if(!this.hasFocus){
+
+ this.html.push(indentstr + '<', name.toLowerCase());
+
+ if (attrs) {
+ for (i = 0, l = attrs.length; i < l; i++) {
+ attr = attrs[i];
+ this.html.push(' ', attr.name, '="', this.encode(attr.value, true), '"');
+ }
+ }
+
+ if (empty) {
+ if (is_short) {
+ this.html[this.html.length] = '/>';
+ } else {
+ this.html[this.html.length] = '></' + name.toLowerCase() + '>';
+ }
+ var e_inline = name == 'BR' ? false : this.in_inline;
+
+ if (!e_inline && !this.in_pre) {
+ this.addLine();
+ }
return;
+
}
- if(this.store.getCount() > 0){
- this.expand();
- this.restrictHeight();
- if(this.lastQuery == this.allQuery){
- if(this.editable){
- this.el.dom.select();
- }
- if(!this.selectByValue(this.value, true)){
- this.select(0, true);
- }
- }else{
- this.selectNext();
- if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
- this.taTask.delay(this.typeAheadDelay);
+ // not empty..
+ this.html[this.html.length] = '>';
+
+ // there is a special situation, where we need to turn on in_inline - if any of the imediate chidlren are one of these.
+ /*
+ if (!in_inline && !in_pre) {
+ var cn = node.firstChild;
+ while(cn) {
+ if (Roo.htmleditor.TidyWriter.inline_elements.indexOf(cn.nodeName) > -1) {
+ in_inline = true
+ break;
}
+ cn = cn.nextSibling;
}
- }else{
- this.onEmptyResults();
- }
- //this.el.focus();
- },
- // private
- onLoadException : function()
- {
- this.collapse();
- Roo.log(this.store.reader.jsonData);
- if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
- Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
+
}
+ */
- },
- // private
- onTypeAhead : function(){
- if(this.store.getCount() > 0){
- var r = this.store.getAt(0);
- var newValue = r.data[this.displayField];
- var len = newValue.length;
- var selStart = this.getRawValue().length;
- if(selStart != len){
- this.setRawValue(newValue);
- this.selectText(selStart, newValue.length);
- }
+ this.pushState({
+ indentstr : in_pre ? '' : (this.indentstr + this.indent),
+ in_pre : in_pre,
+ in_inline : in_inline
+ });
+ // add a line after if we are not in a
+
+ if (!in_inline && !in_pre) {
+ this.addLine();
}
+
+
+
+
},
-
- // private
- onSelect : function(record, index){
- if(this.fireEvent('beforeselect', this, record, index) !== false){
- this.setFromData(index > -1 ? record.data : false);
- this.collapse();
- this.fireEvent('select', this, record, index);
+
+ lastElementEndsWS : function()
+ {
+ var value = this.html.length > 0 ? this.html[this.html.length-1] : false;
+ if (value === false) {
+ return true;
}
+ return value.match(/\s+$/);
+
},
-
+
/**
- * Returns the currently selected field value or empty string if no value is set.
- * @return {String} value The selected value
+ * Writes the a end element such as </p>.
+ *
+ * @method end
+ * @param {String} name Name of the element.
*/
- getValue : function(){
- if(this.valueField){
- return typeof this.value != 'undefined' ? this.value : '';
+ end: function(name) {
+ var value;
+ this.popState();
+ var indentstr = '';
+ var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
+
+ if (!this.in_pre && !in_inline) {
+ this.addLine();
+ indentstr = this.indentstr;
}
- return Roo.form.ComboBox.superclass.getValue.call(this);
+ this.html.push(indentstr + '</', name.toLowerCase(), '>');
+ this.last_inline = in_inline;
+
+ // pop the indent state..
},
-
/**
- * Clears any text/value currently set in the field
+ * Writes a text node.
+ *
+ * In pre - we should not mess with the contents.
+ *
+ *
+ * @method text
+ * @param {String} text String to write out.
+ * @param {Boolean} raw Optional raw state if true the contents wont get encoded.
*/
- clearValue : function(){
- if(this.hiddenField){
- this.hiddenField.value = '';
+ text: function(in_text, node)
+ {
+ // if not in whitespace critical
+ if (in_text.length < 1) {
+ return;
}
- this.value = '';
- this.setRawValue('');
- this.lastSelectionText = '';
+ var text = new XMLSerializer().serializeToString(document.createTextNode(in_text)); // escape it properly?
- },
-
- /**
- * Sets the specified value into the field. If the value finds a match, the corresponding record text
- * will be displayed in the field. If the value does not match the data value of an existing item,
- * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
- * Otherwise the field will be blank (although the value will still be set).
- * @param {String} value The value to match
- */
- setValue : function(v){
- var text = v;
- if(this.valueField){
- var r = this.findRecord(this.valueField, v);
- if(r){
- text = r.data[this.displayField];
- }else if(this.valueNotFoundText !== undefined){
- text = this.valueNotFoundText;
- }
+ if (this.in_pre) {
+ this.html[this.html.length] = text;
+ return;
}
- this.lastSelectionText = text;
- if(this.hiddenField){
- this.hiddenField.value = v;
+
+ if (this.in_inline) {
+ text = text.replace(/\s+/g,' '); // all white space inc line breaks to a slingle' '
+ if (text != ' ') {
+ text = text.replace(/\s+/,' '); // all white space to single white space
+
+
+ // if next tag is '<BR>', then we can trim right..
+ if (node.nextSibling &&
+ node.nextSibling.nodeType == 1 &&
+ node.nextSibling.nodeName == 'BR' )
+ {
+ text = text.replace(/\s+$/g,'');
+ }
+ // if previous tag was a BR, we can also trim..
+ if (node.previousSibling &&
+ node.previousSibling.nodeType == 1 &&
+ node.previousSibling.nodeName == 'BR' )
+ {
+ text = this.indentstr + text.replace(/^\s+/g,'');
+ }
+ if (text.match(/\n/)) {
+ text = text.replace(
+ /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
+ );
+ // remoeve the last whitespace / line break.
+ text = text.replace(/\n\s+$/,'');
+ }
+ // repace long lines
+
+ }
+
+ this.html[this.html.length] = text;
+ return;
}
- Roo.form.ComboBox.superclass.setValue.call(this, text);
- this.value = v;
- },
- /**
- * @property {Object} the last set data for the element
- */
-
- lastData : false,
- /**
- * Sets the value of the field based on a object which is related to the record format for the store.
- * @param {Object} value the value to set as. or false on reset?
- */
- setFromData : function(o){
- var dv = ''; // display value
- var vv = ''; // value value..
- this.lastData = o;
- if (this.displayField) {
- dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
+ // see if previous element was a inline element.
+ var indentstr = this.indentstr;
+
+ text = text.replace(/\s+/g," "); // all whitespace into single white space.
+
+ // should trim left?
+ if (node.previousSibling &&
+ node.previousSibling.nodeType == 1 &&
+ Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.previousSibling.nodeName) > -1)
+ {
+ indentstr = '';
+
} else {
- // this is an error condition!!!
- Roo.log('no displayField value set for '+ (this.name ? this.name : this.id));
+ this.addLine();
+ text = text.replace(/^\s+/,''); // trim left
+
+ }
+ // should trim right?
+ if (node.nextSibling &&
+ node.nextSibling.nodeType == 1 &&
+ Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.nextSibling.nodeName) > -1)
+ {
+ // noop
+
+ } else {
+ text = text.replace(/\s+$/,''); // trim right
}
+
+
- if(this.valueField){
- vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
+
+
+ if (text.length < 1) {
+ return;
}
- if(this.hiddenField){
- this.hiddenField.value = vv;
-
- this.lastSelectionText = dv;
- Roo.form.ComboBox.superclass.setValue.call(this, dv);
- this.value = vv;
+ if (!text.match(/\n/)) {
+ this.html.push(indentstr + text);
return;
}
- // no hidden field.. - we store the value in 'value', but still display
- // display field!!!!
- this.lastSelectionText = dv;
- Roo.form.ComboBox.superclass.setValue.call(this, dv);
- this.value = vv;
+
+ text = this.indentstr + text.replace(
+ /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
+ );
+ // remoeve the last whitespace / line break.
+ text = text.replace(/\s+$/,'');
+
+ this.html.push(text);
+
+ // split and indent..
},
- // private
- reset : function(){
- // overridden so that last data is reset..
- this.setValue(this.resetValue);
- this.originalValue = this.getValue();
- this.clearInvalid();
- this.lastData = false;
- if (this.view) {
- this.view.clearSelections();
- }
+ /**
+ * Writes a cdata node such as <![CDATA[data]]>.
+ *
+ * @method cdata
+ * @param {String} text String to write out inside the cdata.
+ */
+ cdata: function(text) {
+ this.html.push('<![CDATA[', text, ']]>');
},
- // private
- findRecord : function(prop, value){
- var record;
- if(this.store.getCount() > 0){
- this.store.each(function(r){
- if(r.data[prop] == value){
- record = r;
- return false;
- }
- return true;
- });
- }
- return record;
+ /**
+ * Writes a comment node such as <!-- Comment -->.
+ *
+ * @method cdata
+ * @param {String} text String to write out inside the comment.
+ */
+ comment: function(text) {
+ this.html.push('<!--', text, '-->');
+ },
+ /**
+ * Writes a PI node such as <?xml attr="value" ?>.
+ *
+ * @method pi
+ * @param {String} name Name of the pi.
+ * @param {String} text String to write out inside the pi.
+ */
+ pi: function(name, text) {
+ text ? this.html.push('<?', name, ' ', this.encode(text), '?>') : this.html.push('<?', name, '?>');
+ this.indent != '' && this.html.push('\n');
},
-
- getName: function()
- {
- // returns hidden if it's set..
- if (!this.rendered) {return ''};
- return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
-
+ /**
+ * Writes a doctype node such as <!DOCTYPE data>.
+ *
+ * @method doctype
+ * @param {String} text String to write out inside the doctype.
+ */
+ doctype: function(text) {
+ this.html.push('<!DOCTYPE', text, '>', this.indent != '' ? '\n' : '');
},
- // private
- onViewMove : function(e, t){
- this.inKeyMode = false;
+ /**
+ * Resets the internal buffer if one wants to reuse the writer.
+ *
+ * @method reset
+ */
+ reset: function() {
+ this.html.length = 0;
+ this.state = [];
+ this.pushState({
+ indentstr : '',
+ in_pre : false,
+ in_inline : false
+ })
+ },
+ /**
+ * Returns the contents that got serialized.
+ *
+ * @method getContent
+ * @return {String} HTML contents that got written down.
+ */
+ getContent: function() {
+ return this.html.join('').replace(/\n$/, '');
},
-
- // private
- onViewOver : function(e, t){
- if(this.inKeyMode){ // prevent key nav and mouse over conflicts
- return;
+
+ pushState : function(cfg)
+ {
+ this.state.push(cfg);
+ Roo.apply(this, cfg);
+ },
+
+ popState : function()
+ {
+ if (this.state.length < 1) {
+ return; // nothing to push
}
- var item = this.view.findItemFromChild(t);
- if(item){
- var index = this.view.indexOf(item);
- this.select(index, false);
+ var cfg = {
+ in_pre: false,
+ indentstr : ''
+ };
+ this.state.pop();
+ if (this.state.length > 0) {
+ cfg = this.state[this.state.length-1];
}
+ Roo.apply(this, cfg);
},
-
- // private
- onViewClick : function(doFocus)
+
+ addLine: function()
{
- var index = this.view.getSelectedIndexes()[0];
- var r = this.store.getAt(index);
- if(r){
- this.onSelect(r, index);
+ if (this.html.length < 1) {
+ return;
}
- if(doFocus !== false && !this.blockFocus){
- this.el.focus();
+
+
+ var value = this.html[this.html.length - 1];
+ if (value.length > 0 && '\n' !== value) {
+ this.html.push('\n');
}
- },
+ }
+
+
+//'pre script noscript style textarea video audio iframe object code'
+// shortended... 'area base basefont br col frame hr img input isindex link meta param embed source wbr track');
+// inline
+};
- // private
- restrictHeight : function(){
- this.innerList.dom.style.height = '';
- var inner = this.innerList.dom;
- var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
- this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
- this.list.beginUpdate();
- this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
- this.list.alignTo(this.el, this.listAlign);
- this.list.endUpdate();
- },
+Roo.htmleditor.TidyWriter.inline_elements = [
+ 'SPAN','STRONG','B','EM','I','FONT','STRIKE','U','VAR',
+ 'CITE','DFN','CODE','MARK','Q','SUP','SUB','SAMP', 'A'
+];
+Roo.htmleditor.TidyWriter.shortend_elements = [
+ 'AREA','BASE','BASEFONT','BR','COL','FRAME','HR','IMG','INPUT',
+ 'ISINDEX','LINK','','META','PARAM','EMBED','SOURCE','WBR','TRACK'
+];
- // private
- onEmptyResults : function(){
- this.collapse();
- },
+Roo.htmleditor.TidyWriter.whitespace_elements = [
+ 'PRE','SCRIPT','NOSCRIPT','STYLE','TEXTAREA','VIDEO','AUDIO','IFRAME','OBJECT','CODE'
+];/***
+ * This is based loosely on tinymce
+ * @class Roo.htmleditor.TidyEntities
+ * @static
+ * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
+ *
+ * Not 100% sure this is actually used or needed.
+ */
+Roo.htmleditor.TidyEntities = {
+
/**
- * Returns true if the dropdown list is expanded, else false.
+ * initialize data..
*/
- isExpanded : function(){
- return this.list.isVisible();
+ init : function (){
+
+ this.namedEntities = this.buildEntitiesLookup(this.namedEntitiesData, 32);
+
},
+
+ buildEntitiesLookup: function(items, radix) {
+ var i, chr, entity, lookup = {};
+ if (!items) {
+ return {};
+ }
+ items = typeof(items) == 'string' ? items.split(',') : items;
+ radix = radix || 10;
+ // Build entities lookup table
+ for (i = 0; i < items.length; i += 2) {
+ chr = String.fromCharCode(parseInt(items[i], radix));
+ // Only add non base entities
+ if (!this.baseEntities[chr]) {
+ entity = '&' + items[i + 1] + ';';
+ lookup[chr] = entity;
+ lookup[entity] = chr;
+ }
+ }
+ return lookup;
+
+ },
+
+ asciiMap : {
+ 128: '€',
+ 130: '‚',
+ 131: 'ƒ',
+ 132: '„',
+ 133: '…',
+ 134: '†',
+ 135: '‡',
+ 136: 'ˆ',
+ 137: '‰',
+ 138: 'Š',
+ 139: '‹',
+ 140: 'Œ',
+ 142: 'Ž',
+ 145: '‘',
+ 146: '’',
+ 147: '“',
+ 148: '”',
+ 149: '•',
+ 150: '–',
+ 151: '—',
+ 152: '˜',
+ 153: '™',
+ 154: 'š',
+ 155: '›',
+ 156: 'œ',
+ 158: 'ž',
+ 159: 'Ÿ'
+ },
+ // Raw entities
+ baseEntities : {
+ '"': '"',
+ // Needs to be escaped since the YUI compressor would otherwise break the code
+ '\'': ''',
+ '<': '<',
+ '>': '>',
+ '&': '&',
+ '`': '`'
+ },
+ // Reverse lookup table for raw entities
+ reverseEntities : {
+ '<': '<',
+ '>': '>',
+ '&': '&',
+ '"': '"',
+ ''': '\''
+ },
+
+ attrsCharsRegExp : /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
+ textCharsRegExp : /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
+ rawCharsRegExp : /[<>&\"\']/g,
+ entityRegExp : /&#([a-z0-9]+);?|&([a-z0-9]+);/gi,
+ namedEntities : false,
+ namedEntitiesData : [
+ '50',
+ 'nbsp',
+ '51',
+ 'iexcl',
+ '52',
+ 'cent',
+ '53',
+ 'pound',
+ '54',
+ 'curren',
+ '55',
+ 'yen',
+ '56',
+ 'brvbar',
+ '57',
+ 'sect',
+ '58',
+ 'uml',
+ '59',
+ 'copy',
+ '5a',
+ 'ordf',
+ '5b',
+ 'laquo',
+ '5c',
+ 'not',
+ '5d',
+ 'shy',
+ '5e',
+ 'reg',
+ '5f',
+ 'macr',
+ '5g',
+ 'deg',
+ '5h',
+ 'plusmn',
+ '5i',
+ 'sup2',
+ '5j',
+ 'sup3',
+ '5k',
+ 'acute',
+ '5l',
+ 'micro',
+ '5m',
+ 'para',
+ '5n',
+ 'middot',
+ '5o',
+ 'cedil',
+ '5p',
+ 'sup1',
+ '5q',
+ 'ordm',
+ '5r',
+ 'raquo',
+ '5s',
+ 'frac14',
+ '5t',
+ 'frac12',
+ '5u',
+ 'frac34',
+ '5v',
+ 'iquest',
+ '60',
+ 'Agrave',
+ '61',
+ 'Aacute',
+ '62',
+ 'Acirc',
+ '63',
+ 'Atilde',
+ '64',
+ 'Auml',
+ '65',
+ 'Aring',
+ '66',
+ 'AElig',
+ '67',
+ 'Ccedil',
+ '68',
+ 'Egrave',
+ '69',
+ 'Eacute',
+ '6a',
+ 'Ecirc',
+ '6b',
+ 'Euml',
+ '6c',
+ 'Igrave',
+ '6d',
+ 'Iacute',
+ '6e',
+ 'Icirc',
+ '6f',
+ 'Iuml',
+ '6g',
+ 'ETH',
+ '6h',
+ 'Ntilde',
+ '6i',
+ 'Ograve',
+ '6j',
+ 'Oacute',
+ '6k',
+ 'Ocirc',
+ '6l',
+ 'Otilde',
+ '6m',
+ 'Ouml',
+ '6n',
+ 'times',
+ '6o',
+ 'Oslash',
+ '6p',
+ 'Ugrave',
+ '6q',
+ 'Uacute',
+ '6r',
+ 'Ucirc',
+ '6s',
+ 'Uuml',
+ '6t',
+ 'Yacute',
+ '6u',
+ 'THORN',
+ '6v',
+ 'szlig',
+ '70',
+ 'agrave',
+ '71',
+ 'aacute',
+ '72',
+ 'acirc',
+ '73',
+ 'atilde',
+ '74',
+ 'auml',
+ '75',
+ 'aring',
+ '76',
+ 'aelig',
+ '77',
+ 'ccedil',
+ '78',
+ 'egrave',
+ '79',
+ 'eacute',
+ '7a',
+ 'ecirc',
+ '7b',
+ 'euml',
+ '7c',
+ 'igrave',
+ '7d',
+ 'iacute',
+ '7e',
+ 'icirc',
+ '7f',
+ 'iuml',
+ '7g',
+ 'eth',
+ '7h',
+ 'ntilde',
+ '7i',
+ 'ograve',
+ '7j',
+ 'oacute',
+ '7k',
+ 'ocirc',
+ '7l',
+ 'otilde',
+ '7m',
+ 'ouml',
+ '7n',
+ 'divide',
+ '7o',
+ 'oslash',
+ '7p',
+ 'ugrave',
+ '7q',
+ 'uacute',
+ '7r',
+ 'ucirc',
+ '7s',
+ 'uuml',
+ '7t',
+ 'yacute',
+ '7u',
+ 'thorn',
+ '7v',
+ 'yuml',
+ 'ci',
+ 'fnof',
+ 'sh',
+ 'Alpha',
+ 'si',
+ 'Beta',
+ 'sj',
+ 'Gamma',
+ 'sk',
+ 'Delta',
+ 'sl',
+ 'Epsilon',
+ 'sm',
+ 'Zeta',
+ 'sn',
+ 'Eta',
+ 'so',
+ 'Theta',
+ 'sp',
+ 'Iota',
+ 'sq',
+ 'Kappa',
+ 'sr',
+ 'Lambda',
+ 'ss',
+ 'Mu',
+ 'st',
+ 'Nu',
+ 'su',
+ 'Xi',
+ 'sv',
+ 'Omicron',
+ 't0',
+ 'Pi',
+ 't1',
+ 'Rho',
+ 't3',
+ 'Sigma',
+ 't4',
+ 'Tau',
+ 't5',
+ 'Upsilon',
+ 't6',
+ 'Phi',
+ 't7',
+ 'Chi',
+ 't8',
+ 'Psi',
+ 't9',
+ 'Omega',
+ 'th',
+ 'alpha',
+ 'ti',
+ 'beta',
+ 'tj',
+ 'gamma',
+ 'tk',
+ 'delta',
+ 'tl',
+ 'epsilon',
+ 'tm',
+ 'zeta',
+ 'tn',
+ 'eta',
+ 'to',
+ 'theta',
+ 'tp',
+ 'iota',
+ 'tq',
+ 'kappa',
+ 'tr',
+ 'lambda',
+ 'ts',
+ 'mu',
+ 'tt',
+ 'nu',
+ 'tu',
+ 'xi',
+ 'tv',
+ 'omicron',
+ 'u0',
+ 'pi',
+ 'u1',
+ 'rho',
+ 'u2',
+ 'sigmaf',
+ 'u3',
+ 'sigma',
+ 'u4',
+ 'tau',
+ 'u5',
+ 'upsilon',
+ 'u6',
+ 'phi',
+ 'u7',
+ 'chi',
+ 'u8',
+ 'psi',
+ 'u9',
+ 'omega',
+ 'uh',
+ 'thetasym',
+ 'ui',
+ 'upsih',
+ 'um',
+ 'piv',
+ '812',
+ 'bull',
+ '816',
+ 'hellip',
+ '81i',
+ 'prime',
+ '81j',
+ 'Prime',
+ '81u',
+ 'oline',
+ '824',
+ 'frasl',
+ '88o',
+ 'weierp',
+ '88h',
+ 'image',
+ '88s',
+ 'real',
+ '892',
+ 'trade',
+ '89l',
+ 'alefsym',
+ '8cg',
+ 'larr',
+ '8ch',
+ 'uarr',
+ '8ci',
+ 'rarr',
+ '8cj',
+ 'darr',
+ '8ck',
+ 'harr',
+ '8dl',
+ 'crarr',
+ '8eg',
+ 'lArr',
+ '8eh',
+ 'uArr',
+ '8ei',
+ 'rArr',
+ '8ej',
+ 'dArr',
+ '8ek',
+ 'hArr',
+ '8g0',
+ 'forall',
+ '8g2',
+ 'part',
+ '8g3',
+ 'exist',
+ '8g5',
+ 'empty',
+ '8g7',
+ 'nabla',
+ '8g8',
+ 'isin',
+ '8g9',
+ 'notin',
+ '8gb',
+ 'ni',
+ '8gf',
+ 'prod',
+ '8gh',
+ 'sum',
+ '8gi',
+ 'minus',
+ '8gn',
+ 'lowast',
+ '8gq',
+ 'radic',
+ '8gt',
+ 'prop',
+ '8gu',
+ 'infin',
+ '8h0',
+ 'ang',
+ '8h7',
+ 'and',
+ '8h8',
+ 'or',
+ '8h9',
+ 'cap',
+ '8ha',
+ 'cup',
+ '8hb',
+ 'int',
+ '8hk',
+ 'there4',
+ '8hs',
+ 'sim',
+ '8i5',
+ 'cong',
+ '8i8',
+ 'asymp',
+ '8j0',
+ 'ne',
+ '8j1',
+ 'equiv',
+ '8j4',
+ 'le',
+ '8j5',
+ 'ge',
+ '8k2',
+ 'sub',
+ '8k3',
+ 'sup',
+ '8k4',
+ 'nsub',
+ '8k6',
+ 'sube',
+ '8k7',
+ 'supe',
+ '8kl',
+ 'oplus',
+ '8kn',
+ 'otimes',
+ '8l5',
+ 'perp',
+ '8m5',
+ 'sdot',
+ '8o8',
+ 'lceil',
+ '8o9',
+ 'rceil',
+ '8oa',
+ 'lfloor',
+ '8ob',
+ 'rfloor',
+ '8p9',
+ 'lang',
+ '8pa',
+ 'rang',
+ '9ea',
+ 'loz',
+ '9j0',
+ 'spades',
+ '9j3',
+ 'clubs',
+ '9j5',
+ 'hearts',
+ '9j6',
+ 'diams',
+ 'ai',
+ 'OElig',
+ 'aj',
+ 'oelig',
+ 'b0',
+ 'Scaron',
+ 'b1',
+ 'scaron',
+ 'bo',
+ 'Yuml',
+ 'm6',
+ 'circ',
+ 'ms',
+ 'tilde',
+ '802',
+ 'ensp',
+ '803',
+ 'emsp',
+ '809',
+ 'thinsp',
+ '80c',
+ 'zwnj',
+ '80d',
+ 'zwj',
+ '80e',
+ 'lrm',
+ '80f',
+ 'rlm',
+ '80j',
+ 'ndash',
+ '80k',
+ 'mdash',
+ '80o',
+ 'lsquo',
+ '80p',
+ 'rsquo',
+ '80q',
+ 'sbquo',
+ '80s',
+ 'ldquo',
+ '80t',
+ 'rdquo',
+ '80u',
+ 'bdquo',
+ '810',
+ 'dagger',
+ '811',
+ 'Dagger',
+ '81g',
+ 'permil',
+ '81p',
+ 'lsaquo',
+ '81q',
+ 'rsaquo',
+ '85c',
+ 'euro'
+ ],
+
+
/**
- * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
- * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
- * @param {String} value The data value of the item to select
- * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
- * selected item if it is not currently in view (defaults to true)
- * @return {Boolean} True if the value matched an item in the list, else false
+ * Encodes the specified string using raw entities. This means only the required XML base entities will be encoded.
+ *
+ * @method encodeRaw
+ * @param {String} text Text to encode.
+ * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
+ * @return {String} Entity encoded text.
*/
- selectByValue : function(v, scrollIntoView){
- if(v !== undefined && v !== null){
- var r = this.findRecord(this.valueField || this.displayField, v);
- if(r){
- this.select(this.store.indexOf(r), scrollIntoView);
- return true;
- }
- }
- return false;
+ encodeRaw: function(text, attr)
+ {
+ var t = this;
+ return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
+ return t.baseEntities[chr] || chr;
+ });
},
-
/**
- * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
- * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
- * @param {Number} index The zero-based index of the list item to select
- * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
- * selected item if it is not currently in view (defaults to true)
+ * Encoded the specified text with both the attributes and text entities. This function will produce larger text contents
+ * since it doesn't know if the context is within a attribute or text node. This was added for compatibility
+ * and is exposed as the DOMUtils.encode function.
+ *
+ * @method encodeAllRaw
+ * @param {String} text Text to encode.
+ * @return {String} Entity encoded text.
*/
- select : function(index, scrollIntoView){
- this.selectedIndex = index;
- this.view.select(index);
- if(scrollIntoView !== false){
- var el = this.view.getNode(index);
- if(el){
- this.innerList.scrollChildIntoView(el, false);
+ encodeAllRaw: function(text) {
+ var t = this;
+ return ('' + text).replace(this.rawCharsRegExp, function(chr) {
+ return t.baseEntities[chr] || chr;
+ });
+ },
+ /**
+ * Encodes the specified string using numeric entities. The core entities will be
+ * encoded as named ones but all non lower ascii characters will be encoded into numeric entities.
+ *
+ * @method encodeNumeric
+ * @param {String} text Text to encode.
+ * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
+ * @return {String} Entity encoded text.
+ */
+ encodeNumeric: function(text, attr) {
+ var t = this;
+ return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
+ // Multi byte sequence convert it to a single entity
+ if (chr.length > 1) {
+ return '&#' + (1024 * (chr.charCodeAt(0) - 55296) + (chr.charCodeAt(1) - 56320) + 65536) + ';';
}
- }
+ return t.baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
+ });
+ },
+ /**
+ * Encodes the specified string using named entities. The core entities will be encoded
+ * as named ones but all non lower ascii characters will be encoded into named entities.
+ *
+ * @method encodeNamed
+ * @param {String} text Text to encode.
+ * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
+ * @param {Object} entities Optional parameter with entities to use.
+ * @return {String} Entity encoded text.
+ */
+ encodeNamed: function(text, attr, entities) {
+ var t = this;
+ entities = entities || this.namedEntities;
+ return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
+ return t.baseEntities[chr] || entities[chr] || chr;
+ });
},
+ /**
+ * Returns an encode function based on the name(s) and it's optional entities.
+ *
+ * @method getEncodeFunc
+ * @param {String} name Comma separated list of encoders for example named,numeric.
+ * @param {String} entities Optional parameter with entities to use instead of the built in set.
+ * @return {function} Encode function to be used.
+ */
+ getEncodeFunc: function(name, entities) {
+ entities = this.buildEntitiesLookup(entities) || this.namedEntities;
+ var t = this;
+ function encodeNamedAndNumeric(text, attr) {
+ return text.replace(attr ? t.attrsCharsRegExp : t.textCharsRegExp, function(chr) {
+ return t.baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr;
+ });
+ }
- // private
- selectNext : function(){
- var ct = this.store.getCount();
- if(ct > 0){
- if(this.selectedIndex == -1){
- this.select(0);
- }else if(this.selectedIndex < ct-1){
- this.select(this.selectedIndex+1);
+ function encodeCustomNamed(text, attr) {
+ return t.encodeNamed(text, attr, entities);
+ }
+ // Replace + with , to be compatible with previous TinyMCE versions
+ name = this.makeMap(name.replace(/\+/g, ','));
+ // Named and numeric encoder
+ if (name.named && name.numeric) {
+ return this.encodeNamedAndNumeric;
+ }
+ // Named encoder
+ if (name.named) {
+ // Custom names
+ if (entities) {
+ return encodeCustomNamed;
}
+ return this.encodeNamed;
}
+ // Numeric
+ if (name.numeric) {
+ return this.encodeNumeric;
+ }
+ // Raw encoder
+ return this.encodeRaw;
},
-
- // private
- selectPrev : function(){
- var ct = this.store.getCount();
- if(ct > 0){
- if(this.selectedIndex == -1){
- this.select(0);
- }else if(this.selectedIndex != 0){
- this.select(this.selectedIndex-1);
+ /**
+ * Decodes the specified string, this will replace entities with raw UTF characters.
+ *
+ * @method decode
+ * @param {String} text Text to entity decode.
+ * @return {String} Entity decoded string.
+ */
+ decode: function(text)
+ {
+ var t = this;
+ return text.replace(this.entityRegExp, function(all, numeric) {
+ if (numeric) {
+ numeric = 'x' === numeric.charAt(0).toLowerCase() ? parseInt(numeric.substr(1), 16) : parseInt(numeric, 10);
+ // Support upper UTF
+ if (numeric > 65535) {
+ numeric -= 65536;
+ return String.fromCharCode(55296 + (numeric >> 10), 56320 + (1023 & numeric));
+ }
+ return t.asciiMap[numeric] || String.fromCharCode(numeric);
}
- }
+ return t.reverseEntities[all] || t.namedEntities[all] || t.nativeDecode(all);
+ });
},
-
- // private
- onKeyUp : function(e){
- if(this.editable !== false && !e.isSpecialKey()){
- this.lastKey = e.getKey();
- this.dqTask.delay(this.queryDelay);
- }
+ nativeDecode : function (text) {
+ return text;
},
+ makeMap : function (items, delim, map) {
+ var i;
+ items = items || [];
+ delim = delim || ',';
+ if (typeof items == "string") {
+ items = items.split(delim);
+ }
+ map = map || {};
+ i = items.length;
+ while (i--) {
+ map[items[i]] = {};
+ }
+ return map;
+ }
+};
+
+
+
+Roo.htmleditor.TidyEntities.init();
+/**
+ * @class Roo.htmleditor.KeyEnter
+ * Handle Enter press..
+ * @cfg {Roo.HtmlEditorCore} core the editor.
+ * @constructor
+ * Create a new Filter.
+ * @param {Object} config Configuration options
+ */
- // private
- validateBlur : function(){
- return !this.list || !this.list.isVisible();
- },
- // private
- initQuery : function(){
- this.doQuery(this.getRawValue());
- },
- // private
- doForce : function(){
- if(this.el.dom.value.length > 0){
- this.el.dom.value =
- this.lastSelectionText === undefined ? '' : this.lastSelectionText;
-
- }
- },
- /**
- * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
- * query allowing the query action to be canceled if needed.
- * @param {String} query The SQL query to execute
- * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
- * in the field than the minimum specified by the minChars config option. It also clears any filter previously
- * saved in the current store (defaults to false)
- */
- doQuery : function(q, forceAll){
- if(q === undefined || q === null){
- q = '';
+
+Roo.htmleditor.KeyEnter = function(cfg) {
+ Roo.apply(this, cfg);
+ // this does not actually call walk as it's really just a abstract class
+
+ Roo.get(this.core.doc.body).on('keypress', this.keypress, this);
+}
+
+//Roo.htmleditor.KeyEnter.i = 0;
+
+
+Roo.htmleditor.KeyEnter.prototype = {
+
+ core : false,
+
+ keypress : function(e)
+ {
+ if (e.charCode != 13 && e.charCode != 10) {
+ Roo.log([e.charCode,e]);
+ return true;
}
- var qe = {
- query: q,
- forceAll: forceAll,
- combo: this,
- cancel:false
- };
- if(this.fireEvent('beforequery', qe)===false || qe.cancel){
+ e.preventDefault();
+ // https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
+ var doc = this.core.doc;
+ //add a new line
+
+
+ var sel = this.core.getSelection();
+ var range = sel.getRangeAt(0);
+ var n = range.commonAncestorContainer;
+ var pc = range.closest([ 'ol', 'ul']);
+ var pli = range.closest('li');
+ if (!pc || e.ctrlKey) {
+ // on it list, or ctrl pressed.
+ if (!e.ctrlKey) {
+ sel.insertNode('br', 'after');
+ } else {
+ // only do this if we have ctrl key..
+ var br = doc.createElement('br');
+ br.className = 'clear';
+ br.setAttribute('style', 'clear: both');
+ sel.insertNode(br, 'after');
+ }
+
+
+ this.core.undoManager.addEvent();
+ this.core.fireEditorEvent(e);
return false;
}
- q = qe.query;
- forceAll = qe.forceAll;
- if(forceAll === true || (q.length >= this.minChars)){
- if(this.lastQuery != q || this.alwaysQuery){
- this.lastQuery = q;
- if(this.mode == 'local'){
- this.selectedIndex = -1;
- if(forceAll){
- this.store.clearFilter();
- }else{
- this.store.filter(this.displayField, q);
- }
- this.onLoad();
- }else{
- this.store.baseParams[this.queryParam] = q;
- this.store.load({
- params: this.getParams(q)
- });
- this.expand();
- }
- }else{
- this.selectedIndex = -1;
- this.onLoad();
- }
+
+ // deal with <li> insetion
+ if (pli.innerText.trim() == '' &&
+ pli.previousSibling &&
+ pli.previousSibling.nodeName == 'LI' &&
+ pli.previousSibling.innerText.trim() == '') {
+ pli.parentNode.removeChild(pli.previousSibling);
+ sel.cursorAfter(pc);
+ this.core.undoManager.addEvent();
+ this.core.fireEditorEvent(e);
+ return false;
}
- },
-
- // private
- getParams : function(q){
- var p = {};
- //p[this.queryParam] = q;
- if(this.pageSize){
- p.start = 0;
- p.limit = this.pageSize;
+
+ var li = doc.createElement('LI');
+ li.innerHTML = ' ';
+ if (!pli || !pli.firstSibling) {
+ pc.appendChild(li);
+ } else {
+ pli.parentNode.insertBefore(li, pli.firstSibling);
}
- return p;
- },
+ sel.cursorText (li.firstChild);
+
+ this.core.undoManager.addEvent();
+ this.core.fireEditorEvent(e);
+
+ return false;
+
+
+
+
+
+ }
+};
+
+/**
+ * @class Roo.htmleditor.Block
+ * Base class for html editor blocks - do not use it directly .. extend it..
+ * @cfg {DomElement} node The node to apply stuff to.
+ * @cfg {String} friendly_name the name that appears in the context bar about this block
+ * @cfg {Object} Context menu - see Roo.form.HtmlEditor.ToolbarContext
+
+ * @constructor
+ * Create a new Filter.
+ * @param {Object} config Configuration options
+ */
+
+Roo.htmleditor.Block = function(cfg)
+{
+ // do nothing .. should not be called really.
+}
+/**
+ * factory method to get the block from an element (using cache if necessary)
+ * @static
+ * @param {HtmlElement} the dom element
+ */
+Roo.htmleditor.Block.factory = function(node)
+{
+ var cc = Roo.htmleditor.Block.cache;
+ var id = Roo.get(node).id;
+ if (typeof(cc[id]) != 'undefined' && (!cc[id].node || cc[id].node.closest('body'))) {
+ Roo.htmleditor.Block.cache[id].readElement(node);
+ return Roo.htmleditor.Block.cache[id];
+ }
+ var db = node.getAttribute('data-block');
+ if (!db) {
+ db = node.nodeName.toLowerCase().toUpperCaseFirst();
+ }
+ var cls = Roo.htmleditor['Block' + db];
+ if (typeof(cls) == 'undefined') {
+ //Roo.log(node.getAttribute('data-block'));
+ Roo.log("OOps missing block : " + 'Block' + db);
+ return false;
+ }
+ Roo.htmleditor.Block.cache[id] = new cls({ node: node });
+ return Roo.htmleditor.Block.cache[id]; /// should trigger update element
+};
+
+/**
+ * initalize all Elements from content that are 'blockable'
+ * @static
+ * @param the body element
+ */
+Roo.htmleditor.Block.initAll = function(body, type)
+{
+ if (typeof(type) == 'undefined') {
+ var ia = Roo.htmleditor.Block.initAll;
+ ia(body,'table');
+ ia(body,'td');
+ ia(body,'figure');
+ return;
+ }
+ Roo.each(Roo.get(body).query(type), function(e) {
+ Roo.htmleditor.Block.factory(e);
+ },this);
+};
+// question goes here... do we need to clear out this cache sometimes?
+// or show we make it relivant to the htmleditor.
+Roo.htmleditor.Block.cache = {};
+Roo.htmleditor.Block.prototype = {
+
+ node : false,
+
+ // used by context menu
+ friendly_name : 'Based Block',
+
+ // text for button to delete this element
+ deleteTitle : false,
+
+ context : false,
/**
- * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
+ * Update a node with values from this object
+ * @param {DomElement} node
*/
- collapse : function(){
- if(!this.isExpanded()){
- return;
- }
- this.list.hide();
- Roo.get(document).un('mousedown', this.collapseIf, this);
- Roo.get(document).un('mousewheel', this.collapseIf, this);
- if (!this.editable) {
- Roo.get(document).un('keydown', this.listKeyPress, this);
- }
- this.fireEvent('collapse', this);
+ updateElement : function(node)
+ {
+ Roo.DomHelper.update(node === undefined ? this.node : node, this.toObject());
},
-
- // private
- collapseIf : function(e){
- if(!e.within(this.wrap) && !e.within(this.list)){
- this.collapse();
- }
+ /**
+ * convert to plain HTML for calling insertAtCursor..
+ */
+ toHTML : function()
+ {
+ return Roo.DomHelper.markup(this.toObject());
},
-
/**
- * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
+ * used by readEleemnt to extract data from a node
+ * may need improving as it's pretty basic
+
+ * @param {DomElement} node
+ * @param {String} tag - tag to find, eg. IMG ?? might be better to use DomQuery ?
+ * @param {String} attribute (use html - for contents, style for using next param as style, or false to return the node)
+ * @param {String} style the style property - eg. text-align
*/
- expand : function(){
- if(this.isExpanded() || !this.hasFocus){
- return;
+ getVal : function(node, tag, attr, style)
+ {
+ var n = node;
+ if (tag !== true && n.tagName != tag.toUpperCase()) {
+ // in theory we could do figure[3] << 3rd figure? or some more complex search..?
+ // but kiss for now.
+ n = node.getElementsByTagName(tag).item(0);
}
- this.list.alignTo(this.el, this.listAlign);
- this.list.show();
- Roo.get(document).on('mousedown', this.collapseIf, this);
- Roo.get(document).on('mousewheel', this.collapseIf, this);
- if (!this.editable) {
- Roo.get(document).on('keydown', this.listKeyPress, this);
+ if (!n) {
+ return '';
+ }
+ if (attr === false) {
+ return n;
+ }
+ if (attr == 'html') {
+ return n.innerHTML;
+ }
+ if (attr == 'style') {
+ return n.style[style];
}
- this.fireEvent('expand', this);
+ return n.hasAttribute(attr) ? n.getAttribute(attr) : '';
+
+ },
+ /**
+ * create a DomHelper friendly object - for use with
+ * Roo.DomHelper.markup / overwrite / etc..
+ * (override this)
+ */
+ toObject : function()
+ {
+ return {};
},
+ /**
+ * Read a node that has a 'data-block' property - and extract the values from it.
+ * @param {DomElement} node - the node
+ */
+ readElement : function(node)
+ {
+
+ }
+
+
+};
- // private
- // Implements the default empty TriggerField.onTriggerClick function
- onTriggerClick : function(){
- if(this.disabled){
- return;
- }
- if(this.isExpanded()){
- this.collapse();
- if (!this.blockFocus) {
- this.el.focus();
- }
+
+
+/**
+ * @class Roo.htmleditor.BlockFigure
+ * Block that has an image and a figcaption
+ * @cfg {String} image_src the url for the image
+ * @cfg {String} align (left|right) alignment for the block default left
+ * @cfg {String} caption the text to appear below (and in the alt tag)
+ * @cfg {String} caption_display (block|none) display or not the caption
+ * @cfg {String|number} image_width the width of the image number or %?
+ * @cfg {String|number} image_height the height of the image number or %?
+ *
+ * @constructor
+ * Create a new Filter.
+ * @param {Object} config Configuration options
+ */
+
+Roo.htmleditor.BlockFigure = function(cfg)
+{
+ if (cfg.node) {
+ this.readElement(cfg.node);
+ this.updateElement(cfg.node);
+ }
+ Roo.apply(this, cfg);
+}
+Roo.extend(Roo.htmleditor.BlockFigure, Roo.htmleditor.Block, {
+
+
+ // setable values.
+ image_src: '',
+ align: 'center',
+ caption : '',
+ caption_display : 'block',
+ width : '100%',
+ cls : '',
+ href: '',
+ video_url : '',
+
+ // margin: '2%', not used
+
+ text_align: 'left', // (left|right) alignment for the text caption default left. - not used at present
+
+
+ // used by context menu
+ friendly_name : 'Image with caption',
+ deleteTitle : "Delete Image and Caption",
+
+ contextMenu : function(toolbar)
+ {
+
+ var block = function() {
+ return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
+ };
+
+
+ var rooui = typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
+
+ var syncValue = toolbar.editorcore.syncValue;
+
+ var fields = {};
+
+ return [
+ {
+ xtype : 'TextItem',
+ text : "Source: ",
+ xns : rooui.Toolbar //Boostrap?
+ },
+ {
+ xtype : 'Button',
+ text: 'Change Image URL',
+
+ listeners : {
+ click: function (btn, state)
+ {
+ var b = block();
+
+ Roo.MessageBox.show({
+ title : "Image Source URL",
+ msg : "Enter the url for the image",
+ buttons: Roo.MessageBox.OKCANCEL,
+ fn: function(btn, val){
+ if (btn != 'ok') {
+ return;
+ }
+ b.image_src = val;
+ b.updateElement();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ },
+ minWidth:250,
+ prompt:true,
+ //multiline: multiline,
+ modal : true,
+ value : b.image_src
+ });
+ }
+ },
+ xns : rooui.Toolbar
+ },
+
+ {
+ xtype : 'Button',
+ text: 'Change Link URL',
+
+ listeners : {
+ click: function (btn, state)
+ {
+ var b = block();
+
+ Roo.MessageBox.show({
+ title : "Link URL",
+ msg : "Enter the url for the link - leave blank to have no link",
+ buttons: Roo.MessageBox.OKCANCEL,
+ fn: function(btn, val){
+ if (btn != 'ok') {
+ return;
+ }
+ b.href = val;
+ b.updateElement();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ },
+ minWidth:250,
+ prompt:true,
+ //multiline: multiline,
+ modal : true,
+ value : b.href
+ });
+ }
+ },
+ xns : rooui.Toolbar
+ },
+ {
+ xtype : 'Button',
+ text: 'Show Video URL',
+
+ listeners : {
+ click: function (btn, state)
+ {
+ Roo.MessageBox.alert("Video URL",
+ block().video_url == '' ? 'This image is not linked ot a video' :
+ 'The image is linked to: <a target="_new" href="' + block().video_url + '">' + block().video_url + '</a>');
+ }
+ },
+ xns : rooui.Toolbar
+ },
- }else {
- this.hasFocus = true;
- if(this.triggerAction == 'all') {
- this.doQuery(this.allQuery, true);
- } else {
- this.doQuery(this.getRawValue());
- }
- if (!this.blockFocus) {
- this.el.focus();
+
+ {
+ xtype : 'TextItem',
+ text : "Width: ",
+ xns : rooui.Toolbar //Boostrap?
+ },
+ {
+ xtype : 'ComboBox',
+ allowBlank : false,
+ displayField : 'val',
+ editable : true,
+ listWidth : 100,
+ triggerAction : 'all',
+ typeAhead : true,
+ valueField : 'val',
+ width : 70,
+ name : 'width',
+ listeners : {
+ select : function (combo, r, index)
+ {
+ toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ var b = block();
+ b.width = r.get('val');
+ b.updateElement();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.form,
+ store : {
+ xtype : 'SimpleStore',
+ data : [
+ ['100%'],
+ ['80%'],
+ ['50%'],
+ ['20%'],
+ ['10%']
+ ],
+ fields : [ 'val'],
+ xns : Roo.data
+ }
+ },
+ {
+ xtype : 'TextItem',
+ text : "Align: ",
+ xns : rooui.Toolbar //Boostrap?
+ },
+ {
+ xtype : 'ComboBox',
+ allowBlank : false,
+ displayField : 'val',
+ editable : true,
+ listWidth : 100,
+ triggerAction : 'all',
+ typeAhead : true,
+ valueField : 'val',
+ width : 70,
+ name : 'align',
+ listeners : {
+ select : function (combo, r, index)
+ {
+ toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ var b = block();
+ b.align = r.get('val');
+ b.updateElement();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.form,
+ store : {
+ xtype : 'SimpleStore',
+ data : [
+ ['left'],
+ ['right'],
+ ['center']
+ ],
+ fields : [ 'val'],
+ xns : Roo.data
+ }
+ },
+
+
+ {
+ xtype : 'Button',
+ text: 'Hide Caption',
+ name : 'caption_display',
+ pressed : false,
+ enableToggle : true,
+ setValue : function(v) {
+ // this trigger toggle.
+
+ this.setText(v ? "Hide Caption" : "Show Caption");
+ this.setPressed(v != 'block');
+ },
+ listeners : {
+ toggle: function (btn, state)
+ {
+ var b = block();
+ b.caption_display = b.caption_display == 'block' ? 'none' : 'block';
+ this.setText(b.caption_display == 'block' ? "Hide Caption" : "Show Caption");
+ b.updateElement();
+ syncValue();
+ toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.Toolbar
}
- }
+ ];
+
},
- listKeyPress : function(e)
+ /**
+ * create a DomHelper friendly object - for use with
+ * Roo.DomHelper.markup / overwrite / etc..
+ */
+ toObject : function()
{
- //Roo.log('listkeypress');
- // scroll to first matching element based on key pres..
- if (e.isSpecialKey()) {
- return false;
+ var d = document.createElement('div');
+ d.innerHTML = this.caption;
+
+ var m = this.width != '100%' && this.align == 'center' ? '0 auto' : 0;
+
+ var iw = this.align == 'center' ? this.width : '100%';
+ var img = {
+ tag : 'img',
+ contenteditable : 'false',
+ src : this.image_src,
+ alt : d.innerText.replace(/\n/g, " ").replace(/\s+/g, ' ').trim(), // removeHTML and reduce spaces..
+ style: {
+ width : iw,
+ maxWidth : iw + ' !important', // this is not getting rendered?
+ margin : m
+
+ },
+ width: this.align == 'center' ? this.width : '100%'
+
+ };
+
+ /*
+ '<div class="{0}" width="420" height="315" src="{1}" frameborder="0" allowfullscreen>' +
+ '<a href="{2}">' +
+ '<img class="{0}-thumbnail" src="{3}/Images/{4}/{5}#image-{4}" />' +
+ '</a>' +
+ '</div>',
+ */
+
+ if (this.href.length > 0) {
+ img = {
+ tag : 'a',
+ href: this.href,
+ contenteditable : 'true',
+ cn : [
+ img
+ ]
+ };
}
- var k = String.fromCharCode(e.getKey()).toUpperCase();
- //Roo.log(k);
- var match = false;
- var csel = this.view.getSelectedNodes();
- var cselitem = false;
- if (csel.length) {
- var ix = this.view.indexOf(csel[0]);
- cselitem = this.store.getAt(ix);
- if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
- cselitem = false;
- }
+
+
+ if (this.video_url.length > 0) {
+ img = {
+ tag : 'div',
+ cls : this.cls,
+ frameborder : 0,
+ allowfullscreen : true,
+ width : 420, // these are for video tricks - that we replace the outer
+ height : 315,
+ src : this.video_url,
+ cn : [
+ img
+ ]
+ };
+ }
+
+
+
+ var ret = {
+ tag: 'figure',
+ 'data-block' : 'Figure',
+ 'data-width' : this.width,
+ 'data-caption' : this.caption,
+ 'data-caption-display' : this.caption_display,
+ contenteditable : 'false',
+
+ style : {
+ display: 'block',
+ float : this.align ,
+ maxWidth : this.align == 'center' ? '100% !important' : (this.width + ' !important'),
+ width : this.align == 'center' ? '100%' : this.width,
+ margin: '0px',
+ padding: this.align == 'center' ? '0' : '0 10px' ,
+ textAlign : this.align // seems to work for email..
+
+ },
+ align : this.align,
+ cn : [
+ img
+ ]
+ };
+
+ // show figcaption only if caption_display is 'block'
+ if(this.caption_display == 'block') {
+ ret['cn'].push({
+ tag: 'figcaption',
+ style : {
+ textAlign : 'left',
+ fontSize : '16px',
+ lineHeight : '24px',
+ display : this.caption_display,
+ maxWidth : (this.align == 'center' ? this.width : '100%' ) + ' !important',
+ margin: m,
+ width: this.align == 'center' ? this.width : '100%'
+
+
+ },
+ cls : this.cls.length > 0 ? (this.cls + '-thumbnail' ) : '',
+ cn : [
+ {
+ tag: 'div',
+ style : {
+ marginTop : '16px',
+ textAlign : 'start'
+ },
+ align: 'left',
+ cn : [
+ {
+ // we can not rely on yahoo syndication to use CSS elements - so have to use '<i>' to encase stuff.
+ tag : 'i',
+ contenteditable : Roo.htmleditor.BlockFigure.caption_edit,
+ html : this.caption.length ? this.caption : "Caption" // fake caption
+ }
+
+ ]
+ }
+
+ ]
+
+ });
}
+ return ret;
+
+ },
+
+ readElement : function(node)
+ {
+ // this should not really come from the link...
+ this.video_url = this.getVal(node, 'div', 'src');
+ this.cls = this.getVal(node, 'div', 'class');
+ this.href = this.getVal(node, 'a', 'href');
- this.store.each(function(v) {
- if (cselitem) {
- // start at existing selection.
- if (cselitem.id == v.id) {
- cselitem = false;
- }
- return;
- }
-
- if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
- match = this.store.indexOf(v);
- return false;
- }
- }, this);
- if (match === false) {
- return true; // no more action?
+ this.image_src = this.getVal(node, 'img', 'src');
+
+ this.align = this.getVal(node, 'figure', 'align');
+
+ // caption display is stored in figure
+ this.caption_display = this.getVal(node, true, 'data-caption-display');
+
+ // backward compatible
+ // it was stored in figcaption
+ if(this.caption_display == '') {
+ this.caption_display = this.getVal(node, 'figcaption', 'data-display');
}
- // scroll to?
- this.view.select(match);
- var sn = Roo.get(this.view.getSelectedNodes()[0]);
- sn.scrollIntoView(sn.dom.parentNode, false);
- }
- /**
- * @cfg {Boolean} grow
- * @hide
- */
- /**
- * @cfg {Number} growMin
- * @hide
- */
- /**
- * @cfg {Number} growMax
- * @hide
- */
- /**
- * @hide
- * @method autoSize
- */
-});/*
- * Copyright(c) 2010-2012, Roo J Solutions Limited
- *
- * Licence LGPL
- *
- */
+ // read caption from figcaption
+ var figcaption = this.getVal(node, 'figcaption', false);
-/**
- * @class Roo.form.ComboBoxArray
- * @extends Roo.form.TextField
- * A facebook style adder... for lists of email / people / countries etc...
- * pick multiple items from a combo box, and shows each one.
- *
- * Fred [x] Brian [x] [Pick another |v]
- *
- *
- * For this to work: it needs various extra information
- * - normal combo problay has
- * name, hiddenName
- * + displayField, valueField
- *
- * For our purpose...
- *
- *
- * If we change from 'extends' to wrapping...
- *
- *
- *
-
-
- * @constructor
- * Create a new ComboBoxArray.
- * @param {Object} config Configuration options
- */
-
+ if (figcaption !== '') {
+ this.caption = this.getVal(figcaption, 'i', 'html');
+ }
+
-Roo.form.ComboBoxArray = function(config)
-{
- this.addEvents({
- /**
- * @event beforeremove
- * Fires before remove the value from the list
- * @param {Roo.form.ComboBoxArray} _self This combo box array
- * @param {Roo.form.ComboBoxArray.Item} item removed item
- */
- 'beforeremove' : true,
- /**
- * @event remove
- * Fires when remove the value from the list
- * @param {Roo.form.ComboBoxArray} _self This combo box array
- * @param {Roo.form.ComboBoxArray.Item} item removed item
- */
- 'remove' : true
-
+ // read caption from data-caption in figure if no caption from figcaption
+ var dc = this.getVal(node, true, 'data-caption');
+
+ if(this.caption_display == 'none' && dc && dc.length){
+ this.caption = dc;
+ }
+
+ //this.text_align = this.getVal(node, 'figcaption', 'style','text-align');
+ this.width = this.getVal(node, true, 'data-width');
+ //this.margin = this.getVal(node, 'figure', 'style', 'margin');
- });
-
- Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
-
- this.items = new Roo.util.MixedCollection(false);
-
- // construct the child combo...
+ },
+ removeNode : function()
+ {
+ return this.node;
+ }
+
+
+
-
-}
+});
+
+Roo.apply(Roo.htmleditor.BlockFigure, {
+ caption_edit : true
+});
-Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
-{
- /**
- * @cfg {Roo.form.ComboBox} combo [required] The combo box that is wrapped
- */
-
- lastData : false,
-
- // behavies liek a hiddne field
- inputType: 'hidden',
- /**
- * @cfg {Number} width The width of the box that displays the selected element
- */
- width: 300,
+/**
+ * @class Roo.htmleditor.BlockTable
+ * Block that manages a table
+ *
+ * @constructor
+ * Create a new Filter.
+ * @param {Object} config Configuration options
+ */
+
+Roo.htmleditor.BlockTable = function(cfg)
+{
+ if (cfg.node) {
+ this.readElement(cfg.node);
+ this.updateElement(cfg.node);
+ }
+ Roo.apply(this, cfg);
+ if (!cfg.node) {
+ this.rows = [];
+ for(var r = 0; r < this.no_row; r++) {
+ this.rows[r] = [];
+ for(var c = 0; c < this.no_col; c++) {
+ this.rows[r][c] = this.emptyCell();
+ }
+ }
+ }
- /**
- * @cfg {String} name The name of the visable items on this form (eg. titles not ids)
- */
- name : false,
- /**
- * @cfg {String} hiddenName The hidden name of the field, often contains an comma seperated list of names
- */
- hiddenName : false,
- /**
- * @cfg {String} seperator The value seperator normally ','
- */
- seperator : ',',
+}
+Roo.extend(Roo.htmleditor.BlockTable, Roo.htmleditor.Block, {
+
+ rows : false,
+ no_col : 1,
+ no_row : 1,
- // private the array of items that are displayed..
- items : false,
- // private - the hidden field el.
- hiddenEl : false,
- // private - the filed el..
- el : false,
- //validateValue : function() { return true; }, // all values are ok!
- //onAddClick: function() { },
+ width: '100%',
- onRender : function(ct, position)
+ // used by context menu
+ friendly_name : 'Table',
+ deleteTitle : 'Delete Table',
+ // context menu is drawn once..
+
+ contextMenu : function(toolbar)
{
- // create the standard hidden element
- //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
-
-
- // give fake names to child combo;
- this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
- this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
-
- this.combo = Roo.factory(this.combo, Roo.form);
- this.combo.onRender(ct, position);
- if (typeof(this.combo.width) != 'undefined') {
- this.combo.onResize(this.combo.width,0);
- }
-
- this.combo.initEvents();
-
- // assigned so form know we need to do this..
- this.store = this.combo.store;
- this.valueField = this.combo.valueField;
- this.displayField = this.combo.displayField ;
-
-
- this.combo.wrap.addClass('x-cbarray-grp');
-
- var cbwrap = this.combo.wrap.createChild(
- {tag: 'div', cls: 'x-cbarray-cb'},
- this.combo.el.dom
- );
-
-
- this.hiddenEl = this.combo.wrap.createChild({
- tag: 'input', type:'hidden' , name: this.hiddenName, value : ''
- });
- this.el = this.combo.wrap.createChild({
- tag: 'input', type:'hidden' , name: this.name, value : ''
- });
- // this.el.dom.removeAttribute("name");
-
-
- this.outerWrap = this.combo.wrap;
- this.wrap = cbwrap;
-
- this.outerWrap.setWidth(this.width);
- this.outerWrap.dom.removeChild(this.el.dom);
+ var block = function() {
+ return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
+ };
- this.wrap.dom.appendChild(this.el.dom);
- this.outerWrap.dom.removeChild(this.combo.trigger.dom);
- this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
- this.combo.trigger.setStyle('position','relative');
- this.combo.trigger.setStyle('left', '0px');
- this.combo.trigger.setStyle('top', '2px');
+ var rooui = typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
- this.combo.el.setStyle('vertical-align', 'text-bottom');
+ var syncValue = toolbar.editorcore.syncValue;
- //this.trigger.setStyle('vertical-align', 'top');
+ var fields = {};
- // this should use the code from combo really... on('add' ....)
- if (this.adder) {
+ return [
+ {
+ xtype : 'TextItem',
+ text : "Width: ",
+ xns : rooui.Toolbar //Boostrap?
+ },
+ {
+ xtype : 'ComboBox',
+ allowBlank : false,
+ displayField : 'val',
+ editable : true,
+ listWidth : 100,
+ triggerAction : 'all',
+ typeAhead : true,
+ valueField : 'val',
+ width : 100,
+ name : 'width',
+ listeners : {
+ select : function (combo, r, index)
+ {
+ toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ var b = block();
+ b.width = r.get('val');
+ b.updateElement();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.form,
+ store : {
+ xtype : 'SimpleStore',
+ data : [
+ ['100%'],
+ ['auto']
+ ],
+ fields : [ 'val'],
+ xns : Roo.data
+ }
+ },
+ // -------- Cols
-
- this.adder = this.outerWrap.createChild(
- {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});
- var _t = this;
- this.adder.on('click', function(e) {
- _t.fireEvent('adderclick', this, e);
- }, _t);
- }
- //var _t = this;
- //this.adder.on('click', this.onAddClick, _t);
-
-
- this.combo.on('select', function(cb, rec, ix) {
- this.addItem(rec.data);
+ {
+ xtype : 'TextItem',
+ text : "Columns: ",
+ xns : rooui.Toolbar //Boostrap?
+ },
+
+ {
+ xtype : 'Button',
+ text: '-',
+ listeners : {
+ click : function (_self, e)
+ {
+ toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ block().removeColumn();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.Toolbar
+ },
+ {
+ xtype : 'Button',
+ text: '+',
+ listeners : {
+ click : function (_self, e)
+ {
+ toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ block().addColumn();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.Toolbar
+ },
+ // -------- ROWS
+ {
+ xtype : 'TextItem',
+ text : "Rows: ",
+ xns : rooui.Toolbar //Boostrap?
+ },
+
+ {
+ xtype : 'Button',
+ text: '-',
+ listeners : {
+ click : function (_self, e)
+ {
+ toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ block().removeRow();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.Toolbar
+ },
+ {
+ xtype : 'Button',
+ text: '+',
+ listeners : {
+ click : function (_self, e)
+ {
+ block().addRow();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.Toolbar
+ },
+ // -------- ROWS
+ {
+ xtype : 'Button',
+ text: 'Reset Column Widths',
+ listeners : {
+
+ click : function (_self, e)
+ {
+ block().resetWidths();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.Toolbar
+ }
- cb.setValue('');
- cb.el.dom.value = '';
- //cb.lastData = rec.data;
- // add to list
- }, this);
-
+
+ ];
},
- getName: function()
+ /**
+ * create a DomHelper friendly object - for use with
+ * Roo.DomHelper.markup / overwrite / etc..
+ * ?? should it be called with option to hide all editing features?
+ */
+ toObject : function()
{
- // returns hidden if it's set..
- if (!this.rendered) {return ''};
- return this.hiddenName ? this.hiddenName : this.name;
-
- },
-
-
- onResize: function(w, h){
- return;
- // not sure if this is needed..
- //this.combo.onResize(w,h);
+ var ret = {
+ tag : 'table',
+ contenteditable : 'false', // this stops cell selection from picking the table.
+ 'data-block' : 'Table',
+ style : {
+ width: this.width,
+ border : 'solid 1px #000', // ??? hard coded?
+ 'border-collapse' : 'collapse'
+ },
+ cn : [
+ { tag : 'tbody' , cn : [] }
+ ]
+ };
- if(typeof w != 'number'){
- // we do not handle it!?!?
- return;
- }
- var tw = this.combo.trigger.getWidth();
- tw += this.addicon ? this.addicon.getWidth() : 0;
- tw += this.editicon ? this.editicon.getWidth() : 0;
- var x = w - tw;
- this.combo.el.setWidth( this.combo.adjustWidth('input', x));
+ // do we have a head = not really
+ var ncols = 0;
+ Roo.each(this.rows, function( row ) {
+ var tr = {
+ tag: 'tr',
+ style : {
+ margin: '6px',
+ border : 'solid 1px #000',
+ textAlign : 'left'
+ },
+ cn : [ ]
+ };
- this.combo.trigger.setStyle('left', '0px');
-
- if(this.list && this.listWidth === undefined){
- var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
- this.list.setWidth(lw);
- this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
- }
-
-
-
- },
-
- addItem: function(rec)
- {
- var valueField = this.combo.valueField;
- var displayField = this.combo.displayField;
-
- if (this.items.indexOfKey(rec[valueField]) > -1) {
- //console.log("GOT " + rec.data.id);
- return;
- }
+ ret.cn[0].cn.push(tr);
+ // does the row have any properties? ?? height?
+ var nc = 0;
+ Roo.each(row, function( cell ) {
+
+ var td = {
+ tag : 'td',
+ contenteditable : 'true',
+ 'data-block' : 'Td',
+ html : cell.html,
+ style : cell.style
+ };
+ if (cell.colspan > 1) {
+ td.colspan = cell.colspan ;
+ nc += cell.colspan;
+ } else {
+ nc++;
+ }
+ if (cell.rowspan > 1) {
+ td.rowspan = cell.rowspan ;
+ }
+
+
+ // widths ?
+ tr.cn.push(td);
+
+
+ }, this);
+ ncols = Math.max(nc, ncols);
+
+
+ }, this);
+ // add the header row..
- var x = new Roo.form.ComboBoxArray.Item({
- //id : rec[this.idField],
- data : rec,
- displayField : displayField ,
- tipField : displayField ,
- cb : this
- });
- // use the
- this.items.add(rec[valueField],x);
- // add it before the element..
- this.updateHiddenEl();
- x.render(this.outerWrap, this.wrap.dom);
- // add the image handler..
- },
-
- updateHiddenEl : function()
- {
- this.validate();
- if (!this.hiddenEl) {
- return;
- }
- var ar = [];
- var idField = this.combo.valueField;
+ ncols++;
+
- this.items.each(function(f) {
- ar.push(f.data[idField]);
- });
- this.hiddenEl.dom.value = ar.join(this.seperator);
- this.validate();
+ return ret;
+
},
- reset : function()
+ readElement : function(node)
{
- this.items.clear();
-
- Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
- el.remove();
- });
+ node = node ? node : this.node ;
+ this.width = this.getVal(node, true, 'style', 'width') || '100%';
+
+ this.rows = [];
+ this.no_row = 0;
+ var trs = Array.from(node.rows);
+ trs.forEach(function(tr) {
+ var row = [];
+ this.rows.push(row);
+
+ this.no_row++;
+ var no_column = 0;
+ Array.from(tr.cells).forEach(function(td) {
+
+ var add = {
+ colspan : td.hasAttribute('colspan') ? td.getAttribute('colspan')*1 : 1,
+ rowspan : td.hasAttribute('rowspan') ? td.getAttribute('rowspan')*1 : 1,
+ style : td.hasAttribute('style') ? td.getAttribute('style') : '',
+ html : td.innerHTML
+ };
+ no_column += add.colspan;
+
+
+ row.push(add);
+
+
+ },this);
+ this.no_col = Math.max(this.no_col, no_column);
+
+
+ },this);
- this.el.dom.value = '';
- if (this.hiddenEl) {
- this.hiddenEl.dom.value = '';
- }
},
- getValue: function()
- {
- return this.hiddenEl ? this.hiddenEl.dom.value : '';
- },
- setValue: function(v) // not a valid action - must use addItems..
+ normalizeRows: function()
{
-
- this.reset();
-
- if (this.store.isLocal && (typeof(v) == 'string')) {
- // then we can use the store to find the values..
- // comma seperated at present.. this needs to allow JSON based encoding..
- this.hiddenEl.value = v;
- var v_ar = [];
- Roo.each(v.split(this.seperator), function(k) {
- Roo.log("CHECK " + this.valueField + ',' + k);
- var li = this.store.query(this.valueField, k);
- if (!li.length) {
+ var ret= [];
+ var rid = -1;
+ this.rows.forEach(function(row) {
+ rid++;
+ ret[rid] = [];
+ row = this.normalizeRow(row);
+ var cid = 0;
+ row.forEach(function(c) {
+ while (typeof(ret[rid][cid]) != 'undefined') {
+ cid++;
+ }
+ if (typeof(ret[rid]) == 'undefined') {
+ ret[rid] = [];
+ }
+ ret[rid][cid] = c;
+ c.row = rid;
+ c.col = cid;
+ if (c.rowspan < 2) {
return;
}
- var add = {};
- add[this.valueField] = k;
- add[this.displayField] = li.item(0).data[this.displayField];
- this.addItem(add);
- }, this)
-
- }
- if (typeof(v) == 'object' ) {
- // then let's assume it's an array of objects..
- Roo.each(v, function(l) {
- var add = l;
- if (typeof(l) == 'string') {
- add = {};
- add[this.valueField] = l;
- add[this.displayField] = l
+ for(var i = 1 ;i < c.rowspan; i++) {
+ if (typeof(ret[rid+i]) == 'undefined') {
+ ret[rid+i] = [];
+ }
+ ret[rid+i][cid] = c;
}
- this.addItem(add);
- }, this);
-
- }
-
-
- },
- setFromData: function(v)
- {
- // this recieves an object, if setValues is called.
- this.reset();
- this.el.dom.value = v[this.displayField];
- this.hiddenEl.dom.value = v[this.valueField];
- if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
- return;
- }
- var kv = v[this.valueField];
- var dv = v[this.displayField];
- kv = typeof(kv) != 'string' ? '' : kv;
- dv = typeof(dv) != 'string' ? '' : dv;
-
-
- var keys = kv.split(this.seperator);
- var display = dv.split(this.seperator);
- for (var i = 0 ; i < keys.length; i++) {
- add = {};
- add[this.valueField] = keys[i];
- add[this.displayField] = display[i];
- this.addItem(add);
- }
-
-
- },
-
- /**
- * Validates the combox array value
- * @return {Boolean} True if the value is valid, else false
- */
- validate : function(){
- if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
- this.clearInvalid();
- return true;
- }
- return false;
- },
+ });
+ }, this);
+ return ret;
- validateValue : function(value){
- return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
-
},
- /*@
- * overide
- *
- */
- isDirty : function() {
- if(this.disabled) {
- return false;
- }
-
- try {
- var d = Roo.decode(String(this.originalValue));
- } catch (e) {
- return String(this.getValue()) !== String(this.originalValue);
+ normalizeRow: function(row)
+ {
+ var ret= [];
+ row.forEach(function(c) {
+ if (c.colspan < 2) {
+ ret.push(c);
+ return;
+ }
+ for(var i =0 ;i < c.colspan; i++) {
+ ret.push(c);
+ }
+ });
+ return ret;
+
+ },
+
+ deleteColumn : function(sel)
+ {
+ if (!sel || sel.type != 'col') {
+ return;
}
-
- var originalValue = [];
-
- for (var i = 0; i < d.length; i++){
- originalValue.push(d[i][this.valueField]);
+ if (this.no_col < 2) {
+ return;
}
- return String(this.getValue()) !== String(originalValue.join(this.seperator));
+ this.rows.forEach(function(row) {
+ var cols = this.normalizeRow(row);
+ var col = cols[sel.col];
+ if (col.colspan > 1) {
+ col.colspan --;
+ } else {
+ row.remove(col);
+ }
+
+ }, this);
+ this.no_col--;
- }
-
-});
-
-
-
-/**
- * @class Roo.form.ComboBoxArray.Item
- * @extends Roo.BoxComponent
- * A selected item in the list
- * Fred [x] Brian [x] [Pick another |v]
- *
- * @constructor
- * Create a new item.
- * @param {Object} config Configuration options
- */
-
-Roo.form.ComboBoxArray.Item = function(config) {
- config.id = Roo.id();
- Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
-}
-
-Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
- data : {},
- cb: false,
- displayField : false,
- tipField : false,
-
+ },
+ removeColumn : function()
+ {
+ this.deleteColumn({
+ type: 'col',
+ col : this.no_col-1
+ });
+ this.updateElement();
+ },
- defaultAutoCreate : {
- tag: 'div',
- cls: 'x-cbarray-item',
- cn : [
- { tag: 'div' },
- {
- tag: 'img',
- width:16,
- height : 16,
- src : Roo.BLANK_IMAGE_URL ,
- align: 'center'
- }
- ]
+
+ addColumn : function()
+ {
+ this.rows.forEach(function(row) {
+ row.push(this.emptyCell());
+
+ }, this);
+ this.updateElement();
},
-
- onRender : function(ct, position)
+ deleteRow : function(sel)
{
- Roo.form.Field.superclass.onRender.call(this, ct, position);
+ if (!sel || sel.type != 'row') {
+ return;
+ }
- if(!this.el){
- var cfg = this.getAutoCreate();
- this.el = ct.createChild(cfg, position);
+ if (this.no_row < 2) {
+ return;
}
- this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
+ var rows = this.normalizeRows();
- this.el.child('div').dom.innerHTML = this.cb.renderer ?
- this.cb.renderer(this.data) :
- String.format('{0}',this.data[this.displayField]);
+ rows[sel.row].forEach(function(col) {
+ if (col.rowspan > 1) {
+ col.rowspan--;
+ } else {
+ col.remove = 1; // flage it as removed.
+ }
- this.el.child('div').dom.setAttribute('qtip',
- String.format('{0}',this.data[this.tipField])
- );
+ }, this);
+ var newrows = [];
+ this.rows.forEach(function(row) {
+ newrow = [];
+ row.forEach(function(c) {
+ if (typeof(c.remove) == 'undefined') {
+ newrow.push(c);
+ }
+
+ });
+ if (newrow.length > 0) {
+ newrows.push(row);
+ }
+ });
+ this.rows = newrows;
+
- this.el.child('img').on('click', this.remove, this);
+
+ this.no_row--;
+ this.updateElement();
},
-
- remove : function()
+ removeRow : function()
{
- if(this.cb.disabled){
- return;
- }
+ this.deleteRow({
+ type: 'row',
+ row : this.no_row-1
+ });
- if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
- this.cb.items.remove(this);
- this.el.child('img').un('click', this.remove, this);
- this.el.remove();
- this.cb.updateHiddenEl();
-
- this.cb.fireEvent('remove', this.cb, this);
+ },
+
+
+ addRow : function()
+ {
+
+ var row = [];
+ for (var i = 0; i < this.no_col; i++ ) {
+
+ row.push(this.emptyCell());
+
}
+ this.rows.push(row);
+ this.updateElement();
+
+ },
+
+ // the default cell object... at present...
+ emptyCell : function() {
+ return (new Roo.htmleditor.BlockTd({})).toObject();
+
+ },
+
+ removeNode : function()
+ {
+ return this.node;
+ },
+
+
+
+ resetWidths : function()
+ {
+ Array.from(this.node.getElementsByTagName('td')).forEach(function(n) {
+ var nn = Roo.htmleditor.Block.factory(n);
+ nn.width = '';
+ nn.updateElement(n);
+ });
}
-});/*
- * RooJS Library 1.1.1
- * Copyright(c) 2008-2011 Alan Knowles
+
+
+
+
+})
+
+/**
+ *
+ * editing a TD?
+ *
+ * since selections really work on the table cell, then editing really should work from there
+ *
+ * The original plan was to support merging etc... - but that may not be needed yet..
+ *
+ * So this simple version will support:
+ * add/remove cols
+ * adjust the width +/-
+ * reset the width...
+ *
*
- * License - LGPL
*/
+
+
/**
- * @class Roo.form.ComboNested
- * @extends Roo.form.ComboBox
- * A combobox for that allows selection of nested items in a list,
- * eg.
- *
- * Book
- * -> red
- * -> green
- * Table
- * -> square
- * ->red
- * ->green
- * -> rectangle
- * ->green
- *
+ * @class Roo.htmleditor.BlockTable
+ * Block that manages a table
*
* @constructor
- * Create a new ComboNested
+ * Create a new Filter.
* @param {Object} config Configuration options
*/
-Roo.form.ComboNested = function(config){
- Roo.form.ComboCheck.superclass.constructor.call(this, config);
- // should verify some data...
- // like
- // hiddenName = required..
- // displayField = required
- // valudField == required
- var req= [ 'hiddenName', 'displayField', 'valueField' ];
- var _t = this;
- Roo.each(req, function(e) {
- if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
- throw "Roo.form.ComboNested : missing value for: " + e;
- }
- });
+
+Roo.htmleditor.BlockTd = function(cfg)
+{
+ if (cfg.node) {
+ this.readElement(cfg.node);
+ this.updateElement(cfg.node);
+ }
+ Roo.apply(this, cfg);
-};
-
-Roo.extend(Roo.form.ComboNested, Roo.form.ComboBox, {
-
- /*
- * @config {Number} max Number of columns to show
- */
- maxColumns : 3,
-
- list : null, // the outermost div..
- innerLists : null, // the
- views : null,
- stores : null,
- // private
- loadingChildren : false,
+}
+Roo.extend(Roo.htmleditor.BlockTd, Roo.htmleditor.Block, {
+
+ node : false,
- onRender : function(ct, position)
+ width: '',
+ textAlign : 'left',
+ valign : 'top',
+
+ colspan : 1,
+ rowspan : 1,
+
+
+ // used by context menu
+ friendly_name : 'Table Cell',
+ deleteTitle : false, // use our customer delete
+
+ // context menu is drawn once..
+
+ contextMenu : function(toolbar)
{
- Roo.form.ComboBox.superclass.onRender.call(this, ct, position); // skip parent call - got to above..
- if(this.hiddenName){
- this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
- 'before', true);
- this.hiddenField.value =
- this.hiddenValue !== undefined ? this.hiddenValue :
- this.value !== undefined ? this.value : '';
-
- // prevent input submission
- this.el.dom.removeAttribute('name');
-
-
- }
-
- if(Roo.isGecko){
- this.el.dom.setAttribute('autocomplete', 'off');
- }
-
- var cls = 'x-combo-list';
-
- this.list = new Roo.Layer({
- shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
- });
-
- var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
- this.list.setWidth(lw);
- this.list.swallowEvent('mousewheel');
- this.assetHeight = 0;
-
- if(this.title){
- this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
- this.assetHeight += this.header.getHeight();
- }
- this.innerLists = [];
- this.views = [];
- this.stores = [];
- for (var i =0 ; i < this.maxColumns; i++) {
- this.onRenderList( cls, i);
- }
+ var cell = function() {
+ return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
+ };
- // always needs footer, as we are going to have an 'OK' button.
- this.footer = this.list.createChild({cls:cls+'-ft'});
- this.pageTb = new Roo.Toolbar(this.footer);
- var _this = this;
- this.pageTb.add( {
-
- text: 'Done',
- handler: function()
- {
- _this.collapse();
- }
- });
+ var table = function() {
+ return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode.closest('table'));
+ };
- if ( this.allowBlank && !this.disableClear) {
-
- this.pageTb.add(new Roo.Toolbar.Fill(), {
- cls: 'x-btn-icon x-btn-clear',
- text: ' ',
- handler: function()
- {
- _this.collapse();
- _this.clearValue();
- _this.onSelect(false, -1);
- }
- });
+ var lr = false;
+ var saveSel = function()
+ {
+ lr = toolbar.editorcore.getSelection().getRangeAt(0);
}
- if (this.footer) {
- this.assetHeight += this.footer.getHeight();
+ var restoreSel = function()
+ {
+ if (lr) {
+ (function() {
+ toolbar.editorcore.focus();
+ var cr = toolbar.editorcore.getSelection();
+ cr.removeAllRanges();
+ cr.addRange(lr);
+ toolbar.editorcore.onEditorEvent();
+ }).defer(10, this);
+
+
+ }
}
- },
- onRenderList : function ( cls, i)
- {
+ var rooui = typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
- var lw = Math.floor(
- ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
- );
+ var syncValue = toolbar.editorcore.syncValue;
- this.list.setWidth(lw); // default to '1'
-
- var il = this.innerLists[i] = this.list.createChild({cls:cls+'-inner'});
- //il.on('mouseover', this.onViewOver, this, { list: i });
- //il.on('mousemove', this.onViewMove, this, { list: i });
- il.setWidth(lw);
- il.setStyle({ 'overflow-x' : 'hidden'});
-
- if(!this.tpl){
- this.tpl = new Roo.Template({
- html : '<div class="'+cls+'-item '+cls+'-item-{cn:this.isEmpty}">{' + this.displayField + '}</div>',
- isEmpty: function (value, allValues) {
- //Roo.log(value);
- var dl = typeof(value.data) != 'undefined' ? value.data.length : value.length; ///json is a nested response..
- return dl ? 'has-children' : 'no-children'
- }
- });
- }
+ var fields = {};
- var store = this.store;
- if (i > 0) {
- store = new Roo.data.SimpleStore({
- //fields : this.store.reader.meta.fields,
- reader : this.store.reader,
- data : [ ]
- });
- }
- this.stores[i] = store;
-
- var view = this.views[i] = new Roo.View(
- il,
- this.tpl,
+ return [
{
- singleSelect:true,
- store: store,
- selectedClass: this.selectedClass
- }
- );
- view.getEl().setWidth(lw);
- view.getEl().setStyle({
- position: i < 1 ? 'relative' : 'absolute',
- top: 0,
- left: (i * lw ) + 'px',
- display : i > 0 ? 'none' : 'block'
- });
- view.on('selectionchange', this.onSelectChange.createDelegate(this, {list : i }, true));
- view.on('dblclick', this.onDoubleClick.createDelegate(this, {list : i }, true));
- //view.on('click', this.onViewClick, this, { list : i });
-
- store.on('beforeload', this.onBeforeLoad, this);
- store.on('load', this.onLoad, this, { list : i});
- store.on('loadexception', this.onLoadException, this);
-
- // hide the other vies..
-
-
-
- },
-
- restrictHeight : function()
- {
- var mh = 0;
- Roo.each(this.innerLists, function(il,i) {
- var el = this.views[i].getEl();
- el.dom.style.height = '';
- var inner = el.dom;
- var h = Math.max(il.clientHeight, il.offsetHeight, il.scrollHeight);
- // only adjust heights on other ones..
- mh = Math.max(h, mh);
- if (i < 1) {
+ xtype : 'Button',
+ text : 'Edit Table',
+ listeners : {
+ click : function() {
+ var t = toolbar.tb.selectedNode.closest('table');
+ toolbar.editorcore.selectNode(t);
+ toolbar.editorcore.onEditorEvent();
+ }
+ }
- el.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
- il.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
+ },
+
+
+
+ {
+ xtype : 'TextItem',
+ text : "Column Width: ",
+ xns : rooui.Toolbar
- }
+ },
+ {
+ xtype : 'Button',
+ text: '-',
+ listeners : {
+ click : function (_self, e)
+ {
+ toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ cell().shrinkColumn();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.Toolbar
+ },
+ {
+ xtype : 'Button',
+ text: '+',
+ listeners : {
+ click : function (_self, e)
+ {
+ toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ cell().growColumn();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.Toolbar
+ },
+ {
+ xtype : 'TextItem',
+ text : "Vertical Align: ",
+ xns : rooui.Toolbar //Boostrap?
+ },
+ {
+ xtype : 'ComboBox',
+ allowBlank : false,
+ displayField : 'val',
+ editable : true,
+ listWidth : 100,
+ triggerAction : 'all',
+ typeAhead : true,
+ valueField : 'val',
+ width : 100,
+ name : 'valign',
+ listeners : {
+ select : function (combo, r, index)
+ {
+ toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ var b = cell();
+ b.valign = r.get('val');
+ b.updateElement();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.form,
+ store : {
+ xtype : 'SimpleStore',
+ data : [
+ ['top'],
+ ['middle'],
+ ['bottom'] // there are afew more...
+ ],
+ fields : [ 'val'],
+ xns : Roo.data
+ }
+ },
- }, this);
-
- this.list.beginUpdate();
- this.list.setHeight(mh+this.list.getFrameWidth('tb')+this.assetHeight);
- this.list.alignTo(this.el, this.listAlign);
- this.list.endUpdate();
-
- },
-
-
- // -- store handlers..
- // private
- onBeforeLoad : function()
- {
- if(!this.hasFocus){
- return;
- }
- this.innerLists[0].update(this.loadingText ?
- '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
- this.restrictHeight();
- this.selectedIndex = -1;
- },
- // private
- onLoad : function(a,b,c,d)
- {
- if (!this.loadingChildren) {
- // then we are loading the top level. - hide the children
- for (var i = 1;i < this.views.length; i++) {
- this.views[i].getEl().setStyle({ display : 'none' });
- }
- var lw = Math.floor(
- ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
- );
-
- this.list.setWidth(lw); // default to '1'
-
+ {
+ xtype : 'TextItem',
+ text : "Merge Cells: ",
+ xns : rooui.Toolbar
+
+ },
- }
- if(!this.hasFocus){
- return;
- }
-
- if(this.store.getCount() > 0) {
- this.expand();
- this.restrictHeight();
- } else {
- this.onEmptyResults();
- }
-
- if (!this.loadingChildren) {
- this.selectActive();
- }
- /*
- this.stores[1].loadData([]);
- this.stores[2].loadData([]);
- this.views
- */
-
- //this.el.focus();
- },
-
-
- // private
- onLoadException : function()
- {
- this.collapse();
- Roo.log(this.store.reader.jsonData);
- if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
- Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
- }
-
+
+ {
+ xtype : 'Button',
+ text: 'Right',
+ listeners : {
+ click : function (_self, e)
+ {
+ toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ cell().mergeRight();
+ //block().growColumn();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.Toolbar
+ },
+
+ {
+ xtype : 'Button',
+ text: 'Below',
+ listeners : {
+ click : function (_self, e)
+ {
+ toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ cell().mergeBelow();
+ //block().growColumn();
+ syncValue();
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.Toolbar
+ },
+ {
+ xtype : 'TextItem',
+ text : "| ",
+ xns : rooui.Toolbar
+
+ },
+
+ {
+ xtype : 'Button',
+ text: 'Split',
+ listeners : {
+ click : function (_self, e)
+ {
+ //toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ cell().split();
+ syncValue();
+ toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
+ toolbar.editorcore.onEditorEvent();
+
+ }
+ },
+ xns : rooui.Toolbar
+ },
+ {
+ xtype : 'Fill',
+ xns : rooui.Toolbar
+
+ },
- },
- // no cleaning of leading spaces on blur here.
- cleanLeadingSpace : function(e) { },
-
-
- onSelectChange : function (view, sels, opts )
- {
- var ix = view.getSelectedIndexes();
-
- if (opts.list > this.maxColumns - 2) {
- if (view.store.getCount()< 1) {
- this.views[opts.list ].getEl().setStyle({ display : 'none' });
-
- } else {
- if (ix.length) {
- // used to clear ?? but if we are loading unselected
- this.setFromData(view.store.getAt(ix[0]).data);
+
+ {
+ xtype : 'Button',
+ text: 'Delete',
+
+ xns : rooui.Toolbar,
+ menu : {
+ xtype : 'Menu',
+ xns : rooui.menu,
+ items : [
+ {
+ xtype : 'Item',
+ html: 'Column',
+ listeners : {
+ click : function (_self, e)
+ {
+ var t = table();
+
+ cell().deleteColumn();
+ syncValue();
+ toolbar.editorcore.selectNode(t.node);
+ toolbar.editorcore.onEditorEvent();
+ }
+ },
+ xns : rooui.menu
+ },
+ {
+ xtype : 'Item',
+ html: 'Row',
+ listeners : {
+ click : function (_self, e)
+ {
+ var t = table();
+ cell().deleteRow();
+ syncValue();
+
+ toolbar.editorcore.selectNode(t.node);
+ toolbar.editorcore.onEditorEvent();
+
+ }
+ },
+ xns : rooui.menu
+ },
+ {
+ xtype : 'Separator',
+ xns : rooui.menu
+ },
+ {
+ xtype : 'Item',
+ html: 'Table',
+ listeners : {
+ click : function (_self, e)
+ {
+ var t = table();
+ var nn = t.node.nextSibling || t.node.previousSibling;
+ t.node.parentNode.removeChild(t.node);
+ if (nn) {
+ toolbar.editorcore.selectNode(nn, true);
+ }
+ toolbar.editorcore.onEditorEvent();
+
+ }
+ },
+ xns : rooui.menu
+ }
+ ]
}
-
}
- return;
- }
+ // align... << fixme
+
+ ];
- if (!ix.length) {
- // this get's fired when trigger opens..
- // this.setFromData({});
- var str = this.stores[opts.list+1];
- str.data.clear(); // removeall wihtout the fire events..
- return;
+ },
+
+
+ /**
+ * create a DomHelper friendly object - for use with
+ * Roo.DomHelper.markup / overwrite / etc..
+ * ?? should it be called with option to hide all editing features?
+ */
+ /**
+ * create a DomHelper friendly object - for use with
+ * Roo.DomHelper.markup / overwrite / etc..
+ * ?? should it be called with option to hide all editing features?
+ */
+ toObject : function()
+ {
+ var ret = {
+ tag : 'td',
+ contenteditable : 'true', // this stops cell selection from picking the table.
+ 'data-block' : 'Td',
+ valign : this.valign,
+ style : {
+ 'text-align' : this.textAlign,
+ border : 'solid 1px rgb(0, 0, 0)', // ??? hard coded?
+ 'border-collapse' : 'collapse',
+ padding : '6px', // 8 for desktop / 4 for mobile
+ 'vertical-align': this.valign
+ },
+ html : this.html
+ };
+ if (this.width != '') {
+ ret.width = this.width;
+ ret.style.width = this.width;
}
- var rec = view.store.getAt(ix[0]);
-
- this.setFromData(rec.data);
- this.fireEvent('select', this, rec, ix[0]);
-
- var lw = Math.floor(
- (
- (this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')
- ) / this.maxColumns
- );
- this.loadingChildren = true;
- this.stores[opts.list+1].loadDataFromChildren( rec );
- this.loadingChildren = false;
- var dl = this.stores[opts.list+1]. getTotalCount();
-
- this.views[opts.list+1].getEl().setHeight( this.innerLists[0].getHeight());
- this.views[opts.list+1].getEl().setStyle({ display : dl ? 'block' : 'none' });
- for (var i = opts.list+2; i < this.views.length;i++) {
- this.views[i].getEl().setStyle({ display : 'none' });
+ if (this.colspan > 1) {
+ ret.colspan = this.colspan ;
+ }
+ if (this.rowspan > 1) {
+ ret.rowspan = this.rowspan ;
}
- this.innerLists[opts.list+1].setHeight( this.innerLists[0].getHeight());
- this.list.setWidth(lw * (opts.list + (dl ? 2 : 1)));
+
- if (this.isLoading) {
- // this.selectActive(opts.list);
- }
+ return ret;
},
-
-
-
- onDoubleClick : function()
+ readElement : function(node)
{
- this.collapse(); //??
+ node = node ? node : this.node ;
+ this.width = node.style.width;
+ this.colspan = Math.max(1,1*node.getAttribute('colspan'));
+ this.rowspan = Math.max(1,1*node.getAttribute('rowspan'));
+ this.html = node.innerHTML;
+ if (node.style.textAlign != '') {
+ this.textAlign = node.style.textAlign;
+ }
+
+
},
-
+ // the default cell object... at present...
+ emptyCell : function() {
+ return {
+ colspan : 1,
+ rowspan : 1,
+ textAlign : 'left',
+ html : " " // is this going to be editable now?
+ };
+
+ },
+ removeNode : function()
+ {
+ return this.node.closest('table');
+
+ },
+ cellData : false,
- // private
- recordToStack : function(store, prop, value, stack)
+ colWidths : false,
+
+ toTableArray : function()
{
- var cstore = new Roo.data.SimpleStore({
- //fields : this.store.reader.meta.fields, // we need array reader.. for
- reader : this.store.reader,
- data : [ ]
+ var ret = [];
+ var tab = this.node.closest('tr').closest('table');
+ Array.from(tab.rows).forEach(function(r, ri){
+ ret[ri] = [];
});
- var _this = this;
- var record = false;
- var srec = false;
- if(store.getCount() < 1){
- return false;
- }
- store.each(function(r){
- if(r.data[prop] == value){
- record = r;
- srec = r;
- return false;
- }
- if (r.data.cn && r.data.cn.length) {
- cstore.loadDataFromChildren( r);
- var cret = _this.recordToStack(cstore, prop, value, stack);
- if (cret !== false) {
- record = cret;
- srec = r;
- return false;
+ var rn = 0;
+ this.colWidths = [];
+ var all_auto = true;
+ Array.from(tab.rows).forEach(function(r, ri){
+
+ var cn = 0;
+ Array.from(r.cells).forEach(function(ce, ci){
+ var c = {
+ cell : ce,
+ row : rn,
+ col: cn,
+ colspan : ce.colSpan,
+ rowspan : ce.rowSpan
+ };
+ if (ce.isEqualNode(this.node)) {
+ this.cellData = c;
}
- }
-
- return true;
- });
- if (record == false) {
- return false
+ // if we have been filled up by a row?
+ if (typeof(ret[rn][cn]) != 'undefined') {
+ while(typeof(ret[rn][cn]) != 'undefined') {
+ cn++;
+ }
+ c.col = cn;
+ }
+
+ if (typeof(this.colWidths[cn]) == 'undefined' && c.colspan < 2) {
+ this.colWidths[cn] = ce.style.width;
+ if (this.colWidths[cn] != '') {
+ all_auto = false;
+ }
+ }
+
+
+ if (c.colspan < 2 && c.rowspan < 2 ) {
+ ret[rn][cn] = c;
+ cn++;
+ return;
+ }
+ for(var j = 0; j < c.rowspan; j++) {
+ if (typeof(ret[rn+j]) == 'undefined') {
+ continue; // we have a problem..
+ }
+ ret[rn+j][cn] = c;
+ for(var i = 0; i < c.colspan; i++) {
+ ret[rn+j][cn+i] = c;
+ }
+ }
+
+ cn += c.colspan;
+ }, this);
+ rn++;
+ }, this);
+
+ // initalize widths.?
+ // either all widths or no widths..
+ if (all_auto) {
+ this.colWidths[0] = false; // no widths flag.
}
- stack.unshift(srec);
- return record;
+
+
+ return ret;
+
},
- /*
- * find the stack of stores that match our value.
- *
- *
- */
-
- selectActive : function ()
- {
- // if store is not loaded, then we will need to wait for that to happen first.
- var stack = [];
- this.recordToStack(this.store, this.valueField, this.getValue(), stack);
- for (var i = 0; i < stack.length; i++ ) {
- this.views[i].select(stack[i].store.indexOf(stack[i]), false, false );
- }
-
- }
-
-
-
-
-
-
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-/**
- * @class Roo.form.Checkbox
- * @extends Roo.form.Field
- * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
- * @constructor
- * Creates a new Checkbox
- * @param {Object} config Configuration options
- */
-Roo.form.Checkbox = function(config){
- Roo.form.Checkbox.superclass.constructor.call(this, config);
- this.addEvents({
- /**
- * @event check
- * Fires when the checkbox is checked or unchecked.
- * @param {Roo.form.Checkbox} this This checkbox
- * @param {Boolean} checked The new checked value
- */
- check : true
- });
-};
-
-Roo.extend(Roo.form.Checkbox, Roo.form.Field, {
- /**
- * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
- */
- focusClass : undefined,
- /**
- * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
- */
- fieldClass: "x-form-field",
- /**
- * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
- */
- checked: false,
- /**
- * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
- * {tag: "input", type: "checkbox", autocomplete: "off"})
- */
- defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
- /**
- * @cfg {String} boxLabel The text that appears beside the checkbox
- */
- boxLabel : "",
- /**
- * @cfg {String} inputValue The value that should go into the generated input element's value attribute
- */
- inputValue : '1',
- /**
- * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
- */
- valueOff: '0', // value when not checked..
-
- actionMode : 'viewEl',
- //
- // private
- itemCls : 'x-menu-check-item x-form-item',
- groupClass : 'x-menu-group-item',
- inputType : 'hidden',
-
- inSetChecked: false, // check that we are not calling self...
- inputElement: false, // real input element?
- basedOn: false, // ????
- isFormField: true, // not sure where this is needed!!!!
-
- onResize : function(){
- Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
- if(!this.boxLabel){
- this.el.alignTo(this.wrap, 'c-c');
- }
- },
-
- initEvents : function(){
- Roo.form.Checkbox.superclass.initEvents.call(this);
- this.el.on("click", this.onClick, this);
- this.el.on("change", this.onClick, this);
- },
-
-
- getResizeEl : function(){
- return this.wrap;
- },
-
- getPositionEl : function(){
- return this.wrap;
- },
-
- // private
- onRender : function(ct, position){
- Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
- /*
- if(this.inputValue !== undefined){
- this.el.dom.value = this.inputValue;
+ mergeRight: function()
+ {
+
+ // get the contents of the next cell along..
+ var tr = this.node.closest('tr');
+ var i = Array.prototype.indexOf.call(tr.childNodes, this.node);
+ if (i >= tr.childNodes.length - 1) {
+ return; // no cells on right to merge with.
}
- */
- //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
- this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
- var viewEl = this.wrap.createChild({
- tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
- this.viewEl = viewEl;
- this.wrap.on('click', this.onClick, this);
+ var table = this.toTableArray();
- this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
- this.el.on('propertychange', this.setFromHidden, this); //ie
+ if (typeof(table[this.cellData.row][this.cellData.col+this.cellData.colspan]) == 'undefined') {
+ return; // nothing right?
+ }
+ var rc = table[this.cellData.row][this.cellData.col+this.cellData.colspan];
+ // right cell - must be same rowspan and on the same row.
+ if (rc.rowspan != this.cellData.rowspan || rc.row != this.cellData.row) {
+ return; // right hand side is not same rowspan.
+ }
- if(this.boxLabel){
- this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
- // viewEl.on('click', this.onClick, this);
- }
- //if(this.checked){
- this.setChecked(this.checked);
- //}else{
- //this.checked = this.el.dom;
- //}
+ this.node.innerHTML += ' ' + rc.cell.innerHTML;
+ tr.removeChild(rc.cell);
+ this.colspan += rc.colspan;
+ this.node.setAttribute('colspan', this.colspan);
+ var table = this.toTableArray();
+ this.normalizeWidths(table);
+ this.updateWidths(table);
},
-
- // private
- initValue : Roo.emptyFn,
-
- /**
- * Returns the checked state of the checkbox.
- * @return {Boolean} True if checked, else false
- */
- getValue : function(){
- if(this.el){
- return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
+
+
+ mergeBelow : function()
+ {
+ var table = this.toTableArray();
+ if (typeof(table[this.cellData.row+this.cellData.rowspan]) == 'undefined') {
+ return; // no row below
}
- return this.valueOff;
+ if (typeof(table[this.cellData.row+this.cellData.rowspan][this.cellData.col]) == 'undefined') {
+ return; // nothing right?
+ }
+ var rc = table[this.cellData.row+this.cellData.rowspan][this.cellData.col];
+ if (rc.colspan != this.cellData.colspan || rc.col != this.cellData.col) {
+ return; // right hand side is not same rowspan.
+ }
+ this.node.innerHTML = this.node.innerHTML + rc.cell.innerHTML ;
+ rc.cell.parentNode.removeChild(rc.cell);
+ this.rowspan += rc.rowspan;
+ this.node.setAttribute('rowspan', this.rowspan);
},
-
- // private
- onClick : function(){
- if (this.disabled) {
+
+ split: function()
+ {
+ if (this.node.rowSpan < 2 && this.node.colSpan < 2) {
return;
}
- this.setChecked(!this.checked);
-
- //if(this.el.dom.checked != this.checked){
- // this.setValue(this.el.dom.checked);
- // }
+ var table = this.toTableArray();
+ var cd = this.cellData;
+ this.rowspan = 1;
+ this.colspan = 1;
+
+ for(var r = cd.row; r < cd.row + cd.rowspan; r++) {
+
+
+ for(var c = cd.col; c < cd.col + cd.colspan; c++) {
+ if (r == cd.row && c == cd.col) {
+ this.node.removeAttribute('rowspan');
+ this.node.removeAttribute('colspan');
+ }
+
+ var ntd = this.node.cloneNode(); // which col/row should be 0..
+ ntd.removeAttribute('id');
+ ntd.style.width = this.colWidths[c];
+ ntd.innerHTML = '';
+ table[r][c] = { cell : ntd, col : c, row: r , colspan : 1 , rowspan : 1 };
+ }
+
+ }
+ this.redrawAllCells(table);
+
},
-
- /**
- * Sets the checked state of the checkbox.
- * On is always based on a string comparison between inputValue and the param.
- * @param {Boolean/String} value - the value to set
- * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
- */
- setValue : function(v,suppressEvent){
+
+
+
+ redrawAllCells: function(table)
+ {
+
+ var tab = this.node.closest('tr').closest('table');
+ var ctr = tab.rows[0].parentNode;
+ Array.from(tab.rows).forEach(function(r, ri){
+
+ Array.from(r.cells).forEach(function(ce, ci){
+ ce.parentNode.removeChild(ce);
+ });
+ r.parentNode.removeChild(r);
+ });
+ for(var r = 0 ; r < table.length; r++) {
+ var re = tab.rows[r];
+
+ var re = tab.ownerDocument.createElement('tr');
+ ctr.appendChild(re);
+ for(var c = 0 ; c < table[r].length; c++) {
+ if (table[r][c].cell === false) {
+ continue;
+ }
+
+ re.appendChild(table[r][c].cell);
+
+ table[r][c].cell = false;
+ }
+ }
- //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
- //if(this.el && this.el.dom){
- // this.el.dom.checked = this.checked;
- // this.el.dom.defaultChecked = this.checked;
- //}
- this.setChecked(String(v) === String(this.inputValue), suppressEvent);
- //this.fireEvent("check", this, this.checked);
},
- // private..
- setChecked : function(state,suppressEvent)
+ updateWidths : function(table)
{
- if (this.inSetChecked) {
- this.checked = state;
+ for(var r = 0 ; r < table.length; r++) {
+
+ for(var c = 0 ; c < table[r].length; c++) {
+ if (table[r][c].cell === false) {
+ continue;
+ }
+
+ if (this.colWidths[0] != false && table[r][c].colspan < 2) {
+ var el = Roo.htmleditor.Block.factory(table[r][c].cell);
+ el.width = Math.floor(this.colWidths[c]) +'%';
+ el.updateElement(el.node);
+ }
+ if (this.colWidths[0] != false && table[r][c].colspan > 1) {
+ var el = Roo.htmleditor.Block.factory(table[r][c].cell);
+ var width = 0;
+ var lv = false;
+ for(var i = 0; i < table[r][c].colspan; i ++) {
+ if (typeof(this.colWidths[c + i]) != 'undefined') {
+ lv = this.colWidths[c + i];
+ } else {
+ this.colWidths[c + i] = lv;
+ }
+ width += Math.floor(this.colWidths[c + i]);
+ }
+ el.width = width +'%';
+ el.updateElement(el.node);
+ }
+ table[r][c].cell = false; // done
+ }
+ }
+ },
+ normalizeWidths : function(table)
+ {
+ if (this.colWidths[0] === false) {
+ var nw = 100.0 / this.colWidths.length;
+ this.colWidths.forEach(function(w,i) {
+ this.colWidths[i] = nw;
+ },this);
return;
}
-
- if(this.wrap){
- this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
- }
- this.checked = state;
- if(suppressEvent !== true){
- this.fireEvent('check', this, state);
+ var t = 0, missing = [];
+
+ this.colWidths.forEach(function(w,i) {
+ //if you mix % and
+ this.colWidths[i] = this.colWidths[i] == '' ? 0 : (this.colWidths[i]+'').replace(/[^0-9]+/g,'')*1;
+ var add = this.colWidths[i];
+ if (add > 0) {
+ t+=add;
+ return;
+ }
+ missing.push(i);
+
+
+ },this);
+ var nc = this.colWidths.length;
+ if (missing.length) {
+ var mult = (nc - missing.length) / (1.0 * nc);
+ var t = mult * t;
+ var ew = (100 -t) / (1.0 * missing.length);
+ this.colWidths.forEach(function(w,i) {
+ if (w > 0) {
+ this.colWidths[i] = w * mult;
+ return;
+ }
+
+ this.colWidths[i] = ew;
+ }, this);
+ // have to make up numbers..
+
}
- this.inSetChecked = true;
- this.el.dom.value = state ? this.inputValue : this.valueOff;
- this.inSetChecked = false;
+ // now we should have all the widths..
+
},
- // handle setting of hidden value by some other method!!?!?
- setFromHidden: function()
+
+ shrinkColumn : function()
{
- if(!this.el){
+ var table = this.toTableArray();
+ this.normalizeWidths(table);
+ var col = this.cellData.col;
+ var nw = this.colWidths[col] * 0.8;
+ if (nw < 5) {
return;
}
- //console.log("SET FROM HIDDEN");
- //alert('setFrom hidden');
- this.setValue(this.el.dom.value);
+ var otherAdd = (this.colWidths[col] * 0.2) / (this.colWidths.length -1);
+ this.colWidths.forEach(function(w,i) {
+ if (i == col) {
+ this.colWidths[i] = nw;
+ return;
+ }
+ if (typeof(this.colWidths[i]) == 'undefined') {
+ this.colWidths[i] = otherAdd;
+ } else {
+ this.colWidths[i] += otherAdd;
+ }
+ }, this);
+ this.updateWidths(table);
+
},
-
- onDestroy : function()
+ growColumn : function()
{
- if(this.viewEl){
- Roo.get(this.viewEl).remove();
+ var table = this.toTableArray();
+ this.normalizeWidths(table);
+ var col = this.cellData.col;
+ var nw = this.colWidths[col] * 1.2;
+ if (nw > 90) {
+ return;
}
+ var otherSub = (this.colWidths[col] * 0.2) / (this.colWidths.length -1);
+ this.colWidths.forEach(function(w,i) {
+ if (i == col) {
+ this.colWidths[i] = nw;
+ return;
+ }
+ if (typeof(this.colWidths[i]) == 'undefined') {
+ this.colWidths[i] = otherSub;
+ } else {
+ this.colWidths[i] -= otherSub;
+ }
+
+ }, this);
+ this.updateWidths(table);
- Roo.form.Checkbox.superclass.onDestroy.call(this);
},
-
- setBoxLabel : function(str)
+ deleteRow : function()
{
- this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
- }
-
-});/*
- * Based on:
- * Ext JS Library 1.1.1
- * Copyright(c) 2006-2007, Ext JS, LLC.
- *
- * Originally Released Under LGPL - original licence link has changed is not relivant.
- *
- * Fork - LGPL
- * <script type="text/javascript">
- */
-
-/**
- * @class Roo.form.Radio
- * @extends Roo.form.Checkbox
- * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
- * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
- * @constructor
- * Creates a new Radio
- * @param {Object} config Configuration options
- */
-Roo.form.Radio = function(){
- Roo.form.Radio.superclass.constructor.apply(this, arguments);
-};
-Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
- inputType: 'radio',
-
- /**
- * If this radio is part of a group, it will return the selected value
- * @return {String}
- */
- getGroupValue : function(){
- return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
- },
-
-
- onRender : function(ct, position){
- Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
-
- if(this.inputValue !== undefined){
- this.el.dom.value = this.inputValue;
+ // delete this rows 'tr'
+ // if any of the cells in this row have a rowspan > 1 && row!= this row..
+ // then reduce the rowspan.
+ var table = this.toTableArray();
+ // this.cellData.row;
+ for (var i =0;i< table[this.cellData.row].length ; i++) {
+ var c = table[this.cellData.row][i];
+ if (c.row != this.cellData.row) {
+
+ c.rowspan--;
+ c.cell.setAttribute('rowspan', c.rowspan);
+ continue;
+ }
+ if (c.rowspan > 1) {
+ c.rowspan--;
+ c.cell.setAttribute('rowspan', c.rowspan);
+ }
}
-
- this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
- //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
- //var viewEl = this.wrap.createChild({
- // tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
- //this.viewEl = viewEl;
- //this.wrap.on('click', this.onClick, this);
-
- //this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
- //this.el.on('propertychange', this.setFromHidden, this); //ie
-
+ table.splice(this.cellData.row,1);
+ this.redrawAllCells(table);
+ },
+ deleteColumn : function()
+ {
+ var table = this.toTableArray();
- if(this.boxLabel){
- this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
- // viewEl.on('click', this.onClick, this);
- }
- if(this.checked){
- this.el.dom.checked = 'checked' ;
+ for (var i =0;i< table.length ; i++) {
+ var c = table[i][this.cellData.col];
+ if (c.col != this.cellData.col) {
+ table[i][this.cellData.col].colspan--;
+ } else if (c.colspan > 1) {
+ c.colspan--;
+ c.cell.setAttribute('colspan', c.colspan);
+ }
+ table[i].splice(this.cellData.col,1);
}
-
- }
+
+ this.redrawAllCells(table);
+ }
+
-});//<script type="text/javascript">
+
+})
+
+//<script type="text/javascript">
/*
* Based Ext JS Library 1.1.1
* @param {Roo.HtmlEditorCore} this
*/
editorevent: true
-
+
});
owner : false,
/**
- * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
- * Roo.resizable.
+ * @cfg {String} css styling for resizing. (used on bootstrap only)
*/
- resizable : false,
+ resize : false,
/**
* @cfg {Number} height (in pixels)
*/
this.frameId = Roo.id();
-
-
- var iframe = this.owner.wrap.createChild({
+ var ifcfg = {
tag: 'iframe',
cls: 'form-control', // bootstrap..
id: this.frameId,
name: this.frameId,
frameBorder : 'no',
'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL : "javascript:false"
- }, this.el
- );
+ };
+ if (this.resize) {
+ ifcfg.style = { resize : this.resize };
+ }
+
+ var iframe = this.owner.wrap.createChild(ifcfg, this.el);
this.iframe = iframe.dom;
//Roo.log("HtmlEditorCore:syncValue (EDITOR->TEXT)");
if(this.initialized){
- this.undoManager.addEvent();
+ if (this.undoManager) {
+ this.undoManager.addEvent();
+ }
var bd = (this.doc.body || this.doc.documentElement);
if (this.enableBlocks) {
new Roo.htmleditor.FilterBlock({ node : div });
}
+
+ var html = div.innerHTML;
+
//?? tidy?
- var tidy = new Roo.htmleditor.TidySerializer({
- inner: true
- });
- var html = tidy.serialize(div);
+ if (this.autoClean) {
+
+ new Roo.htmleditor.FilterAttributes({
+ node : div,
+ attrib_white : [
+ 'href',
+ 'src',
+ 'name',
+ 'align',
+ 'colspan',
+ 'rowspan',
+ 'data-display',
+ 'data-caption-display',
+ 'data-width',
+ 'data-caption',
+ 'start' ,
+ 'style',
+ // youtube embed.
+ 'class',
+ 'allowfullscreen',
+ 'frameborder',
+ 'width',
+ 'height',
+ 'alt'
+ ],
+ attrib_clean : ['href', 'src' ]
+ });
+
+ var tidy = new Roo.htmleditor.TidySerializer({
+ inner: true
+ });
+ html = tidy.serialize(div);
+
+ }
if(Roo.isSafari){
var cd = (e.browserEvent.clipboardData || window.clipboardData);
// check what type of paste - if it's an image, then handle it differently.
- if (cd.files.length > 0) {
- // pasting images?
+ if (cd.files && cd.files.length > 0 && cd.types.indexOf('text/html') < 0) {
+ // pasting images?
var urlAPI = (window.createObjectURL && window) ||
(window.URL && URL.revokeObjectURL && URL) ||
(window.webkitURL && webkitURL);
-
- var url = urlAPI.createObjectURL( cd.files[0]);
- this.insertAtCursor('<img src=" + url + ">');
+
+ var r = new FileReader();
+ var t = this;
+ r.addEventListener('load',function()
+ {
+
+ var d = (new DOMParser().parseFromString('<img src="' + r.result+ '">', 'text/html')).body;
+ // is insert asycn?
+ if (t.enableBlocks) {
+
+ Array.from(d.getElementsByTagName('img')).forEach(function(img) {
+ if (img.closest('figure')) { // assume!! that it's aready
+ return;
+ }
+ var fig = new Roo.htmleditor.BlockFigure({
+ image_src : img.src
+ });
+ fig.updateElement(img); // replace it..
+
+ });
+ }
+ t.insertAtCursor(d.innerHTML.replace(/ /g,' '));
+ t.owner.fireEvent('paste', this);
+ });
+ r.readAsDataURL(cd.files[0]);
+
+ e.preventDefault();
+
return false;
}
-
+ if (cd.types.indexOf('text/html') < 0 ) {
+ return false;
+ }
+ var images = [];
var html = cd.getData('text/html'); // clipboard event
- var parser = new Roo.rtf.Parser(cd.getData('text/rtf'));
- var images = parser.doc ? parser.doc.getElementsByType('pict') : [];
- Roo.log(images);
- //Roo.log(imgs);
+ if (cd.types.indexOf('text/rtf') > -1) {
+ var parser = new Roo.rtf.Parser(cd.getData('text/rtf'));
+ images = parser.doc ? parser.doc.getElementsByType('pict') : [];
+ }
+ // Roo.log(images);
+ // Roo.log(imgs);
// fixme..
- images = images.filter(function(g) { return !g.path.match(/^rtf\/(head|pgdsctbl|listtable)/); }) // ignore headers
+ images = images.filter(function(g) { return !g.path.match(/^rtf\/(head|pgdsctbl|listtable|footerf)/); }) // ignore headers/footers etc.
.map(function(g) { return g.toDataURL(); })
.filter(function(g) { return g != 'about:blank'; });
-
+ //Roo.log(html);
html = this.cleanWordChars(html);
var d = (new DOMParser().parseFromString(html, 'text/html')).body;
return false;
}
+
+
if (images.length > 0) {
+ // replace all v:imagedata - with img.
+ var ar = Array.from(d.getElementsByTagName('v:imagedata'));
+ Roo.each(ar, function(node) {
+ node.parentNode.insertBefore(d.ownerDocument.createElement('img'), node );
+ node.parentNode.removeChild(node);
+ });
+
+
Roo.each(d.getElementsByTagName('img'), function(img, i) {
img.setAttribute('src', images[i]);
});
}
if (this.autoClean) {
+ new Roo.htmleditor.FilterWord({ node : d });
+
new Roo.htmleditor.FilterStyleToTag({ node : d });
new Roo.htmleditor.FilterAttributes({
node : d,
- attrib_white : ['href', 'src', 'name', 'align'],
+ attrib_white : [
+ 'href',
+ 'src',
+ 'name',
+ 'align',
+ 'colspan',
+ 'rowspan'
+ /* THESE ARE NOT ALLWOED FOR PASTE
+ * 'data-display',
+ 'data-caption-display',
+ 'data-width',
+ 'data-caption',
+ 'start' ,
+ 'style',
+ // youtube embed.
+ 'class',
+ 'allowfullscreen',
+ 'frameborder',
+ 'width',
+ 'height',
+ 'alt'
+ */
+ ],
attrib_clean : ['href', 'src' ]
});
new Roo.htmleditor.FilterBlack({ node : d, tag : this.black});
// should be fonts..
- new Roo.htmleditor.FilterKeepChildren({node : d, tag : [ 'FONT', 'O:P' ]} );
+ new Roo.htmleditor.FilterKeepChildren({node : d, tag : [ 'FONT', ':' ]} );
new Roo.htmleditor.FilterParagraph({ node : d });
+ new Roo.htmleditor.FilterHashLink({node : d});
new Roo.htmleditor.FilterSpan({ node : d });
new Roo.htmleditor.FilterLongBr({ node : d });
+ new Roo.htmleditor.FilterComment({ node : d });
+
+
}
if (this.enableBlocks) {
if (this.enableBlocks) {
Roo.htmleditor.Block.initAll(this.doc.body);
}
-
+
e.preventDefault();
+ this.owner.fireEvent('paste', this);
return false;
// default behaveiour should be our local cleanup paste? (optional?)
// for simple editor - we want to hammer the paste and get rid of everything... - so over-rideable..
if (e && (e.ctrlKey || e.metaKey) && e.keyCode === 90) {
return; // we do not handle this.. (undo manager does..)
}
+ // clicking a 'block'?
+
// in theory this detects if the last element is not a br, then we try and do that.
// its so clicking in space at bottom triggers adding a br and moving the cursor.
if (e &&
break;
case 'bold':
case 'italic':
+ case 'underline':
// if there is no selection, then we insert, and set the curson inside it..
this.execCmd('styleWithCSS', false);
break;
cleanWord : function(node)
{
new Roo.htmleditor.FilterWord({ node : node ? node : this.doc.body });
+ new Roo.htmleditor.FilterKeepChildren({node : node ? node : this.doc.body, tag : [ 'FONT', ':' ]} );
},
* @param {Roo.HtmlEditorCore} this
*/
paste: true
+
});
this.defaultAutoCreate = {
tag: "textarea",
disableMask : false,
/**
- * @cfg {Boolean} errorMask (true|false) default false
+ * @cfg {Boolean} errorMask Should the form be masked (and the active element highlighted on error - default false
*/
errorMask : false,
/**
- * @cfg {Number} maskOffset Default 100
+ * @cfg {Number} maskOffset space around form element to mask if there is an error Default 100
*/
maskOffset : 100,
for(id in values){
if(typeof values[id] != 'function' && (field = this.findField(id))){
+
+
+
if (field.setFromData &&
field.valueField &&
field.displayField &&
sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
field.setFromData(sd);
+ } else if (field.inputType && field.inputType == 'radio') {
+
+ field.setValue(values[id]);
} else {
field.setValue(values[id]);
}
/**
* Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
* they are returned as an array.
- * @param {Boolean} asString
+ * @param {Boolean} asString (def)
* @return {Object}
*/
getValues : function(asString)
* @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
*/
/**
- * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
+ * @cfg {String} buttonAlign (left|center|right) Valid values are "left," "center" and "right" (defaults to "center")
*/
buttonAlign:'center',
minButtonWidth:75,
/**
- * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
+ * @cfg {String} labelAlign (left|top|right) Valid values are "left," "top" and "right" (defaults to "left").
* This property cascades to child containers if not set.
*/
labelAlign:'left',
}
var ret = false;
try {
- ret = Roo.decode(response.responseText);
+ var rt = response.responseText;
+ if (rt.match(/^\<!--\[CDATA\[/)) {
+ rt = rt.replace(/^\<!--\[CDATA\[/,'');
+ rt = rt.replace(/\]\]--\>$/,'');
+ }
+
+ ret = Roo.decode(rt);
} catch (e) {
ret = {
success: false,
* a function which returns such a specification.
*/
/**
- * @cfg {String} labelAlign
+ * @cfg {String} labelAlign (left|top|right)
* Valid values are "left," "top" and "right" (defaults to "left")
*/
/**
}
});
+
/**
* @class Roo.form.Column
* @extends Roo.form.Layout
}
});
-
/**
* @class Roo.form.Row
* @extends Roo.form.Layout
// closure these in so they are only created once.
var alpha = /^[a-zA-Z_]+$/;
var alphanum = /^[a-zA-Z0-9_]+$/;
- var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
- var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
+ var email = /^([\w'-]+)(\.[\w'-]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
+ var url = /^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
+ var urlWeb = /^((https?):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
// All these messages and functions are configurable
return {
* The function used to validate email addresses
* @param {String} value The email address
*/
- 'email' : function(v){
+ email : function(v){
return email.test(v);
},
/**
* The error text to display when the email validation function returns false
* @type String
*/
- 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
+ emailText : 'This field should be an e-mail address in the format "user@domain.com"',
/**
* The keystroke filter mask to be applied on email input
* @type RegExp
*/
- 'emailMask' : /[a-z0-9_\.\-@]/i,
+ emailMask : /[a-z0-9_\.\-@]/i,
/**
* The function used to validate URLs
* @param {String} value The URL
*/
- 'url' : function(v){
+ url : function(v){
return url.test(v);
},
+ /**
+ * The funciton used to validate URLs (only allow schemes 'https' and 'http')
+ * @param {String} v The URL
+ */
+ urlWeb : function(v) {
+ return urlWeb.test(v);
+ },
/**
* The error text to display when the url validation function returns false
* @type String
*/
- 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
+ urlText : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
/**
* The function used to validate alpha values
* @param {String} value The value
*/
- 'alpha' : function(v){
+ alpha : function(v){
return alpha.test(v);
},
/**
* The error text to display when the alpha validation function returns false
* @type String
*/
- 'alphaText' : 'This field should only contain letters and _',
+ alphaText : 'This field should only contain letters and _',
/**
* The keystroke filter mask to be applied on alpha input
* @type RegExp
*/
- 'alphaMask' : /[a-z_]/i,
+ alphaMask : /[a-z_]/i,
/**
* The function used to validate alphanumeric values
* @param {String} value The value
*/
- 'alphanum' : function(v){
+ alphanum : function(v){
return alphanum.test(v);
},
/**
* The error text to display when the alphanumeric validation function returns false
* @type String
*/
- 'alphanumText' : 'This field should only contain letters, numbers and _',
+ alphanumText : 'This field should only contain letters, numbers and _',
/**
* The keystroke filter mask to be applied on alphanumeric input
* @type RegExp
*/
- 'alphanumMask' : /[a-z0-9_]/i
+ alphanumMask : /[a-z0-9_]/i
};
}();//<script type="text/javascript">
this.view.singleSelect = false;
this.view.multiSelect = true;
this.view.toggleSelect = true;
- this.pageTb.add(new Roo.Toolbar.Fill(), {
+ this.pageTb.add(new Roo.Toolbar.Fill(),{
+ text: 'Select All',
+ handler: function() {
+ _t.selectAll();
+ }
+ },
+ {
text: 'Done',
- handler: function()
- {
+ handler: function() {
_t.collapse();
}
});
},
+ cleanLeadingSpace : function(e)
+ {
+ // this is disabled, as it retriggers setvalue on blur
+ return;
+ },
+ doForce : function() {
+ // no idea what this did, but it blanks out our values.
+ return;
+ },
onViewOver : function(e, t){
// do nothing...
return;
return false;
},
-
+ selectAll : function()
+ {
+ var sels = [];
+ this.store.each(function(r,i) {
+ sels.push(i);
+ });
+ this.view.select(sels);
+ this.collapse();
+ return false;
+
+ },
onSelect : function(record, index){
// Roo.log("onselect Called");
}
}
});
-/*
+Roo.layout = {};/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
*/
/**
- * @class Roo.LayoutManager
+ * @class Roo.layout.Manager
* @extends Roo.util.Observable
* Base class for layout managers.
*/
-Roo.LayoutManager = function(container, config){
- Roo.LayoutManager.superclass.constructor.call(this);
+Roo.layout.Manager = function(container, config){
+ Roo.layout.Manager.superclass.constructor.call(this);
this.el = Roo.get(container);
// ie scrollbar fix
if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
/**
* @event layout
* Fires when a layout is performed.
- * @param {Roo.LayoutManager} this
+ * @param {Roo.layout.Manager} this
*/
"layout" : true,
/**
* @event regionresized
* Fires when the user resizes a region.
- * @param {Roo.LayoutRegion} region The resized region
+ * @param {Roo.layout.Region} region The resized region
* @param {Number} newSize The new size (width for east/west, height for north/south)
*/
"regionresized" : true,
/**
* @event regioncollapsed
* Fires when a region is collapsed.
- * @param {Roo.LayoutRegion} region The collapsed region
+ * @param {Roo.layout.Region} region The collapsed region
*/
"regioncollapsed" : true,
/**
* @event regionexpanded
* Fires when a region is expanded.
- * @param {Roo.LayoutRegion} region The expanded region
+ * @param {Roo.layout.Region} region The expanded region
*/
"regionexpanded" : true
});
Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
};
-Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
+Roo.extend(Roo.layout.Manager, Roo.util.Observable, {
/**
* Returns true if this layout is currently being updated
* @return {Boolean}
/**
* Returns the specified region.
* @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
- * @return {Roo.LayoutRegion}
+ * @return {Roo.layout.Region}
*/
getRegion : function(target){
return this.regions[target.toLowerCase()];
* <script type="text/javascript">
*/
/**
- * @class Roo.BorderLayout
- * @extends Roo.LayoutManager
- * @children Roo.ContentPanel
+ * @class Roo.layout.Border
+ * @extends Roo.layout.Manager
+ * @children Roo.panel.Content
* This class represents a common layout manager used in desktop applications. For screenshots and more details,
* please see: <br><br>
* <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>
* <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>
* Example:
<pre><code>
- var layout = new Roo.BorderLayout(document.body, {
+ var layout = new Roo.layout.Border(document.body, {
north: {
initialSize: 25,
titlebar: false
});
// shorthand
-var CP = Roo.ContentPanel;
+var CP = Roo.panel.Content;
layout.beginUpdate();
layout.add("north", new CP("north", "North"));
* @param {String/HTMLElement/Element} container The container this layout is bound to
* @param {Object} config Configuration options
*/
-Roo.BorderLayout = function(container, config){
+Roo.layout.Border = function(container, config){
config = config || {};
- Roo.BorderLayout.superclass.constructor.call(this, container, config);
- this.factory = config.factory || Roo.BorderLayout.RegionFactory;
+ Roo.layout.Border.superclass.constructor.call(this, container, config);
+ this.factory = config.factory || Roo.layout.Border.RegionFactory;
for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
var target = this.factory.validRegions[i];
if(config[target]){
}
};
-Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
+Roo.extend(Roo.layout.Border, Roo.layout.Manager, {
/**
- * @cfg {Roo.LayoutRegion} east
+ * @cfg {Roo.layout.Region} east
*/
/**
- * @cfg {Roo.LayoutRegion} west
+ * @cfg {Roo.layout.Region} west
*/
/**
- * @cfg {Roo.LayoutRegion} north
+ * @cfg {Roo.layout.Region} north
*/
/**
- * @cfg {Roo.LayoutRegion} south
+ * @cfg {Roo.layout.Region} south
*/
/**
- * @cfg {Roo.LayoutRegion} center
+ * @cfg {Roo.layout.Region} center
*/
/**
* Creates and adds a new region if it doesn't already exist.
/**
* Adds a ContentPanel (or subclass) to this layout.
* @param {String} target The target region key (north, south, east, west or center).
- * @param {Roo.ContentPanel} panel The panel to add
- * @return {Roo.ContentPanel} The added panel
+ * @param {Roo.panel.Content} panel The panel to add
+ * @return {Roo.panel.Content} The added panel
*/
add : function(target, panel){
/**
* Remove a ContentPanel (or subclass) to this layout.
* @param {String} target The target region key (north, south, east, west or center).
- * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
- * @return {Roo.ContentPanel} The removed panel
+ * @param {Number/String/Roo.panel.Content} panel The index, id or panel to remove
+ * @return {Roo.panel.Content} The removed panel
*/
remove : function(target, panel){
target = target.toLowerCase();
/**
* Searches all regions for a panel with the specified id
* @param {String} panelId
- * @return {Roo.ContentPanel} The panel or null if it wasn't found
+ * @return {Roo.panel.Content} The panel or null if it wasn't found
*/
findPanel : function(panelId){
var rs = this.regions;
/**
* Searches all regions for a panel with the specified id and activates (shows) it.
- * @param {String/ContentPanel} panelId The panels id or the panel itself
- * @return {Roo.ContentPanel} The shown panel or null
+ * @param {String/panel.Content} panelId The panels id or the panel itself
+ * @return {Roo.panel.Content} The shown panel or null
*/
showPanel : function(panelId) {
var rs = this.regions;
if(!provider){
provider = Roo.state.Manager;
}
- var sm = new Roo.LayoutStateManager();
+ var sm = new Roo.layout.StateManager();
sm.init(this, provider);
},
* a valid ContentPanel config object. Example:
* <pre><code>
// Create the main layout
-var layout = new Roo.BorderLayout('main-ct', {
+var layout = new Roo.layout.Border('main-ct', {
west: {
split:true,
minSize: 175,
// private
addTypedPanels : function(lr, ps){
if(typeof ps == 'string'){
- lr.add(new Roo.ContentPanel(ps));
+ lr.add(new Roo.panel.Content(ps));
}
else if(ps instanceof Array){
for(var i =0, len = ps.length; i < len; i++){
else if(!ps.events){ // raw config?
var el = ps.el;
delete ps.el; // prevent conflict
- lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
+ lr.add(new Roo.panel.Content(el || Roo.id(), ps));
}
else { // panel object assumed!
lr.add(ps);
{
// basically accepts a pannel...
// can accept a layout region..!?!?
- //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
+ //Roo.log('Roo.layout.Border add ' + cfg.xtype)
- if (!cfg.xtype.match(/Panel$/)) {
- return false;
- }
+ // if (!cfg.xtype.match(/Panel$/)) {
+ // return false;
+ // }
var ret = false;
-
+
if (typeof(cfg.region) == 'undefined') {
Roo.log("Failed to add Panel, region was not set");
Roo.log(cfg);
switch(cfg.xtype)
{
- case 'ContentPanel': // ContentPanel (el, cfg)
+ case 'Content':
+ if(cfg.autoCreate) {
+ ret = new Roo.panel[cfg.xtype](cfg); // new panel!!!!!
+ } else {
+ var el = this.el.createChild();
+ ret = new Roo.panel[cfg.xtype](el, cfg); // new panel!!!!!
+ }
+
+ this.add(region, ret);
+ break;
+ case 'Grid':
+ // needs grid and region
+
+ //var el = this.getRegion(region).el.createChild();
+ var el = this.el.createChild();
+ // create the grid first...
+
+ var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
+ delete cfg.grid;
+ if (region == 'center' && this.active ) {
+ cfg.background = false;
+ }
+ ret = new Roo.panel[cfg.xtype](grid, cfg); // new panel!!!!!
+
+ this.add(region, ret);
+ if (cfg.background) {
+ ret.on('activate', function(gp) {
+ if (!gp.grid.rendered) {
+ gp.grid.render();
+ }
+ });
+ } else {
+ grid.render();
+ }
+ break;
+ case 'NestedLayout':
+ // create a new Layout (which is a Border Layout...
+ var el = this.el.createChild();
+ var clayout = cfg.layout;
+ delete cfg.layout;
+ clayout.items = clayout.items || [];
+ // replace this exitems with the clayout ones..
+ xitems = clayout.items;
+
+
+ if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
+ cfg.background = false;
+ }
+ var layout = new Roo.layout.Border(el, clayout);
+
+ ret = new Roo.panel[cfg.xtype](layout, cfg); // new panel!!!!!
+ //console.log('adding nested layout panel ' + cfg.toSource());
+ this.add(region, ret);
+ nb = {}; /// find first...
+ break;
+
+ case 'Calendar':
+ ret = new Roo.panel[cfg.xtype](cfg); // new panel!!!!!
+ this.add(region, ret);
+ break;
+ case 'Tree': // our new panel!
+ cfg.el = this.el.createChild();
+ ret = new Roo.panel[cfg.xtype](cfg); // new panel!!!!!
+ this.add(region, ret);
+ break;
+ case 'ContentPanel':
case 'ScrollPanel': // ContentPanel (el, cfg)
case 'ViewPanel':
if(cfg.autoCreate) {
if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
cfg.background = false;
}
- var layout = new Roo.BorderLayout(el, clayout);
+ var layout = new Roo.layout.Border(el, clayout);
ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
//console.log('adding nested layout panel ' + cfg.toSource());
// shorthand
var CP = Roo.ContentPanel;
-var layout = Roo.BorderLayout.create({
+var layout = Roo.layout.Border.create({
north: {
initialSize: 25,
titlebar: false,
* @param config
* @param targetEl
*/
-Roo.BorderLayout.create = function(config, targetEl){
- var layout = new Roo.BorderLayout(targetEl || document.body, config);
+Roo.layout.Border.create = function(config, targetEl){
+ var layout = new Roo.layout.Border(targetEl || document.body, config);
layout.beginUpdate();
- var regions = Roo.BorderLayout.RegionFactory.validRegions;
+ var regions = Roo.layout.Border.RegionFactory.validRegions;
for(var j = 0, jlen = regions.length; j < jlen; j++){
var lr = regions[j];
if(layout.regions[lr] && config[lr].panels){
};
// private
-Roo.BorderLayout.RegionFactory = {
+Roo.layout.Border.RegionFactory = {
// private
validRegions : ["north","south","east","west","center"],
create : function(target, mgr, config){
target = target.toLowerCase();
if(config.lightweight || config.basic){
- return new Roo.BasicLayoutRegion(mgr, config, target);
- }
- switch(target){
- case "north":
- return new Roo.NorthLayoutRegion(mgr, config);
- case "south":
- return new Roo.SouthLayoutRegion(mgr, config);
- case "east":
- return new Roo.EastLayoutRegion(mgr, config);
- case "west":
- return new Roo.WestLayoutRegion(mgr, config);
- case "center":
- return new Roo.CenterLayoutRegion(mgr, config);
+ return new Roo.layout.BasicRegion(mgr, config, target);
}
- throw 'Layout region "'+target+'" not supported.';
+ var cn = target.charAt(0).toUpperCase() + target.slice(1);
+ if (typeof (Roo.layout[cn]) == 'undefined') {
+ throw 'Layout region "'+target+'" not supported.';
+ }
+ return new Roo.layout[cn](mgr, config);
+
+
}
};/*
* Based on:
*/
/**
- * @class Roo.BasicLayoutRegion
+ * @class Roo.layout.BasicRegion
* @extends Roo.util.Observable
* This class represents a lightweight region in a layout manager. This region does not move dom nodes
* and does not have a titlebar, tabs or any other features. All it does is size and position
* panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
*/
-Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
+Roo.layout.BasicRegion= function(mgr, config, pos, skipConfig){
this.mgr = mgr;
this.position = pos;
this.events = {
/**
- * @scope Roo.BasicLayoutRegion
+ * @scope Roo.layout.BasicRegion
*/
/**
* @event beforeremove
* Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
- * @param {Roo.LayoutRegion} this
- * @param {Roo.ContentPanel} panel The panel
+ * @param {Roo.layout.Region} this
+ * @param {Roo.panel.Content} panel The panel
* @param {Object} e The cancel event object
*/
"beforeremove" : true,
/**
* @event invalidated
* Fires when the layout for this region is changed.
- * @param {Roo.LayoutRegion} this
+ * @param {Roo.layout.Region} this
*/
"invalidated" : true,
/**
* @event visibilitychange
* Fires when this region is shown or hidden
- * @param {Roo.LayoutRegion} this
+ * @param {Roo.layout.Region} this
* @param {Boolean} visibility true or false
*/
"visibilitychange" : true,
/**
* @event paneladded
* Fires when a panel is added.
- * @param {Roo.LayoutRegion} this
- * @param {Roo.ContentPanel} panel The panel
+ * @param {Roo.layout.Region} this
+ * @param {Roo.panel.Content} panel The panel
*/
"paneladded" : true,
/**
* @event panelremoved
* Fires when a panel is removed.
- * @param {Roo.LayoutRegion} this
- * @param {Roo.ContentPanel} panel The panel
+ * @param {Roo.layout.Region} this
+ * @param {Roo.panel.Content} panel The panel
*/
"panelremoved" : true,
/**
* @event beforecollapse
* Fires when this region before collapse.
- * @param {Roo.LayoutRegion} this
+ * @param {Roo.layout.Region} this
*/
"beforecollapse" : true,
/**
* @event collapsed
* Fires when this region is collapsed.
- * @param {Roo.LayoutRegion} this
+ * @param {Roo.layout.Region} this
*/
"collapsed" : true,
/**
* @event expanded
* Fires when this region is expanded.
- * @param {Roo.LayoutRegion} this
+ * @param {Roo.layout.Region} this
*/
"expanded" : true,
/**
* @event slideshow
* Fires when this region is slid into view.
- * @param {Roo.LayoutRegion} this
+ * @param {Roo.layout.Region} this
*/
"slideshow" : true,
/**
* @event slidehide
* Fires when this region slides out of view.
- * @param {Roo.LayoutRegion} this
+ * @param {Roo.layout.Region} this
*/
"slidehide" : true,
/**
* @event panelactivated
* Fires when a panel is activated.
- * @param {Roo.LayoutRegion} this
- * @param {Roo.ContentPanel} panel The activated panel
+ * @param {Roo.layout.Region} this
+ * @param {Roo.panel.Content} panel The activated panel
*/
"panelactivated" : true,
/**
* @event resized
* Fires when the user resizes this region.
- * @param {Roo.LayoutRegion} this
+ * @param {Roo.layout.Region} this
* @param {Number} newSize The new size (width for east/west, height for north/south)
*/
"resized" : true
// ensure listeners are added...
if (config.listeners || config.events) {
- Roo.BasicLayoutRegion.superclass.constructor.call(this, {
+ Roo.layout.BasicRegion.superclass.constructor.call(this, {
listeners : config.listeners || {},
events : config.events || {}
});
}
};
-Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
+Roo.extend(Roo.layout.BasicRegion, Roo.util.Observable, {
getPanelId : function(p){
return p.getId();
},
/**
* Show the specified panel.
- * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
- * @return {Roo.ContentPanel} The shown panel or null
+ * @param {Number/String/panel.Content} panelId The panels index, id or the panel itself
+ * @return {Roo.panel.Content} The shown panel or null
*/
showPanel : function(panel){
if(panel = this.getPanel(panel)){
/**
* Get the active panel for this region.
- * @return {Roo.ContentPanel} The active panel or null
+ * @return {Roo.panel.Content} The active panel or null
*/
getActivePanel : function(){
return this.activePanel;
/**
* Add the passed ContentPanel(s)
- * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
- * @return {Roo.ContentPanel} The panel added (if only one was added)
+ * @param {panel.Content...} panel The ContentPanel(s) to add (you can pass more than one)
+ * @return {Roo.panel.Content} The panel added (if only one was added)
*/
add : function(panel){
if(arguments.length > 1){
/**
* Returns true if the panel is in this region.
- * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
+ * @param {Number/String/panel.Content} panel The panels index, id or the panel itself
* @return {Boolean}
*/
hasPanel : function(panel){
/**
* Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
- * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
+ * @param {Number/String/panel.Content} panel The panels index, id or the panel itself
* @param {Boolean} preservePanel Overrides the config preservePanel option
- * @return {Roo.ContentPanel} The panel that was removed
+ * @return {Roo.panel.Content} The panel that was removed
*/
remove : function(panel, preservePanel){
panel = this.getPanel(panel);
/**
* Returns the panel specified or null if it's not in this region.
- * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
- * @return {Roo.ContentPanel}
+ * @param {Number/String/panel.Content} panel The panels index, id or the panel itself
+ * @return {Roo.panel.Content}
*/
getPanel : function(id){
if(typeof id == "object"){ // must be panel obj
*/
/**
- * @class Roo.LayoutRegion
- * @extends Roo.BasicLayoutRegion
+ * @class Roo.layout.Region
+ * @extends Roo.layout.BasicRegion
* This class represents a region in a layout manager.
* @cfg {Boolean} collapsible False to disable collapsing (defaults to true)
* @cfg {Boolean} collapsed True to set the initial display to collapsed (defaults to false)
* @cfg {Boolean} split To show the splitter
* @cfg {Boolean} toolbar xtype configuration for a toolbar - shows on right of tabbar
*/
-Roo.LayoutRegion = function(mgr, config, pos){
- Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
+Roo.layout.Region = function(mgr, config, pos){
+ Roo.layout.Region.superclass.constructor.call(this, mgr, config, pos, true);
var dh = Roo.DomHelper;
/** This region's container element
* @type Roo.Element */
this.applyConfig(config);
};
-Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
+Roo.extend(Roo.layout.Region, Roo.layout.BasicRegion, {
createBody : function(){
/** This region's body element
initTabs : function()
{
this.bodyEl.setStyle("overflow", "hidden");
- var ts = new Roo.TabPanel(
+ var ts = new Roo.panel.Tab(
this.bodyEl.dom,
{
tabPosition: this.bottomTabs ? 'bottom' : 'top',
/**
* Shows the specified panel.
- * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
- * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
+ * @param {Number/String/panel.Content} panelId The panel's index, id or the panel itself
+ * @return {Roo.panel.Content} The shown panel, or null if a panel could not be found from panelId
*/
showPanel : function(panel)
{
/**
* Get the active panel for this region.
- * @return {Roo.ContentPanel} The active panel or null
+ * @return {Roo.panel.Content} The active panel or null
*/
getActivePanel : function(){
return this.activePanel;
/**
* Adds the passed ContentPanel(s) to this region.
- * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
- * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
+ * @param {panel.Content...} panel The ContentPanel(s) to add (you can pass more than one)
+ * @return {Roo.panel.Content} The panel added (if only one was added; null otherwise)
*/
add : function(panel){
if(arguments.length > 1){
/**
* Hides the tab for the specified panel.
- * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
+ * @param {Number/String/panel.Content} panel The panel's index, id or the panel itself
*/
hidePanel : function(panel){
if(this.tabs && (panel = this.getPanel(panel))){
/**
* Unhides the tab for a previously hidden panel.
- * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
+ * @param {Number/String/panel.Content} panel The panel's index, id or the panel itself
*/
unhidePanel : function(panel){
if(this.tabs && (panel = this.getPanel(panel))){
/**
* Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
- * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
+ * @param {Number/String/panel.Content} panel The panel's index, id or the panel itself
* @param {Boolean} preservePanel Overrides the config preservePanel option
- * @return {Roo.ContentPanel} The panel that was removed
+ * @return {Roo.panel.Content} The panel that was removed
*/
remove : function(panel, preservePanel){
panel = this.getPanel(panel);
/**
* Returns the TabPanel component used by this region
- * @return {Roo.TabPanel}
+ * @return {Roo.panel.Tab}
*/
getTabs : function(){
return this.tabs;
/**
- * @class Roo.SplitLayoutRegion
- * @extends Roo.LayoutRegion
- * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
+ * @class Roo.layout.SplitRegion
+ * @extends Roo.layout.Region
+ * Adds a splitbar and other (private) useful functionality to a {@link Roo.layout.Region}.
*/
-Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
+Roo.layout.SplitRegion = function(mgr, config, pos, cursor){
this.cursor = cursor;
- Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
+ Roo.layout.SplitRegion.superclass.constructor.call(this, mgr, config, pos);
};
-Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
+Roo.extend(Roo.layout.SplitRegion, Roo.layout.Region, {
splitTip : "Drag to resize.",
collapsibleSplitTip : "Drag to resize. Double click to hide.",
useSplitTips : false,
applyConfig : function(config){
- Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
+ Roo.layout.SplitRegion.superclass.applyConfig.call(this, config);
if(config.split){
if(!this.split){
var splitEl = Roo.DomHelper.append(this.mgr.el.dom,
hide : function(){
this.hideSplitter();
- Roo.SplitLayoutRegion.superclass.hide.call(this);
+ Roo.layout.SplitRegion.superclass.hide.call(this);
},
hideSplitter : function(){
if(this.split){
this.split.el.show();
}
- Roo.SplitLayoutRegion.superclass.show.call(this);
+ Roo.layout.SplitRegion.superclass.show.call(this);
},
beforeSlide: function(){
/*
* These classes are private internal classes
*/
-Roo.CenterLayoutRegion = function(mgr, config){
- Roo.LayoutRegion.call(this, mgr, config, "center");
+Roo.layout.Center = function(mgr, config){
+ Roo.layout.Region.call(this, mgr, config, "center");
this.visible = true;
this.minWidth = config.minWidth || 20;
this.minHeight = config.minHeight || 20;
};
-Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
+Roo.extend(Roo.layout.Center, Roo.layout.Region, {
hide : function(){
// center panel can't be hidden
},
return this.minHeight;
}
});
-
-
-Roo.NorthLayoutRegion = function(mgr, config){
- Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
+Roo.layout.West = function(mgr, config){
+ Roo.layout.SplitRegion.call(this, mgr, config, "west", "w-resize");
if(this.split){
- this.split.placement = Roo.SplitBar.TOP;
- this.split.orientation = Roo.SplitBar.VERTICAL;
- this.split.el.addClass("x-layout-split-v");
+ this.split.placement = Roo.SplitBar.LEFT;
+ this.split.orientation = Roo.SplitBar.HORIZONTAL;
+ this.split.el.addClass("x-layout-split-h");
}
- var size = config.initialSize || config.height;
+ var size = config.initialSize || config.width;
if(typeof size != "undefined"){
- this.el.setHeight(size);
+ this.el.setWidth(size);
}
};
-Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
- orientation: Roo.SplitBar.VERTICAL,
+Roo.extend(Roo.layout.West, Roo.layout.SplitRegion, {
+ orientation: Roo.SplitBar.HORIZONTAL,
getBox : function(){
if(this.collapsed){
return this.collapsedEl.getBox();
}
var box = this.el.getBox();
if(this.split){
- box.height += this.split.el.getHeight();
+ box.width += this.split.el.getWidth();
}
return box;
},
updateBox : function(box){
if(this.split && !this.collapsed){
- box.height -= this.split.el.getHeight();
- this.split.el.setLeft(box.x);
- this.split.el.setTop(box.y+box.height);
- this.split.el.setWidth(box.width);
+ var sw = this.split.el.getWidth();
+ box.width -= sw;
+ this.split.el.setLeft(box.x+box.width);
+ this.split.el.setTop(box.y);
+ this.split.el.setHeight(box.height);
}
if(this.collapsed){
- this.updateBody(box.width, null);
+ this.updateBody(null, box.height);
}
- Roo.LayoutRegion.prototype.updateBox.call(this, box);
+ Roo.layout.Region.prototype.updateBox.call(this, box);
}
});
-
-Roo.SouthLayoutRegion = function(mgr, config){
- Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
+Roo.layout.East = function(mgr, config){
+ Roo.layout.SplitRegion.call(this, mgr, config, "east", "e-resize");
if(this.split){
- this.split.placement = Roo.SplitBar.BOTTOM;
- this.split.orientation = Roo.SplitBar.VERTICAL;
- this.split.el.addClass("x-layout-split-v");
+ this.split.placement = Roo.SplitBar.RIGHT;
+ this.split.orientation = Roo.SplitBar.HORIZONTAL;
+ this.split.el.addClass("x-layout-split-h");
}
- var size = config.initialSize || config.height;
+ var size = config.initialSize || config.width;
if(typeof size != "undefined"){
- this.el.setHeight(size);
+ this.el.setWidth(size);
}
};
-Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
- orientation: Roo.SplitBar.VERTICAL,
+Roo.extend(Roo.layout.East, Roo.layout.SplitRegion, {
+ orientation: Roo.SplitBar.HORIZONTAL,
getBox : function(){
if(this.collapsed){
return this.collapsedEl.getBox();
}
var box = this.el.getBox();
if(this.split){
- var sh = this.split.el.getHeight();
- box.height += sh;
- box.y -= sh;
+ var sw = this.split.el.getWidth();
+ box.width += sw;
+ box.x -= sw;
}
return box;
},
-
+
updateBox : function(box){
if(this.split && !this.collapsed){
- var sh = this.split.el.getHeight();
- box.height -= sh;
- box.y += sh;
+ var sw = this.split.el.getWidth();
+ box.width -= sw;
this.split.el.setLeft(box.x);
- this.split.el.setTop(box.y-sh);
- this.split.el.setWidth(box.width);
+ this.split.el.setTop(box.y);
+ this.split.el.setHeight(box.height);
+ box.x += sw;
}
if(this.collapsed){
- this.updateBody(box.width, null);
+ this.updateBody(null, box.height);
}
- Roo.LayoutRegion.prototype.updateBox.call(this, box);
+ Roo.layout.Region.prototype.updateBox.call(this, box);
}
-});
-
-Roo.EastLayoutRegion = function(mgr, config){
- Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
+});Roo.layout.South = function(mgr, config){
+ Roo.layout.SplitRegion.call(this, mgr, config, "south", "s-resize");
if(this.split){
- this.split.placement = Roo.SplitBar.RIGHT;
- this.split.orientation = Roo.SplitBar.HORIZONTAL;
- this.split.el.addClass("x-layout-split-h");
+ this.split.placement = Roo.SplitBar.BOTTOM;
+ this.split.orientation = Roo.SplitBar.VERTICAL;
+ this.split.el.addClass("x-layout-split-v");
}
- var size = config.initialSize || config.width;
+ var size = config.initialSize || config.height;
if(typeof size != "undefined"){
- this.el.setWidth(size);
+ this.el.setHeight(size);
}
};
-Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
- orientation: Roo.SplitBar.HORIZONTAL,
+Roo.extend(Roo.layout.South, Roo.layout.SplitRegion, {
+ orientation: Roo.SplitBar.VERTICAL,
getBox : function(){
if(this.collapsed){
return this.collapsedEl.getBox();
}
var box = this.el.getBox();
if(this.split){
- var sw = this.split.el.getWidth();
- box.width += sw;
- box.x -= sw;
+ var sh = this.split.el.getHeight();
+ box.height += sh;
+ box.y -= sh;
}
return box;
},
-
+
updateBox : function(box){
if(this.split && !this.collapsed){
- var sw = this.split.el.getWidth();
- box.width -= sw;
+ var sh = this.split.el.getHeight();
+ box.height -= sh;
+ box.y += sh;
this.split.el.setLeft(box.x);
- this.split.el.setTop(box.y);
- this.split.el.setHeight(box.height);
- box.x += sw;
+ this.split.el.setTop(box.y-sh);
+ this.split.el.setWidth(box.width);
}
if(this.collapsed){
- this.updateBody(null, box.height);
+ this.updateBody(box.width, null);
}
- Roo.LayoutRegion.prototype.updateBox.call(this, box);
+ Roo.layout.Region.prototype.updateBox.call(this, box);
}
});
-Roo.WestLayoutRegion = function(mgr, config){
- Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
+
+Roo.layout.North = function(mgr, config){
+ Roo.layout.Region.call(this, mgr, config, "north", "n-resize");
if(this.split){
- this.split.placement = Roo.SplitBar.LEFT;
- this.split.orientation = Roo.SplitBar.HORIZONTAL;
- this.split.el.addClass("x-layout-split-h");
+ this.split.placement = Roo.SplitBar.TOP;
+ this.split.orientation = Roo.SplitBar.VERTICAL;
+ this.split.el.addClass("x-layout-split-v");
}
- var size = config.initialSize || config.width;
+ var size = config.initialSize || config.height;
if(typeof size != "undefined"){
- this.el.setWidth(size);
+ this.el.setHeight(size);
}
};
-Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
- orientation: Roo.SplitBar.HORIZONTAL,
+Roo.extend(Roo.layout.North, Roo.layout.SplitRegion, {
+ orientation: Roo.SplitBar.VERTICAL,
getBox : function(){
if(this.collapsed){
return this.collapsedEl.getBox();
}
var box = this.el.getBox();
if(this.split){
- box.width += this.split.el.getWidth();
+ box.height += this.split.el.getHeight();
}
return box;
},
updateBox : function(box){
if(this.split && !this.collapsed){
- var sw = this.split.el.getWidth();
- box.width -= sw;
- this.split.el.setLeft(box.x+box.width);
- this.split.el.setTop(box.y);
- this.split.el.setHeight(box.height);
+ box.height -= this.split.el.getHeight();
+ this.split.el.setLeft(box.x);
+ this.split.el.setTop(box.y+box.height);
+ this.split.el.setWidth(box.width);
}
if(this.collapsed){
- this.updateBody(null, box.height);
+ this.updateBody(box.width, null);
}
- Roo.LayoutRegion.prototype.updateBox.call(this, box);
+ Roo.layout.Region.prototype.updateBox.call(this, box);
}
-});
-/*
+});/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
/*
* Private internal class for reading and applying state
*/
-Roo.LayoutStateManager = function(layout){
+Roo.layout.StateManager = function(layout){
// default empty state
this.state = {
north: {},
};
};
-Roo.LayoutStateManager.prototype = {
+Roo.layout.StateManager.prototype = {
init : function(layout, provider){
this.provider = provider;
var state = provider.get(layout.id+"-layout-state");
* <script type="text/javascript">
*/
/**
- * @class Roo.ContentPanel
+ * @class Roo.panel.Content
* @extends Roo.util.Observable
* @children Roo.form.Form Roo.JsonView Roo.View
- * @parent Roo.BorderLayout Roo.LayoutDialog builder
- * A basic ContentPanel element.
+ * @parent Roo.layout.Border Roo.LayoutDialog builder
+ * A basic Content Panel element.
* @cfg {Boolean} fitToFrame True for this panel to adjust its size to fit when the region resizes (defaults to false)
* @cfg {Boolean} fitContainer When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container (defaults to false)
* @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
* @cfg {Roo.menu.Menu} menu popup menu
* @constructor
- * Create a new ContentPanel.
+ * Create a new Content Panel.
* @param {String/HTMLElement/Roo.Element} el The container element for this panel
* @param {String/Object} config A string to set only the title or a config object
* @param {String} content (optional) Set the HTML content for this panel
* @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
*/
-Roo.ContentPanel = function(el, config, content){
+Roo.panel.Content = function(el, config, content){
-
/*
if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
config = el;
/**
* @event activate
* Fires when this panel is activated.
- * @param {Roo.ContentPanel} this
+ * @param {Roo.panel.Content} this
*/
"activate" : true,
/**
* @event deactivate
* Fires when this panel is activated.
- * @param {Roo.ContentPanel} this
+ * @param {Roo.panel.Content} this
*/
"deactivate" : true,
/**
* @event resize
* Fires when this panel is resized if fitToFrame is true.
- * @param {Roo.ContentPanel} this
+ * @param {Roo.panel.Content} this
* @param {Number} width The width after any component adjustments
* @param {Number} height The height after any component adjustments
*/
/**
* @event render
* Fires when this tab is created
- * @param {Roo.ContentPanel} this
+ * @param {Roo.panel.Content} this
*/
"render" : true
- Roo.ContentPanel.superclass.constructor.call(this);
+ Roo.panel.Content.superclass.constructor.call(this);
if (this.view && typeof(this.view.xtype) != 'undefined') {
this.view.el = this.el.appendChild(document.createElement("div"));
this.fireEvent('render', this);
};
-Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
+Roo.extend(Roo.panel.Content, Roo.util.Observable, {
tabTip:'',
setRegion : function(region){
this.region = region;
* @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}
* @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
* @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.
- * @return {Roo.ContentPanel} this
+ * @return {Roo.panel.Content} this
*/
load : function(){
var um = this.el.getUpdateManager();
*/
addxtype : function(cfg) {
+ if(cfg.xtype.match(/^Cropbox$/)) {
+
+ this.cropbox = new Roo.factory(cfg);
+
+ this.cropbox.render(this.el);
+
+ return this.cropbox;
+ }
// add form..
if (cfg.xtype.match(/^Form$/)) {
/**
- * @class Roo.GridPanel
- * @extends Roo.ContentPanel
- * @parent Roo.BorderLayout Roo.LayoutDialog builder
+ * @class Roo.panel.Grid
+ * @extends Roo.panel.Content
+ * @parent Roo.layout.Border Roo.LayoutDialog builder
* @constructor
* Create a new GridPanel.
* @cfg {Roo.grid.Grid} grid The grid for this panel
*/
-Roo.GridPanel = function(grid, config){
+Roo.panel.Grid = function(grid, config){
// universal ctor...
if (typeof(grid.grid) != 'undefined') {
this.wrapper.dom.appendChild(grid.getGridEl().dom);
- Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
+ Roo.panel.Grid.superclass.constructor.call(this, this.wrapper, config);
if(this.toolbar){
this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
};
-Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
+Roo.extend(Roo.panel.Grid, Roo.panel.Content, {
getId : function(){
return this.grid.id;
},
destroy : function(){
this.grid.destroy();
delete this.grid;
- Roo.GridPanel.superclass.destroy.call(this);
+ Roo.panel.Grid.superclass.destroy.call(this);
}
});
/**
- * @class Roo.NestedLayoutPanel
- * @extends Roo.ContentPanel
- * @parent Roo.BorderLayout Roo.LayoutDialog builder
- * @cfg {Roo.BorderLayout} layout [required] The layout for this panel
+ * @class Roo.panel.NestedLayout
+ * @extends Roo.panel.Content
+ * @parent Roo.layout.Border Roo.LayoutDialog builder
+ * @cfg {Roo.layout.Border} layout [required] The layout for this panel
*
*
* @constructor
* Create a new NestedLayoutPanel.
*
*
- * @param {Roo.BorderLayout} layout [required] The layout for this panel
+ * @param {Roo.layout.Border} layout [required] The layout for this panel
* @param {String/Object} config A string to set only the title or a config object
*/
-Roo.NestedLayoutPanel = function(layout, config)
+Roo.panel.NestedLayout = function(layout, config)
{
// construct with only one argument..
/* FIXME - implement nicer consturctors
*/
- Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
+ Roo.panel.NestedLayout.superclass.constructor.call(this, layout.getEl(), config);
layout.monitorWindowResize = false; // turn off autosizing
this.layout = layout;
};
-Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
+Roo.extend(Roo.panel.NestedLayout, Roo.panel.Content, {
layout : false,
/**
* Returns the nested BorderLayout for this panel
- * @return {Roo.BorderLayout}
+ * @return {Roo.layout.Border}
*/
getLayout : function(){
return this.layout;
);
panel.addxtype({
- xtype : 'NestedLayoutPanel',
+ xtype : 'panel.NestedLayout',
region: 'west',
layout: {
center: { },
}
});
-Roo.ScrollPanel = function(el, config, content){
+Roo.panel.Scroll = function(el, config, content){
config = config || {};
config.fitToFrame = true;
- Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
+ Roo.panel.Scroll.superclass.constructor.call(this, el, config, content);
this.el.dom.style.overflow = "hidden";
var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
this.el = wrap; this.up = up; this.down = down;
};
-Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
+Roo.extend(Roo.panel.Scroll, Roo.panel.Content, {
increment : 100,
wheelIncrement : 5,
scrollUp : function(){
},
setSize : function(){
- Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
+ Roo.panel.Scroll.superclass.setSize.apply(this, arguments);
this.afterScroll();
},
/**
- * @class Roo.TreePanel
- * @extends Roo.ContentPanel
- * @parent Roo.BorderLayout Roo.LayoutDialog builder
+ * @class Roo.panel.Tree
+ * @extends Roo.panel.Content
+ * @parent Roo.layout.Border Roo.LayoutDialog builder
* Treepanel component
*
* @constructor
* Create a new TreePanel. - defaults to fit/scoll contents.
* @param {String/Object} config A string to set only the panel's title, or a config object
*/
-Roo.TreePanel = function(config){
+Roo.panel.Tree = function(config){
var el = config.el;
var tree = config.tree;
delete config.tree;
- Roo.TreePanel.superclass.constructor.call(this, el, config);
+ Roo.panel.Tree.superclass.constructor.call(this, el, config);
this.tree = new Roo.tree.TreePanel(treeEl , tree);
};
-Roo.extend(Roo.TreePanel, Roo.ContentPanel, {
+Roo.extend(Roo.panel.Tree, Roo.panel.Content, {
fitToFrame : true,
autoScroll : true,
/*
- * @cfg {Roo.tree.TreePanel} tree [required] The tree TreePanel, with config etc.
+ * @cfg {Roo.tree.panel.Tree} tree [required] The tree TreePanel, with config etc.
*/
tree : false
/**
- * @class Roo.ReaderLayout
- * @extends Roo.BorderLayout
+ * @class Roo.layout.Reader
+ * @extends Roo.layout.Border
* This is a pre-built layout that represents a classic, 5-pane application. It consists of a header, a primary
* center region containing two nested regions (a top one for a list view and one for item preview below),
* and regions on either side that can be used for navigation, application commands, informational displays, etc.
- * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
+ * The setup and configuration work exactly the same as it does for a {@link Roo.layout.Border} - this class simply
* expedites the setup of the overall layout and regions for this common application style.
* Example:
<pre><code>
-var reader = new Roo.ReaderLayout();
-var CP = Roo.ContentPanel; // shortcut for adding
+var reader = new Roo.layout.Reader();
+var CP = Roo.panel.Content; // shortcut for adding
reader.beginUpdate();
reader.add("north", new CP("north", "North"));
* @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
* document.body if omitted)
*/
-Roo.ReaderLayout = function(config, renderTo){
+Roo.layout.Reader = function(config, renderTo){
var c = config || {size:{}};
- Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
+ Roo.layout.Reader.superclass.constructor.call(this, renderTo || document.body, {
north: c.north !== false ? Roo.apply({
split:false,
initialSize: 32,
this.beginUpdate();
- var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
+ var inner = new Roo.layout.Border(Roo.get(document.body).createChild(), {
south: c.preview !== false ? Roo.apply({
split:true,
initialSize: 200,
minHeight:200
}, c.listView)
});
- this.add('center', new Roo.NestedLayoutPanel(inner,
+ this.add('center', new Roo.panel.NestedLayout(inner,
Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
this.endUpdate();
this.regions.listView = inner.getRegion('center');
};
-Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
+Roo.extend(Roo.layout.Reader, Roo.layout.Border);/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* @cfg {Roo.grid.ColumnModel} cm[] The columns of the grid
*/
/**
- * @cfg {Roo.grid.Store} ds The data store for the grid
+ * @cfg {Roo.data.Store} ds The data store for the grid
*/
/**
* @cfg {Roo.Toolbar} toolbar a toolbar for buttons etc.
*/
+
+ /**
+ * @cfg {Roo.PagingToolbar} footer the paging toolbar
+ */
+
/**
* @cfg {String} ddGroup - drag drop group.
*/
};
Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
/**
- * @cfg {String} header The header text to display in the Grid view.
+ * @cfg {String} header [required] The header text to display in the Grid view.
*/
/**
* @cfg {String} xsHeader Header at Bootsrap Extra Small width (default for all)
* @cfg {String} xlHeader Header at Bootsrap extra Large width
*/
/**
- * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
+ * @cfg {String} dataIndex The name of the field in the grid's {@link Roo.data.Store}'s
* {@link Roo.data.Record} definition from which to draw the column's value. If not
* specified, the column's index is used as an index into the Record's data Array.
*/
/**
- * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
+ * @cfg {Number} width The initial width in pixels of the column. Using this
* instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
*/
/**
- * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
+ * @cfg {Boolean} sortable True if sorting is to be allowed on this column.
* Defaults to the value of the {@link #defaultSortable} property.
* Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
*/
/**
- * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid. Defaults to false.
+ * @cfg {Boolean} locked True to lock the column in place while scrolling the Grid. Defaults to false.
*/
/**
- * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed. Defaults to false.
+ * @cfg {Boolean} fixed True if the column width cannot be changed. Defaults to false.
*/
/**
- * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
+ * @cfg {Boolean} resizable False to disable column resizing. Defaults to true.
*/
/**
- * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
+ * @cfg {Boolean} hidden True to hide the column. Defaults to false.
*/
/**
- * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
+ * @cfg {Function} renderer A function used to generate HTML markup for a cell
* given the cell's data value. See {@link #setRenderer}. If not specified, the
* default renderer returns the escaped data value. If an object is returned (bootstrap only)
* then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
*/
/**
- * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor
+ * @cfg {Roo.grid.GridEditor} editor For grid editors - returns the grid editor
*/
/**
- * @cfg {String} align (Optional) Set the CSS text-align property of the column. Defaults to undefined.
+ * @cfg {String} align (left|right) Set the CSS text-align property of the column. Defaults to undefined (left).
*/
/**
- * @cfg {String} valign (Optional) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc). Defaults to undefined.
+ * @cfg {String} valign (top|bottom|middle) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc). Defaults to undefined (middle)
*/
/**
- * @cfg {String} cursor (Optional)
+ * @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)
*/
/**
- * @cfg {String} tooltip (Optional)
+ * @cfg {String} tooltip mouse over tooltip text
*/
/**
- * @cfg {Number} xs (Optional) can be '0' for hidden at this size (number less than 12)
+ * @cfg {Number} xs can be '0' for hidden at this size (number less than 12)
*/
/**
- * @cfg {Number} sm (Optional) can be '0' for hidden at this size (number less than 12)
+ * @cfg {Number} sm can be '0' for hidden at this size (number less than 12)
*/
/**
- * @cfg {Number} md (Optional) can be '0' for hidden at this size (number less than 12)
+ * @cfg {Number} md can be '0' for hidden at this size (number less than 12)
*/
/**
- * @cfg {Number} lg (Optional) can be '0' for hidden at this size (number less than 12)
+ * @cfg {Number} lg can be '0' for hidden at this size (number less than 12)
*/
/**
- * @cfg {Number} xl (Optional) can be '0' for hidden at this size (number less than 12)
+ * @cfg {Number} xl can be '0' for hidden at this size (number less than 12)
*/
/**
* Returns the id of the column at the specified index.
Roo.XTemplate.from = function(el){
el = Roo.getDom(el);
return new Roo.XTemplate(el.value || el.innerHTML);
-};
\ No newline at end of file
+};// old names for panel elements
+Roo.GridPanel = Roo.panel.Grid;
+Roo.CalendarPanel = Roo.panel.Calendar;
+Roo.ContentPanel = Roo.panel.Content;
+Roo.NestedLayoutPanel = Roo.panel.NestedLayout;
+Roo.TabPanel = Roo.panel.Tab;
+Roo.TabPanelItem = Roo.panel.TabItem;
+Roo.TreePanel = Roo.panel.Tree;
+
+
+// phase 2 update
+Roo.ScrollPanel = Roo.panel.Scroll;
+
+Roo.BorderLayout = Roo.layout.Border;
+Roo.BasicLayoutRegion = Roo.layout.BasicRegion;
+Roo.LayoutRegion = Roo.layout.Region;
+Roo.SplitLayoutRegion = Roo.layout.SplitRegion;
+Roo.LayoutManager = Roo.layout.Manager;
+
+
+Roo.NorthLayoutRegion = Roo.layout.North;
+Roo.EastLayoutRegion = Roo.layout.East;
+Roo.WestLayoutRegion = Roo.layout.West;
+Roo.SouthLayoutRegion = Roo.layout.South;
+Roo.CenterLayoutRegion = Roo.layout.Center;
+
+
+Roo.LayoutStateManager = Roo.layout.StateManager;
+Roo.ReaderLayout = Roo.layout.Reader;
+