*/
-
-/*
- * These classes are derivatives of the similarly named classes in the YUI Library.
- * The original license:
- * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
- * Code licensed under the BSD License:
- * http://developer.yahoo.net/yui/license.txt
- */
-
-(function() {
-
-var Event=Roo.EventManager;
-var Dom=Roo.lib.Dom;
-
/**
- * @class Roo.dd.DragDrop
- * @extends Roo.util.Observable
- * Defines the interface and base operation of items that that can be
- * dragged or can be drop targets. It was designed to be extended, overriding
- * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
- * Up to three html elements can be associated with a DragDrop instance:
- * <ul>
- * <li>linked element: the element that is passed into the constructor.
- * This is the element which defines the boundaries for interaction with
- * other DragDrop objects.</li>
- * <li>handle element(s): The drag operation only occurs if the element that
- * was clicked matches a handle element. By default this is the linked
- * element, but there are times that you will want only a portion of the
- * linked element to initiate the drag operation, and the setHandleElId()
- * method provides a way to define this.</li>
- * <li>drag element: this represents the element that would be moved along
- * with the cursor during a drag operation. By default, this is the linked
- * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
- * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
- * </li>
- * </ul>
- * This class should not be instantiated until the onload event to ensure that
- * the associated elements are available.
- * The following would define a DragDrop obj that would interact with any
- * other DragDrop obj in the "group1" group:
- * <pre>
- * dd = new Roo.dd.DragDrop("div1", "group1");
- * </pre>
- * Since none of the event handlers have been implemented, nothing would
- * actually happen if you were to run the code above. Normally you would
- * override this class or one of the default implementations, but you can
- * also override the methods you want on an instance of the class...
- * <pre>
- * dd.onDragDrop = function(e, id) {
- * alert("dd was dropped on " + id);
- * }
- * </pre>
- * @constructor
- * @param {String} id of the element that is linked to this instance
- * @param {String} sGroup the group of related DragDrop objects
- * @param {object} config an object containing configurable attributes
- * Valid properties for DragDrop:
- * padding, isTarget, maintainOffset, primaryButtonOnly
+ * @class Roo.data.SortTypes
+ * @singleton
+ * Defines the default sorting (casting?) comparison functions used when sorting data.
*/
-Roo.dd.DragDrop = function(id, sGroup, config) {
- if (id) {
- this.init(id, sGroup, config);
- }
-
-};
-
-Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
-
- /**
- * The id of the element associated with this object. This is what we
- * refer to as the "linked element" because the size and position of
- * this element is used to determine when the drag and drop objects have
- * interacted.
- * @property id
- * @type String
- */
- id: null,
-
- /**
- * Configuration attributes passed into the constructor
- * @property config
- * @type object
- */
- config: null,
-
- /**
- * The id of the element that will be dragged. By default this is same
- * as the linked element , but could be changed to another element. Ex:
- * Roo.dd.DDProxy
- * @property dragElId
- * @type String
- * @private
- */
- dragElId: null,
-
- /**
- * the id of the element that initiates the drag operation. By default
- * this is the linked element, but could be changed to be a child of this
- * element. This lets us do things like only starting the drag when the
- * header element within the linked html element is clicked.
- * @property handleElId
- * @type String
- * @private
- */
- handleElId: null,
-
- /**
- * An associative array of HTML tags that will be ignored if clicked.
- * @property invalidHandleTypes
- * @type {string: string}
- */
- invalidHandleTypes: null,
-
- /**
- * An associative array of ids for elements that will be ignored if clicked
- * @property invalidHandleIds
- * @type {string: string}
- */
- invalidHandleIds: null,
-
- /**
- * An indexted array of css class names for elements that will be ignored
- * if clicked.
- * @property invalidHandleClasses
- * @type string[]
- */
- invalidHandleClasses: null,
-
- /**
- * The linked element's absolute X position at the time the drag was
- * started
- * @property startPageX
- * @type int
- * @private
- */
- startPageX: 0,
-
- /**
- * The linked element's absolute X position at the time the drag was
- * started
- * @property startPageY
- * @type int
- * @private
- */
- startPageY: 0,
-
- /**
- * The group defines a logical collection of DragDrop objects that are
- * related. Instances only get events when interacting with other
- * DragDrop object in the same group. This lets us define multiple
- * groups using a single DragDrop subclass if we want.
- * @property groups
- * @type {string: string}
- */
- groups: null,
-
- /**
- * Individual drag/drop instances can be locked. This will prevent
- * onmousedown start drag.
- * @property locked
- * @type boolean
- * @private
- */
- locked: false,
-
- /**
- * Lock this instance
- * @method lock
- */
- lock: function() { this.locked = true; },
-
- /**
- * Unlock this instace
- * @method unlock
- */
- unlock: function() { this.locked = false; },
-
- /**
- * By default, all insances can be a drop target. This can be disabled by
- * setting isTarget to false.
- * @method isTarget
- * @type boolean
- */
- isTarget: true,
-
- /**
- * The padding configured for this drag and drop object for calculating
- * the drop zone intersection with this object.
- * @method padding
- * @type int[]
- */
- padding: null,
-
- /**
- * Cached reference to the linked element
- * @property _domRef
- * @private
- */
- _domRef: null,
-
- /**
- * Internal typeof flag
- * @property __ygDragDrop
- * @private
- */
- __ygDragDrop: true,
-
- /**
- * Set to true when horizontal contraints are applied
- * @property constrainX
- * @type boolean
- * @private
- */
- constrainX: false,
-
- /**
- * Set to true when vertical contraints are applied
- * @property constrainY
- * @type boolean
- * @private
- */
- constrainY: false,
-
- /**
- * The left constraint
- * @property minX
- * @type int
- * @private
- */
- minX: 0,
-
- /**
- * The right constraint
- * @property maxX
- * @type int
- * @private
- */
- maxX: 0,
-
- /**
- * The up constraint
- * @property minY
- * @type int
- * @type int
- * @private
- */
- minY: 0,
-
- /**
- * The down constraint
- * @property maxY
- * @type int
- * @private
- */
- maxY: 0,
-
- /**
- * Maintain offsets when we resetconstraints. Set to true when you want
- * the position of the element relative to its parent to stay the same
- * when the page changes
- *
- * @property maintainOffset
- * @type boolean
- */
- maintainOffset: false,
-
- /**
- * Array of pixel locations the element will snap to if we specified a
- * horizontal graduation/interval. This array is generated automatically
- * when you define a tick interval.
- * @property xTicks
- * @type int[]
- */
- xTicks: null,
-
- /**
- * Array of pixel locations the element will snap to if we specified a
- * vertical graduation/interval. This array is generated automatically
- * when you define a tick interval.
- * @property yTicks
- * @type int[]
- */
- yTicks: null,
-
- /**
- * By default the drag and drop instance will only respond to the primary
- * button click (left button for a right-handed mouse). Set to true to
- * allow drag and drop to start with any mouse click that is propogated
- * by the browser
- * @property primaryButtonOnly
- * @type boolean
- */
- primaryButtonOnly: true,
-
- /**
- * The availabe property is false until the linked dom element is accessible.
- * @property available
- * @type boolean
- */
- available: false,
-
- /**
- * By default, drags can only be initiated if the mousedown occurs in the
- * region the linked element is. This is done in part to work around a
- * bug in some browsers that mis-report the mousedown if the previous
- * mouseup happened outside of the window. This property is set to true
- * if outer handles are defined.
- *
- * @property hasOuterHandles
- * @type boolean
- * @default false
- */
- hasOuterHandles: false,
-
- /**
- * Code that executes immediately before the startDrag event
- * @method b4StartDrag
- * @private
- */
- b4StartDrag: function(x, y) { },
-
- /**
- * Abstract method called after a drag/drop object is clicked
- * and the drag or mousedown time thresholds have beeen met.
- * @method startDrag
- * @param {int} X click location
- * @param {int} Y click location
- */
- startDrag: function(x, y) { /* override this */ },
-
- /**
- * Code that executes immediately before the onDrag event
- * @method b4Drag
- * @private
- */
- b4Drag: function(e) { },
-
- /**
- * Abstract method called during the onMouseMove event while dragging an
- * object.
- * @method onDrag
- * @param {Event} e the mousemove event
- */
- onDrag: function(e) { /* override this */ },
-
- /**
- * Abstract method called when this element fist begins hovering over
- * another DragDrop obj
- * @method onDragEnter
- * @param {Event} e the mousemove event
- * @param {String|DragDrop[]} id In POINT mode, the element
- * id this is hovering over. In INTERSECT mode, an array of one or more
- * dragdrop items being hovered over.
- */
- onDragEnter: function(e, id) { /* override this */ },
-
- /**
- * Code that executes immediately before the onDragOver event
- * @method b4DragOver
- * @private
- */
- b4DragOver: function(e) { },
-
- /**
- * Abstract method called when this element is hovering over another
- * DragDrop obj
- * @method onDragOver
- * @param {Event} e the mousemove event
- * @param {String|DragDrop[]} id In POINT mode, the element
- * id this is hovering over. In INTERSECT mode, an array of dd items
- * being hovered over.
- */
- onDragOver: function(e, id) { /* override this */ },
-
- /**
- * Code that executes immediately before the onDragOut event
- * @method b4DragOut
- * @private
- */
- b4DragOut: function(e) { },
-
- /**
- * Abstract method called when we are no longer hovering over an element
- * @method onDragOut
- * @param {Event} e the mousemove event
- * @param {String|DragDrop[]} id In POINT mode, the element
- * id this was hovering over. In INTERSECT mode, an array of dd items
- * that the mouse is no longer over.
- */
- onDragOut: function(e, id) { /* override this */ },
-
- /**
- * Code that executes immediately before the onDragDrop event
- * @method b4DragDrop
- * @private
- */
- b4DragDrop: function(e) { },
-
- /**
- * Abstract method called when this item is dropped on another DragDrop
- * obj
- * @method onDragDrop
- * @param {Event} e the mouseup event
- * @param {String|DragDrop[]} id In POINT mode, the element
- * id this was dropped on. In INTERSECT mode, an array of dd items this
- * was dropped on.
- */
- onDragDrop: function(e, id) { /* override this */ },
-
- /**
- * Abstract method called when this item is dropped on an area with no
- * drop target
- * @method onInvalidDrop
- * @param {Event} e the mouseup event
- */
- onInvalidDrop: function(e) { /* override this */ },
-
- /**
- * Code that executes immediately before the endDrag event
- * @method b4EndDrag
- * @private
- */
- b4EndDrag: function(e) { },
-
- /**
- * Fired when we are done dragging the object
- * @method endDrag
- * @param {Event} e the mouseup event
- */
- endDrag: function(e) { /* override this */ },
-
- /**
- * Code executed immediately before the onMouseDown event
- * @method b4MouseDown
- * @param {Event} e the mousedown event
- * @private
- */
- b4MouseDown: function(e) { },
-
+Roo.data.SortTypes = {
/**
- * Event handler that fires when a drag/drop obj gets a mousedown
- * @method onMouseDown
- * @param {Event} e the mousedown event
+ * Default sort that does nothing
+ * @param {Mixed} s The value being converted
+ * @return {Mixed} The comparison value
*/
- onMouseDown: function(e) { /* override this */ },
-
+ none : function(s){
+ return s;
+ },
+
/**
- * Event handler that fires when a drag/drop obj gets a mouseup
- * @method onMouseUp
- * @param {Event} e the mouseup event
+ * The regular expression used to strip tags
+ * @type {RegExp}
+ * @property
*/
- onMouseUp: function(e) { /* override this */ },
-
+ stripTagsRE : /<\/?[^>]+>/gi,
+
/**
- * Override the onAvailable method to do what is needed after the initial
- * position was determined.
- * @method onAvailable
+ * Strips all HTML tags to sort on text only
+ * @param {Mixed} s The value being converted
+ * @return {String} The comparison value
*/
- onAvailable: function () {
+ asText : function(s){
+ return String(s).replace(this.stripTagsRE, "");
},
-
- /*
- * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
- * @type Object
+
+ /**
+ * Strips all HTML tags to sort on text only - Case insensitive
+ * @param {Mixed} s The value being converted
+ * @return {String} The comparison value
*/
- defaultPadding : {left:0, right:0, top:0, bottom:0},
-
- /*
- * Initializes the drag drop object's constraints to restrict movement to a certain element.
- *
- * Usage:
- <pre><code>
- var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
- { dragElId: "existingProxyDiv" });
- dd.startDrag = function(){
- this.constrainTo("parent-id");
- };
- </code></pre>
- * Or you can initalize it using the {@link Roo.Element} object:
- <pre><code>
- Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
- startDrag : function(){
- this.constrainTo("parent-id");
- }
- });
- </code></pre>
- * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
- * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
- * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
- * an object containing the sides to pad. For example: {right:10, bottom:10}
- * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
- */
- constrainTo : function(constrainTo, pad, inContent){
- if(typeof pad == "number"){
- pad = {left: pad, right:pad, top:pad, bottom:pad};
- }
- pad = pad || this.defaultPadding;
- var b = Roo.get(this.getEl()).getBox();
- var ce = Roo.get(constrainTo);
- var s = ce.getScroll();
- var c, cd = ce.dom;
- if(cd == document.body){
- c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
- }else{
- xy = ce.getXY();
- c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
- }
-
-
- var topSpace = b.y - c.y;
- var leftSpace = b.x - c.x;
-
- this.resetConstraints();
- this.setXConstraint(leftSpace - (pad.left||0), // left
- c.width - leftSpace - b.width - (pad.right||0) //right
- );
- this.setYConstraint(topSpace - (pad.top||0), //top
- c.height - topSpace - b.height - (pad.bottom||0) //bottom
- );
+ asUCText : function(s){
+ return String(s).toUpperCase().replace(this.stripTagsRE, "");
},
-
+
/**
- * Returns a reference to the linked element
- * @method getEl
- * @return {HTMLElement} the html element
+ * Case insensitive string
+ * @param {Mixed} s The value being converted
+ * @return {String} The comparison value
*/
- getEl: function() {
- if (!this._domRef) {
- this._domRef = Roo.getDom(this.id);
- }
-
- return this._domRef;
+ asUCString : function(s) {
+ return String(s).toUpperCase();
},
-
+
/**
- * Returns a reference to the actual element to drag. By default this is
- * the same as the html element, but it can be assigned to another
- * element. An example of this can be found in Roo.dd.DDProxy
- * @method getDragEl
- * @return {HTMLElement} the html element
+ * Date sorting
+ * @param {Mixed} s The value being converted
+ * @return {Number} The comparison value
*/
- getDragEl: function() {
- return Roo.getDom(this.dragElId);
+ asDate : function(s) {
+ if(!s){
+ return 0;
+ }
+ if(s instanceof Date){
+ return s.getTime();
+ }
+ return Date.parse(String(s));
},
-
+
/**
- * Sets up the DragDrop object. Must be called in the constructor of any
- * Roo.dd.DragDrop subclass
- * @method init
- * @param id the id of the linked element
- * @param {String} sGroup the group of related items
- * @param {object} config configuration attributes
+ * Float sorting
+ * @param {Mixed} s The value being converted
+ * @return {Float} The comparison value
*/
- init: function(id, sGroup, config) {
- this.initTarget(id, sGroup, config);
- if (!Roo.isTouch) {
- Event.on(this.id, "mousedown", this.handleMouseDown, this);
+ asFloat : function(s) {
+ var val = parseFloat(String(s).replace(/,/g, ""));
+ if(isNaN(val)) {
+ val = 0;
}
- Event.on(this.id, "touchstart", this.handleMouseDown, this);
- // Event.on(this.id, "selectstart", Event.preventDefault);
+ return val;
},
-
+
/**
- * Initializes Targeting functionality only... the object does not
- * get a mousedown handler.
- * @method initTarget
- * @param id the id of the linked element
- * @param {String} sGroup the group of related items
- * @param {object} config configuration attributes
+ * Integer sorting
+ * @param {Mixed} s The value being converted
+ * @return {Number} The comparison value
*/
- initTarget: function(id, sGroup, config) {
-
- // configuration attributes
- this.config = config || {};
-
- // create a local reference to the drag and drop manager
- this.DDM = Roo.dd.DDM;
- // initialize the groups array
- this.groups = {};
-
- // assume that we have an element reference instead of an id if the
- // parameter is not a string
- if (typeof id !== "string") {
- id = Roo.id(id);
+ asInt : function(s) {
+ var val = parseInt(String(s).replace(/,/g, ""));
+ if(isNaN(val)) {
+ val = 0;
}
+ return val;
+ }
+};/*
+ * 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">
+ */
- // set the id
- this.id = id;
-
- // add to an interaction group
- this.addToGroup((sGroup) ? sGroup : "default");
-
- // We don't want to register this as the handle with the manager
- // so we just set the id rather than calling the setter.
- this.handleElId = id;
-
- // the linked element is the element that gets dragged by default
- this.setDragElId(id);
-
- // by default, clicked anchors will not start drag operations.
- this.invalidHandleTypes = { A: "A" };
- this.invalidHandleIds = {};
- this.invalidHandleClasses = [];
-
- this.applyConfig();
-
- this.handleOnAvailable();
- },
+/**
+* @class Roo.data.Record
+ * Instances of this class encapsulate both record <em>definition</em> information, and record
+ * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
+ * to access Records cached in an {@link Roo.data.Store} object.<br>
+ * <p>
+ * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
+ * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
+ * objects.<br>
+ * <p>
+ * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
+ * @constructor
+ * This constructor should not be used to create Record objects. Instead, use the constructor generated by
+ * {@link #create}. The parameters are the same.
+ * @param {Array} data An associative Array of data values keyed by the field name.
+ * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
+ * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
+ * not specified an integer id is generated.
+ */
+Roo.data.Record = function(data, id){
+ this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
+ this.data = data;
+};
- /**
- * Applies the configuration parameters that were passed into the constructor.
- * This is supposed to happen at each level through the inheritance chain. So
- * a DDProxy implentation will execute apply config on DDProxy, DD, and
- * DragDrop in order to get all of the parameters that are available in
- * each object.
- * @method applyConfig
- */
- applyConfig: function() {
+/**
+ * Generate a constructor for a specific record layout.
+ * @param {Array} o An Array of field definition objects which specify field names, and optionally,
+ * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
+ * Each field definition object may contain the following properties: <ul>
+ * <li><b>name</b> : String<p style="margin-left:1em">The name by which the field is referenced within the Record. This is referenced by,
+ * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
+ * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
+ * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
+ * is being used, then this is a string containing the javascript expression to reference the data relative to
+ * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
+ * to the data item relative to the record element. If the mapping expression is the same as the field name,
+ * this may be omitted.</p></li>
+ * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
+ * <ul><li>auto (Default, implies no conversion)</li>
+ * <li>string</li>
+ * <li>int</li>
+ * <li>float</li>
+ * <li>boolean</li>
+ * <li>date</li></ul></p></li>
+ * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
+ * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
+ * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
+ * by the Reader into an object that will be stored in the Record. It is passed the
+ * following parameters:<ul>
+ * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
+ * </ul></p></li>
+ * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
+ * </ul>
+ * <br>usage:<br><pre><code>
+var TopicRecord = Roo.data.Record.create(
+ {name: 'title', mapping: 'topic_title'},
+ {name: 'author', mapping: 'username'},
+ {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
+ {name: 'lastPost', mapping: 'post_time', type: 'date'},
+ {name: 'lastPoster', mapping: 'user2'},
+ {name: 'excerpt', mapping: 'post_text'}
+);
- // configurable properties:
- // padding, isTarget, maintainOffset, primaryButtonOnly
- this.padding = this.config.padding || [0, 0, 0, 0];
- this.isTarget = (this.config.isTarget !== false);
- this.maintainOffset = (this.config.maintainOffset);
- this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
+var myNewRecord = new TopicRecord({
+ title: 'Do my job please',
+ author: 'noobie',
+ totalPosts: 1,
+ lastPost: new Date(),
+ lastPoster: 'Animal',
+ excerpt: 'No way dude!'
+});
+myStore.add(myNewRecord);
+</code></pre>
+ * @method create
+ * @static
+ */
+Roo.data.Record.create = function(o){
+ var f = function(){
+ f.superclass.constructor.apply(this, arguments);
+ };
+ Roo.extend(f, Roo.data.Record);
+ var p = f.prototype;
+ p.fields = new Roo.util.MixedCollection(false, function(field){
+ return field.name;
+ });
+ for(var i = 0, len = o.length; i < len; i++){
+ p.fields.add(new Roo.data.Field(o[i]));
+ }
+ f.getField = function(name){
+ return p.fields.get(name);
+ };
+ return f;
+};
- },
+Roo.data.Record.AUTO_ID = 1000;
+Roo.data.Record.EDIT = 'edit';
+Roo.data.Record.REJECT = 'reject';
+Roo.data.Record.COMMIT = 'commit';
+Roo.data.Record.prototype = {
/**
- * Executed when the linked element is available
- * @method handleOnAvailable
- * @private
+ * Readonly flag - true if this record has been modified.
+ * @type Boolean
*/
- handleOnAvailable: function() {
- this.available = true;
- this.resetConstraints();
- this.onAvailable();
- },
+ dirty : false,
+ editing : false,
+ error: null,
+ modified: null,
- /**
- * Configures the padding for the target zone in px. Effectively expands
- * (or reduces) the virtual object size for targeting calculations.
- * Supports css-style shorthand; if only one parameter is passed, all sides
- * will have that padding, and if only two are passed, the top and bottom
- * will have the first param, the left and right the second.
- * @method setPadding
- * @param {int} iTop Top pad
- * @param {int} iRight Right pad
- * @param {int} iBot Bot pad
- * @param {int} iLeft Left pad
- */
- setPadding: function(iTop, iRight, iBot, iLeft) {
- // this.padding = [iLeft, iRight, iTop, iBot];
- if (!iRight && 0 !== iRight) {
- this.padding = [iTop, iTop, iTop, iTop];
- } else if (!iBot && 0 !== iBot) {
- this.padding = [iTop, iRight, iTop, iRight];
- } else {
- this.padding = [iTop, iRight, iBot, iLeft];
- }
+ // private
+ join : function(store){
+ this.store = store;
},
/**
- * Stores the initial placement of the linked element.
- * @method setInitialPosition
- * @param {int} diffX the X offset, default 0
- * @param {int} diffY the Y offset, default 0
+ * Set the named field to the specified value.
+ * @param {String} name The name of the field to set.
+ * @param {Object} value The value to set the field to.
*/
- setInitPosition: function(diffX, diffY) {
- var el = this.getEl();
-
- if (!this.DDM.verifyEl(el)) {
+ set : function(name, value){
+ if(this.data[name] == value){
return;
}
-
- var dx = diffX || 0;
- var dy = diffY || 0;
-
- var p = Dom.getXY( el );
-
- this.initPageX = p[0] - dx;
- this.initPageY = p[1] - dy;
-
- this.lastPageX = p[0];
- this.lastPageY = p[1];
-
-
- this.setStartPosition(p);
+ this.dirty = true;
+ if(!this.modified){
+ this.modified = {};
+ }
+ if(typeof this.modified[name] == 'undefined'){
+ this.modified[name] = this.data[name];
+ }
+ this.data[name] = value;
+ if(!this.editing && this.store){
+ this.store.afterEdit(this);
+ }
},
/**
- * Sets the start position of the element. This is set when the obj
- * is initialized, the reset when a drag is started.
- * @method setStartPosition
- * @param pos current position (from previous lookup)
- * @private
+ * Get the value of the named field.
+ * @param {String} name The name of the field to get the value of.
+ * @return {Object} The value of the field.
*/
- setStartPosition: function(pos) {
- var p = pos || Dom.getXY( this.getEl() );
- this.deltaSetXY = null;
-
- this.startPageX = p[0];
- this.startPageY = p[1];
+ get : function(name){
+ return this.data[name];
},
- /**
- * Add this instance to a group of related drag/drop objects. All
- * instances belong to at least one group, and can belong to as many
- * groups as needed.
- * @method addToGroup
- * @param sGroup {string} the name of the group
- */
- addToGroup: function(sGroup) {
- this.groups[sGroup] = true;
- this.DDM.regDragDrop(this, sGroup);
+ // private
+ beginEdit : function(){
+ this.editing = true;
+ this.modified = {};
},
- /**
- * Remove's this instance from the supplied interaction group
- * @method removeFromGroup
- * @param {string} sGroup The group to drop
- */
- removeFromGroup: function(sGroup) {
- if (this.groups[sGroup]) {
- delete this.groups[sGroup];
- }
-
- this.DDM.removeDDFromGroup(this, sGroup);
+ // private
+ cancelEdit : function(){
+ this.editing = false;
+ delete this.modified;
},
- /**
- * Allows you to specify that an element other than the linked element
- * will be moved with the cursor during a drag
- * @method setDragElId
- * @param id {string} the id of the element that will be used to initiate the drag
- */
- setDragElId: function(id) {
- this.dragElId = id;
+ // private
+ endEdit : function(){
+ this.editing = false;
+ if(this.dirty && this.store){
+ this.store.afterEdit(this);
+ }
},
/**
- * Allows you to specify a child of the linked element that should be
- * used to initiate the drag operation. An example of this would be if
- * you have a content div with text and links. Clicking anywhere in the
- * content area would normally start the drag operation. Use this method
- * to specify that an element inside of the content div is the element
- * that starts the drag operation.
- * @method setHandleElId
- * @param id {string} the id of the element that will be used to
- * initiate the drag.
+ * Usually called by the {@link Roo.data.Store} which owns the Record.
+ * Rejects all changes made to the Record since either creation, or the last commit operation.
+ * Modified fields are reverted to their original values.
+ * <p>
+ * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
+ * of reject operations.
*/
- setHandleElId: function(id) {
- if (typeof id !== "string") {
- id = Roo.id(id);
+ reject : function(){
+ var m = this.modified;
+ for(var n in m){
+ if(typeof m[n] != "function"){
+ this.data[n] = m[n];
+ }
+ }
+ this.dirty = false;
+ delete this.modified;
+ this.editing = false;
+ if(this.store){
+ this.store.afterReject(this);
}
- this.handleElId = id;
- this.DDM.regHandle(this.id, id);
},
/**
- * Allows you to set an element outside of the linked element as a drag
- * handle
- * @method setOuterHandleElId
- * @param id the id of the element that will be used to initiate the drag
+ * Usually called by the {@link Roo.data.Store} which owns the Record.
+ * Commits all changes made to the Record since either creation, or the last commit operation.
+ * <p>
+ * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
+ * of commit operations.
*/
- setOuterHandleElId: function(id) {
- if (typeof id !== "string") {
- id = Roo.id(id);
+ commit : function(){
+ this.dirty = false;
+ delete this.modified;
+ this.editing = false;
+ if(this.store){
+ this.store.afterCommit(this);
}
- Event.on(id, "mousedown",
- this.handleMouseDown, this);
- this.setHandleElId(id);
-
- this.hasOuterHandles = true;
},
- /**
- * Remove all drag and drop hooks for this element
- * @method unreg
- */
- unreg: function() {
- Event.un(this.id, "mousedown",
- this.handleMouseDown);
- Event.un(this.id, "touchstart",
- this.handleMouseDown);
- this._domRef = null;
- this.DDM._remove(this);
+ // private
+ hasError : function(){
+ return this.error != null;
},
- destroy : function(){
- this.unreg();
+ // private
+ clearError : function(){
+ this.error = null;
},
/**
- * Returns true if this instance is locked, or the drag drop mgr is locked
- * (meaning that all drag/drop is disabled on the page.)
- * @method isLocked
- * @return {boolean} true if this obj or all drag/drop is locked, else
- * false
+ * Creates a copy of this record.
+ * @param {String} id (optional) A new record id if you don't want to use this record's id
+ * @return {Record}
*/
- isLocked: function() {
- return (this.DDM.isLocked() || this.locked);
- },
+ copy : function(newId) {
+ return new this.constructor(Roo.apply({}, this.data), newId || this.id);
+ }
+};/*
+ * 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">
+ */
- /**
- * Fired when this object is clicked
- * @method handleMouseDown
- * @param {Event} e
- * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
- * @private
- */
- handleMouseDown: function(e, oDD){
-
- if (!Roo.isTouch && this.primaryButtonOnly && e.button != 0) {
- //Roo.log('not touch/ button !=0');
- return;
- }
- if (e.browserEvent.touches && e.browserEvent.touches.length != 1) {
- return; // double touch..
- }
-
- if (this.isLocked()) {
- //Roo.log('locked');
- return;
+
+/**
+ * @class Roo.data.Store
+ * @extends Roo.util.Observable
+ * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
+ * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
+ * <p>
+ * A Store object uses an implementation of {@link Roo.data.DataProxy} to access a data object unless you call loadData() directly and pass in your data. The Store object
+ * has no knowledge of the format of the data returned by the Proxy.<br>
+ * <p>
+ * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
+ * instances from the data object. These records are cached and made available through accessor functions.
+ * @constructor
+ * Creates a new Store.
+ * @param {Object} config A config object containing the objects needed for the Store to access data,
+ * and read the data into Records.
+ */
+Roo.data.Store = function(config){
+ this.data = new Roo.util.MixedCollection(false);
+ this.data.getKey = function(o){
+ return o.id;
+ };
+ this.baseParams = {};
+ // private
+ this.paramNames = {
+ "start" : "start",
+ "limit" : "limit",
+ "sort" : "sort",
+ "dir" : "dir",
+ "multisort" : "_multisort"
+ };
+
+ if(config && config.data){
+ this.inlineData = config.data;
+ delete config.data;
+ }
+
+ Roo.apply(this, config);
+
+ if(this.reader){ // reader passed
+ this.reader = Roo.factory(this.reader, Roo.data);
+ this.reader.xmodule = this.xmodule || false;
+ if(!this.recordType){
+ this.recordType = this.reader.recordType;
+ }
+ if(this.reader.onMetaChange){
+ this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
}
+ }
- this.DDM.refreshCache(this.groups);
-// Roo.log([Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e)]);
- var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
- if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
- //Roo.log('no outer handes or not over target');
- // do nothing.
- } else {
-// Roo.log('check validator');
- if (this.clickValidator(e)) {
-// Roo.log('validate success');
- // set the initial element position
- this.setStartPosition();
+ if(this.recordType){
+ this.fields = this.recordType.prototype.fields;
+ }
+ this.modified = [];
+
+ this.addEvents({
+ /**
+ * @event datachanged
+ * Fires when the data cache has changed, and a widget which is using this Store
+ * as a Record cache should refresh its view.
+ * @param {Store} this
+ */
+ datachanged : true,
+ /**
+ * @event metachange
+ * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
+ * @param {Store} this
+ * @param {Object} meta The JSON metadata
+ */
+ metachange : true,
+ /**
+ * @event add
+ * Fires when Records have been added to the Store
+ * @param {Store} this
+ * @param {Roo.data.Record[]} records The array of Records added
+ * @param {Number} index The index at which the record(s) were added
+ */
+ add : true,
+ /**
+ * @event remove
+ * Fires when a Record has been removed from the Store
+ * @param {Store} this
+ * @param {Roo.data.Record} record The Record that was removed
+ * @param {Number} index The index at which the record was removed
+ */
+ remove : true,
+ /**
+ * @event update
+ * Fires when a Record has been updated
+ * @param {Store} this
+ * @param {Roo.data.Record} record The Record that was updated
+ * @param {String} operation The update operation being performed. Value may be one of:
+ * <pre><code>
+ Roo.data.Record.EDIT
+ Roo.data.Record.REJECT
+ Roo.data.Record.COMMIT
+ * </code></pre>
+ */
+ update : true,
+ /**
+ * @event clear
+ * Fires when the data cache has been cleared.
+ * @param {Store} this
+ */
+ clear : true,
+ /**
+ * @event beforeload
+ * Fires before a request is made for a new data object. If the beforeload handler returns false
+ * the load action will be canceled.
+ * @param {Store} this
+ * @param {Object} options The loading options that were specified (see {@link #load} for details)
+ */
+ beforeload : true,
+ /**
+ * @event beforeloadadd
+ * Fires after a new set of Records has been loaded.
+ * @param {Store} this
+ * @param {Roo.data.Record[]} records The Records that were loaded
+ * @param {Object} options The loading options that were specified (see {@link #load} for details)
+ */
+ beforeloadadd : true,
+ /**
+ * @event load
+ * Fires after a new set of Records has been loaded, before they are added to the store.
+ * @param {Store} this
+ * @param {Roo.data.Record[]} records The Records that were loaded
+ * @param {Object} options The loading options that were specified (see {@link #load} for details)
+ * @params {Object} return from reader
+ */
+ load : true,
+ /**
+ * @event loadexception
+ * Fires if an exception occurs in the Proxy during loading.
+ * Called with the signature of the Proxy's "loadexception" event.
+ * 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} jsonData from your request (normally this contains the Exception)
+ */
+ loadexception : true
+ });
+
+ if(this.proxy){
+ this.proxy = Roo.factory(this.proxy, Roo.data);
+ this.proxy.xmodule = this.xmodule || false;
+ this.relayEvents(this.proxy, ["loadexception"]);
+ }
+ this.sortToggle = {};
+ this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
+ Roo.data.Store.superclass.constructor.call(this);
- this.b4MouseDown(e);
- this.onMouseDown(e);
+ if(this.inlineData){
+ this.loadData(this.inlineData);
+ delete this.inlineData;
+ }
+};
- this.DDM.handleMouseDown(e, this);
+Roo.extend(Roo.data.Store, Roo.util.Observable, {
+ /**
+ * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
+ * without a remote query - used by combo/forms at present.
+ */
+
+ /**
+ * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
+ */
+ /**
+ * @cfg {Array} data Inline data to be loaded when the store is initialized.
+ */
+ /**
+ * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
+ * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
+ */
+ /**
+ * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
+ * on any HTTP request
+ */
+ /**
+ * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
+ */
+ /**
+ * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
+ */
+ multiSort: false,
+ /**
+ * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
+ * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
+ */
+ remoteSort : false,
- this.DDM.stopEvent(e);
- } else {
+ /**
+ * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
+ * loaded or when a record is removed. (defaults to false).
+ */
+ pruneModifiedRecords : false,
+ // private
+ lastOptions : null,
- }
+ /**
+ * Add Records to the Store and fires the add event.
+ * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
+ */
+ add : function(records){
+ records = [].concat(records);
+ for(var i = 0, len = records.length; i < len; i++){
+ records[i].join(this);
}
+ var index = this.data.length;
+ this.data.addAll(records);
+ this.fireEvent("add", this, records, index);
},
- clickValidator: function(e) {
- var target = e.getTarget();
- return ( this.isValidHandleChild(target) &&
- (this.id == this.handleElId ||
- this.DDM.handleWasClicked(target, this.id)) );
+ /**
+ * Remove a Record from the Store and fires the remove event.
+ * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
+ */
+ remove : function(record){
+ var index = this.data.indexOf(record);
+ this.data.removeAt(index);
+
+ if(this.pruneModifiedRecords){
+ this.modified.remove(record);
+ }
+ this.fireEvent("remove", this, record, index);
},
/**
- * Allows you to specify a tag name that should not start a drag operation
- * when clicked. This is designed to facilitate embedding links within a
- * drag handle that do something other than start the drag.
- * @method addInvalidHandleType
- * @param {string} tagName the type of element to exclude
+ * Remove all Records from the Store and fires the clear event.
*/
- addInvalidHandleType: function(tagName) {
- var type = tagName.toUpperCase();
- this.invalidHandleTypes[type] = type;
+ removeAll : function(){
+ this.data.clear();
+ if(this.pruneModifiedRecords){
+ this.modified = [];
+ }
+ this.fireEvent("clear", this);
},
/**
- * Lets you to specify an element id for a child of a drag handle
- * that should not initiate a drag
- * @method addInvalidHandleId
- * @param {string} id the element id of the element you wish to ignore
+ * Inserts Records to the Store at the given index and fires the add event.
+ * @param {Number} index The start index at which to insert the passed Records.
+ * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
*/
- addInvalidHandleId: function(id) {
- if (typeof id !== "string") {
- id = Roo.id(id);
+ insert : function(index, records){
+ records = [].concat(records);
+ for(var i = 0, len = records.length; i < len; i++){
+ this.data.insert(index, records[i]);
+ records[i].join(this);
}
- this.invalidHandleIds[id] = id;
+ this.fireEvent("add", this, records, index);
},
/**
- * Lets you specify a css class of elements that will not initiate a drag
- * @method addInvalidHandleClass
- * @param {string} cssClass the class of the elements you wish to ignore
+ * Get the index within the cache of the passed Record.
+ * @param {Roo.data.Record} record The Roo.data.Record object to to find.
+ * @return {Number} The index of the passed Record. Returns -1 if not found.
*/
- addInvalidHandleClass: function(cssClass) {
- this.invalidHandleClasses.push(cssClass);
+ indexOf : function(record){
+ return this.data.indexOf(record);
},
/**
- * Unsets an excluded tag name set by addInvalidHandleType
- * @method removeInvalidHandleType
- * @param {string} tagName the type of element to unexclude
+ * Get the index within the cache of the Record with the passed id.
+ * @param {String} id The id of the Record to find.
+ * @return {Number} The index of the Record. Returns -1 if not found.
*/
- removeInvalidHandleType: function(tagName) {
- var type = tagName.toUpperCase();
- // this.invalidHandleTypes[type] = null;
- delete this.invalidHandleTypes[type];
+ indexOfId : function(id){
+ return this.data.indexOfKey(id);
},
/**
- * Unsets an invalid handle id
- * @method removeInvalidHandleId
- * @param {string} id the id of the element to re-enable
+ * Get the Record with the specified id.
+ * @param {String} id The id of the Record to find.
+ * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
*/
- removeInvalidHandleId: function(id) {
- if (typeof id !== "string") {
- id = Roo.id(id);
- }
- delete this.invalidHandleIds[id];
+ getById : function(id){
+ return this.data.key(id);
},
/**
- * Unsets an invalid css class
- * @method removeInvalidHandleClass
- * @param {string} cssClass the class of the element(s) you wish to
- * re-enable
+ * Get the Record at the specified index.
+ * @param {Number} index The index of the Record to find.
+ * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
*/
- removeInvalidHandleClass: function(cssClass) {
- for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
- if (this.invalidHandleClasses[i] == cssClass) {
- delete this.invalidHandleClasses[i];
- }
- }
+ getAt : function(index){
+ return this.data.itemAt(index);
},
/**
- * Checks the tag exclusion list to see if this click should be ignored
- * @method isValidHandleChild
- * @param {HTMLElement} node the HTMLElement to evaluate
- * @return {boolean} true if this is a valid tag type, false if not
+ * Returns a range of Records between specified indices.
+ * @param {Number} startIndex (optional) The starting index (defaults to 0)
+ * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
+ * @return {Roo.data.Record[]} An array of Records
*/
- isValidHandleChild: function(node) {
-
- var valid = true;
- // var n = (node.nodeName == "#text") ? node.parentNode : node;
- var nodeName;
- try {
- nodeName = node.nodeName.toUpperCase();
- } catch(e) {
- nodeName = node.nodeName;
- }
- valid = valid && !this.invalidHandleTypes[nodeName];
- valid = valid && !this.invalidHandleIds[node.id];
-
- for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
- valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
- }
-
-
- return valid;
+ getRange : function(start, end){
+ return this.data.getRange(start, end);
+ },
+ // private
+ storeOptions : function(o){
+ o = Roo.apply({}, o);
+ delete o.callback;
+ delete o.scope;
+ this.lastOptions = o;
},
/**
- * Create the array of horizontal tick marks if an interval was specified
- * in setXConstraint().
- * @method setXTicks
- * @private
+ * Loads the Record cache from the configured Proxy using the configured Reader.
+ * <p>
+ * If using remote paging, then the first load call must specify the <em>start</em>
+ * and <em>limit</em> properties in the options.params property to establish the initial
+ * position within the dataset, and the number of Records to cache on each read from the Proxy.
+ * <p>
+ * <strong>It is important to note that for remote data sources, loading is asynchronous,
+ * and this call will return before the new data has been loaded. Perform any post-processing
+ * in a callback function, or in a "load" event handler.</strong>
+ * <p>
+ * @param {Object} options An object containing properties which control loading options:<ul>
+ * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
+ * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
+ * passed the following arguments:<ul>
+ * <li>r : Roo.data.Record[]</li>
+ * <li>options: Options object from the load call</li>
+ * <li>success: Boolean success indicator</li></ul></li>
+ * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
+ * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
+ * </ul>
*/
- setXTicks: function(iStartX, iTickSize) {
- this.xTicks = [];
- this.xTickSize = iTickSize;
-
- var tickMap = {};
-
- for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
- if (!tickMap[i]) {
- this.xTicks[this.xTicks.length] = i;
- tickMap[i] = true;
+ load : function(options){
+ options = options || {};
+ if(this.fireEvent("beforeload", this, options) !== false){
+ this.storeOptions(options);
+ var p = Roo.apply(options.params || {}, this.baseParams);
+ // if meta was not loaded from remote source.. try requesting it.
+ if (!this.reader.metaFromRemote) {
+ p._requestMeta = 1;
}
- }
-
- for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
- if (!tickMap[i]) {
- this.xTicks[this.xTicks.length] = i;
- tickMap[i] = true;
+ if(this.sortInfo && this.remoteSort){
+ var pn = this.paramNames;
+ p[pn["sort"]] = this.sortInfo.field;
+ p[pn["dir"]] = this.sortInfo.direction;
}
+ if (this.multiSort) {
+ var pn = this.paramNames;
+ p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
+ }
+
+ this.proxy.load(p, this.reader, this.loadRecords, this, options);
}
-
- this.xTicks.sort(this.DDM.numericSort) ;
},
/**
- * Create the array of vertical tick marks if an interval was specified in
- * setYConstraint().
- * @method setYTicks
- * @private
+ * Reloads the Record cache from the configured Proxy using the configured Reader and
+ * the options from the last load operation performed.
+ * @param {Object} options (optional) An object containing properties which may override the options
+ * used in the last load operation. See {@link #load} for details (defaults to null, in which case
+ * the most recently used options are reused).
*/
- setYTicks: function(iStartY, iTickSize) {
- this.yTicks = [];
- this.yTickSize = iTickSize;
-
- var tickMap = {};
+ reload : function(options){
+ this.load(Roo.applyIf(options||{}, this.lastOptions));
+ },
- for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
- if (!tickMap[i]) {
- this.yTicks[this.yTicks.length] = i;
- tickMap[i] = true;
+ // private
+ // Called as a callback by the Reader during a load operation.
+ loadRecords : function(o, options, success){
+ if(!o || success === false){
+ if(success !== false){
+ this.fireEvent("load", this, [], options, o);
+ }
+ if(options.callback){
+ options.callback.call(options.scope || this, [], options, false);
}
+ return;
}
-
- for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
- if (!tickMap[i]) {
- this.yTicks[this.yTicks.length] = i;
- tickMap[i] = true;
+ // if data returned failure - throw an exception.
+ if (o.success === false) {
+ // show a message if no listener is registered.
+ if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
+ Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
+ }
+ // loadmask wil be hooked into this..
+ this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
+ return;
+ }
+ var r = o.records, t = o.totalRecords || r.length;
+
+ this.fireEvent("beforeloadadd", this, r, options, o);
+
+ if(!options || options.add !== true){
+ if(this.pruneModifiedRecords){
+ this.modified = [];
+ }
+ for(var i = 0, len = r.length; i < len; i++){
+ r[i].join(this);
}
+ if(this.snapshot){
+ this.data = this.snapshot;
+ delete this.snapshot;
+ }
+ this.data.clear();
+ this.data.addAll(r);
+ this.totalLength = t;
+ this.applySort();
+ this.fireEvent("datachanged", this);
+ }else{
+ this.totalLength = Math.max(t, this.data.length+r.length);
+ this.add(r);
}
+
+ if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
+
+ var e = new Roo.data.Record({});
- this.yTicks.sort(this.DDM.numericSort) ;
+ e.set(this.parent.displayField, this.parent.emptyTitle);
+ e.set(this.parent.valueField, '');
+
+ this.insert(0, e);
+ }
+
+ this.fireEvent("load", this, r, options, o);
+ if(options.callback){
+ options.callback.call(options.scope || this, r, options, true);
+ }
},
+
/**
- * By default, the element can be dragged any place on the screen. Use
- * this method to limit the horizontal travel of the element. Pass in
- * 0,0 for the parameters if you want to lock the drag to the y axis.
- * @method setXConstraint
- * @param {int} iLeft the number of pixels the element can move to the left
- * @param {int} iRight the number of pixels the element can move to the
- * right
- * @param {int} iTickSize optional parameter for specifying that the
- * element
- * should move iTickSize pixels at a time.
+ * Loads data from a passed data block. A Reader which understands the format of the data
+ * must have been configured in the constructor.
+ * @param {Object} data The data block from which to read the Records. The format of the data expected
+ * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
+ * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
*/
- setXConstraint: function(iLeft, iRight, iTickSize) {
- this.leftConstraint = iLeft;
- this.rightConstraint = iRight;
-
- this.minX = this.initPageX - iLeft;
- this.maxX = this.initPageX + iRight;
- if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
-
- this.constrainX = true;
+ loadData : function(o, append){
+ var r = this.reader.readRecords(o);
+ this.loadRecords(r, {add: append}, true);
},
+
+ /**
+ * using 'cn' the nested child reader read the child array into it's child stores.
+ * @param {Object} rec The record with a 'children array
+ */
+ loadDataFromChildren : function(rec)
+ {
+ this.loadData(this.reader.toLoadData(rec));
+ },
+
/**
- * Clears any constraints applied to this instance. Also clears ticks
- * since they can't exist independent of a constraint at this time.
- * @method clearConstraints
+ * Gets the number of cached records.
+ * <p>
+ * <em>If using paging, this may not be the total size of the dataset. If the data object
+ * used by the Reader contains the dataset size, then the getTotalCount() function returns
+ * the data set size</em>
*/
- clearConstraints: function() {
- this.constrainX = false;
- this.constrainY = false;
- this.clearTicks();
+ getCount : function(){
+ return this.data.length || 0;
},
/**
- * Clears any tick interval defined for this instance
- * @method clearTicks
+ * Gets the total number of records in the dataset as returned by the server.
+ * <p>
+ * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
+ * the dataset size</em>
*/
- clearTicks: function() {
- this.xTicks = null;
- this.yTicks = null;
- this.xTickSize = 0;
- this.yTickSize = 0;
+ getTotalCount : function(){
+ return this.totalLength || 0;
},
/**
- * By default, the element can be dragged any place on the screen. Set
- * this to limit the vertical travel of the element. Pass in 0,0 for the
- * parameters if you want to lock the drag to the x axis.
- * @method setYConstraint
- * @param {int} iUp the number of pixels the element can move up
- * @param {int} iDown the number of pixels the element can move down
- * @param {int} iTickSize optional parameter for specifying that the
- * element should move iTickSize pixels at a time.
+ * Returns the sort state of the Store as an object with two properties:
+ * <pre><code>
+ field {String} The name of the field by which the Records are sorted
+ direction {String} The sort order, "ASC" or "DESC"
+ * </code></pre>
*/
- setYConstraint: function(iUp, iDown, iTickSize) {
- this.topConstraint = iUp;
- this.bottomConstraint = iDown;
-
- this.minY = this.initPageY - iUp;
- this.maxY = this.initPageY + iDown;
- if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
-
- this.constrainY = true;
+ getSortState : function(){
+ return this.sortInfo;
+ },
+ // private
+ applySort : function(){
+ if(this.sortInfo && !this.remoteSort){
+ var s = this.sortInfo, f = s.field;
+ var st = this.fields.get(f).sortType;
+ var fn = function(r1, r2){
+ var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
+ return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
+ };
+ this.data.sort(s.direction, fn);
+ if(this.snapshot && this.snapshot != this.data){
+ this.snapshot.sort(s.direction, fn);
+ }
+ }
},
/**
- * resetConstraints must be called if you manually reposition a dd element.
- * @method resetConstraints
- * @param {boolean} maintainOffset
+ * Sets the default sort column and order to be used by the next load operation.
+ * @param {String} fieldName The name of the field to sort by.
+ * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
*/
- resetConstraints: function() {
-
-
- // Maintain offsets if necessary
- if (this.initPageX || this.initPageX === 0) {
- // figure out how much this thing has moved
- var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
- var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
-
- this.setInitPosition(dx, dy);
+ setDefaultSort : function(field, dir){
+ this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
+ },
- // This is the first time we have detected the element's position
- } else {
- this.setInitPosition();
+ /**
+ * Sort the Records.
+ * If remote sorting is used, the sort is performed on the server, and the cache is
+ * reloaded. If local sorting is used, the cache is sorted internally.
+ * @param {String} fieldName The name of the field to sort by.
+ * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
+ */
+ sort : function(fieldName, dir){
+ var f = this.fields.get(fieldName);
+ if(!dir){
+ this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
+
+ if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
+ dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
+ }else{
+ dir = f.sortDir;
+ }
}
-
- if (this.constrainX) {
- this.setXConstraint( this.leftConstraint,
- this.rightConstraint,
- this.xTickSize );
+ this.sortToggle[f.name] = dir;
+ this.sortInfo = {field: f.name, direction: dir};
+ if(!this.remoteSort){
+ this.applySort();
+ this.fireEvent("datachanged", this);
+ }else{
+ this.load(this.lastOptions);
}
+ },
- if (this.constrainY) {
- this.setYConstraint( this.topConstraint,
- this.bottomConstraint,
- this.yTickSize );
- }
+ /**
+ * Calls the specified function for each of the Records in the cache.
+ * @param {Function} fn The function to call. The Record is passed as the first parameter.
+ * Returning <em>false</em> aborts and exits the iteration.
+ * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
+ */
+ each : function(fn, scope){
+ this.data.each(fn, scope);
},
/**
- * Normally the drag element is moved pixel by pixel, but we can specify
- * that it move a number of pixels at a time. This method resolves the
- * location when we have it set up like this.
- * @method getTick
- * @param {int} val where we want to place the object
- * @param {int[]} tickArray sorted array of valid points
- * @return {int} the closest tick
- * @private
+ * Gets all records modified since the last commit. Modified records are persisted across load operations
+ * (e.g., during paging).
+ * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
*/
- getTick: function(val, tickArray) {
+ getModifiedRecords : function(){
+ return this.modified;
+ },
- if (!tickArray) {
- // If tick interval is not defined, it is effectively 1 pixel,
- // so we return the value passed to us.
- return val;
- } else if (tickArray[0] >= val) {
- // The value is lower than the first tick, so we return the first
- // tick.
- return tickArray[0];
- } else {
- for (var i=0, len=tickArray.length; i<len; ++i) {
- var next = i + 1;
- if (tickArray[next] && tickArray[next] >= val) {
- var diff1 = val - tickArray[i];
- var diff2 = tickArray[next] - val;
- return (diff2 > diff1) ? tickArray[i] : tickArray[next];
- }
+ // private
+ createFilterFn : function(property, value, anyMatch){
+ if(!value.exec){ // not a regex
+ value = String(value);
+ if(value.length == 0){
+ return false;
}
-
- // The value is larger than the last tick, so we return the last
- // tick.
- return tickArray[tickArray.length - 1];
+ value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
}
- },
-
- /**
- * toString method
- * @method toString
- * @return {string} string representation of the dd obj
- */
- toString: function() {
- return ("DragDrop " + this.id);
- }
-
-});
-
-})();
-/*
- * 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">
- */
-
-
-/**
- * The drag and drop utility provides a framework for building drag and drop
- * applications. In addition to enabling drag and drop for specific elements,
- * the drag and drop elements are tracked by the manager class, and the
- * interactions between the various elements are tracked during the drag and
- * the implementing code is notified about these important moments.
- */
-
-// Only load the library once. Rewriting the manager class would orphan
-// existing drag and drop instances.
-if (!Roo.dd.DragDropMgr) {
-
-/**
- * @class Roo.dd.DragDropMgr
- * DragDropMgr is a singleton that tracks the element interaction for
- * all DragDrop items in the window. Generally, you will not call
- * this class directly, but it does have helper methods that could
- * be useful in your DragDrop implementations.
- * @singleton
- */
-Roo.dd.DragDropMgr = function() {
-
- var Event = Roo.EventManager;
-
- return {
-
- /**
- * Two dimensional Array of registered DragDrop objects. The first
- * dimension is the DragDrop item group, the second the DragDrop
- * object.
- * @property ids
- * @type {string: string}
- * @private
- * @static
- */
- ids: {},
-
- /**
- * Array of element ids defined as drag handles. Used to determine
- * if the element that generated the mousedown event is actually the
- * handle and not the html element itself.
- * @property handleIds
- * @type {string: string}
- * @private
- * @static
- */
- handleIds: {},
-
- /**
- * the DragDrop object that is currently being dragged
- * @property dragCurrent
- * @type DragDrop
- * @private
- * @static
- **/
- dragCurrent: null,
-
- /**
- * the DragDrop object(s) that are being hovered over
- * @property dragOvers
- * @type Array
- * @private
- * @static
- */
- dragOvers: {},
-
- /**
- * the X distance between the cursor and the object being dragged
- * @property deltaX
- * @type int
- * @private
- * @static
- */
- deltaX: 0,
-
- /**
- * the Y distance between the cursor and the object being dragged
- * @property deltaY
- * @type int
- * @private
- * @static
- */
- deltaY: 0,
-
- /**
- * Flag to determine if we should prevent the default behavior of the
- * events we define. By default this is true, but this can be set to
- * false if you need the default behavior (not recommended)
- * @property preventDefault
- * @type boolean
- * @static
- */
- preventDefault: true,
-
- /**
- * Flag to determine if we should stop the propagation of the events
- * we generate. This is true by default but you may want to set it to
- * false if the html element contains other features that require the
- * mouse click.
- * @property stopPropagation
- * @type boolean
- * @static
- */
- stopPropagation: true,
-
- /**
- * Internal flag that is set to true when drag and drop has been
- * intialized
- * @property initialized
- * @private
- * @static
- */
- initalized: false,
-
- /**
- * All drag and drop can be disabled.
- * @property locked
- * @private
- * @static
- */
- locked: false,
-
- /**
- * Called the first time an element is registered.
- * @method init
- * @private
- * @static
- */
- init: function() {
- this.initialized = true;
- },
-
- /**
- * In point mode, drag and drop interaction is defined by the
- * location of the cursor during the drag/drop
- * @property POINT
- * @type int
- * @static
- */
- POINT: 0,
-
- /**
- * In intersect mode, drag and drop interactio nis defined by the
- * overlap of two or more drag and drop objects.
- * @property INTERSECT
- * @type int
- * @static
- */
- INTERSECT: 1,
-
- /**
- * The current drag and drop mode. Default: POINT
- * @property mode
- * @type int
- * @static
- */
- mode: 0,
-
- /**
- * Runs method on all drag and drop objects
- * @method _execOnAll
- * @private
- * @static
- */
- _execOnAll: function(sMethod, args) {
- for (var i in this.ids) {
- for (var j in this.ids[i]) {
- var oDD = this.ids[i][j];
- if (! this.isTypeOfDD(oDD)) {
- continue;
- }
- oDD[sMethod].apply(oDD, args);
- }
- }
- },
-
- /**
- * Drag and drop initialization. Sets up the global event handlers
- * @method _onLoad
- * @private
- * @static
- */
- _onLoad: function() {
-
- this.init();
-
- if (!Roo.isTouch) {
- Event.on(document, "mouseup", this.handleMouseUp, this, true);
- Event.on(document, "mousemove", this.handleMouseMove, this, true);
- }
- Event.on(document, "touchend", this.handleMouseUp, this, true);
- Event.on(document, "touchmove", this.handleMouseMove, this, true);
-
- Event.on(window, "unload", this._onUnload, this, true);
- Event.on(window, "resize", this._onResize, this, true);
- // Event.on(window, "mouseout", this._test);
-
- },
-
- /**
- * Reset constraints on all drag and drop objs
- * @method _onResize
- * @private
- * @static
- */
- _onResize: function(e) {
- this._execOnAll("resetConstraints", []);
- },
-
- /**
- * Lock all drag and drop functionality
- * @method lock
- * @static
- */
- lock: function() { this.locked = true; },
-
- /**
- * Unlock all drag and drop functionality
- * @method unlock
- * @static
- */
- unlock: function() { this.locked = false; },
-
- /**
- * Is drag and drop locked?
- * @method isLocked
- * @return {boolean} True if drag and drop is locked, false otherwise.
- * @static
- */
- isLocked: function() { return this.locked; },
-
- /**
- * Location cache that is set for all drag drop objects when a drag is
- * initiated, cleared when the drag is finished.
- * @property locationCache
- * @private
- * @static
- */
- locationCache: {},
-
- /**
- * Set useCache to false if you want to force object the lookup of each
- * drag and drop linked element constantly during a drag.
- * @property useCache
- * @type boolean
- * @static
- */
- useCache: true,
-
- /**
- * The number of pixels that the mouse needs to move after the
- * mousedown before the drag is initiated. Default=3;
- * @property clickPixelThresh
- * @type int
- * @static
- */
- clickPixelThresh: 3,
-
- /**
- * The number of milliseconds after the mousedown event to initiate the
- * drag if we don't get a mouseup event. Default=1000
- * @property clickTimeThresh
- * @type int
- * @static
- */
- clickTimeThresh: 350,
-
- /**
- * Flag that indicates that either the drag pixel threshold or the
- * mousdown time threshold has been met
- * @property dragThreshMet
- * @type boolean
- * @private
- * @static
- */
- dragThreshMet: false,
-
- /**
- * Timeout used for the click time threshold
- * @property clickTimeout
- * @type Object
- * @private
- * @static
- */
- clickTimeout: null,
-
- /**
- * The X position of the mousedown event stored for later use when a
- * drag threshold is met.
- * @property startX
- * @type int
- * @private
- * @static
- */
- startX: 0,
-
- /**
- * The Y position of the mousedown event stored for later use when a
- * drag threshold is met.
- * @property startY
- * @type int
- * @private
- * @static
- */
- startY: 0,
-
- /**
- * Each DragDrop instance must be registered with the DragDropMgr.
- * This is executed in DragDrop.init()
- * @method regDragDrop
- * @param {DragDrop} oDD the DragDrop object to register
- * @param {String} sGroup the name of the group this element belongs to
- * @static
- */
- regDragDrop: function(oDD, sGroup) {
- if (!this.initialized) { this.init(); }
-
- if (!this.ids[sGroup]) {
- this.ids[sGroup] = {};
- }
- this.ids[sGroup][oDD.id] = oDD;
- },
-
- /**
- * Removes the supplied dd instance from the supplied group. Executed
- * by DragDrop.removeFromGroup, so don't call this function directly.
- * @method removeDDFromGroup
- * @private
- * @static
- */
- removeDDFromGroup: function(oDD, sGroup) {
- if (!this.ids[sGroup]) {
- this.ids[sGroup] = {};
- }
-
- var obj = this.ids[sGroup];
- if (obj && obj[oDD.id]) {
- delete obj[oDD.id];
- }
- },
-
- /**
- * Unregisters a drag and drop item. This is executed in
- * DragDrop.unreg, use that method instead of calling this directly.
- * @method _remove
- * @private
- * @static
- */
- _remove: function(oDD) {
- for (var g in oDD.groups) {
- if (g && this.ids[g][oDD.id]) {
- delete this.ids[g][oDD.id];
- }
- }
- delete this.handleIds[oDD.id];
- },
-
- /**
- * Each DragDrop handle element must be registered. This is done
- * automatically when executing DragDrop.setHandleElId()
- * @method regHandle
- * @param {String} sDDId the DragDrop id this element is a handle for
- * @param {String} sHandleId the id of the element that is the drag
- * handle
- * @static
- */
- regHandle: function(sDDId, sHandleId) {
- if (!this.handleIds[sDDId]) {
- this.handleIds[sDDId] = {};
- }
- this.handleIds[sDDId][sHandleId] = sHandleId;
- },
-
- /**
- * Utility function to determine if a given element has been
- * registered as a drag drop item.
- * @method isDragDrop
- * @param {String} id the element id to check
- * @return {boolean} true if this element is a DragDrop item,
- * false otherwise
- * @static
- */
- isDragDrop: function(id) {
- return ( this.getDDById(id) ) ? true : false;
- },
-
- /**
- * Returns the drag and drop instances that are in all groups the
- * passed in instance belongs to.
- * @method getRelated
- * @param {DragDrop} p_oDD the obj to get related data for
- * @param {boolean} bTargetsOnly if true, only return targetable objs
- * @return {DragDrop[]} the related instances
- * @static
- */
- getRelated: function(p_oDD, bTargetsOnly) {
- var oDDs = [];
- for (var i in p_oDD.groups) {
- for (j in this.ids[i]) {
- var dd = this.ids[i][j];
- if (! this.isTypeOfDD(dd)) {
- continue;
- }
- if (!bTargetsOnly || dd.isTarget) {
- oDDs[oDDs.length] = dd;
- }
- }
- }
-
- return oDDs;
- },
-
- /**
- * Returns true if the specified dd target is a legal target for
- * the specifice drag obj
- * @method isLegalTarget
- * @param {DragDrop} the drag obj
- * @param {DragDrop} the target
- * @return {boolean} true if the target is a legal target for the
- * dd obj
- * @static
- */
- isLegalTarget: function (oDD, oTargetDD) {
- var targets = this.getRelated(oDD, true);
- for (var i=0, len=targets.length;i<len;++i) {
- if (targets[i].id == oTargetDD.id) {
- return true;
- }
- }
-
- return false;
- },
-
- /**
- * My goal is to be able to transparently determine if an object is
- * typeof DragDrop, and the exact subclass of DragDrop. typeof
- * returns "object", oDD.constructor.toString() always returns
- * "DragDrop" and not the name of the subclass. So for now it just
- * evaluates a well-known variable in DragDrop.
- * @method isTypeOfDD
- * @param {Object} the object to evaluate
- * @return {boolean} true if typeof oDD = DragDrop
- * @static
- */
- isTypeOfDD: function (oDD) {
- return (oDD && oDD.__ygDragDrop);
- },
-
- /**
- * Utility function to determine if a given element has been
- * registered as a drag drop handle for the given Drag Drop object.
- * @method isHandle
- * @param {String} id the element id to check
- * @return {boolean} true if this element is a DragDrop handle, false
- * otherwise
- * @static
- */
- isHandle: function(sDDId, sHandleId) {
- return ( this.handleIds[sDDId] &&
- this.handleIds[sDDId][sHandleId] );
- },
-
- /**
- * Returns the DragDrop instance for a given id
- * @method getDDById
- * @param {String} id the id of the DragDrop object
- * @return {DragDrop} the drag drop object, null if it is not found
- * @static
- */
- getDDById: function(id) {
- for (var i in this.ids) {
- if (this.ids[i][id]) {
- return this.ids[i][id];
- }
- }
- return null;
- },
-
- /**
- * Fired after a registered DragDrop object gets the mousedown event.
- * Sets up the events required to track the object being dragged
- * @method handleMouseDown
- * @param {Event} e the event
- * @param oDD the DragDrop object being dragged
- * @private
- * @static
- */
- handleMouseDown: function(e, oDD) {
- if(Roo.QuickTips){
- Roo.QuickTips.disable();
- }
- this.currentTarget = e.getTarget();
-
- this.dragCurrent = oDD;
-
- var el = oDD.getEl();
-
- // track start position
- this.startX = e.getPageX();
- this.startY = e.getPageY();
-
- this.deltaX = this.startX - el.offsetLeft;
- this.deltaY = this.startY - el.offsetTop;
-
- this.dragThreshMet = false;
-
- this.clickTimeout = setTimeout(
- function() {
- var DDM = Roo.dd.DDM;
- DDM.startDrag(DDM.startX, DDM.startY);
- },
- this.clickTimeThresh );
- },
-
- /**
- * Fired when either the drag pixel threshol or the mousedown hold
- * time threshold has been met.
- * @method startDrag
- * @param x {int} the X position of the original mousedown
- * @param y {int} the Y position of the original mousedown
- * @static
- */
- startDrag: function(x, y) {
- clearTimeout(this.clickTimeout);
- if (this.dragCurrent) {
- this.dragCurrent.b4StartDrag(x, y);
- this.dragCurrent.startDrag(x, y);
- }
- this.dragThreshMet = true;
- },
-
- /**
- * Internal function to handle the mouseup event. Will be invoked
- * from the context of the document.
- * @method handleMouseUp
- * @param {Event} e the event
- * @private
- * @static
- */
- handleMouseUp: function(e) {
-
- if(Roo.QuickTips){
- Roo.QuickTips.enable();
- }
- if (! this.dragCurrent) {
- return;
- }
-
- clearTimeout(this.clickTimeout);
-
- if (this.dragThreshMet) {
- this.fireEvents(e, true);
- } else {
- }
-
- this.stopDrag(e);
-
- this.stopEvent(e);
- },
-
- /**
- * Utility to stop event propagation and event default, if these
- * features are turned on.
- * @method stopEvent
- * @param {Event} e the event as returned by this.getEvent()
- * @static
- */
- stopEvent: function(e){
- if(this.stopPropagation) {
- e.stopPropagation();
- }
-
- if (this.preventDefault) {
- e.preventDefault();
- }
- },
-
- /**
- * Internal function to clean up event handlers after the drag
- * operation is complete
- * @method stopDrag
- * @param {Event} e the event
- * @private
- * @static
- */
- stopDrag: function(e) {
- // Fire the drag end event for the item that was dragged
- if (this.dragCurrent) {
- if (this.dragThreshMet) {
- this.dragCurrent.b4EndDrag(e);
- this.dragCurrent.endDrag(e);
- }
-
- this.dragCurrent.onMouseUp(e);
- }
-
- this.dragCurrent = null;
- this.dragOvers = {};
- },
-
- /**
- * Internal function to handle the mousemove event. Will be invoked
- * from the context of the html element.
- *
- * @TODO figure out what we can do about mouse events lost when the
- * user drags objects beyond the window boundary. Currently we can
- * detect this in internet explorer by verifying that the mouse is
- * down during the mousemove event. Firefox doesn't give us the
- * button state on the mousemove event.
- * @method handleMouseMove
- * @param {Event} e the event
- * @private
- * @static
- */
- handleMouseMove: function(e) {
- if (! this.dragCurrent) {
- return true;
- }
-
- // var button = e.which || e.button;
-
- // check for IE mouseup outside of page boundary
- if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
- this.stopEvent(e);
- return this.handleMouseUp(e);
- }
-
- if (!this.dragThreshMet) {
- var diffX = Math.abs(this.startX - e.getPageX());
- var diffY = Math.abs(this.startY - e.getPageY());
- if (diffX > this.clickPixelThresh ||
- diffY > this.clickPixelThresh) {
- this.startDrag(this.startX, this.startY);
- }
- }
-
- if (this.dragThreshMet) {
- this.dragCurrent.b4Drag(e);
- this.dragCurrent.onDrag(e);
- if(!this.dragCurrent.moveOnly){
- this.fireEvents(e, false);
- }
- }
-
- this.stopEvent(e);
-
- return true;
- },
-
- /**
- * Iterates over all of the DragDrop elements to find ones we are
- * hovering over or dropping on
- * @method fireEvents
- * @param {Event} e the event
- * @param {boolean} isDrop is this a drop op or a mouseover op?
- * @private
- * @static
- */
- fireEvents: function(e, isDrop) {
- var dc = this.dragCurrent;
-
- // If the user did the mouse up outside of the window, we could
- // get here even though we have ended the drag.
- if (!dc || dc.isLocked()) {
- return;
- }
-
- var pt = e.getPoint();
-
- // cache the previous dragOver array
- var oldOvers = [];
-
- var outEvts = [];
- var overEvts = [];
- var dropEvts = [];
- var enterEvts = [];
-
- // Check to see if the object(s) we were hovering over is no longer
- // being hovered over so we can fire the onDragOut event
- for (var i in this.dragOvers) {
-
- var ddo = this.dragOvers[i];
-
- if (! this.isTypeOfDD(ddo)) {
- continue;
- }
-
- if (! this.isOverTarget(pt, ddo, this.mode)) {
- outEvts.push( ddo );
- }
-
- oldOvers[i] = true;
- delete this.dragOvers[i];
- }
-
- for (var sGroup in dc.groups) {
-
- if ("string" != typeof sGroup) {
- continue;
- }
-
- for (i in this.ids[sGroup]) {
- var oDD = this.ids[sGroup][i];
- if (! this.isTypeOfDD(oDD)) {
- continue;
- }
-
- if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
- if (this.isOverTarget(pt, oDD, this.mode)) {
- // look for drop interactions
- if (isDrop) {
- dropEvts.push( oDD );
- // look for drag enter and drag over interactions
- } else {
-
- // initial drag over: dragEnter fires
- if (!oldOvers[oDD.id]) {
- enterEvts.push( oDD );
- // subsequent drag overs: dragOver fires
- } else {
- overEvts.push( oDD );
- }
-
- this.dragOvers[oDD.id] = oDD;
- }
- }
- }
- }
- }
-
- if (this.mode) {
- if (outEvts.length) {
- dc.b4DragOut(e, outEvts);
- dc.onDragOut(e, outEvts);
- }
-
- if (enterEvts.length) {
- dc.onDragEnter(e, enterEvts);
- }
-
- if (overEvts.length) {
- dc.b4DragOver(e, overEvts);
- dc.onDragOver(e, overEvts);
- }
-
- if (dropEvts.length) {
- dc.b4DragDrop(e, dropEvts);
- dc.onDragDrop(e, dropEvts);
- }
-
- } else {
- // fire dragout events
- var len = 0;
- for (i=0, len=outEvts.length; i<len; ++i) {
- dc.b4DragOut(e, outEvts[i].id);
- dc.onDragOut(e, outEvts[i].id);
- }
-
- // fire enter events
- for (i=0,len=enterEvts.length; i<len; ++i) {
- // dc.b4DragEnter(e, oDD.id);
- dc.onDragEnter(e, enterEvts[i].id);
- }
-
- // fire over events
- for (i=0,len=overEvts.length; i<len; ++i) {
- dc.b4DragOver(e, overEvts[i].id);
- dc.onDragOver(e, overEvts[i].id);
- }
-
- // fire drop events
- for (i=0, len=dropEvts.length; i<len; ++i) {
- dc.b4DragDrop(e, dropEvts[i].id);
- dc.onDragDrop(e, dropEvts[i].id);
- }
-
- }
-
- // notify about a drop that did not find a target
- if (isDrop && !dropEvts.length) {
- dc.onInvalidDrop(e);
- }
-
- },
-
- /**
- * Helper function for getting the best match from the list of drag
- * and drop objects returned by the drag and drop events when we are
- * in INTERSECT mode. It returns either the first object that the
- * cursor is over, or the object that has the greatest overlap with
- * the dragged element.
- * @method getBestMatch
- * @param {DragDrop[]} dds The array of drag and drop objects
- * targeted
- * @return {DragDrop} The best single match
- * @static
- */
- getBestMatch: function(dds) {
- var winner = null;
- // Return null if the input is not what we expect
- //if (!dds || !dds.length || dds.length == 0) {
- // winner = null;
- // If there is only one item, it wins
- //} else if (dds.length == 1) {
-
- var len = dds.length;
-
- if (len == 1) {
- winner = dds[0];
- } else {
- // Loop through the targeted items
- for (var i=0; i<len; ++i) {
- var dd = dds[i];
- // If the cursor is over the object, it wins. If the
- // cursor is over multiple matches, the first one we come
- // to wins.
- if (dd.cursorIsOver) {
- winner = dd;
- break;
- // Otherwise the object with the most overlap wins
- } else {
- if (!winner ||
- winner.overlap.getArea() < dd.overlap.getArea()) {
- winner = dd;
- }
- }
- }
- }
-
- return winner;
- },
-
- /**
- * Refreshes the cache of the top-left and bottom-right points of the
- * drag and drop objects in the specified group(s). This is in the
- * format that is stored in the drag and drop instance, so typical
- * usage is:
- * <code>
- * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
- * </code>
- * Alternatively:
- * <code>
- * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
- * </code>
- * @TODO this really should be an indexed array. Alternatively this
- * method could accept both.
- * @method refreshCache
- * @param {Object} groups an associative array of groups to refresh
- * @static
- */
- refreshCache: function(groups) {
- for (var sGroup in groups) {
- if ("string" != typeof sGroup) {
- continue;
- }
- for (var i in this.ids[sGroup]) {
- var oDD = this.ids[sGroup][i];
-
- if (this.isTypeOfDD(oDD)) {
- // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
- var loc = this.getLocation(oDD);
- if (loc) {
- this.locationCache[oDD.id] = loc;
- } else {
- delete this.locationCache[oDD.id];
- // this will unregister the drag and drop object if
- // the element is not in a usable state
- // oDD.unreg();
- }
- }
- }
- }
- },
-
- /**
- * This checks to make sure an element exists and is in the DOM. The
- * main purpose is to handle cases where innerHTML is used to remove
- * drag and drop objects from the DOM. IE provides an 'unspecified
- * error' when trying to access the offsetParent of such an element
- * @method verifyEl
- * @param {HTMLElement} el the element to check
- * @return {boolean} true if the element looks usable
- * @static
- */
- verifyEl: function(el) {
- if (el) {
- var parent;
- if(Roo.isIE){
- try{
- parent = el.offsetParent;
- }catch(e){}
- }else{
- parent = el.offsetParent;
- }
- if (parent) {
- return true;
- }
- }
-
- return false;
- },
-
- /**
- * Returns a Region object containing the drag and drop element's position
- * and size, including the padding configured for it
- * @method getLocation
- * @param {DragDrop} oDD the drag and drop object to get the
- * location for
- * @return {Roo.lib.Region} a Region object representing the total area
- * the element occupies, including any padding
- * the instance is configured for.
- * @static
- */
- getLocation: function(oDD) {
- if (! this.isTypeOfDD(oDD)) {
- return null;
- }
-
- var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
-
- try {
- pos= Roo.lib.Dom.getXY(el);
- } catch (e) { }
-
- if (!pos) {
- return null;
- }
-
- x1 = pos[0];
- x2 = x1 + el.offsetWidth;
- y1 = pos[1];
- y2 = y1 + el.offsetHeight;
-
- t = y1 - oDD.padding[0];
- r = x2 + oDD.padding[1];
- b = y2 + oDD.padding[2];
- l = x1 - oDD.padding[3];
-
- return new Roo.lib.Region( t, r, b, l );
- },
-
- /**
- * Checks the cursor location to see if it over the target
- * @method isOverTarget
- * @param {Roo.lib.Point} pt The point to evaluate
- * @param {DragDrop} oTarget the DragDrop object we are inspecting
- * @return {boolean} true if the mouse is over the target
- * @private
- * @static
- */
- isOverTarget: function(pt, oTarget, intersect) {
- // use cache if available
- var loc = this.locationCache[oTarget.id];
- if (!loc || !this.useCache) {
- loc = this.getLocation(oTarget);
- this.locationCache[oTarget.id] = loc;
-
- }
-
- if (!loc) {
- return false;
- }
-
- oTarget.cursorIsOver = loc.contains( pt );
-
- // DragDrop is using this as a sanity check for the initial mousedown
- // in this case we are done. In POINT mode, if the drag obj has no
- // contraints, we are also done. Otherwise we need to evaluate the
- // location of the target as related to the actual location of the
- // dragged element.
- var dc = this.dragCurrent;
- if (!dc || !dc.getTargetCoord ||
- (!intersect && !dc.constrainX && !dc.constrainY)) {
- return oTarget.cursorIsOver;
- }
-
- oTarget.overlap = null;
-
- // Get the current location of the drag element, this is the
- // location of the mouse event less the delta that represents
- // where the original mousedown happened on the element. We
- // need to consider constraints and ticks as well.
- var pos = dc.getTargetCoord(pt.x, pt.y);
-
- var el = dc.getDragEl();
- var curRegion = new Roo.lib.Region( pos.y,
- pos.x + el.offsetWidth,
- pos.y + el.offsetHeight,
- pos.x );
-
- var overlap = curRegion.intersect(loc);
-
- if (overlap) {
- oTarget.overlap = overlap;
- return (intersect) ? true : oTarget.cursorIsOver;
- } else {
- return false;
- }
- },
-
- /**
- * unload event handler
- * @method _onUnload
- * @private
- * @static
- */
- _onUnload: function(e, me) {
- Roo.dd.DragDropMgr.unregAll();
- },
-
- /**
- * Cleans up the drag and drop events and objects.
- * @method unregAll
- * @private
- * @static
- */
- unregAll: function() {
-
- if (this.dragCurrent) {
- this.stopDrag();
- this.dragCurrent = null;
- }
-
- this._execOnAll("unreg", []);
-
- for (i in this.elementCache) {
- delete this.elementCache[i];
- }
-
- this.elementCache = {};
- this.ids = {};
- },
-
- /**
- * A cache of DOM elements
- * @property elementCache
- * @private
- * @static
- */
- elementCache: {},
-
- /**
- * Get the wrapper for the DOM element specified
- * @method getElWrapper
- * @param {String} id the id of the element to get
- * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
- * @private
- * @deprecated This wrapper isn't that useful
- * @static
- */
- getElWrapper: function(id) {
- var oWrapper = this.elementCache[id];
- if (!oWrapper || !oWrapper.el) {
- oWrapper = this.elementCache[id] =
- new this.ElementWrapper(Roo.getDom(id));
- }
- return oWrapper;
- },
-
- /**
- * Returns the actual DOM element
- * @method getElement
- * @param {String} id the id of the elment to get
- * @return {Object} The element
- * @deprecated use Roo.getDom instead
- * @static
- */
- getElement: function(id) {
- return Roo.getDom(id);
- },
-
- /**
- * Returns the style property for the DOM element (i.e.,
- * document.getElById(id).style)
- * @method getCss
- * @param {String} id the id of the elment to get
- * @return {Object} The style property of the element
- * @deprecated use Roo.getDom instead
- * @static
- */
- getCss: function(id) {
- var el = Roo.getDom(id);
- return (el) ? el.style : null;
- },
-
- /**
- * Inner class for cached elements
- * @class DragDropMgr.ElementWrapper
- * @for DragDropMgr
- * @private
- * @deprecated
- */
- ElementWrapper: function(el) {
- /**
- * The element
- * @property el
- */
- this.el = el || null;
- /**
- * The element id
- * @property id
- */
- this.id = this.el && el.id;
- /**
- * A reference to the style property
- * @property css
- */
- this.css = this.el && el.style;
- },
-
- /**
- * Returns the X position of an html element
- * @method getPosX
- * @param el the element for which to get the position
- * @return {int} the X coordinate
- * @for DragDropMgr
- * @deprecated use Roo.lib.Dom.getX instead
- * @static
- */
- getPosX: function(el) {
- return Roo.lib.Dom.getX(el);
- },
-
- /**
- * Returns the Y position of an html element
- * @method getPosY
- * @param el the element for which to get the position
- * @return {int} the Y coordinate
- * @deprecated use Roo.lib.Dom.getY instead
- * @static
- */
- getPosY: function(el) {
- return Roo.lib.Dom.getY(el);
- },
-
- /**
- * Swap two nodes. In IE, we use the native method, for others we
- * emulate the IE behavior
- * @method swapNode
- * @param n1 the first node to swap
- * @param n2 the other node to swap
- * @static
- */
- swapNode: function(n1, n2) {
- if (n1.swapNode) {
- n1.swapNode(n2);
- } else {
- var p = n2.parentNode;
- var s = n2.nextSibling;
-
- if (s == n1) {
- p.insertBefore(n1, n2);
- } else if (n2 == n1.nextSibling) {
- p.insertBefore(n2, n1);
- } else {
- n1.parentNode.replaceChild(n2, n1);
- p.insertBefore(n1, s);
- }
- }
- },
-
- /**
- * Returns the current scroll position
- * @method getScroll
- * @private
- * @static
- */
- getScroll: function () {
- var t, l, dde=document.documentElement, db=document.body;
- if (dde && (dde.scrollTop || dde.scrollLeft)) {
- t = dde.scrollTop;
- l = dde.scrollLeft;
- } else if (db) {
- t = db.scrollTop;
- l = db.scrollLeft;
- } else {
-
- }
- return { top: t, left: l };
- },
-
- /**
- * Returns the specified element style property
- * @method getStyle
- * @param {HTMLElement} el the element
- * @param {string} styleProp the style property
- * @return {string} The value of the style property
- * @deprecated use Roo.lib.Dom.getStyle
- * @static
- */
- getStyle: function(el, styleProp) {
- return Roo.fly(el).getStyle(styleProp);
- },
-
- /**
- * Gets the scrollTop
- * @method getScrollTop
- * @return {int} the document's scrollTop
- * @static
- */
- getScrollTop: function () { return this.getScroll().top; },
-
- /**
- * Gets the scrollLeft
- * @method getScrollLeft
- * @return {int} the document's scrollTop
- * @static
- */
- getScrollLeft: function () { return this.getScroll().left; },
-
- /**
- * Sets the x/y position of an element to the location of the
- * target element.
- * @method moveToEl
- * @param {HTMLElement} moveEl The element to move
- * @param {HTMLElement} targetEl The position reference element
- * @static
- */
- moveToEl: function (moveEl, targetEl) {
- var aCoord = Roo.lib.Dom.getXY(targetEl);
- Roo.lib.Dom.setXY(moveEl, aCoord);
- },
-
- /**
- * Numeric array sort function
- * @method numericSort
- * @static
- */
- numericSort: function(a, b) { return (a - b); },
-
- /**
- * Internal counter
- * @property _timeoutCount
- * @private
- * @static
- */
- _timeoutCount: 0,
-
- /**
- * Trying to make the load order less important. Without this we get
- * an error if this file is loaded before the Event Utility.
- * @method _addListeners
- * @private
- * @static
- */
- _addListeners: function() {
- var DDM = Roo.dd.DDM;
- if ( Roo.lib.Event && document ) {
- DDM._onLoad();
- } else {
- if (DDM._timeoutCount > 2000) {
- } else {
- setTimeout(DDM._addListeners, 10);
- if (document && document.body) {
- DDM._timeoutCount += 1;
- }
- }
- }
- },
-
- /**
- * Recursively searches the immediate parent and all child nodes for
- * the handle element in order to determine wheter or not it was
- * clicked.
- * @method handleWasClicked
- * @param node the html element to inspect
- * @static
- */
- handleWasClicked: function(node, id) {
- if (this.isHandle(id, node.id)) {
- return true;
- } else {
- // check to see if this is a text node child of the one we want
- var p = node.parentNode;
-
- while (p) {
- if (this.isHandle(id, p.id)) {
- return true;
- } else {
- p = p.parentNode;
- }
- }
- }
-
- return false;
- }
-
- };
-
-}();
-
-// shorter alias, save a few bytes
-Roo.dd.DDM = Roo.dd.DragDropMgr;
-Roo.dd.DDM._addListeners();
-
-}/*
- * 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.dd.DD
- * A DragDrop implementation where the linked element follows the
- * mouse cursor during a drag.
- * @extends Roo.dd.DragDrop
- * @constructor
- * @param {String} id the id of the linked element
- * @param {String} sGroup the group of related DragDrop items
- * @param {object} config an object containing configurable attributes
- * Valid properties for DD:
- * scroll
- */
-Roo.dd.DD = function(id, sGroup, config) {
- if (id) {
- this.init(id, sGroup, config);
- }
-};
-
-Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
-
- /**
- * When set to true, the utility automatically tries to scroll the browser
- * window wehn a drag and drop element is dragged near the viewport boundary.
- * Defaults to true.
- * @property scroll
- * @type boolean
- */
- scroll: true,
-
- /**
- * Sets the pointer offset to the distance between the linked element's top
- * left corner and the location the element was clicked
- * @method autoOffset
- * @param {int} iPageX the X coordinate of the click
- * @param {int} iPageY the Y coordinate of the click
- */
- autoOffset: function(iPageX, iPageY) {
- var x = iPageX - this.startPageX;
- var y = iPageY - this.startPageY;
- this.setDelta(x, y);
- },
-
- /**
- * Sets the pointer offset. You can call this directly to force the
- * offset to be in a particular location (e.g., pass in 0,0 to set it
- * to the center of the object)
- * @method setDelta
- * @param {int} iDeltaX the distance from the left
- * @param {int} iDeltaY the distance from the top
- */
- setDelta: function(iDeltaX, iDeltaY) {
- this.deltaX = iDeltaX;
- this.deltaY = iDeltaY;
- },
-
- /**
- * Sets the drag element to the location of the mousedown or click event,
- * maintaining the cursor location relative to the location on the element
- * that was clicked. Override this if you want to place the element in a
- * location other than where the cursor is.
- * @method setDragElPos
- * @param {int} iPageX the X coordinate of the mousedown or drag event
- * @param {int} iPageY the Y coordinate of the mousedown or drag event
- */
- setDragElPos: function(iPageX, iPageY) {
- // the first time we do this, we are going to check to make sure
- // the element has css positioning
-
- var el = this.getDragEl();
- this.alignElWithMouse(el, iPageX, iPageY);
- },
-
- /**
- * Sets the element to the location of the mousedown or click event,
- * maintaining the cursor location relative to the location on the element
- * that was clicked. Override this if you want to place the element in a
- * location other than where the cursor is.
- * @method alignElWithMouse
- * @param {HTMLElement} el the element to move
- * @param {int} iPageX the X coordinate of the mousedown or drag event
- * @param {int} iPageY the Y coordinate of the mousedown or drag event
- */
- alignElWithMouse: function(el, iPageX, iPageY) {
- var oCoord = this.getTargetCoord(iPageX, iPageY);
- var fly = el.dom ? el : Roo.fly(el);
- if (!this.deltaSetXY) {
- var aCoord = [oCoord.x, oCoord.y];
- fly.setXY(aCoord);
- var newLeft = fly.getLeft(true);
- var newTop = fly.getTop(true);
- this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
- } else {
- fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
- }
-
- this.cachePosition(oCoord.x, oCoord.y);
- this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
- return oCoord;
- },
-
- /**
- * Saves the most recent position so that we can reset the constraints and
- * tick marks on-demand. We need to know this so that we can calculate the
- * number of pixels the element is offset from its original position.
- * @method cachePosition
- * @param iPageX the current x position (optional, this just makes it so we
- * don't have to look it up again)
- * @param iPageY the current y position (optional, this just makes it so we
- * don't have to look it up again)
- */
- cachePosition: function(iPageX, iPageY) {
- if (iPageX) {
- this.lastPageX = iPageX;
- this.lastPageY = iPageY;
- } else {
- var aCoord = Roo.lib.Dom.getXY(this.getEl());
- this.lastPageX = aCoord[0];
- this.lastPageY = aCoord[1];
- }
- },
-
- /**
- * Auto-scroll the window if the dragged object has been moved beyond the
- * visible window boundary.
- * @method autoScroll
- * @param {int} x the drag element's x position
- * @param {int} y the drag element's y position
- * @param {int} h the height of the drag element
- * @param {int} w the width of the drag element
- * @private
- */
- autoScroll: function(x, y, h, w) {
-
- if (this.scroll) {
- // The client height
- var clientH = Roo.lib.Dom.getViewWidth();
-
- // The client width
- var clientW = Roo.lib.Dom.getViewHeight();
-
- // The amt scrolled down
- var st = this.DDM.getScrollTop();
-
- // The amt scrolled right
- var sl = this.DDM.getScrollLeft();
-
- // Location of the bottom of the element
- var bot = h + y;
-
- // Location of the right of the element
- var right = w + x;
-
- // The distance from the cursor to the bottom of the visible area,
- // adjusted so that we don't scroll if the cursor is beyond the
- // element drag constraints
- var toBot = (clientH + st - y - this.deltaY);
-
- // The distance from the cursor to the right of the visible area
- var toRight = (clientW + sl - x - this.deltaX);
-
-
- // How close to the edge the cursor must be before we scroll
- // var thresh = (document.all) ? 100 : 40;
- var thresh = 40;
-
- // How many pixels to scroll per autoscroll op. This helps to reduce
- // clunky scrolling. IE is more sensitive about this ... it needs this
- // value to be higher.
- var scrAmt = (document.all) ? 80 : 30;
-
- // Scroll down if we are near the bottom of the visible page and the
- // obj extends below the crease
- if ( bot > clientH && toBot < thresh ) {
- window.scrollTo(sl, st + scrAmt);
- }
-
- // Scroll up if the window is scrolled down and the top of the object
- // goes above the top border
- if ( y < st && st > 0 && y - st < thresh ) {
- window.scrollTo(sl, st - scrAmt);
- }
-
- // Scroll right if the obj is beyond the right border and the cursor is
- // near the border.
- if ( right > clientW && toRight < thresh ) {
- window.scrollTo(sl + scrAmt, st);
- }
-
- // Scroll left if the window has been scrolled to the right and the obj
- // extends past the left border
- if ( x < sl && sl > 0 && x - sl < thresh ) {
- window.scrollTo(sl - scrAmt, st);
- }
- }
- },
-
- /**
- * Finds the location the element should be placed if we want to move
- * it to where the mouse location less the click offset would place us.
- * @method getTargetCoord
- * @param {int} iPageX the X coordinate of the click
- * @param {int} iPageY the Y coordinate of the click
- * @return an object that contains the coordinates (Object.x and Object.y)
- * @private
- */
- getTargetCoord: function(iPageX, iPageY) {
-
-
- var x = iPageX - this.deltaX;
- var y = iPageY - this.deltaY;
-
- if (this.constrainX) {
- if (x < this.minX) { x = this.minX; }
- if (x > this.maxX) { x = this.maxX; }
- }
-
- if (this.constrainY) {
- if (y < this.minY) { y = this.minY; }
- if (y > this.maxY) { y = this.maxY; }
- }
-
- x = this.getTick(x, this.xTicks);
- y = this.getTick(y, this.yTicks);
-
-
- return {x:x, y:y};
- },
-
- /*
- * Sets up config options specific to this class. Overrides
- * Roo.dd.DragDrop, but all versions of this method through the
- * inheritance chain are called
- */
- applyConfig: function() {
- Roo.dd.DD.superclass.applyConfig.call(this);
- this.scroll = (this.config.scroll !== false);
- },
-
- /*
- * Event that fires prior to the onMouseDown event. Overrides
- * Roo.dd.DragDrop.
- */
- b4MouseDown: function(e) {
- // this.resetConstraints();
- this.autoOffset(e.getPageX(),
- e.getPageY());
- },
-
- /*
- * Event that fires prior to the onDrag event. Overrides
- * Roo.dd.DragDrop.
- */
- b4Drag: function(e) {
- this.setDragElPos(e.getPageX(),
- e.getPageY());
- },
-
- toString: function() {
- return ("DD " + this.id);
- }
-
- //////////////////////////////////////////////////////////////////////////
- // Debugging ygDragDrop events that can be overridden
- //////////////////////////////////////////////////////////////////////////
- /*
- startDrag: function(x, y) {
- },
-
- onDrag: function(e) {
- },
-
- onDragEnter: function(e, id) {
- },
-
- onDragOver: function(e, id) {
- },
-
- onDragOut: function(e, id) {
- },
-
- onDragDrop: function(e, id) {
- },
-
- endDrag: function(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.dd.DDProxy
- * A DragDrop implementation that inserts an empty, bordered div into
- * the document that follows the cursor during drag operations. At the time of
- * the click, the frame div is resized to the dimensions of the linked html
- * element, and moved to the exact location of the linked element.
- *
- * References to the "frame" element refer to the single proxy element that
- * was created to be dragged in place of all DDProxy elements on the
- * page.
- *
- * @extends Roo.dd.DD
- * @constructor
- * @param {String} id the id of the linked html element
- * @param {String} sGroup the group of related DragDrop objects
- * @param {object} config an object containing configurable attributes
- * Valid properties for DDProxy in addition to those in DragDrop:
- * resizeFrame, centerFrame, dragElId
- */
-Roo.dd.DDProxy = function(id, sGroup, config) {
- if (id) {
- this.init(id, sGroup, config);
- this.initFrame();
- }
-};
-
-/**
- * The default drag frame div id
- * @property Roo.dd.DDProxy.dragElId
- * @type String
- * @static
- */
-Roo.dd.DDProxy.dragElId = "ygddfdiv";
-
-Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
-
- /**
- * By default we resize the drag frame to be the same size as the element
- * we want to drag (this is to get the frame effect). We can turn it off
- * if we want a different behavior.
- * @property resizeFrame
- * @type boolean
- */
- resizeFrame: true,
-
- /**
- * By default the frame is positioned exactly where the drag element is, so
- * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
- * you do not have constraints on the obj is to have the drag frame centered
- * around the cursor. Set centerFrame to true for this effect.
- * @property centerFrame
- * @type boolean
- */
- centerFrame: false,
-
- /**
- * Creates the proxy element if it does not yet exist
- * @method createFrame
- */
- createFrame: function() {
- var self = this;
- var body = document.body;
-
- if (!body || !body.firstChild) {
- setTimeout( function() { self.createFrame(); }, 50 );
- return;
- }
-
- var div = this.getDragEl();
-
- if (!div) {
- div = document.createElement("div");
- div.id = this.dragElId;
- var s = div.style;
-
- s.position = "absolute";
- s.visibility = "hidden";
- s.cursor = "move";
- s.border = "2px solid #aaa";
- s.zIndex = 999;
-
- // appendChild can blow up IE if invoked prior to the window load event
- // while rendering a table. It is possible there are other scenarios
- // that would cause this to happen as well.
- body.insertBefore(div, body.firstChild);
- }
- },
-
- /**
- * Initialization for the drag frame element. Must be called in the
- * constructor of all subclasses
- * @method initFrame
- */
- initFrame: function() {
- this.createFrame();
- },
-
- applyConfig: function() {
- Roo.dd.DDProxy.superclass.applyConfig.call(this);
-
- this.resizeFrame = (this.config.resizeFrame !== false);
- this.centerFrame = (this.config.centerFrame);
- this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
- },
-
- /**
- * Resizes the drag frame to the dimensions of the clicked object, positions
- * it over the object, and finally displays it
- * @method showFrame
- * @param {int} iPageX X click position
- * @param {int} iPageY Y click position
- * @private
- */
- showFrame: function(iPageX, iPageY) {
- var el = this.getEl();
- var dragEl = this.getDragEl();
- var s = dragEl.style;
-
- this._resizeProxy();
-
- if (this.centerFrame) {
- this.setDelta( Math.round(parseInt(s.width, 10)/2),
- Math.round(parseInt(s.height, 10)/2) );
- }
-
- this.setDragElPos(iPageX, iPageY);
-
- Roo.fly(dragEl).show();
- },
-
- /**
- * The proxy is automatically resized to the dimensions of the linked
- * element when a drag is initiated, unless resizeFrame is set to false
- * @method _resizeProxy
- * @private
- */
- _resizeProxy: function() {
- if (this.resizeFrame) {
- var el = this.getEl();
- Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
- }
- },
-
- // overrides Roo.dd.DragDrop
- b4MouseDown: function(e) {
- var x = e.getPageX();
- var y = e.getPageY();
- this.autoOffset(x, y);
- this.setDragElPos(x, y);
- },
-
- // overrides Roo.dd.DragDrop
- b4StartDrag: function(x, y) {
- // show the drag frame
- this.showFrame(x, y);
- },
-
- // overrides Roo.dd.DragDrop
- b4EndDrag: function(e) {
- Roo.fly(this.getDragEl()).hide();
- },
-
- // overrides Roo.dd.DragDrop
- // By default we try to move the element to the last location of the frame.
- // This is so that the default behavior mirrors that of Roo.dd.DD.
- endDrag: function(e) {
-
- var lel = this.getEl();
- var del = this.getDragEl();
-
- // Show the drag frame briefly so we can get its position
- del.style.visibility = "";
-
- this.beforeMove();
- // Hide the linked element before the move to get around a Safari
- // rendering bug.
- lel.style.visibility = "hidden";
- Roo.dd.DDM.moveToEl(lel, del);
- del.style.visibility = "hidden";
- lel.style.visibility = "";
-
- this.afterDrag();
- },
-
- beforeMove : function(){
-
- },
-
- afterDrag : function(){
-
- },
-
- toString: function() {
- return ("DDProxy " + this.id);
- }
-
-});
-/*
- * 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.dd.DDTarget
- * A DragDrop implementation that does not move, but can be a drop
- * target. You would get the same result by simply omitting implementation
- * for the event callbacks, but this way we reduce the processing cost of the
- * event listener and the callbacks.
- * @extends Roo.dd.DragDrop
- * @constructor
- * @param {String} id the id of the element that is a drop target
- * @param {String} sGroup the group of related DragDrop objects
- * @param {object} config an object containing configurable attributes
- * Valid properties for DDTarget in addition to those in
- * DragDrop:
- * none
- */
-Roo.dd.DDTarget = function(id, sGroup, config) {
- if (id) {
- this.initTarget(id, sGroup, config);
- }
- if (config.listeners || config.events) {
- Roo.dd.DragDrop.superclass.constructor.call(this, {
- listeners : config.listeners || {},
- events : config.events || {}
- });
- }
-};
-
-// Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
-Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
- toString: function() {
- return ("DDTarget " + this.id);
- }
-});
-/*
- * 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.dd.ScrollManager
- * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
- * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
- * @singleton
- */
-Roo.dd.ScrollManager = function(){
- var ddm = Roo.dd.DragDropMgr;
- var els = {};
- var dragEl = null;
- var proc = {};
-
-
-
- var onStop = function(e){
- dragEl = null;
- clearProc();
- };
-
- var triggerRefresh = function(){
- if(ddm.dragCurrent){
- ddm.refreshCache(ddm.dragCurrent.groups);
- }
- };
-
- var doScroll = function(){
- if(ddm.dragCurrent){
- var dds = Roo.dd.ScrollManager;
- if(!dds.animate){
- if(proc.el.scroll(proc.dir, dds.increment)){
- triggerRefresh();
- }
- }else{
- proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
- }
- }
- };
-
- var clearProc = function(){
- if(proc.id){
- clearInterval(proc.id);
- }
- proc.id = 0;
- proc.el = null;
- proc.dir = "";
- };
-
- var startProc = function(el, dir){
- Roo.log('scroll startproc');
- clearProc();
- proc.el = el;
- proc.dir = dir;
- proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
- };
-
- var onFire = function(e, isDrop){
-
- if(isDrop || !ddm.dragCurrent){ return; }
- var dds = Roo.dd.ScrollManager;
- if(!dragEl || dragEl != ddm.dragCurrent){
- dragEl = ddm.dragCurrent;
- // refresh regions on drag start
- dds.refreshCache();
- }
-
- var xy = Roo.lib.Event.getXY(e);
- var pt = new Roo.lib.Point(xy[0], xy[1]);
- for(var id in els){
- var el = els[id], r = el._region;
- if(r && r.contains(pt) && el.isScrollable()){
- if(r.bottom - pt.y <= dds.thresh){
- if(proc.el != el){
- startProc(el, "down");
- }
- return;
- }else if(r.right - pt.x <= dds.thresh){
- if(proc.el != el){
- startProc(el, "left");
- }
- return;
- }else if(pt.y - r.top <= dds.thresh){
- if(proc.el != el){
- startProc(el, "up");
- }
- return;
- }else if(pt.x - r.left <= dds.thresh){
- if(proc.el != el){
- startProc(el, "right");
- }
- return;
- }
- }
- }
- clearProc();
- };
-
- ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
- ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
-
- return {
- /**
- * Registers new overflow element(s) to auto scroll
- * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
- */
- register : function(el){
- if(el instanceof Array){
- for(var i = 0, len = el.length; i < len; i++) {
- this.register(el[i]);
- }
- }else{
- el = Roo.get(el);
- els[el.id] = el;
- }
- Roo.dd.ScrollManager.els = els;
- },
-
- /**
- * Unregisters overflow element(s) so they are no longer scrolled
- * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
- */
- unregister : function(el){
- if(el instanceof Array){
- for(var i = 0, len = el.length; i < len; i++) {
- this.unregister(el[i]);
- }
- }else{
- el = Roo.get(el);
- delete els[el.id];
- }
- },
-
- /**
- * The number of pixels from the edge of a container the pointer needs to be to
- * trigger scrolling (defaults to 25)
- * @type Number
- */
- thresh : 25,
-
- /**
- * The number of pixels to scroll in each scroll increment (defaults to 50)
- * @type Number
- */
- increment : 100,
-
- /**
- * The frequency of scrolls in milliseconds (defaults to 500)
- * @type Number
- */
- frequency : 500,
-
- /**
- * True to animate the scroll (defaults to true)
- * @type Boolean
- */
- animate: true,
-
- /**
- * The animation duration in seconds -
- * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
- * @type Number
- */
- animDuration: .4,
-
- /**
- * Manually trigger a cache refresh.
- */
- refreshCache : function(){
- for(var id in els){
- if(typeof els[id] == 'object'){ // for people extending the object prototype
- els[id]._region = els[id].getRegion();
- }
- }
- }
- };
-}();/*
- * 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.dd.Registry
- * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
- * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
- * @singleton
- */
-Roo.dd.Registry = function(){
- var elements = {};
- var handles = {};
- var autoIdSeed = 0;
-
- var getId = function(el, autogen){
- if(typeof el == "string"){
- return el;
- }
- var id = el.id;
- if(!id && autogen !== false){
- id = "roodd-" + (++autoIdSeed);
- el.id = id;
- }
- return id;
- };
-
- return {
- /**
- * Register a drag drop element
- * @param {String|HTMLElement} element The id or DOM node to register
- * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
- * in drag drop operations. You can populate this object with any arbitrary properties that your own code
- * knows how to interpret, plus there are some specific properties known to the Registry that should be
- * populated in the data object (if applicable):
- * <pre>
-Value Description<br />
---------- ------------------------------------------<br />
-handles Array of DOM nodes that trigger dragging<br />
- for the element being registered<br />
-isHandle True if the element passed in triggers<br />
- dragging itself, else false
-</pre>
- */
- register : function(el, data){
- data = data || {};
- if(typeof el == "string"){
- el = document.getElementById(el);
- }
- data.ddel = el;
- elements[getId(el)] = data;
- if(data.isHandle !== false){
- handles[data.ddel.id] = data;
- }
- if(data.handles){
- var hs = data.handles;
- for(var i = 0, len = hs.length; i < len; i++){
- handles[getId(hs[i])] = data;
- }
- }
- },
-
- /**
- * Unregister a drag drop element
- * @param {String|HTMLElement} element The id or DOM node to unregister
- */
- unregister : function(el){
- var id = getId(el, false);
- var data = elements[id];
- if(data){
- delete elements[id];
- if(data.handles){
- var hs = data.handles;
- for(var i = 0, len = hs.length; i < len; i++){
- delete handles[getId(hs[i], false)];
- }
- }
- }
- },
-
- /**
- * Returns the handle registered for a DOM Node by id
- * @param {String|HTMLElement} id The DOM node or id to look up
- * @return {Object} handle The custom handle data
- */
- getHandle : function(id){
- if(typeof id != "string"){ // must be element?
- id = id.id;
- }
- return handles[id];
- },
-
- /**
- * Returns the handle that is registered for the DOM node that is the target of the event
- * @param {Event} e The event
- * @return {Object} handle The custom handle data
- */
- getHandleFromEvent : function(e){
- var t = Roo.lib.Event.getTarget(e);
- return t ? handles[t.id] : null;
- },
-
- /**
- * Returns a custom data object that is registered for a DOM node by id
- * @param {String|HTMLElement} id The DOM node or id to look up
- * @return {Object} data The custom data
- */
- getTarget : function(id){
- if(typeof id != "string"){ // must be element?
- id = id.id;
- }
- return elements[id];
- },
-
- /**
- * Returns a custom data object that is registered for the DOM node that is the target of the event
- * @param {Event} e The event
- * @return {Object} data The custom data
- */
- getTargetFromEvent : function(e){
- var t = Roo.lib.Event.getTarget(e);
- return t ? elements[t.id] || handles[t.id] : null;
- }
- };
-}();/*
- * 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.dd.StatusProxy
- * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
- * default drag proxy used by all Roo.dd components.
- * @constructor
- * @param {Object} config
- */
-Roo.dd.StatusProxy = function(config){
- Roo.apply(this, config);
- this.id = this.id || Roo.id();
- this.el = new Roo.Layer({
- dh: {
- id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
- {tag: "div", cls: "x-dd-drop-icon"},
- {tag: "div", cls: "x-dd-drag-ghost"}
- ]
- },
- shadow: !config || config.shadow !== false
- });
- this.ghost = Roo.get(this.el.dom.childNodes[1]);
- this.dropStatus = this.dropNotAllowed;
-};
-
-Roo.dd.StatusProxy.prototype = {
- /**
- * @cfg {String} dropAllowed
- * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
- */
- dropAllowed : "x-dd-drop-ok",
- /**
- * @cfg {String} dropNotAllowed
- * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
- */
- dropNotAllowed : "x-dd-drop-nodrop",
-
- /**
- * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
- * over the current target element.
- * @param {String} cssClass The css class for the new drop status indicator image
- */
- setStatus : function(cssClass){
- cssClass = cssClass || this.dropNotAllowed;
- if(this.dropStatus != cssClass){
- this.el.replaceClass(this.dropStatus, cssClass);
- this.dropStatus = cssClass;
- }
- },
-
- /**
- * Resets the status indicator to the default dropNotAllowed value
- * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
- */
- reset : function(clearGhost){
- this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
- this.dropStatus = this.dropNotAllowed;
- if(clearGhost){
- this.ghost.update("");
- }
- },
-
- /**
- * Updates the contents of the ghost element
- * @param {String} html The html that will replace the current innerHTML of the ghost element
- */
- update : function(html){
- if(typeof html == "string"){
- this.ghost.update(html);
- }else{
- this.ghost.update("");
- html.style.margin = "0";
- this.ghost.dom.appendChild(html);
- }
- // ensure float = none set?? cant remember why though.
- var el = this.ghost.dom.firstChild;
- if(el){
- Roo.fly(el).setStyle('float', 'none');
- }
- },
-
- /**
- * Returns the underlying proxy {@link Roo.Layer}
- * @return {Roo.Layer} el
- */
- getEl : function(){
- return this.el;
- },
-
- /**
- * Returns the ghost element
- * @return {Roo.Element} el
- */
- getGhost : function(){
- return this.ghost;
- },
-
- /**
- * Hides the proxy
- * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
- */
- hide : function(clear){
- this.el.hide();
- if(clear){
- this.reset(true);
- }
- },
-
- /**
- * Stops the repair animation if it's currently running
- */
- stop : function(){
- if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
- this.anim.stop();
- }
- },
-
- /**
- * Displays this proxy
- */
- show : function(){
- this.el.show();
- },
-
- /**
- * Force the Layer to sync its shadow and shim positions to the element
- */
- sync : function(){
- this.el.sync();
- },
-
- /**
- * Causes the proxy to return to its position of origin via an animation. Should be called after an
- * invalid drop operation by the item being dragged.
- * @param {Array} xy The XY position of the element ([x, y])
- * @param {Function} callback The function to call after the repair is complete
- * @param {Object} scope The scope in which to execute the callback
- */
- repair : function(xy, callback, scope){
- this.callback = callback;
- this.scope = scope;
- if(xy && this.animRepair !== false){
- this.el.addClass("x-dd-drag-repair");
- this.el.hideUnders(true);
- this.anim = this.el.shift({
- duration: this.repairDuration || .5,
- easing: 'easeOut',
- xy: xy,
- stopFx: true,
- callback: this.afterRepair,
- scope: this
- });
- }else{
- this.afterRepair();
- }
- },
-
- // private
- afterRepair : function(){
- this.hide(true);
- if(typeof this.callback == "function"){
- this.callback.call(this.scope || this);
- }
- this.callback = null;
- this.scope = null;
- }
-};/*
- * 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.dd.DragSource
- * @extends Roo.dd.DDProxy
- * A simple class that provides the basic implementation needed to make any element draggable.
- * @constructor
- * @param {String/HTMLElement/Element} el The container element
- * @param {Object} config
- */
-Roo.dd.DragSource = function(el, config){
- this.el = Roo.get(el);
- this.dragData = {};
-
- Roo.apply(this, config);
-
- if(!this.proxy){
- this.proxy = new Roo.dd.StatusProxy();
- }
-
- Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
- {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
-
- this.dragging = false;
-};
-
-Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
- /**
- * @cfg {String} dropAllowed
- * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
- */
- dropAllowed : "x-dd-drop-ok",
- /**
- * @cfg {String} dropNotAllowed
- * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
- */
- dropNotAllowed : "x-dd-drop-nodrop",
-
- /**
- * Returns the data object associated with this drag source
- * @return {Object} data An object containing arbitrary data
- */
- getDragData : function(e){
- return this.dragData;
- },
-
- // private
- onDragEnter : function(e, id){
- var target = Roo.dd.DragDropMgr.getDDById(id);
- this.cachedTarget = target;
- if(this.beforeDragEnter(target, e, id) !== false){
- if(target.isNotifyTarget){
- var status = target.notifyEnter(this, e, this.dragData);
- this.proxy.setStatus(status);
- }else{
- this.proxy.setStatus(this.dropAllowed);
- }
-
- if(this.afterDragEnter){
- /**
- * An empty function by default, but provided so that you can perform a custom action
- * when the dragged item enters the drop target by providing an implementation.
- * @param {Roo.dd.DragDrop} target The drop target
- * @param {Event} e The event object
- * @param {String} id The id of the dragged element
- * @method afterDragEnter
- */
- this.afterDragEnter(target, e, id);
- }
- }
- },
-
- /**
- * An empty function by default, but provided so that you can perform a custom action
- * before the dragged item enters the drop target and optionally cancel the onDragEnter.
- * @param {Roo.dd.DragDrop} target The drop target
- * @param {Event} e The event object
- * @param {String} id The id of the dragged element
- * @return {Boolean} isValid True if the drag event is valid, else false to cancel
- */
- beforeDragEnter : function(target, e, id){
- return true;
- },
-
- // private
- alignElWithMouse: function() {
- Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
- this.proxy.sync();
- },
-
- // private
- onDragOver : function(e, id){
- var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
- if(this.beforeDragOver(target, e, id) !== false){
- if(target.isNotifyTarget){
- var status = target.notifyOver(this, e, this.dragData);
- this.proxy.setStatus(status);
- }
-
- if(this.afterDragOver){
- /**
- * An empty function by default, but provided so that you can perform a custom action
- * while the dragged item is over the drop target by providing an implementation.
- * @param {Roo.dd.DragDrop} target The drop target
- * @param {Event} e The event object
- * @param {String} id The id of the dragged element
- * @method afterDragOver
- */
- this.afterDragOver(target, e, id);
- }
- }
- },
-
- /**
- * An empty function by default, but provided so that you can perform a custom action
- * while the dragged item is over the drop target and optionally cancel the onDragOver.
- * @param {Roo.dd.DragDrop} target The drop target
- * @param {Event} e The event object
- * @param {String} id The id of the dragged element
- * @return {Boolean} isValid True if the drag event is valid, else false to cancel
- */
- beforeDragOver : function(target, e, id){
- return true;
- },
-
- // private
- onDragOut : function(e, id){
- var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
- if(this.beforeDragOut(target, e, id) !== false){
- if(target.isNotifyTarget){
- target.notifyOut(this, e, this.dragData);
- }
- this.proxy.reset();
- if(this.afterDragOut){
- /**
- * An empty function by default, but provided so that you can perform a custom action
- * after the dragged item is dragged out of the target without dropping.
- * @param {Roo.dd.DragDrop} target The drop target
- * @param {Event} e The event object
- * @param {String} id The id of the dragged element
- * @method afterDragOut
- */
- this.afterDragOut(target, e, id);
- }
- }
- this.cachedTarget = null;
- },
-
- /**
- * An empty function by default, but provided so that you can perform a custom action before the dragged
- * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
- * @param {Roo.dd.DragDrop} target The drop target
- * @param {Event} e The event object
- * @param {String} id The id of the dragged element
- * @return {Boolean} isValid True if the drag event is valid, else false to cancel
- */
- beforeDragOut : function(target, e, id){
- return true;
- },
-
- // private
- onDragDrop : function(e, id){
- var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
- if(this.beforeDragDrop(target, e, id) !== false){
- if(target.isNotifyTarget){
- if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
- this.onValidDrop(target, e, id);
- }else{
- this.onInvalidDrop(target, e, id);
- }
- }else{
- this.onValidDrop(target, e, id);
- }
-
- if(this.afterDragDrop){
- /**
- * An empty function by default, but provided so that you can perform a custom action
- * after a valid drag drop has occurred by providing an implementation.
- * @param {Roo.dd.DragDrop} target The drop target
- * @param {Event} e The event object
- * @param {String} id The id of the dropped element
- * @method afterDragDrop
- */
- this.afterDragDrop(target, e, id);
- }
- }
- delete this.cachedTarget;
- },
-
- /**
- * An empty function by default, but provided so that you can perform a custom action before the dragged
- * item is dropped onto the target and optionally cancel the onDragDrop.
- * @param {Roo.dd.DragDrop} target The drop target
- * @param {Event} e The event object
- * @param {String} id The id of the dragged element
- * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
- */
- beforeDragDrop : function(target, e, id){
- return true;
- },
-
- // private
- onValidDrop : function(target, e, id){
- this.hideProxy();
- if(this.afterValidDrop){
- /**
- * An empty function by default, but provided so that you can perform a custom action
- * after a valid drop has occurred by providing an implementation.
- * @param {Object} target The target DD
- * @param {Event} e The event object
- * @param {String} id The id of the dropped element
- * @method afterInvalidDrop
- */
- this.afterValidDrop(target, e, id);
- }
- },
-
- // private
- getRepairXY : function(e, data){
- return this.el.getXY();
- },
-
- // private
- onInvalidDrop : function(target, e, id){
- this.beforeInvalidDrop(target, e, id);
- if(this.cachedTarget){
- if(this.cachedTarget.isNotifyTarget){
- this.cachedTarget.notifyOut(this, e, this.dragData);
- }
- this.cacheTarget = null;
- }
- this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
-
- if(this.afterInvalidDrop){
- /**
- * An empty function by default, but provided so that you can perform a custom action
- * after an invalid drop has occurred by providing an implementation.
- * @param {Event} e The event object
- * @param {String} id The id of the dropped element
- * @method afterInvalidDrop
- */
- this.afterInvalidDrop(e, id);
- }
- },
-
- // private
- afterRepair : function(){
- if(Roo.enableFx){
- this.el.highlight(this.hlColor || "c3daf9");
- }
- this.dragging = false;
- },
-
- /**
- * An empty function by default, but provided so that you can perform a custom action after an invalid
- * drop has occurred.
- * @param {Roo.dd.DragDrop} target The drop target
- * @param {Event} e The event object
- * @param {String} id The id of the dragged element
- * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
- */
- beforeInvalidDrop : function(target, e, id){
- return true;
- },
-
- // private
- handleMouseDown : function(e){
- if(this.dragging) {
- return;
- }
- var data = this.getDragData(e);
- if(data && this.onBeforeDrag(data, e) !== false){
- this.dragData = data;
- this.proxy.stop();
- Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
- }
- },
-
- /**
- * An empty function by default, but provided so that you can perform a custom action before the initial
- * drag event begins and optionally cancel it.
- * @param {Object} data An object containing arbitrary data to be shared with drop targets
- * @param {Event} e The event object
- * @return {Boolean} isValid True if the drag event is valid, else false to cancel
- */
- onBeforeDrag : function(data, e){
- return true;
- },
-
- /**
- * An empty function by default, but provided so that you can perform a custom action once the initial
- * drag event has begun. The drag cannot be canceled from this function.
- * @param {Number} x The x position of the click on the dragged object
- * @param {Number} y The y position of the click on the dragged object
- */
- onStartDrag : Roo.emptyFn,
-
- // private - YUI override
- startDrag : function(x, y){
- this.proxy.reset();
- this.dragging = true;
- this.proxy.update("");
- this.onInitDrag(x, y);
- this.proxy.show();
- },
-
- // private
- onInitDrag : function(x, y){
- var clone = this.el.dom.cloneNode(true);
- clone.id = Roo.id(); // prevent duplicate ids
- this.proxy.update(clone);
- this.onStartDrag(x, y);
- return true;
- },
-
- /**
- * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
- * @return {Roo.dd.StatusProxy} proxy The StatusProxy
- */
- getProxy : function(){
- return this.proxy;
- },
-
- /**
- * Hides the drag source's {@link Roo.dd.StatusProxy}
- */
- hideProxy : function(){
- this.proxy.hide();
- this.proxy.reset(true);
- this.dragging = false;
- },
-
- // private
- triggerCacheRefresh : function(){
- Roo.dd.DDM.refreshCache(this.groups);
- },
-
- // private - override to prevent hiding
- b4EndDrag: function(e) {
- },
-
- // private - override to prevent moving
- endDrag : function(e){
- this.onEndDrag(this.dragData, e);
- },
-
- // private
- onEndDrag : function(data, e){
- },
-
- // private - pin to cursor
- autoOffset : function(x, y) {
- this.setDelta(-12, -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.dd.DropTarget
- * @extends Roo.dd.DDTarget
- * A simple class that provides the basic implementation needed to make any element a drop target that can have
- * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
- * @constructor
- * @param {String/HTMLElement/Element} el The container element
- * @param {Object} config
- */
-Roo.dd.DropTarget = function(el, config){
- this.el = Roo.get(el);
-
- var listeners = false; ;
- if (config && config.listeners) {
- listeners= config.listeners;
- delete config.listeners;
- }
- Roo.apply(this, config);
-
- if(this.containerScroll){
- Roo.dd.ScrollManager.register(this.el);
- }
- this.addEvents( {
- /**
- * @scope Roo.dd.DropTarget
- */
-
- /**
- * @event enter
- * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
- * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
- * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
- *
- * IMPORTANT : it should set this.overClass and this.dropAllowed
- *
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag source
- */
- "enter" : true,
-
- /**
- * @event over
- * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
- * This method will be called on every mouse movement while the drag source is over the drop target.
- * This default implementation simply returns the dropAllowed config value.
- *
- * IMPORTANT : it should set this.dropAllowed
- *
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag source
-
- */
- "over" : true,
- /**
- * @event out
- * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
- * out of the target without dropping. This default implementation simply removes the CSS class specified by
- * overClass (if any) from the drop element.
- *
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag source
- */
- "out" : true,
-
- /**
- * @event drop
- * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
- * been dropped on it. This method has no default implementation and returns false, so you must provide an
- * implementation that does something to process the drop event and returns true so that the drag source's
- * repair action does not run.
- *
- * IMPORTANT : it should set this.success
- *
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag source
- */
- "drop" : true
- });
-
-
- Roo.dd.DropTarget.superclass.constructor.call( this,
- this.el.dom,
- this.ddGroup || this.group,
- {
- isTarget: true,
- listeners : listeners || {}
-
-
- }
- );
-
-};
-
-Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
- /**
- * @cfg {String} overClass
- * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
- */
- /**
- * @cfg {String} ddGroup
- * The drag drop group to handle drop events for
- */
-
- /**
- * @cfg {String} dropAllowed
- * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
- */
- dropAllowed : "x-dd-drop-ok",
- /**
- * @cfg {String} dropNotAllowed
- * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
- */
- dropNotAllowed : "x-dd-drop-nodrop",
- /**
- * @cfg {boolean} success
- * set this after drop listener..
- */
- success : false,
- /**
- * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
- * if the drop point is valid for over/enter..
- */
- valid : false,
- // private
- isTarget : true,
-
- // private
- isNotifyTarget : true,
-
- /**
- * @hide
- */
- notifyEnter : function(dd, e, data)
- {
- this.valid = true;
- this.fireEvent('enter', dd, e, data);
- if(this.overClass){
- this.el.addClass(this.overClass);
- }
- return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
- this.valid ? this.dropAllowed : this.dropNotAllowed
- );
- },
-
- /**
- * @hide
- */
- notifyOver : function(dd, e, data)
- {
- this.valid = true;
- this.fireEvent('over', dd, e, data);
- return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
- this.valid ? this.dropAllowed : this.dropNotAllowed
- );
- },
-
- /**
- * @hide
- */
- notifyOut : function(dd, e, data)
- {
- this.fireEvent('out', dd, e, data);
- if(this.overClass){
- this.el.removeClass(this.overClass);
- }
- },
-
- /**
- * @hide
- */
- notifyDrop : function(dd, e, data)
- {
- this.success = false;
- this.fireEvent('drop', dd, e, data);
- return this.success;
- }
-});/*
- * 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.dd.DragZone
- * @extends Roo.dd.DragSource
- * This class provides a container DD instance that proxies for multiple child node sources.<br />
- * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
- * @constructor
- * @param {String/HTMLElement/Element} el The container element
- * @param {Object} config
- */
-Roo.dd.DragZone = function(el, config){
- Roo.dd.DragZone.superclass.constructor.call(this, el, config);
- if(this.containerScroll){
- Roo.dd.ScrollManager.register(this.el);
- }
-};
-
-Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
- /**
- * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
- * for auto scrolling during drag operations.
- */
- /**
- * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
- * method after a failed drop (defaults to "c3daf9" - light blue)
- */
-
- /**
- * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
- * for a valid target to drag based on the mouse down. Override this method
- * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
- * object has a "ddel" attribute (with an HTML Element) for other functions to work.
- * @param {EventObject} e The mouse down event
- * @return {Object} The dragData
- */
- getDragData : function(e){
- return Roo.dd.Registry.getHandleFromEvent(e);
- },
-
- /**
- * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
- * this.dragData.ddel
- * @param {Number} x The x position of the click on the dragged object
- * @param {Number} y The y position of the click on the dragged object
- * @return {Boolean} true to continue the drag, false to cancel
- */
- onInitDrag : function(x, y){
- this.proxy.update(this.dragData.ddel.cloneNode(true));
- this.onStartDrag(x, y);
- return true;
- },
-
- /**
- * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
- */
- afterRepair : function(){
- if(Roo.enableFx){
- Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
- }
- this.dragging = false;
- },
-
- /**
- * Called before a repair of an invalid drop to get the XY to animate to. By default returns
- * the XY of this.dragData.ddel
- * @param {EventObject} e The mouse up event
- * @return {Array} The xy location (e.g. [100, 200])
- */
- getRepairXY : function(e){
- return Roo.Element.fly(this.dragData.ddel).getXY();
- }
-});/*
- * 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.dd.DropZone
- * @extends Roo.dd.DropTarget
- * This class provides a container DD instance that proxies for multiple child node targets.<br />
- * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
- * @constructor
- * @param {String/HTMLElement/Element} el The container element
- * @param {Object} config
- */
-Roo.dd.DropZone = function(el, config){
- Roo.dd.DropZone.superclass.constructor.call(this, el, config);
-};
-
-Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
- /**
- * Returns a custom data object associated with the DOM node that is the target of the event. By default
- * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
- * provide your own custom lookup.
- * @param {Event} e The event
- * @return {Object} data The custom data
- */
- getTargetFromEvent : function(e){
- return Roo.dd.Registry.getTargetFromEvent(e);
- },
-
- /**
- * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
- * that it has registered. This method has no default implementation and should be overridden to provide
- * node-specific processing if necessary.
- * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
- * {@link #getTargetFromEvent} for this node)
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag source
- */
- onNodeEnter : function(n, dd, e, data){
-
- },
-
- /**
- * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
- * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
- * overridden to provide the proper feedback.
- * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
- * {@link #getTargetFromEvent} for this node)
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag source
- * @return {String} status The CSS class that communicates the drop status back to the source so that the
- * underlying {@link Roo.dd.StatusProxy} can be updated
- */
- onNodeOver : function(n, dd, e, data){
- return this.dropAllowed;
- },
-
- /**
- * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
- * the drop node without dropping. This method has no default implementation and should be overridden to provide
- * node-specific processing if necessary.
- * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
- * {@link #getTargetFromEvent} for this node)
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag source
- */
- onNodeOut : function(n, dd, e, data){
-
- },
-
- /**
- * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
- * the drop node. The default implementation returns false, so it should be overridden to provide the
- * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
- * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
- * {@link #getTargetFromEvent} for this node)
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag source
- * @return {Boolean} True if the drop was valid, else false
- */
- onNodeDrop : function(n, dd, e, data){
- return false;
- },
-
- /**
- * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
- * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
- * it should be overridden to provide the proper feedback if necessary.
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag source
- * @return {String} status The CSS class that communicates the drop status back to the source so that the
- * underlying {@link Roo.dd.StatusProxy} can be updated
- */
- onContainerOver : function(dd, e, data){
- return this.dropNotAllowed;
- },
-
- /**
- * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
- * but not on any of its registered drop nodes. The default implementation returns false, so it should be
- * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
- * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag source
- * @return {Boolean} True if the drop was valid, else false
- */
- onContainerDrop : function(dd, e, data){
- return false;
- },
-
- /**
- * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
- * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
- * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
- * you should override this method and provide a custom implementation.
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag source
- * @return {String} status The CSS class that communicates the drop status back to the source so that the
- * underlying {@link Roo.dd.StatusProxy} can be updated
- */
- notifyEnter : function(dd, e, data){
- return this.dropNotAllowed;
- },
-
- /**
- * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
- * This method will be called on every mouse movement while the drag source is over the drop zone.
- * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
- * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
- * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
- * registered node, it will call {@link #onContainerOver}.
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag source
- * @return {String} status The CSS class that communicates the drop status back to the source so that the
- * underlying {@link Roo.dd.StatusProxy} can be updated
- */
- notifyOver : function(dd, e, data){
- var n = this.getTargetFromEvent(e);
- if(!n){ // not over valid drop target
- if(this.lastOverNode){
- this.onNodeOut(this.lastOverNode, dd, e, data);
- this.lastOverNode = null;
- }
- return this.onContainerOver(dd, e, data);
- }
- if(this.lastOverNode != n){
- if(this.lastOverNode){
- this.onNodeOut(this.lastOverNode, dd, e, data);
- }
- this.onNodeEnter(n, dd, e, data);
- this.lastOverNode = n;
- }
- return this.onNodeOver(n, dd, e, data);
- },
-
- /**
- * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
- * out of the zone without dropping. If the drag source is currently over a registered node, the notification
- * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag zone
- */
- notifyOut : function(dd, e, data){
- if(this.lastOverNode){
- this.onNodeOut(this.lastOverNode, dd, e, data);
- this.lastOverNode = null;
- }
- },
-
- /**
- * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
- * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
- * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
- * otherwise it will call {@link #onContainerDrop}.
- * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
- * @param {Event} e The event
- * @param {Object} data An object containing arbitrary data supplied by the drag source
- * @return {Boolean} True if the drop was valid, else false
- */
- notifyDrop : function(dd, e, data){
- if(this.lastOverNode){
- this.onNodeOut(this.lastOverNode, dd, e, data);
- this.lastOverNode = null;
- }
- var n = this.getTargetFromEvent(e);
- return n ?
- this.onNodeDrop(n, dd, e, data) :
- this.onContainerDrop(dd, e, data);
- },
-
- // private
- triggerCacheRefresh : function(){
- Roo.dd.DDM.refreshCache(this.groups);
- }
-});/*
- * 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.data.SortTypes
- * @singleton
- * Defines the default sorting (casting?) comparison functions used when sorting data.
- */
-Roo.data.SortTypes = {
- /**
- * Default sort that does nothing
- * @param {Mixed} s The value being converted
- * @return {Mixed} The comparison value
- */
- none : function(s){
- return s;
- },
-
- /**
- * The regular expression used to strip tags
- * @type {RegExp}
- * @property
- */
- stripTagsRE : /<\/?[^>]+>/gi,
-
- /**
- * Strips all HTML tags to sort on text only
- * @param {Mixed} s The value being converted
- * @return {String} The comparison value
- */
- asText : function(s){
- return String(s).replace(this.stripTagsRE, "");
- },
-
- /**
- * Strips all HTML tags to sort on text only - Case insensitive
- * @param {Mixed} s The value being converted
- * @return {String} The comparison value
- */
- asUCText : function(s){
- return String(s).toUpperCase().replace(this.stripTagsRE, "");
- },
-
- /**
- * Case insensitive string
- * @param {Mixed} s The value being converted
- * @return {String} The comparison value
- */
- asUCString : function(s) {
- return String(s).toUpperCase();
- },
-
- /**
- * Date sorting
- * @param {Mixed} s The value being converted
- * @return {Number} The comparison value
- */
- asDate : function(s) {
- if(!s){
- return 0;
- }
- if(s instanceof Date){
- return s.getTime();
- }
- return Date.parse(String(s));
- },
-
- /**
- * Float sorting
- * @param {Mixed} s The value being converted
- * @return {Float} The comparison value
- */
- asFloat : function(s) {
- var val = parseFloat(String(s).replace(/,/g, ""));
- if(isNaN(val)) val = 0;
- return val;
- },
-
- /**
- * Integer sorting
- * @param {Mixed} s The value being converted
- * @return {Number} The comparison value
- */
- asInt : function(s) {
- var val = parseInt(String(s).replace(/,/g, ""));
- if(isNaN(val)) val = 0;
- return val;
- }
-};/*
- * 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.data.Record
- * Instances of this class encapsulate both record <em>definition</em> information, and record
- * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
- * to access Records cached in an {@link Roo.data.Store} object.<br>
- * <p>
- * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
- * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
- * objects.<br>
- * <p>
- * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
- * @constructor
- * This constructor should not be used to create Record objects. Instead, use the constructor generated by
- * {@link #create}. The parameters are the same.
- * @param {Array} data An associative Array of data values keyed by the field name.
- * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
- * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
- * not specified an integer id is generated.
- */
-Roo.data.Record = function(data, id){
- this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
- this.data = data;
-};
-
-/**
- * Generate a constructor for a specific record layout.
- * @param {Array} o An Array of field definition objects which specify field names, and optionally,
- * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
- * Each field definition object may contain the following properties: <ul>
- * <li><b>name</b> : String<p style="margin-left:1em">The name by which the field is referenced within the Record. This is referenced by,
- * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
- * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
- * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
- * is being used, then this is a string containing the javascript expression to reference the data relative to
- * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
- * to the data item relative to the record element. If the mapping expression is the same as the field name,
- * this may be omitted.</p></li>
- * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
- * <ul><li>auto (Default, implies no conversion)</li>
- * <li>string</li>
- * <li>int</li>
- * <li>float</li>
- * <li>boolean</li>
- * <li>date</li></ul></p></li>
- * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
- * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
- * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
- * by the Reader into an object that will be stored in the Record. It is passed the
- * following parameters:<ul>
- * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
- * </ul></p></li>
- * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
- * </ul>
- * <br>usage:<br><pre><code>
-var TopicRecord = Roo.data.Record.create(
- {name: 'title', mapping: 'topic_title'},
- {name: 'author', mapping: 'username'},
- {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
- {name: 'lastPost', mapping: 'post_time', type: 'date'},
- {name: 'lastPoster', mapping: 'user2'},
- {name: 'excerpt', mapping: 'post_text'}
-);
-
-var myNewRecord = new TopicRecord({
- title: 'Do my job please',
- author: 'noobie',
- totalPosts: 1,
- lastPost: new Date(),
- lastPoster: 'Animal',
- excerpt: 'No way dude!'
-});
-myStore.add(myNewRecord);
-</code></pre>
- * @method create
- * @static
- */
-Roo.data.Record.create = function(o){
- var f = function(){
- f.superclass.constructor.apply(this, arguments);
- };
- Roo.extend(f, Roo.data.Record);
- var p = f.prototype;
- p.fields = new Roo.util.MixedCollection(false, function(field){
- return field.name;
- });
- for(var i = 0, len = o.length; i < len; i++){
- p.fields.add(new Roo.data.Field(o[i]));
- }
- f.getField = function(name){
- return p.fields.get(name);
- };
- return f;
-};
-
-Roo.data.Record.AUTO_ID = 1000;
-Roo.data.Record.EDIT = 'edit';
-Roo.data.Record.REJECT = 'reject';
-Roo.data.Record.COMMIT = 'commit';
-
-Roo.data.Record.prototype = {
- /**
- * Readonly flag - true if this record has been modified.
- * @type Boolean
- */
- dirty : false,
- editing : false,
- error: null,
- modified: null,
-
- // private
- join : function(store){
- this.store = store;
- },
-
- /**
- * Set the named field to the specified value.
- * @param {String} name The name of the field to set.
- * @param {Object} value The value to set the field to.
- */
- set : function(name, value){
- if(this.data[name] == value){
- return;
- }
- this.dirty = true;
- if(!this.modified){
- this.modified = {};
- }
- if(typeof this.modified[name] == 'undefined'){
- this.modified[name] = this.data[name];
- }
- this.data[name] = value;
- if(!this.editing && this.store){
- this.store.afterEdit(this);
- }
- },
-
- /**
- * Get the value of the named field.
- * @param {String} name The name of the field to get the value of.
- * @return {Object} The value of the field.
- */
- get : function(name){
- return this.data[name];
- },
-
- // private
- beginEdit : function(){
- this.editing = true;
- this.modified = {};
- },
-
- // private
- cancelEdit : function(){
- this.editing = false;
- delete this.modified;
- },
-
- // private
- endEdit : function(){
- this.editing = false;
- if(this.dirty && this.store){
- this.store.afterEdit(this);
- }
- },
-
- /**
- * Usually called by the {@link Roo.data.Store} which owns the Record.
- * Rejects all changes made to the Record since either creation, or the last commit operation.
- * Modified fields are reverted to their original values.
- * <p>
- * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
- * of reject operations.
- */
- reject : function(){
- var m = this.modified;
- for(var n in m){
- if(typeof m[n] != "function"){
- this.data[n] = m[n];
- }
- }
- this.dirty = false;
- delete this.modified;
- this.editing = false;
- if(this.store){
- this.store.afterReject(this);
- }
- },
-
- /**
- * Usually called by the {@link Roo.data.Store} which owns the Record.
- * Commits all changes made to the Record since either creation, or the last commit operation.
- * <p>
- * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
- * of commit operations.
- */
- commit : function(){
- this.dirty = false;
- delete this.modified;
- this.editing = false;
- if(this.store){
- this.store.afterCommit(this);
- }
- },
-
- // private
- hasError : function(){
- return this.error != null;
- },
-
- // private
- clearError : function(){
- this.error = null;
- },
-
- /**
- * Creates a copy of this record.
- * @param {String} id (optional) A new record id if you don't want to use this record's id
- * @return {Record}
- */
- copy : function(newId) {
- return new this.constructor(Roo.apply({}, this.data), newId || this.id);
- }
-};/*
- * 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.data.Store
- * @extends Roo.util.Observable
- * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
- * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
- * <p>
- * A Store object uses an implementation of {@link Roo.data.DataProxy} to access a data object unless you call loadData() directly and pass in your data. The Store object
- * has no knowledge of the format of the data returned by the Proxy.<br>
- * <p>
- * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
- * instances from the data object. These records are cached and made available through accessor functions.
- * @constructor
- * Creates a new Store.
- * @param {Object} config A config object containing the objects needed for the Store to access data,
- * and read the data into Records.
- */
-Roo.data.Store = function(config){
- this.data = new Roo.util.MixedCollection(false);
- this.data.getKey = function(o){
- return o.id;
- };
- this.baseParams = {};
- // private
- this.paramNames = {
- "start" : "start",
- "limit" : "limit",
- "sort" : "sort",
- "dir" : "dir",
- "multisort" : "_multisort"
- };
-
- if(config && config.data){
- this.inlineData = config.data;
- delete config.data;
- }
-
- Roo.apply(this, config);
-
- if(this.reader){ // reader passed
- this.reader = Roo.factory(this.reader, Roo.data);
- this.reader.xmodule = this.xmodule || false;
- if(!this.recordType){
- this.recordType = this.reader.recordType;
- }
- if(this.reader.onMetaChange){
- this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
- }
- }
-
- if(this.recordType){
- this.fields = this.recordType.prototype.fields;
- }
- this.modified = [];
-
- this.addEvents({
- /**
- * @event datachanged
- * Fires when the data cache has changed, and a widget which is using this Store
- * as a Record cache should refresh its view.
- * @param {Store} this
- */
- datachanged : true,
- /**
- * @event metachange
- * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
- * @param {Store} this
- * @param {Object} meta The JSON metadata
- */
- metachange : true,
- /**
- * @event add
- * Fires when Records have been added to the Store
- * @param {Store} this
- * @param {Roo.data.Record[]} records The array of Records added
- * @param {Number} index The index at which the record(s) were added
- */
- add : true,
- /**
- * @event remove
- * Fires when a Record has been removed from the Store
- * @param {Store} this
- * @param {Roo.data.Record} record The Record that was removed
- * @param {Number} index The index at which the record was removed
- */
- remove : true,
- /**
- * @event update
- * Fires when a Record has been updated
- * @param {Store} this
- * @param {Roo.data.Record} record The Record that was updated
- * @param {String} operation The update operation being performed. Value may be one of:
- * <pre><code>
- Roo.data.Record.EDIT
- Roo.data.Record.REJECT
- Roo.data.Record.COMMIT
- * </code></pre>
- */
- update : true,
- /**
- * @event clear
- * Fires when the data cache has been cleared.
- * @param {Store} this
- */
- clear : true,
- /**
- * @event beforeload
- * Fires before a request is made for a new data object. If the beforeload handler returns false
- * the load action will be canceled.
- * @param {Store} this
- * @param {Object} options The loading options that were specified (see {@link #load} for details)
- */
- beforeload : true,
- /**
- * @event beforeloadadd
- * Fires after a new set of Records has been loaded.
- * @param {Store} this
- * @param {Roo.data.Record[]} records The Records that were loaded
- * @param {Object} options The loading options that were specified (see {@link #load} for details)
- */
- beforeloadadd : true,
- /**
- * @event load
- * Fires after a new set of Records has been loaded, before they are added to the store.
- * @param {Store} this
- * @param {Roo.data.Record[]} records The Records that were loaded
- * @param {Object} options The loading options that were specified (see {@link #load} for details)
- * @params {Object} return from reader
- */
- load : true,
- /**
- * @event loadexception
- * Fires if an exception occurs in the Proxy during loading.
- * Called with the signature of the Proxy's "loadexception" event.
- * 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} jsonData from your request (normally this contains the Exception)
- */
- loadexception : true
- });
-
- if(this.proxy){
- this.proxy = Roo.factory(this.proxy, Roo.data);
- this.proxy.xmodule = this.xmodule || false;
- this.relayEvents(this.proxy, ["loadexception"]);
- }
- this.sortToggle = {};
- this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
-
- Roo.data.Store.superclass.constructor.call(this);
-
- if(this.inlineData){
- this.loadData(this.inlineData);
- delete this.inlineData;
- }
-};
-
-Roo.extend(Roo.data.Store, Roo.util.Observable, {
- /**
- * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
- * without a remote query - used by combo/forms at present.
- */
-
- /**
- * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
- */
- /**
- * @cfg {Array} data Inline data to be loaded when the store is initialized.
- */
- /**
- * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
- * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
- */
- /**
- * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
- * on any HTTP request
- */
- /**
- * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
- */
- /**
- * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
- */
- multiSort: false,
- /**
- * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
- * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
- */
- remoteSort : false,
-
- /**
- * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
- * loaded or when a record is removed. (defaults to false).
- */
- pruneModifiedRecords : false,
-
- // private
- lastOptions : null,
-
- /**
- * Add Records to the Store and fires the add event.
- * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
- */
- add : function(records){
- records = [].concat(records);
- for(var i = 0, len = records.length; i < len; i++){
- records[i].join(this);
- }
- var index = this.data.length;
- this.data.addAll(records);
- this.fireEvent("add", this, records, index);
- },
-
- /**
- * Remove a Record from the Store and fires the remove event.
- * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
- */
- remove : function(record){
- var index = this.data.indexOf(record);
- this.data.removeAt(index);
- if(this.pruneModifiedRecords){
- this.modified.remove(record);
- }
- this.fireEvent("remove", this, record, index);
- },
-
- /**
- * Remove all Records from the Store and fires the clear event.
- */
- removeAll : function(){
- this.data.clear();
- if(this.pruneModifiedRecords){
- this.modified = [];
- }
- this.fireEvent("clear", this);
- },
-
- /**
- * Inserts Records to the Store at the given index and fires the add event.
- * @param {Number} index The start index at which to insert the passed Records.
- * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
- */
- insert : function(index, records){
- records = [].concat(records);
- for(var i = 0, len = records.length; i < len; i++){
- this.data.insert(index, records[i]);
- records[i].join(this);
- }
- this.fireEvent("add", this, records, index);
- },
-
- /**
- * Get the index within the cache of the passed Record.
- * @param {Roo.data.Record} record The Roo.data.Record object to to find.
- * @return {Number} The index of the passed Record. Returns -1 if not found.
- */
- indexOf : function(record){
- return this.data.indexOf(record);
- },
-
- /**
- * Get the index within the cache of the Record with the passed id.
- * @param {String} id The id of the Record to find.
- * @return {Number} The index of the Record. Returns -1 if not found.
- */
- indexOfId : function(id){
- return this.data.indexOfKey(id);
- },
-
- /**
- * Get the Record with the specified id.
- * @param {String} id The id of the Record to find.
- * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
- */
- getById : function(id){
- return this.data.key(id);
- },
-
- /**
- * Get the Record at the specified index.
- * @param {Number} index The index of the Record to find.
- * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
- */
- getAt : function(index){
- return this.data.itemAt(index);
- },
-
- /**
- * Returns a range of Records between specified indices.
- * @param {Number} startIndex (optional) The starting index (defaults to 0)
- * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
- * @return {Roo.data.Record[]} An array of Records
- */
- getRange : function(start, end){
- return this.data.getRange(start, end);
- },
-
- // private
- storeOptions : function(o){
- o = Roo.apply({}, o);
- delete o.callback;
- delete o.scope;
- this.lastOptions = o;
- },
-
- /**
- * Loads the Record cache from the configured Proxy using the configured Reader.
- * <p>
- * If using remote paging, then the first load call must specify the <em>start</em>
- * and <em>limit</em> properties in the options.params property to establish the initial
- * position within the dataset, and the number of Records to cache on each read from the Proxy.
- * <p>
- * <strong>It is important to note that for remote data sources, loading is asynchronous,
- * and this call will return before the new data has been loaded. Perform any post-processing
- * in a callback function, or in a "load" event handler.</strong>
- * <p>
- * @param {Object} options An object containing properties which control loading options:<ul>
- * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
- * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
- * passed the following arguments:<ul>
- * <li>r : Roo.data.Record[]</li>
- * <li>options: Options object from the load call</li>
- * <li>success: Boolean success indicator</li></ul></li>
- * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
- * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
- * </ul>
- */
- load : function(options){
- options = options || {};
- if(this.fireEvent("beforeload", this, options) !== false){
- this.storeOptions(options);
- var p = Roo.apply(options.params || {}, this.baseParams);
- // if meta was not loaded from remote source.. try requesting it.
- if (!this.reader.metaFromRemote) {
- p._requestMeta = 1;
- }
- if(this.sortInfo && this.remoteSort){
- var pn = this.paramNames;
- p[pn["sort"]] = this.sortInfo.field;
- p[pn["dir"]] = this.sortInfo.direction;
- }
- if (this.multiSort) {
- var pn = this.paramNames;
- p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
- }
-
- this.proxy.load(p, this.reader, this.loadRecords, this, options);
- }
- },
-
- /**
- * Reloads the Record cache from the configured Proxy using the configured Reader and
- * the options from the last load operation performed.
- * @param {Object} options (optional) An object containing properties which may override the options
- * used in the last load operation. See {@link #load} for details (defaults to null, in which case
- * the most recently used options are reused).
- */
- reload : function(options){
- this.load(Roo.applyIf(options||{}, this.lastOptions));
- },
-
- // private
- // Called as a callback by the Reader during a load operation.
- loadRecords : function(o, options, success){
- if(!o || success === false){
- if(success !== false){
- this.fireEvent("load", this, [], options, o);
- }
- if(options.callback){
- options.callback.call(options.scope || this, [], options, false);
- }
- return;
- }
- // if data returned failure - throw an exception.
- if (o.success === false) {
- // show a message if no listener is registered.
- if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
- Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
- }
- // loadmask wil be hooked into this..
- this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
- return;
- }
- var r = o.records, t = o.totalRecords || r.length;
-
- this.fireEvent("beforeloadadd", this, r, options, o);
-
- if(!options || options.add !== true){
- if(this.pruneModifiedRecords){
- this.modified = [];
- }
- for(var i = 0, len = r.length; i < len; i++){
- r[i].join(this);
- }
- if(this.snapshot){
- this.data = this.snapshot;
- delete this.snapshot;
- }
- this.data.clear();
- this.data.addAll(r);
- this.totalLength = t;
- this.applySort();
- this.fireEvent("datachanged", this);
- }else{
- this.totalLength = Math.max(t, this.data.length+r.length);
- this.add(r);
- }
- this.fireEvent("load", this, r, options, o);
- if(options.callback){
- options.callback.call(options.scope || this, r, options, true);
- }
- },
-
-
- /**
- * Loads data from a passed data block. A Reader which understands the format of the data
- * must have been configured in the constructor.
- * @param {Object} data The data block from which to read the Records. The format of the data expected
- * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
- * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
- */
- loadData : function(o, append){
- var r = this.reader.readRecords(o);
- this.loadRecords(r, {add: append}, true);
- },
-
- /**
- * Gets the number of cached records.
- * <p>
- * <em>If using paging, this may not be the total size of the dataset. If the data object
- * used by the Reader contains the dataset size, then the getTotalCount() function returns
- * the data set size</em>
- */
- getCount : function(){
- return this.data.length || 0;
- },
-
- /**
- * Gets the total number of records in the dataset as returned by the server.
- * <p>
- * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
- * the dataset size</em>
- */
- getTotalCount : function(){
- return this.totalLength || 0;
- },
-
- /**
- * Returns the sort state of the Store as an object with two properties:
- * <pre><code>
- field {String} The name of the field by which the Records are sorted
- direction {String} The sort order, "ASC" or "DESC"
- * </code></pre>
- */
- getSortState : function(){
- return this.sortInfo;
- },
-
- // private
- applySort : function(){
- if(this.sortInfo && !this.remoteSort){
- var s = this.sortInfo, f = s.field;
- var st = this.fields.get(f).sortType;
- var fn = function(r1, r2){
- var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
- return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
- };
- this.data.sort(s.direction, fn);
- if(this.snapshot && this.snapshot != this.data){
- this.snapshot.sort(s.direction, fn);
- }
- }
- },
-
- /**
- * Sets the default sort column and order to be used by the next load operation.
- * @param {String} fieldName The name of the field to sort by.
- * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
- */
- setDefaultSort : function(field, dir){
- this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
- },
-
- /**
- * Sort the Records.
- * If remote sorting is used, the sort is performed on the server, and the cache is
- * reloaded. If local sorting is used, the cache is sorted internally.
- * @param {String} fieldName The name of the field to sort by.
- * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
- */
- sort : function(fieldName, dir){
- var f = this.fields.get(fieldName);
- if(!dir){
- this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
-
- if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
- dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
- }else{
- dir = f.sortDir;
- }
- }
- this.sortToggle[f.name] = dir;
- this.sortInfo = {field: f.name, direction: dir};
- if(!this.remoteSort){
- this.applySort();
- this.fireEvent("datachanged", this);
- }else{
- this.load(this.lastOptions);
- }
- },
-
- /**
- * Calls the specified function for each of the Records in the cache.
- * @param {Function} fn The function to call. The Record is passed as the first parameter.
- * Returning <em>false</em> aborts and exits the iteration.
- * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
- */
- each : function(fn, scope){
- this.data.each(fn, scope);
- },
-
- /**
- * Gets all records modified since the last commit. Modified records are persisted across load operations
- * (e.g., during paging).
- * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
- */
- getModifiedRecords : function(){
- return this.modified;
- },
-
- // private
- createFilterFn : function(property, value, anyMatch){
- if(!value.exec){ // not a regex
- value = String(value);
- if(value.length == 0){
- return false;
- }
- value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
- }
- return function(r){
- return value.test(r.data[property]);
- };
+ return function(r){
+ return value.test(r.data[property]);
+ };
},
/**
this.sortInfo = meta.sortInfo || this.sortInfo;
this.modified = [];
this.fireEvent('metachange', this, this.reader.meta);
+ },
+
+ moveIndex : function(data, type)
+ {
+ var index = this.indexOf(data);
+
+ var newIndex = index + type;
+
+ this.remove(data);
+
+ this.insert(newIndex, data);
+
}
});/*
* Based on:
* Small helper class to make creating Stores from Array data easier.
* @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
* @cfg {Array} fields An array of field definition objects, or field name strings.
+ * @cfg {Object} an existing reader (eg. copied from another store)
* @cfg {Array} data The multi-dimensional array of data
* @constructor
* @param {Object} config
*/
-Roo.data.SimpleStore = function(config){
+Roo.data.SimpleStore = function(config)
+{
Roo.data.SimpleStore.superclass.constructor.call(this, {
isLocal : true,
- reader: new Roo.data.ArrayReader({
+ reader: typeof(config.reader) != 'undefined' ? config.reader : new Roo.data.ArrayReader({
id: config.id
},
Roo.data.Record.create(config.fields)
};
Roo.data.DataReader.prototype = {
+
+
+ readerType : 'Data',
/**
* Create an empty record
* @param {Object} data (optional) - overlay some values
return new this.recordType(Roo.apply(da, d));
}
+
};/*
* Based on:
* Ext JS Library 1.1.1
};
Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
+
/**
* Load data from the requested source (in this case an in-memory
* data object passed to the constructor), read the data object into
params = params || {};
var result;
try {
- result = reader.readRecords(this.data);
+ result = reader.readRecords(params.data ? params.data :this.data);
}catch(e){
this.fireEvent("loadexception", this, arg, null, e);
callback.call(scope, null, arg, false);
* @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
* @cfg {String} root name of the property which contains the Array of row objects.
* @cfg {String} id Name of the property within a row object that contains a record identifier value.
+ * @cfg {Array} fields Array of field definition objects
* @constructor
* Create a new JsonReader
* @param {Object} meta Metadata configuration options
};
Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
+ readerType : 'Json',
+
/**
* @prop {Boolean} metaFromRemote - if the meta data was loaded from the remote source.
* Used by Store query builder to append _requestMeta to params.
*/
this.o = o;
var s = this.meta, Record = this.recordType,
- f = Record.prototype.fields, fi = f.items, fl = f.length;
+ f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
// Generate extraction functions for the totalProperty, the root, the id, and for each field
if (!this.ef) {
if (s.id) {
var g = this.getJsonAccessor(s.id);
this.getId = function(rec) {
- var r = g(rec);
+ var r = g(rec);
return (r === undefined || r === "") ? null : r;
};
} else {
}
}
var records = [];
- for(var i = 0; i < c; i++){
- var n = root[i];
- var values = {};
- var id = this.getId(n);
- for(var j = 0; j < fl; j++){
- f = fi[j];
- var v = this.ef[j](n);
- if (!f.convert) {
- Roo.log('missing convert for ' + f.name);
- Roo.log(f);
- continue;
- }
- values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
- }
- var record = new Record(values, id);
- record.json = n;
- records[i] = record;
- }
- return {
+ for(var i = 0; i < c; i++){
+ var n = root[i];
+ var values = {};
+ var id = this.getId(n);
+ for(var j = 0; j < fl; j++){
+ f = fi[j];
+ var v = this.ef[j](n);
+ if (!f.convert) {
+ Roo.log('missing convert for ' + f.name);
+ Roo.log(f);
+ continue;
+ }
+ values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
+ }
+ var record = new Record(values, id);
+ record.json = n;
+ records[i] = record;
+ }
+ return {
raw : o,
- success : success,
- records : records,
- totalRecords : totalRecords
- };
+ success : success,
+ records : records,
+ totalRecords : totalRecords
+ };
+ },
+ // used when loading children.. @see loadDataFromChildren
+ toLoadData: function(rec)
+ {
+ // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
+ var data = typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
+ return { data : data, total : data.length };
+
}
});/*
* Based on:
Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
};
Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
+
+ readerType : 'Xml',
+
/**
* This method is only used by a DataProxy which has retrieved data from a remote server.
* @param {Object} response The XHR object which contains the parsed XML document. The response is expected
* <pre><code>
[ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
</code></pre>
- * @cfg {String} id (optional) The subscript within row Array that provides an ID for the Record
+
* @constructor
* Create a new JsonReader
* @param {Object} meta Metadata configuration options.
- * @param {Object} recordType Either an Array of field definition objects
+ * @param {Object|Array} recordType Either an Array of field definition objects
+ *
+ * @cfg {Array} fields Array of field definition objects
+ * @cfg {String} id Name of the property within a row object that contains a record identifier value.
* as specified to {@link Roo.data.Record#create},
* or an {@link Roo.data.Record} object
+ *
+ *
* created using {@link Roo.data.Record#create}.
*/
-Roo.data.ArrayReader = function(meta, recordType){
- Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType);
+Roo.data.ArrayReader = function(meta, recordType)
+{
+ Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
};
Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
- /**
+
+ /**
* Create a data block containing Roo.data.Records from an XML document.
* @param {Object} o An Array of row objects which represents the dataset.
- * @return {Object} data A data block which is used by an Roo.data.Store object as
+ * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
* a cache of Roo.data.Records.
*/
- readRecords : function(o){
+ readRecords : function(o)
+ {
var sid = this.meta ? this.meta.id : null;
var recordType = this.recordType, fields = recordType.prototype.fields;
var records = [];
var root = o;
- for(var i = 0; i < root.length; i++){
- var n = root[i];
- var values = {};
- var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
- for(var j = 0, jlen = fields.length; j < jlen; j++){
- var f = fields.items[j];
- var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
- var v = n[k] !== undefined ? n[k] : f.defaultValue;
- v = f.convert(v);
- values[f.name] = v;
- }
- var record = new recordType(values, id);
- record.json = n;
- records[records.length] = record;
+ for(var i = 0; i < root.length; i++){
+ var n = root[i];
+ var values = {};
+ var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
+ for(var j = 0, jlen = fields.length; j < jlen; j++){
+ var f = fields.items[j];
+ var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
+ var v = n[k] !== undefined ? n[k] : f.defaultValue;
+ v = f.convert(v);
+ values[f.name] = v;
}
- return {
- records : records,
- totalRecords : records.length
- };
+ var record = new recordType(values, id);
+ record.json = n;
+ records[records.length] = record;
+ }
+ return {
+ records : records,
+ totalRecords : records.length
+ };
+ },
+ // used when loading children.. @see loadDataFromChildren
+ toLoadData: function(rec)
+ {
+ // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
+ return typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
+
}
+
+
});/*
* Based on:
* Ext JS Library 1.1.1
}else if(arguments.length > 1){
multi = arguments;
}
+
// if passed an array or multiple args do them one by one
if(multi){
for(var i = 0, len = multi.length; i < len; i++) {
}
oldParent.removeChild(node);
}
+
index = this.childNodes.length;
if(index == 0){
this.setFirstChild(node);
this.setLastChild(node);
node.setOwnerTree(this.getOwnerTree());
this.fireEvent("append", this.ownerTree, this, node, index);
+ if(this.ownerTree) {
+ this.ownerTree.fireEvent("appendnode", this, node, index);
+ }
if(oldParent){
node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
}
*/
Roo.View = function(config, depreciated_tpl, depreciated_config){
+ this.parent = false;
+
if (typeof(depreciated_tpl) == 'undefined') {
// new way.. - universal constructor.
Roo.apply(this, config);
this.tpl.compile();
-
-
-
/** @private */
this.addEvents({
/**
var fctr = this.wrapEl.appendChild(document.createElement("div"));
- this.footer.dataSource = this.store
+ this.footer.dataSource = this.store;
this.footer.container = fctr;
this.footer = Roo.factory(this.footer, Roo);
fctr.insertFirst(this.el);
*/
toggleSelect : false,
+ /**
+ * @cfg {Boolean} tickable - selecting
+ */
+ tickable : false,
+
/**
* Returns the element this view is bound to.
* @return {Roo.Element}
* Refreshes the view. - called by datachanged on the store. - do not call directly.
*/
refresh : function(){
+ //Roo.log('refresh');
var t = this.tpl;
// if we are using something like 'domtemplate', then
for(var i = 0, len = records.length; i < len; i++){
var data = this.prepareData(records[i].data, i, records[i]);
this.fireEvent("preparedata", this, data, i, records[i]);
+
+ var d = Roo.apply({}, data);
+
+ if(this.tickable){
+ Roo.apply(d, {'roo-id' : Roo.id()});
+
+ var _this = this;
+
+ Roo.each(this.parent.item, function(item){
+ if(item[_this.parent.valueField] != data[_this.parent.valueField]){
+ return;
+ }
+ Roo.apply(d, {'roo-data-checked' : 'checked'});
+ });
+ }
+
html[html.length] = Roo.util.Format.trim(
this.dataName ?
- t.applySubtemplate(this.dataName, data, this.store.meta) :
- t.apply(data)
+ t.applySubtemplate(this.dataName, d, this.store.meta) :
+ t.apply(d)
);
}
this.nodes = el.dom.childNodes;
this.updateIndexes(0);
},
+
/**
* Function to override to reformat the data that is sent to
},
onUpdate : function(ds, record){
+ // Roo.log('on update');
this.clearSelections();
var index = this.store.indexOf(record);
var n = this.nodes[index];
// --------- FIXME
onAdd : function(ds, records, index)
{
+ //Roo.log(['on Add', ds, records, index] );
this.clearSelections();
if(this.nodes.length == 0){
this.refresh();
},
onRemove : function(ds, record, index){
+ // Roo.log('onRemove');
this.clearSelections();
var el = this.dataName ?
this.el.child('.roo-tpl-' + this.dataName) :
this.el;
+
el.dom.removeChild(this.nodes[index]);
this.updateIndexes(index);
},
* onbeforeLoad - masks the loading area.
*
*/
- onBeforeLoad : function()
+ onBeforeLoad : function(store,opts)
{
- this.el.update("");
+ //Roo.log('onBeforeLoad');
+ if (!opts.add) {
+ this.el.update("");
+ }
this.el.mask(this.mask ? this.mask : "Loading" );
},
onLoad : function ()
}
if (this.toggleSelect) {
var m = this.isSelected(item) ? 'unselect' : 'select';
- Roo.log(m);
+ //Roo.log(m);
var _t = this;
_t[m](item, true, false);
return true;
this.select(item, this.multiSelect && e.ctrlKey);
this.lastSelection = item;
}
- e.preventDefault();
+
+ if(!this.tickable){
+ e.preventDefault();
+ }
+
}
return true;
},
if(!keepExisting){
this.clearSelections(true);
}
+
if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
Roo.fly(node).addClass(this.selectedClass);
this.selections.push(node);
}
var node = this.getNode(nodeInfo);
if(!node || !this.isSelected(node)){
- Roo.log("not selected");
+ //Roo.log("not selected");
return; // not selected.
}
// fireevent???
um.update.apply(um, arguments);
},
+ // note - render is a standard framework call...
+ // using it for the response is really flaky... - it's called by UpdateManager normally, except when called by the XComponent/addXtype.
render : function(el, response){
+
this.clearSelections();
this.el.update("");
var o;
try{
- o = Roo.util.JSON.decode(response.responseText);
- if(this.jsonRoot){
-
- o = o[this.jsonRoot];
+ if (response != '') {
+ o = Roo.util.JSON.decode(response.responseText);
+ if(this.jsonRoot){
+
+ o = o[this.jsonRoot];
+ }
}
} catch(e){
}
var re = "(?:";
for(var i = 0; i < dd.length; i++){
re += dd[i];
- if(i != dd.length-1) re += "|";
+ if(i != dd.length-1) {
+ re += "|";
+ }
}
this.disabledDatesRE = new RegExp(re + ")");
}
autoSizeTabs : function(){
var count = this.items.length;
var vcount = count - this.hiddenCount;
- if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) return;
+ 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;
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);
+ if(!this.items[i].isHidden()) {
+ this.items[i].setWidth(width);
+ }
}
},
autoSize : function(){
//this.el.beginMeasure();
this.textEl.setWidth(1);
- this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr"));
+ /*
+ * #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();
},
},
// private
- onClick : function(e){
+ onClick : function(e)
+ {
if(e){
e.preventDefault();
}
* @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.Toolbar.Item.prototype = {
+Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
+//Roo.Toolbar.Item.prototype = {
/**
* Get this item's HTML Element
// private
render : function(td){
- this.td = td;
+
+ this.td = td;
td.appendChild(this.el);
+
+ this.fireEvent('render', this);
},
/**
this.disabled = false;
this.el.disabled = false;
}
-};
+});
/**
* @constructor
* Creates a new Separator
*/
-Roo.Toolbar.Separator = function(){
+Roo.Toolbar.Separator = function(cfg){
+
var s = document.createElement("span");
s.className = "ytb-sep";
- Roo.Toolbar.Separator.superclass.constructor.call(this, s);
+ 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,
* @constructor
* Creates a new Spacer
*/
-Roo.Toolbar.Spacer = function(){
+Roo.Toolbar.Spacer = function(cfg){
var s = document.createElement("div");
s.className = "ytb-spacer";
- Roo.Toolbar.Spacer.superclass.constructor.call(this, s);
+ 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,
* Creates a new TextItem
* @param {String} text
*/
-Roo.Toolbar.TextItem = function(text){
- if (typeof(text) == 'object') {
- text = text.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;
- Roo.Toolbar.TextItem.superclass.constructor.call(this, s);
+ 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
{
var v = this.field.dom.value, pageNum;
var increment = (e.shiftKey) ? 10 : 1;
- if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
+ 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;
// private
snap : function(value, inc, min){
- if(!inc || !value) return value;
+ if(!inc || !value) {
+ return value;
+ }
var newValue = value;
var m = value % inc;
if(m > 0){
// private
Roo.Resizable.Handle.prototype = {
afterResize : function(rz){
+ Roo.log('after?');
// do nothing
},
// private
t.removeAttribute("title");
e.preventDefault();
}else{
- ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute);
+ 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,
+ 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),
// private
tagConfig : {
- namespace : "ext",
+ namespace : "roo", // was ext?? this may break..
+ alt_namespace : "ext",
attribute : "qtip",
width : "width",
target : "target",
* </ul>
* @param {Object} dragOverEvent
*/
- "nodedragover" : true
+ "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){
* @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.
+ * 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 #)
this.renderChildren();
}
this.expanded = true;
- if(!this.isHiddenRoot() && (this.getOwnerTree().animate && anim !== false) || anim){
+
+ if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
this.ui.animExpand(function(){
this.fireEvent("expand", this);
if(typeof callback == "function"){
this.addClass("x-tree-node-disabled");
}
var ot = this.node.getOwnerTree();
- var dd = ot.enableDD || ot.enableDrag || ot.enableDrop;
+ 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,
// 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.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
+ 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.rendererTip ? t.rendererTip(n.attributes) : txt;
+ 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,'">',
myTreeLoader.on("beforeload", function(treeLoader, node) {
this.baseParams.category = node.attributes.category;
}, this);
-</code></pre><
+
+</code></pre>
+ *
* This would pass an HTTP parameter called "category" to the server containing
* the value of the Node's "category" attribute.
* @constructor
* @param {Object} config Configuration options
*/
Roo.menu.Menu = function(config){
- Roo.apply(this, config);
+
+ Roo.menu.Menu.superclass.constructor.call(this, config);
+
this.id = this.id || Roo.id();
this.addEvents({
/**
tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
});
var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
- ul.on("click", this.onClick, this);
+ //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){
// private
onClick : function(e){
- var t;
- if(t = this.findTargetItem(e)){
- t.onClick(e);
- this.fireEvent("click", this, t, e);
+ Roo.log("menu.onClick");
+ var t = this.findTargetItem(e);
+ if(!t){
+ return;
}
+ 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;
+
+
+ }
+
+ t.onClick(e);
+ this.fireEvent("click", this, t, e);
},
// private
* <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, {
+
+ /**
+ * @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;
+
+ },
+
+ 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);
+ }
+ }
+
+});/*
+ * 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
* @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: "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")
*/
/**
* @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);
/**
* 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 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;
+ }
+ return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
+ },
+
+
+
// private
afterRender : function(){
Roo.form.Field.superclass.afterRender.call(this);
* Resets the current field value to the originally loaded value and clears any validation messages
*/
reset : function(){
- this.setValue(this.originalValue);
+ this.setValue(this.resetValue);
+ this.originalValue = this.getValue();
this.clearInvalid();
},
// reference to original value for reset
this.originalValue = this.getValue();
+ this.resetValue = this.getValue();
},
// private
if(!this.rendered || this.preventMark){ // not rendered
return;
}
- this.el.addClass(this.invalidClass);
+
+ 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':
- this.el.dom.qtip = msg;
- this.el.dom.qclass = 'x-form-invalid-tip';
+ 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();
}
if(!this.rendered || this.preventMark){ // not rendered
return;
}
- this.el.removeClass(this.invalidClass);
+ var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
+
+ obj.el.removeClass(this.invalidClass);
switch(this.msgTarget){
case 'qtip':
- this.el.dom.qtip = '';
+ obj.el.dom.qtip = '';
break;
case 'title':
this.el.dom.title = '';
* @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} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
*/
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);
}
this.autoSize();
}
},
-
+ // 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
preFocus : function(){
* @return {Boolean} True if the value is valid, else false
*/
validateValue : function(value){
- Roo.log('run TEXTFILED validateValue');
if(value.length < 1) { // if it's blank
if(this.allowBlank){
this.clearInvalid();
return true;
}else{
- Roo.log('run mark Invalid');
this.markInvalid(this.blankText);
return false;
}
return;
}
- if(isSelectAll){ // backspace and delete key
+ 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());
}
* @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: "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)
*/
this.defaultAutoCreate = {
tag: "textarea",
style:"width:300px;height:60px;",
- autocomplete: "off"
+ autocomplete: "new-password"
};
}
Roo.form.TextArea.superclass.onRender.call(this, ct, position);
* Create a new DateField
* @param {Object} config
*/
-Roo.form.DateField = function(config){
+Roo.form.DateField = function(config)
+{
Roo.form.DateField.superclass.constructor.call(this, config);
this.addEvents({
});
- if(typeof this.minValue == "string") this.minValue = this.parseDate(this.minValue);
- if(typeof this.maxValue == "string") this.maxValue = this.parseDate(this.maxValue);
+ 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(i != dd.length-1) {
+ re += "|";
+ }
}
this.ddMatch = new RegExp(re + ")");
}
if(v){
this.setValue(v);
}
- }
+ },
- /** @cfg {Boolean} grow @hide */
- /** @cfg {Number} growMin @hide */
- /** @cfg {Number} growMax @hide */
- /**
- * @hide
- * @method autoSize
+ /*@
+ * overide
+ *
*/
+ isDirty : function() {
+ if(this.disabled) {
+ return false;
+ }
+
+ if(typeof(this.startValue) === 'undefined'){
+ return false;
+ }
+
+ return String(this.getValue()) !== String(this.startValue);
+
+ },
+ // @overide
+ cleanLeadingSpace : function(e)
+ {
+ return;
+ }
+
});/*
* Based on:
* Ext JS Library 1.1.1
});
- if(typeof this.minValue == "string") this.minValue = this.parseDate(this.minValue);
- if(typeof this.maxValue == "string") this.maxValue = this.parseDate(this.maxValue);
+ 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(i != dd.length-1) {
+ re += "|";
+ }
}
this.ddMatch = new RegExp(re + ")");
}
* {tag: "input", type: "text", size: "10", autocomplete: "off"})
*/
// private
- defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
+ defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
// private
hiddenField: false,
// element that contains real text value.. (when hidden is used..)
// private
- onRender : function(ct, position){
+ onRender : function(ct, position)
+ {
Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
- if(this.hiddenName){
+
+ 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 =
}
+
if(Roo.isGecko){
this.el.dom.setAttribute('autocomplete', 'off');
}
}
this.view = new Roo.View(this.innerList, this.tpl, {
- singleSelect:true, store: this.store, selectedClass: this.selectedClass
+ singleSelect:true,
+ store: this.store,
+ selectedClass: this.selectedClass
});
this.view.on('click', this.onViewClick, this);
getValue : function(){
if(this.valueField){
return typeof this.value != 'undefined' ? this.value : '';
- }else{
- return Roo.form.ComboBox.superclass.getValue.call(this);
}
+ return Roo.form.ComboBox.superclass.getValue.call(this);
},
/**
// private
reset : function(){
// overridden so that last data is reset..
- this.setValue(this.originalValue);
+ this.setValue(this.resetValue);
+ this.originalValue = this.getValue();
this.clearInvalid();
this.lastData = false;
if (this.view) {
}
// scroll to?
this.view.select(match);
- var sn = Roo.get(this.view.getSelectedNodes()[0])
+ var sn = Roo.get(this.view.getSelectedNodes()[0]);
sn.scrollIntoView(sn.dom.parentNode, false);
- }
+ }
/**
* @cfg {Boolean} grow
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
+
+
+ });
Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
* @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 : ',',
// private the array of items that are displayed..
items : false,
// 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.name = this.name ? (this.name+'-subcombo') : this.name;
this.combo = Roo.factory(this.combo, Roo.form);
this.combo.onRender(ct, position);
{
var valueField = this.combo.valueField;
var displayField = this.combo.displayField;
+
if (this.items.indexOfKey(rec[valueField]) > -1) {
//console.log("GOT " + rec.data.id);
return;
x.render(this.outerWrap, this.wrap.dom);
// add the image handler..
},
-
- updateHiddenEl : function()
+
+ 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()
+ {
+ this.items.clear();
+
+ Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
+ el.remove();
+ });
+
+ 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..
+ {
+
+ 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)
+
+ }
+ if (typeof(v) == 'object' ) {
+ // then let's assume it's an array of objects..
+ Roo.each(v, function(l) {
+ this.addItem(l);
+ }, 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;
+ },
+
+ 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);
+ }
+
+ var originalValue = [];
+
+ for (var i = 0; i < d.length; i++){
+ originalValue.push(d[i][this.valueField]);
+ }
+
+ return String(this.getValue()) !== String(originalValue.join(this.seperator));
+
+ }
+
+});
+
+
+
+/**
+ * @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'
+ }
+ ]
+
+ },
+
+
+ onRender : function(ct, position)
+ {
+ Roo.form.Field.superclass.onRender.call(this, ct, position);
+
+ if(!this.el){
+ var cfg = this.getAutoCreate();
+ this.el = ct.createChild(cfg, position);
+ }
+
+ 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);
+ }
+
+ }
+});/*
+ * RooJS Library 1.1.1
+ * Copyright(c) 2008-2011 Alan Knowles
+ *
+ * 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
+ *
+ *
+ * @constructor
+ * Create a new ComboNested
+ * @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.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,
+
+ 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 : '';
+
+ // 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);
+ }
+
+ // 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'
+
+ 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 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,
+ {
+ 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) {
+
+ 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
+ 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)
{
- this.validate();
- if (!this.hiddenEl) {
+ 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'
+
+
+ }
+ if(!this.hasFocus){
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.validate();
+ 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();
},
- reset : function()
+
+ // private
+ onLoadException : function()
{
- //Roo.form.ComboBoxArray.superclass.reset.call(this);
- this.items.each(function(f) {
- f.remove();
- });
- this.el.dom.value = '';
- if (this.hiddenEl) {
- this.hiddenEl.dom.value = '';
+ 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);
}
+
},
- getValue: function()
- {
- return this.hiddenEl ? this.hiddenEl.dom.value : '';
- },
- setValue: function(v) // not a valid action - must use addItems..
+ // no cleaning of leading spaces on blur here.
+ cleanLeadingSpace : function(e) { },
+
+
+ onSelectChange : function (view, sels, opts )
{
+ var ix = view.getSelectedIndexes();
- 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(','), function(k) {
- Roo.log("CHECK " + this.valueField + ',' + k);
- var li = this.store.query(this.valueField, k);
- if (!li.length) {
- return;
+ 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);
}
- 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) {
- this.addItem(l);
- }, this);
-
+ }
+
+ return;
}
-
- },
- 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) {
+ 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;
}
- var kv = v[this.valueField];
- var dv = v[this.displayField];
- kv = typeof(kv) != 'string' ? '' : kv;
- dv = typeof(dv) != 'string' ? '' : dv;
+ var rec = view.store.getAt(ix[0]);
+
+ this.setFromData(rec.data);
+ this.fireEvent('select', this, rec, ix[0]);
- var keys = kv.split(',');
- var display = dv.split(',');
- for (var i = 0 ; i < keys.length; i++) {
-
- add = {};
- add[this.valueField] = keys[i];
- add[this.displayField] = display[i];
- this.addItem(add);
+ 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' });
}
-
- },
-
- /**
- * 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;
+ 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 false;
+
},
- validateValue : function(value){
- return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
-
- }
-});
-
-
-
-/**
- * @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'
- }
- ]
-
+ onDoubleClick : function()
+ {
+ this.collapse(); //??
},
-
- onRender : function(ct, position)
+
+
+
+
+ // private
+ recordToStack : function(store, prop, value, stack)
{
- Roo.form.Field.superclass.onRender.call(this, ct, position);
-
- if(!this.el){
- var cfg = this.getAutoCreate();
- this.el = ct.createChild(cfg, position);
+ 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;
}
-
- 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);
-
+ 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;
+ }
+ }
+
+ return true;
+ });
+ if (record == false) {
+ return false
+ }
+ stack.unshift(srec);
+ return record;
},
-
- remove : function()
+
+ /*
+ * find the stack of stores that match our value.
+ *
+ *
+ */
+
+ selectActive : function ()
{
-
- this.cb.items.remove(this);
- this.el.child('img').un('click', this.remove, this);
- this.el.remove();
- this.cb.updateHiddenEl();
+ // 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:
// private
onClick : function(){
+ if (this.disabled) {
+ return;
+ }
this.setChecked(!this.checked);
//if(this.el.dom.checked != this.checked){
}
Roo.form.Checkbox.superclass.onDestroy.call(this);
+ },
+
+ setBoxLabel : function(str)
+ {
+ this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
}
});/*
});//<script type="text/javascript">
/*
- * Ext JS Library 1.1.1
+ * Based Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
- * licensing@extjs.com
- *
- * http://www.extjs.com/license
+ * LGPL
+ *
*/
- /*
- *
- * Known bugs:
- * Default CSS appears to render it as fixed text by default (should really be Sans-Serif)
- * - IE ? - no idea how much works there.
- *
- *
- *
- */
-
-
/**
- * @class Ext.form.HtmlEditor
- * @extends Ext.form.Field
- * Provides a lightweight HTML Editor component.
+ * @class Roo.HtmlEditorCore
+ * @extends Roo.Component
+ * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
*
- * This has been tested on Fireforx / Chrome.. IE may not be so great..
- *
- * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
- * supported by this editor.</b><br/><br/>
- * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
* any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
*/
-Roo.form.HtmlEditor = Roo.extend(Roo.form.Field, {
- /**
- * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
- */
- toolbars : false,
- /**
- * @cfg {String} createLinkText The default text for the create link prompt
- */
- createLinkText : 'Please enter the URL for the link:',
- /**
- * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
+
+Roo.HtmlEditorCore = function(config){
+
+
+ Roo.HtmlEditorCore.superclass.constructor.call(this, config);
+
+
+ this.addEvents({
+ /**
+ * @event initialize
+ * Fires when the editor is fully initialized (including the iframe)
+ * @param {Roo.HtmlEditorCore} this
+ */
+ initialize: true,
+ /**
+ * @event activate
+ * Fires when the editor is first receives the focus. Any insertion must wait
+ * until after this event.
+ * @param {Roo.HtmlEditorCore} this
+ */
+ activate: true,
+ /**
+ * @event beforesync
+ * Fires before the textarea is updated with content from the editor iframe. Return false
+ * to cancel the sync.
+ * @param {Roo.HtmlEditorCore} this
+ * @param {String} html
+ */
+ beforesync: true,
+ /**
+ * @event beforepush
+ * Fires before the iframe editor is updated with content from the textarea. Return false
+ * to cancel the push.
+ * @param {Roo.HtmlEditorCore} this
+ * @param {String} html
+ */
+ beforepush: true,
+ /**
+ * @event sync
+ * Fires when the textarea is updated with content from the editor iframe.
+ * @param {Roo.HtmlEditorCore} this
+ * @param {String} html
+ */
+ sync: true,
+ /**
+ * @event push
+ * Fires when the iframe editor is updated with content from the textarea.
+ * @param {Roo.HtmlEditorCore} this
+ * @param {String} html
+ */
+ push: true,
+
+ /**
+ * @event editorevent
+ * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
+ * @param {Roo.HtmlEditorCore} this
+ */
+ editorevent: true
+
+ });
+
+ // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
+
+ // defaults : white / black...
+ this.applyBlacklists();
+
+
+
+};
+
+
+Roo.extend(Roo.HtmlEditorCore, Roo.Component, {
+
+
+ /**
+ * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field
*/
- defaultLinkValue : 'http:/'+'/',
-
+
+ owner : false,
+
/**
* @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
* Roo.resizable.
iframePad:3,
hideMode:'offsets',
- defaultAutoCreate : { // modified by initCompnoent..
- tag: "textarea",
- style:"width:500px;height:300px;",
- autocomplete: "off"
- },
-
- // private
- initComponent : function(){
- this.addEvents({
- /**
- * @event initialize
- * Fires when the editor is fully initialized (including the iframe)
- * @param {HtmlEditor} this
- */
- initialize: true,
- /**
- * @event activate
- * Fires when the editor is first receives the focus. Any insertion must wait
- * until after this event.
- * @param {HtmlEditor} this
- */
- activate: true,
- /**
- * @event beforesync
- * Fires before the textarea is updated with content from the editor iframe. Return false
- * to cancel the sync.
- * @param {HtmlEditor} this
- * @param {String} html
- */
- beforesync: true,
- /**
- * @event beforepush
- * Fires before the iframe editor is updated with content from the textarea. Return false
- * to cancel the push.
- * @param {HtmlEditor} this
- * @param {String} html
- */
- beforepush: true,
- /**
- * @event sync
- * Fires when the textarea is updated with content from the editor iframe.
- * @param {HtmlEditor} this
- * @param {String} html
- */
- sync: true,
- /**
- * @event push
- * Fires when the iframe editor is updated with content from the textarea.
- * @param {HtmlEditor} this
- * @param {String} html
- */
- push: true,
- /**
- * @event editmodechange
- * Fires when the editor switches edit modes
- * @param {HtmlEditor} this
- * @param {Boolean} sourceEdit True if source edit, false if standard editing.
- */
- editmodechange: true,
- /**
- * @event editorevent
- * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
- * @param {HtmlEditor} this
- */
- editorevent: true
- });
- this.defaultAutoCreate = {
- tag: "textarea",
- style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
- autocomplete: "off"
- };
- },
-
- /**
- * Protected method that will not generally be called directly. It
- * is called when the editor creates its toolbar. Override this method if you need to
- * add custom toolbar buttons.
- * @param {HtmlEditor} editor
- */
- createToolbar : function(editor){
- if (!editor.toolbars || !editor.toolbars.length) {
- editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
- }
-
- for (var i =0 ; i < editor.toolbars.length;i++) {
- editor.toolbars[i] = Roo.factory(
- typeof(editor.toolbars[i]) == 'string' ?
- { xtype: editor.toolbars[i]} : editor.toolbars[i],
- Roo.form.HtmlEditor);
- editor.toolbars[i].init(editor);
- }
-
-
- },
+ clearUp: true,
+
+ // blacklist + whitelisted elements..
+ black: false,
+ white: false,
+
+ bodyCls : '',
/**
* Protected method that will not generally be called directly. It
getDocMarkup : function(){
// body styles..
var st = '';
+
+ // inherit styels from page...??
if (this.stylesheets === false) {
Roo.get(document.head).select('style').each(function(node) {
st = '<style type="text/css">' +
'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
'</style>';
- } else {
- Roo.each(this.stylesheets, function(s) {
- st += '<link rel="stylesheet" type="text/css" href="' + s +'" />'
- });
-
+ } else {
+ st = '<style type="text/css">' +
+ this.stylesheets +
+ '</style>';
}
st += '<style type="text/css">' +
'IMG { cursor: pointer } ' +
'</style>';
+ var cls = 'roo-htmleditor-body';
+
+ if(this.bodyCls.length){
+ cls += ' ' + this.bodyCls;
+ }
return '<html><head>' + st +
//<style type="text/css">' +
//'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
//'</style>' +
- ' </head><body class="roo-htmleditor-body"></body></html>';
+ ' </head><body class="' + cls + '"></body></html>';
},
// private
onRender : function(ct, position)
{
var _t = this;
- Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
+ //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
+ this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
+
+
this.el.dom.style.border = '0 none';
this.el.dom.setAttribute('tabIndex', -1);
- this.el.addClass('x-hidden');
+ this.el.addClass('x-hidden hide');
+
+
+
if(Roo.isIE){ // fix IE 1px bogus margin
this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
}
- this.wrap = this.el.wrap({
- cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
- });
+
- if (this.resizable) {
- this.resizeEl = new Roo.Resizable(this.wrap, {
- pinned : true,
- wrap: true,
- dynamic : true,
- minHeight : this.height,
- height: this.height,
- handles : this.resizable,
- width: this.width,
- listeners : {
- resize : function(r, w, h) {
- _t.onResize(w,h); // -something
- }
- }
- });
-
- }
-
this.frameId = Roo.id();
- this.createToolbar(this);
-
-
+
- var iframe = this.wrap.createChild({
+ var iframe = this.owner.wrap.createChild({
tag: 'iframe',
+ cls: 'form-control', // bootstrap..
id: this.frameId,
name: this.frameId,
frameBorder : 'no',
}, this.el
);
- // console.log(iframe);
- //this.wrap.dom.appendChild(iframe);
-
+
this.iframe = iframe.dom;
this.assignDocWin();
}
},
interval : 10,
- duration:10000,
+ duration: 10000,
scope: this
};
Roo.TaskMgr.start(task);
- if(!this.width){
- this.setSize(this.wrap.getSize());
- }
- if (this.resizeEl) {
- this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
- // should trigger onReize..
- }
},
// private
onResize : function(w, h)
{
- //Roo.log('resize: ' +w + ',' + h );
- Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
- if(this.el && this.iframe){
- if(typeof w == 'number'){
- var aw = w - this.wrap.getFrameWidth('lr');
- this.el.setWidth(this.adjustWidth('textarea', aw));
- this.iframe.style.width = aw + 'px';
- }
- if(typeof h == 'number'){
- var tbh = 0;
- for (var i =0; i < this.toolbars.length;i++) {
- // fixme - ask toolbars for heights?
- tbh += this.toolbars[i].tb.el.getHeight();
- if (this.toolbars[i].footer) {
- tbh += this.toolbars[i].footer.el.getHeight();
- }
- }
-
-
-
-
- var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
- ah -= 5; // knock a few pixes off for look..
- this.el.setHeight(this.adjustWidth('textarea', ah));
- this.iframe.style.height = ah + 'px';
- if(this.doc){
- (this.doc.body || this.doc.documentElement).style.height = (ah - (this.iframePad*2)) + 'px';
- }
+ Roo.log('resize: ' +w + ',' + h );
+ //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
+ if(!this.iframe){
+ return;
+ }
+ if(typeof w == 'number'){
+
+ this.iframe.style.width = w + 'px';
+ }
+ if(typeof h == 'number'){
+
+ this.iframe.style.height = h + 'px';
+ if(this.doc){
+ (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
}
}
+
},
/**
this.sourceEditMode = sourceEditMode === true;
if(this.sourceEditMode){
-// Roo.log('in');
-// Roo.log(this.syncValue());
- this.syncValue();
- this.iframe.className = 'x-hidden';
- this.el.removeClass('x-hidden');
- this.el.dom.removeAttribute('tabIndex');
- this.el.focus();
+
+ Roo.get(this.iframe).addClass(['x-hidden','hide']); //FIXME - what's the BS styles for these
+
}else{
-// Roo.log('out')
-// Roo.log(this.pushValue());
- this.pushValue();
- this.iframe.className = '';
- this.el.addClass('x-hidden');
- this.el.dom.setAttribute('tabIndex', -1);
+ Roo.get(this.iframe).removeClass(['x-hidden','hide']);
+ //this.iframe.className = '';
this.deferFocus();
}
- this.setSize(this.wrap.getSize());
- this.fireEvent('editmodechange', this, this.sourceEditMode);
- },
-
- // private used internally
- createLink : function(){
- var url = prompt(this.createLinkText, this.defaultLinkValue);
- if(url && url != 'http:/'+'/'){
- this.relayCmd('createlink', url);
- }
- },
-
- // private (for BoxComponent)
- adjustSize : Roo.BoxComponent.prototype.adjustSize,
-
- // private (for BoxComponent)
- getResizeEl : function(){
- return this.wrap;
- },
-
- // private (for BoxComponent)
- getPositionEl : function(){
- return this.wrap;
- },
-
- // private
- initEvents : function(){
- this.originalValue = this.getValue();
+ //this.setSize(this.owner.wrap.getSize());
+ //this.fireEvent('editmodechange', this, this.sourceEditMode);
},
- /**
- * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
- * @method
- */
- markInvalid : Roo.emptyFn,
- /**
- * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
- * @method
- */
- clearInvalid : Roo.emptyFn,
-
- setValue : function(v){
- Roo.form.HtmlEditor.superclass.setValue.call(this, v);
- this.pushValue();
- },
+
+
/**
* Protected method that will not generally be called directly. If you need/want
},
/**
+ * HTML Editor -> Textarea
* Protected method that will not generally be called directly. Syncs the contents
* of the editor iframe with the textarea.
*/
var html = bd.innerHTML;
if(Roo.isSafari){
var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
- var m = bs.match(/text-align:(.*?);/i);
+ var m = bs ? bs.match(/text-align:(.*?);/i) : false;
if(m && m[1]){
html = '<div style="'+m[0]+'">' + html + '</div>';
}
html = this.cleanHtml(html);
// fix up the special chars.. normaly like back quotes in word...
// however we do not want to do this with chinese..
- html = html.replace(/([\x80-\uffff])/g, function (a, b) {
- var cc = b.charCodeAt();
- if (
+ html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
+
+ var cc = match.charCodeAt();
+
+ // Get the character value, handling surrogate pairs
+ if (match.length == 2) {
+ // It's a surrogate pair, calculate the Unicode code point
+ var high = match.charCodeAt(0) - 0xD800;
+ var low = match.charCodeAt(1) - 0xDC00;
+ cc = (high * 0x400) + low + 0x10000;
+ } else if (
(cc >= 0x4E00 && cc < 0xA000 ) ||
(cc >= 0x3400 && cc < 0x4E00 ) ||
(cc >= 0xf900 && cc < 0xfb00 )
) {
- return b;
- }
- return "&#"+cc+";"
+ return match;
+ }
+
+ // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
+ return "&#" + cc + ";";
+
+
});
- if(this.fireEvent('beforesync', this, html) !== false){
+
+
+
+ if(this.owner.fireEvent('beforesync', this, html) !== false){
this.el.dom.value = html;
- this.fireEvent('sync', this, html);
+ this.owner.fireEvent('sync', this, html);
}
}
},
*/
pushValue : function(){
if(this.initialized){
- var v = this.el.dom.value;
+ var v = this.el.dom.value.trim();
- if(v.length < 1){
- v = ' ';
- }
+// if(v.length < 1){
+// v = ' ';
+// }
- if(this.fireEvent('beforepush', this, v) !== false){
+ if(this.owner.fireEvent('beforepush', this, v) !== false){
var d = (this.doc.body || this.doc.documentElement);
d.innerHTML = v;
this.cleanUpPaste();
this.el.dom.value = d.innerHTML;
- this.fireEvent('push', this, v);
+ this.owner.fireEvent('push', this, v);
}
}
},
this.doc = iframe.contentWindow.document;
this.win = iframe.contentWindow;
} else {
- if (!Roo.get(this.frameId)) {
+// if (!Roo.get(this.frameId)) {
+// return;
+// }
+// this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
+// this.win = Roo.get(this.frameId).dom.contentWindow;
+
+ if (!Roo.get(this.frameId) && !iframe.contentDocument) {
return;
}
+
this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
- this.win = Roo.get(this.frameId).dom.contentWindow;
+ this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
}
},
//var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
// this copies styles from the containing element into thsi one..
// not sure why we need all of this..
- var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
- ss['background-attachment'] = 'fixed'; // w3c
+ //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
+
+ //var ss = this.el.getStyles( 'background-image', 'background-repeat');
+ //ss['background-attachment'] = 'fixed'; // w3c
dbody.bgProperties = 'fixed'; // ie
- Roo.DomHelper.applyStyles(dbody, ss);
+ //Roo.DomHelper.applyStyles(dbody, ss);
Roo.EventManager.on(this.doc, {
//'mousedown': this.onEditorEvent,
'mouseup': this.onEditorEvent,
}
this.initialized = true;
- this.fireEvent('initialize', this);
+ this.owner.fireEvent('initialize', this);
this.pushValue();
},
if(this.rendered){
- for (var i =0; i < this.toolbars.length;i++) {
- // fixme - ask toolbars for heights?
- this.toolbars[i].onDestroy();
- }
+ //for (var i =0; i < this.toolbars.length;i++) {
+ // // fixme - ask toolbars for heights?
+ // this.toolbars[i].onDestroy();
+ // }
- this.wrap.dom.innerHTML = '';
- this.wrap.remove();
+ //this.wrap.dom.innerHTML = '';
+ //this.wrap.remove();
}
},
this.activated = true;
- for (var i =0; i < this.toolbars.length;i++) {
- this.toolbars[i].onFirstFocus();
- }
-
+
+
if(Roo.isGecko){ // prevent silly gecko errors
this.win.focus();
var s = this.win.getSelection();
this.execCmd('styleWithCSS', false);
}catch(e){}
}
- this.fireEvent('activate', this);
+ this.owner.fireEvent('activate', this);
},
// private
this.execCmd('FontSize', v );
},
- onEditorEvent : function(e){
- this.fireEvent('editorevent', this, e);
+ onEditorEvent : function(e)
+ {
+ this.owner.fireEvent('editorevent', this, e);
// this.updateToolbar();
this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
},
insertTag : function(tg)
{
// could be a bit smarter... -> wrap the current selected tRoo..
- if (tg.toLowerCase() == 'span' || tg.toLowerCase() == 'code') {
+ if (tg.toLowerCase() == 'span' ||
+ tg.toLowerCase() == 'code' ||
+ tg.toLowerCase() == 'sup' ||
+ tg.toLowerCase() == 'sub'
+ ) {
range = this.createRange(this.getSelection());
var wrappingNode = this.doc.createElement(tg.toLowerCase());
range.insertNode(this.doc.createTextNode(txt));
} ,
- // private
- relayBtnCmd : function(btn){
- this.relayCmd(btn.cmd);
- },
+
/**
* Executes a Midas editor command on the editor document and performs necessary focus and
relayCmd : function(cmd, value){
this.win.focus();
this.execCmd(cmd, value);
- this.fireEvent('editorevent', this);
+ this.owner.fireEvent('editorevent', this);
//this.updateToolbar();
- this.deferFocus();
+ this.owner.deferFocus();
},
/**
insertAtCursor : function(text)
{
-
-
if(!this.activated){
return;
}
}
- while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
- a.push(p);
- p = p.parentNode;
- }
- a.push(this.doc.body);
- return a;
+ while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
+ a.push(p);
+ p = p.parentNode;
+ }
+ a.push(this.doc.body);
+ return a;
+ },
+ lastSel : false,
+ lastSelNode : false,
+
+
+ getSelection : function()
+ {
+ this.assignDocWin();
+ return Roo.isIE ? this.doc.selection : this.win.getSelection();
+ },
+
+ getSelectedNode: function()
+ {
+ // this may only work on Gecko!!!
+
+ // should we cache this!!!!
+
+
+
+
+ var range = this.createRange(this.getSelection()).cloneRange();
+
+ if (Roo.isIE) {
+ var parent = range.parentElement();
+ while (true) {
+ var testRange = range.duplicate();
+ testRange.moveToElementText(parent);
+ if (testRange.inRange(range)) {
+ break;
+ }
+ if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
+ break;
+ }
+ parent = parent.parentElement;
+ }
+ return parent;
+ }
+
+ // is ancestor a text element.
+ var ac = range.commonAncestorContainer;
+ if (ac.nodeType == 3) {
+ ac = ac.parentNode;
+ }
+
+ var ar = ac.childNodes;
+
+ var nodes = [];
+ var other_nodes = [];
+ var has_other_nodes = false;
+ for (var i=0;i<ar.length;i++) {
+ if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ?
+ continue;
+ }
+ // fullly contained node.
+
+ if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
+ nodes.push(ar[i]);
+ continue;
+ }
+
+ // probably selected..
+ if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
+ other_nodes.push(ar[i]);
+ continue;
+ }
+ // outer..
+ if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0)) {
+ continue;
+ }
+
+
+ has_other_nodes = true;
+ }
+ if (!nodes.length && other_nodes.length) {
+ nodes= other_nodes;
+ }
+ if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
+ return false;
+ }
+
+ return nodes[0];
+ },
+ createRange: function(sel)
+ {
+ // this has strange effects when using with
+ // top toolbar - not sure if it's a great idea.
+ //this.editor.contentWindow.focus();
+ if (typeof sel != "undefined") {
+ try {
+ return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
+ } catch(e) {
+ return this.doc.createRange();
+ }
+ } else {
+ return this.doc.createRange();
+ }
+ },
+ getParentElement: function()
+ {
+
+ this.assignDocWin();
+ var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
+
+ var range = this.createRange(sel);
+
+ try {
+ var p = range.commonAncestorContainer;
+ while (p.nodeType == 3) { // text node
+ p = p.parentNode;
+ }
+ return p;
+ } catch (e) {
+ return null;
+ }
+
+ },
+ /***
+ *
+ * Range intersection.. the hard stuff...
+ * '-1' = before
+ * '0' = hits..
+ * '1' = after.
+ * [ -- selected range --- ]
+ * [fail] [fail]
+ *
+ * basically..
+ * if end is before start or hits it. fail.
+ * if start is after end or hits it fail.
+ *
+ * if either hits (but other is outside. - then it's not
+ *
+ *
+ **/
+
+
+ // @see http://www.thismuchiknow.co.uk/?p=64.
+ rangeIntersectsNode : function(range, node)
+ {
+ var nodeRange = node.ownerDocument.createRange();
+ try {
+ nodeRange.selectNode(node);
+ } catch (e) {
+ nodeRange.selectNodeContents(node);
+ }
+
+ var rangeStartRange = range.cloneRange();
+ rangeStartRange.collapse(true);
+
+ var rangeEndRange = range.cloneRange();
+ rangeEndRange.collapse(false);
+
+ var nodeStartRange = nodeRange.cloneRange();
+ nodeStartRange.collapse(true);
+
+ var nodeEndRange = nodeRange.cloneRange();
+ nodeEndRange.collapse(false);
+
+ return rangeStartRange.compareBoundaryPoints(
+ Range.START_TO_START, nodeEndRange) == -1 &&
+ rangeEndRange.compareBoundaryPoints(
+ Range.START_TO_START, nodeStartRange) == 1;
+
+
+ },
+ rangeCompareNode : function(range, node)
+ {
+ var nodeRange = node.ownerDocument.createRange();
+ try {
+ nodeRange.selectNode(node);
+ } catch (e) {
+ nodeRange.selectNodeContents(node);
+ }
+
+
+ range.collapse(true);
+
+ nodeRange.collapse(true);
+
+ var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
+ var ee = range.compareBoundaryPoints( Range.END_TO_END, nodeRange);
+
+ //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
+
+ var nodeIsBefore = ss == 1;
+ var nodeIsAfter = ee == -1;
+
+ if (nodeIsBefore && nodeIsAfter) {
+ return 0; // outer
+ }
+ if (!nodeIsBefore && nodeIsAfter) {
+ return 1; //right trailed.
+ }
+
+ if (nodeIsBefore && !nodeIsAfter) {
+ return 2; // left trailed.
+ }
+ // fully contined.
+ return 3;
+ },
+
+ // private? - in a new class?
+ cleanUpPaste : function()
+ {
+ // cleans up the whole document..
+ Roo.log('cleanuppaste');
+
+ this.cleanUpChildren(this.doc.body);
+ var clean = this.cleanWordChars(this.doc.body.innerHTML);
+ if (clean != this.doc.body.innerHTML) {
+ this.doc.body.innerHTML = clean;
+ }
+
+ },
+
+ cleanWordChars : function(input) {// change the chars to hex code
+ var he = Roo.HtmlEditorCore;
+
+ var output = input;
+ Roo.each(he.swapCodes, function(sw) {
+ var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
+
+ output = output.replace(swapper, sw[1]);
+ });
+
+ return output;
+ },
+
+
+ cleanUpChildren : function (n)
+ {
+ if (!n.childNodes.length) {
+ return;
+ }
+ for (var i = n.childNodes.length-1; i > -1 ; i--) {
+ this.cleanUpChild(n.childNodes[i]);
+ }
+ },
+
+
+
+
+ cleanUpChild : function (node)
+ {
+ var ed = this;
+ //console.log(node);
+ if (node.nodeName == "#text") {
+ // clean up silly Windows -- stuff?
+ return;
+ }
+ if (node.nodeName == "#comment") {
+ node.parentNode.removeChild(node);
+ // clean up silly Windows -- stuff?
+ return;
+ }
+ var lcname = node.tagName.toLowerCase();
+ // we ignore whitelists... ?? = not really the way to go, but we probably have not got a full
+ // whitelist of tags..
+
+ if (this.black.indexOf(lcname) > -1 && this.clearUp ) {
+ // remove node.
+ node.parentNode.removeChild(node);
+ return;
+
+ }
+
+ var remove_keep_children= Roo.HtmlEditorCore.remove.indexOf(node.tagName.toLowerCase()) > -1;
+
+ // spans with no attributes - just remove them..
+ if ((!node.attributes || !node.attributes.length) && lcname == 'span') {
+ remove_keep_children = true;
+ }
+
+ // remove <a name=....> as rendering on yahoo mailer is borked with this.
+ // this will have to be flaged elsewhere - perhaps ablack=name... on the mailer..
+
+ //if (node.tagName.toLowerCase() == 'a' && !node.hasAttribute('href')) {
+ // remove_keep_children = true;
+ //}
+
+ if (remove_keep_children) {
+ this.cleanUpChildren(node);
+ // inserts everything just before this node...
+ while (node.childNodes.length) {
+ var cn = node.childNodes[0];
+ node.removeChild(cn);
+ node.parentNode.insertBefore(cn, node);
+ }
+ node.parentNode.removeChild(node);
+ return;
+ }
+
+ if (!node.attributes || !node.attributes.length) {
+
+
+
+
+ this.cleanUpChildren(node);
+ return;
+ }
+
+ function cleanAttr(n,v)
+ {
+
+ if (v.match(/^\./) || v.match(/^\//)) {
+ return;
+ }
+ if (v.match(/^(http|https):\/\//) || v.match(/^mailto:/) || v.match(/^ftp:/)) {
+ return;
+ }
+ if (v.match(/^#/)) {
+ return;
+ }
+// Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
+ node.removeAttribute(n);
+
+ }
+
+ var cwhite = this.cwhite;
+ var cblack = this.cblack;
+
+ function cleanStyle(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;
+ }
+ var l = p.split(':').shift().replace(/\s+/g,'');
+ l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
+
+ if ( cwhite.length && cblack.indexOf(l) > -1) {
+// Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
+ //node.removeAttribute(n);
+ return true;
+ }
+ //Roo.log()
+ // only allow 'c whitelisted system attributes'
+ if ( cwhite.length && cwhite.indexOf(l) < 0) {
+// Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
+ //node.removeAttribute(n);
+ return true;
+ }
+
+
+
+
+ clean.push(p);
+ return true;
+ });
+ if (clean.length) {
+ node.setAttribute(n, clean.join(';'));
+ } else {
+ node.removeAttribute(n);
+ }
+
+ }
+
+
+ for (var i = node.attributes.length-1; i > -1 ; i--) {
+ var a = node.attributes[i];
+ //console.log(a);
+
+ if (a.name.toLowerCase().substr(0,2)=='on') {
+ node.removeAttribute(a.name);
+ continue;
+ }
+ if (Roo.HtmlEditorCore.ablack.indexOf(a.name.toLowerCase()) > -1) {
+ node.removeAttribute(a.name);
+ continue;
+ }
+ if (Roo.HtmlEditorCore.aclean.indexOf(a.name.toLowerCase()) > -1) {
+ cleanAttr(a.name,a.value); // fixme..
+ continue;
+ }
+ if (a.name == 'style') {
+ cleanStyle(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?
+
+ }
+
+
+ this.cleanUpChildren(node);
+
+
+ },
+
+ /**
+ * Clean up MS wordisms...
+ */
+ cleanWord : function(node)
+ {
+ if (!node) {
+ this.cleanWord(this.doc.body);
+ return;
+ }
+
+ 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);
+ }
+ node.parentNode.removeChild(node);
+ }
+
+ if (node.nodeName == "#text") {
+ // clean up silly Windows -- stuff?
+ return;
+ }
+ if (node.nodeName == "#comment") {
+ node.parentNode.removeChild(node);
+ // clean up silly Windows -- stuff?
+ return;
+ }
+
+ if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
+ node.parentNode.removeChild(node);
+ return;
+ }
+ //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..
+ this.cleanWord(cn);
+ }
+ node.parentNode.removeChild(node);
+ /// no need to iterate chidlren = it's got none..
+ //this.iterateChildren(node, this.cleanWord);
+ return;
+ }
+ // 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 (node.hasAttribute("lang")) {
+ node.removeAttribute("lang");
+ }
+
+ 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');
+ }
+ }
+ this.iterateChildren(node, this.cleanWord);
+
+
+
+ },
+ /**
+ * iterateChildren of a Node, calling fn each time, using this as the scole..
+ * @param {DomNode} node node to iterate children of.
+ * @param {Function} fn method of this class to call on each item.
+ */
+ iterateChildren : function(node, fn)
+ {
+ if (!node.childNodes.length) {
+ return;
+ }
+ for (var i = node.childNodes.length-1; i > -1 ; i--) {
+ fn.call(this, node.childNodes[i])
+ }
+ },
+
+
+ /**
+ * 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..
+ *
+ */
+ cleanTableWidths : function(node)
+ {
+
+
+ if (!node) {
+ this.cleanTableWidths(this.doc.body);
+ return;
+ }
+
+ // ignore list...
+ if (node.nodeName == "#text" || node.nodeName == "#comment") {
+ return;
+ }
+ Roo.log(node.tagName);
+ if (!node.tagName.toLowerCase().match(/^(table|td|tr)$/)) {
+ this.iterateChildren(node, this.cleanTableWidths);
+ return;
+ }
+ if (node.hasAttribute('width')) {
+ node.removeAttribute('width');
+ }
+
+
+ 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.iterateChildren(node, this.cleanTableWidths);
+
+
},
- lastSel : false,
- lastSelNode : false,
- getSelection : function()
- {
- this.assignDocWin();
- return Roo.isIE ? this.doc.selection : this.win.getSelection();
- },
- getSelectedNode: function()
- {
- // this may only work on Gecko!!!
+
+ domToHTML : function(currentElement, depth, nopadtext) {
- // should we cache this!!!!
+ depth = depth || 0;
+ nopadtext = nopadtext || false;
+
+ if (!currentElement) {
+ return this.domToHTML(this.doc.body);
+ }
+ //Roo.log(currentElement);
+ var j;
+ var allText = false;
+ var nodeName = currentElement.nodeName;
+ var tagName = Roo.util.Format.htmlEncode(currentElement.tagName);
+ if (nodeName == '#text') {
+
+ return nopadtext ? currentElement.nodeValue : currentElement.nodeValue.trim();
+ }
-
- var range = this.createRange(this.getSelection()).cloneRange();
- if (Roo.isIE) {
- var parent = range.parentElement();
- while (true) {
- var testRange = range.duplicate();
- testRange.moveToElementText(parent);
- if (testRange.inRange(range)) {
- break;
+ var ret = '';
+ if (nodeName != 'BODY') {
+
+ var i = 0;
+ // Prints the node tagName, such as <A>, <IMG>, etc
+ if (tagName) {
+ var attr = [];
+ for(i = 0; i < currentElement.attributes.length;i++) {
+ // quoting?
+ var aname = currentElement.attributes.item(i).name;
+ if (!currentElement.attributes.item(i).value.length) {
+ continue;
+ }
+ attr.push(aname + '="' + Roo.util.Format.htmlEncode(currentElement.attributes.item(i).value) + '"' );
}
- if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
- break;
+
+ ret = "<"+currentElement.tagName+ ( attr.length ? (' ' + attr.join(' ') ) : '') + ">";
+ }
+ else {
+
+ // eack
+ }
+ } else {
+ tagName = false;
+ }
+ if (['IMG', 'BR', 'HR', 'INPUT'].indexOf(tagName) > -1) {
+ return ret;
+ }
+ if (['PRE', 'TEXTAREA', 'TD', 'A', 'SPAN'].indexOf(tagName) > -1) { // or code?
+ nopadtext = true;
+ }
+
+
+ // Traverse the tree
+ i = 0;
+ var currentElementChild = currentElement.childNodes.item(i);
+ var allText = true;
+ var innerHTML = '';
+ lastnode = '';
+ while (currentElementChild) {
+ // Formatting code (indent the tree so it looks nice on the screen)
+ var nopad = nopadtext;
+ if (lastnode == 'SPAN') {
+ nopad = true;
+ }
+ // text
+ if (currentElementChild.nodeName == '#text') {
+ var toadd = Roo.util.Format.htmlEncode(currentElementChild.nodeValue);
+ toadd = nopadtext ? toadd : toadd.trim();
+ if (!nopad && toadd.length > 80) {
+ innerHTML += "\n" + (new Array( depth + 1 )).join( " " );
}
- parent = parent.parentElement;
+ innerHTML += toadd;
+
+ i++;
+ currentElementChild = currentElement.childNodes.item(i);
+ lastNode = '';
+ continue;
}
- return parent;
+ allText = false;
+
+ innerHTML += nopad ? '' : "\n" + (new Array( depth + 1 )).join( " " );
+
+ // Recursively traverse the tree structure of the child node
+ innerHTML += this.domToHTML(currentElementChild, depth+1, nopadtext);
+ lastnode = currentElementChild.nodeName;
+ i++;
+ currentElementChild=currentElement.childNodes.item(i);
}
- // is ancestor a text element.
- var ac = range.commonAncestorContainer;
- if (ac.nodeType == 3) {
- ac = ac.parentNode;
+ ret += innerHTML;
+
+ if (!allText) {
+ // The remaining code is mostly for formatting the tree
+ ret+= nopadtext ? '' : "\n" + (new Array( depth )).join( " " );
}
- var ar = ac.childNodes;
-
- var nodes = [];
- var other_nodes = [];
- var has_other_nodes = false;
- for (var i=0;i<ar.length;i++) {
- if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ?
- continue;
+
+ if (tagName) {
+ ret+= "</"+tagName+">";
+ }
+ return ret;
+
+ },
+
+ applyBlacklists : function()
+ {
+ var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white : [];
+ var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black : [];
+
+ this.white = [];
+ this.black = [];
+ Roo.each(Roo.HtmlEditorCore.white, function(tag) {
+ if (b.indexOf(tag) > -1) {
+ return;
}
- // fullly contained node.
+ this.white.push(tag);
- if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
- nodes.push(ar[i]);
- continue;
+ }, this);
+
+ Roo.each(w, function(tag) {
+ if (b.indexOf(tag) > -1) {
+ return;
+ }
+ if (this.white.indexOf(tag) > -1) {
+ return;
}
+ this.white.push(tag);
- // probably selected..
- if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
- other_nodes.push(ar[i]);
- continue;
+ }, this);
+
+
+ Roo.each(Roo.HtmlEditorCore.black, function(tag) {
+ if (w.indexOf(tag) > -1) {
+ return;
}
- // outer..
- if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0)) {
- continue;
+ this.black.push(tag);
+
+ }, this);
+
+ Roo.each(b, function(tag) {
+ if (w.indexOf(tag) > -1) {
+ return;
+ }
+ if (this.black.indexOf(tag) > -1) {
+ return;
}
+ this.black.push(tag);
+ }, this);
+
+
+ w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite : [];
+ b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack : [];
+
+ this.cwhite = [];
+ this.cblack = [];
+ Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
+ if (b.indexOf(tag) > -1) {
+ return;
+ }
+ this.cwhite.push(tag);
- has_other_nodes = true;
- }
- if (!nodes.length && other_nodes.length) {
- nodes= other_nodes;
- }
- if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
- return false;
- }
+ }, this);
- return nodes[0];
+ Roo.each(w, function(tag) {
+ if (b.indexOf(tag) > -1) {
+ return;
+ }
+ if (this.cwhite.indexOf(tag) > -1) {
+ return;
+ }
+ this.cwhite.push(tag);
+
+ }, this);
+
+
+ Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
+ if (w.indexOf(tag) > -1) {
+ return;
+ }
+ this.cblack.push(tag);
+
+ }, this);
+
+ Roo.each(b, function(tag) {
+ if (w.indexOf(tag) > -1) {
+ return;
+ }
+ if (this.cblack.indexOf(tag) > -1) {
+ return;
+ }
+ this.cblack.push(tag);
+
+ }, this);
},
- createRange: function(sel)
+
+ setStylesheets : function(stylesheets)
{
- // this has strange effects when using with
- // top toolbar - not sure if it's a great idea.
- //this.editor.contentWindow.focus();
- if (typeof sel != "undefined") {
- try {
- return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
- } catch(e) {
- return this.doc.createRange();
- }
- } else {
- return this.doc.createRange();
+ if(typeof(stylesheets) == 'string'){
+ Roo.get(this.iframe.contentDocument.head).createChild({
+ tag : 'link',
+ rel : 'stylesheet',
+ type : 'text/css',
+ href : stylesheets
+ });
+
+ return;
}
+ var _this = this;
+
+ Roo.each(stylesheets, function(s) {
+ if(!s.length){
+ return;
+ }
+
+ Roo.get(_this.iframe.contentDocument.head).createChild({
+ tag : 'link',
+ rel : 'stylesheet',
+ type : 'text/css',
+ href : s
+ });
+ });
+
+
},
- getParentElement: function()
+
+ removeStylesheets : function()
{
+ var _this = this;
- this.assignDocWin();
- var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
+ Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
+ s.remove();
+ });
+ },
+
+ setStyle : function(style)
+ {
+ Roo.get(this.iframe.contentDocument.head).createChild({
+ tag : 'style',
+ type : 'text/css',
+ html : style
+ });
+
+ return;
+ }
+
+ // hide stuff that is not compatible
+ /**
+ * @event blur
+ * @hide
+ */
+ /**
+ * @event change
+ * @hide
+ */
+ /**
+ * @event focus
+ * @hide
+ */
+ /**
+ * @event specialkey
+ * @hide
+ */
+ /**
+ * @cfg {String} fieldClass @hide
+ */
+ /**
+ * @cfg {String} focusClass @hide
+ */
+ /**
+ * @cfg {String} autoCreate @hide
+ */
+ /**
+ * @cfg {String} inputType @hide
+ */
+ /**
+ * @cfg {String} invalidClass @hide
+ */
+ /**
+ * @cfg {String} invalidText @hide
+ */
+ /**
+ * @cfg {String} msgFx @hide
+ */
+ /**
+ * @cfg {String} validateOnBlur @hide
+ */
+});
+
+Roo.HtmlEditorCore.white = [
+ 'area', 'br', 'img', 'input', 'hr', 'wbr',
- var range = this.createRange(sel);
+ 'address', 'blockquote', 'center', 'dd', 'dir', 'div',
+ 'dl', 'dt', 'h1', 'h2', 'h3', 'h4',
+ 'h5', 'h6', 'hr', 'isindex', 'listing', 'marquee',
+ 'menu', 'multicol', 'ol', 'p', 'plaintext', 'pre',
+ 'table', 'ul', 'xmp',
+
+ 'caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
+ 'thead', 'tr',
+
+ 'dir', 'menu', 'ol', 'ul', 'dl',
+
+ 'embed', 'object'
+];
+
+
+Roo.HtmlEditorCore.black = [
+ // 'embed', 'object', // enable - backend responsiblity to clean thiese
+ 'applet', //
+ 'base', 'basefont', 'bgsound', 'blink', 'body',
+ 'frame', 'frameset', 'head', 'html', 'ilayer',
+ 'iframe', 'layer', 'link', 'meta', 'object',
+ 'script', 'style' ,'title', 'xml' // clean later..
+];
+Roo.HtmlEditorCore.clean = [
+ 'script', 'style', 'title', 'xml'
+];
+Roo.HtmlEditorCore.remove = [
+ 'font'
+];
+// attributes..
+
+Roo.HtmlEditorCore.ablack = [
+ 'on'
+];
+
+Roo.HtmlEditorCore.aclean = [
+ 'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc'
+];
+
+// protocols..
+Roo.HtmlEditorCore.pwhite= [
+ 'http', 'https', 'mailto'
+];
+
+// white listed style attributes.
+Roo.HtmlEditorCore.cwhite= [
+ // 'text-align', /// default is to allow most things..
+
- try {
- var p = range.commonAncestorContainer;
- while (p.nodeType == 3) { // text node
- p = p.parentNode;
- }
- return p;
- } catch (e) {
- return null;
- }
+// 'font-size'//??
+];
+
+// black listed style attributes.
+Roo.HtmlEditorCore.cblack= [
+ // 'font-size' -- this can be set by the project
+];
+
+
+Roo.HtmlEditorCore.swapCodes =[
+ [ 8211, "--" ],
+ [ 8212, "--" ],
+ [ 8216, "'" ],
+ [ 8217, "'" ],
+ [ 8220, '"' ],
+ [ 8221, '"' ],
+ [ 8226, "*" ],
+ [ 8230, "..." ]
+];
+
+ //<script type="text/javascript">
+
+/*
+ * Ext JS Library 1.1.1
+ * Copyright(c) 2006-2007, Ext JS, LLC.
+ * Licence LGPL
+ *
+ */
+
+
+Roo.form.HtmlEditor = function(config){
- },
- /***
- *
- * Range intersection.. the hard stuff...
- * '-1' = before
- * '0' = hits..
- * '1' = after.
- * [ -- selected range --- ]
- * [fail] [fail]
- *
- * basically..
- * if end is before start or hits it. fail.
- * if start is after end or hits it fail.
- *
- * if either hits (but other is outside. - then it's not
- *
- *
- **/
- // @see http://www.thismuchiknow.co.uk/?p=64.
- rangeIntersectsNode : function(range, node)
- {
- var nodeRange = node.ownerDocument.createRange();
- try {
- nodeRange.selectNode(node);
- } catch (e) {
- nodeRange.selectNodeContents(node);
- }
+ Roo.form.HtmlEditor.superclass.constructor.call(this, config);
- var rangeStartRange = range.cloneRange();
- rangeStartRange.collapse(true);
+ if (!this.toolbars) {
+ this.toolbars = [];
+ }
+ this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
- var rangeEndRange = range.cloneRange();
- rangeEndRange.collapse(false);
- var nodeStartRange = nodeRange.cloneRange();
- nodeStartRange.collapse(true);
+};
+
+/**
+ * @class Roo.form.HtmlEditor
+ * @extends Roo.form.Field
+ * Provides a lightweight HTML Editor component.
+ *
+ * This has been tested on Fireforx / Chrome.. IE may not be so great..
+ *
+ * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
+ * supported by this editor.</b><br/><br/>
+ * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
+ * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
+ */
+Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
+ /**
+ * @cfg {Boolean} clearUp
+ */
+ clearUp : true,
+ /**
+ * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
+ */
+ toolbars : false,
+
+ /**
+ * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
+ * Roo.resizable.
+ */
+ resizable : false,
+ /**
+ * @cfg {Number} height (in pixels)
+ */
+ height: 300,
+ /**
+ * @cfg {Number} width (in pixels)
+ */
+ width: 500,
- var nodeEndRange = nodeRange.cloneRange();
- nodeEndRange.collapse(false);
+ /**
+ * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
+ *
+ */
+ stylesheets: false,
- return rangeStartRange.compareBoundaryPoints(
- Range.START_TO_START, nodeEndRange) == -1 &&
- rangeEndRange.compareBoundaryPoints(
- Range.START_TO_START, nodeStartRange) == 1;
-
-
- },
- rangeCompareNode : function(range, node)
- {
- var nodeRange = node.ownerDocument.createRange();
- try {
- nodeRange.selectNode(node);
- } catch (e) {
- nodeRange.selectNodeContents(node);
- }
-
-
- range.collapse(true);
- nodeRange.collapse(true);
-
- var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
- var ee = range.compareBoundaryPoints( Range.END_TO_END, nodeRange);
-
- //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
-
- var nodeIsBefore = ss == 1;
- var nodeIsAfter = ee == -1;
-
- if (nodeIsBefore && nodeIsAfter)
- return 0; // outer
- if (!nodeIsBefore && nodeIsAfter)
- return 1; //right trailed.
-
- if (nodeIsBefore && !nodeIsAfter)
- return 2; // left trailed.
- // fully contined.
- return 3;
+ /**
+ * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
+ *
+ */
+ cblack: false,
+ /**
+ * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
+ *
+ */
+ cwhite: false,
+
+ /**
+ * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
+ *
+ */
+ black: false,
+ /**
+ * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
+ *
+ */
+ white: false,
+
+ // id of frame..
+ frameId: false,
+
+ // private properties
+ validationEvent : false,
+ deferHeight: true,
+ initialized : false,
+ activated : false,
+
+ onFocus : Roo.emptyFn,
+ iframePad:3,
+ hideMode:'offsets',
+
+ actionMode : 'container', // defaults to hiding it...
+
+ defaultAutoCreate : { // modified by initCompnoent..
+ tag: "textarea",
+ style:"width:500px;height:300px;",
+ autocomplete: "new-password"
+ },
+
+ // private
+ initComponent : function(){
+ this.addEvents({
+ /**
+ * @event initialize
+ * Fires when the editor is fully initialized (including the iframe)
+ * @param {HtmlEditor} this
+ */
+ initialize: true,
+ /**
+ * @event activate
+ * Fires when the editor is first receives the focus. Any insertion must wait
+ * until after this event.
+ * @param {HtmlEditor} this
+ */
+ activate: true,
+ /**
+ * @event beforesync
+ * Fires before the textarea is updated with content from the editor iframe. Return false
+ * to cancel the sync.
+ * @param {HtmlEditor} this
+ * @param {String} html
+ */
+ beforesync: true,
+ /**
+ * @event beforepush
+ * Fires before the iframe editor is updated with content from the textarea. Return false
+ * to cancel the push.
+ * @param {HtmlEditor} this
+ * @param {String} html
+ */
+ beforepush: true,
+ /**
+ * @event sync
+ * Fires when the textarea is updated with content from the editor iframe.
+ * @param {HtmlEditor} this
+ * @param {String} html
+ */
+ sync: true,
+ /**
+ * @event push
+ * Fires when the iframe editor is updated with content from the textarea.
+ * @param {HtmlEditor} this
+ * @param {String} html
+ */
+ push: true,
+ /**
+ * @event editmodechange
+ * Fires when the editor switches edit modes
+ * @param {HtmlEditor} this
+ * @param {Boolean} sourceEdit True if source edit, false if standard editing.
+ */
+ editmodechange: true,
+ /**
+ * @event editorevent
+ * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
+ * @param {HtmlEditor} this
+ */
+ editorevent: true,
+ /**
+ * @event firstfocus
+ * Fires when on first focus - needed by toolbars..
+ * @param {HtmlEditor} this
+ */
+ firstfocus: true,
+ /**
+ * @event autosave
+ * Auto save the htmlEditor value as a file into Events
+ * @param {HtmlEditor} this
+ */
+ autosave: true,
+ /**
+ * @event savedpreview
+ * preview the saved version of htmlEditor
+ * @param {HtmlEditor} this
+ */
+ savedpreview: true,
+
+ /**
+ * @event stylesheetsclick
+ * Fires when press the Sytlesheets button
+ * @param {Roo.HtmlEditorCore} this
+ */
+ stylesheetsclick: true
+ });
+ this.defaultAutoCreate = {
+ tag: "textarea",
+ style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
+ autocomplete: "new-password"
+ };
},
- // private? - in a new class?
- cleanUpPaste : function()
- {
- // cleans up the whole document..
- Roo.log('cleanuppaste');
- this.cleanUpChildren(this.doc.body);
- var clean = this.cleanWordChars(this.doc.body.innerHTML);
- if (clean != this.doc.body.innerHTML) {
- this.doc.body.innerHTML = clean;
+ /**
+ * Protected method that will not generally be called directly. It
+ * is called when the editor creates its toolbar. Override this method if you need to
+ * add custom toolbar buttons.
+ * @param {HtmlEditor} editor
+ */
+ createToolbar : function(editor){
+ Roo.log("create toolbars");
+ if (!editor.toolbars || !editor.toolbars.length) {
+ editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
}
- },
-
- cleanWordChars : function(input) {// change the chars to hex code
- var he = Roo.form.HtmlEditor;
-
- var output = input;
- Roo.each(he.swapCodes, function(sw) {
- var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
-
- output = output.replace(swapper, sw[1]);
- });
+ for (var i =0 ; i < editor.toolbars.length;i++) {
+ editor.toolbars[i] = Roo.factory(
+ typeof(editor.toolbars[i]) == 'string' ?
+ { xtype: editor.toolbars[i]} : editor.toolbars[i],
+ Roo.form.HtmlEditor);
+ editor.toolbars[i].init(editor);
+ }
+
- return output;
},
-
-
- cleanUpChildren : function (n)
+
+
+ // private
+ onRender : function(ct, position)
{
- if (!n.childNodes.length) {
- return;
- }
- for (var i = n.childNodes.length-1; i > -1 ; i--) {
- this.cleanUpChild(n.childNodes[i]);
- }
- },
-
-
+ var _t = this;
+ Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
-
- cleanUpChild : function (node)
- {
- var ed = this;
- //console.log(node);
- if (node.nodeName == "#text") {
- // clean up silly Windows -- stuff?
- return;
- }
- if (node.nodeName == "#comment") {
- node.parentNode.removeChild(node);
- // clean up silly Windows -- stuff?
- return;
- }
+ this.wrap = this.el.wrap({
+ cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
+ });
- if (Roo.form.HtmlEditor.black.indexOf(node.tagName.toLowerCase()) > -1) {
- // remove node.
- node.parentNode.removeChild(node);
- return;
+ this.editorcore.onRender(ct, position);
+
+ if (this.resizable) {
+ this.resizeEl = new Roo.Resizable(this.wrap, {
+ pinned : true,
+ wrap: true,
+ dynamic : true,
+ minHeight : this.height,
+ height: this.height,
+ handles : this.resizable,
+ width: this.width,
+ listeners : {
+ resize : function(r, w, h) {
+ _t.onResize(w,h); // -something
+ }
+ }
+ });
}
+ this.createToolbar(this);
+
- var remove_keep_children= Roo.form.HtmlEditor.remove.indexOf(node.tagName.toLowerCase()) > -1;
-
- // remove <a name=....> as rendering on yahoo mailer is borked with this.
- // this will have to be flaged elsewhere - perhaps ablack=name... on the mailer..
-
- //if (node.tagName.toLowerCase() == 'a' && !node.hasAttribute('href')) {
- // remove_keep_children = true;
- //}
-
- if (remove_keep_children) {
- this.cleanUpChildren(node);
- // inserts everything just before this node...
- while (node.childNodes.length) {
- var cn = node.childNodes[0];
- node.removeChild(cn);
- node.parentNode.insertBefore(cn, node);
- }
- node.parentNode.removeChild(node);
- return;
- }
-
- if (!node.attributes || !node.attributes.length) {
- this.cleanUpChildren(node);
- return;
+ if(!this.width){
+ this.setSize(this.wrap.getSize());
}
-
- function cleanAttr(n,v)
- {
-
- if (v.match(/^\./) || v.match(/^\//)) {
- return;
- }
- if (v.match(/^(http|https):\/\//) || v.match(/^mailto:/)) {
- return;
- }
- if (v.match(/^#/)) {
- return;
- }
-// Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
- node.removeAttribute(n);
-
+ if (this.resizeEl) {
+ this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
+ // should trigger onReize..
}
- function cleanStyle(n,v)
- {
- if (v.match(/expression/)) { //XSS?? should we even bother..
- node.removeAttribute(n);
- return;
- }
- var cwhite = typeof(ed.cwhite) == 'undefined' ? Roo.form.HtmlEditor.cwhite : ed.cwhite;
- var cblack = typeof(ed.cblack) == 'undefined' ? Roo.form.HtmlEditor.cblack : ed.cblack;
+ this.keyNav = new Roo.KeyNav(this.el, {
+ "tab" : function(e){
+ e.preventDefault();
+
+ var value = this.getValue();
+
+ var start = this.el.dom.selectionStart;
+ var end = this.el.dom.selectionEnd;
+
+ if(!e.shiftKey){
+
+ this.setValue(value.substring(0, start) + "\t" + value.substring(end));
+ this.el.dom.setSelectionRange(end + 1, end + 1);
+ return;
+ }
+
+ var f = value.substring(0, start).split("\t");
+
+ if(f.pop().length != 0){
+ return;
+ }
+
+ this.setValue(f.join("\t") + value.substring(end));
+ this.el.dom.setSelectionRange(start - 1, start - 1);
+
+ },
- var parts = v.split(/;/);
- var clean = [];
+ "home" : function(e){
+ e.preventDefault();
+
+ var curr = this.el.dom.selectionStart;
+ var lines = this.getValue().split("\n");
+
+ if(!lines.length){
+ return;
+ }
+
+ if(e.ctrlKey){
+ this.el.dom.setSelectionRange(0, 0);
+ return;
+ }
+
+ var pos = 0;
+
+ for (var i = 0; i < lines.length;i++) {
+ pos += lines[i].length;
+
+ if(i != 0){
+ pos += 1;
+ }
+
+ if(pos < curr){
+ continue;
+ }
+
+ pos -= lines[i].length;
+
+ break;
+ }
+
+ if(!e.shiftKey){
+ this.el.dom.setSelectionRange(pos, pos);
+ return;
+ }
+
+ this.el.dom.selectionStart = pos;
+ this.el.dom.selectionEnd = curr;
+ },
- Roo.each(parts, function(p) {
- p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
- if (!p.length) {
- return true;
+ "end" : function(e){
+ e.preventDefault();
+
+ var curr = this.el.dom.selectionStart;
+ var lines = this.getValue().split("\n");
+
+ if(!lines.length){
+ return;
}
- var l = p.split(':').shift().replace(/\s+/g,'');
- l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
+ if(e.ctrlKey){
+ this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
+ return;
+ }
- if ( cblack.indexOf(l) > -1) {
-// Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
- //node.removeAttribute(n);
- return true;
+ var pos = 0;
+
+ for (var i = 0; i < lines.length;i++) {
+
+ pos += lines[i].length;
+
+ if(i != 0){
+ pos += 1;
+ }
+
+ if(pos < curr){
+ continue;
+ }
+
+ break;
}
- //Roo.log()
- // only allow 'c whitelisted system attributes'
- if ( cwhite.length && cwhite.indexOf(l) < 0) {
-// Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
- //node.removeAttribute(n);
- return true;
+
+ if(!e.shiftKey){
+ this.el.dom.setSelectionRange(pos, pos);
+ return;
}
+ this.el.dom.selectionStart = curr;
+ this.el.dom.selectionEnd = pos;
+ },
+
+ scope : this,
+
+ doRelay : function(foo, bar, hname){
+ return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
+ },
+
+ forceKeyDown: true
+ });
+
+// if(this.autosave && this.w){
+// this.autoSaveFn = setInterval(this.autosave, 1000);
+// }
+ },
+
+ // private
+ onResize : function(w, h)
+ {
+ Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
+ var ew = false;
+ var eh = false;
+
+ if(this.el ){
+ if(typeof w == 'number'){
+ var aw = w - this.wrap.getFrameWidth('lr');
+ this.el.setWidth(this.adjustWidth('textarea', aw));
+ ew = aw;
+ }
+ if(typeof h == 'number'){
+ var tbh = 0;
+ for (var i =0; i < this.toolbars.length;i++) {
+ // fixme - ask toolbars for heights?
+ tbh += this.toolbars[i].tb.el.getHeight();
+ if (this.toolbars[i].footer) {
+ tbh += this.toolbars[i].footer.el.getHeight();
+ }
+ }
-
- clean.push(p);
- return true;
- });
- if (clean.length) {
- node.setAttribute(n, clean.join(';'));
- } else {
- node.removeAttribute(n);
+
+
+ var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
+ ah -= 5; // knock a few pixes off for look..
+// Roo.log(ah);
+ this.el.setHeight(this.adjustWidth('textarea', ah));
+ var eh = ah;
}
-
}
+ Roo.log('onResize:' + [w,h,ew,eh].join(',') );
+ this.editorcore.onResize(ew,eh);
+ },
+
+ /**
+ * Toggles the editor between standard and source edit mode.
+ * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
+ */
+ toggleSourceEdit : function(sourceEditMode)
+ {
+ this.editorcore.toggleSourceEdit(sourceEditMode);
- for (var i = node.attributes.length-1; i > -1 ; i--) {
- var a = node.attributes[i];
- //console.log(a);
+ if(this.editorcore.sourceEditMode){
+ Roo.log('editor - showing textarea');
- if (a.name.toLowerCase().substr(0,2)=='on') {
- node.removeAttribute(a.name);
- continue;
- }
- if (Roo.form.HtmlEditor.ablack.indexOf(a.name.toLowerCase()) > -1) {
- node.removeAttribute(a.name);
- continue;
- }
- if (Roo.form.HtmlEditor.aclean.indexOf(a.name.toLowerCase()) > -1) {
- cleanAttr(a.name,a.value); // fixme..
- continue;
- }
- if (a.name == 'style') {
- cleanStyle(a.name,a.value);
- continue;
+// Roo.log('in');
+// Roo.log(this.syncValue());
+ this.editorcore.syncValue();
+ this.el.removeClass('x-hidden');
+ this.el.dom.removeAttribute('tabIndex');
+ this.el.focus();
+
+ for (var i = 0; i < this.toolbars.length; i++) {
+ if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
+ this.toolbars[i].tb.hide();
+ this.toolbars[i].footer.hide();
+ }
}
- /// clean up MS crap..
- // tecnically this should be a list of valid class'es..
+ }else{
+ Roo.log('editor - hiding textarea');
+// Roo.log('out')
+// Roo.log(this.pushValue());
+ this.editorcore.pushValue();
+
+ this.el.addClass('x-hidden');
+ this.el.dom.setAttribute('tabIndex', -1);
- if (a.name == 'class') {
- if (a.value.match(/^Mso/)) {
- node.className = '';
- }
-
- if (a.value.match(/body/)) {
- node.className = '';
+ for (var i = 0; i < this.toolbars.length; i++) {
+ if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
+ this.toolbars[i].tb.show();
+ this.toolbars[i].footer.show();
}
- continue;
}
- // style cleanup!?
- // class cleanup?
-
+ //this.deferFocus();
}
+ this.setSize(this.wrap.getSize());
+ this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
- this.cleanUpChildren(node);
+ this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
+ },
+
+ // private (for BoxComponent)
+ adjustSize : Roo.BoxComponent.prototype.adjustSize,
+
+ // private (for BoxComponent)
+ getResizeEl : function(){
+ return this.wrap;
+ },
+
+ // private (for BoxComponent)
+ getPositionEl : function(){
+ return this.wrap;
+ },
+
+ // private
+ initEvents : function(){
+ this.originalValue = this.getValue();
+ },
+
+ /**
+ * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
+ * @method
+ */
+ markInvalid : Roo.emptyFn,
+ /**
+ * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
+ * @method
+ */
+ clearInvalid : Roo.emptyFn,
+
+ setValue : function(v){
+ Roo.form.HtmlEditor.superclass.setValue.call(this, v);
+ this.editorcore.pushValue();
+ },
+
+
+ // private
+ deferFocus : function(){
+ this.focus.defer(10, this);
+ },
+
+ // doc'ed in Field
+ focus : function(){
+ this.editorcore.focus();
+
+ },
+
+
+ // private
+ onDestroy : function(){
- }
+
+ if(this.rendered){
+
+ for (var i =0; i < this.toolbars.length;i++) {
+ // fixme - ask toolbars for heights?
+ this.toolbars[i].onDestroy();
+ }
+
+ this.wrap.dom.innerHTML = '';
+ this.wrap.remove();
+ }
+ },
+
+ // private
+ onFirstFocus : function(){
+ //Roo.log("onFirstFocus");
+ this.editorcore.onFirstFocus();
+ for (var i =0; i < this.toolbars.length;i++) {
+ this.toolbars[i].onFirstFocus();
+ }
+
+ },
+
+ // private
+ syncValue : function()
+ {
+ this.editorcore.syncValue();
+ },
+
+ pushValue : function()
+ {
+ this.editorcore.pushValue();
+ },
+
+ setStylesheets : function(stylesheets)
+ {
+ this.editorcore.setStylesheets(stylesheets);
+ },
+ removeStylesheets : function()
+ {
+ this.editorcore.removeStylesheets();
+ }
+
// hide stuff that is not compatible
/**
* @cfg {String} validateOnBlur @hide
*/
});
-
-Roo.form.HtmlEditor.white = [
- 'area', 'br', 'img', 'input', 'hr', 'wbr',
-
- 'address', 'blockquote', 'center', 'dd', 'dir', 'div',
- 'dl', 'dt', 'h1', 'h2', 'h3', 'h4',
- 'h5', 'h6', 'hr', 'isindex', 'listing', 'marquee',
- 'menu', 'multicol', 'ol', 'p', 'plaintext', 'pre',
- 'table', 'ul', 'xmp',
-
- 'caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
- 'thead', 'tr',
-
- 'dir', 'menu', 'ol', 'ul', 'dl',
-
- 'embed', 'object'
-];
-
-
-Roo.form.HtmlEditor.black = [
- // 'embed', 'object', // enable - backend responsiblity to clean thiese
- 'applet', //
- 'base', 'basefont', 'bgsound', 'blink', 'body',
- 'frame', 'frameset', 'head', 'html', 'ilayer',
- 'iframe', 'layer', 'link', 'meta', 'object',
- 'script', 'style' ,'title', 'xml' // clean later..
-];
-Roo.form.HtmlEditor.clean = [
- 'script', 'style', 'title', 'xml'
-];
-Roo.form.HtmlEditor.remove = [
- 'font'
-];
-// attributes..
-
-Roo.form.HtmlEditor.ablack = [
- 'on'
-];
-
-Roo.form.HtmlEditor.aclean = [
- 'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc'
-];
-
-// protocols..
-Roo.form.HtmlEditor.pwhite= [
- 'http', 'https', 'mailto'
-];
-
-// white listed style attributes.
-Roo.form.HtmlEditor.cwhite= [
- // 'text-align', /// default is to allow most things..
-
-
-// 'font-size'//??
-];
-
-// black listed style attributes.
-Roo.form.HtmlEditor.cblack= [
- // 'font-size' -- this can be set by the project
-];
-
-
-Roo.form.HtmlEditor.swapCodes =[
- [ 8211, "--" ],
- [ 8212, "--" ],
- [ 8216, "'" ],
- [ 8217, "'" ],
- [ 8220, '"' ],
- [ 8221, '"' ],
- [ 8226, "*" ],
- [ 8230, "..." ]
-];
-
+
// <script type="text/javascript">
/*
* Based on
rendered: false,
editor : false,
+ editorcore : false,
/**
* @cfg {Object} disable List of toolbar elements to disable
*/
disable : false,
+
+
+ /**
+ * @cfg {String} createLinkText The default text for the create link prompt
+ */
+ createLinkText : 'Please enter the URL for the link:',
+ /**
+ * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
+ */
+ defaultLinkValue : 'http:/'+'/',
+
+
/**
* @cfg {Array} fontFamilies An array of available font families
*/
["h1"],["h2"],["h3"],["h4"],["h5"],["h6"],
["pre"],[ "code"],
["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
- ['div'],['span']
+ ['div'],['span'],
+ ['sup'],['sub']
],
cleanStyles : [
init : function(editor)
{
this.editor = editor;
+ this.editorcore = editor.editorcore ? editor.editorcore : editor;
+ var editorcore = this.editorcore;
+ var _t = this;
- var fid = editor.frameId;
+ var fid = editorcore.frameId;
var etb = this;
function btn(id, toggle, handler){
var xid = fid + '-'+ id ;
cmd : id,
cls : 'x-btn-icon x-edit-'+id,
enableToggle:toggle !== false,
- scope: editor, // was editor...
- handler:handler||editor.relayBtnCmd,
+ scope: _t, // was editor...
+ handler:handler||_t.relayBtnCmd,
clickEvent:'mousedown',
tooltip: etb.buttonTips[id] || undefined, ///tips ???
tabIndex:-1
width:135,
listeners : {
'select': function(c, r, i) {
- editor.insertTag(r.get('tag'));
+ editorcore.insertTag(r.get('tag'));
editor.focus();
}
}
tb.add(
btn('bold'),
btn('italic'),
- btn('underline')
+ btn('underline'),
+ btn('strikethrough')
);
};
if(!this.disable.fontSize){
'-',
- btn('increasefontsize', false, editor.adjustFont),
- btn('decreasefontsize', false, editor.adjustFont)
+ btn('increasefontsize', false, editorcore.adjustFont),
+ btn('decreasefontsize', false, editorcore.adjustFont)
);
};
if(!this.disable.colors){
tb.add(
'-', {
- id:editor.frameId +'-forecolor',
+ id:editorcore.frameId +'-forecolor',
cls:'x-btn-icon x-edit-forecolor',
clickEvent:'mousedown',
tooltip: this.buttonTips['forecolor'] || undefined,
value:'000000',
plain:true,
selectHandler: function(cp, color){
- editor.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
+ editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
editor.deferFocus();
},
- scope: editor,
+ scope: editorcore,
clickEvent:'mousedown'
})
}, {
- id:editor.frameId +'backcolor',
+ id:editorcore.frameId +'backcolor',
cls:'x-btn-icon x-edit-backcolor',
clickEvent:'mousedown',
tooltip: this.buttonTips['backcolor'] || undefined,
allowReselect: true,
selectHandler: function(cp, color){
if(Roo.isGecko){
- editor.execCmd('useCSS', false);
- editor.execCmd('hilitecolor', color);
- editor.execCmd('useCSS', true);
+ editorcore.execCmd('useCSS', false);
+ editorcore.execCmd('hilitecolor', color);
+ editorcore.execCmd('useCSS', true);
editor.deferFocus();
}else{
- editor.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor',
+ editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor',
Roo.isSafari || Roo.isIE ? '#'+color : color);
editor.deferFocus();
}
},
- scope:editor,
+ scope:editorcore,
clickEvent:'mousedown'
})
}
if(!this.disable.links){
tb.add(
'-',
- btn('createlink', false, editor.createLink) /// MOVE TO HERE?!!?!?!?!
+ btn('createlink', false, this.createLink) /// MOVE TO HERE?!!?!?!?!
);
};
html: this.specialChars[i],
handler: function(a,b) {
- editor.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
+ editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
//editor.insertAtCursor(a.html);
},
actiontype : this.cleanStyles[i],
html: 'Remove ' + this.cleanStyles[i],
handler: function(a,b) {
- Roo.log(a);
- Roo.log(b);
- var c = Roo.get(editor.doc.body);
+// Roo.log(a);
+// Roo.log(b);
+ var c = Roo.get(editorcore.doc.body);
c.select('[style]').each(function(s) {
s.dom.style.removeProperty(a.actiontype);
});
-
+ editorcore.syncValue();
},
tabIndex:-1
});
}
+ cmenu.menu.items.push({
+ actiontype : 'tablewidths',
+ html: 'Remove Table Widths',
+ handler: function(a,b) {
+ editorcore.cleanTableWidths();
+ editorcore.syncValue();
+ },
+ tabIndex:-1
+ });
+ cmenu.menu.items.push({
+ actiontype : 'word',
+ html: 'Remove MS Word Formating',
+ handler: function(a,b) {
+ editorcore.cleanWord();
+ editorcore.syncValue();
+ },
+ tabIndex:-1
+ });
+
+ cmenu.menu.items.push({
+ actiontype : 'all',
+ html: 'Remove All Styles',
+ handler: function(a,b) {
+
+ var c = Roo.get(editorcore.doc.body);
+ c.select('[style]').each(function(s) {
+ s.dom.removeAttribute('style');
+ });
+ editorcore.syncValue();
+ },
+ tabIndex:-1
+ });
+
+ cmenu.menu.items.push({
+ actiontype : 'all',
+ html: 'Remove All CSS Classes',
+ handler: function(a,b) {
+
+ var c = Roo.get(editorcore.doc.body);
+ c.select('[class]').each(function(s) {
+ s.dom.removeAttribute('class');
+ });
+ editorcore.cleanWord();
+ editorcore.syncValue();
+ },
+ tabIndex:-1
+ });
+
+ cmenu.menu.items.push({
+ actiontype : 'tidy',
+ html: 'Tidy HTML Source',
+ handler: function(a,b) {
+ editorcore.doc.body.innerHTML = editorcore.domToHTML();
+ editorcore.syncValue();
+ },
+ tabIndex:-1
+ });
+
tb.add(cmenu);
}
for(var i =0; i< this.btns.length;i++) {
var b = Roo.factory(this.btns[i],Roo.form);
b.cls = 'x-edit-none';
- b.scope = editor;
+
+ if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
+ b.cls += ' x-init-enable';
+ }
+
+ b.scope = editorcore;
tb.add(b);
}
// disable everything...
this.tb.items.each(function(item){
- if(item.id != editor.frameId+ '-sourceedit'){
+
+ if(
+ item.id != editorcore.frameId+ '-sourceedit' &&
+ (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
+ ){
+
item.disable();
}
});
},
+ relayBtnCmd : function(btn) {
+ this.editorcore.relayCmd(btn.cmd);
+ },
+ // private used internally
+ createLink : function(){
+ Roo.log("create link?");
+ var url = prompt(this.createLinkText, this.defaultLinkValue);
+ if(url && url != 'http:/'+'/'){
+ this.editorcore.relayCmd('createlink', url);
+ }
+ },
+
/**
* Protected method that will not generally be called directly. It triggers
*/
updateToolbar: function(){
- if(!this.editor.activated){
+ if(!this.editorcore.activated){
this.editor.onFirstFocus();
return;
}
var btns = this.tb.items.map,
- doc = this.editor.doc,
- frameId = this.editor.frameId;
+ doc = this.editorcore.doc,
+ frameId = this.editorcore.frameId;
if(!this.disable.font && !Roo.isSafari){
/*
btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
+ btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
}
if(!this.disable.alignments){
btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
}
- var ans = this.editor.getAllAncestors();
+ var ans = this.editorcore.getAllAncestors();
if (this.formatCombo) {
},
toggleSourceEdit : function(sourceEditMode){
+
+ Roo.log("toolbar toogle");
if(sourceEditMode === undefined){
sourceEditMode = !this.sourceEditMode;
}
this.sourceEditMode = sourceEditMode === true;
- var btn = this.tb.items.get(this.editor.frameId +'-sourceedit');
+ var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
// just toggle the button?
- if(btn.pressed !== this.editor.sourceEditMode){
- btn.toggle(this.editor.sourceEditMode);
+ if(btn.pressed !== this.sourceEditMode){
+ btn.toggle(this.sourceEditMode);
return;
}
- if(this.sourceEditMode){
+ if(sourceEditMode){
+ Roo.log("disabling buttons");
this.tb.items.each(function(item){
- if(item.cmd != 'sourceedit'){
+ if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
item.disable();
}
});
}else{
- if(this.initialized){
+ Roo.log("enabling buttons");
+ if(this.editorcore.initialized){
this.tb.items.each(function(item){
item.enable();
});
}
}
+ Roo.log("calling toggole on editor");
// tell the editor that it's been pressed..
this.editor.toggleSourceEdit(sourceEditMode);
text: 'Underline the selected text.',
cls: 'x-html-editor-tip'
},
+ strikethrough : {
+ title: 'Strikethrough',
+ text: 'Strikethrough the selected text.',
+ cls: 'x-html-editor-tip'
+ },
increasefontsize : {
title: 'Grow Text',
text: 'Increase the font size.',
// fixme - these need to be configurable..
-Roo.form.HtmlEditor.ToolbarContext.types
+//Roo.form.HtmlEditor.ToolbarContext.types
Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype, {
rendered: false,
editor : false,
+ editorcore : false,
/**
* @cfg {Object} disable List of toolbar elements to disable
init : function(editor)
{
this.editor = editor;
+ this.editorcore = editor.editorcore ? editor.editorcore : editor;
+ var editorcore = this.editorcore;
-
- var fid = editor.frameId;
+ var fid = editorcore.frameId;
var etb = this;
function btn(id, toggle, handler){
var xid = fid + '-'+ id ;
cmd : id,
cls : 'x-btn-icon x-edit-'+id,
enableToggle:toggle !== false,
- scope: editor, // was editor...
- handler:handler||editor.relayBtnCmd,
+ scope: editorcore, // was editor...
+ handler:handler||editorcore.relayBtnCmd,
clickEvent:'mousedown',
tooltip: etb.buttonTips[id] || undefined, ///tips ???
tabIndex:-1
/**
* Protected method that will not generally be called directly. It triggers
* a toolbar update by reading the markup state of the current selection in the editor.
+ *
+ * Note you can force an update by calling on('editorevent', scope, false)
*/
updateToolbar: function(editor,ev,sel){
//Roo.log(ev);
// capture mouse up - this is handy for selecting images..
// perhaps should go somewhere else...
- if(!this.editor.activated){
+ if(!this.editorcore.activated){
this.editor.onFirstFocus();
return;
}
+
+
// http://developer.yahoo.com/yui/docs/simple-editor.js.html
// selectNode - might want to handle IE?
if (ev &&
nodeRange.selectNodeContents(sel);
}
//nodeRange.collapse(true);
- var s = editor.win.getSelection();
+ var s = this.editorcore.win.getSelection();
s.removeAllRanges();
s.addRange(nodeRange);
}
var updateFooter = sel ? false : true;
- var ans = this.editor.getAllAncestors();
+ var ans = this.editorcore.getAllAncestors();
// pick
var ty= Roo.form.HtmlEditor.ToolbarContext.types;
if (!sel) {
- sel = ans.length ? (ans[0] ? ans[0] : ans[1]) : this.editor.doc.body;
- sel = sel ? sel : this.editor.doc.body;
- sel = sel.tagName.length ? sel : this.editor.doc.body;
+ sel = ans.length ? (ans[0] ? ans[0] : ans[1]) : this.editorcore.doc.body;
+ sel = sel ? sel : this.editorcore.doc.body;
+ sel = sel.tagName.length ? sel : this.editorcore.doc.body;
}
// pick a menu that exists..
tn = sel.tagName.toUpperCase();
- var lastSel = this.tb.selectedNode
+ var lastSel = this.tb.selectedNode;
this.tb.selectedNode = sel;
// if current menu does not match..
- if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode)) {
+
+ if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode) || ev === false) {
this.tb.el.hide();
///console.log("show: " + tn);
buildToolbar: function(tlist, nm)
{
var editor = this.editor;
+ var editorcore = this.editorcore;
// create a new element.
var wdiv = editor.wrap.createChild({
tag: 'div'
'select': function(c, r, i) {
// initial support only for on class per el..
tb.selectedNode.className = r ? r.get('val') : '';
- editor.syncValue();
+ editorcore.syncValue();
}
}
listeners: {
'change' : function(f, nv, ov) {
tb.selectedNode.setAttribute(f.attrname, nv);
+ editorcore.syncValue();
}
}
}));
}
- tb.addFill();
+
var _this = this;
+
+ if(nm == 'BODY'){
+ tb.addSeparator();
+
+ tb.addButton( {
+ text: 'Stylesheets',
+
+ listeners : {
+ click : function ()
+ {
+ _this.editor.fireEvent('stylesheetsclick', _this.editor);
+ }
+ }
+ });
+ }
+
+ tb.addFill();
tb.addButton( {
text: 'Remove Tag',
}
pn.removeChild(sn);
- var range = editor.createRange();
+ var range = editorcore.createRange();
range.setStart(stn,0);
range.setEnd(en,0); //????
//range.selectNode(sel);
- var selection = editor.getSelection();
+ var selection = editorcore.getSelection();
selection.removeAllRanges();
selection.addRange(range);
var sel = ans[n];
// pick
- var range = this.editor.createRange();
+ var range = this.editorcore.createRange();
range.selectNodeContents(sel);
//range.selectNode(sel);
- var selection = this.editor.getSelection();
+ var selection = this.editorcore.getSelection();
selection.removeAllRanges();
selection.addRange(range);
this.initEl(el);
}
Roo.form.BasicForm.superclass.constructor.call(this);
+
+ Roo.form.BasicForm.popover.apply();
};
Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
* @type Mixed
*/
waitMsgTarget : false,
+
+ /**
+ * @type Boolean
+ */
+ disableMask : false,
+
+ /**
+ * @cfg {Boolean} errorMask (true|false) default false
+ */
+ errorMask : false,
+
+ /**
+ * @cfg {Number} maskOffset Default 100
+ */
+ maskOffset : 100,
// private
initEl : function(el){
*/
isValid : function(){
var valid = true;
+ var target = false;
this.items.each(function(f){
- if(!f.validate()){
- valid = false;
- }
+ if(f.validate()){
+ return;
+ }
+
+ valid = false;
+
+ if(!target && f.el.isVisible(true)){
+ target = f;
+ }
});
+
+ if(this.errorMask && !valid){
+ Roo.form.BasicForm.popover.mask(this, target);
+ }
+
return valid;
},
/**
- * Returns true if any fields in this form have changed since their original load.
+ * DEPRICATED Returns true if any fields in this form have changed since their original load.
* @return Boolean
*/
isDirty : function(){
});
return dirty;
},
-
+
+ /**
+ * Returns true if any fields in this form have changed since their original load. (New version)
+ * @return Boolean
+ */
+
+ hasChanged : function()
+ {
+ var dirty = false;
+ this.items.each(function(f){
+ if(f.hasChanged()){
+ dirty = true;
+ return false;
+ }
+ });
+ return dirty;
+
+ },
+ /**
+ * Resets all hasChanged to 'false' -
+ * The old 'isDirty' used 'original value..' however this breaks reset() and a few other things.
+ * So hasChanged storage is only to be used for this purpose
+ * @return Boolean
+ */
+ resetHasChanged : function()
+ {
+ this.items.each(function(f){
+ f.resetHasChanged();
+ });
+
+ },
+
+
/**
* Performs a predefined action (submit or load) or custom actions you define on this form.
* @param {String} actionName The name of the action type
beforeAction : function(action){
var o = action.options;
-
- if(this.waitMsgTarget === true){
- this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
- }else if(this.waitMsgTarget){
- this.waitMsgTarget = Roo.get(this.waitMsgTarget);
- this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
- }else {
- Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
+ if(!this.disableMask) {
+ if(this.waitMsgTarget === true){
+ this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
+ }else if(this.waitMsgTarget){
+ this.waitMsgTarget = Roo.get(this.waitMsgTarget);
+ this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
+ }else {
+ Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
+ }
}
+
},
this.activeAction = null;
var o = action.options;
- if(this.waitMsgTarget === true){
- this.el.unmask();
- }else if(this.waitMsgTarget){
- this.waitMsgTarget.unmask();
- }else{
- Roo.MessageBox.updateProgress(1);
- Roo.MessageBox.hide();
+ if(!this.disableMask) {
+ if(this.waitMsgTarget === true){
+ this.el.unmask();
+ }else if(this.waitMsgTarget){
+ this.waitMsgTarget.unmask();
+ }else{
+ Roo.MessageBox.updateProgress(1);
+ Roo.MessageBox.hide();
+ }
}
-
+
if(success){
if(o.reset){
this.reset();
}
}
}
-
+ this.resetHasChanged();
+
+
Roo.each(this.childForms || [], function (f) {
f.setValues(values);
+ f.resetHasChanged();
});
return this;
},
-
+
/**
* 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.
}, this);
}
+ // use formdata
+ if (typeof(FormData) != 'undefined' && asString !== true) {
+ // this relies on a 'recent' version of chrome apparently...
+ try {
+ var fd = (new FormData(this.el.dom)).entries();
+ var ret = {};
+ var ent = fd.next();
+ while (!ent.done) {
+ ret[ent.value[0]] = ent.value[1]; // not sure how this will handle duplicates..
+ ent = fd.next();
+ };
+ return ret;
+ } catch(e) {
+
+ }
+
+ }
var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
Roo.each(this.childForms || [], function (f) {
f.reset();
});
-
+ this.resetHasChanged();
return this;
},
});
// back compat
-Roo.BasicForm = Roo.form.BasicForm;/*
+Roo.BasicForm = Roo.form.BasicForm;
+
+Roo.apply(Roo.form.BasicForm, {
+
+ popover : {
+
+ padding : 5,
+
+ isApplied : false,
+
+ isMasked : false,
+
+ form : false,
+
+ target : false,
+
+ intervalID : false,
+
+ maskEl : false,
+
+ apply : function()
+ {
+ if(this.isApplied){
+ return;
+ }
+
+ this.maskEl = {
+ top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
+ left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
+ bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
+ right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
+ };
+
+ this.maskEl.top.enableDisplayMode("block");
+ this.maskEl.left.enableDisplayMode("block");
+ this.maskEl.bottom.enableDisplayMode("block");
+ this.maskEl.right.enableDisplayMode("block");
+
+ Roo.get(document.body).on('click', function(){
+ this.unmask();
+ }, this);
+
+ Roo.get(document.body).on('touchstart', function(){
+ this.unmask();
+ }, this);
+
+ this.isApplied = true
+ },
+
+ mask : function(form, target)
+ {
+ this.form = form;
+
+ this.target = target;
+
+ if(!this.form.errorMask || !target.el){
+ return;
+ }
+
+ var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.x-layout-active-content', 100, true) || Roo.get(document.body);
+
+ var ot = this.target.el.calcOffsetsTo(scrollable);
+
+ var scrollTo = ot[1] - this.form.maskOffset;
+
+ scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
+
+ scrollable.scrollTo('top', scrollTo);
+
+ var el = this.target.wrap || this.target.el;
+
+ var box = el.getBox();
+
+ this.maskEl.top.setStyle('position', 'absolute');
+ this.maskEl.top.setStyle('z-index', 10000);
+ this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
+ this.maskEl.top.setLeft(0);
+ this.maskEl.top.setTop(0);
+ this.maskEl.top.show();
+
+ this.maskEl.left.setStyle('position', 'absolute');
+ this.maskEl.left.setStyle('z-index', 10000);
+ this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
+ this.maskEl.left.setLeft(0);
+ this.maskEl.left.setTop(box.y - this.padding);
+ this.maskEl.left.show();
+
+ this.maskEl.bottom.setStyle('position', 'absolute');
+ this.maskEl.bottom.setStyle('z-index', 10000);
+ this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
+ this.maskEl.bottom.setLeft(0);
+ this.maskEl.bottom.setTop(box.bottom + this.padding);
+ this.maskEl.bottom.show();
+
+ this.maskEl.right.setStyle('position', 'absolute');
+ this.maskEl.right.setStyle('z-index', 10000);
+ this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
+ this.maskEl.right.setLeft(box.right + this.padding);
+ this.maskEl.right.setTop(box.y - this.padding);
+ this.maskEl.right.show();
+
+ this.intervalID = window.setInterval(function() {
+ Roo.form.BasicForm.popover.unmask();
+ }, 10000);
+
+ window.onwheel = function(){ return false;};
+
+ (function(){ this.isMasked = true; }).defer(500, this);
+
+ },
+
+ unmask : function()
+ {
+ if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
+ return;
+ }
+
+ this.maskEl.top.setStyle('position', 'absolute');
+ this.maskEl.top.setSize(0, 0).setXY([0, 0]);
+ this.maskEl.top.hide();
+
+ this.maskEl.left.setStyle('position', 'absolute');
+ this.maskEl.left.setSize(0, 0).setXY([0, 0]);
+ this.maskEl.left.hide();
+
+ this.maskEl.bottom.setStyle('position', 'absolute');
+ this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
+ this.maskEl.bottom.hide();
+
+ this.maskEl.right.setStyle('position', 'absolute');
+ this.maskEl.right.setSize(0, 0).setXY([0, 0]);
+ this.maskEl.right.hide();
+
+ window.onwheel = function(){ return true;};
+
+ if(this.intervalID){
+ window.clearInterval(this.intervalID);
+ this.intervalID = false;
+ }
+
+ this.isMasked = false;
+
+ }
+
+ }
+
+});/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
Roo.each(xitems, this.addxtype, this);
-
-
};
Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
*/
progressUrl : false,
-
+ /**
+ * @cfg {boolean|FormData} formData - true to use new 'FormData' post, or set to a new FormData({dom form}) Object, if
+ * sending a formdata with extra parameters - eg uploaded elements.
+ */
+
+ formData : false,
+
/**
* Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
* fields are added and the column is closed. If no fields are passed the column remains open
url:this.getUrl(!isPost),
method: method,
params:isPost ? this.getParams() : null,
- isUpload: this.form.fileUpload
+ isUpload: this.form.fileUpload,
+ formData : this.form.formData
}));
this.uploadProgress();
// 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,4}$/;
+ 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;
// All these messages and functions are configurable
this.defaultAutoCreate = {
tag: "textarea",
style:"width:300px;height:60px;",
- autocomplete: "off"
+ autocomplete: "new-password"
};
}
Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
replaceTextarea : function()
{
- if ( document.getElementById( this.getId() + '___Frame' ) )
+ if ( document.getElementById( this.getId() + '___Frame' ) ) {
return ;
+ }
//if ( !this.checkBrowser || this._isCompatibleBrowser() )
//{
// We must check the elements firstly using the Id and then the name.
* {tag: "input", type: "checkbox", autocomplete: "off"})
*/
// defaultAutoCreate : { tag: 'div' },
- defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
+ defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
/**
* @cfg {String} addTitle Text to include for adding a title.
*/
* @class Roo.form.DisplayField
* @extends Roo.form.Field
* A generic Field to display non-editable data.
+ * @cfg {Boolean} closable (true|false) default false
* @constructor
* Creates a new Display Field item.
* @param {Object} config Configuration options
Roo.form.DisplayField = function(config){
Roo.form.DisplayField.superclass.constructor.call(this, config);
+ this.addEvents({
+ /**
+ * @event close
+ * Fires after the click the close btn
+ * @param {Roo.form.DisplayField} this
+ */
+ close : true
+ });
};
Roo.extend(Roo.form.DisplayField, Roo.form.TextField, {
*/
// defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
-
+
+ closable : false,
+
onResize : function(){
Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
initEvents : function(){
// Roo.form.Checkbox.superclass.initEvents.call(this);
// has no events...
+
+ if(this.closable){
+ this.closeEl.on('click', this.onClose, this);
+ }
},
this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
+ if(this.closable){
+ this.closeEl = this.wrap.createChild({ tag: 'div', cls: 'x-dlg-close'});
+ }
+
if (this.bodyStyle) {
this.viewEl.applyStyles(this.bodyStyle);
}
this.viewEl.dom.innerHTML = html;
Roo.form.DisplayField.superclass.setValue.call(this, v);
+ },
+
+ onClose : function(e)
+ {
+ e.preventDefault();
+
+ this.fireEvent('close', this);
}
});/*
*
* @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"},
+ defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
actionMode : 'viewEl',
pt.x = e.clientX;
pt.y = e.clientY;
if (this.isTouchEvent(e)) {
- pt.x = e.targetTouches[0].clientX
+ pt.x = e.targetTouches[0].clientX;
pt.y = e.targetTouches[0].clientY;
}
var a = this.svgEl.dom.getScreenCTM();
* Performs a layout update.
*/
layout : function(){
- if(this.updating) return;
+ if(this.updating) {
+ return;
+ }
var size = this.getViewSize();
var w = size.width;
var h = size.height;
- default:
- alert("Can not add '" + cfg.xtype + "' to BorderLayout");
- return null;
+ default:
+ if (typeof(Roo[cfg.xtype]) != 'undefined') {
+
+ ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
+ this.add(region, ret);
+ } else {
+
+ alert("Can not add '" + cfg.xtype + "' to BorderLayout");
+ return null;
+ }
+
// GridPanel (grid, cfg)
}
* @param {Roo.ContentPanel} panel The panel
*/
"panelremoved" : true,
+ /**
+ * @event beforecollapse
+ * Fires when this region before collapse.
+ * @param {Roo.LayoutRegion} this
+ */
+ "beforecollapse" : true,
/**
* @event collapsed
* Fires when this region is collapsed.
* @cfg {Boolean} floatable False to disable floating (defaults to true)
* @cfg {Object} margins Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
* @cfg {Object} cmargins Margins for the element when collapsed (defaults to: north/south {top: 2, left: 0, right:0, bottom: 2} or east/west {top: 0, left: 2, right:2, bottom: 0})
- * @cfg {String} tabPosition "top" or "bottom" (defaults to "bottom")
+ * @cfg {String} tabPosition (top|bottom) "top" or "bottom" (defaults to "bottom")
* @cfg {String} collapsedTitle Optional string message to display in the collapsed block of a north or south region
* @cfg {Boolean} alwaysShowTabs True to always display tabs even when there is only 1 panel (defaults to false)
* @cfg {Boolean} autoScroll True to enable overflow scrolling (defaults to false)
* Collapses this region.
* @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
*/
- collapse : function(skipAnim){
- if(this.collapsed) return;
- this.collapsed = true;
- if(this.split){
- this.split.el.hide();
+ collapse : function(skipAnim, skipCheck){
+ if(this.collapsed) {
+ return;
}
- if(this.config.animate && skipAnim !== true){
- this.fireEvent("invalidated", this);
- this.animateCollapse();
- }else{
- this.el.setLocation(-20000,-20000);
- this.el.hide();
- this.collapsedEl.show();
- this.fireEvent("collapsed", this);
- this.fireEvent("invalidated", this);
+
+ if(skipCheck || this.fireEvent("beforecollapse", this) != false){
+
+ this.collapsed = true;
+ if(this.split){
+ this.split.el.hide();
+ }
+ if(this.config.animate && skipAnim !== true){
+ this.fireEvent("invalidated", this);
+ this.animateCollapse();
+ }else{
+ this.el.setLocation(-20000,-20000);
+ this.el.hide();
+ this.collapsedEl.show();
+ this.fireEvent("collapsed", this);
+ this.fireEvent("invalidated", this);
+ }
}
+
},
animateCollapse : function(){
* @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
*/
expand : function(e, skipAnim){
- if(e) e.stopPropagation();
- if(!this.collapsed || this.el.hasActiveFx()) return;
+ if(e) {
+ e.stopPropagation();
+ }
+ if(!this.collapsed || this.el.hasActiveFx()) {
+ return;
+ }
if(this.isSlid){
this.afterSlideIn();
skipAnim = true;
* @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
*/
- showPanel : function(panel){
- if(panel = this.getPanel(panel)){
+ showPanel : function(panel)
+ {
+ panel = this.getPanel(panel);
+ if(panel){
if(this.tabs){
var tab = this.tabs.getTab(panel.getEl().id);
if(tab.isHidden()){
beforeSlide: function(){
if(Roo.isGecko){// firefox overflow auto bug workaround
this.bodyEl.clip();
- if(this.tabs) this.tabs.bodyEl.clip();
+ if(this.tabs) {
+ this.tabs.bodyEl.clip();
+ }
if(this.activePanel){
this.activePanel.getEl().clip();
afterSlide : function(){
if(Roo.isGecko){// firefox overflow auto bug workaround
this.bodyEl.unclip();
- if(this.tabs) this.tabs.bodyEl.unclip();
+ if(this.tabs) {
+ this.tabs.bodyEl.unclip();
+ }
if(this.activePanel){
this.activePanel.getEl().unclip();
if(this.activePanel.afterSlide){
* @param {Roo.ContentPanel} this
*/
"render" : true
-
-
+
});
}
if(this.footer){
var te = this.footer.getEl();
- Roo.log("footer:" + te.getHeight());
+ //Roo.log("footer:" + te.getHeight());
height -= te.getHeight();
te.setWidth(width);
this.form = new Roo.form.Form(cfg);
- if ( this.form.allItems.length) this.form.render(el.dom);
+ if ( this.form.allItems.length) {
+ this.form.render(el.dom);
+ }
return this.form;
}
// should only have one of theses..
return this;
},
- /**
- * Reconfigures the grid to use a different Store and Column Model.
- * The View will be bound to the new objects and refreshed.
- * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
- * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
- */
+ /**
+ * Reconfigures the grid to use a different Store and Column Model.
+ * The View will be bound to the new objects and refreshed.
+ * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
+ * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
+ */
reconfigure : function(dataSource, colModel){
if(this.loadMask){
this.loadMask.destroy();
this.colModel = colModel;
this.view.refresh(true);
},
-
+ /**
+ * addColumns
+ * Add's a column, default at the end..
+
+ * @param {int} position to add (default end)
+ * @param {Array} of objects of column configuration see {@link Roo.grid.ColumnModel}
+ */
+ addColumns : function(pos, ar)
+ {
+
+ for (var i =0;i< ar.length;i++) {
+ var cfg = ar[i];
+ cfg.id = typeof(cfg.id) == 'undefined' ? Roo.id() : cfg.id; // don't normally use this..
+ this.cm.lookup[cfg.id] = cfg;
+ }
+
+
+ if (typeof(pos) == 'undefined' || pos >= this.cm.config.length) {
+ pos = this.cm.config.length; //this.cm.config.push(cfg);
+ }
+ pos = Math.max(0,pos);
+ ar.unshift(0);
+ ar.unshift(pos);
+ this.cm.config.splice.apply(this.cm.config, ar);
+
+
+
+ this.view.generateRules(this.cm);
+ this.view.refresh(true);
+
+ },
+
+
+
+
// private
onKeyDown : function(e){
this.fireEvent("keydown", e);
// private
processEvent : function(name, e){
// does this fire select???
- Roo.log('grid:processEvent ' + name);
+ //Roo.log('grid:processEvent ' + name);
if (name != 'touchstart' ) {
this.fireEvent(name, e);
var v = this.view;
var header = v.findHeaderIndex(t);
if(header !== false){
- this.fireEvent("header" + (name == 'touchstart' ? 'click' : name), this, header, e);
+ var ename = name == 'touchstart' ? 'click' : name;
+
+ this.fireEvent("header" + ename, this, header, e);
}else{
var row = v.findRowIndex(t);
var cell = v.findCellIndex(t);
hdClass : "x-grid-hd",
splitClass : "x-grid-hd-split",
- init: function(grid){
+ init: function(grid){
this.grid = grid;
var cid = this.grid.getGridEl().id;
this.colSelector = "#" + cid + " ." + this.cellClass + "-";
this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
},
- getColumnRenderers : function(){
+ getColumnRenderers : function(){
var renderers = [];
var cm = this.grid.colModel;
var colCount = cm.getColumnCount();
p.cellId = "x-grid-hd-0-" + i;
p.splitId = "x-grid-csplit-0-" + i;
p.id = cm.getColumnId(i);
- p.title = cm.getColumnTooltip(i) || "";
p.value = cm.getColumnHeader(i) || "";
+ p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</) ? '' : p.value || "";
p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
if(!cm.isLocked(i)){
cb[cb.length] = ct.apply(p);
if(s){ // splitters not created yet
var pos = 0, locked = true;
for(var i = 0, len = cm.getColumnCount(); i < len; i++){
- if(cm.isHidden(i)) continue;
+ if(cm.isHidden(i)) {
+ continue;
+ }
var w = cm.getColumnWidth(i); // make sure it's a number
if(!cm.isLocked(i) && locked){
pos = 0;
name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
renderer : cm.getRenderer(i),
id : cm.getColumnId(i),
- locked : cm.isLocked(i)
+ locked : cm.isLocked(i),
+ has_editor : cm.isCellEditable(i)
};
}
p.id = c.id;
p.css = p.attr = "";
p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
- if(p.value == undefined || p.value === "") p.value = " ";
- if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
- p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
+ if(p.value == undefined || p.value === "") {
+ p.value = " ";
+ }
+ if(c.has_editor){
+ p.css += ' x-grid-editable-cell';
+ }
+ if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
+ p.css += ' x-grid-dirty-cell';
}
var markup = ct.apply(p);
if(!c.locked){
record: r,
rowIndex : rowIndex,
rowClass : ''
- }
+ };
this.grid.fireEvent('rowclass', this, rowcfg);
alt.push(rowcfg.rowClass);
}
p.id = c.id;
p.css = p.attr = "";
p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
- if(p.value == undefined || p.value === "") p.value = " ";
+ if(p.value == undefined || p.value === "") {
+ p.value = " ";
+ }
+ //Roo.log(c);
+ if(c.has_editor){
+ p.css += ' x-grid-editable-cell';
+ }
if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
- p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
+ p.css += ' x-grid-dirty-cell'
}
var markup = ct.apply(p);
record: r,
rowIndex : rowIndex,
rowClass : ''
- }
+ };
this.grid.fireEvent('rowclass', this, rowcfg);
alt.push(rowcfg.rowClass);
}
+
rp.alt = alt.join(" ");
rp.cells = lcb.join("");
lbuf[lbuf.length] = rt.apply(rp);
};
var renderer = cm.getRenderer(colIndex);
var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
- if(typeof val == "undefined" || val === "") val = " ";
+ if(typeof val == "undefined" || val === "") {
+ val = " ";
+ }
cellText.innerHTML = val;
cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
this.syncRowHeights(rowIndex, rowIndex);
},
- handleHeaderClick : function(g, index){
+ handleHeaderClick : function(g, index,e){
+
+ Roo.log("header click");
+
+ if (Roo.isTouch) {
+ // touch events on header are handled by context
+ this.handleHdCtx(g,index,e);
+ return;
+ }
+
+
if(this.headersDisabled){
return;
}
cm.setLocked(index, false);
}
break;
+ case 'wider': // used to expand cols on touch..
+ case 'narrow':
+ var cw = cm.getColumnWidth(index);
+ cw += (item.id == 'wider' ? 1 : -1) * 50;
+ cw = Math.max(0, cw);
+ cw = Math.min(cw,4000);
+ cm.setColumnWidth(index, cw);
+ break;
+
default:
index = cm.getIndexById(item.id.substr(4));
if(index != -1){
{id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
);
}
+ if (Roo.isTouch) {
+ this.hmenu.add('-',
+ {id:"wider", text: this.columnsWiderText},
+ {id:"narrow", text: this.columnsNarrowText }
+ );
+
+
+ }
+
if(this.grid.enableColumnHide !== false){
this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
s.setSize(vw, vh);
var bt = this.getBodyTable();
+
+ if(cm.getLockedCount() == cm.config.length){
+ bt = this.getLockedTable();
+ }
+
var ltWidth = hasLock ?
Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
sortDescText : "Sort Descending",
lockText : "Lock Column",
unlockText : "Unlock Column",
- columnsText : "Columns"
+ columnsText : "Columns",
+
+ columnsWiderText : "Wider",
+ columnsNarrowText : "Thinner"
});
/**
* @cfg {Function} renderer (Optional) 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 uses the raw data value.
+ * 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 {String} align (Optional) Set the CSS text-align property of the column. Defaults to undefined.
*/
-
+ /**
+ * @cfg {String} valign (Optional) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc). Defaults to undefined.
+ */
+ /**
+ * @cfg {String} cursor (Optional)
+ */
+ /**
+ * @cfg {String} tooltip (Optional)
+ */
+ /**
+ * @cfg {Number} xs (Optional)
+ */
+ /**
+ * @cfg {Number} sm (Optional)
+ */
+ /**
+ * @cfg {Number} md (Optional)
+ */
+ /**
+ * @cfg {Number} lg (Optional)
+ */
/**
* Returns the id of the column at the specified index.
* @param {Number} index The column index
if(!this.isLocked(i)){
return i;
}
- }
+ }
+
+ return this.config.length;
+ },
+
+ /**
+ * Returns the number of columns.
+ * @return {Number}
+ */
+ getColumnCount : function(visibleOnly){
+ if(visibleOnly === true){
+ var c = 0;
+ for(var i = 0, len = this.config.length; i < len; i++){
+ if(!this.isHidden(i)){
+ c++;
+ }
+ }
+ return c;
+ }
+ return this.config.length;
+ },
+
+ /**
+ * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
+ * @param {Function} fn
+ * @param {Object} scope (optional)
+ * @return {Array} result
+ */
+ getColumnsBy : function(fn, scope){
+ var r = [];
+ for(var i = 0, len = this.config.length; i < len; i++){
+ var c = this.config[i];
+ if(fn.call(scope||this, c, i) === true){
+ r[r.length] = c;
+ }
+ }
+ return r;
+ },
+
+ /**
+ * Returns true if the specified column is sortable.
+ * @param {Number} col The column index
+ * @return {Boolean}
+ */
+ isSortable : function(col){
+ if(typeof this.config[col].sortable == "undefined"){
+ return this.defaultSortable;
+ }
+ return this.config[col].sortable;
+ },
+
+ /**
+ * Returns the rendering (formatting) function defined for the column.
+ * @param {Number} col The column index.
+ * @return {Function} The function used to render the cell. See {@link #setRenderer}.
+ */
+ getRenderer : function(col){
+ if(!this.config[col].renderer){
+ return Roo.grid.ColumnModel.defaultRenderer;
+ }
+ return this.config[col].renderer;
+ },
+
+ /**
+ * Sets the rendering (formatting) function for a column.
+ * @param {Number} col The column index
+ * @param {Function} fn The function to use to process the cell's raw data
+ * to return HTML markup for the grid view. The render function is called with
+ * the following parameters:<ul>
+ * <li>Data value.</li>
+ * <li>Cell metadata. An object in which you may set the following attributes:<ul>
+ * <li>css A CSS style string to apply to the table cell.</li>
+ * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
+ * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
+ * <li>Row index</li>
+ * <li>Column index</li>
+ * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
+ */
+ setRenderer : function(col, fn){
+ this.config[col].renderer = fn;
+ },
+
+ /**
+ * Returns the width for the specified column.
+ * @param {Number} col The column index
+ * @return {Number}
+ */
+ getColumnWidth : function(col){
+ return this.config[col].width * 1 || this.defaultWidth;
+ },
+
+ /**
+ * Sets the width for a column.
+ * @param {Number} col The column index
+ * @param {Number} width The new width
+ */
+ setColumnWidth : function(col, width, suppressEvent){
+ this.config[col].width = width;
+ this.totalWidth = null;
+ if(!suppressEvent){
+ this.fireEvent("widthchange", this, col, width);
+ }
+ },
+
+ /**
+ * Returns the total width of all columns.
+ * @param {Boolean} includeHidden True to include hidden column widths
+ * @return {Number}
+ */
+ getTotalWidth : function(includeHidden){
+ if(!this.totalWidth){
+ this.totalWidth = 0;
+ for(var i = 0, len = this.config.length; i < len; i++){
+ if(includeHidden || !this.isHidden(i)){
+ this.totalWidth += this.getColumnWidth(i);
+ }
+ }
+ }
+ return this.totalWidth;
+ },
+
+ /**
+ * Returns the header for the specified column.
+ * @param {Number} col The column index
+ * @return {String}
+ */
+ getColumnHeader : function(col){
+ return this.config[col].header;
+ },
+
+ /**
+ * Sets the header for a column.
+ * @param {Number} col The column index
+ * @param {String} header The new header
+ */
+ setColumnHeader : function(col, header){
+ this.config[col].header = header;
+ this.fireEvent("headerchange", this, col, header);
+ },
+
+ /**
+ * Returns the tooltip for the specified column.
+ * @param {Number} col The column index
+ * @return {String}
+ */
+ getColumnTooltip : function(col){
+ return this.config[col].tooltip;
+ },
+ /**
+ * Sets the tooltip for a column.
+ * @param {Number} col The column index
+ * @param {String} tooltip The new tooltip
+ */
+ setColumnTooltip : function(col, tooltip){
+ this.config[col].tooltip = tooltip;
+ },
+
+ /**
+ * Returns the dataIndex for the specified column.
+ * @param {Number} col The column index
+ * @return {Number}
+ */
+ getDataIndex : function(col){
+ return this.config[col].dataIndex;
+ },
+
+ /**
+ * Sets the dataIndex for a column.
+ * @param {Number} col The column index
+ * @param {Number} dataIndex The new dataIndex
+ */
+ setDataIndex : function(col, dataIndex){
+ this.config[col].dataIndex = dataIndex;
+ },
+
+
+
+ /**
+ * Returns true if the cell is editable.
+ * @param {Number} colIndex The column index
+ * @param {Number} rowIndex The row index - this is nto actually used..?
+ * @return {Boolean}
+ */
+ isCellEditable : function(colIndex, rowIndex){
+ return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
+ },
+
+ /**
+ * Returns the editor defined for the cell/column.
+ * return false or null to disable editing.
+ * @param {Number} colIndex The column index
+ * @param {Number} rowIndex The row index
+ * @return {Object}
+ */
+ getCellEditor : function(colIndex, rowIndex){
+ return this.config[colIndex].editor;
+ },
+
+ /**
+ * Sets if a column is editable.
+ * @param {Number} col The column index
+ * @param {Boolean} editable True if the column is editable
+ */
+ setEditable : function(col, editable){
+ this.config[col].editable = editable;
+ },
+
+
+ /**
+ * Returns true if the column is hidden.
+ * @param {Number} colIndex The column index
+ * @return {Boolean}
+ */
+ isHidden : function(colIndex){
+ return this.config[colIndex].hidden;
+ },
+
+
+ /**
+ * Returns true if the column width cannot be changed
+ */
+ isFixed : function(colIndex){
+ return this.config[colIndex].fixed;
+ },
+
+ /**
+ * Returns true if the column can be resized
+ * @return {Boolean}
+ */
+ isResizable : function(colIndex){
+ return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
+ },
+ /**
+ * Sets if a column is hidden.
+ * @param {Number} colIndex The column index
+ * @param {Boolean} hidden True if the column is hidden
+ */
+ setHidden : function(colIndex, hidden){
+ this.config[colIndex].hidden = hidden;
+ this.totalWidth = null;
+ this.fireEvent("hiddenchange", this, colIndex, hidden);
+ },
+
+ /**
+ * Sets the editor for a column.
+ * @param {Number} col The column index
+ * @param {Object} editor The editor object
+ */
+ setEditor : function(col, editor){
+ this.config[col].editor = editor;
+ }
+});
+
+Roo.grid.ColumnModel.defaultRenderer = function(value)
+{
+ if(typeof value == "object") {
+ return value;
+ }
+ if(typeof value == "string" && value.length < 1){
+ return " ";
+ }
+
+ return String.format("{0}", value);
+};
+
+// Alias for backwards compatibility
+Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
+/*
+ * 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.grid.AbstractSelectionModel
+ * @extends Roo.util.Observable
+ * Abstract base class for grid SelectionModels. It provides the interface that should be
+ * implemented by descendant classes. This class should not be directly instantiated.
+ * @constructor
+ */
+Roo.grid.AbstractSelectionModel = function(){
+ this.locked = false;
+ Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
+};
+
+Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable, {
+ /** @ignore Called by the grid automatically. Do not call directly. */
+ init : function(grid){
+ this.grid = grid;
+ this.initEvents();
+ },
+
+ /**
+ * Locks the selections.
+ */
+ lock : function(){
+ this.locked = true;
+ },
+
+ /**
+ * Unlocks the selections.
+ */
+ unlock : function(){
+ this.locked = false;
+ },
+
+ /**
+ * Returns true if the selections are locked.
+ * @return {Boolean}
+ */
+ isLocked : function(){
+ return this.locked;
+ }
+});/*
+ * 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">
+ */
+/**
+ * @extends Roo.grid.AbstractSelectionModel
+ * @class Roo.grid.RowSelectionModel
+ * The default SelectionModel used by {@link Roo.grid.Grid}.
+ * It supports multiple selections and keyboard selection/navigation.
+ * @constructor
+ * @param {Object} config
+ */
+Roo.grid.RowSelectionModel = function(config){
+ Roo.apply(this, config);
+ this.selections = new Roo.util.MixedCollection(false, function(o){
+ return o.id;
+ });
+
+ this.last = false;
+ this.lastActive = false;
+
+ this.addEvents({
+ /**
+ * @event selectionchange
+ * Fires when the selection changes
+ * @param {SelectionModel} this
+ */
+ "selectionchange" : true,
+ /**
+ * @event afterselectionchange
+ * Fires after the selection changes (eg. by key press or clicking)
+ * @param {SelectionModel} this
+ */
+ "afterselectionchange" : true,
+ /**
+ * @event beforerowselect
+ * Fires when a row is selected being selected, return false to cancel.
+ * @param {SelectionModel} this
+ * @param {Number} rowIndex The selected index
+ * @param {Boolean} keepExisting False if other selections will be cleared
+ */
+ "beforerowselect" : true,
+ /**
+ * @event rowselect
+ * Fires when a row is selected.
+ * @param {SelectionModel} this
+ * @param {Number} rowIndex The selected index
+ * @param {Roo.data.Record} r The record
+ */
+ "rowselect" : true,
+ /**
+ * @event rowdeselect
+ * Fires when a row is deselected.
+ * @param {SelectionModel} this
+ * @param {Number} rowIndex The selected index
+ */
+ "rowdeselect" : true
+ });
+ Roo.grid.RowSelectionModel.superclass.constructor.call(this);
+ this.locked = false;
+};
+
+Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel, {
+ /**
+ * @cfg {Boolean} singleSelect
+ * True to allow selection of only one row at a time (defaults to false)
+ */
+ singleSelect : false,
+
+ // private
+ initEvents : function(){
+
+ if(!this.grid.enableDragDrop && !this.grid.enableDrag){
+ this.grid.on("mousedown", this.handleMouseDown, this);
+ }else{ // allow click to work like normal
+ this.grid.on("rowclick", this.handleDragableRowClick, this);
+ }
+
+ this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
+ "up" : function(e){
+ if(!e.shiftKey){
+ this.selectPrevious(e.shiftKey);
+ }else if(this.last !== false && this.lastActive !== false){
+ var last = this.last;
+ this.selectRange(this.last, this.lastActive-1);
+ this.grid.getView().focusRow(this.lastActive);
+ if(last !== false){
+ this.last = last;
+ }
+ }else{
+ this.selectFirstRow();
+ }
+ this.fireEvent("afterselectionchange", this);
+ },
+ "down" : function(e){
+ if(!e.shiftKey){
+ this.selectNext(e.shiftKey);
+ }else if(this.last !== false && this.lastActive !== false){
+ var last = this.last;
+ this.selectRange(this.last, this.lastActive+1);
+ this.grid.getView().focusRow(this.lastActive);
+ if(last !== false){
+ this.last = last;
+ }
+ }else{
+ this.selectFirstRow();
+ }
+ this.fireEvent("afterselectionchange", this);
+ },
+ scope: this
+ });
+
+ var view = this.grid.view;
+ view.on("refresh", this.onRefresh, this);
+ view.on("rowupdated", this.onRowUpdated, this);
+ view.on("rowremoved", this.onRemove, this);
+ },
+
+ // private
+ onRefresh : function(){
+ var ds = this.grid.dataSource, i, v = this.grid.view;
+ var s = this.selections;
+ s.each(function(r){
+ if((i = ds.indexOfId(r.id)) != -1){
+ v.onRowSelect(i);
+ s.add(ds.getAt(i)); // updating the selection relate data
+ }else{
+ s.remove(r);
+ }
+ });
},
- /**
- * Returns the number of columns.
- * @return {Number}
- */
- getColumnCount : function(visibleOnly){
- if(visibleOnly === true){
- var c = 0;
- for(var i = 0, len = this.config.length; i < len; i++){
- if(!this.isHidden(i)){
- c++;
- }
- }
- return c;
- }
- return this.config.length;
+ // private
+ onRemove : function(v, index, r){
+ this.selections.remove(r);
},
- /**
- * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
- * @param {Function} fn
- * @param {Object} scope (optional)
- * @return {Array} result
- */
- getColumnsBy : function(fn, scope){
- var r = [];
- for(var i = 0, len = this.config.length; i < len; i++){
- var c = this.config[i];
- if(fn.call(scope||this, c, i) === true){
- r[r.length] = c;
- }
+ // private
+ onRowUpdated : function(v, index, r){
+ if(this.isSelected(r)){
+ v.onRowSelect(index);
}
- return r;
},
/**
- * Returns true if the specified column is sortable.
- * @param {Number} col The column index
- * @return {Boolean}
+ * Select records.
+ * @param {Array} records The records to select
+ * @param {Boolean} keepExisting (optional) True to keep existing selections
*/
- isSortable : function(col){
- if(typeof this.config[col].sortable == "undefined"){
- return this.defaultSortable;
+ selectRecords : function(records, keepExisting){
+ if(!keepExisting){
+ this.clearSelections();
+ }
+ var ds = this.grid.dataSource;
+ for(var i = 0, len = records.length; i < len; i++){
+ this.selectRow(ds.indexOf(records[i]), true);
}
- return this.config[col].sortable;
},
/**
- * Returns the rendering (formatting) function defined for the column.
- * @param {Number} col The column index.
- * @return {Function} The function used to render the cell. See {@link #setRenderer}.
+ * Gets the number of selected rows.
+ * @return {Number}
*/
- getRenderer : function(col){
- if(!this.config[col].renderer){
- return Roo.grid.ColumnModel.defaultRenderer;
- }
- return this.config[col].renderer;
+ getCount : function(){
+ return this.selections.length;
},
/**
- * Sets the rendering (formatting) function for a column.
- * @param {Number} col The column index
- * @param {Function} fn The function to use to process the cell's raw data
- * to return HTML markup for the grid view. The render function is called with
- * the following parameters:<ul>
- * <li>Data value.</li>
- * <li>Cell metadata. An object in which you may set the following attributes:<ul>
- * <li>css A CSS style string to apply to the table cell.</li>
- * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
- * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
- * <li>Row index</li>
- * <li>Column index</li>
- * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
+ * Selects the first row in the grid.
*/
- setRenderer : function(col, fn){
- this.config[col].renderer = fn;
+ selectFirstRow : function(){
+ this.selectRow(0);
},
/**
- * Returns the width for the specified column.
- * @param {Number} col The column index
- * @return {Number}
+ * Select the last row.
+ * @param {Boolean} keepExisting (optional) True to keep existing selections
*/
- getColumnWidth : function(col){
- return this.config[col].width * 1 || this.defaultWidth;
+ selectLastRow : function(keepExisting){
+ this.selectRow(this.grid.dataSource.getCount() - 1, keepExisting);
},
/**
- * Sets the width for a column.
- * @param {Number} col The column index
- * @param {Number} width The new width
+ * Selects the row immediately following the last selected row.
+ * @param {Boolean} keepExisting (optional) True to keep existing selections
*/
- setColumnWidth : function(col, width, suppressEvent){
- this.config[col].width = width;
- this.totalWidth = null;
- if(!suppressEvent){
- this.fireEvent("widthchange", this, col, width);
+ selectNext : function(keepExisting){
+ if(this.last !== false && (this.last+1) < this.grid.dataSource.getCount()){
+ this.selectRow(this.last+1, keepExisting);
+ this.grid.getView().focusRow(this.last);
}
},
/**
- * Returns the total width of all columns.
- * @param {Boolean} includeHidden True to include hidden column widths
- * @return {Number}
+ * Selects the row that precedes the last selected row.
+ * @param {Boolean} keepExisting (optional) True to keep existing selections
*/
- getTotalWidth : function(includeHidden){
- if(!this.totalWidth){
- this.totalWidth = 0;
- for(var i = 0, len = this.config.length; i < len; i++){
- if(includeHidden || !this.isHidden(i)){
- this.totalWidth += this.getColumnWidth(i);
- }
- }
+ selectPrevious : function(keepExisting){
+ if(this.last){
+ this.selectRow(this.last-1, keepExisting);
+ this.grid.getView().focusRow(this.last);
}
- return this.totalWidth;
},
/**
- * Returns the header for the specified column.
- * @param {Number} col The column index
- * @return {String}
+ * Returns the selected records
+ * @return {Array} Array of selected records
*/
- getColumnHeader : function(col){
- return this.config[col].header;
+ getSelections : function(){
+ return [].concat(this.selections.items);
},
/**
- * Sets the header for a column.
- * @param {Number} col The column index
- * @param {String} header The new header
+ * Returns the first selected record.
+ * @return {Record}
*/
- setColumnHeader : function(col, header){
- this.config[col].header = header;
- this.fireEvent("headerchange", this, col, header);
+ getSelected : function(){
+ return this.selections.itemAt(0);
},
+
/**
- * Returns the tooltip for the specified column.
- * @param {Number} col The column index
- * @return {String}
- */
- getColumnTooltip : function(col){
- return this.config[col].tooltip;
- },
- /**
- * Sets the tooltip for a column.
- * @param {Number} col The column index
- * @param {String} tooltip The new tooltip
+ * Clears all selections.
*/
- setColumnTooltip : function(col, tooltip){
- this.config[col].tooltip = tooltip;
+ clearSelections : function(fast){
+ if(this.locked) {
+ return;
+ }
+ if(fast !== true){
+ var ds = this.grid.dataSource;
+ var s = this.selections;
+ s.each(function(r){
+ this.deselectRow(ds.indexOfId(r.id));
+ }, this);
+ s.clear();
+ }else{
+ this.selections.clear();
+ }
+ this.last = false;
},
+
/**
- * Returns the dataIndex for the specified column.
- * @param {Number} col The column index
- * @return {Number}
+ * Selects all rows.
*/
- getDataIndex : function(col){
- return this.config[col].dataIndex;
+ selectAll : function(){
+ if(this.locked) {
+ return;
+ }
+ this.selections.clear();
+ for(var i = 0, len = this.grid.dataSource.getCount(); i < len; i++){
+ this.selectRow(i, true);
+ }
},
/**
- * Sets the dataIndex for a column.
- * @param {Number} col The column index
- * @param {Number} dataIndex The new dataIndex
+ * Returns True if there is a selection.
+ * @return {Boolean}
*/
- setDataIndex : function(col, dataIndex){
- this.config[col].dataIndex = dataIndex;
+ hasSelection : function(){
+ return this.selections.length > 0;
},
-
-
/**
- * Returns true if the cell is editable.
- * @param {Number} colIndex The column index
- * @param {Number} rowIndex The row index
+ * Returns True if the specified row is selected.
+ * @param {Number/Record} record The record or index of the record to check
* @return {Boolean}
*/
- isCellEditable : function(colIndex, rowIndex){
- return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
+ isSelected : function(index){
+ var r = typeof index == "number" ? this.grid.dataSource.getAt(index) : index;
+ return (r && this.selections.key(r.id) ? true : false);
},
/**
- * Returns the editor defined for the cell/column.
- * return false or null to disable editing.
- * @param {Number} colIndex The column index
- * @param {Number} rowIndex The row index
- * @return {Object}
+ * Returns True if the specified record id is selected.
+ * @param {String} id The id of record to check
+ * @return {Boolean}
*/
- getCellEditor : function(colIndex, rowIndex){
- return this.config[colIndex].editor;
+ isIdSelected : function(id){
+ return (this.selections.key(id) ? true : false);
},
+ // private
+ handleMouseDown : function(e, t){
+ var view = this.grid.getView(), rowIndex;
+ if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
+ return;
+ };
+ if(e.shiftKey && this.last !== false){
+ var last = this.last;
+ this.selectRange(last, rowIndex, e.ctrlKey);
+ this.last = last; // reset the last
+ view.focusRow(rowIndex);
+ }else{
+ var isSelected = this.isSelected(rowIndex);
+ if(e.button !== 0 && isSelected){
+ view.focusRow(rowIndex);
+ }else if(e.ctrlKey && isSelected){
+ this.deselectRow(rowIndex);
+ }else if(!isSelected){
+ this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
+ view.focusRow(rowIndex);
+ }
+ }
+ this.fireEvent("afterselectionchange", this);
+ },
+ // private
+ handleDragableRowClick : function(grid, rowIndex, e)
+ {
+ if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
+ this.selectRow(rowIndex, false);
+ grid.view.focusRow(rowIndex);
+ this.fireEvent("afterselectionchange", this);
+ }
+ },
+
/**
- * Sets if a column is editable.
- * @param {Number} col The column index
- * @param {Boolean} editable True if the column is editable
+ * Selects multiple rows.
+ * @param {Array} rows Array of the indexes of the row to select
+ * @param {Boolean} keepExisting (optional) True to keep existing selections
*/
- setEditable : function(col, editable){
- this.config[col].editable = editable;
+ selectRows : function(rows, keepExisting){
+ if(!keepExisting){
+ this.clearSelections();
+ }
+ for(var i = 0, len = rows.length; i < len; i++){
+ this.selectRow(rows[i], true);
+ }
},
-
/**
- * Returns true if the column is hidden.
- * @param {Number} colIndex The column index
- * @return {Boolean}
+ * Selects a range of rows. All rows in between startRow and endRow are also selected.
+ * @param {Number} startRow The index of the first row in the range
+ * @param {Number} endRow The index of the last row in the range
+ * @param {Boolean} keepExisting (optional) True to retain existing selections
*/
- isHidden : function(colIndex){
- return this.config[colIndex].hidden;
+ selectRange : function(startRow, endRow, keepExisting){
+ if(this.locked) {
+ return;
+ }
+ if(!keepExisting){
+ this.clearSelections();
+ }
+ if(startRow <= endRow){
+ for(var i = startRow; i <= endRow; i++){
+ this.selectRow(i, true);
+ }
+ }else{
+ for(var i = startRow; i >= endRow; i--){
+ this.selectRow(i, true);
+ }
+ }
},
-
/**
- * Returns true if the column width cannot be changed
+ * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
+ * @param {Number} startRow The index of the first row in the range
+ * @param {Number} endRow The index of the last row in the range
*/
- isFixed : function(colIndex){
- return this.config[colIndex].fixed;
+ deselectRange : function(startRow, endRow, preventViewNotify){
+ if(this.locked) {
+ return;
+ }
+ for(var i = startRow; i <= endRow; i++){
+ this.deselectRow(i, preventViewNotify);
+ }
},
/**
- * Returns true if the column can be resized
- * @return {Boolean}
+ * Selects a row.
+ * @param {Number} row The index of the row to select
+ * @param {Boolean} keepExisting (optional) True to keep existing selections
*/
- isResizable : function(colIndex){
- return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
+ selectRow : function(index, keepExisting, preventViewNotify){
+ if(this.locked || (index < 0 || index >= this.grid.dataSource.getCount())) {
+ return;
+ }
+ if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
+ if(!keepExisting || this.singleSelect){
+ this.clearSelections();
+ }
+ var r = this.grid.dataSource.getAt(index);
+ this.selections.add(r);
+ this.last = this.lastActive = index;
+ if(!preventViewNotify){
+ this.grid.getView().onRowSelect(index);
+ }
+ this.fireEvent("rowselect", this, index, r);
+ this.fireEvent("selectionchange", this);
+ }
},
+
/**
- * Sets if a column is hidden.
- * @param {Number} colIndex The column index
- * @param {Boolean} hidden True if the column is hidden
+ * Deselects a row.
+ * @param {Number} row The index of the row to deselect
*/
- setHidden : function(colIndex, hidden){
- this.config[colIndex].hidden = hidden;
- this.totalWidth = null;
- this.fireEvent("hiddenchange", this, colIndex, hidden);
+ deselectRow : function(index, preventViewNotify){
+ if(this.locked) {
+ return;
+ }
+ if(this.last == index){
+ this.last = false;
+ }
+ if(this.lastActive == index){
+ this.lastActive = false;
+ }
+ var r = this.grid.dataSource.getAt(index);
+ this.selections.remove(r);
+ if(!preventViewNotify){
+ this.grid.getView().onRowDeselect(index);
+ }
+ this.fireEvent("rowdeselect", this, index);
+ this.fireEvent("selectionchange", this);
},
- /**
- * Sets the editor for a column.
- * @param {Number} col The column index
- * @param {Object} editor The editor object
- */
- setEditor : function(col, editor){
- this.config[col].editor = editor;
- }
-});
+ // private
+ restoreLast : function(){
+ if(this._last){
+ this.last = this._last;
+ }
+ },
-Roo.grid.ColumnModel.defaultRenderer = function(value){
- if(typeof value == "string" && value.length < 1){
- return " ";
- }
- return value;
-};
+ // private
+ acceptsNav : function(row, col, cm){
+ return !cm.isHidden(col) && cm.isCellEditable(col, row);
+ },
-// Alias for backwards compatibility
-Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
-/*
+ // private
+ onEditorKey : function(field, e){
+ var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
+ if(k == e.TAB){
+ e.stopEvent();
+ ed.completeEdit();
+ if(e.shiftKey){
+ newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
+ }else{
+ newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
+ }
+ }else if(k == e.ENTER && !e.ctrlKey){
+ e.stopEvent();
+ ed.completeEdit();
+ if(e.shiftKey){
+ newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
+ }else{
+ newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
+ }
+ }else if(k == e.ESC){
+ ed.cancelEdit();
+ }
+ if(newCell){
+ g.startEditing(newCell[0], newCell[1]);
+ }
+ }
+});/*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* Fork - LGPL
* <script type="text/javascript">
*/
-
/**
- * @class Roo.grid.AbstractSelectionModel
- * @extends Roo.util.Observable
- * Abstract base class for grid SelectionModels. It provides the interface that should be
- * implemented by descendant classes. This class should not be directly instantiated.
+ * @class Roo.grid.CellSelectionModel
+ * @extends Roo.grid.AbstractSelectionModel
+ * This class provides the basic implementation for cell selection in a grid.
* @constructor
+ * @param {Object} config The object containing the configuration of this model.
+ * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
*/
-Roo.grid.AbstractSelectionModel = function(){
- this.locked = false;
- Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
+Roo.grid.CellSelectionModel = function(config){
+ Roo.apply(this, config);
+
+ this.selection = null;
+
+ this.addEvents({
+ /**
+ * @event beforerowselect
+ * Fires before a cell is selected.
+ * @param {SelectionModel} this
+ * @param {Number} rowIndex The selected row index
+ * @param {Number} colIndex The selected cell index
+ */
+ "beforecellselect" : true,
+ /**
+ * @event cellselect
+ * Fires when a cell is selected.
+ * @param {SelectionModel} this
+ * @param {Number} rowIndex The selected row index
+ * @param {Number} colIndex The selected cell index
+ */
+ "cellselect" : true,
+ /**
+ * @event selectionchange
+ * Fires when the active selection changes.
+ * @param {SelectionModel} this
+ * @param {Object} selection null for no selection or an object (o) with two properties
+ <ul>
+ <li>o.record: the record object for the row the selection is in</li>
+ <li>o.cell: An array of [rowIndex, columnIndex]</li>
+ </ul>
+ */
+ "selectionchange" : true,
+ /**
+ * @event tabend
+ * Fires when the tab (or enter) was pressed on the last editable cell
+ * You can use this to trigger add new row.
+ * @param {SelectionModel} this
+ */
+ "tabend" : true,
+ /**
+ * @event beforeeditnext
+ * Fires before the next editable sell is made active
+ * You can use this to skip to another cell or fire the tabend
+ * if you set cell to false
+ * @param {Object} eventdata object : { cell : [ row, col ] }
+ */
+ "beforeeditnext" : true
+ });
+ Roo.grid.CellSelectionModel.superclass.constructor.call(this);
};
-Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable, {
- /** @ignore Called by the grid automatically. Do not call directly. */
- init : function(grid){
- this.grid = grid;
- this.initEvents();
+Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel, {
+
+ enter_is_tab: false,
+
+ /** @ignore */
+ initEvents : function(){
+ this.grid.on("mousedown", this.handleMouseDown, this);
+ this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
+ var view = this.grid.view;
+ view.on("refresh", this.onViewChange, this);
+ view.on("rowupdated", this.onRowUpdated, this);
+ view.on("beforerowremoved", this.clearSelections, this);
+ view.on("beforerowsinserted", this.clearSelections, this);
+ if(this.grid.isEditor){
+ this.grid.on("beforeedit", this.beforeEdit, this);
+ }
+ },
+
+ //private
+ beforeEdit : function(e){
+ this.select(e.row, e.column, false, true, e.record);
+ },
+
+ //private
+ onRowUpdated : function(v, index, r){
+ if(this.selection && this.selection.record == r){
+ v.onCellSelect(index, this.selection.cell[1]);
+ }
+ },
+
+ //private
+ onViewChange : function(){
+ this.clearSelections(true);
+ },
+
+ /**
+ * Returns the currently selected cell,.
+ * @return {Array} The selected cell (row, column) or null if none selected.
+ */
+ getSelectedCell : function(){
+ return this.selection ? this.selection.cell : null;
},
/**
- * Locks the selections.
+ * Clears all selections.
+ * @param {Boolean} true to prevent the gridview from being notified about the change.
*/
- lock : function(){
- this.locked = true;
+ clearSelections : function(preventNotify){
+ var s = this.selection;
+ if(s){
+ if(preventNotify !== true){
+ this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
+ }
+ this.selection = null;
+ this.fireEvent("selectionchange", this, null);
+ }
},
/**
- * Unlocks the selections.
+ * Returns true if there is a selection.
+ * @return {Boolean}
*/
- unlock : function(){
- this.locked = false;
+ hasSelection : function(){
+ return this.selection ? true : false;
+ },
+
+ /** @ignore */
+ handleMouseDown : function(e, t){
+ var v = this.grid.getView();
+ if(this.isLocked()){
+ return;
+ };
+ var row = v.findRowIndex(t);
+ var cell = v.findCellIndex(t);
+ if(row !== false && cell !== false){
+ this.select(row, cell);
+ }
},
/**
- * Returns true if the selections are locked.
- * @return {Boolean}
+ * Selects a cell.
+ * @param {Number} rowIndex
+ * @param {Number} collIndex
*/
- isLocked : function(){
- return this.locked;
+ select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
+ if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
+ this.clearSelections();
+ r = r || this.grid.dataSource.getAt(rowIndex);
+ this.selection = {
+ record : r,
+ cell : [rowIndex, colIndex]
+ };
+ if(!preventViewNotify){
+ var v = this.grid.getView();
+ v.onCellSelect(rowIndex, colIndex);
+ if(preventFocus !== true){
+ v.focusCell(rowIndex, colIndex);
+ }
+ }
+ this.fireEvent("cellselect", this, rowIndex, colIndex);
+ this.fireEvent("selectionchange", this, this.selection);
+ }
+ },
+
+ //private
+ isSelectable : function(rowIndex, colIndex, cm){
+ return !cm.isHidden(colIndex);
+ },
+
+ /** @ignore */
+ handleKeyDown : function(e){
+ //Roo.log('Cell Sel Model handleKeyDown');
+ if(!e.isNavKeyPress()){
+ return;
+ }
+ var g = this.grid, s = this.selection;
+ if(!s){
+ e.stopEvent();
+ var cell = g.walkCells(0, 0, 1, this.isSelectable, this);
+ if(cell){
+ this.select(cell[0], cell[1]);
+ }
+ return;
+ }
+ var sm = this;
+ var walk = function(row, col, step){
+ return g.walkCells(row, col, step, sm.isSelectable, sm);
+ };
+ var k = e.getKey(), r = s.cell[0], c = s.cell[1];
+ var newCell;
+
+
+
+ switch(k){
+ case e.TAB:
+ // handled by onEditorKey
+ if (g.isEditor && g.editing) {
+ return;
+ }
+ if(e.shiftKey) {
+ newCell = walk(r, c-1, -1);
+ } else {
+ newCell = walk(r, c+1, 1);
+ }
+ break;
+
+ case e.DOWN:
+ newCell = walk(r+1, c, 1);
+ break;
+
+ case e.UP:
+ newCell = walk(r-1, c, -1);
+ break;
+
+ case e.RIGHT:
+ newCell = walk(r, c+1, 1);
+ break;
+
+ case e.LEFT:
+ newCell = walk(r, c-1, -1);
+ break;
+
+ case e.ENTER:
+
+ if(g.isEditor && !g.editing){
+ g.startEditing(r, c);
+ e.stopEvent();
+ return;
+ }
+
+
+ break;
+ };
+ if(newCell){
+ this.select(newCell[0], newCell[1]);
+ e.stopEvent();
+
+ }
+ },
+
+ acceptsNav : function(row, col, cm){
+ return !cm.isHidden(col) && cm.isCellEditable(col, row);
+ },
+ /**
+ * Selects a cell.
+ * @param {Number} field (not used) - as it's normally used as a listener
+ * @param {Number} e - event - fake it by using
+ *
+ * var e = Roo.EventObjectImpl.prototype;
+ * e.keyCode = e.TAB
+ *
+ *
+ */
+ onEditorKey : function(field, e){
+
+ var k = e.getKey(),
+ newCell,
+ g = this.grid,
+ ed = g.activeEditor,
+ forward = false;
+ ///Roo.log('onEditorKey' + k);
+
+
+ if (this.enter_is_tab && k == e.ENTER) {
+ k = e.TAB;
+ }
+
+ if(k == e.TAB){
+ if(e.shiftKey){
+ newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
+ }else{
+ newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
+ forward = true;
+ }
+
+ e.stopEvent();
+
+ } else if(k == e.ENTER && !e.ctrlKey){
+ ed.completeEdit();
+ e.stopEvent();
+ newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
+
+ } else if(k == e.ESC){
+ ed.cancelEdit();
+ }
+
+ if (newCell) {
+ var ecall = { cell : newCell, forward : forward };
+ this.fireEvent('beforeeditnext', ecall );
+ newCell = ecall.cell;
+ forward = ecall.forward;
+ }
+
+ if(newCell){
+ //Roo.log('next cell after edit');
+ g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
+ } else if (forward) {
+ // tabbed past last
+ this.fireEvent.defer(100, this, ['tabend',this]);
+ }
}
});/*
* Based on:
* Fork - LGPL
* <script type="text/javascript">
*/
+
/**
- * @extends Roo.grid.AbstractSelectionModel
- * @class Roo.grid.RowSelectionModel
- * The default SelectionModel used by {@link Roo.grid.Grid}.
- * It supports multiple selections and keyboard selection/navigation.
- * @constructor
- * @param {Object} config
+ * @class Roo.grid.EditorGrid
+ * @extends Roo.grid.Grid
+ * Class for creating and editable grid.
+ * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
+ * The container MUST have some type of size defined for the grid to fill. The container will be
+ * automatically set to position relative if it isn't already.
+ * @param {Object} dataSource The data model to bind to
+ * @param {Object} colModel The column model with info about this grid's columns
*/
-Roo.grid.RowSelectionModel = function(config){
- Roo.apply(this, config);
- this.selections = new Roo.util.MixedCollection(false, function(o){
- return o.id;
- });
+Roo.grid.EditorGrid = function(container, config){
+ Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
+ this.getGridEl().addClass("xedit-grid");
- this.last = false;
- this.lastActive = false;
+ if(!this.selModel){
+ this.selModel = new Roo.grid.CellSelectionModel();
+ }
- this.addEvents({
- /**
- * @event selectionchange
- * Fires when the selection changes
- * @param {SelectionModel} this
- */
- "selectionchange" : true,
- /**
- * @event afterselectionchange
- * Fires after the selection changes (eg. by key press or clicking)
- * @param {SelectionModel} this
- */
- "afterselectionchange" : true,
- /**
- * @event beforerowselect
- * Fires when a row is selected being selected, return false to cancel.
- * @param {SelectionModel} this
- * @param {Number} rowIndex The selected index
- * @param {Boolean} keepExisting False if other selections will be cleared
+ this.activeEditor = null;
+
+ this.addEvents({
+ /**
+ * @event beforeedit
+ * Fires before cell editing is triggered. The edit event object has the following properties <br />
+ * <ul style="padding:5px;padding-left:16px;">
+ * <li>grid - This grid</li>
+ * <li>record - The record being edited</li>
+ * <li>field - The field name being edited</li>
+ * <li>value - The value for the field being edited.</li>
+ * <li>row - The grid row index</li>
+ * <li>column - The grid column index</li>
+ * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
+ * </ul>
+ * @param {Object} e An edit event (see above for description)
*/
- "beforerowselect" : true,
- /**
- * @event rowselect
- * Fires when a row is selected.
- * @param {SelectionModel} this
- * @param {Number} rowIndex The selected index
- * @param {Roo.data.Record} r The record
+ "beforeedit" : true,
+ /**
+ * @event afteredit
+ * Fires after a cell is edited. <br />
+ * <ul style="padding:5px;padding-left:16px;">
+ * <li>grid - This grid</li>
+ * <li>record - The record being edited</li>
+ * <li>field - The field name being edited</li>
+ * <li>value - The value being set</li>
+ * <li>originalValue - The original value for the field, before the edit.</li>
+ * <li>row - The grid row index</li>
+ * <li>column - The grid column index</li>
+ * </ul>
+ * @param {Object} e An edit event (see above for description)
*/
- "rowselect" : true,
- /**
- * @event rowdeselect
- * Fires when a row is deselected.
- * @param {SelectionModel} this
- * @param {Number} rowIndex The selected index
+ "afteredit" : true,
+ /**
+ * @event validateedit
+ * Fires after a cell is edited, but before the value is set in the record.
+ * You can use this to modify the value being set in the field, Return false
+ * to cancel the change. The edit event object has the following properties <br />
+ * <ul style="padding:5px;padding-left:16px;">
+ * <li>editor - This editor</li>
+ * <li>grid - This grid</li>
+ * <li>record - The record being edited</li>
+ * <li>field - The field name being edited</li>
+ * <li>value - The value being set</li>
+ * <li>originalValue - The original value for the field, before the edit.</li>
+ * <li>row - The grid row index</li>
+ * <li>column - The grid column index</li>
+ * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
+ * </ul>
+ * @param {Object} e An edit event (see above for description)
*/
- "rowdeselect" : true
- });
- Roo.grid.RowSelectionModel.superclass.constructor.call(this);
- this.locked = false;
+ "validateedit" : true
+ });
+ this.on("bodyscroll", this.stopEditing, this);
+ this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick, this);
};
-Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel, {
+Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
/**
- * @cfg {Boolean} singleSelect
- * True to allow selection of only one row at a time (defaults to false)
+ * @cfg {Number} clicksToEdit
+ * The number of clicks on a cell required to display the cell's editor (defaults to 2)
*/
- singleSelect : false,
+ clicksToEdit: 2,
// private
- initEvents : function(){
+ isEditor : true,
+ // private
+ trackMouseOver: false, // causes very odd FF errors
- if(!this.grid.enableDragDrop && !this.grid.enableDrag){
- this.grid.on("mousedown", this.handleMouseDown, this);
- }else{ // allow click to work like normal
- this.grid.on("rowclick", this.handleDragableRowClick, this);
- }
+ onCellDblClick : function(g, row, col){
+ this.startEditing(row, col);
+ },
- this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
- "up" : function(e){
- if(!e.shiftKey){
- this.selectPrevious(e.shiftKey);
- }else if(this.last !== false && this.lastActive !== false){
- var last = this.last;
- this.selectRange(this.last, this.lastActive-1);
- this.grid.getView().focusRow(this.lastActive);
- if(last !== false){
- this.last = last;
- }
- }else{
- this.selectFirstRow();
- }
- this.fireEvent("afterselectionchange", this);
- },
- "down" : function(e){
- if(!e.shiftKey){
- this.selectNext(e.shiftKey);
- }else if(this.last !== false && this.lastActive !== false){
- var last = this.last;
- this.selectRange(this.last, this.lastActive+1);
- this.grid.getView().focusRow(this.lastActive);
- if(last !== false){
- this.last = last;
- }
- }else{
- this.selectFirstRow();
+ onEditComplete : function(ed, value, startValue){
+ this.editing = false;
+ this.activeEditor = null;
+ ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
+ var r = ed.record;
+ var field = this.colModel.getDataIndex(ed.col);
+ var e = {
+ grid: this,
+ record: r,
+ field: field,
+ originalValue: startValue,
+ value: value,
+ row: ed.row,
+ column: ed.col,
+ cancel:false,
+ editor: ed
+ };
+ var cell = Roo.get(this.view.getCell(ed.row,ed.col));
+ cell.show();
+
+ if(String(value) !== String(startValue)){
+
+ if(this.fireEvent("validateedit", e) !== false && !e.cancel){
+ r.set(field, e.value);
+ // if we are dealing with a combo box..
+ // then we also set the 'name' colum to be the displayField
+ if (ed.field.displayField && ed.field.name) {
+ r.set(ed.field.name, ed.field.el.dom.value);
}
- this.fireEvent("afterselectionchange", this);
- },
- scope: this
- });
-
- var view = this.grid.view;
- view.on("refresh", this.onRefresh, this);
- view.on("rowupdated", this.onRowUpdated, this);
- view.on("rowremoved", this.onRemove, this);
+
+ delete e.cancel; //?? why!!!
+ this.fireEvent("afteredit", e);
+ }
+ } else {
+ this.fireEvent("afteredit", e); // always fire it!
+ }
+ this.view.focusCell(ed.row, ed.col);
},
- // private
- onRefresh : function(){
- var ds = this.grid.dataSource, i, v = this.grid.view;
- var s = this.selections;
- s.each(function(r){
- if((i = ds.indexOfId(r.id)) != -1){
- v.onRowSelect(i);
- }else{
- s.remove(r);
+ /**
+ * Starts editing the specified for the specified row/column
+ * @param {Number} rowIndex
+ * @param {Number} colIndex
+ */
+ startEditing : function(row, col){
+ this.stopEditing();
+ if(this.colModel.isCellEditable(col, row)){
+ this.view.ensureVisible(row, col, true);
+
+ var r = this.dataSource.getAt(row);
+ var field = this.colModel.getDataIndex(col);
+ var cell = Roo.get(this.view.getCell(row,col));
+ var e = {
+ grid: this,
+ record: r,
+ field: field,
+ value: r.data[field],
+ row: row,
+ column: col,
+ cancel:false
+ };
+ if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
+ this.editing = true;
+ var ed = this.colModel.getCellEditor(col, row);
+
+ if (!ed) {
+ return;
+ }
+ if(!ed.rendered){
+ ed.render(ed.parentEl || document.body);
+ }
+ ed.field.reset();
+
+ cell.hide();
+
+ (function(){ // complex but required for focus issues in safari, ie and opera
+ ed.row = row;
+ ed.col = col;
+ ed.record = r;
+ ed.on("complete", this.onEditComplete, this, {single: true});
+ ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
+ this.activeEditor = ed;
+ var v = r.data[field];
+ ed.startEdit(this.view.getCell(row, col), v);
+ // combo's with 'displayField and name set
+ if (ed.field.displayField && ed.field.name) {
+ ed.field.el.dom.value = r.data[ed.field.name];
+ }
+
+
+ }).defer(50, this);
}
- });
+ }
},
-
- // private
- onRemove : function(v, index, r){
- this.selections.remove(r);
+
+ /**
+ * Stops any active editing
+ */
+ stopEditing : function(){
+ if(this.activeEditor){
+ this.activeEditor.completeEdit();
+ }
+ this.activeEditor = null;
},
+
+ /**
+ * Called to get grid's drag proxy text, by default returns this.ddText.
+ * @return {String}
+ */
+ getDragDropText : function(){
+ var count = this.selModel.getSelectedCell() ? 1 : 0;
+ return String.format(this.ddText, count, count == 1 ? '' : 's');
+ }
+
+});/*
+ * 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
- onRowUpdated : function(v, index, r){
- if(this.isSelected(r)){
- v.onRowSelect(index);
- }
- },
+// private - not really -- you end up using it !
+// This is a support class used internally by the Grid components
- /**
- * Select records.
- * @param {Array} records The records to select
- * @param {Boolean} keepExisting (optional) True to keep existing selections
- */
- selectRecords : function(records, keepExisting){
- if(!keepExisting){
- this.clearSelections();
- }
- var ds = this.grid.dataSource;
- for(var i = 0, len = records.length; i < len; i++){
- this.selectRow(ds.indexOf(records[i]), true);
- }
- },
+/**
+ * @class Roo.grid.GridEditor
+ * @extends Roo.Editor
+ * Class for creating and editable grid elements.
+ * @param {Object} config any settings (must include field)
+ */
+Roo.grid.GridEditor = function(field, config){
+ if (!config && field.field) {
+ config = field;
+ field = Roo.factory(config.field, Roo.form);
+ }
+ Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
+ field.monitorTab = false;
+};
+Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
+
/**
- * Gets the number of selected rows.
- * @return {Number}
+ * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
*/
- getCount : function(){
- return this.selections.length;
- },
+
+ alignment: "tl-tl",
+ autoSize: "width",
+ hideEl : false,
+ cls: "x-small-editor x-grid-editor",
+ shim:false,
+ shadow:"frame"
+});/*
+ * 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">
+ */
+
- /**
- * Selects the first row in the grid.
- */
- selectFirstRow : function(){
- this.selectRow(0);
- },
+
+Roo.grid.PropertyRecord = Roo.data.Record.create([
+ {name:'name',type:'string'}, 'value'
+]);
- /**
- * Select the last row.
- * @param {Boolean} keepExisting (optional) True to keep existing selections
- */
- selectLastRow : function(keepExisting){
- this.selectRow(this.grid.dataSource.getCount() - 1, keepExisting);
- },
- /**
- * Selects the row immediately following the last selected row.
- * @param {Boolean} keepExisting (optional) True to keep existing selections
- */
- selectNext : function(keepExisting){
- if(this.last !== false && (this.last+1) < this.grid.dataSource.getCount()){
- this.selectRow(this.last+1, keepExisting);
- this.grid.getView().focusRow(this.last);
+Roo.grid.PropertyStore = function(grid, source){
+ this.grid = grid;
+ this.store = new Roo.data.Store({
+ recordType : Roo.grid.PropertyRecord
+ });
+ this.store.on('update', this.onUpdate, this);
+ if(source){
+ this.setSource(source);
+ }
+ Roo.grid.PropertyStore.superclass.constructor.call(this);
+};
+
+
+
+Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
+ setSource : function(o){
+ this.source = o;
+ this.store.removeAll();
+ var data = [];
+ for(var k in o){
+ if(this.isEditableValue(o[k])){
+ data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
+ }
}
+ this.store.loadRecords({records: data}, {}, true);
},
- /**
- * Selects the row that precedes the last selected row.
- * @param {Boolean} keepExisting (optional) True to keep existing selections
- */
- selectPrevious : function(keepExisting){
- if(this.last){
- this.selectRow(this.last-1, keepExisting);
- this.grid.getView().focusRow(this.last);
+ onUpdate : function(ds, record, type){
+ if(type == Roo.data.Record.EDIT){
+ var v = record.data['value'];
+ var oldValue = record.modified['value'];
+ if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
+ this.source[record.id] = v;
+ record.commit();
+ this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
+ }else{
+ record.reject();
+ }
}
},
- /**
- * Returns the selected records
- * @return {Array} Array of selected records
- */
- getSelections : function(){
- return [].concat(this.selections.items);
+ getProperty : function(row){
+ return this.store.getAt(row);
},
- /**
- * Returns the first selected record.
- * @return {Record}
- */
- getSelected : function(){
- return this.selections.itemAt(0);
+ isEditableValue: function(val){
+ if(val && val instanceof Date){
+ return true;
+ }else if(typeof val == 'object' || typeof val == 'function'){
+ return false;
+ }
+ return true;
},
-
- /**
- * Clears all selections.
- */
- clearSelections : function(fast){
- if(this.locked) return;
- if(fast !== true){
- var ds = this.grid.dataSource;
- var s = this.selections;
- s.each(function(r){
- this.deselectRow(ds.indexOfId(r.id));
- }, this);
- s.clear();
- }else{
- this.selections.clear();
- }
- this.last = false;
+ setValue : function(prop, value){
+ this.source[prop] = value;
+ this.store.getById(prop).set('value', value);
},
+ getSource : function(){
+ return this.source;
+ }
+});
- /**
- * Selects all rows.
- */
- selectAll : function(){
- if(this.locked) return;
- this.selections.clear();
- for(var i = 0, len = this.grid.dataSource.getCount(); i < len; i++){
- this.selectRow(i, true);
- }
+Roo.grid.PropertyColumnModel = function(grid, store){
+ this.grid = grid;
+ var g = Roo.grid;
+ g.PropertyColumnModel.superclass.constructor.call(this, [
+ {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
+ {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
+ ]);
+ this.store = store;
+ this.bselect = Roo.DomHelper.append(document.body, {
+ tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
+ {tag: 'option', value: 'true', html: 'true'},
+ {tag: 'option', value: 'false', html: 'false'}
+ ]
+ });
+ Roo.id(this.bselect);
+ var f = Roo.form;
+ this.editors = {
+ 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
+ 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
+ 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
+ 'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
+ 'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
+ };
+ this.renderCellDelegate = this.renderCell.createDelegate(this);
+ this.renderPropDelegate = this.renderProp.createDelegate(this);
+};
+
+Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
+
+
+ nameText : 'Name',
+ valueText : 'Value',
+
+ dateFormat : 'm/j/Y',
+
+
+ renderDate : function(dateVal){
+ return dateVal.dateFormat(this.dateFormat);
},
- /**
- * Returns True if there is a selection.
- * @return {Boolean}
- */
- hasSelection : function(){
- return this.selections.length > 0;
+ renderBool : function(bVal){
+ return bVal ? 'true' : 'false';
},
- /**
- * Returns True if the specified row is selected.
- * @param {Number/Record} record The record or index of the record to check
- * @return {Boolean}
- */
- isSelected : function(index){
- var r = typeof index == "number" ? this.grid.dataSource.getAt(index) : index;
- return (r && this.selections.key(r.id) ? true : false);
+ isCellEditable : function(colIndex, rowIndex){
+ return colIndex == 1;
},
- /**
- * Returns True if the specified record id is selected.
- * @param {String} id The id of record to check
- * @return {Boolean}
- */
- isIdSelected : function(id){
- return (this.selections.key(id) ? true : false);
+ getRenderer : function(col){
+ return col == 1 ?
+ this.renderCellDelegate : this.renderPropDelegate;
},
- // private
- handleMouseDown : function(e, t){
- var view = this.grid.getView(), rowIndex;
- if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
- return;
- };
- if(e.shiftKey && this.last !== false){
- var last = this.last;
- this.selectRange(last, rowIndex, e.ctrlKey);
- this.last = last; // reset the last
- view.focusRow(rowIndex);
- }else{
- var isSelected = this.isSelected(rowIndex);
- if(e.button !== 0 && isSelected){
- view.focusRow(rowIndex);
- }else if(e.ctrlKey && isSelected){
- this.deselectRow(rowIndex);
- }else if(!isSelected){
- this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
- view.focusRow(rowIndex);
- }
- }
- this.fireEvent("afterselectionchange", this);
+ renderProp : function(v){
+ return this.getPropertyName(v);
},
- // private
- handleDragableRowClick : function(grid, rowIndex, e)
- {
- if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
- this.selectRow(rowIndex, false);
- grid.view.focusRow(rowIndex);
- this.fireEvent("afterselectionchange", this);
+
+ renderCell : function(val){
+ var rv = val;
+ if(val instanceof Date){
+ rv = this.renderDate(val);
+ }else if(typeof val == 'boolean'){
+ rv = this.renderBool(val);
}
+ return Roo.util.Format.htmlEncode(rv);
},
-
- /**
- * Selects multiple rows.
- * @param {Array} rows Array of the indexes of the row to select
- * @param {Boolean} keepExisting (optional) True to keep existing selections
- */
- selectRows : function(rows, keepExisting){
- if(!keepExisting){
- this.clearSelections();
- }
- for(var i = 0, len = rows.length; i < len; i++){
- this.selectRow(rows[i], true);
- }
+
+ getPropertyName : function(name){
+ var pn = this.grid.propertyNames;
+ return pn && pn[name] ? pn[name] : name;
},
- /**
- * Selects a range of rows. All rows in between startRow and endRow are also selected.
- * @param {Number} startRow The index of the first row in the range
- * @param {Number} endRow The index of the last row in the range
- * @param {Boolean} keepExisting (optional) True to retain existing selections
- */
- selectRange : function(startRow, endRow, keepExisting){
- if(this.locked) return;
- if(!keepExisting){
- this.clearSelections();
+ getCellEditor : function(colIndex, rowIndex){
+ var p = this.store.getProperty(rowIndex);
+ var n = p.data['name'], val = p.data['value'];
+
+ if(typeof(this.grid.customEditors[n]) == 'string'){
+ return this.editors[this.grid.customEditors[n]];
}
- if(startRow <= endRow){
- for(var i = startRow; i <= endRow; i++){
- this.selectRow(i, true);
- }
+ if(typeof(this.grid.customEditors[n]) != 'undefined'){
+ return this.grid.customEditors[n];
+ }
+ if(val instanceof Date){
+ return this.editors['date'];
+ }else if(typeof val == 'number'){
+ return this.editors['number'];
+ }else if(typeof val == 'boolean'){
+ return this.editors['boolean'];
}else{
- for(var i = startRow; i >= endRow; i--){
- this.selectRow(i, true);
- }
+ return this.editors['string'];
}
+ }
+});
+
+/**
+ * @class Roo.grid.PropertyGrid
+ * @extends Roo.grid.EditorGrid
+ * This class represents the interface of a component based property grid control.
+ * <br><br>Usage:<pre><code>
+ var grid = new Roo.grid.PropertyGrid("my-container-id", {
+
+ });
+ // set any options
+ grid.render();
+ * </code></pre>
+
+ * @constructor
+ * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
+ * The container MUST have some type of size defined for the grid to fill. The container will be
+ * automatically set to position relative if it isn't already.
+ * @param {Object} config A config object that sets properties on this grid.
+ */
+Roo.grid.PropertyGrid = function(container, config){
+ config = config || {};
+ var store = new Roo.grid.PropertyStore(this);
+ this.store = store;
+ var cm = new Roo.grid.PropertyColumnModel(this, store);
+ store.store.sort('name', 'ASC');
+ Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
+ ds: store.store,
+ cm: cm,
+ enableColLock:false,
+ enableColumnMove:false,
+ stripeRows:false,
+ trackMouseOver: false,
+ clicksToEdit:1
+ }, config));
+ this.getGridEl().addClass('x-props-grid');
+ this.lastEditRow = null;
+ this.on('columnresize', this.onColumnResize, this);
+ this.addEvents({
+ /**
+ * @event beforepropertychange
+ * Fires before a property changes (return false to stop?)
+ * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
+ * @param {String} id Record Id
+ * @param {String} newval New Value
+ * @param {String} oldval Old Value
+ */
+ "beforepropertychange": true,
+ /**
+ * @event propertychange
+ * Fires after a property changes
+ * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
+ * @param {String} id Record Id
+ * @param {String} newval New Value
+ * @param {String} oldval Old Value
+ */
+ "propertychange": true
+ });
+ this.customEditors = this.customEditors || {};
+};
+Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
+
+ /**
+ * @cfg {Object} customEditors map of colnames=> custom editors.
+ * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
+ * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
+ * false disables editing of the field.
+ */
+
+ /**
+ * @cfg {Object} propertyNames map of property Names to their displayed value
+ */
+
+ render : function(){
+ Roo.grid.PropertyGrid.superclass.render.call(this);
+ this.autoSize.defer(100, this);
},
- /**
- * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
- * @param {Number} startRow The index of the first row in the range
- * @param {Number} endRow The index of the last row in the range
- */
- deselectRange : function(startRow, endRow, preventViewNotify){
- if(this.locked) return;
- for(var i = startRow; i <= endRow; i++){
- this.deselectRow(i, preventViewNotify);
+ autoSize : function(){
+ Roo.grid.PropertyGrid.superclass.autoSize.call(this);
+ if(this.view){
+ this.view.fitColumns();
}
},
+ onColumnResize : function(){
+ this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
+ this.autoSize();
+ },
/**
- * Selects a row.
- * @param {Number} row The index of the row to select
- * @param {Boolean} keepExisting (optional) True to keep existing selections
+ * Sets the data for the Grid
+ * accepts a Key => Value object of all the elements avaiable.
+ * @param {Object} data to appear in grid.
*/
- selectRow : function(index, keepExisting, preventViewNotify){
- if(this.locked || (index < 0 || index >= this.grid.dataSource.getCount())) return;
- if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
- if(!keepExisting || this.singleSelect){
- this.clearSelections();
- }
- var r = this.grid.dataSource.getAt(index);
- this.selections.add(r);
- this.last = this.lastActive = index;
- if(!preventViewNotify){
- this.grid.getView().onRowSelect(index);
- }
- this.fireEvent("rowselect", this, index, r);
- this.fireEvent("selectionchange", this);
- }
+ setSource : function(source){
+ this.store.setSource(source);
+ //this.autoSize();
},
-
/**
- * Deselects a row.
- * @param {Number} row The index of the row to deselect
+ * Gets all the data from the grid.
+ * @return {Object} data data stored in grid
*/
- deselectRow : function(index, preventViewNotify){
- if(this.locked) return;
- if(this.last == index){
- this.last = false;
- }
- if(this.lastActive == index){
- this.lastActive = false;
- }
- var r = this.grid.dataSource.getAt(index);
- this.selections.remove(r);
- if(!preventViewNotify){
- this.grid.getView().onRowDeselect(index);
- }
- this.fireEvent("rowdeselect", this, index);
- this.fireEvent("selectionchange", this);
- },
-
- // private
- restoreLast : function(){
- if(this._last){
- this.last = this._last;
- }
- },
-
- // private
- acceptsNav : function(row, col, cm){
- return !cm.isHidden(col) && cm.isCellEditable(col, row);
- },
-
- // private
- onEditorKey : function(field, e){
- var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
- if(k == e.TAB){
- e.stopEvent();
- ed.completeEdit();
- if(e.shiftKey){
- newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
- }else{
- newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
- }
- }else if(k == e.ENTER && !e.ctrlKey){
- e.stopEvent();
- ed.completeEdit();
- if(e.shiftKey){
- newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
- }else{
- newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
- }
- }else if(k == e.ESC){
- ed.cancelEdit();
- }
- if(newCell){
- g.startEditing(newCell[0], newCell[1]);
- }
+ getSource : function(){
+ return this.store.getSource();
}
});/*
- * 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">
+
+ * Licence LGPL
+
*/
+
/**
- * @class Roo.grid.CellSelectionModel
- * @extends Roo.grid.AbstractSelectionModel
- * This class provides the basic implementation for cell selection in a grid.
- * @constructor
- * @param {Object} config The object containing the configuration of this model.
- * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
+ * @class Roo.grid.Calendar
+ * @extends Roo.util.Grid
+ * This class extends the Grid to provide a calendar widget
+ * <br><br>Usage:<pre><code>
+ var grid = new Roo.grid.Calendar("my-container-id", {
+ ds: myDataStore,
+ cm: myColModel,
+ selModel: mySelectionModel,
+ autoSizeColumns: true,
+ monitorWindowResize: false,
+ trackMouseOver: true
+ eventstore : real data store..
+ });
+ // set any options
+ grid.render();
+
+ * @constructor
+ * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
+ * The container MUST have some type of size defined for the grid to fill. The container will be
+ * automatically set to position relative if it isn't already.
+ * @param {Object} config A config object that sets properties on this grid.
*/
-Roo.grid.CellSelectionModel = function(config){
+Roo.grid.Calendar = function(container, config){
+ // initialize the container
+ this.container = Roo.get(container);
+ this.container.update("");
+ this.container.setStyle("overflow", "hidden");
+ this.container.addClass('x-grid-container');
+
+ this.id = this.container.id;
+
Roo.apply(this, config);
+ // check and correct shorthanded configs
+
+ var rows = [];
+ var d =1;
+ for (var r = 0;r < 6;r++) {
+
+ rows[r]=[];
+ for (var c =0;c < 7;c++) {
+ rows[r][c]= '';
+ }
+ }
+ if (this.eventStore) {
+ this.eventStore= Roo.factory(this.eventStore, Roo.data);
+ this.eventStore.on('load',this.onLoad, this);
+ this.eventStore.on('beforeload',this.clearEvents, this);
+
+ }
+
+ this.dataSource = new Roo.data.Store({
+ proxy: new Roo.data.MemoryProxy(rows),
+ reader: new Roo.data.ArrayReader({}, [
+ 'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
+ });
- this.selection = null;
+ this.dataSource.load();
+ this.ds = this.dataSource;
+ this.ds.xmodule = this.xmodule || false;
+
+
+ var cellRender = function(v,x,r)
+ {
+ return String.format(
+ '<div class="fc-day fc-widget-content"><div>' +
+ '<div class="fc-event-container"></div>' +
+ '<div class="fc-day-number">{0}</div>'+
+
+ '<div class="fc-day-content"><div style="position:relative"></div></div>' +
+ '</div></div>', v);
+
+ }
+
+
+ this.colModel = new Roo.grid.ColumnModel( [
+ {
+ xtype: 'ColumnModel',
+ xns: Roo.grid,
+ dataIndex : 'weekday0',
+ header : 'Sunday',
+ renderer : cellRender
+ },
+ {
+ xtype: 'ColumnModel',
+ xns: Roo.grid,
+ dataIndex : 'weekday1',
+ header : 'Monday',
+ renderer : cellRender
+ },
+ {
+ xtype: 'ColumnModel',
+ xns: Roo.grid,
+ dataIndex : 'weekday2',
+ header : 'Tuesday',
+ renderer : cellRender
+ },
+ {
+ xtype: 'ColumnModel',
+ xns: Roo.grid,
+ dataIndex : 'weekday3',
+ header : 'Wednesday',
+ renderer : cellRender
+ },
+ {
+ xtype: 'ColumnModel',
+ xns: Roo.grid,
+ dataIndex : 'weekday4',
+ header : 'Thursday',
+ renderer : cellRender
+ },
+ {
+ xtype: 'ColumnModel',
+ xns: Roo.grid,
+ dataIndex : 'weekday5',
+ header : 'Friday',
+ renderer : cellRender
+ },
+ {
+ xtype: 'ColumnModel',
+ xns: Roo.grid,
+ dataIndex : 'weekday6',
+ header : 'Saturday',
+ renderer : cellRender
+ }
+ ]);
+ this.cm = this.colModel;
+ this.cm.xmodule = this.xmodule || false;
+
+
+
+ //this.selModel = new Roo.grid.CellSelectionModel();
+ //this.sm = this.selModel;
+ //this.selModel.init(this);
+
+
+ if(this.width){
+ this.container.setWidth(this.width);
+ }
+
+ if(this.height){
+ this.container.setHeight(this.height);
+ }
+ /** @private */
+ this.addEvents({
+ // raw events
+ /**
+ * @event click
+ * The raw click event for the entire grid.
+ * @param {Roo.EventObject} e
+ */
+ "click" : true,
+ /**
+ * @event dblclick
+ * The raw dblclick event for the entire grid.
+ * @param {Roo.EventObject} e
+ */
+ "dblclick" : true,
+ /**
+ * @event contextmenu
+ * The raw contextmenu event for the entire grid.
+ * @param {Roo.EventObject} e
+ */
+ "contextmenu" : true,
+ /**
+ * @event mousedown
+ * The raw mousedown event for the entire grid.
+ * @param {Roo.EventObject} e
+ */
+ "mousedown" : true,
+ /**
+ * @event mouseup
+ * The raw mouseup event for the entire grid.
+ * @param {Roo.EventObject} e
+ */
+ "mouseup" : true,
+ /**
+ * @event mouseover
+ * The raw mouseover event for the entire grid.
+ * @param {Roo.EventObject} e
+ */
+ "mouseover" : true,
+ /**
+ * @event mouseout
+ * The raw mouseout event for the entire grid.
+ * @param {Roo.EventObject} e
+ */
+ "mouseout" : true,
+ /**
+ * @event keypress
+ * The raw keypress event for the entire grid.
+ * @param {Roo.EventObject} e
+ */
+ "keypress" : true,
+ /**
+ * @event keydown
+ * The raw keydown event for the entire grid.
+ * @param {Roo.EventObject} e
+ */
+ "keydown" : true,
+
+ // custom events
+
+ /**
+ * @event cellclick
+ * Fires when a cell is clicked
+ * @param {Grid} this
+ * @param {Number} rowIndex
+ * @param {Number} columnIndex
+ * @param {Roo.EventObject} e
+ */
+ "cellclick" : true,
+ /**
+ * @event celldblclick
+ * Fires when a cell is double clicked
+ * @param {Grid} this
+ * @param {Number} rowIndex
+ * @param {Number} columnIndex
+ * @param {Roo.EventObject} e
+ */
+ "celldblclick" : true,
+ /**
+ * @event rowclick
+ * Fires when a row is clicked
+ * @param {Grid} this
+ * @param {Number} rowIndex
+ * @param {Roo.EventObject} e
+ */
+ "rowclick" : true,
+ /**
+ * @event rowdblclick
+ * Fires when a row is double clicked
+ * @param {Grid} this
+ * @param {Number} rowIndex
+ * @param {Roo.EventObject} e
+ */
+ "rowdblclick" : true,
+ /**
+ * @event headerclick
+ * Fires when a header is clicked
+ * @param {Grid} this
+ * @param {Number} columnIndex
+ * @param {Roo.EventObject} e
+ */
+ "headerclick" : true,
+ /**
+ * @event headerdblclick
+ * Fires when a header cell is double clicked
+ * @param {Grid} this
+ * @param {Number} columnIndex
+ * @param {Roo.EventObject} e
+ */
+ "headerdblclick" : true,
+ /**
+ * @event rowcontextmenu
+ * Fires when a row is right clicked
+ * @param {Grid} this
+ * @param {Number} rowIndex
+ * @param {Roo.EventObject} e
+ */
+ "rowcontextmenu" : true,
+ /**
+ * @event cellcontextmenu
+ * Fires when a cell is right clicked
+ * @param {Grid} this
+ * @param {Number} rowIndex
+ * @param {Number} cellIndex
+ * @param {Roo.EventObject} e
+ */
+ "cellcontextmenu" : true,
+ /**
+ * @event headercontextmenu
+ * Fires when a header is right clicked
+ * @param {Grid} this
+ * @param {Number} columnIndex
+ * @param {Roo.EventObject} e
+ */
+ "headercontextmenu" : true,
+ /**
+ * @event bodyscroll
+ * Fires when the body element is scrolled
+ * @param {Number} scrollLeft
+ * @param {Number} scrollTop
+ */
+ "bodyscroll" : true,
+ /**
+ * @event columnresize
+ * Fires when the user resizes a column
+ * @param {Number} columnIndex
+ * @param {Number} newSize
+ */
+ "columnresize" : true,
+ /**
+ * @event columnmove
+ * Fires when the user moves a column
+ * @param {Number} oldIndex
+ * @param {Number} newIndex
+ */
+ "columnmove" : true,
+ /**
+ * @event startdrag
+ * Fires when row(s) start being dragged
+ * @param {Grid} this
+ * @param {Roo.GridDD} dd The drag drop object
+ * @param {event} e The raw browser event
+ */
+ "startdrag" : true,
+ /**
+ * @event enddrag
+ * Fires when a drag operation is complete
+ * @param {Grid} this
+ * @param {Roo.GridDD} dd The drag drop object
+ * @param {event} e The raw browser event
+ */
+ "enddrag" : true,
+ /**
+ * @event dragdrop
+ * Fires when dragged row(s) are dropped on a valid DD target
+ * @param {Grid} this
+ * @param {Roo.GridDD} dd The drag drop object
+ * @param {String} targetId The target drag drop object
+ * @param {event} e The raw browser event
+ */
+ "dragdrop" : true,
+ /**
+ * @event dragover
+ * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
+ * @param {Grid} this
+ * @param {Roo.GridDD} dd The drag drop object
+ * @param {String} targetId The target drag drop object
+ * @param {event} e The raw browser event
+ */
+ "dragover" : true,
+ /**
+ * @event dragenter
+ * Fires when the dragged row(s) first cross another DD target while being dragged
+ * @param {Grid} this
+ * @param {Roo.GridDD} dd The drag drop object
+ * @param {String} targetId The target drag drop object
+ * @param {event} e The raw browser event
+ */
+ "dragenter" : true,
+ /**
+ * @event dragout
+ * Fires when the dragged row(s) leave another DD target while being dragged
+ * @param {Grid} this
+ * @param {Roo.GridDD} dd The drag drop object
+ * @param {String} targetId The target drag drop object
+ * @param {event} e The raw browser event
+ */
+ "dragout" : true,
+ /**
+ * @event rowclass
+ * Fires when a row is rendered, so you can change add a style to it.
+ * @param {GridView} gridview The grid view
+ * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
+ */
+ 'rowclass' : true,
- this.addEvents({
/**
- * @event beforerowselect
- * Fires before a cell is selected.
- * @param {SelectionModel} this
- * @param {Number} rowIndex The selected row index
- * @param {Number} colIndex The selected cell index
+ * @event render
+ * Fires when the grid is rendered
+ * @param {Grid} grid
+ */
+ 'render' : true,
+ /**
+ * @event select
+ * Fires when a date is selected
+ * @param {DatePicker} this
+ * @param {Date} date The selected date
*/
- "beforecellselect" : true,
+ 'select': true,
/**
- * @event cellselect
- * Fires when a cell is selected.
- * @param {SelectionModel} this
- * @param {Number} rowIndex The selected row index
- * @param {Number} colIndex The selected cell index
+ * @event monthchange
+ * Fires when the displayed month changes
+ * @param {DatePicker} this
+ * @param {Date} date The selected month
*/
- "cellselect" : true,
+ 'monthchange': true,
/**
- * @event selectionchange
- * Fires when the active selection changes.
- * @param {SelectionModel} this
- * @param {Object} selection null for no selection or an object (o) with two properties
- <ul>
- <li>o.record: the record object for the row the selection is in</li>
- <li>o.cell: An array of [rowIndex, columnIndex]</li>
- </ul>
+ * @event evententer
+ * Fires when mouse over an event
+ * @param {Calendar} this
+ * @param {event} Event
*/
- "selectionchange" : true,
+ 'evententer': true,
/**
- * @event tabend
- * Fires when the tab (or enter) was pressed on the last editable cell
- * You can use this to trigger add new row.
- * @param {SelectionModel} this
+ * @event eventleave
+ * Fires when the mouse leaves an
+ * @param {Calendar} this
+ * @param {event}
*/
- "tabend" : true,
- /**
- * @event beforeeditnext
- * Fires before the next editable sell is made active
- * You can use this to skip to another cell or fire the tabend
- * if you set cell to false
- * @param {Object} eventdata object : { cell : [ row, col ] }
+ 'eventleave': true,
+ /**
+ * @event eventclick
+ * Fires when the mouse click an
+ * @param {Calendar} this
+ * @param {event}
*/
- "beforeeditnext" : true
+ 'eventclick': true,
+ /**
+ * @event eventrender
+ * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
+ * @param {Calendar} this
+ * @param {data} data to be modified
+ */
+ 'eventrender': true
+
});
- Roo.grid.CellSelectionModel.superclass.constructor.call(this);
-};
-Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel, {
+ Roo.grid.Grid.superclass.constructor.call(this);
+ this.on('render', function() {
+ this.view.el.addClass('x-grid-cal');
+
+ (function() { this.setDate(new Date()); }).defer(100,this); //default today..
+
+ },this);
- enter_is_tab: false,
+ if (!Roo.grid.Calendar.style) {
+ Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
+
+
+ '.x-grid-cal .x-grid-col' : {
+ height: 'auto !important',
+ 'vertical-align': 'top'
+ },
+ '.x-grid-cal .fc-event-hori' : {
+ height: '14px'
+ }
+
+
+ }, Roo.id());
+ }
- /** @ignore */
- initEvents : function(){
- this.grid.on("mousedown", this.handleMouseDown, this);
- this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
- var view = this.grid.view;
- view.on("refresh", this.onViewChange, this);
- view.on("rowupdated", this.onRowUpdated, this);
- view.on("beforerowremoved", this.clearSelections, this);
- view.on("beforerowsinserted", this.clearSelections, this);
- if(this.grid.isEditor){
- this.grid.on("beforeedit", this.beforeEdit, this);
- }
- },
+
+
+};
+Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
+ /**
+ * @cfg {Store} eventStore The store that loads events.
+ */
+ eventStore : 25,
- //private
- beforeEdit : function(e){
- this.select(e.row, e.column, false, true, e.record);
- },
+
+ activeDate : false,
+ startDay : 0,
+ autoWidth : true,
+ monitorWindowResize : false,
- //private
- onRowUpdated : function(v, index, r){
- if(this.selection && this.selection.record == r){
- v.onCellSelect(index, this.selection.cell[1]);
+
+ resizeColumns : function() {
+ var col = (this.view.el.getWidth() / 7) - 3;
+ // loop through cols, and setWidth
+ for(var i =0 ; i < 7 ; i++){
+ this.cm.setColumnWidth(i, col);
}
},
+ setDate :function(date) {
+
+ Roo.log('setDate?');
+
+ this.resizeColumns();
+ var vd = this.activeDate;
+ this.activeDate = date;
+// if(vd && this.el){
+// var t = date.getTime();
+// if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
+// Roo.log('using add remove');
+//
+// this.fireEvent('monthchange', this, date);
+//
+// this.cells.removeClass("fc-state-highlight");
+// this.cells.each(function(c){
+// if(c.dateValue == t){
+// c.addClass("fc-state-highlight");
+// setTimeout(function(){
+// try{c.dom.firstChild.focus();}catch(e){}
+// }, 50);
+// return false;
+// }
+// return true;
+// });
+// return;
+// }
+// }
+
+ var days = date.getDaysInMonth();
+
+ var firstOfMonth = date.getFirstDateOfMonth();
+ var startingPos = firstOfMonth.getDay()-this.startDay;
+
+ if(startingPos < this.startDay){
+ startingPos += 7;
+ }
+
+ var pm = date.add(Date.MONTH, -1);
+ var prevStart = pm.getDaysInMonth()-startingPos;
+//
+
+
+ this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
+
+ this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
+ //this.cells.addClassOnOver('fc-state-hover');
+
+ var cells = this.cells.elements;
+ var textEls = this.textNodes;
+
+ //Roo.each(cells, function(cell){
+ // cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
+ //});
+
+ days += startingPos;
- //private
- onViewChange : function(){
- this.clearSelections(true);
- },
+ // convert everything to numbers so it's fast
+ var day = 86400000;
+ var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
+ //Roo.log(d);
+ //Roo.log(pm);
+ //Roo.log(prevStart);
+
+ var today = new Date().clearTime().getTime();
+ var sel = date.clearTime().getTime();
+ var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
+ var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
+ var ddMatch = this.disabledDatesRE;
+ var ddText = this.disabledDatesText;
+ var ddays = this.disabledDays ? this.disabledDays.join("") : false;
+ var ddaysText = this.disabledDaysText;
+ var format = this.format;
+
+ var setCellClass = function(cal, cell){
+
+ //Roo.log('set Cell Class');
+ cell.title = "";
+ var t = d.getTime();
+
+ //Roo.log(d);
+
+
+ cell.dateValue = t;
+ if(t == today){
+ cell.className += " fc-today";
+ cell.className += " fc-state-highlight";
+ cell.title = cal.todayText;
+ }
+ if(t == sel){
+ // disable highlight in other month..
+ cell.className += " fc-state-highlight";
+
+ }
+ // disabling
+ if(t < min) {
+ //cell.className = " fc-state-disabled";
+ cell.title = cal.minText;
+ return;
+ }
+ if(t > max) {
+ //cell.className = " fc-state-disabled";
+ cell.title = cal.maxText;
+ return;
+ }
+ if(ddays){
+ if(ddays.indexOf(d.getDay()) != -1){
+ // cell.title = ddaysText;
+ // cell.className = " fc-state-disabled";
+ }
+ }
+ if(ddMatch && format){
+ var fvalue = d.dateFormat(format);
+ if(ddMatch.test(fvalue)){
+ cell.title = ddText.replace("%0", fvalue);
+ cell.className = " fc-state-disabled";
+ }
+ }
+
+ if (!cell.initialClassName) {
+ cell.initialClassName = cell.dom.className;
+ }
+
+ cell.dom.className = cell.initialClassName + ' ' + cell.className;
+ };
- /**
- * Returns the currently selected cell,.
- * @return {Array} The selected cell (row, column) or null if none selected.
- */
- getSelectedCell : function(){
- return this.selection ? this.selection.cell : null;
+ var i = 0;
+
+ for(; i < startingPos; i++) {
+ cells[i].dayName = (++prevStart);
+ Roo.log(textEls[i]);
+ d.setDate(d.getDate()+1);
+
+ //cells[i].className = "fc-past fc-other-month";
+ setCellClass(this, cells[i]);
+ }
+
+ var intDay = 0;
+
+ for(; i < days; i++){
+ intDay = i - startingPos + 1;
+ cells[i].dayName = (intDay);
+ d.setDate(d.getDate()+1);
+
+ cells[i].className = ''; // "x-date-active";
+ setCellClass(this, cells[i]);
+ }
+ var extraDays = 0;
+
+ for(; i < 42; i++) {
+ //textEls[i].innerHTML = (++extraDays);
+
+ d.setDate(d.getDate()+1);
+ cells[i].dayName = (++extraDays);
+ cells[i].className = "fc-future fc-other-month";
+ setCellClass(this, cells[i]);
+ }
+
+ //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
+
+ var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
+
+ // this will cause all the cells to mis
+ var rows= [];
+ var i =0;
+ for (var r = 0;r < 6;r++) {
+ for (var c =0;c < 7;c++) {
+ this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
+ }
+ }
+
+ this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
+ for(i=0;i<cells.length;i++) {
+
+ this.cells.elements[i].dayName = cells[i].dayName ;
+ this.cells.elements[i].className = cells[i].className;
+ this.cells.elements[i].initialClassName = cells[i].initialClassName ;
+ this.cells.elements[i].title = cells[i].title ;
+ this.cells.elements[i].dateValue = cells[i].dateValue ;
+ }
+
+
+
+
+ //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
+ //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
+
+ ////if(totalRows != 6){
+ //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
+ // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
+ // }
+
+ this.fireEvent('monthchange', this, date);
+
+
},
-
- /**
- * Clears all selections.
- * @param {Boolean} true to prevent the gridview from being notified about the change.
+ /**
+ * Returns the grid's SelectionModel.
+ * @return {SelectionModel}
*/
- clearSelections : function(preventNotify){
- var s = this.selection;
- if(s){
- if(preventNotify !== true){
- this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
- }
- this.selection = null;
- this.fireEvent("selectionchange", this, null);
+ getSelectionModel : function(){
+ if(!this.selModel){
+ this.selModel = new Roo.grid.CellSelectionModel();
}
+ return this.selModel;
},
- /**
- * Returns true if there is a selection.
- * @return {Boolean}
- */
- hasSelection : function(){
- return this.selection ? true : false;
+ load: function() {
+ this.eventStore.load()
+
+
+
},
-
- /** @ignore */
- handleMouseDown : function(e, t){
- var v = this.grid.getView();
- if(this.isLocked()){
- return;
- };
- var row = v.findRowIndex(t);
- var cell = v.findCellIndex(t);
- if(row !== false && cell !== false){
- this.select(row, cell);
- }
+
+ findCell : function(dt) {
+ dt = dt.clearTime().getTime();
+ var ret = false;
+ this.cells.each(function(c){
+ //Roo.log("check " +c.dateValue + '?=' + dt);
+ if(c.dateValue == dt){
+ ret = c;
+ return false;
+ }
+ return true;
+ });
+
+ return ret;
},
-
- /**
- * Selects a cell.
- * @param {Number} rowIndex
- * @param {Number} collIndex
- */
- select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
- if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
- this.clearSelections();
- r = r || this.grid.dataSource.getAt(rowIndex);
- this.selection = {
- record : r,
- cell : [rowIndex, colIndex]
- };
- if(!preventViewNotify){
- var v = this.grid.getView();
- v.onCellSelect(rowIndex, colIndex);
- if(preventFocus !== true){
- v.focusCell(rowIndex, colIndex);
- }
+
+ findCells : function(rec) {
+ var s = rec.data.start_dt.clone().clearTime().getTime();
+ // Roo.log(s);
+ var e= rec.data.end_dt.clone().clearTime().getTime();
+ // Roo.log(e);
+ var ret = [];
+ this.cells.each(function(c){
+ ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
+
+ if(c.dateValue > e){
+ return ;
}
- this.fireEvent("cellselect", this, rowIndex, colIndex);
- this.fireEvent("selectionchange", this, this.selection);
+ if(c.dateValue < s){
+ return ;
+ }
+ ret.push(c);
+ });
+
+ return ret;
+ },
+
+ findBestRow: function(cells)
+ {
+ var ret = 0;
+
+ for (var i =0 ; i < cells.length;i++) {
+ ret = Math.max(cells[i].rows || 0,ret);
}
+ return ret;
+
},
-
- //private
- isSelectable : function(rowIndex, colIndex, cm){
- return !cm.isHidden(colIndex);
+
+
+ addItem : function(rec)
+ {
+ // look for vertical location slot in
+ var cells = this.findCells(rec);
+
+ rec.row = this.findBestRow(cells);
+
+ // work out the location.
+
+ var crow = false;
+ var rows = [];
+ for(var i =0; i < cells.length; i++) {
+ if (!crow) {
+ crow = {
+ start : cells[i],
+ end : cells[i]
+ };
+ continue;
+ }
+ if (crow.start.getY() == cells[i].getY()) {
+ // on same row.
+ crow.end = cells[i];
+ continue;
+ }
+ // different row.
+ rows.push(crow);
+ crow = {
+ start: cells[i],
+ end : cells[i]
+ };
+
+ }
+
+ rows.push(crow);
+ rec.els = [];
+ rec.rows = rows;
+ rec.cells = cells;
+ for (var i = 0; i < cells.length;i++) {
+ cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
+
+ }
+
+
},
-
- /** @ignore */
- handleKeyDown : function(e){
- //Roo.log('Cell Sel Model handleKeyDown');
- if(!e.isNavKeyPress()){
+
+ clearEvents: function() {
+
+ if (!this.eventStore.getCount()) {
return;
}
- var g = this.grid, s = this.selection;
- if(!s){
- e.stopEvent();
- var cell = g.walkCells(0, 0, 1, this.isSelectable, this);
- if(cell){
- this.select(cell[0], cell[1]);
- }
- return;
+ // reset number of rows in cells.
+ Roo.each(this.cells.elements, function(c){
+ c.rows = 0;
+ });
+
+ this.eventStore.each(function(e) {
+ this.clearEvent(e);
+ },this);
+
+ },
+
+ clearEvent : function(ev)
+ {
+ if (ev.els) {
+ Roo.each(ev.els, function(el) {
+ el.un('mouseenter' ,this.onEventEnter, this);
+ el.un('mouseleave' ,this.onEventLeave, this);
+ el.remove();
+ },this);
+ ev.els = [];
}
- var sm = this;
- var walk = function(row, col, step){
- return g.walkCells(row, col, step, sm.isSelectable, sm);
- };
- var k = e.getKey(), r = s.cell[0], c = s.cell[1];
- var newCell;
-
-
-
- switch(k){
- case e.TAB:
- // handled by onEditorKey
- if (g.isEditor && g.editing) {
- return;
- }
- if(e.shiftKey) {
- newCell = walk(r, c-1, -1);
- } else {
- newCell = walk(r, c+1, 1);
- }
- break;
+ },
+
+
+ renderEvent : function(ev,ctr) {
+ if (!ctr) {
+ ctr = this.view.el.select('.fc-event-container',true).first();
+ }
+
+
+ this.clearEvent(ev);
+ //code
+
+
+
+ ev.els = [];
+ var cells = ev.cells;
+ var rows = ev.rows;
+ this.fireEvent('eventrender', this, ev);
+
+ for(var i =0; i < rows.length; i++) {
- case e.DOWN:
- newCell = walk(r+1, c, 1);
- break;
+ cls = '';
+ if (i == 0) {
+ cls += ' fc-event-start';
+ }
+ if ((i+1) == rows.length) {
+ cls += ' fc-event-end';
+ }
- case e.UP:
- newCell = walk(r-1, c, -1);
- break;
+ //Roo.log(ev.data);
+ // how many rows should it span..
+ var cg = this.eventTmpl.append(ctr,Roo.apply({
+ fccls : cls
+
+ }, ev.data) , true);
- case e.RIGHT:
- newCell = walk(r, c+1, 1);
- break;
- case e.LEFT:
- newCell = walk(r, c-1, -1);
- break;
+ cg.on('mouseenter' ,this.onEventEnter, this, ev);
+ cg.on('mouseleave' ,this.onEventLeave, this, ev);
+ cg.on('click', this.onEventClick, this, ev);
- case e.ENTER:
-
- if(g.isEditor && !g.editing){
- g.startEditing(r, c);
- e.stopEvent();
- return;
- }
-
-
- break;
- };
- if(newCell){
- this.select(newCell[0], newCell[1]);
- e.stopEvent();
+ ev.els.push(cg);
+ var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
+ var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
+ //Roo.log(cg);
+
+ cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);
+ cg.setWidth(ebox.right - sbox.x -2);
}
},
-
- acceptsNav : function(row, col, cm){
- return !cm.isHidden(col) && cm.isCellEditable(col, row);
- },
- /**
- * Selects a cell.
- * @param {Number} field (not used) - as it's normally used as a listener
- * @param {Number} e - event - fake it by using
- *
- * var e = Roo.EventObjectImpl.prototype;
- * e.keyCode = e.TAB
- *
- *
- */
- onEditorKey : function(field, e){
+
+ renderEvents: function()
+ {
+ // first make sure there is enough space..
- var k = e.getKey(),
- newCell,
- g = this.grid,
- ed = g.activeEditor,
- forward = false;
- ///Roo.log('onEditorKey' + k);
+ if (!this.eventTmpl) {
+ this.eventTmpl = new Roo.Template(
+ '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}" style="position: absolute" unselectable="on">' +
+ '<div class="fc-event-inner">' +
+ '<span class="fc-event-time">{time}</span>' +
+ '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
+ '</div>' +
+ '<div class="ui-resizable-heandle ui-resizable-e"> </div>' +
+ '</div>'
+ );
+
+ }
+
- if (this.enter_is_tab && k == e.ENTER) {
- k = e.TAB;
- }
+ this.cells.each(function(c) {
+ //Roo.log(c.select('.fc-day-content div',true).first());
+ c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
+ });
- if(k == e.TAB){
- if(e.shiftKey){
- newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
- }else{
- newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
- forward = true;
- }
-
- e.stopEvent();
+ var ctr = this.view.el.select('.fc-event-container',true).first();
+
+ var cls;
+ this.eventStore.each(function(ev){
- } else if(k == e.ENTER && !e.ctrlKey){
- ed.completeEdit();
- e.stopEvent();
- newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
+ this.renderEvent(ev);
+
+
+ }, this);
+ this.view.layout();
- } else if(k == e.ESC){
- ed.cancelEdit();
- }
-
- if (newCell) {
- var ecall = { cell : newCell, forward : forward };
- this.fireEvent('beforeeditnext', ecall );
- newCell = ecall.cell;
- forward = ecall.forward;
- }
-
- if(newCell){
- //Roo.log('next cell after edit');
- g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
- } else if (forward) {
- // tabbed past last
- this.fireEvent.defer(100, this, ['tabend',this]);
+ },
+
+ onEventEnter: function (e, el,event,d) {
+ this.fireEvent('evententer', this, el, event);
+ },
+
+ onEventLeave: function (e, el,event,d) {
+ this.fireEvent('eventleave', this, el, event);
+ },
+
+ onEventClick: function (e, el,event,d) {
+ this.fireEvent('eventclick', this, el, event);
+ },
+
+ onMonthChange: function () {
+ this.store.load();
+ },
+
+ onLoad: function () {
+
+ //Roo.log('calendar onload');
+//
+ if(this.eventStore.getCount() > 0){
+
+
+
+ this.eventStore.each(function(d){
+
+
+ // FIXME..
+ var add = d.data;
+ if (typeof(add.end_dt) == 'undefined') {
+ Roo.log("Missing End time in calendar data: ");
+ Roo.log(d);
+ return;
+ }
+ if (typeof(add.start_dt) == 'undefined') {
+ Roo.log("Missing Start time in calendar data: ");
+ Roo.log(d);
+ return;
+ }
+ add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
+ add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
+ add.id = add.id || d.id;
+ add.title = add.title || '??';
+
+ this.addItem(d);
+
+
+ },this);
}
+
+ this.renderEvents();
}
-});/*
+
+
+});
+/*
+ grid : {
+ xtype: 'Grid',
+ xns: Roo.grid,
+ listeners : {
+ render : function ()
+ {
+ _this.grid = this;
+
+ if (!this.view.el.hasClass('course-timesheet')) {
+ this.view.el.addClass('course-timesheet');
+ }
+ if (this.tsStyle) {
+ this.ds.load({});
+ return;
+ }
+ Roo.log('width');
+ Roo.log(_this.grid.view.el.getWidth());
+
+
+ this.tsStyle = Roo.util.CSS.createStyleSheet({
+ '.course-timesheet .x-grid-row' : {
+ height: '80px'
+ },
+ '.x-grid-row td' : {
+ 'vertical-align' : 0
+ },
+ '.course-edit-link' : {
+ 'color' : 'blue',
+ 'text-overflow' : 'ellipsis',
+ 'overflow' : 'hidden',
+ 'white-space' : 'nowrap',
+ 'cursor' : 'pointer'
+ },
+ '.sub-link' : {
+ 'color' : 'green'
+ },
+ '.de-act-sup-link' : {
+ 'color' : 'purple',
+ 'text-decoration' : 'line-through'
+ },
+ '.de-act-link' : {
+ 'color' : 'red',
+ 'text-decoration' : 'line-through'
+ },
+ '.course-timesheet .course-highlight' : {
+ 'border-top-style': 'dashed !important',
+ 'border-bottom-bottom': 'dashed !important'
+ },
+ '.course-timesheet .course-item' : {
+ 'font-family' : 'tahoma, arial, helvetica',
+ 'font-size' : '11px',
+ 'overflow' : 'hidden',
+ 'padding-left' : '10px',
+ 'padding-right' : '10px',
+ 'padding-top' : '10px'
+ }
+
+ }, Roo.id());
+ this.ds.load({});
+ }
+ },
+ autoWidth : true,
+ monitorWindowResize : false,
+ cellrenderer : function(v,x,r)
+ {
+ return v;
+ },
+ sm : {
+ xtype: 'CellSelectionModel',
+ xns: Roo.grid
+ },
+ dataSource : {
+ xtype: 'Store',
+ xns: Roo.data,
+ listeners : {
+ beforeload : function (_self, options)
+ {
+ options.params = options.params || {};
+ options.params._month = _this.monthField.getValue();
+ options.params.limit = 9999;
+ options.params['sort'] = 'when_dt';
+ options.params['dir'] = 'ASC';
+ this.proxy.loadResponse = this.loadResponse;
+ Roo.log("load?");
+ //this.addColumns();
+ },
+ load : function (_self, records, options)
+ {
+ _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
+ // if you click on the translation.. you can edit it...
+ var el = Roo.get(this);
+ var id = el.dom.getAttribute('data-id');
+ var d = el.dom.getAttribute('data-date');
+ var t = el.dom.getAttribute('data-time');
+ //var id = this.child('span').dom.textContent;
+
+ //Roo.log(this);
+ Pman.Dialog.CourseCalendar.show({
+ id : id,
+ when_d : d,
+ when_t : t,
+ productitem_active : id ? 1 : 0
+ }, function() {
+ _this.grid.ds.load({});
+ });
+
+ });
+
+ _this.panel.fireEvent('resize', [ '', '' ]);
+ }
+ },
+ loadResponse : function(o, success, response){
+ // this is overridden on before load..
+
+ Roo.log("our code?");
+ //Roo.log(success);
+ //Roo.log(response)
+ delete this.activeRequest;
+ if(!success){
+ this.fireEvent("loadexception", this, o, response);
+ o.request.callback.call(o.request.scope, null, o.request.arg, false);
+ return;
+ }
+ var result;
+ try {
+ result = o.reader.read(response);
+ }catch(e){
+ Roo.log("load exception?");
+ this.fireEvent("loadexception", this, o, response, e);
+ o.request.callback.call(o.request.scope, null, o.request.arg, false);
+ return;
+ }
+ Roo.log("ready...");
+ // loop through result.records;
+ // and set this.tdate[date] = [] << array of records..
+ _this.tdata = {};
+ Roo.each(result.records, function(r){
+ //Roo.log(r.data);
+ if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
+ _this.tdata[r.data.when_dt.format('j')] = [];
+ }
+ _this.tdata[r.data.when_dt.format('j')].push(r.data);
+ });
+
+ //Roo.log(_this.tdata);
+
+ result.records = [];
+ result.totalRecords = 6;
+
+ // let's generate some duumy records for the rows.
+ //var st = _this.dateField.getValue();
+
+ // work out monday..
+ //st = st.add(Date.DAY, -1 * st.format('w'));
+
+ var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
+
+ var firstOfMonth = date.getFirstDayOfMonth();
+ var days = date.getDaysInMonth();
+ var d = 1;
+ var firstAdded = false;
+ for (var i = 0; i < result.totalRecords ; i++) {
+ //var d= st.add(Date.DAY, i);
+ var row = {};
+ var added = 0;
+ for(var w = 0 ; w < 7 ; w++){
+ if(!firstAdded && firstOfMonth != w){
+ continue;
+ }
+ if(d > days){
+ continue;
+ }
+ firstAdded = true;
+ var dd = (d > 0 && d < 10) ? "0"+d : d;
+ row['weekday'+w] = String.format(
+ '<span style="font-size: 16px;"><b>{0}</b></span>'+
+ '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
+ d,
+ date.format('Y-m-')+dd
+ );
+ added++;
+ if(typeof(_this.tdata[d]) != 'undefined'){
+ Roo.each(_this.tdata[d], function(r){
+ var is_sub = '';
+ var deactive = '';
+ var id = r.id;
+ var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
+ if(r.parent_id*1>0){
+ is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
+ id = r.parent_id;
+ }
+ if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
+ deactive = 'de-act-link';
+ }
+
+ row['weekday'+w] += String.format(
+ '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
+ id, //0
+ r.product_id_name, //1
+ r.when_dt.format('h:ia'), //2
+ is_sub, //3
+ deactive, //4
+ desc // 5
+ );
+ });
+ }
+ d++;
+ }
+
+ // only do this if something added..
+ if(added > 0){
+ result.records.push(_this.grid.dataSource.reader.newRow(row));
+ }
+
+
+ // push it twice. (second one with an hour..
+
+ }
+ //Roo.log(result);
+ this.fireEvent("load", this, o, o.request.arg);
+ o.request.callback.call(o.request.scope, result, o.request.arg, true);
+ },
+ sortInfo : {field: 'when_dt', direction : 'ASC' },
+ proxy : {
+ xtype: 'HttpProxy',
+ xns: Roo.data,
+ method : 'GET',
+ url : baseURL + '/Roo/Shop_course.php'
+ },
+ reader : {
+ xtype: 'JsonReader',
+ xns: Roo.data,
+ id : 'id',
+ fields : [
+ {
+ 'name': 'id',
+ 'type': 'int'
+ },
+ {
+ 'name': 'when_dt',
+ 'type': 'string'
+ },
+ {
+ 'name': 'end_dt',
+ 'type': 'string'
+ },
+ {
+ 'name': 'parent_id',
+ 'type': 'int'
+ },
+ {
+ 'name': 'product_id',
+ 'type': 'int'
+ },
+ {
+ 'name': 'productitem_id',
+ 'type': 'int'
+ },
+ {
+ 'name': 'guid',
+ 'type': 'int'
+ }
+ ]
+ }
+ },
+ toolbar : {
+ xtype: 'Toolbar',
+ xns: Roo,
+ items : [
+ {
+ xtype: 'Button',
+ xns: Roo.Toolbar,
+ listeners : {
+ click : function (_self, e)
+ {
+ var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
+ sd.setMonth(sd.getMonth()-1);
+ _this.monthField.setValue(sd.format('Y-m-d'));
+ _this.grid.ds.load({});
+ }
+ },
+ text : "Back"
+ },
+ {
+ xtype: 'Separator',
+ xns: Roo.Toolbar
+ },
+ {
+ xtype: 'MonthField',
+ xns: Roo.form,
+ listeners : {
+ render : function (_self)
+ {
+ _this.monthField = _self;
+ // _this.monthField.set today
+ },
+ select : function (combo, date)
+ {
+ _this.grid.ds.load({});
+ }
+ },
+ value : (function() { return new Date(); })()
+ },
+ {
+ xtype: 'Separator',
+ xns: Roo.Toolbar
+ },
+ {
+ xtype: 'TextItem',
+ xns: Roo.Toolbar,
+ text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
+ },
+ {
+ xtype: 'Fill',
+ xns: Roo.Toolbar
+ },
+ {
+ xtype: 'Button',
+ xns: Roo.Toolbar,
+ listeners : {
+ click : function (_self, e)
+ {
+ var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
+ sd.setMonth(sd.getMonth()+1);
+ _this.monthField.setValue(sd.format('Y-m-d'));
+ _this.grid.ds.load({});
+ }
+ },
+ text : "Next"
+ }
+ ]
+ },
+
+ }
+ };
+
+ *//*
* Based on:
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
*/
/**
- * @class Roo.grid.EditorGrid
- * @extends Roo.grid.Grid
- * Class for creating and editable grid.
- * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
- * The container MUST have some type of size defined for the grid to fill. The container will be
- * automatically set to position relative if it isn't already.
- * @param {Object} dataSource The data model to bind to
- * @param {Object} colModel The column model with info about this grid's columns
+ * @class Roo.LoadMask
+ * A simple utility class for generically masking elements while loading data. If the element being masked has
+ * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
+ * process and the mask element will be cached for reuse. For all other elements, this mask will replace the
+ * element's UpdateManager load indicator and will be destroyed after the initial load.
+ * @constructor
+ * Create a new LoadMask
+ * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
+ * @param {Object} config The config object
*/
-Roo.grid.EditorGrid = function(container, config){
- Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
- this.getGridEl().addClass("xedit-grid");
-
- if(!this.selModel){
- this.selModel = new Roo.grid.CellSelectionModel();
+Roo.LoadMask = function(el, config){
+ this.el = Roo.get(el);
+ Roo.apply(this, config);
+ if(this.store){
+ this.store.on('beforeload', this.onBeforeLoad, this);
+ this.store.on('load', this.onLoad, this);
+ this.store.on('loadexception', this.onLoadException, this);
+ this.removeMask = false;
+ }else{
+ var um = this.el.getUpdateManager();
+ um.showLoadIndicator = false; // disable the default indicator
+ um.on('beforeupdate', this.onBeforeLoad, this);
+ um.on('update', this.onLoad, this);
+ um.on('failure', this.onLoad, this);
+ this.removeMask = true;
}
-
- this.activeEditor = null;
-
- this.addEvents({
- /**
- * @event beforeedit
- * Fires before cell editing is triggered. The edit event object has the following properties <br />
- * <ul style="padding:5px;padding-left:16px;">
- * <li>grid - This grid</li>
- * <li>record - The record being edited</li>
- * <li>field - The field name being edited</li>
- * <li>value - The value for the field being edited.</li>
- * <li>row - The grid row index</li>
- * <li>column - The grid column index</li>
- * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
- * </ul>
- * @param {Object} e An edit event (see above for description)
- */
- "beforeedit" : true,
- /**
- * @event afteredit
- * Fires after a cell is edited. <br />
- * <ul style="padding:5px;padding-left:16px;">
- * <li>grid - This grid</li>
- * <li>record - The record being edited</li>
- * <li>field - The field name being edited</li>
- * <li>value - The value being set</li>
- * <li>originalValue - The original value for the field, before the edit.</li>
- * <li>row - The grid row index</li>
- * <li>column - The grid column index</li>
- * </ul>
- * @param {Object} e An edit event (see above for description)
- */
- "afteredit" : true,
- /**
- * @event validateedit
- * Fires after a cell is edited, but before the value is set in the record.
- * You can use this to modify the value being set in the field, Return false
- * to cancel the change. The edit event object has the following properties <br />
- * <ul style="padding:5px;padding-left:16px;">
- * <li>editor - This editor</li>
- * <li>grid - This grid</li>
- * <li>record - The record being edited</li>
- * <li>field - The field name being edited</li>
- * <li>value - The value being set</li>
- * <li>originalValue - The original value for the field, before the edit.</li>
- * <li>row - The grid row index</li>
- * <li>column - The grid column index</li>
- * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
- * </ul>
- * @param {Object} e An edit event (see above for description)
- */
- "validateedit" : true
- });
- this.on("bodyscroll", this.stopEditing, this);
- this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick, this);
};
-Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
+Roo.LoadMask.prototype = {
/**
- * @cfg {Number} clicksToEdit
- * The number of clicks on a cell required to display the cell's editor (defaults to 2)
+ * @cfg {Boolean} removeMask
+ * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
+ * False to persist the mask element reference for multiple uses (e.g., for paged data widgets). Defaults to false.
*/
- clicksToEdit: 2,
+ /**
+ * @cfg {String} msg
+ * The text to display in a centered loading message box (defaults to 'Loading...')
+ */
+ msg : 'Loading...',
+ /**
+ * @cfg {String} msgCls
+ * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
+ */
+ msgCls : 'x-mask-loading',
- // private
- isEditor : true,
- // private
- trackMouseOver: false, // causes very odd FF errors
+ /**
+ * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
+ * @type Boolean
+ */
+ disabled: false,
- onCellDblClick : function(g, row, col){
- this.startEditing(row, col);
+ /**
+ * Disables the mask to prevent it from being displayed
+ */
+ disable : function(){
+ this.disabled = true;
},
- onEditComplete : function(ed, value, startValue){
- this.editing = false;
- this.activeEditor = null;
- ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
- var r = ed.record;
- var field = this.colModel.getDataIndex(ed.col);
- var e = {
- grid: this,
- record: r,
- field: field,
- originalValue: startValue,
- value: value,
- row: ed.row,
- column: ed.col,
- cancel:false,
- editor: ed
- };
- var cell = Roo.get(this.view.getCell(ed.row,ed.col))
- cell.show();
-
- if(String(value) !== String(startValue)){
+ /**
+ * Enables the mask so that it can be displayed
+ */
+ enable : function(){
+ this.disabled = false;
+ },
+
+ onLoadException : function()
+ {
+ Roo.log(arguments);
+
+ if (typeof(arguments[3]) != 'undefined') {
+ Roo.MessageBox.alert("Error loading",arguments[3]);
+ }
+ /*
+ try {
+ if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
+ Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
+ }
+ } catch(e) {
- if(this.fireEvent("validateedit", e) !== false && !e.cancel){
- r.set(field, e.value);
- // if we are dealing with a combo box..
- // then we also set the 'name' colum to be the displayField
- if (ed.field.displayField && ed.field.name) {
- r.set(ed.field.name, ed.field.el.dom.value);
- }
-
- delete e.cancel; //?? why!!!
- this.fireEvent("afteredit", e);
- }
- } else {
- this.fireEvent("afteredit", e); // always fire it!
}
- this.view.focusCell(ed.row, ed.col);
+ */
+
+ (function() { this.el.unmask(this.removeMask); }).defer(50, this);
+ },
+ // private
+ onLoad : function()
+ {
+ (function() { this.el.unmask(this.removeMask); }).defer(50, this);
+ },
+
+ // private
+ onBeforeLoad : function(){
+ if(!this.disabled){
+ (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
+ }
},
+ // private
+ destroy : function(){
+ if(this.store){
+ this.store.un('beforeload', this.onBeforeLoad, this);
+ this.store.un('load', this.onLoad, this);
+ this.store.un('loadexception', this.onLoadException, this);
+ }else{
+ var um = this.el.getUpdateManager();
+ um.un('beforeupdate', this.onBeforeLoad, this);
+ um.un('update', this.onLoad, this);
+ um.un('failure', this.onLoad, 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.XTemplate
+ * @extends Roo.Template
+ * Provides a template that can have nested templates for loops or conditionals. The syntax is:
+<pre><code>
+var t = new Roo.XTemplate(
+ '<select name="{name}">',
+ '<tpl for="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
+ '</select>'
+);
+
+// then append, applying the master template values
+ </code></pre>
+ *
+ * Supported features:
+ *
+ * Tags:
+
+<pre><code>
+ {a_variable} - output encoded.
+ {a_variable.format:("Y-m-d")} - call a method on the variable
+ {a_variable:raw} - unencoded output
+ {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
+ {a_variable:this.method_on_template(...)} - call a method on the template object.
+
+</code></pre>
+ * The tpl tag:
+<pre><code>
+ <tpl for="a_variable or condition.."></tpl>
+ <tpl if="a_variable or condition"></tpl>
+ <tpl exec="some javascript"></tpl>
+ <tpl name="named_template"></tpl> (experimental)
+
+ <tpl for="."></tpl> - just iterate the property..
+ <tpl for=".."></tpl> - iterates with the parent (probably the template)
+</code></pre>
+ *
+ */
+Roo.XTemplate = function()
+{
+ Roo.XTemplate.superclass.constructor.apply(this, arguments);
+ if (this.html) {
+ this.compile();
+ }
+};
+
+
+Roo.extend(Roo.XTemplate, Roo.Template, {
+
/**
- * Starts editing the specified for the specified row/column
- * @param {Number} rowIndex
- * @param {Number} colIndex
+ * The various sub templates
*/
- startEditing : function(row, col){
- this.stopEditing();
- if(this.colModel.isCellEditable(col, row)){
- this.view.ensureVisible(row, col, true);
-
- var r = this.dataSource.getAt(row);
- var field = this.colModel.getDataIndex(col);
- var cell = Roo.get(this.view.getCell(row,col));
- var e = {
- grid: this,
- record: r,
- field: field,
- value: r.data[field],
- row: row,
- column: col,
- cancel:false
- };
- if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
- this.editing = true;
- var ed = this.colModel.getCellEditor(col, row);
+ tpls : false,
+ /**
+ *
+ * basic tag replacing syntax
+ * WORD:WORD()
+ *
+ * // you can fake an object call by doing this
+ * x.t:(test,tesT)
+ *
+ */
+ re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
+
+ /**
+ * compile the template
+ *
+ * This is not recursive, so I'm not sure how nested templates are really going to be handled..
+ *
+ */
+ compile: function()
+ {
+ var s = this.html;
+
+ s = ['<tpl>', s, '</tpl>'].join('');
+
+ var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
+ nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
+ ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
+ execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
+ namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
+ m,
+ id = 0,
+ tpls = [];
+
+ while(true == !!(m = s.match(re))){
+ var forMatch = m[0].match(nameRe),
+ ifMatch = m[0].match(ifRe),
+ execMatch = m[0].match(execRe),
+ namedMatch = m[0].match(namedRe),
- if (!ed) {
- return;
+ exp = null,
+ fn = null,
+ exec = null,
+ name = forMatch && forMatch[1] ? forMatch[1] : '';
+
+ if (ifMatch) {
+ // if - puts fn into test..
+ exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
+ if(exp){
+ fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
}
- if(!ed.rendered){
- ed.render(ed.parentEl || document.body);
+ }
+
+ if (execMatch) {
+ // exec - calls a function... returns empty if true is returned.
+ exp = execMatch && execMatch[1] ? execMatch[1] : null;
+ if(exp){
+ exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
+ }
+ }
+
+
+ if (name) {
+ // for =
+ switch(name){
+ case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
+ case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
+ default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
}
- ed.field.reset();
-
- cell.hide();
-
- (function(){ // complex but required for focus issues in safari, ie and opera
- ed.row = row;
- ed.col = col;
- ed.record = r;
- ed.on("complete", this.onEditComplete, this, {single: true});
- ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
- this.activeEditor = ed;
- var v = r.data[field];
- ed.startEdit(this.view.getCell(row, col), v);
- // combo's with 'displayField and name set
- if (ed.field.displayField && ed.field.name) {
- ed.field.el.dom.value = r.data[ed.field.name];
- }
-
-
- }).defer(50, this);
}
+ var uid = namedMatch ? namedMatch[1] : id;
+
+
+ tpls.push({
+ id: namedMatch ? namedMatch[1] : id,
+ target: name,
+ exec: exec,
+ test: fn,
+ body: m[1] || ''
+ });
+ if (namedMatch) {
+ s = s.replace(m[0], '');
+ } else {
+ s = s.replace(m[0], '{xtpl'+ id + '}');
+ }
+ ++id;
}
+ this.tpls = [];
+ for(var i = tpls.length-1; i >= 0; --i){
+ this.compileTpl(tpls[i]);
+ this.tpls[tpls[i].id] = tpls[i];
+ }
+ this.master = tpls[tpls.length-1];
+ return this;
},
-
/**
- * Stops any active editing
+ * same as applyTemplate, except it's done to one of the subTemplates
+ * when using named templates, you can do:
+ *
+ * var str = pl.applySubTemplate('your-name', values);
+ *
+ *
+ * @param {Number} id of the template
+ * @param {Object} values to apply to template
+ * @param {Object} parent (normaly the instance of this object)
*/
- stopEditing : function(){
- if(this.activeEditor){
- this.activeEditor.completeEdit();
+ applySubTemplate : function(id, values, parent)
+ {
+
+
+ var t = this.tpls[id];
+
+
+ try {
+ if(t.test && !t.test.call(this, values, parent)){
+ return '';
+ }
+ } catch(e) {
+ Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
+ Roo.log(e.toString());
+ Roo.log(t.test);
+ return ''
+ }
+ try {
+
+ if(t.exec && t.exec.call(this, values, parent)){
+ return '';
+ }
+ } catch(e) {
+ Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
+ Roo.log(e.toString());
+ Roo.log(t.exec);
+ return ''
+ }
+ try {
+ var vs = t.target ? t.target.call(this, values, parent) : values;
+ parent = t.target ? values : parent;
+ if(t.target && vs instanceof Array){
+ var buf = [];
+ for(var i = 0, len = vs.length; i < len; i++){
+ buf[buf.length] = t.compiled.call(this, vs[i], parent);
+ }
+ return buf.join('');
+ }
+ return t.compiled.call(this, vs, parent);
+ } catch (e) {
+ Roo.log("Xtemplate.applySubTemplate : Exception thrown");
+ Roo.log(e.toString());
+ Roo.log(t.compiled);
+ return '';
}
- this.activeEditor = null;
},
-
- /**
- * Called to get grid's drag proxy text, by default returns this.ddText.
- * @return {String}
- */
- getDragDropText : function(){
- var count = this.selModel.getSelectedCell() ? 1 : 0;
- return String.format(this.ddText, count, count == 1 ? '' : 's');
+
+ compileTpl : function(tpl)
+ {
+ var fm = Roo.util.Format;
+ var useF = this.disableFormats !== true;
+ var sep = Roo.isGecko ? "+" : ",";
+ var undef = function(str) {
+ Roo.log("Property not found :" + str);
+ return '';
+ };
+
+ var fn = function(m, name, format, args)
+ {
+ //Roo.log(arguments);
+ args = args ? args.replace(/\\'/g,"'") : args;
+ //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
+ if (typeof(format) == 'undefined') {
+ format= 'htmlEncode';
+ }
+ if (format == 'raw' ) {
+ format = false;
+ }
+
+ if(name.substr(0, 4) == 'xtpl'){
+ return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
+ }
+
+ // build an array of options to determine if value is undefined..
+
+ // basically get 'xxxx.yyyy' then do
+ // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
+ // (function () { Roo.log("Property not found"); return ''; })() :
+ // ......
+
+ var udef_ar = [];
+ var lookfor = '';
+ Roo.each(name.split('.'), function(st) {
+ lookfor += (lookfor.length ? '.': '') + st;
+ udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
+ });
+
+ var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
+
+
+ if(format && useF){
+
+ args = args ? ',' + args : "";
+
+ if(format.substr(0, 5) != "this."){
+ format = "fm." + format + '(';
+ }else{
+ format = 'this.call("'+ format.substr(5) + '", ';
+ args = ", values";
+ }
+
+ return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
+ }
+
+ if (args.length) {
+ // called with xxyx.yuu:(test,test)
+ // change to ()
+ return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
+ }
+ // raw.. - :raw modifier..
+ return "'"+ sep + udef_st + name + ")"+sep+"'";
+
+ };
+ var body;
+ // branched to use + in gecko and [].join() in others
+ if(Roo.isGecko){
+ body = "tpl.compiled = function(values, parent){ with(values) { return '" +
+ tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
+ "';};};";
+ }else{
+ body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
+ body.push(tpl.body.replace(/(\r\n|\n)/g,
+ '\\n').replace(/'/g, "\\'").replace(this.re, fn));
+ body.push("'].join('');};};");
+ body = body.join('');
+ }
+
+ Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
+
+ /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
+ eval(body);
+
+ return this;
+ },
+
+ applyTemplate : function(values){
+ return this.master.compiled.call(this, values, {});
+ //var s = this.subs;
+ },
+
+ apply : function(){
+ return this.applyTemplate.apply(this, arguments);
}
-
-});
\ No newline at end of file
+
+ });
+
+Roo.XTemplate.from = function(el){
+ el = Roo.getDom(el);
+ return new Roo.XTemplate(el.value || el.innerHTML);
+};
\ No newline at end of file