4 * Copyright(c) 2006-2007, Ext JS, LLC.
6 * Originally Released Under LGPL - original licence link has changed is not relivant.
9 * <script type="text/javascript">
15 * These classes are derivatives of the similarly named classes in the YUI Library.
16 * The original license:
17 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
18 * Code licensed under the BSD License:
19 * http://developer.yahoo.net/yui/license.txt
24 var Event=Roo.EventManager;
28 * @class Roo.dd.DragDrop
29 * @extends Roo.util.Observable
30 * Defines the interface and base operation of items that that can be
31 * dragged or can be drop targets. It was designed to be extended, overriding
32 * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
33 * Up to three html elements can be associated with a DragDrop instance:
35 * <li>linked element: the element that is passed into the constructor.
36 * This is the element which defines the boundaries for interaction with
37 * other DragDrop objects.</li>
38 * <li>handle element(s): The drag operation only occurs if the element that
39 * was clicked matches a handle element. By default this is the linked
40 * element, but there are times that you will want only a portion of the
41 * linked element to initiate the drag operation, and the setHandleElId()
42 * method provides a way to define this.</li>
43 * <li>drag element: this represents the element that would be moved along
44 * with the cursor during a drag operation. By default, this is the linked
45 * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
46 * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
49 * This class should not be instantiated until the onload event to ensure that
50 * the associated elements are available.
51 * The following would define a DragDrop obj that would interact with any
52 * other DragDrop obj in the "group1" group:
54 * dd = new Roo.dd.DragDrop("div1", "group1");
56 * Since none of the event handlers have been implemented, nothing would
57 * actually happen if you were to run the code above. Normally you would
58 * override this class or one of the default implementations, but you can
59 * also override the methods you want on an instance of the class...
61 * dd.onDragDrop = function(e, id) {
62 * alert("dd was dropped on " + id);
66 * @param {String} id of the element that is linked to this instance
67 * @param {String} sGroup the group of related DragDrop objects
68 * @param {object} config an object containing configurable attributes
69 * Valid properties for DragDrop:
70 * padding, isTarget, maintainOffset, primaryButtonOnly
72 Roo.dd.DragDrop = function(id, sGroup, config) {
74 this.init(id, sGroup, config);
79 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
82 * The id of the element associated with this object. This is what we
83 * refer to as the "linked element" because the size and position of
84 * this element is used to determine when the drag and drop objects have
92 * Configuration attributes passed into the constructor
99 * The id of the element that will be dragged. By default this is same
100 * as the linked element , but could be changed to another element. Ex:
109 * the id of the element that initiates the drag operation. By default
110 * this is the linked element, but could be changed to be a child of this
111 * element. This lets us do things like only starting the drag when the
112 * header element within the linked html element is clicked.
113 * @property handleElId
120 * An associative array of HTML tags that will be ignored if clicked.
121 * @property invalidHandleTypes
122 * @type {string: string}
124 invalidHandleTypes: null,
127 * An associative array of ids for elements that will be ignored if clicked
128 * @property invalidHandleIds
129 * @type {string: string}
131 invalidHandleIds: null,
134 * An indexted array of css class names for elements that will be ignored
136 * @property invalidHandleClasses
139 invalidHandleClasses: null,
142 * The linked element's absolute X position at the time the drag was
144 * @property startPageX
151 * The linked element's absolute X position at the time the drag was
153 * @property startPageY
160 * The group defines a logical collection of DragDrop objects that are
161 * related. Instances only get events when interacting with other
162 * DragDrop object in the same group. This lets us define multiple
163 * groups using a single DragDrop subclass if we want.
165 * @type {string: string}
170 * Individual drag/drop instances can be locked. This will prevent
171 * onmousedown start drag.
182 lock: function() { this.locked = true; },
185 * Unlock this instace
188 unlock: function() { this.locked = false; },
191 * By default, all insances can be a drop target. This can be disabled by
192 * setting isTarget to false.
199 * The padding configured for this drag and drop object for calculating
200 * the drop zone intersection with this object.
207 * Cached reference to the linked element
214 * Internal typeof flag
215 * @property __ygDragDrop
221 * Set to true when horizontal contraints are applied
222 * @property constrainX
229 * Set to true when vertical contraints are applied
230 * @property constrainY
237 * The left constraint
245 * The right constraint
262 * The down constraint
270 * Maintain offsets when we resetconstraints. Set to true when you want
271 * the position of the element relative to its parent to stay the same
272 * when the page changes
274 * @property maintainOffset
277 maintainOffset: false,
280 * Array of pixel locations the element will snap to if we specified a
281 * horizontal graduation/interval. This array is generated automatically
282 * when you define a tick interval.
289 * Array of pixel locations the element will snap to if we specified a
290 * vertical graduation/interval. This array is generated automatically
291 * when you define a tick interval.
298 * By default the drag and drop instance will only respond to the primary
299 * button click (left button for a right-handed mouse). Set to true to
300 * allow drag and drop to start with any mouse click that is propogated
302 * @property primaryButtonOnly
305 primaryButtonOnly: true,
308 * The availabe property is false until the linked dom element is accessible.
309 * @property available
315 * By default, drags can only be initiated if the mousedown occurs in the
316 * region the linked element is. This is done in part to work around a
317 * bug in some browsers that mis-report the mousedown if the previous
318 * mouseup happened outside of the window. This property is set to true
319 * if outer handles are defined.
321 * @property hasOuterHandles
325 hasOuterHandles: false,
328 * Code that executes immediately before the startDrag event
329 * @method b4StartDrag
332 b4StartDrag: function(x, y) { },
335 * Abstract method called after a drag/drop object is clicked
336 * and the drag or mousedown time thresholds have beeen met.
338 * @param {int} X click location
339 * @param {int} Y click location
341 startDrag: function(x, y) { /* override this */ },
344 * Code that executes immediately before the onDrag event
348 b4Drag: function(e) { },
351 * Abstract method called during the onMouseMove event while dragging an
354 * @param {Event} e the mousemove event
356 onDrag: function(e) { /* override this */ },
359 * Abstract method called when this element fist begins hovering over
360 * another DragDrop obj
361 * @method onDragEnter
362 * @param {Event} e the mousemove event
363 * @param {String|DragDrop[]} id In POINT mode, the element
364 * id this is hovering over. In INTERSECT mode, an array of one or more
365 * dragdrop items being hovered over.
367 onDragEnter: function(e, id) { /* override this */ },
370 * Code that executes immediately before the onDragOver event
374 b4DragOver: function(e) { },
377 * Abstract method called when this element is hovering over another
380 * @param {Event} e the mousemove event
381 * @param {String|DragDrop[]} id In POINT mode, the element
382 * id this is hovering over. In INTERSECT mode, an array of dd items
383 * being hovered over.
385 onDragOver: function(e, id) { /* override this */ },
388 * Code that executes immediately before the onDragOut event
392 b4DragOut: function(e) { },
395 * Abstract method called when we are no longer hovering over an element
397 * @param {Event} e the mousemove event
398 * @param {String|DragDrop[]} id In POINT mode, the element
399 * id this was hovering over. In INTERSECT mode, an array of dd items
400 * that the mouse is no longer over.
402 onDragOut: function(e, id) { /* override this */ },
405 * Code that executes immediately before the onDragDrop event
409 b4DragDrop: function(e) { },
412 * Abstract method called when this item is dropped on another DragDrop
415 * @param {Event} e the mouseup event
416 * @param {String|DragDrop[]} id In POINT mode, the element
417 * id this was dropped on. In INTERSECT mode, an array of dd items this
420 onDragDrop: function(e, id) { /* override this */ },
423 * Abstract method called when this item is dropped on an area with no
425 * @method onInvalidDrop
426 * @param {Event} e the mouseup event
428 onInvalidDrop: function(e) { /* override this */ },
431 * Code that executes immediately before the endDrag event
435 b4EndDrag: function(e) { },
438 * Fired when we are done dragging the object
440 * @param {Event} e the mouseup event
442 endDrag: function(e) { /* override this */ },
445 * Code executed immediately before the onMouseDown event
446 * @method b4MouseDown
447 * @param {Event} e the mousedown event
450 b4MouseDown: function(e) { },
453 * Event handler that fires when a drag/drop obj gets a mousedown
454 * @method onMouseDown
455 * @param {Event} e the mousedown event
457 onMouseDown: function(e) { /* override this */ },
460 * Event handler that fires when a drag/drop obj gets a mouseup
462 * @param {Event} e the mouseup event
464 onMouseUp: function(e) { /* override this */ },
467 * Override the onAvailable method to do what is needed after the initial
468 * position was determined.
469 * @method onAvailable
471 onAvailable: function () {
475 * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
478 defaultPadding : {left:0, right:0, top:0, bottom:0},
481 * Initializes the drag drop object's constraints to restrict movement to a certain element.
485 var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
486 { dragElId: "existingProxyDiv" });
487 dd.startDrag = function(){
488 this.constrainTo("parent-id");
491 * Or you can initalize it using the {@link Roo.Element} object:
493 Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
494 startDrag : function(){
495 this.constrainTo("parent-id");
499 * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
500 * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
501 * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
502 * an object containing the sides to pad. For example: {right:10, bottom:10}
503 * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
505 constrainTo : function(constrainTo, pad, inContent){
506 if(typeof pad == "number"){
507 pad = {left: pad, right:pad, top:pad, bottom:pad};
509 pad = pad || this.defaultPadding;
510 var b = Roo.get(this.getEl()).getBox();
511 var ce = Roo.get(constrainTo);
512 var s = ce.getScroll();
514 if(cd == document.body){
515 c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
518 c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
522 var topSpace = b.y - c.y;
523 var leftSpace = b.x - c.x;
525 this.resetConstraints();
526 this.setXConstraint(leftSpace - (pad.left||0), // left
527 c.width - leftSpace - b.width - (pad.right||0) //right
529 this.setYConstraint(topSpace - (pad.top||0), //top
530 c.height - topSpace - b.height - (pad.bottom||0) //bottom
535 * Returns a reference to the linked element
537 * @return {HTMLElement} the html element
541 this._domRef = Roo.getDom(this.id);
548 * Returns a reference to the actual element to drag. By default this is
549 * the same as the html element, but it can be assigned to another
550 * element. An example of this can be found in Roo.dd.DDProxy
552 * @return {HTMLElement} the html element
554 getDragEl: function() {
555 return Roo.getDom(this.dragElId);
559 * Sets up the DragDrop object. Must be called in the constructor of any
560 * Roo.dd.DragDrop subclass
562 * @param id the id of the linked element
563 * @param {String} sGroup the group of related items
564 * @param {object} config configuration attributes
566 init: function(id, sGroup, config) {
567 this.initTarget(id, sGroup, config);
568 Event.on(this.id, "mousedown", this.handleMouseDown, this);
569 // Event.on(this.id, "selectstart", Event.preventDefault);
573 * Initializes Targeting functionality only... the object does not
574 * get a mousedown handler.
576 * @param id the id of the linked element
577 * @param {String} sGroup the group of related items
578 * @param {object} config configuration attributes
580 initTarget: function(id, sGroup, config) {
582 // configuration attributes
583 this.config = config || {};
585 // create a local reference to the drag and drop manager
586 this.DDM = Roo.dd.DDM;
587 // initialize the groups array
590 // assume that we have an element reference instead of an id if the
591 // parameter is not a string
592 if (typeof id !== "string") {
599 // add to an interaction group
600 this.addToGroup((sGroup) ? sGroup : "default");
602 // We don't want to register this as the handle with the manager
603 // so we just set the id rather than calling the setter.
604 this.handleElId = id;
606 // the linked element is the element that gets dragged by default
607 this.setDragElId(id);
609 // by default, clicked anchors will not start drag operations.
610 this.invalidHandleTypes = { A: "A" };
611 this.invalidHandleIds = {};
612 this.invalidHandleClasses = [];
616 this.handleOnAvailable();
620 * Applies the configuration parameters that were passed into the constructor.
621 * This is supposed to happen at each level through the inheritance chain. So
622 * a DDProxy implentation will execute apply config on DDProxy, DD, and
623 * DragDrop in order to get all of the parameters that are available in
625 * @method applyConfig
627 applyConfig: function() {
629 // configurable properties:
630 // padding, isTarget, maintainOffset, primaryButtonOnly
631 this.padding = this.config.padding || [0, 0, 0, 0];
632 this.isTarget = (this.config.isTarget !== false);
633 this.maintainOffset = (this.config.maintainOffset);
634 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
639 * Executed when the linked element is available
640 * @method handleOnAvailable
643 handleOnAvailable: function() {
644 this.available = true;
645 this.resetConstraints();
650 * Configures the padding for the target zone in px. Effectively expands
651 * (or reduces) the virtual object size for targeting calculations.
652 * Supports css-style shorthand; if only one parameter is passed, all sides
653 * will have that padding, and if only two are passed, the top and bottom
654 * will have the first param, the left and right the second.
656 * @param {int} iTop Top pad
657 * @param {int} iRight Right pad
658 * @param {int} iBot Bot pad
659 * @param {int} iLeft Left pad
661 setPadding: function(iTop, iRight, iBot, iLeft) {
662 // this.padding = [iLeft, iRight, iTop, iBot];
663 if (!iRight && 0 !== iRight) {
664 this.padding = [iTop, iTop, iTop, iTop];
665 } else if (!iBot && 0 !== iBot) {
666 this.padding = [iTop, iRight, iTop, iRight];
668 this.padding = [iTop, iRight, iBot, iLeft];
673 * Stores the initial placement of the linked element.
674 * @method setInitialPosition
675 * @param {int} diffX the X offset, default 0
676 * @param {int} diffY the Y offset, default 0
678 setInitPosition: function(diffX, diffY) {
679 var el = this.getEl();
681 if (!this.DDM.verifyEl(el)) {
688 var p = Dom.getXY( el );
690 this.initPageX = p[0] - dx;
691 this.initPageY = p[1] - dy;
693 this.lastPageX = p[0];
694 this.lastPageY = p[1];
697 this.setStartPosition(p);
701 * Sets the start position of the element. This is set when the obj
702 * is initialized, the reset when a drag is started.
703 * @method setStartPosition
704 * @param pos current position (from previous lookup)
707 setStartPosition: function(pos) {
708 var p = pos || Dom.getXY( this.getEl() );
709 this.deltaSetXY = null;
711 this.startPageX = p[0];
712 this.startPageY = p[1];
716 * Add this instance to a group of related drag/drop objects. All
717 * instances belong to at least one group, and can belong to as many
720 * @param sGroup {string} the name of the group
722 addToGroup: function(sGroup) {
723 this.groups[sGroup] = true;
724 this.DDM.regDragDrop(this, sGroup);
728 * Remove's this instance from the supplied interaction group
729 * @method removeFromGroup
730 * @param {string} sGroup The group to drop
732 removeFromGroup: function(sGroup) {
733 if (this.groups[sGroup]) {
734 delete this.groups[sGroup];
737 this.DDM.removeDDFromGroup(this, sGroup);
741 * Allows you to specify that an element other than the linked element
742 * will be moved with the cursor during a drag
743 * @method setDragElId
744 * @param id {string} the id of the element that will be used to initiate the drag
746 setDragElId: function(id) {
751 * Allows you to specify a child of the linked element that should be
752 * used to initiate the drag operation. An example of this would be if
753 * you have a content div with text and links. Clicking anywhere in the
754 * content area would normally start the drag operation. Use this method
755 * to specify that an element inside of the content div is the element
756 * that starts the drag operation.
757 * @method setHandleElId
758 * @param id {string} the id of the element that will be used to
761 setHandleElId: function(id) {
762 if (typeof id !== "string") {
765 this.handleElId = id;
766 this.DDM.regHandle(this.id, id);
770 * Allows you to set an element outside of the linked element as a drag
772 * @method setOuterHandleElId
773 * @param id the id of the element that will be used to initiate the drag
775 setOuterHandleElId: function(id) {
776 if (typeof id !== "string") {
779 Event.on(id, "mousedown",
780 this.handleMouseDown, this);
781 this.setHandleElId(id);
783 this.hasOuterHandles = true;
787 * Remove all drag and drop hooks for this element
791 Event.un(this.id, "mousedown",
792 this.handleMouseDown);
794 this.DDM._remove(this);
797 destroy : function(){
802 * Returns true if this instance is locked, or the drag drop mgr is locked
803 * (meaning that all drag/drop is disabled on the page.)
805 * @return {boolean} true if this obj or all drag/drop is locked, else
808 isLocked: function() {
809 return (this.DDM.isLocked() || this.locked);
813 * Fired when this object is clicked
814 * @method handleMouseDown
816 * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
819 handleMouseDown: function(e, oDD){
820 if (this.primaryButtonOnly && e.button != 0) {
824 if (this.isLocked()) {
828 this.DDM.refreshCache(this.groups);
830 var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
831 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
833 if (this.clickValidator(e)) {
835 // set the initial element position
836 this.setStartPosition();
842 this.DDM.handleMouseDown(e, this);
844 this.DDM.stopEvent(e);
852 clickValidator: function(e) {
853 var target = e.getTarget();
854 return ( this.isValidHandleChild(target) &&
855 (this.id == this.handleElId ||
856 this.DDM.handleWasClicked(target, this.id)) );
860 * Allows you to specify a tag name that should not start a drag operation
861 * when clicked. This is designed to facilitate embedding links within a
862 * drag handle that do something other than start the drag.
863 * @method addInvalidHandleType
864 * @param {string} tagName the type of element to exclude
866 addInvalidHandleType: function(tagName) {
867 var type = tagName.toUpperCase();
868 this.invalidHandleTypes[type] = type;
872 * Lets you to specify an element id for a child of a drag handle
873 * that should not initiate a drag
874 * @method addInvalidHandleId
875 * @param {string} id the element id of the element you wish to ignore
877 addInvalidHandleId: function(id) {
878 if (typeof id !== "string") {
881 this.invalidHandleIds[id] = id;
885 * Lets you specify a css class of elements that will not initiate a drag
886 * @method addInvalidHandleClass
887 * @param {string} cssClass the class of the elements you wish to ignore
889 addInvalidHandleClass: function(cssClass) {
890 this.invalidHandleClasses.push(cssClass);
894 * Unsets an excluded tag name set by addInvalidHandleType
895 * @method removeInvalidHandleType
896 * @param {string} tagName the type of element to unexclude
898 removeInvalidHandleType: function(tagName) {
899 var type = tagName.toUpperCase();
900 // this.invalidHandleTypes[type] = null;
901 delete this.invalidHandleTypes[type];
905 * Unsets an invalid handle id
906 * @method removeInvalidHandleId
907 * @param {string} id the id of the element to re-enable
909 removeInvalidHandleId: function(id) {
910 if (typeof id !== "string") {
913 delete this.invalidHandleIds[id];
917 * Unsets an invalid css class
918 * @method removeInvalidHandleClass
919 * @param {string} cssClass the class of the element(s) you wish to
922 removeInvalidHandleClass: function(cssClass) {
923 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
924 if (this.invalidHandleClasses[i] == cssClass) {
925 delete this.invalidHandleClasses[i];
931 * Checks the tag exclusion list to see if this click should be ignored
932 * @method isValidHandleChild
933 * @param {HTMLElement} node the HTMLElement to evaluate
934 * @return {boolean} true if this is a valid tag type, false if not
936 isValidHandleChild: function(node) {
939 // var n = (node.nodeName == "#text") ? node.parentNode : node;
942 nodeName = node.nodeName.toUpperCase();
944 nodeName = node.nodeName;
946 valid = valid && !this.invalidHandleTypes[nodeName];
947 valid = valid && !this.invalidHandleIds[node.id];
949 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
950 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
959 * Create the array of horizontal tick marks if an interval was specified
960 * in setXConstraint().
964 setXTicks: function(iStartX, iTickSize) {
966 this.xTickSize = iTickSize;
970 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
972 this.xTicks[this.xTicks.length] = i;
977 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
979 this.xTicks[this.xTicks.length] = i;
984 this.xTicks.sort(this.DDM.numericSort) ;
988 * Create the array of vertical tick marks if an interval was specified in
993 setYTicks: function(iStartY, iTickSize) {
995 this.yTickSize = iTickSize;
999 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
1001 this.yTicks[this.yTicks.length] = i;
1006 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
1008 this.yTicks[this.yTicks.length] = i;
1013 this.yTicks.sort(this.DDM.numericSort) ;
1017 * By default, the element can be dragged any place on the screen. Use
1018 * this method to limit the horizontal travel of the element. Pass in
1019 * 0,0 for the parameters if you want to lock the drag to the y axis.
1020 * @method setXConstraint
1021 * @param {int} iLeft the number of pixels the element can move to the left
1022 * @param {int} iRight the number of pixels the element can move to the
1024 * @param {int} iTickSize optional parameter for specifying that the
1026 * should move iTickSize pixels at a time.
1028 setXConstraint: function(iLeft, iRight, iTickSize) {
1029 this.leftConstraint = iLeft;
1030 this.rightConstraint = iRight;
1032 this.minX = this.initPageX - iLeft;
1033 this.maxX = this.initPageX + iRight;
1034 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
1036 this.constrainX = true;
1040 * Clears any constraints applied to this instance. Also clears ticks
1041 * since they can't exist independent of a constraint at this time.
1042 * @method clearConstraints
1044 clearConstraints: function() {
1045 this.constrainX = false;
1046 this.constrainY = false;
1051 * Clears any tick interval defined for this instance
1052 * @method clearTicks
1054 clearTicks: function() {
1062 * By default, the element can be dragged any place on the screen. Set
1063 * this to limit the vertical travel of the element. Pass in 0,0 for the
1064 * parameters if you want to lock the drag to the x axis.
1065 * @method setYConstraint
1066 * @param {int} iUp the number of pixels the element can move up
1067 * @param {int} iDown the number of pixels the element can move down
1068 * @param {int} iTickSize optional parameter for specifying that the
1069 * element should move iTickSize pixels at a time.
1071 setYConstraint: function(iUp, iDown, iTickSize) {
1072 this.topConstraint = iUp;
1073 this.bottomConstraint = iDown;
1075 this.minY = this.initPageY - iUp;
1076 this.maxY = this.initPageY + iDown;
1077 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
1079 this.constrainY = true;
1084 * resetConstraints must be called if you manually reposition a dd element.
1085 * @method resetConstraints
1086 * @param {boolean} maintainOffset
1088 resetConstraints: function() {
1091 // Maintain offsets if necessary
1092 if (this.initPageX || this.initPageX === 0) {
1093 // figure out how much this thing has moved
1094 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
1095 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
1097 this.setInitPosition(dx, dy);
1099 // This is the first time we have detected the element's position
1101 this.setInitPosition();
1104 if (this.constrainX) {
1105 this.setXConstraint( this.leftConstraint,
1106 this.rightConstraint,
1110 if (this.constrainY) {
1111 this.setYConstraint( this.topConstraint,
1112 this.bottomConstraint,
1118 * Normally the drag element is moved pixel by pixel, but we can specify
1119 * that it move a number of pixels at a time. This method resolves the
1120 * location when we have it set up like this.
1122 * @param {int} val where we want to place the object
1123 * @param {int[]} tickArray sorted array of valid points
1124 * @return {int} the closest tick
1127 getTick: function(val, tickArray) {
1130 // If tick interval is not defined, it is effectively 1 pixel,
1131 // so we return the value passed to us.
1133 } else if (tickArray[0] >= val) {
1134 // The value is lower than the first tick, so we return the first
1136 return tickArray[0];
1138 for (var i=0, len=tickArray.length; i<len; ++i) {
1140 if (tickArray[next] && tickArray[next] >= val) {
1141 var diff1 = val - tickArray[i];
1142 var diff2 = tickArray[next] - val;
1143 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
1147 // The value is larger than the last tick, so we return the last
1149 return tickArray[tickArray.length - 1];
1156 * @return {string} string representation of the dd obj
1158 toString: function() {
1159 return ("DragDrop " + this.id);
1167 * Ext JS Library 1.1.1
1168 * Copyright(c) 2006-2007, Ext JS, LLC.
1170 * Originally Released Under LGPL - original licence link has changed is not relivant.
1173 * <script type="text/javascript">
1178 * The drag and drop utility provides a framework for building drag and drop
1179 * applications. In addition to enabling drag and drop for specific elements,
1180 * the drag and drop elements are tracked by the manager class, and the
1181 * interactions between the various elements are tracked during the drag and
1182 * the implementing code is notified about these important moments.
1185 // Only load the library once. Rewriting the manager class would orphan
1186 // existing drag and drop instances.
1187 if (!Roo.dd.DragDropMgr) {
1190 * @class Roo.dd.DragDropMgr
1191 * DragDropMgr is a singleton that tracks the element interaction for
1192 * all DragDrop items in the window. Generally, you will not call
1193 * this class directly, but it does have helper methods that could
1194 * be useful in your DragDrop implementations.
1197 Roo.dd.DragDropMgr = function() {
1199 var Event = Roo.EventManager;
1204 * Two dimensional Array of registered DragDrop objects. The first
1205 * dimension is the DragDrop item group, the second the DragDrop
1208 * @type {string: string}
1215 * Array of element ids defined as drag handles. Used to determine
1216 * if the element that generated the mousedown event is actually the
1217 * handle and not the html element itself.
1218 * @property handleIds
1219 * @type {string: string}
1226 * the DragDrop object that is currently being dragged
1227 * @property dragCurrent
1235 * the DragDrop object(s) that are being hovered over
1236 * @property dragOvers
1244 * the X distance between the cursor and the object being dragged
1253 * the Y distance between the cursor and the object being dragged
1262 * Flag to determine if we should prevent the default behavior of the
1263 * events we define. By default this is true, but this can be set to
1264 * false if you need the default behavior (not recommended)
1265 * @property preventDefault
1269 preventDefault: true,
1272 * Flag to determine if we should stop the propagation of the events
1273 * we generate. This is true by default but you may want to set it to
1274 * false if the html element contains other features that require the
1276 * @property stopPropagation
1280 stopPropagation: true,
1283 * Internal flag that is set to true when drag and drop has been
1285 * @property initialized
1292 * All drag and drop can be disabled.
1300 * Called the first time an element is registered.
1306 this.initialized = true;
1310 * In point mode, drag and drop interaction is defined by the
1311 * location of the cursor during the drag/drop
1319 * In intersect mode, drag and drop interactio nis defined by the
1320 * overlap of two or more drag and drop objects.
1321 * @property INTERSECT
1328 * The current drag and drop mode. Default: POINT
1336 * Runs method on all drag and drop objects
1337 * @method _execOnAll
1341 _execOnAll: function(sMethod, args) {
1342 for (var i in this.ids) {
1343 for (var j in this.ids[i]) {
1344 var oDD = this.ids[i][j];
1345 if (! this.isTypeOfDD(oDD)) {
1348 oDD[sMethod].apply(oDD, args);
1354 * Drag and drop initialization. Sets up the global event handlers
1359 _onLoad: function() {
1364 Event.on(document, "mouseup", this.handleMouseUp, this, true);
1365 Event.on(document, "mousemove", this.handleMouseMove, this, true);
1366 Event.on(window, "unload", this._onUnload, this, true);
1367 Event.on(window, "resize", this._onResize, this, true);
1368 // Event.on(window, "mouseout", this._test);
1373 * Reset constraints on all drag and drop objs
1378 _onResize: function(e) {
1379 this._execOnAll("resetConstraints", []);
1383 * Lock all drag and drop functionality
1387 lock: function() { this.locked = true; },
1390 * Unlock all drag and drop functionality
1394 unlock: function() { this.locked = false; },
1397 * Is drag and drop locked?
1399 * @return {boolean} True if drag and drop is locked, false otherwise.
1402 isLocked: function() { return this.locked; },
1405 * Location cache that is set for all drag drop objects when a drag is
1406 * initiated, cleared when the drag is finished.
1407 * @property locationCache
1414 * Set useCache to false if you want to force object the lookup of each
1415 * drag and drop linked element constantly during a drag.
1416 * @property useCache
1423 * The number of pixels that the mouse needs to move after the
1424 * mousedown before the drag is initiated. Default=3;
1425 * @property clickPixelThresh
1429 clickPixelThresh: 3,
1432 * The number of milliseconds after the mousedown event to initiate the
1433 * drag if we don't get a mouseup event. Default=1000
1434 * @property clickTimeThresh
1438 clickTimeThresh: 350,
1441 * Flag that indicates that either the drag pixel threshold or the
1442 * mousdown time threshold has been met
1443 * @property dragThreshMet
1448 dragThreshMet: false,
1451 * Timeout used for the click time threshold
1452 * @property clickTimeout
1460 * The X position of the mousedown event stored for later use when a
1461 * drag threshold is met.
1470 * The Y position of the mousedown event stored for later use when a
1471 * drag threshold is met.
1480 * Each DragDrop instance must be registered with the DragDropMgr.
1481 * This is executed in DragDrop.init()
1482 * @method regDragDrop
1483 * @param {DragDrop} oDD the DragDrop object to register
1484 * @param {String} sGroup the name of the group this element belongs to
1487 regDragDrop: function(oDD, sGroup) {
1488 if (!this.initialized) { this.init(); }
1490 if (!this.ids[sGroup]) {
1491 this.ids[sGroup] = {};
1493 this.ids[sGroup][oDD.id] = oDD;
1497 * Removes the supplied dd instance from the supplied group. Executed
1498 * by DragDrop.removeFromGroup, so don't call this function directly.
1499 * @method removeDDFromGroup
1503 removeDDFromGroup: function(oDD, sGroup) {
1504 if (!this.ids[sGroup]) {
1505 this.ids[sGroup] = {};
1508 var obj = this.ids[sGroup];
1509 if (obj && obj[oDD.id]) {
1515 * Unregisters a drag and drop item. This is executed in
1516 * DragDrop.unreg, use that method instead of calling this directly.
1521 _remove: function(oDD) {
1522 for (var g in oDD.groups) {
1523 if (g && this.ids[g][oDD.id]) {
1524 delete this.ids[g][oDD.id];
1527 delete this.handleIds[oDD.id];
1531 * Each DragDrop handle element must be registered. This is done
1532 * automatically when executing DragDrop.setHandleElId()
1534 * @param {String} sDDId the DragDrop id this element is a handle for
1535 * @param {String} sHandleId the id of the element that is the drag
1539 regHandle: function(sDDId, sHandleId) {
1540 if (!this.handleIds[sDDId]) {
1541 this.handleIds[sDDId] = {};
1543 this.handleIds[sDDId][sHandleId] = sHandleId;
1547 * Utility function to determine if a given element has been
1548 * registered as a drag drop item.
1549 * @method isDragDrop
1550 * @param {String} id the element id to check
1551 * @return {boolean} true if this element is a DragDrop item,
1555 isDragDrop: function(id) {
1556 return ( this.getDDById(id) ) ? true : false;
1560 * Returns the drag and drop instances that are in all groups the
1561 * passed in instance belongs to.
1562 * @method getRelated
1563 * @param {DragDrop} p_oDD the obj to get related data for
1564 * @param {boolean} bTargetsOnly if true, only return targetable objs
1565 * @return {DragDrop[]} the related instances
1568 getRelated: function(p_oDD, bTargetsOnly) {
1570 for (var i in p_oDD.groups) {
1571 for (j in this.ids[i]) {
1572 var dd = this.ids[i][j];
1573 if (! this.isTypeOfDD(dd)) {
1576 if (!bTargetsOnly || dd.isTarget) {
1577 oDDs[oDDs.length] = dd;
1586 * Returns true if the specified dd target is a legal target for
1587 * the specifice drag obj
1588 * @method isLegalTarget
1589 * @param {DragDrop} the drag obj
1590 * @param {DragDrop} the target
1591 * @return {boolean} true if the target is a legal target for the
1595 isLegalTarget: function (oDD, oTargetDD) {
1596 var targets = this.getRelated(oDD, true);
1597 for (var i=0, len=targets.length;i<len;++i) {
1598 if (targets[i].id == oTargetDD.id) {
1607 * My goal is to be able to transparently determine if an object is
1608 * typeof DragDrop, and the exact subclass of DragDrop. typeof
1609 * returns "object", oDD.constructor.toString() always returns
1610 * "DragDrop" and not the name of the subclass. So for now it just
1611 * evaluates a well-known variable in DragDrop.
1612 * @method isTypeOfDD
1613 * @param {Object} the object to evaluate
1614 * @return {boolean} true if typeof oDD = DragDrop
1617 isTypeOfDD: function (oDD) {
1618 return (oDD && oDD.__ygDragDrop);
1622 * Utility function to determine if a given element has been
1623 * registered as a drag drop handle for the given Drag Drop object.
1625 * @param {String} id the element id to check
1626 * @return {boolean} true if this element is a DragDrop handle, false
1630 isHandle: function(sDDId, sHandleId) {
1631 return ( this.handleIds[sDDId] &&
1632 this.handleIds[sDDId][sHandleId] );
1636 * Returns the DragDrop instance for a given id
1638 * @param {String} id the id of the DragDrop object
1639 * @return {DragDrop} the drag drop object, null if it is not found
1642 getDDById: function(id) {
1643 for (var i in this.ids) {
1644 if (this.ids[i][id]) {
1645 return this.ids[i][id];
1652 * Fired after a registered DragDrop object gets the mousedown event.
1653 * Sets up the events required to track the object being dragged
1654 * @method handleMouseDown
1655 * @param {Event} e the event
1656 * @param oDD the DragDrop object being dragged
1660 handleMouseDown: function(e, oDD) {
1662 Roo.QuickTips.disable();
1664 this.currentTarget = e.getTarget();
1666 this.dragCurrent = oDD;
1668 var el = oDD.getEl();
1670 // track start position
1671 this.startX = e.getPageX();
1672 this.startY = e.getPageY();
1674 this.deltaX = this.startX - el.offsetLeft;
1675 this.deltaY = this.startY - el.offsetTop;
1677 this.dragThreshMet = false;
1679 this.clickTimeout = setTimeout(
1681 var DDM = Roo.dd.DDM;
1682 DDM.startDrag(DDM.startX, DDM.startY);
1684 this.clickTimeThresh );
1688 * Fired when either the drag pixel threshol or the mousedown hold
1689 * time threshold has been met.
1691 * @param x {int} the X position of the original mousedown
1692 * @param y {int} the Y position of the original mousedown
1695 startDrag: function(x, y) {
1696 clearTimeout(this.clickTimeout);
1697 if (this.dragCurrent) {
1698 this.dragCurrent.b4StartDrag(x, y);
1699 this.dragCurrent.startDrag(x, y);
1701 this.dragThreshMet = true;
1705 * Internal function to handle the mouseup event. Will be invoked
1706 * from the context of the document.
1707 * @method handleMouseUp
1708 * @param {Event} e the event
1712 handleMouseUp: function(e) {
1715 Roo.QuickTips.enable();
1717 if (! this.dragCurrent) {
1721 clearTimeout(this.clickTimeout);
1723 if (this.dragThreshMet) {
1724 this.fireEvents(e, true);
1734 * Utility to stop event propagation and event default, if these
1735 * features are turned on.
1737 * @param {Event} e the event as returned by this.getEvent()
1740 stopEvent: function(e){
1741 if(this.stopPropagation) {
1742 e.stopPropagation();
1745 if (this.preventDefault) {
1751 * Internal function to clean up event handlers after the drag
1752 * operation is complete
1754 * @param {Event} e the event
1758 stopDrag: function(e) {
1759 // Fire the drag end event for the item that was dragged
1760 if (this.dragCurrent) {
1761 if (this.dragThreshMet) {
1762 this.dragCurrent.b4EndDrag(e);
1763 this.dragCurrent.endDrag(e);
1766 this.dragCurrent.onMouseUp(e);
1769 this.dragCurrent = null;
1770 this.dragOvers = {};
1774 * Internal function to handle the mousemove event. Will be invoked
1775 * from the context of the html element.
1777 * @TODO figure out what we can do about mouse events lost when the
1778 * user drags objects beyond the window boundary. Currently we can
1779 * detect this in internet explorer by verifying that the mouse is
1780 * down during the mousemove event. Firefox doesn't give us the
1781 * button state on the mousemove event.
1782 * @method handleMouseMove
1783 * @param {Event} e the event
1787 handleMouseMove: function(e) {
1788 if (! this.dragCurrent) {
1792 // var button = e.which || e.button;
1794 // check for IE mouseup outside of page boundary
1795 if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
1797 return this.handleMouseUp(e);
1800 if (!this.dragThreshMet) {
1801 var diffX = Math.abs(this.startX - e.getPageX());
1802 var diffY = Math.abs(this.startY - e.getPageY());
1803 if (diffX > this.clickPixelThresh ||
1804 diffY > this.clickPixelThresh) {
1805 this.startDrag(this.startX, this.startY);
1809 if (this.dragThreshMet) {
1810 this.dragCurrent.b4Drag(e);
1811 this.dragCurrent.onDrag(e);
1812 if(!this.dragCurrent.moveOnly){
1813 this.fireEvents(e, false);
1823 * Iterates over all of the DragDrop elements to find ones we are
1824 * hovering over or dropping on
1825 * @method fireEvents
1826 * @param {Event} e the event
1827 * @param {boolean} isDrop is this a drop op or a mouseover op?
1831 fireEvents: function(e, isDrop) {
1832 var dc = this.dragCurrent;
1834 // If the user did the mouse up outside of the window, we could
1835 // get here even though we have ended the drag.
1836 if (!dc || dc.isLocked()) {
1840 var pt = e.getPoint();
1842 // cache the previous dragOver array
1850 // Check to see if the object(s) we were hovering over is no longer
1851 // being hovered over so we can fire the onDragOut event
1852 for (var i in this.dragOvers) {
1854 var ddo = this.dragOvers[i];
1856 if (! this.isTypeOfDD(ddo)) {
1860 if (! this.isOverTarget(pt, ddo, this.mode)) {
1861 outEvts.push( ddo );
1865 delete this.dragOvers[i];
1868 for (var sGroup in dc.groups) {
1870 if ("string" != typeof sGroup) {
1874 for (i in this.ids[sGroup]) {
1875 var oDD = this.ids[sGroup][i];
1876 if (! this.isTypeOfDD(oDD)) {
1880 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
1881 if (this.isOverTarget(pt, oDD, this.mode)) {
1882 // look for drop interactions
1884 dropEvts.push( oDD );
1885 // look for drag enter and drag over interactions
1888 // initial drag over: dragEnter fires
1889 if (!oldOvers[oDD.id]) {
1890 enterEvts.push( oDD );
1891 // subsequent drag overs: dragOver fires
1893 overEvts.push( oDD );
1896 this.dragOvers[oDD.id] = oDD;
1904 if (outEvts.length) {
1905 dc.b4DragOut(e, outEvts);
1906 dc.onDragOut(e, outEvts);
1909 if (enterEvts.length) {
1910 dc.onDragEnter(e, enterEvts);
1913 if (overEvts.length) {
1914 dc.b4DragOver(e, overEvts);
1915 dc.onDragOver(e, overEvts);
1918 if (dropEvts.length) {
1919 dc.b4DragDrop(e, dropEvts);
1920 dc.onDragDrop(e, dropEvts);
1924 // fire dragout events
1926 for (i=0, len=outEvts.length; i<len; ++i) {
1927 dc.b4DragOut(e, outEvts[i].id);
1928 dc.onDragOut(e, outEvts[i].id);
1931 // fire enter events
1932 for (i=0,len=enterEvts.length; i<len; ++i) {
1933 // dc.b4DragEnter(e, oDD.id);
1934 dc.onDragEnter(e, enterEvts[i].id);
1938 for (i=0,len=overEvts.length; i<len; ++i) {
1939 dc.b4DragOver(e, overEvts[i].id);
1940 dc.onDragOver(e, overEvts[i].id);
1944 for (i=0, len=dropEvts.length; i<len; ++i) {
1945 dc.b4DragDrop(e, dropEvts[i].id);
1946 dc.onDragDrop(e, dropEvts[i].id);
1951 // notify about a drop that did not find a target
1952 if (isDrop && !dropEvts.length) {
1953 dc.onInvalidDrop(e);
1959 * Helper function for getting the best match from the list of drag
1960 * and drop objects returned by the drag and drop events when we are
1961 * in INTERSECT mode. It returns either the first object that the
1962 * cursor is over, or the object that has the greatest overlap with
1963 * the dragged element.
1964 * @method getBestMatch
1965 * @param {DragDrop[]} dds The array of drag and drop objects
1967 * @return {DragDrop} The best single match
1970 getBestMatch: function(dds) {
1972 // Return null if the input is not what we expect
1973 //if (!dds || !dds.length || dds.length == 0) {
1975 // If there is only one item, it wins
1976 //} else if (dds.length == 1) {
1978 var len = dds.length;
1983 // Loop through the targeted items
1984 for (var i=0; i<len; ++i) {
1986 // If the cursor is over the object, it wins. If the
1987 // cursor is over multiple matches, the first one we come
1989 if (dd.cursorIsOver) {
1992 // Otherwise the object with the most overlap wins
1995 winner.overlap.getArea() < dd.overlap.getArea()) {
2006 * Refreshes the cache of the top-left and bottom-right points of the
2007 * drag and drop objects in the specified group(s). This is in the
2008 * format that is stored in the drag and drop instance, so typical
2011 * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
2015 * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
2017 * @TODO this really should be an indexed array. Alternatively this
2018 * method could accept both.
2019 * @method refreshCache
2020 * @param {Object} groups an associative array of groups to refresh
2023 refreshCache: function(groups) {
2024 for (var sGroup in groups) {
2025 if ("string" != typeof sGroup) {
2028 for (var i in this.ids[sGroup]) {
2029 var oDD = this.ids[sGroup][i];
2031 if (this.isTypeOfDD(oDD)) {
2032 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
2033 var loc = this.getLocation(oDD);
2035 this.locationCache[oDD.id] = loc;
2037 delete this.locationCache[oDD.id];
2038 // this will unregister the drag and drop object if
2039 // the element is not in a usable state
2048 * This checks to make sure an element exists and is in the DOM. The
2049 * main purpose is to handle cases where innerHTML is used to remove
2050 * drag and drop objects from the DOM. IE provides an 'unspecified
2051 * error' when trying to access the offsetParent of such an element
2053 * @param {HTMLElement} el the element to check
2054 * @return {boolean} true if the element looks usable
2057 verifyEl: function(el) {
2062 parent = el.offsetParent;
2065 parent = el.offsetParent;
2076 * Returns a Region object containing the drag and drop element's position
2077 * and size, including the padding configured for it
2078 * @method getLocation
2079 * @param {DragDrop} oDD the drag and drop object to get the
2081 * @return {Roo.lib.Region} a Region object representing the total area
2082 * the element occupies, including any padding
2083 * the instance is configured for.
2086 getLocation: function(oDD) {
2087 if (! this.isTypeOfDD(oDD)) {
2091 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
2094 pos= Roo.lib.Dom.getXY(el);
2102 x2 = x1 + el.offsetWidth;
2104 y2 = y1 + el.offsetHeight;
2106 t = y1 - oDD.padding[0];
2107 r = x2 + oDD.padding[1];
2108 b = y2 + oDD.padding[2];
2109 l = x1 - oDD.padding[3];
2111 return new Roo.lib.Region( t, r, b, l );
2115 * Checks the cursor location to see if it over the target
2116 * @method isOverTarget
2117 * @param {Roo.lib.Point} pt The point to evaluate
2118 * @param {DragDrop} oTarget the DragDrop object we are inspecting
2119 * @return {boolean} true if the mouse is over the target
2123 isOverTarget: function(pt, oTarget, intersect) {
2124 // use cache if available
2125 var loc = this.locationCache[oTarget.id];
2126 if (!loc || !this.useCache) {
2127 loc = this.getLocation(oTarget);
2128 this.locationCache[oTarget.id] = loc;
2136 oTarget.cursorIsOver = loc.contains( pt );
2138 // DragDrop is using this as a sanity check for the initial mousedown
2139 // in this case we are done. In POINT mode, if the drag obj has no
2140 // contraints, we are also done. Otherwise we need to evaluate the
2141 // location of the target as related to the actual location of the
2143 var dc = this.dragCurrent;
2144 if (!dc || !dc.getTargetCoord ||
2145 (!intersect && !dc.constrainX && !dc.constrainY)) {
2146 return oTarget.cursorIsOver;
2149 oTarget.overlap = null;
2151 // Get the current location of the drag element, this is the
2152 // location of the mouse event less the delta that represents
2153 // where the original mousedown happened on the element. We
2154 // need to consider constraints and ticks as well.
2155 var pos = dc.getTargetCoord(pt.x, pt.y);
2157 var el = dc.getDragEl();
2158 var curRegion = new Roo.lib.Region( pos.y,
2159 pos.x + el.offsetWidth,
2160 pos.y + el.offsetHeight,
2163 var overlap = curRegion.intersect(loc);
2166 oTarget.overlap = overlap;
2167 return (intersect) ? true : oTarget.cursorIsOver;
2174 * unload event handler
2179 _onUnload: function(e, me) {
2180 Roo.dd.DragDropMgr.unregAll();
2184 * Cleans up the drag and drop events and objects.
2189 unregAll: function() {
2191 if (this.dragCurrent) {
2193 this.dragCurrent = null;
2196 this._execOnAll("unreg", []);
2198 for (i in this.elementCache) {
2199 delete this.elementCache[i];
2202 this.elementCache = {};
2207 * A cache of DOM elements
2208 * @property elementCache
2215 * Get the wrapper for the DOM element specified
2216 * @method getElWrapper
2217 * @param {String} id the id of the element to get
2218 * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
2220 * @deprecated This wrapper isn't that useful
2223 getElWrapper: function(id) {
2224 var oWrapper = this.elementCache[id];
2225 if (!oWrapper || !oWrapper.el) {
2226 oWrapper = this.elementCache[id] =
2227 new this.ElementWrapper(Roo.getDom(id));
2233 * Returns the actual DOM element
2234 * @method getElement
2235 * @param {String} id the id of the elment to get
2236 * @return {Object} The element
2237 * @deprecated use Roo.getDom instead
2240 getElement: function(id) {
2241 return Roo.getDom(id);
2245 * Returns the style property for the DOM element (i.e.,
2246 * document.getElById(id).style)
2248 * @param {String} id the id of the elment to get
2249 * @return {Object} The style property of the element
2250 * @deprecated use Roo.getDom instead
2253 getCss: function(id) {
2254 var el = Roo.getDom(id);
2255 return (el) ? el.style : null;
2259 * Inner class for cached elements
2260 * @class DragDropMgr.ElementWrapper
2265 ElementWrapper: function(el) {
2270 this.el = el || null;
2275 this.id = this.el && el.id;
2277 * A reference to the style property
2280 this.css = this.el && el.style;
2284 * Returns the X position of an html element
2286 * @param el the element for which to get the position
2287 * @return {int} the X coordinate
2289 * @deprecated use Roo.lib.Dom.getX instead
2292 getPosX: function(el) {
2293 return Roo.lib.Dom.getX(el);
2297 * Returns the Y position of an html element
2299 * @param el the element for which to get the position
2300 * @return {int} the Y coordinate
2301 * @deprecated use Roo.lib.Dom.getY instead
2304 getPosY: function(el) {
2305 return Roo.lib.Dom.getY(el);
2309 * Swap two nodes. In IE, we use the native method, for others we
2310 * emulate the IE behavior
2312 * @param n1 the first node to swap
2313 * @param n2 the other node to swap
2316 swapNode: function(n1, n2) {
2320 var p = n2.parentNode;
2321 var s = n2.nextSibling;
2324 p.insertBefore(n1, n2);
2325 } else if (n2 == n1.nextSibling) {
2326 p.insertBefore(n2, n1);
2328 n1.parentNode.replaceChild(n2, n1);
2329 p.insertBefore(n1, s);
2335 * Returns the current scroll position
2340 getScroll: function () {
2341 var t, l, dde=document.documentElement, db=document.body;
2342 if (dde && (dde.scrollTop || dde.scrollLeft)) {
2351 return { top: t, left: l };
2355 * Returns the specified element style property
2357 * @param {HTMLElement} el the element
2358 * @param {string} styleProp the style property
2359 * @return {string} The value of the style property
2360 * @deprecated use Roo.lib.Dom.getStyle
2363 getStyle: function(el, styleProp) {
2364 return Roo.fly(el).getStyle(styleProp);
2368 * Gets the scrollTop
2369 * @method getScrollTop
2370 * @return {int} the document's scrollTop
2373 getScrollTop: function () { return this.getScroll().top; },
2376 * Gets the scrollLeft
2377 * @method getScrollLeft
2378 * @return {int} the document's scrollTop
2381 getScrollLeft: function () { return this.getScroll().left; },
2384 * Sets the x/y position of an element to the location of the
2387 * @param {HTMLElement} moveEl The element to move
2388 * @param {HTMLElement} targetEl The position reference element
2391 moveToEl: function (moveEl, targetEl) {
2392 var aCoord = Roo.lib.Dom.getXY(targetEl);
2393 Roo.lib.Dom.setXY(moveEl, aCoord);
2397 * Numeric array sort function
2398 * @method numericSort
2401 numericSort: function(a, b) { return (a - b); },
2405 * @property _timeoutCount
2412 * Trying to make the load order less important. Without this we get
2413 * an error if this file is loaded before the Event Utility.
2414 * @method _addListeners
2418 _addListeners: function() {
2419 var DDM = Roo.dd.DDM;
2420 if ( Roo.lib.Event && document ) {
2423 if (DDM._timeoutCount > 2000) {
2425 setTimeout(DDM._addListeners, 10);
2426 if (document && document.body) {
2427 DDM._timeoutCount += 1;
2434 * Recursively searches the immediate parent and all child nodes for
2435 * the handle element in order to determine wheter or not it was
2437 * @method handleWasClicked
2438 * @param node the html element to inspect
2441 handleWasClicked: function(node, id) {
2442 if (this.isHandle(id, node.id)) {
2445 // check to see if this is a text node child of the one we want
2446 var p = node.parentNode;
2449 if (this.isHandle(id, p.id)) {
2464 // shorter alias, save a few bytes
2465 Roo.dd.DDM = Roo.dd.DragDropMgr;
2466 Roo.dd.DDM._addListeners();
2470 * Ext JS Library 1.1.1
2471 * Copyright(c) 2006-2007, Ext JS, LLC.
2473 * Originally Released Under LGPL - original licence link has changed is not relivant.
2476 * <script type="text/javascript">
2481 * A DragDrop implementation where the linked element follows the
2482 * mouse cursor during a drag.
2483 * @extends Roo.dd.DragDrop
2485 * @param {String} id the id of the linked element
2486 * @param {String} sGroup the group of related DragDrop items
2487 * @param {object} config an object containing configurable attributes
2488 * Valid properties for DD:
2491 Roo.dd.DD = function(id, sGroup, config) {
2493 this.init(id, sGroup, config);
2497 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
2500 * When set to true, the utility automatically tries to scroll the browser
2501 * window wehn a drag and drop element is dragged near the viewport boundary.
2509 * Sets the pointer offset to the distance between the linked element's top
2510 * left corner and the location the element was clicked
2511 * @method autoOffset
2512 * @param {int} iPageX the X coordinate of the click
2513 * @param {int} iPageY the Y coordinate of the click
2515 autoOffset: function(iPageX, iPageY) {
2516 var x = iPageX - this.startPageX;
2517 var y = iPageY - this.startPageY;
2518 this.setDelta(x, y);
2522 * Sets the pointer offset. You can call this directly to force the
2523 * offset to be in a particular location (e.g., pass in 0,0 to set it
2524 * to the center of the object)
2526 * @param {int} iDeltaX the distance from the left
2527 * @param {int} iDeltaY the distance from the top
2529 setDelta: function(iDeltaX, iDeltaY) {
2530 this.deltaX = iDeltaX;
2531 this.deltaY = iDeltaY;
2535 * Sets the drag element to the location of the mousedown or click event,
2536 * maintaining the cursor location relative to the location on the element
2537 * that was clicked. Override this if you want to place the element in a
2538 * location other than where the cursor is.
2539 * @method setDragElPos
2540 * @param {int} iPageX the X coordinate of the mousedown or drag event
2541 * @param {int} iPageY the Y coordinate of the mousedown or drag event
2543 setDragElPos: function(iPageX, iPageY) {
2544 // the first time we do this, we are going to check to make sure
2545 // the element has css positioning
2547 var el = this.getDragEl();
2548 this.alignElWithMouse(el, iPageX, iPageY);
2552 * Sets the element to the location of the mousedown or click event,
2553 * maintaining the cursor location relative to the location on the element
2554 * that was clicked. Override this if you want to place the element in a
2555 * location other than where the cursor is.
2556 * @method alignElWithMouse
2557 * @param {HTMLElement} el the element to move
2558 * @param {int} iPageX the X coordinate of the mousedown or drag event
2559 * @param {int} iPageY the Y coordinate of the mousedown or drag event
2561 alignElWithMouse: function(el, iPageX, iPageY) {
2562 var oCoord = this.getTargetCoord(iPageX, iPageY);
2563 var fly = el.dom ? el : Roo.fly(el);
2564 if (!this.deltaSetXY) {
2565 var aCoord = [oCoord.x, oCoord.y];
2567 var newLeft = fly.getLeft(true);
2568 var newTop = fly.getTop(true);
2569 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
2571 fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
2574 this.cachePosition(oCoord.x, oCoord.y);
2575 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
2580 * Saves the most recent position so that we can reset the constraints and
2581 * tick marks on-demand. We need to know this so that we can calculate the
2582 * number of pixels the element is offset from its original position.
2583 * @method cachePosition
2584 * @param iPageX the current x position (optional, this just makes it so we
2585 * don't have to look it up again)
2586 * @param iPageY the current y position (optional, this just makes it so we
2587 * don't have to look it up again)
2589 cachePosition: function(iPageX, iPageY) {
2591 this.lastPageX = iPageX;
2592 this.lastPageY = iPageY;
2594 var aCoord = Roo.lib.Dom.getXY(this.getEl());
2595 this.lastPageX = aCoord[0];
2596 this.lastPageY = aCoord[1];
2601 * Auto-scroll the window if the dragged object has been moved beyond the
2602 * visible window boundary.
2603 * @method autoScroll
2604 * @param {int} x the drag element's x position
2605 * @param {int} y the drag element's y position
2606 * @param {int} h the height of the drag element
2607 * @param {int} w the width of the drag element
2610 autoScroll: function(x, y, h, w) {
2613 // The client height
2614 var clientH = Roo.lib.Dom.getViewWidth();
2617 var clientW = Roo.lib.Dom.getViewHeight();
2619 // The amt scrolled down
2620 var st = this.DDM.getScrollTop();
2622 // The amt scrolled right
2623 var sl = this.DDM.getScrollLeft();
2625 // Location of the bottom of the element
2628 // Location of the right of the element
2631 // The distance from the cursor to the bottom of the visible area,
2632 // adjusted so that we don't scroll if the cursor is beyond the
2633 // element drag constraints
2634 var toBot = (clientH + st - y - this.deltaY);
2636 // The distance from the cursor to the right of the visible area
2637 var toRight = (clientW + sl - x - this.deltaX);
2640 // How close to the edge the cursor must be before we scroll
2641 // var thresh = (document.all) ? 100 : 40;
2644 // How many pixels to scroll per autoscroll op. This helps to reduce
2645 // clunky scrolling. IE is more sensitive about this ... it needs this
2646 // value to be higher.
2647 var scrAmt = (document.all) ? 80 : 30;
2649 // Scroll down if we are near the bottom of the visible page and the
2650 // obj extends below the crease
2651 if ( bot > clientH && toBot < thresh ) {
2652 window.scrollTo(sl, st + scrAmt);
2655 // Scroll up if the window is scrolled down and the top of the object
2656 // goes above the top border
2657 if ( y < st && st > 0 && y - st < thresh ) {
2658 window.scrollTo(sl, st - scrAmt);
2661 // Scroll right if the obj is beyond the right border and the cursor is
2663 if ( right > clientW && toRight < thresh ) {
2664 window.scrollTo(sl + scrAmt, st);
2667 // Scroll left if the window has been scrolled to the right and the obj
2668 // extends past the left border
2669 if ( x < sl && sl > 0 && x - sl < thresh ) {
2670 window.scrollTo(sl - scrAmt, st);
2676 * Finds the location the element should be placed if we want to move
2677 * it to where the mouse location less the click offset would place us.
2678 * @method getTargetCoord
2679 * @param {int} iPageX the X coordinate of the click
2680 * @param {int} iPageY the Y coordinate of the click
2681 * @return an object that contains the coordinates (Object.x and Object.y)
2684 getTargetCoord: function(iPageX, iPageY) {
2687 var x = iPageX - this.deltaX;
2688 var y = iPageY - this.deltaY;
2690 if (this.constrainX) {
2691 if (x < this.minX) { x = this.minX; }
2692 if (x > this.maxX) { x = this.maxX; }
2695 if (this.constrainY) {
2696 if (y < this.minY) { y = this.minY; }
2697 if (y > this.maxY) { y = this.maxY; }
2700 x = this.getTick(x, this.xTicks);
2701 y = this.getTick(y, this.yTicks);
2708 * Sets up config options specific to this class. Overrides
2709 * Roo.dd.DragDrop, but all versions of this method through the
2710 * inheritance chain are called
2712 applyConfig: function() {
2713 Roo.dd.DD.superclass.applyConfig.call(this);
2714 this.scroll = (this.config.scroll !== false);
2718 * Event that fires prior to the onMouseDown event. Overrides
2721 b4MouseDown: function(e) {
2722 // this.resetConstraints();
2723 this.autoOffset(e.getPageX(),
2728 * Event that fires prior to the onDrag event. Overrides
2731 b4Drag: function(e) {
2732 this.setDragElPos(e.getPageX(),
2736 toString: function() {
2737 return ("DD " + this.id);
2740 //////////////////////////////////////////////////////////////////////////
2741 // Debugging ygDragDrop events that can be overridden
2742 //////////////////////////////////////////////////////////////////////////
2744 startDrag: function(x, y) {
2747 onDrag: function(e) {
2750 onDragEnter: function(e, id) {
2753 onDragOver: function(e, id) {
2756 onDragOut: function(e, id) {
2759 onDragDrop: function(e, id) {
2762 endDrag: function(e) {
2769 * Ext JS Library 1.1.1
2770 * Copyright(c) 2006-2007, Ext JS, LLC.
2772 * Originally Released Under LGPL - original licence link has changed is not relivant.
2775 * <script type="text/javascript">
2779 * @class Roo.dd.DDProxy
2780 * A DragDrop implementation that inserts an empty, bordered div into
2781 * the document that follows the cursor during drag operations. At the time of
2782 * the click, the frame div is resized to the dimensions of the linked html
2783 * element, and moved to the exact location of the linked element.
2785 * References to the "frame" element refer to the single proxy element that
2786 * was created to be dragged in place of all DDProxy elements on the
2789 * @extends Roo.dd.DD
2791 * @param {String} id the id of the linked html element
2792 * @param {String} sGroup the group of related DragDrop objects
2793 * @param {object} config an object containing configurable attributes
2794 * Valid properties for DDProxy in addition to those in DragDrop:
2795 * resizeFrame, centerFrame, dragElId
2797 Roo.dd.DDProxy = function(id, sGroup, config) {
2799 this.init(id, sGroup, config);
2805 * The default drag frame div id
2806 * @property Roo.dd.DDProxy.dragElId
2810 Roo.dd.DDProxy.dragElId = "ygddfdiv";
2812 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
2815 * By default we resize the drag frame to be the same size as the element
2816 * we want to drag (this is to get the frame effect). We can turn it off
2817 * if we want a different behavior.
2818 * @property resizeFrame
2824 * By default the frame is positioned exactly where the drag element is, so
2825 * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
2826 * you do not have constraints on the obj is to have the drag frame centered
2827 * around the cursor. Set centerFrame to true for this effect.
2828 * @property centerFrame
2834 * Creates the proxy element if it does not yet exist
2835 * @method createFrame
2837 createFrame: function() {
2839 var body = document.body;
2841 if (!body || !body.firstChild) {
2842 setTimeout( function() { self.createFrame(); }, 50 );
2846 var div = this.getDragEl();
2849 div = document.createElement("div");
2850 div.id = this.dragElId;
2853 s.position = "absolute";
2854 s.visibility = "hidden";
2856 s.border = "2px solid #aaa";
2859 // appendChild can blow up IE if invoked prior to the window load event
2860 // while rendering a table. It is possible there are other scenarios
2861 // that would cause this to happen as well.
2862 body.insertBefore(div, body.firstChild);
2867 * Initialization for the drag frame element. Must be called in the
2868 * constructor of all subclasses
2871 initFrame: function() {
2875 applyConfig: function() {
2876 Roo.dd.DDProxy.superclass.applyConfig.call(this);
2878 this.resizeFrame = (this.config.resizeFrame !== false);
2879 this.centerFrame = (this.config.centerFrame);
2880 this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
2884 * Resizes the drag frame to the dimensions of the clicked object, positions
2885 * it over the object, and finally displays it
2887 * @param {int} iPageX X click position
2888 * @param {int} iPageY Y click position
2891 showFrame: function(iPageX, iPageY) {
2892 var el = this.getEl();
2893 var dragEl = this.getDragEl();
2894 var s = dragEl.style;
2896 this._resizeProxy();
2898 if (this.centerFrame) {
2899 this.setDelta( Math.round(parseInt(s.width, 10)/2),
2900 Math.round(parseInt(s.height, 10)/2) );
2903 this.setDragElPos(iPageX, iPageY);
2905 Roo.fly(dragEl).show();
2909 * The proxy is automatically resized to the dimensions of the linked
2910 * element when a drag is initiated, unless resizeFrame is set to false
2911 * @method _resizeProxy
2914 _resizeProxy: function() {
2915 if (this.resizeFrame) {
2916 var el = this.getEl();
2917 Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
2921 // overrides Roo.dd.DragDrop
2922 b4MouseDown: function(e) {
2923 var x = e.getPageX();
2924 var y = e.getPageY();
2925 this.autoOffset(x, y);
2926 this.setDragElPos(x, y);
2929 // overrides Roo.dd.DragDrop
2930 b4StartDrag: function(x, y) {
2931 // show the drag frame
2932 this.showFrame(x, y);
2935 // overrides Roo.dd.DragDrop
2936 b4EndDrag: function(e) {
2937 Roo.fly(this.getDragEl()).hide();
2940 // overrides Roo.dd.DragDrop
2941 // By default we try to move the element to the last location of the frame.
2942 // This is so that the default behavior mirrors that of Roo.dd.DD.
2943 endDrag: function(e) {
2945 var lel = this.getEl();
2946 var del = this.getDragEl();
2948 // Show the drag frame briefly so we can get its position
2949 del.style.visibility = "";
2952 // Hide the linked element before the move to get around a Safari
2954 lel.style.visibility = "hidden";
2955 Roo.dd.DDM.moveToEl(lel, del);
2956 del.style.visibility = "hidden";
2957 lel.style.visibility = "";
2962 beforeMove : function(){
2966 afterDrag : function(){
2970 toString: function() {
2971 return ("DDProxy " + this.id);
2977 * Ext JS Library 1.1.1
2978 * Copyright(c) 2006-2007, Ext JS, LLC.
2980 * Originally Released Under LGPL - original licence link has changed is not relivant.
2983 * <script type="text/javascript">
2987 * @class Roo.dd.DDTarget
2988 * A DragDrop implementation that does not move, but can be a drop
2989 * target. You would get the same result by simply omitting implementation
2990 * for the event callbacks, but this way we reduce the processing cost of the
2991 * event listener and the callbacks.
2992 * @extends Roo.dd.DragDrop
2994 * @param {String} id the id of the element that is a drop target
2995 * @param {String} sGroup the group of related DragDrop objects
2996 * @param {object} config an object containing configurable attributes
2997 * Valid properties for DDTarget in addition to those in
3001 Roo.dd.DDTarget = function(id, sGroup, config) {
3003 this.initTarget(id, sGroup, config);
3005 if (config.listeners || config.events) {
3006 Roo.dd.DragDrop.superclass.constructor.call(this, {
3007 listeners : config.listeners || {},
3008 events : config.events || {}
3013 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
3014 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
3015 toString: function() {
3016 return ("DDTarget " + this.id);
3021 * Ext JS Library 1.1.1
3022 * Copyright(c) 2006-2007, Ext JS, LLC.
3024 * Originally Released Under LGPL - original licence link has changed is not relivant.
3027 * <script type="text/javascript">
3032 * @class Roo.dd.ScrollManager
3033 * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
3034 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
3037 Roo.dd.ScrollManager = function(){
3038 var ddm = Roo.dd.DragDropMgr;
3045 var onStop = function(e){
3050 var triggerRefresh = function(){
3051 if(ddm.dragCurrent){
3052 ddm.refreshCache(ddm.dragCurrent.groups);
3056 var doScroll = function(){
3057 if(ddm.dragCurrent){
3058 var dds = Roo.dd.ScrollManager;
3060 if(proc.el.scroll(proc.dir, dds.increment)){
3064 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
3069 var clearProc = function(){
3071 clearInterval(proc.id);
3078 var startProc = function(el, dir){
3082 proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
3085 var onFire = function(e, isDrop){
3086 Roo.log('scroll onfire');
3087 if(isDrop || !ddm.dragCurrent){ return; }
3088 var dds = Roo.dd.ScrollManager;
3089 if(!dragEl || dragEl != ddm.dragCurrent){
3090 dragEl = ddm.dragCurrent;
3091 // refresh regions on drag start
3095 var xy = Roo.lib.Event.getXY(e);
3096 var pt = new Roo.lib.Point(xy[0], xy[1]);
3098 var el = els[id], r = el._region;
3099 if(r && r.contains(pt) && el.isScrollable()){
3100 if(r.bottom - pt.y <= dds.thresh){
3102 startProc(el, "down");
3105 }else if(r.right - pt.x <= dds.thresh){
3107 startProc(el, "left");
3110 }else if(pt.y - r.top <= dds.thresh){
3112 startProc(el, "up");
3115 }else if(pt.x - r.left <= dds.thresh){
3117 startProc(el, "right");
3126 ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
3127 ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
3131 * Registers new overflow element(s) to auto scroll
3132 * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
3134 register : function(el){
3135 if(el instanceof Array){
3136 for(var i = 0, len = el.length; i < len; i++) {
3137 this.register(el[i]);
3143 Roo.dd.ScrollManager.els = els;
3147 * Unregisters overflow element(s) so they are no longer scrolled
3148 * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
3150 unregister : function(el){
3151 if(el instanceof Array){
3152 for(var i = 0, len = el.length; i < len; i++) {
3153 this.unregister(el[i]);
3162 * The number of pixels from the edge of a container the pointer needs to be to
3163 * trigger scrolling (defaults to 25)
3169 * The number of pixels to scroll in each scroll increment (defaults to 50)
3175 * The frequency of scrolls in milliseconds (defaults to 500)
3181 * True to animate the scroll (defaults to true)
3187 * The animation duration in seconds -
3188 * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
3194 * Manually trigger a cache refresh.
3196 refreshCache : function(){
3198 if(typeof els[id] == 'object'){ // for people extending the object prototype
3199 els[id]._region = els[id].getRegion();
3206 * Ext JS Library 1.1.1
3207 * Copyright(c) 2006-2007, Ext JS, LLC.
3209 * Originally Released Under LGPL - original licence link has changed is not relivant.
3212 * <script type="text/javascript">
3217 * @class Roo.dd.Registry
3218 * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
3219 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
3222 Roo.dd.Registry = function(){
3227 var getId = function(el, autogen){
3228 if(typeof el == "string"){
3232 if(!id && autogen !== false){
3233 id = "roodd-" + (++autoIdSeed);
3241 * Register a drag drop element
3242 * @param {String|HTMLElement} element The id or DOM node to register
3243 * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
3244 * in drag drop operations. You can populate this object with any arbitrary properties that your own code
3245 * knows how to interpret, plus there are some specific properties known to the Registry that should be
3246 * populated in the data object (if applicable):
3248 Value Description<br />
3249 --------- ------------------------------------------<br />
3250 handles Array of DOM nodes that trigger dragging<br />
3251 for the element being registered<br />
3252 isHandle True if the element passed in triggers<br />
3253 dragging itself, else false
3256 register : function(el, data){
3258 if(typeof el == "string"){
3259 el = document.getElementById(el);
3262 elements[getId(el)] = data;
3263 if(data.isHandle !== false){
3264 handles[data.ddel.id] = data;
3267 var hs = data.handles;
3268 for(var i = 0, len = hs.length; i < len; i++){
3269 handles[getId(hs[i])] = data;
3275 * Unregister a drag drop element
3276 * @param {String|HTMLElement} element The id or DOM node to unregister
3278 unregister : function(el){
3279 var id = getId(el, false);
3280 var data = elements[id];
3282 delete elements[id];
3284 var hs = data.handles;
3285 for(var i = 0, len = hs.length; i < len; i++){
3286 delete handles[getId(hs[i], false)];
3293 * Returns the handle registered for a DOM Node by id
3294 * @param {String|HTMLElement} id The DOM node or id to look up
3295 * @return {Object} handle The custom handle data
3297 getHandle : function(id){
3298 if(typeof id != "string"){ // must be element?
3305 * Returns the handle that is registered for the DOM node that is the target of the event
3306 * @param {Event} e The event
3307 * @return {Object} handle The custom handle data
3309 getHandleFromEvent : function(e){
3310 var t = Roo.lib.Event.getTarget(e);
3311 return t ? handles[t.id] : null;
3315 * Returns a custom data object that is registered for a DOM node by id
3316 * @param {String|HTMLElement} id The DOM node or id to look up
3317 * @return {Object} data The custom data
3319 getTarget : function(id){
3320 if(typeof id != "string"){ // must be element?
3323 return elements[id];
3327 * Returns a custom data object that is registered for the DOM node that is the target of the event
3328 * @param {Event} e The event
3329 * @return {Object} data The custom data
3331 getTargetFromEvent : function(e){
3332 var t = Roo.lib.Event.getTarget(e);
3333 return t ? elements[t.id] || handles[t.id] : null;
3338 * Ext JS Library 1.1.1
3339 * Copyright(c) 2006-2007, Ext JS, LLC.
3341 * Originally Released Under LGPL - original licence link has changed is not relivant.
3344 * <script type="text/javascript">
3349 * @class Roo.dd.StatusProxy
3350 * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
3351 * default drag proxy used by all Roo.dd components.
3353 * @param {Object} config
3355 Roo.dd.StatusProxy = function(config){
3356 Roo.apply(this, config);
3357 this.id = this.id || Roo.id();
3358 this.el = new Roo.Layer({
3360 id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
3361 {tag: "div", cls: "x-dd-drop-icon"},
3362 {tag: "div", cls: "x-dd-drag-ghost"}
3365 shadow: !config || config.shadow !== false
3367 this.ghost = Roo.get(this.el.dom.childNodes[1]);
3368 this.dropStatus = this.dropNotAllowed;
3371 Roo.dd.StatusProxy.prototype = {
3373 * @cfg {String} dropAllowed
3374 * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
3376 dropAllowed : "x-dd-drop-ok",
3378 * @cfg {String} dropNotAllowed
3379 * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
3381 dropNotAllowed : "x-dd-drop-nodrop",
3384 * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
3385 * over the current target element.
3386 * @param {String} cssClass The css class for the new drop status indicator image
3388 setStatus : function(cssClass){
3389 cssClass = cssClass || this.dropNotAllowed;
3390 if(this.dropStatus != cssClass){
3391 this.el.replaceClass(this.dropStatus, cssClass);
3392 this.dropStatus = cssClass;
3397 * Resets the status indicator to the default dropNotAllowed value
3398 * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
3400 reset : function(clearGhost){
3401 this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
3402 this.dropStatus = this.dropNotAllowed;
3404 this.ghost.update("");
3409 * Updates the contents of the ghost element
3410 * @param {String} html The html that will replace the current innerHTML of the ghost element
3412 update : function(html){
3413 if(typeof html == "string"){
3414 this.ghost.update(html);
3416 this.ghost.update("");
3417 html.style.margin = "0";
3418 this.ghost.dom.appendChild(html);
3420 // ensure float = none set?? cant remember why though.
3421 var el = this.ghost.dom.firstChild;
3423 Roo.fly(el).setStyle('float', 'none');
3428 * Returns the underlying proxy {@link Roo.Layer}
3429 * @return {Roo.Layer} el
3436 * Returns the ghost element
3437 * @return {Roo.Element} el
3439 getGhost : function(){
3445 * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
3447 hide : function(clear){
3455 * Stops the repair animation if it's currently running
3458 if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
3464 * Displays this proxy
3471 * Force the Layer to sync its shadow and shim positions to the element
3478 * Causes the proxy to return to its position of origin via an animation. Should be called after an
3479 * invalid drop operation by the item being dragged.
3480 * @param {Array} xy The XY position of the element ([x, y])
3481 * @param {Function} callback The function to call after the repair is complete
3482 * @param {Object} scope The scope in which to execute the callback
3484 repair : function(xy, callback, scope){
3485 this.callback = callback;
3487 if(xy && this.animRepair !== false){
3488 this.el.addClass("x-dd-drag-repair");
3489 this.el.hideUnders(true);
3490 this.anim = this.el.shift({
3491 duration: this.repairDuration || .5,
3495 callback: this.afterRepair,
3504 afterRepair : function(){
3506 if(typeof this.callback == "function"){
3507 this.callback.call(this.scope || this);
3509 this.callback = null;
3514 * Ext JS Library 1.1.1
3515 * Copyright(c) 2006-2007, Ext JS, LLC.
3517 * Originally Released Under LGPL - original licence link has changed is not relivant.
3520 * <script type="text/javascript">
3524 * @class Roo.dd.DragSource
3525 * @extends Roo.dd.DDProxy
3526 * A simple class that provides the basic implementation needed to make any element draggable.
3528 * @param {String/HTMLElement/Element} el The container element
3529 * @param {Object} config
3531 Roo.dd.DragSource = function(el, config){
3532 this.el = Roo.get(el);
3535 Roo.apply(this, config);
3538 this.proxy = new Roo.dd.StatusProxy();
3541 Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
3542 {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
3544 this.dragging = false;
3547 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
3549 * @cfg {String} dropAllowed
3550 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
3552 dropAllowed : "x-dd-drop-ok",
3554 * @cfg {String} dropNotAllowed
3555 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
3557 dropNotAllowed : "x-dd-drop-nodrop",
3560 * Returns the data object associated with this drag source
3561 * @return {Object} data An object containing arbitrary data
3563 getDragData : function(e){
3564 return this.dragData;
3568 onDragEnter : function(e, id){
3569 var target = Roo.dd.DragDropMgr.getDDById(id);
3570 this.cachedTarget = target;
3571 if(this.beforeDragEnter(target, e, id) !== false){
3572 if(target.isNotifyTarget){
3573 var status = target.notifyEnter(this, e, this.dragData);
3574 this.proxy.setStatus(status);
3576 this.proxy.setStatus(this.dropAllowed);
3579 if(this.afterDragEnter){
3581 * An empty function by default, but provided so that you can perform a custom action
3582 * when the dragged item enters the drop target by providing an implementation.
3583 * @param {Roo.dd.DragDrop} target The drop target
3584 * @param {Event} e The event object
3585 * @param {String} id The id of the dragged element
3586 * @method afterDragEnter
3588 this.afterDragEnter(target, e, id);
3594 * An empty function by default, but provided so that you can perform a custom action
3595 * before the dragged item enters the drop target and optionally cancel the onDragEnter.
3596 * @param {Roo.dd.DragDrop} target The drop target
3597 * @param {Event} e The event object
3598 * @param {String} id The id of the dragged element
3599 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
3601 beforeDragEnter : function(target, e, id){
3606 alignElWithMouse: function() {
3607 Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
3612 onDragOver : function(e, id){
3613 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
3614 if(this.beforeDragOver(target, e, id) !== false){
3615 if(target.isNotifyTarget){
3616 var status = target.notifyOver(this, e, this.dragData);
3617 this.proxy.setStatus(status);
3620 if(this.afterDragOver){
3622 * An empty function by default, but provided so that you can perform a custom action
3623 * while the dragged item is over the drop target by providing an implementation.
3624 * @param {Roo.dd.DragDrop} target The drop target
3625 * @param {Event} e The event object
3626 * @param {String} id The id of the dragged element
3627 * @method afterDragOver
3629 this.afterDragOver(target, e, id);
3635 * An empty function by default, but provided so that you can perform a custom action
3636 * while the dragged item is over the drop target and optionally cancel the onDragOver.
3637 * @param {Roo.dd.DragDrop} target The drop target
3638 * @param {Event} e The event object
3639 * @param {String} id The id of the dragged element
3640 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
3642 beforeDragOver : function(target, e, id){
3647 onDragOut : function(e, id){
3648 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
3649 if(this.beforeDragOut(target, e, id) !== false){
3650 if(target.isNotifyTarget){
3651 target.notifyOut(this, e, this.dragData);
3654 if(this.afterDragOut){
3656 * An empty function by default, but provided so that you can perform a custom action
3657 * after the dragged item is dragged out of the target without dropping.
3658 * @param {Roo.dd.DragDrop} target The drop target
3659 * @param {Event} e The event object
3660 * @param {String} id The id of the dragged element
3661 * @method afterDragOut
3663 this.afterDragOut(target, e, id);
3666 this.cachedTarget = null;
3670 * An empty function by default, but provided so that you can perform a custom action before the dragged
3671 * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
3672 * @param {Roo.dd.DragDrop} target The drop target
3673 * @param {Event} e The event object
3674 * @param {String} id The id of the dragged element
3675 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
3677 beforeDragOut : function(target, e, id){
3682 onDragDrop : function(e, id){
3683 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
3684 if(this.beforeDragDrop(target, e, id) !== false){
3685 if(target.isNotifyTarget){
3686 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
3687 this.onValidDrop(target, e, id);
3689 this.onInvalidDrop(target, e, id);
3692 this.onValidDrop(target, e, id);
3695 if(this.afterDragDrop){
3697 * An empty function by default, but provided so that you can perform a custom action
3698 * after a valid drag drop has occurred by providing an implementation.
3699 * @param {Roo.dd.DragDrop} target The drop target
3700 * @param {Event} e The event object
3701 * @param {String} id The id of the dropped element
3702 * @method afterDragDrop
3704 this.afterDragDrop(target, e, id);
3707 delete this.cachedTarget;
3711 * An empty function by default, but provided so that you can perform a custom action before the dragged
3712 * item is dropped onto the target and optionally cancel the onDragDrop.
3713 * @param {Roo.dd.DragDrop} target The drop target
3714 * @param {Event} e The event object
3715 * @param {String} id The id of the dragged element
3716 * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
3718 beforeDragDrop : function(target, e, id){
3723 onValidDrop : function(target, e, id){
3725 if(this.afterValidDrop){
3727 * An empty function by default, but provided so that you can perform a custom action
3728 * after a valid drop has occurred by providing an implementation.
3729 * @param {Object} target The target DD
3730 * @param {Event} e The event object
3731 * @param {String} id The id of the dropped element
3732 * @method afterInvalidDrop
3734 this.afterValidDrop(target, e, id);
3739 getRepairXY : function(e, data){
3740 return this.el.getXY();
3744 onInvalidDrop : function(target, e, id){
3745 this.beforeInvalidDrop(target, e, id);
3746 if(this.cachedTarget){
3747 if(this.cachedTarget.isNotifyTarget){
3748 this.cachedTarget.notifyOut(this, e, this.dragData);
3750 this.cacheTarget = null;
3752 this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
3754 if(this.afterInvalidDrop){
3756 * An empty function by default, but provided so that you can perform a custom action
3757 * after an invalid drop has occurred by providing an implementation.
3758 * @param {Event} e The event object
3759 * @param {String} id The id of the dropped element
3760 * @method afterInvalidDrop
3762 this.afterInvalidDrop(e, id);
3767 afterRepair : function(){
3769 this.el.highlight(this.hlColor || "c3daf9");
3771 this.dragging = false;
3775 * An empty function by default, but provided so that you can perform a custom action after an invalid
3776 * drop has occurred.
3777 * @param {Roo.dd.DragDrop} target The drop target
3778 * @param {Event} e The event object
3779 * @param {String} id The id of the dragged element
3780 * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
3782 beforeInvalidDrop : function(target, e, id){
3787 handleMouseDown : function(e){
3791 var data = this.getDragData(e);
3792 if(data && this.onBeforeDrag(data, e) !== false){
3793 this.dragData = data;
3795 Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
3800 * An empty function by default, but provided so that you can perform a custom action before the initial
3801 * drag event begins and optionally cancel it.
3802 * @param {Object} data An object containing arbitrary data to be shared with drop targets
3803 * @param {Event} e The event object
3804 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
3806 onBeforeDrag : function(data, e){
3811 * An empty function by default, but provided so that you can perform a custom action once the initial
3812 * drag event has begun. The drag cannot be canceled from this function.
3813 * @param {Number} x The x position of the click on the dragged object
3814 * @param {Number} y The y position of the click on the dragged object
3816 onStartDrag : Roo.emptyFn,
3818 // private - YUI override
3819 startDrag : function(x, y){
3821 this.dragging = true;
3822 this.proxy.update("");
3823 this.onInitDrag(x, y);
3828 onInitDrag : function(x, y){
3829 var clone = this.el.dom.cloneNode(true);
3830 clone.id = Roo.id(); // prevent duplicate ids
3831 this.proxy.update(clone);
3832 this.onStartDrag(x, y);
3837 * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
3838 * @return {Roo.dd.StatusProxy} proxy The StatusProxy
3840 getProxy : function(){
3845 * Hides the drag source's {@link Roo.dd.StatusProxy}
3847 hideProxy : function(){
3849 this.proxy.reset(true);
3850 this.dragging = false;
3854 triggerCacheRefresh : function(){
3855 Roo.dd.DDM.refreshCache(this.groups);
3858 // private - override to prevent hiding
3859 b4EndDrag: function(e) {
3862 // private - override to prevent moving
3863 endDrag : function(e){
3864 this.onEndDrag(this.dragData, e);
3868 onEndDrag : function(data, e){
3871 // private - pin to cursor
3872 autoOffset : function(x, y) {
3873 this.setDelta(-12, -20);
3877 * Ext JS Library 1.1.1
3878 * Copyright(c) 2006-2007, Ext JS, LLC.
3880 * Originally Released Under LGPL - original licence link has changed is not relivant.
3883 * <script type="text/javascript">
3888 * @class Roo.dd.DropTarget
3889 * @extends Roo.dd.DDTarget
3890 * A simple class that provides the basic implementation needed to make any element a drop target that can have
3891 * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
3893 * @param {String/HTMLElement/Element} el The container element
3894 * @param {Object} config
3896 Roo.dd.DropTarget = function(el, config){
3897 this.el = Roo.get(el);
3899 var listeners = false; ;
3900 if (config && config.listeners) {
3901 listeners= config.listeners;
3902 delete config.listeners;
3904 Roo.apply(this, config);
3906 if(this.containerScroll){
3907 Roo.dd.ScrollManager.register(this.el);
3911 * @scope Roo.dd.DropTarget
3916 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
3917 * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
3918 * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
3920 * IMPORTANT : it should set this.overClass and this.dropAllowed
3922 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
3923 * @param {Event} e The event
3924 * @param {Object} data An object containing arbitrary data supplied by the drag source
3930 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
3931 * This method will be called on every mouse movement while the drag source is over the drop target.
3932 * This default implementation simply returns the dropAllowed config value.
3934 * IMPORTANT : it should set this.dropAllowed
3936 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
3937 * @param {Event} e The event
3938 * @param {Object} data An object containing arbitrary data supplied by the drag source
3944 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
3945 * out of the target without dropping. This default implementation simply removes the CSS class specified by
3946 * overClass (if any) from the drop element.
3947 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
3948 * @param {Event} e The event
3949 * @param {Object} data An object containing arbitrary data supplied by the drag source
3955 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
3956 * been dropped on it. This method has no default implementation and returns false, so you must provide an
3957 * implementation that does something to process the drop event and returns true so that the drag source's
3958 * repair action does not run.
3960 * IMPORTANT : it should set this.success
3962 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
3963 * @param {Event} e The event
3964 * @param {Object} data An object containing arbitrary data supplied by the drag source
3970 Roo.dd.DropTarget.superclass.constructor.call( this,
3972 this.ddGroup || this.group,
3975 listeners : listeners || {}
3983 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
3985 * @cfg {String} overClass
3986 * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
3989 * @cfg {String} ddGroup
3990 * The drag drop group to handle drop events for
3994 * @cfg {String} dropAllowed
3995 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
3997 dropAllowed : "x-dd-drop-ok",
3999 * @cfg {String} dropNotAllowed
4000 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
4002 dropNotAllowed : "x-dd-drop-nodrop",
4004 * @cfg {boolean} success
4005 * set this after drop listener..
4009 * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
4010 * if the drop point is valid for over/enter..
4017 isNotifyTarget : true,
4022 notifyEnter : function(dd, e, data)
4025 this.fireEvent('enter', dd, e, data);
4027 this.el.addClass(this.overClass);
4029 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
4030 this.valid ? this.dropAllowed : this.dropNotAllowed
4037 notifyOver : function(dd, e, data)
4040 this.fireEvent('over', dd, e, data);
4041 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
4042 this.valid ? this.dropAllowed : this.dropNotAllowed
4049 notifyOut : function(dd, e, data)
4051 this.fireEvent('out', dd, e, data);
4053 this.el.removeClass(this.overClass);
4060 notifyDrop : function(dd, e, data)
4062 this.success = false;
4063 this.fireEvent('drop', dd, e, data);
4064 return this.success;
4068 * Ext JS Library 1.1.1
4069 * Copyright(c) 2006-2007, Ext JS, LLC.
4071 * Originally Released Under LGPL - original licence link has changed is not relivant.
4074 * <script type="text/javascript">
4079 * @class Roo.dd.DragZone
4080 * @extends Roo.dd.DragSource
4081 * This class provides a container DD instance that proxies for multiple child node sources.<br />
4082 * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
4084 * @param {String/HTMLElement/Element} el The container element
4085 * @param {Object} config
4087 Roo.dd.DragZone = function(el, config){
4088 Roo.dd.DragZone.superclass.constructor.call(this, el, config);
4089 if(this.containerScroll){
4090 Roo.dd.ScrollManager.register(this.el);
4094 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
4096 * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
4097 * for auto scrolling during drag operations.
4100 * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
4101 * method after a failed drop (defaults to "c3daf9" - light blue)
4105 * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
4106 * for a valid target to drag based on the mouse down. Override this method
4107 * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
4108 * object has a "ddel" attribute (with an HTML Element) for other functions to work.
4109 * @param {EventObject} e The mouse down event
4110 * @return {Object} The dragData
4112 getDragData : function(e){
4113 return Roo.dd.Registry.getHandleFromEvent(e);
4117 * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
4118 * this.dragData.ddel
4119 * @param {Number} x The x position of the click on the dragged object
4120 * @param {Number} y The y position of the click on the dragged object
4121 * @return {Boolean} true to continue the drag, false to cancel
4123 onInitDrag : function(x, y){
4124 this.proxy.update(this.dragData.ddel.cloneNode(true));
4125 this.onStartDrag(x, y);
4130 * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
4132 afterRepair : function(){
4134 Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
4136 this.dragging = false;
4140 * Called before a repair of an invalid drop to get the XY to animate to. By default returns
4141 * the XY of this.dragData.ddel
4142 * @param {EventObject} e The mouse up event
4143 * @return {Array} The xy location (e.g. [100, 200])
4145 getRepairXY : function(e){
4146 return Roo.Element.fly(this.dragData.ddel).getXY();
4150 * Ext JS Library 1.1.1
4151 * Copyright(c) 2006-2007, Ext JS, LLC.
4153 * Originally Released Under LGPL - original licence link has changed is not relivant.
4156 * <script type="text/javascript">
4159 * @class Roo.dd.DropZone
4160 * @extends Roo.dd.DropTarget
4161 * This class provides a container DD instance that proxies for multiple child node targets.<br />
4162 * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
4164 * @param {String/HTMLElement/Element} el The container element
4165 * @param {Object} config
4167 Roo.dd.DropZone = function(el, config){
4168 Roo.dd.DropZone.superclass.constructor.call(this, el, config);
4171 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
4173 * Returns a custom data object associated with the DOM node that is the target of the event. By default
4174 * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
4175 * provide your own custom lookup.
4176 * @param {Event} e The event
4177 * @return {Object} data The custom data
4179 getTargetFromEvent : function(e){
4180 return Roo.dd.Registry.getTargetFromEvent(e);
4184 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
4185 * that it has registered. This method has no default implementation and should be overridden to provide
4186 * node-specific processing if necessary.
4187 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
4188 * {@link #getTargetFromEvent} for this node)
4189 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4190 * @param {Event} e The event
4191 * @param {Object} data An object containing arbitrary data supplied by the drag source
4193 onNodeEnter : function(n, dd, e, data){
4198 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
4199 * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
4200 * overridden to provide the proper feedback.
4201 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
4202 * {@link #getTargetFromEvent} for this node)
4203 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4204 * @param {Event} e The event
4205 * @param {Object} data An object containing arbitrary data supplied by the drag source
4206 * @return {String} status The CSS class that communicates the drop status back to the source so that the
4207 * underlying {@link Roo.dd.StatusProxy} can be updated
4209 onNodeOver : function(n, dd, e, data){
4210 return this.dropAllowed;
4214 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
4215 * the drop node without dropping. This method has no default implementation and should be overridden to provide
4216 * node-specific processing if necessary.
4217 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
4218 * {@link #getTargetFromEvent} for this node)
4219 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4220 * @param {Event} e The event
4221 * @param {Object} data An object containing arbitrary data supplied by the drag source
4223 onNodeOut : function(n, dd, e, data){
4228 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
4229 * the drop node. The default implementation returns false, so it should be overridden to provide the
4230 * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
4231 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
4232 * {@link #getTargetFromEvent} for this node)
4233 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4234 * @param {Event} e The event
4235 * @param {Object} data An object containing arbitrary data supplied by the drag source
4236 * @return {Boolean} True if the drop was valid, else false
4238 onNodeDrop : function(n, dd, e, data){
4243 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
4244 * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
4245 * it should be overridden to provide the proper feedback if necessary.
4246 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4247 * @param {Event} e The event
4248 * @param {Object} data An object containing arbitrary data supplied by the drag source
4249 * @return {String} status The CSS class that communicates the drop status back to the source so that the
4250 * underlying {@link Roo.dd.StatusProxy} can be updated
4252 onContainerOver : function(dd, e, data){
4253 return this.dropNotAllowed;
4257 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
4258 * but not on any of its registered drop nodes. The default implementation returns false, so it should be
4259 * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
4260 * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
4261 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4262 * @param {Event} e The event
4263 * @param {Object} data An object containing arbitrary data supplied by the drag source
4264 * @return {Boolean} True if the drop was valid, else false
4266 onContainerDrop : function(dd, e, data){
4271 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
4272 * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
4273 * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
4274 * you should override this method and provide a custom implementation.
4275 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4276 * @param {Event} e The event
4277 * @param {Object} data An object containing arbitrary data supplied by the drag source
4278 * @return {String} status The CSS class that communicates the drop status back to the source so that the
4279 * underlying {@link Roo.dd.StatusProxy} can be updated
4281 notifyEnter : function(dd, e, data){
4282 return this.dropNotAllowed;
4286 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
4287 * This method will be called on every mouse movement while the drag source is over the drop zone.
4288 * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
4289 * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
4290 * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
4291 * registered node, it will call {@link #onContainerOver}.
4292 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4293 * @param {Event} e The event
4294 * @param {Object} data An object containing arbitrary data supplied by the drag source
4295 * @return {String} status The CSS class that communicates the drop status back to the source so that the
4296 * underlying {@link Roo.dd.StatusProxy} can be updated
4298 notifyOver : function(dd, e, data){
4299 var n = this.getTargetFromEvent(e);
4300 if(!n){ // not over valid drop target
4301 if(this.lastOverNode){
4302 this.onNodeOut(this.lastOverNode, dd, e, data);
4303 this.lastOverNode = null;
4305 return this.onContainerOver(dd, e, data);
4307 if(this.lastOverNode != n){
4308 if(this.lastOverNode){
4309 this.onNodeOut(this.lastOverNode, dd, e, data);
4311 this.onNodeEnter(n, dd, e, data);
4312 this.lastOverNode = n;
4314 return this.onNodeOver(n, dd, e, data);
4318 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
4319 * out of the zone without dropping. If the drag source is currently over a registered node, the notification
4320 * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
4321 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
4322 * @param {Event} e The event
4323 * @param {Object} data An object containing arbitrary data supplied by the drag zone
4325 notifyOut : function(dd, e, data){
4326 if(this.lastOverNode){
4327 this.onNodeOut(this.lastOverNode, dd, e, data);
4328 this.lastOverNode = null;
4333 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
4334 * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
4335 * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
4336 * otherwise it will call {@link #onContainerDrop}.
4337 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4338 * @param {Event} e The event
4339 * @param {Object} data An object containing arbitrary data supplied by the drag source
4340 * @return {Boolean} True if the drop was valid, else false
4342 notifyDrop : function(dd, e, data){
4343 if(this.lastOverNode){
4344 this.onNodeOut(this.lastOverNode, dd, e, data);
4345 this.lastOverNode = null;
4347 var n = this.getTargetFromEvent(e);
4349 this.onNodeDrop(n, dd, e, data) :
4350 this.onContainerDrop(dd, e, data);
4354 triggerCacheRefresh : function(){
4355 Roo.dd.DDM.refreshCache(this.groups);
4359 * Ext JS Library 1.1.1
4360 * Copyright(c) 2006-2007, Ext JS, LLC.
4362 * Originally Released Under LGPL - original licence link has changed is not relivant.
4365 * <script type="text/javascript">
4370 * @class Roo.data.SortTypes
4372 * Defines the default sorting (casting?) comparison functions used when sorting data.
4374 Roo.data.SortTypes = {
4376 * Default sort that does nothing
4377 * @param {Mixed} s The value being converted
4378 * @return {Mixed} The comparison value
4385 * The regular expression used to strip tags
4389 stripTagsRE : /<\/?[^>]+>/gi,
4392 * Strips all HTML tags to sort on text only
4393 * @param {Mixed} s The value being converted
4394 * @return {String} The comparison value
4396 asText : function(s){
4397 return String(s).replace(this.stripTagsRE, "");
4401 * Strips all HTML tags to sort on text only - Case insensitive
4402 * @param {Mixed} s The value being converted
4403 * @return {String} The comparison value
4405 asUCText : function(s){
4406 return String(s).toUpperCase().replace(this.stripTagsRE, "");
4410 * Case insensitive string
4411 * @param {Mixed} s The value being converted
4412 * @return {String} The comparison value
4414 asUCString : function(s) {
4415 return String(s).toUpperCase();
4420 * @param {Mixed} s The value being converted
4421 * @return {Number} The comparison value
4423 asDate : function(s) {
4427 if(s instanceof Date){
4430 return Date.parse(String(s));
4435 * @param {Mixed} s The value being converted
4436 * @return {Float} The comparison value
4438 asFloat : function(s) {
4439 var val = parseFloat(String(s).replace(/,/g, ""));
4440 if(isNaN(val)) val = 0;
4446 * @param {Mixed} s The value being converted
4447 * @return {Number} The comparison value
4449 asInt : function(s) {
4450 var val = parseInt(String(s).replace(/,/g, ""));
4451 if(isNaN(val)) val = 0;
4456 * Ext JS Library 1.1.1
4457 * Copyright(c) 2006-2007, Ext JS, LLC.
4459 * Originally Released Under LGPL - original licence link has changed is not relivant.
4462 * <script type="text/javascript">
4466 * @class Roo.data.Record
4467 * Instances of this class encapsulate both record <em>definition</em> information, and record
4468 * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
4469 * to access Records cached in an {@link Roo.data.Store} object.<br>
4471 * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
4472 * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
4475 * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
4477 * This constructor should not be used to create Record objects. Instead, use the constructor generated by
4478 * {@link #create}. The parameters are the same.
4479 * @param {Array} data An associative Array of data values keyed by the field name.
4480 * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
4481 * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
4482 * not specified an integer id is generated.
4484 Roo.data.Record = function(data, id){
4485 this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
4490 * Generate a constructor for a specific record layout.
4491 * @param {Array} o An Array of field definition objects which specify field names, and optionally,
4492 * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
4493 * Each field definition object may contain the following properties: <ul>
4494 * <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,
4495 * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
4496 * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
4497 * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
4498 * is being used, then this is a string containing the javascript expression to reference the data relative to
4499 * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
4500 * to the data item relative to the record element. If the mapping expression is the same as the field name,
4501 * this may be omitted.</p></li>
4502 * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
4503 * <ul><li>auto (Default, implies no conversion)</li>
4508 * <li>date</li></ul></p></li>
4509 * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
4510 * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
4511 * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
4512 * by the Reader into an object that will be stored in the Record. It is passed the
4513 * following parameters:<ul>
4514 * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
4516 * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
4518 * <br>usage:<br><pre><code>
4519 var TopicRecord = Roo.data.Record.create(
4520 {name: 'title', mapping: 'topic_title'},
4521 {name: 'author', mapping: 'username'},
4522 {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
4523 {name: 'lastPost', mapping: 'post_time', type: 'date'},
4524 {name: 'lastPoster', mapping: 'user2'},
4525 {name: 'excerpt', mapping: 'post_text'}
4528 var myNewRecord = new TopicRecord({
4529 title: 'Do my job please',
4532 lastPost: new Date(),
4533 lastPoster: 'Animal',
4534 excerpt: 'No way dude!'
4536 myStore.add(myNewRecord);
4541 Roo.data.Record.create = function(o){
4543 f.superclass.constructor.apply(this, arguments);
4545 Roo.extend(f, Roo.data.Record);
4546 var p = f.prototype;
4547 p.fields = new Roo.util.MixedCollection(false, function(field){
4550 for(var i = 0, len = o.length; i < len; i++){
4551 p.fields.add(new Roo.data.Field(o[i]));
4553 f.getField = function(name){
4554 return p.fields.get(name);
4559 Roo.data.Record.AUTO_ID = 1000;
4560 Roo.data.Record.EDIT = 'edit';
4561 Roo.data.Record.REJECT = 'reject';
4562 Roo.data.Record.COMMIT = 'commit';
4564 Roo.data.Record.prototype = {
4566 * Readonly flag - true if this record has been modified.
4575 join : function(store){
4580 * Set the named field to the specified value.
4581 * @param {String} name The name of the field to set.
4582 * @param {Object} value The value to set the field to.
4584 set : function(name, value){
4585 if(this.data[name] == value){
4592 if(typeof this.modified[name] == 'undefined'){
4593 this.modified[name] = this.data[name];
4595 this.data[name] = value;
4596 if(!this.editing && this.store){
4597 this.store.afterEdit(this);
4602 * Get the value of the named field.
4603 * @param {String} name The name of the field to get the value of.
4604 * @return {Object} The value of the field.
4606 get : function(name){
4607 return this.data[name];
4611 beginEdit : function(){
4612 this.editing = true;
4617 cancelEdit : function(){
4618 this.editing = false;
4619 delete this.modified;
4623 endEdit : function(){
4624 this.editing = false;
4625 if(this.dirty && this.store){
4626 this.store.afterEdit(this);
4631 * Usually called by the {@link Roo.data.Store} which owns the Record.
4632 * Rejects all changes made to the Record since either creation, or the last commit operation.
4633 * Modified fields are reverted to their original values.
4635 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
4636 * of reject operations.
4638 reject : function(){
4639 var m = this.modified;
4641 if(typeof m[n] != "function"){
4642 this.data[n] = m[n];
4646 delete this.modified;
4647 this.editing = false;
4649 this.store.afterReject(this);
4654 * Usually called by the {@link Roo.data.Store} which owns the Record.
4655 * Commits all changes made to the Record since either creation, or the last commit operation.
4657 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
4658 * of commit operations.
4660 commit : function(){
4662 delete this.modified;
4663 this.editing = false;
4665 this.store.afterCommit(this);
4670 hasError : function(){
4671 return this.error != null;
4675 clearError : function(){
4680 * Creates a copy of this record.
4681 * @param {String} id (optional) A new record id if you don't want to use this record's id
4684 copy : function(newId) {
4685 return new this.constructor(Roo.apply({}, this.data), newId || this.id);
4689 * Ext JS Library 1.1.1
4690 * Copyright(c) 2006-2007, Ext JS, LLC.
4692 * Originally Released Under LGPL - original licence link has changed is not relivant.
4695 * <script type="text/javascript">
4701 * @class Roo.data.Store
4702 * @extends Roo.util.Observable
4703 * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
4704 * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
4706 * 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
4707 * has no knowledge of the format of the data returned by the Proxy.<br>
4709 * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
4710 * instances from the data object. These records are cached and made available through accessor functions.
4712 * Creates a new Store.
4713 * @param {Object} config A config object containing the objects needed for the Store to access data,
4714 * and read the data into Records.
4716 Roo.data.Store = function(config){
4717 this.data = new Roo.util.MixedCollection(false);
4718 this.data.getKey = function(o){
4721 this.baseParams = {};
4728 "multisort" : "_multisort"
4731 if(config && config.data){
4732 this.inlineData = config.data;
4736 Roo.apply(this, config);
4738 if(this.reader){ // reader passed
4739 this.reader = Roo.factory(this.reader, Roo.data);
4740 this.reader.xmodule = this.xmodule || false;
4741 if(!this.recordType){
4742 this.recordType = this.reader.recordType;
4744 if(this.reader.onMetaChange){
4745 this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
4749 if(this.recordType){
4750 this.fields = this.recordType.prototype.fields;
4756 * @event datachanged
4757 * Fires when the data cache has changed, and a widget which is using this Store
4758 * as a Record cache should refresh its view.
4759 * @param {Store} this
4764 * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
4765 * @param {Store} this
4766 * @param {Object} meta The JSON metadata
4771 * Fires when Records have been added to the Store
4772 * @param {Store} this
4773 * @param {Roo.data.Record[]} records The array of Records added
4774 * @param {Number} index The index at which the record(s) were added
4779 * Fires when a Record has been removed from the Store
4780 * @param {Store} this
4781 * @param {Roo.data.Record} record The Record that was removed
4782 * @param {Number} index The index at which the record was removed
4787 * Fires when a Record has been updated
4788 * @param {Store} this
4789 * @param {Roo.data.Record} record The Record that was updated
4790 * @param {String} operation The update operation being performed. Value may be one of:
4792 Roo.data.Record.EDIT
4793 Roo.data.Record.REJECT
4794 Roo.data.Record.COMMIT
4800 * Fires when the data cache has been cleared.
4801 * @param {Store} this
4806 * Fires before a request is made for a new data object. If the beforeload handler returns false
4807 * the load action will be canceled.
4808 * @param {Store} this
4809 * @param {Object} options The loading options that were specified (see {@link #load} for details)
4814 * Fires after a new set of Records has been loaded.
4815 * @param {Store} this
4816 * @param {Roo.data.Record[]} records The Records that were loaded
4817 * @param {Object} options The loading options that were specified (see {@link #load} for details)
4821 * @event loadexception
4822 * Fires if an exception occurs in the Proxy during loading.
4823 * Called with the signature of the Proxy's "loadexception" event.
4824 * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
4827 * @param {Object} return from JsonData.reader() - success, totalRecords, records
4828 * @param {Object} load options
4829 * @param {Object} jsonData from your request (normally this contains the Exception)
4831 loadexception : true
4835 this.proxy = Roo.factory(this.proxy, Roo.data);
4836 this.proxy.xmodule = this.xmodule || false;
4837 this.relayEvents(this.proxy, ["loadexception"]);
4839 this.sortToggle = {};
4840 this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
4842 Roo.data.Store.superclass.constructor.call(this);
4844 if(this.inlineData){
4845 this.loadData(this.inlineData);
4846 delete this.inlineData;
4849 Roo.extend(Roo.data.Store, Roo.util.Observable, {
4851 * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
4852 * without a remote query - used by combo/forms at present.
4856 * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
4859 * @cfg {Array} data Inline data to be loaded when the store is initialized.
4862 * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
4863 * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
4866 * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
4867 * on any HTTP request
4870 * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
4873 * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
4877 * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
4878 * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
4883 * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
4884 * loaded or when a record is removed. (defaults to false).
4886 pruneModifiedRecords : false,
4892 * Add Records to the Store and fires the add event.
4893 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
4895 add : function(records){
4896 records = [].concat(records);
4897 for(var i = 0, len = records.length; i < len; i++){
4898 records[i].join(this);
4900 var index = this.data.length;
4901 this.data.addAll(records);
4902 this.fireEvent("add", this, records, index);
4906 * Remove a Record from the Store and fires the remove event.
4907 * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
4909 remove : function(record){
4910 var index = this.data.indexOf(record);
4911 this.data.removeAt(index);
4912 if(this.pruneModifiedRecords){
4913 this.modified.remove(record);
4915 this.fireEvent("remove", this, record, index);
4919 * Remove all Records from the Store and fires the clear event.
4921 removeAll : function(){
4923 if(this.pruneModifiedRecords){
4926 this.fireEvent("clear", this);
4930 * Inserts Records to the Store at the given index and fires the add event.
4931 * @param {Number} index The start index at which to insert the passed Records.
4932 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
4934 insert : function(index, records){
4935 records = [].concat(records);
4936 for(var i = 0, len = records.length; i < len; i++){
4937 this.data.insert(index, records[i]);
4938 records[i].join(this);
4940 this.fireEvent("add", this, records, index);
4944 * Get the index within the cache of the passed Record.
4945 * @param {Roo.data.Record} record The Roo.data.Record object to to find.
4946 * @return {Number} The index of the passed Record. Returns -1 if not found.
4948 indexOf : function(record){
4949 return this.data.indexOf(record);
4953 * Get the index within the cache of the Record with the passed id.
4954 * @param {String} id The id of the Record to find.
4955 * @return {Number} The index of the Record. Returns -1 if not found.
4957 indexOfId : function(id){
4958 return this.data.indexOfKey(id);
4962 * Get the Record with the specified id.
4963 * @param {String} id The id of the Record to find.
4964 * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
4966 getById : function(id){
4967 return this.data.key(id);
4971 * Get the Record at the specified index.
4972 * @param {Number} index The index of the Record to find.
4973 * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
4975 getAt : function(index){
4976 return this.data.itemAt(index);
4980 * Returns a range of Records between specified indices.
4981 * @param {Number} startIndex (optional) The starting index (defaults to 0)
4982 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
4983 * @return {Roo.data.Record[]} An array of Records
4985 getRange : function(start, end){
4986 return this.data.getRange(start, end);
4990 storeOptions : function(o){
4991 o = Roo.apply({}, o);
4994 this.lastOptions = o;
4998 * Loads the Record cache from the configured Proxy using the configured Reader.
5000 * If using remote paging, then the first load call must specify the <em>start</em>
5001 * and <em>limit</em> properties in the options.params property to establish the initial
5002 * position within the dataset, and the number of Records to cache on each read from the Proxy.
5004 * <strong>It is important to note that for remote data sources, loading is asynchronous,
5005 * and this call will return before the new data has been loaded. Perform any post-processing
5006 * in a callback function, or in a "load" event handler.</strong>
5008 * @param {Object} options An object containing properties which control loading options:<ul>
5009 * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
5010 * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
5011 * passed the following arguments:<ul>
5012 * <li>r : Roo.data.Record[]</li>
5013 * <li>options: Options object from the load call</li>
5014 * <li>success: Boolean success indicator</li></ul></li>
5015 * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
5016 * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
5019 load : function(options){
5020 options = options || {};
5021 if(this.fireEvent("beforeload", this, options) !== false){
5022 this.storeOptions(options);
5023 var p = Roo.apply(options.params || {}, this.baseParams);
5024 // if meta was not loaded from remote source.. try requesting it.
5025 if (!this.reader.metaFromRemote) {
5028 if(this.sortInfo && this.remoteSort){
5029 var pn = this.paramNames;
5030 p[pn["sort"]] = this.sortInfo.field;
5031 p[pn["dir"]] = this.sortInfo.direction;
5033 if (this.multiSort) {
5034 var pn = this.paramNames;
5035 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
5038 this.proxy.load(p, this.reader, this.loadRecords, this, options);
5043 * Reloads the Record cache from the configured Proxy using the configured Reader and
5044 * the options from the last load operation performed.
5045 * @param {Object} options (optional) An object containing properties which may override the options
5046 * used in the last load operation. See {@link #load} for details (defaults to null, in which case
5047 * the most recently used options are reused).
5049 reload : function(options){
5050 this.load(Roo.applyIf(options||{}, this.lastOptions));
5054 // Called as a callback by the Reader during a load operation.
5055 loadRecords : function(o, options, success){
5056 if(!o || success === false){
5057 if(success !== false){
5058 this.fireEvent("load", this, [], options);
5060 if(options.callback){
5061 options.callback.call(options.scope || this, [], options, false);
5065 // if data returned failure - throw an exception.
5066 if (o.success === false) {
5067 // show a message if no listener is registered.
5068 if (!this.hasListener('loadexception') && typeof(this.reader.jsonData.errorMsg) != 'undefined') {
5069 Roo.MessageBox.alert("Error loading",this.reader.jsonData.errorMsg);
5071 // loadmask wil be hooked into this..
5072 this.fireEvent("loadexception", this, o, options, this.reader.jsonData);
5075 var r = o.records, t = o.totalRecords || r.length;
5076 if(!options || options.add !== true){
5077 if(this.pruneModifiedRecords){
5080 for(var i = 0, len = r.length; i < len; i++){
5084 this.data = this.snapshot;
5085 delete this.snapshot;
5088 this.data.addAll(r);
5089 this.totalLength = t;
5091 this.fireEvent("datachanged", this);
5093 this.totalLength = Math.max(t, this.data.length+r.length);
5096 this.fireEvent("load", this, r, options);
5097 if(options.callback){
5098 options.callback.call(options.scope || this, r, options, true);
5104 * Loads data from a passed data block. A Reader which understands the format of the data
5105 * must have been configured in the constructor.
5106 * @param {Object} data The data block from which to read the Records. The format of the data expected
5107 * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
5108 * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
5110 loadData : function(o, append){
5111 var r = this.reader.readRecords(o);
5112 this.loadRecords(r, {add: append}, true);
5116 * Gets the number of cached records.
5118 * <em>If using paging, this may not be the total size of the dataset. If the data object
5119 * used by the Reader contains the dataset size, then the getTotalCount() function returns
5120 * the data set size</em>
5122 getCount : function(){
5123 return this.data.length || 0;
5127 * Gets the total number of records in the dataset as returned by the server.
5129 * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
5130 * the dataset size</em>
5132 getTotalCount : function(){
5133 return this.totalLength || 0;
5137 * Returns the sort state of the Store as an object with two properties:
5139 field {String} The name of the field by which the Records are sorted
5140 direction {String} The sort order, "ASC" or "DESC"
5143 getSortState : function(){
5144 return this.sortInfo;
5148 applySort : function(){
5149 if(this.sortInfo && !this.remoteSort){
5150 var s = this.sortInfo, f = s.field;
5151 var st = this.fields.get(f).sortType;
5152 var fn = function(r1, r2){
5153 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
5154 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
5156 this.data.sort(s.direction, fn);
5157 if(this.snapshot && this.snapshot != this.data){
5158 this.snapshot.sort(s.direction, fn);
5164 * Sets the default sort column and order to be used by the next load operation.
5165 * @param {String} fieldName The name of the field to sort by.
5166 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
5168 setDefaultSort : function(field, dir){
5169 this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
5174 * If remote sorting is used, the sort is performed on the server, and the cache is
5175 * reloaded. If local sorting is used, the cache is sorted internally.
5176 * @param {String} fieldName The name of the field to sort by.
5177 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
5179 sort : function(fieldName, dir){
5180 var f = this.fields.get(fieldName);
5182 this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
5184 if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
5185 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
5190 this.sortToggle[f.name] = dir;
5191 this.sortInfo = {field: f.name, direction: dir};
5192 if(!this.remoteSort){
5194 this.fireEvent("datachanged", this);
5196 this.load(this.lastOptions);
5201 * Calls the specified function for each of the Records in the cache.
5202 * @param {Function} fn The function to call. The Record is passed as the first parameter.
5203 * Returning <em>false</em> aborts and exits the iteration.
5204 * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
5206 each : function(fn, scope){
5207 this.data.each(fn, scope);
5211 * Gets all records modified since the last commit. Modified records are persisted across load operations
5212 * (e.g., during paging).
5213 * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
5215 getModifiedRecords : function(){
5216 return this.modified;
5220 createFilterFn : function(property, value, anyMatch){
5221 if(!value.exec){ // not a regex
5222 value = String(value);
5223 if(value.length == 0){
5226 value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
5229 return value.test(r.data[property]);
5234 * Sums the value of <i>property</i> for each record between start and end and returns the result.
5235 * @param {String} property A field on your records
5236 * @param {Number} start The record index to start at (defaults to 0)
5237 * @param {Number} end The last record index to include (defaults to length - 1)
5238 * @return {Number} The sum
5240 sum : function(property, start, end){
5241 var rs = this.data.items, v = 0;
5243 end = (end || end === 0) ? end : rs.length-1;
5245 for(var i = start; i <= end; i++){
5246 v += (rs[i].data[property] || 0);
5252 * Filter the records by a specified property.
5253 * @param {String} field A field on your records
5254 * @param {String/RegExp} value Either a string that the field
5255 * should start with or a RegExp to test against the field
5256 * @param {Boolean} anyMatch True to match any part not just the beginning
5258 filter : function(property, value, anyMatch){
5259 var fn = this.createFilterFn(property, value, anyMatch);
5260 return fn ? this.filterBy(fn) : this.clearFilter();
5264 * Filter by a function. The specified function will be called with each
5265 * record in this data source. If the function returns true the record is included,
5266 * otherwise it is filtered.
5267 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
5268 * @param {Object} scope (optional) The scope of the function (defaults to this)
5270 filterBy : function(fn, scope){
5271 this.snapshot = this.snapshot || this.data;
5272 this.data = this.queryBy(fn, scope||this);
5273 this.fireEvent("datachanged", this);
5277 * Query the records by a specified property.
5278 * @param {String} field A field on your records
5279 * @param {String/RegExp} value Either a string that the field
5280 * should start with or a RegExp to test against the field
5281 * @param {Boolean} anyMatch True to match any part not just the beginning
5282 * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
5284 query : function(property, value, anyMatch){
5285 var fn = this.createFilterFn(property, value, anyMatch);
5286 return fn ? this.queryBy(fn) : this.data.clone();
5290 * Query by a function. The specified function will be called with each
5291 * record in this data source. If the function returns true the record is included
5293 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
5294 * @param {Object} scope (optional) The scope of the function (defaults to this)
5295 @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
5297 queryBy : function(fn, scope){
5298 var data = this.snapshot || this.data;
5299 return data.filterBy(fn, scope||this);
5303 * Collects unique values for a particular dataIndex from this store.
5304 * @param {String} dataIndex The property to collect
5305 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
5306 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
5307 * @return {Array} An array of the unique values
5309 collect : function(dataIndex, allowNull, bypassFilter){
5310 var d = (bypassFilter === true && this.snapshot) ?
5311 this.snapshot.items : this.data.items;
5312 var v, sv, r = [], l = {};
5313 for(var i = 0, len = d.length; i < len; i++){
5314 v = d[i].data[dataIndex];
5316 if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
5325 * Revert to a view of the Record cache with no filtering applied.
5326 * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
5328 clearFilter : function(suppressEvent){
5329 if(this.snapshot && this.snapshot != this.data){
5330 this.data = this.snapshot;
5331 delete this.snapshot;
5332 if(suppressEvent !== true){
5333 this.fireEvent("datachanged", this);
5339 afterEdit : function(record){
5340 if(this.modified.indexOf(record) == -1){
5341 this.modified.push(record);
5343 this.fireEvent("update", this, record, Roo.data.Record.EDIT);
5347 afterReject : function(record){
5348 this.modified.remove(record);
5349 this.fireEvent("update", this, record, Roo.data.Record.REJECT);
5353 afterCommit : function(record){
5354 this.modified.remove(record);
5355 this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
5359 * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
5360 * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
5362 commitChanges : function(){
5363 var m = this.modified.slice(0);
5365 for(var i = 0, len = m.length; i < len; i++){
5371 * Cancel outstanding changes on all changed records.
5373 rejectChanges : function(){
5374 var m = this.modified.slice(0);
5376 for(var i = 0, len = m.length; i < len; i++){
5381 onMetaChange : function(meta, rtype, o){
5382 this.recordType = rtype;
5383 this.fields = rtype.prototype.fields;
5384 delete this.snapshot;
5385 this.sortInfo = meta.sortInfo || this.sortInfo;
5387 this.fireEvent('metachange', this, this.reader.meta);
5391 * Ext JS Library 1.1.1
5392 * Copyright(c) 2006-2007, Ext JS, LLC.
5394 * Originally Released Under LGPL - original licence link has changed is not relivant.
5397 * <script type="text/javascript">
5401 * @class Roo.data.SimpleStore
5402 * @extends Roo.data.Store
5403 * Small helper class to make creating Stores from Array data easier.
5404 * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
5405 * @cfg {Array} fields An array of field definition objects, or field name strings.
5406 * @cfg {Array} data The multi-dimensional array of data
5408 * @param {Object} config
5410 Roo.data.SimpleStore = function(config){
5411 Roo.data.SimpleStore.superclass.constructor.call(this, {
5413 reader: new Roo.data.ArrayReader({
5416 Roo.data.Record.create(config.fields)
5418 proxy : new Roo.data.MemoryProxy(config.data)
5422 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
5424 * Ext JS Library 1.1.1
5425 * Copyright(c) 2006-2007, Ext JS, LLC.
5427 * Originally Released Under LGPL - original licence link has changed is not relivant.
5430 * <script type="text/javascript">
5435 * @extends Roo.data.Store
5436 * @class Roo.data.JsonStore
5437 * Small helper class to make creating Stores for JSON data easier. <br/>
5439 var store = new Roo.data.JsonStore({
5440 url: 'get-images.php',
5442 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
5445 * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
5446 * JsonReader and HttpProxy (unless inline data is provided).</b>
5447 * @cfg {Array} fields An array of field definition objects, or field name strings.
5449 * @param {Object} config
5451 Roo.data.JsonStore = function(c){
5452 Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
5453 proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
5454 reader: new Roo.data.JsonReader(c, c.fields)
5457 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
5459 * Ext JS Library 1.1.1
5460 * Copyright(c) 2006-2007, Ext JS, LLC.
5462 * Originally Released Under LGPL - original licence link has changed is not relivant.
5465 * <script type="text/javascript">
5469 Roo.data.Field = function(config){
5470 if(typeof config == "string"){
5471 config = {name: config};
5473 Roo.apply(this, config);
5479 var st = Roo.data.SortTypes;
5480 // named sortTypes are supported, here we look them up
5481 if(typeof this.sortType == "string"){
5482 this.sortType = st[this.sortType];
5485 // set default sortType for strings and dates
5489 this.sortType = st.asUCString;
5492 this.sortType = st.asDate;
5495 this.sortType = st.none;
5500 var stripRe = /[\$,%]/g;
5502 // prebuilt conversion function for this field, instead of
5503 // switching every time we're reading a value
5505 var cv, dateFormat = this.dateFormat;
5510 cv = function(v){ return v; };
5513 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
5517 return v !== undefined && v !== null && v !== '' ?
5518 parseInt(String(v).replace(stripRe, ""), 10) : '';
5523 return v !== undefined && v !== null && v !== '' ?
5524 parseFloat(String(v).replace(stripRe, ""), 10) : '';
5529 cv = function(v){ return v === true || v === "true" || v == 1; };
5536 if(v instanceof Date){
5540 if(dateFormat == "timestamp"){
5541 return new Date(v*1000);
5543 return Date.parseDate(v, dateFormat);
5545 var parsed = Date.parse(v);
5546 return parsed ? new Date(parsed) : null;
5555 Roo.data.Field.prototype = {
5563 * Ext JS Library 1.1.1
5564 * Copyright(c) 2006-2007, Ext JS, LLC.
5566 * Originally Released Under LGPL - original licence link has changed is not relivant.
5569 * <script type="text/javascript">
5572 // Base class for reading structured data from a data source. This class is intended to be
5573 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
5576 * @class Roo.data.DataReader
5577 * Base class for reading structured data from a data source. This class is intended to be
5578 * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
5581 Roo.data.DataReader = function(meta, recordType){
5585 this.recordType = recordType instanceof Array ?
5586 Roo.data.Record.create(recordType) : recordType;
5589 Roo.data.DataReader.prototype = {
5591 * Create an empty record
5592 * @param {Object} data (optional) - overlay some values
5593 * @return {Roo.data.Record} record created.
5595 newRow : function(d) {
5597 this.recordType.prototype.fields.each(function(c) {
5599 case 'int' : da[c.name] = 0; break;
5600 case 'date' : da[c.name] = new Date(); break;
5601 case 'float' : da[c.name] = 0.0; break;
5602 case 'boolean' : da[c.name] = false; break;
5603 default : da[c.name] = ""; break;
5607 return new this.recordType(Roo.apply(da, d));
5612 * Ext JS Library 1.1.1
5613 * Copyright(c) 2006-2007, Ext JS, LLC.
5615 * Originally Released Under LGPL - original licence link has changed is not relivant.
5618 * <script type="text/javascript">
5622 * @class Roo.data.DataProxy
5623 * @extends Roo.data.Observable
5624 * This class is an abstract base class for implementations which provide retrieval of
5625 * unformatted data objects.<br>
5627 * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
5628 * (of the appropriate type which knows how to parse the data object) to provide a block of
5629 * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
5631 * Custom implementations must implement the load method as described in
5632 * {@link Roo.data.HttpProxy#load}.
5634 Roo.data.DataProxy = function(){
5638 * Fires before a network request is made to retrieve a data object.
5639 * @param {Object} This DataProxy object.
5640 * @param {Object} params The params parameter to the load function.
5645 * Fires before the load method's callback is called.
5646 * @param {Object} This DataProxy object.
5647 * @param {Object} o The data object.
5648 * @param {Object} arg The callback argument object passed to the load function.
5652 * @event loadexception
5653 * Fires if an Exception occurs during data retrieval.
5654 * @param {Object} This DataProxy object.
5655 * @param {Object} o The data object.
5656 * @param {Object} arg The callback argument object passed to the load function.
5657 * @param {Object} e The Exception.
5659 loadexception : true
5661 Roo.data.DataProxy.superclass.constructor.call(this);
5664 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
5667 * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
5671 * Ext JS Library 1.1.1
5672 * Copyright(c) 2006-2007, Ext JS, LLC.
5674 * Originally Released Under LGPL - original licence link has changed is not relivant.
5677 * <script type="text/javascript">
5680 * @class Roo.data.MemoryProxy
5681 * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
5682 * to the Reader when its load method is called.
5684 * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
5686 Roo.data.MemoryProxy = function(data){
5690 Roo.data.MemoryProxy.superclass.constructor.call(this);
5694 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
5696 * Load data from the requested source (in this case an in-memory
5697 * data object passed to the constructor), read the data object into
5698 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
5699 * process that block using the passed callback.
5700 * @param {Object} params This parameter is not used by the MemoryProxy class.
5701 * @param {Roo.data.DataReader} reader The Reader object which converts the data
5702 * object into a block of Roo.data.Records.
5703 * @param {Function} callback The function into which to pass the block of Roo.data.records.
5704 * The function must be passed <ul>
5705 * <li>The Record block object</li>
5706 * <li>The "arg" argument from the load function</li>
5707 * <li>A boolean success indicator</li>
5709 * @param {Object} scope The scope in which to call the callback
5710 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
5712 load : function(params, reader, callback, scope, arg){
5713 params = params || {};
5716 result = reader.readRecords(this.data);
5718 this.fireEvent("loadexception", this, arg, null, e);
5719 callback.call(scope, null, arg, false);
5722 callback.call(scope, result, arg, true);
5726 update : function(params, records){
5731 * Ext JS Library 1.1.1
5732 * Copyright(c) 2006-2007, Ext JS, LLC.
5734 * Originally Released Under LGPL - original licence link has changed is not relivant.
5737 * <script type="text/javascript">
5740 * @class Roo.data.HttpProxy
5741 * @extends Roo.data.DataProxy
5742 * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
5743 * configured to reference a certain URL.<br><br>
5745 * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
5746 * from which the running page was served.<br><br>
5748 * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
5750 * Be aware that to enable the browser to parse an XML document, the server must set
5751 * the Content-Type header in the HTTP response to "text/xml".
5753 * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
5754 * an {@link Roo.data.Connection} object. If a Connection config is passed, the singleton {@link Roo.Ajax} object
5755 * will be used to make the request.
5757 Roo.data.HttpProxy = function(conn){
5758 Roo.data.HttpProxy.superclass.constructor.call(this);
5759 // is conn a conn config or a real conn?
5761 this.useAjax = !conn || !conn.events;
5765 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
5766 // thse are take from connection...
5769 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
5772 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
5773 * extra parameters to each request made by this object. (defaults to undefined)
5776 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
5777 * to each request made by this object. (defaults to undefined)
5780 * @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
5783 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
5786 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
5792 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
5796 * Return the {@link Roo.data.Connection} object being used by this Proxy.
5797 * @return {Connection} The Connection object. This object may be used to subscribe to events on
5798 * a finer-grained basis than the DataProxy events.
5800 getConnection : function(){
5801 return this.useAjax ? Roo.Ajax : this.conn;
5805 * Load data from the configured {@link Roo.data.Connection}, read the data object into
5806 * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
5807 * process that block using the passed callback.
5808 * @param {Object} params An object containing properties which are to be used as HTTP parameters
5809 * for the request to the remote server.
5810 * @param {Roo.data.DataReader} reader The Reader object which converts the data
5811 * object into a block of Roo.data.Records.
5812 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
5813 * The function must be passed <ul>
5814 * <li>The Record block object</li>
5815 * <li>The "arg" argument from the load function</li>
5816 * <li>A boolean success indicator</li>
5818 * @param {Object} scope The scope in which to call the callback
5819 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
5821 load : function(params, reader, callback, scope, arg){
5822 if(this.fireEvent("beforeload", this, params) !== false){
5824 params : params || {},
5826 callback : callback,
5831 callback : this.loadResponse,
5835 Roo.applyIf(o, this.conn);
5836 if(this.activeRequest){
5837 Roo.Ajax.abort(this.activeRequest);
5839 this.activeRequest = Roo.Ajax.request(o);
5841 this.conn.request(o);
5844 callback.call(scope||this, null, arg, false);
5849 loadResponse : function(o, success, response){
5850 delete this.activeRequest;
5852 this.fireEvent("loadexception", this, o, response);
5853 o.request.callback.call(o.request.scope, null, o.request.arg, false);
5858 result = o.reader.read(response);
5860 this.fireEvent("loadexception", this, o, response, e);
5861 o.request.callback.call(o.request.scope, null, o.request.arg, false);
5865 this.fireEvent("load", this, o, o.request.arg);
5866 o.request.callback.call(o.request.scope, result, o.request.arg, true);
5870 update : function(dataSet){
5875 updateResponse : function(dataSet){
5880 * Ext JS Library 1.1.1
5881 * Copyright(c) 2006-2007, Ext JS, LLC.
5883 * Originally Released Under LGPL - original licence link has changed is not relivant.
5886 * <script type="text/javascript">
5890 * @class Roo.data.ScriptTagProxy
5891 * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
5892 * other than the originating domain of the running page.<br><br>
5894 * <em>Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain
5895 * of the running page, you must use this class, rather than DataProxy.</em><br><br>
5897 * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
5898 * source code that is used as the source inside a <script> tag.<br><br>
5900 * In order for the browser to process the returned data, the server must wrap the data object
5901 * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
5902 * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
5903 * depending on whether the callback name was passed:
5906 boolean scriptTag = false;
5907 String cb = request.getParameter("callback");
5910 response.setContentType("text/javascript");
5912 response.setContentType("application/x-json");
5914 Writer out = response.getWriter();
5916 out.write(cb + "(");
5918 out.print(dataBlock.toJsonString());
5925 * @param {Object} config A configuration object.
5927 Roo.data.ScriptTagProxy = function(config){
5928 Roo.data.ScriptTagProxy.superclass.constructor.call(this);
5929 Roo.apply(this, config);
5930 this.head = document.getElementsByTagName("head")[0];
5933 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
5935 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
5937 * @cfg {String} url The URL from which to request the data object.
5940 * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
5944 * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
5945 * the server the name of the callback function set up by the load call to process the returned data object.
5946 * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
5947 * javascript output which calls this named function passing the data object as its only parameter.
5949 callbackParam : "callback",
5951 * @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
5952 * name to the request.
5957 * Load data from the configured URL, read the data object into
5958 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
5959 * process that block using the passed callback.
5960 * @param {Object} params An object containing properties which are to be used as HTTP parameters
5961 * for the request to the remote server.
5962 * @param {Roo.data.DataReader} reader The Reader object which converts the data
5963 * object into a block of Roo.data.Records.
5964 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
5965 * The function must be passed <ul>
5966 * <li>The Record block object</li>
5967 * <li>The "arg" argument from the load function</li>
5968 * <li>A boolean success indicator</li>
5970 * @param {Object} scope The scope in which to call the callback
5971 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
5973 load : function(params, reader, callback, scope, arg){
5974 if(this.fireEvent("beforeload", this, params) !== false){
5976 var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
5979 url += (url.indexOf("?") != -1 ? "&" : "?") + p;
5981 url += "&_dc=" + (new Date().getTime());
5983 var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
5986 cb : "stcCallback"+transId,
5987 scriptId : "stcScript"+transId,
5991 callback : callback,
5997 window[trans.cb] = function(o){
5998 conn.handleResponse(o, trans);
6001 url += String.format("&{0}={1}", this.callbackParam, trans.cb);
6003 if(this.autoAbort !== false){
6007 trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
6009 var script = document.createElement("script");
6010 script.setAttribute("src", url);
6011 script.setAttribute("type", "text/javascript");
6012 script.setAttribute("id", trans.scriptId);
6013 this.head.appendChild(script);
6017 callback.call(scope||this, null, arg, false);
6022 isLoading : function(){
6023 return this.trans ? true : false;
6027 * Abort the current server request.
6030 if(this.isLoading()){
6031 this.destroyTrans(this.trans);
6036 destroyTrans : function(trans, isLoaded){
6037 this.head.removeChild(document.getElementById(trans.scriptId));
6038 clearTimeout(trans.timeoutId);
6040 window[trans.cb] = undefined;
6042 delete window[trans.cb];
6045 // if hasn't been loaded, wait for load to remove it to prevent script error
6046 window[trans.cb] = function(){
6047 window[trans.cb] = undefined;
6049 delete window[trans.cb];
6056 handleResponse : function(o, trans){
6058 this.destroyTrans(trans, true);
6061 result = trans.reader.readRecords(o);
6063 this.fireEvent("loadexception", this, o, trans.arg, e);
6064 trans.callback.call(trans.scope||window, null, trans.arg, false);
6067 this.fireEvent("load", this, o, trans.arg);
6068 trans.callback.call(trans.scope||window, result, trans.arg, true);
6072 handleFailure : function(trans){
6074 this.destroyTrans(trans, false);
6075 this.fireEvent("loadexception", this, null, trans.arg);
6076 trans.callback.call(trans.scope||window, null, trans.arg, false);
6080 * Ext JS Library 1.1.1
6081 * Copyright(c) 2006-2007, Ext JS, LLC.
6083 * Originally Released Under LGPL - original licence link has changed is not relivant.
6086 * <script type="text/javascript">
6090 * @class Roo.data.JsonReader
6091 * @extends Roo.data.DataReader
6092 * Data reader class to create an Array of Roo.data.Record objects from a JSON response
6093 * based on mappings in a provided Roo.data.Record constructor.
6095 * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
6096 * in the reply previously.
6101 var RecordDef = Roo.data.Record.create([
6102 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
6103 {name: 'occupation'} // This field will use "occupation" as the mapping.
6105 var myReader = new Roo.data.JsonReader({
6106 totalProperty: "results", // The property which contains the total dataset size (optional)
6107 root: "rows", // The property which contains an Array of row objects
6108 id: "id" // The property within each row object that provides an ID for the record (optional)
6112 * This would consume a JSON file like this:
6114 { 'results': 2, 'rows': [
6115 { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
6116 { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
6119 * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
6120 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
6121 * paged from the remote server.
6122 * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
6123 * @cfg {String} root name of the property which contains the Array of row objects.
6124 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
6126 * Create a new JsonReader
6127 * @param {Object} meta Metadata configuration options
6128 * @param {Object} recordType Either an Array of field definition objects,
6129 * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
6131 Roo.data.JsonReader = function(meta, recordType){
6134 // set some defaults:
6136 totalProperty: 'total',
6137 successProperty : 'success',
6142 Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
6144 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
6147 * @prop {Boolean} metaFromRemote - if the meta data was loaded from the remote source.
6148 * Used by Store query builder to append _requestMeta to params.
6151 metaFromRemote : false,
6153 * This method is only used by a DataProxy which has retrieved data from a remote server.
6154 * @param {Object} response The XHR object which contains the JSON data in its responseText.
6155 * @return {Object} data A data block which is used by an Roo.data.Store object as
6156 * a cache of Roo.data.Records.
6158 read : function(response){
6159 var json = response.responseText;
6161 var o = /* eval:var:o */ eval("("+json+")");
6163 throw {message: "JsonReader.read: Json object not found"};
6169 this.metaFromRemote = true;
6170 this.meta = o.metaData;
6171 this.recordType = Roo.data.Record.create(o.metaData.fields);
6172 this.onMetaChange(this.meta, this.recordType, o);
6174 return this.readRecords(o);
6177 // private function a store will implement
6178 onMetaChange : function(meta, recordType, o){
6185 simpleAccess: function(obj, subsc) {
6192 getJsonAccessor: function(){
6194 return function(expr) {
6196 return(re.test(expr))
6197 ? new Function("obj", "return obj." + expr)
6207 * Create a data block containing Roo.data.Records from an XML document.
6208 * @param {Object} o An object which contains an Array of row objects in the property specified
6209 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
6210 * which contains the total size of the dataset.
6211 * @return {Object} data A data block which is used by an Roo.data.Store object as
6212 * a cache of Roo.data.Records.
6214 readRecords : function(o){
6216 * After any data loads, the raw JSON data is available for further custom processing.
6220 var s = this.meta, Record = this.recordType,
6221 f = Record.prototype.fields, fi = f.items, fl = f.length;
6223 // Generate extraction functions for the totalProperty, the root, the id, and for each field
6225 if(s.totalProperty) {
6226 this.getTotal = this.getJsonAccessor(s.totalProperty);
6228 if(s.successProperty) {
6229 this.getSuccess = this.getJsonAccessor(s.successProperty);
6231 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
6233 var g = this.getJsonAccessor(s.id);
6234 this.getId = function(rec) {
6236 return (r === undefined || r === "") ? null : r;
6239 this.getId = function(){return null;};
6242 for(var jj = 0; jj < fl; jj++){
6244 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
6245 this.ef[jj] = this.getJsonAccessor(map);
6249 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
6250 if(s.totalProperty){
6251 var vt = parseInt(this.getTotal(o), 10);
6256 if(s.successProperty){
6257 var vs = this.getSuccess(o);
6258 if(vs === false || vs === 'false'){
6263 for(var i = 0; i < c; i++){
6266 var id = this.getId(n);
6267 for(var j = 0; j < fl; j++){
6269 var v = this.ef[j](n);
6271 Roo.log('missing convert for ' + f.name);
6275 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
6277 var record = new Record(values, id);
6279 records[i] = record;
6284 totalRecords : totalRecords
6289 * Ext JS Library 1.1.1
6290 * Copyright(c) 2006-2007, Ext JS, LLC.
6292 * Originally Released Under LGPL - original licence link has changed is not relivant.
6295 * <script type="text/javascript">
6299 * @class Roo.data.XmlReader
6300 * @extends Roo.data.DataReader
6301 * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
6302 * based on mappings in a provided Roo.data.Record constructor.<br><br>
6304 * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
6305 * header in the HTTP response must be set to "text/xml".</em>
6309 var RecordDef = Roo.data.Record.create([
6310 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
6311 {name: 'occupation'} // This field will use "occupation" as the mapping.
6313 var myReader = new Roo.data.XmlReader({
6314 totalRecords: "results", // The element which contains the total dataset size (optional)
6315 record: "row", // The repeated element which contains row information
6316 id: "id" // The element within the row that provides an ID for the record (optional)
6320 * This would consume an XML file like this:
6324 <results>2</results>
6327 <name>Bill</name>
6328 <occupation>Gardener</occupation>
6332 <name>Ben</name>
6333 <occupation>Horticulturalist</occupation>
6337 * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
6338 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
6339 * paged from the remote server.
6340 * @cfg {String} record The DomQuery path to the repeated element which contains record information.
6341 * @cfg {String} success The DomQuery path to the success attribute used by forms.
6342 * @cfg {String} id The DomQuery path relative from the record element to the element that contains
6343 * a record identifier value.
6345 * Create a new XmlReader
6346 * @param {Object} meta Metadata configuration options
6347 * @param {Mixed} recordType The definition of the data record type to produce. This can be either a valid
6348 * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
6349 * Roo.data.Record.create. See the {@link Roo.data.Record} class for more details.
6351 Roo.data.XmlReader = function(meta, recordType){
6353 Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
6355 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
6357 * This method is only used by a DataProxy which has retrieved data from a remote server.
6358 * @param {Object} response The XHR object which contains the parsed XML document. The response is expected
6359 * to contain a method called 'responseXML' that returns an XML document object.
6360 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
6361 * a cache of Roo.data.Records.
6363 read : function(response){
6364 var doc = response.responseXML;
6366 throw {message: "XmlReader.read: XML Document not available"};
6368 return this.readRecords(doc);
6372 * Create a data block containing Roo.data.Records from an XML document.
6373 * @param {Object} doc A parsed XML document.
6374 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
6375 * a cache of Roo.data.Records.
6377 readRecords : function(doc){
6379 * After any data loads/reads, the raw XML Document is available for further custom processing.
6383 var root = doc.documentElement || doc;
6384 var q = Roo.DomQuery;
6385 var recordType = this.recordType, fields = recordType.prototype.fields;
6386 var sid = this.meta.id;
6387 var totalRecords = 0, success = true;
6388 if(this.meta.totalRecords){
6389 totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
6392 if(this.meta.success){
6393 var sv = q.selectValue(this.meta.success, root, true);
6394 success = sv !== false && sv !== 'false';
6397 var ns = q.select(this.meta.record, root);
6398 for(var i = 0, len = ns.length; i < len; i++) {
6401 var id = sid ? q.selectValue(sid, n) : undefined;
6402 for(var j = 0, jlen = fields.length; j < jlen; j++){
6403 var f = fields.items[j];
6404 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
6408 var record = new recordType(values, id);
6410 records[records.length] = record;
6416 totalRecords : totalRecords || records.length
6421 * Ext JS Library 1.1.1
6422 * Copyright(c) 2006-2007, Ext JS, LLC.
6424 * Originally Released Under LGPL - original licence link has changed is not relivant.
6427 * <script type="text/javascript">
6431 * @class Roo.data.ArrayReader
6432 * @extends Roo.data.DataReader
6433 * Data reader class to create an Array of Roo.data.Record objects from an Array.
6434 * Each element of that Array represents a row of data fields. The
6435 * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
6436 * of the field definition if it exists, or the field's ordinal position in the definition.<br>
6440 var RecordDef = Roo.data.Record.create([
6441 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
6442 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
6444 var myReader = new Roo.data.ArrayReader({
6445 id: 0 // The subscript within row Array that provides an ID for the Record (optional)
6449 * This would consume an Array like this:
6451 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
6453 * @cfg {String} id (optional) The subscript within row Array that provides an ID for the Record
6455 * Create a new JsonReader
6456 * @param {Object} meta Metadata configuration options.
6457 * @param {Object} recordType Either an Array of field definition objects
6458 * as specified to {@link Roo.data.Record#create},
6459 * or an {@link Roo.data.Record} object
6460 * created using {@link Roo.data.Record#create}.
6462 Roo.data.ArrayReader = function(meta, recordType){
6463 Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType);
6466 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
6468 * Create a data block containing Roo.data.Records from an XML document.
6469 * @param {Object} o An Array of row objects which represents the dataset.
6470 * @return {Object} data A data block which is used by an Roo.data.Store object as
6471 * a cache of Roo.data.Records.
6473 readRecords : function(o){
6474 var sid = this.meta ? this.meta.id : null;
6475 var recordType = this.recordType, fields = recordType.prototype.fields;
6478 for(var i = 0; i < root.length; i++){
6481 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
6482 for(var j = 0, jlen = fields.length; j < jlen; j++){
6483 var f = fields.items[j];
6484 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
6485 var v = n[k] !== undefined ? n[k] : f.defaultValue;
6489 var record = new recordType(values, id);
6491 records[records.length] = record;
6495 totalRecords : records.length
6500 * Ext JS Library 1.1.1
6501 * Copyright(c) 2006-2007, Ext JS, LLC.
6503 * Originally Released Under LGPL - original licence link has changed is not relivant.
6506 * <script type="text/javascript">
6511 * @class Roo.data.Tree
6512 * @extends Roo.util.Observable
6513 * Represents a tree data structure and bubbles all the events for its nodes. The nodes
6514 * in the tree have most standard DOM functionality.
6516 * @param {Node} root (optional) The root node
6518 Roo.data.Tree = function(root){
6521 * The root node for this tree
6526 this.setRootNode(root);
6531 * Fires when a new child node is appended to a node in this tree.
6532 * @param {Tree} tree The owner tree
6533 * @param {Node} parent The parent node
6534 * @param {Node} node The newly appended node
6535 * @param {Number} index The index of the newly appended node
6540 * Fires when a child node is removed from a node in this tree.
6541 * @param {Tree} tree The owner tree
6542 * @param {Node} parent The parent node
6543 * @param {Node} node The child node removed
6548 * Fires when a node is moved to a new location in the tree
6549 * @param {Tree} tree The owner tree
6550 * @param {Node} node The node moved
6551 * @param {Node} oldParent The old parent of this node
6552 * @param {Node} newParent The new parent of this node
6553 * @param {Number} index The index it was moved to
6558 * Fires when a new child node is inserted in a node in this tree.
6559 * @param {Tree} tree The owner tree
6560 * @param {Node} parent The parent node
6561 * @param {Node} node The child node inserted
6562 * @param {Node} refNode The child node the node was inserted before
6566 * @event beforeappend
6567 * Fires before a new child is appended to a node in this tree, return false to cancel the append.
6568 * @param {Tree} tree The owner tree
6569 * @param {Node} parent The parent node
6570 * @param {Node} node The child node to be appended
6572 "beforeappend" : true,
6574 * @event beforeremove
6575 * Fires before a child is removed from a node in this tree, return false to cancel the remove.
6576 * @param {Tree} tree The owner tree
6577 * @param {Node} parent The parent node
6578 * @param {Node} node The child node to be removed
6580 "beforeremove" : true,
6583 * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
6584 * @param {Tree} tree The owner tree
6585 * @param {Node} node The node being moved
6586 * @param {Node} oldParent The parent of the node
6587 * @param {Node} newParent The new parent the node is moving to
6588 * @param {Number} index The index it is being moved to
6590 "beforemove" : true,
6592 * @event beforeinsert
6593 * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
6594 * @param {Tree} tree The owner tree
6595 * @param {Node} parent The parent node
6596 * @param {Node} node The child node to be inserted
6597 * @param {Node} refNode The child node the node is being inserted before
6599 "beforeinsert" : true
6602 Roo.data.Tree.superclass.constructor.call(this);
6605 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
6608 proxyNodeEvent : function(){
6609 return this.fireEvent.apply(this, arguments);
6613 * Returns the root node for this tree.
6616 getRootNode : function(){
6621 * Sets the root node for this tree.
6622 * @param {Node} node
6625 setRootNode : function(node){
6627 node.ownerTree = this;
6629 this.registerNode(node);
6634 * Gets a node in this tree by its id.
6635 * @param {String} id
6638 getNodeById : function(id){
6639 return this.nodeHash[id];
6642 registerNode : function(node){
6643 this.nodeHash[node.id] = node;
6646 unregisterNode : function(node){
6647 delete this.nodeHash[node.id];
6650 toString : function(){
6651 return "[Tree"+(this.id?" "+this.id:"")+"]";
6656 * @class Roo.data.Node
6657 * @extends Roo.util.Observable
6658 * @cfg {Boolean} leaf true if this node is a leaf and does not have children
6659 * @cfg {String} id The id for this node. If one is not specified, one is generated.
6661 * @param {Object} attributes The attributes/config for the node
6663 Roo.data.Node = function(attributes){
6665 * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
6668 this.attributes = attributes || {};
6669 this.leaf = this.attributes.leaf;
6671 * The node id. @type String
6673 this.id = this.attributes.id;
6675 this.id = Roo.id(null, "ynode-");
6676 this.attributes.id = this.id;
6681 * All child nodes of this node. @type Array
6683 this.childNodes = [];
6684 if(!this.childNodes.indexOf){ // indexOf is a must
6685 this.childNodes.indexOf = function(o){
6686 for(var i = 0, len = this.length; i < len; i++){
6695 * The parent node for this node. @type Node
6697 this.parentNode = null;
6699 * The first direct child node of this node, or null if this node has no child nodes. @type Node
6701 this.firstChild = null;
6703 * The last direct child node of this node, or null if this node has no child nodes. @type Node
6705 this.lastChild = null;
6707 * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
6709 this.previousSibling = null;
6711 * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
6713 this.nextSibling = null;
6718 * Fires when a new child node is appended
6719 * @param {Tree} tree The owner tree
6720 * @param {Node} this This node
6721 * @param {Node} node The newly appended node
6722 * @param {Number} index The index of the newly appended node
6727 * Fires when a child node is removed
6728 * @param {Tree} tree The owner tree
6729 * @param {Node} this This node
6730 * @param {Node} node The removed node
6735 * Fires when this node is moved to a new location in the tree
6736 * @param {Tree} tree The owner tree
6737 * @param {Node} this This node
6738 * @param {Node} oldParent The old parent of this node
6739 * @param {Node} newParent The new parent of this node
6740 * @param {Number} index The index it was moved to
6745 * Fires when a new child node is inserted.
6746 * @param {Tree} tree The owner tree
6747 * @param {Node} this This node
6748 * @param {Node} node The child node inserted
6749 * @param {Node} refNode The child node the node was inserted before
6753 * @event beforeappend
6754 * Fires before a new child is appended, return false to cancel the append.
6755 * @param {Tree} tree The owner tree
6756 * @param {Node} this This node
6757 * @param {Node} node The child node to be appended
6759 "beforeappend" : true,
6761 * @event beforeremove
6762 * Fires before a child is removed, return false to cancel the remove.
6763 * @param {Tree} tree The owner tree
6764 * @param {Node} this This node
6765 * @param {Node} node The child node to be removed
6767 "beforeremove" : true,
6770 * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
6771 * @param {Tree} tree The owner tree
6772 * @param {Node} this This node
6773 * @param {Node} oldParent The parent of this node
6774 * @param {Node} newParent The new parent this node is moving to
6775 * @param {Number} index The index it is being moved to
6777 "beforemove" : true,
6779 * @event beforeinsert
6780 * Fires before a new child is inserted, return false to cancel the insert.
6781 * @param {Tree} tree The owner tree
6782 * @param {Node} this This node
6783 * @param {Node} node The child node to be inserted
6784 * @param {Node} refNode The child node the node is being inserted before
6786 "beforeinsert" : true
6788 this.listeners = this.attributes.listeners;
6789 Roo.data.Node.superclass.constructor.call(this);
6792 Roo.extend(Roo.data.Node, Roo.util.Observable, {
6793 fireEvent : function(evtName){
6794 // first do standard event for this node
6795 if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
6798 // then bubble it up to the tree if the event wasn't cancelled
6799 var ot = this.getOwnerTree();
6801 if(ot.proxyNodeEvent.apply(ot, arguments) === false){
6809 * Returns true if this node is a leaf
6812 isLeaf : function(){
6813 return this.leaf === true;
6817 setFirstChild : function(node){
6818 this.firstChild = node;
6822 setLastChild : function(node){
6823 this.lastChild = node;
6828 * Returns true if this node is the last child of its parent
6831 isLast : function(){
6832 return (!this.parentNode ? true : this.parentNode.lastChild == this);
6836 * Returns true if this node is the first child of its parent
6839 isFirst : function(){
6840 return (!this.parentNode ? true : this.parentNode.firstChild == this);
6843 hasChildNodes : function(){
6844 return !this.isLeaf() && this.childNodes.length > 0;
6848 * Insert node(s) as the last child node of this node.
6849 * @param {Node/Array} node The node or Array of nodes to append
6850 * @return {Node} The appended node if single append, or null if an array was passed
6852 appendChild : function(node){
6854 if(node instanceof Array){
6856 }else if(arguments.length > 1){
6859 // if passed an array or multiple args do them one by one
6861 for(var i = 0, len = multi.length; i < len; i++) {
6862 this.appendChild(multi[i]);
6865 if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
6868 var index = this.childNodes.length;
6869 var oldParent = node.parentNode;
6870 // it's a move, make sure we move it cleanly
6872 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
6875 oldParent.removeChild(node);
6877 index = this.childNodes.length;
6879 this.setFirstChild(node);
6881 this.childNodes.push(node);
6882 node.parentNode = this;
6883 var ps = this.childNodes[index-1];
6885 node.previousSibling = ps;
6886 ps.nextSibling = node;
6888 node.previousSibling = null;
6890 node.nextSibling = null;
6891 this.setLastChild(node);
6892 node.setOwnerTree(this.getOwnerTree());
6893 this.fireEvent("append", this.ownerTree, this, node, index);
6895 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
6902 * Removes a child node from this node.
6903 * @param {Node} node The node to remove
6904 * @return {Node} The removed node
6906 removeChild : function(node){
6907 var index = this.childNodes.indexOf(node);
6911 if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
6915 // remove it from childNodes collection
6916 this.childNodes.splice(index, 1);
6919 if(node.previousSibling){
6920 node.previousSibling.nextSibling = node.nextSibling;
6922 if(node.nextSibling){
6923 node.nextSibling.previousSibling = node.previousSibling;
6926 // update child refs
6927 if(this.firstChild == node){
6928 this.setFirstChild(node.nextSibling);
6930 if(this.lastChild == node){
6931 this.setLastChild(node.previousSibling);
6934 node.setOwnerTree(null);
6935 // clear any references from the node
6936 node.parentNode = null;
6937 node.previousSibling = null;
6938 node.nextSibling = null;
6939 this.fireEvent("remove", this.ownerTree, this, node);
6944 * Inserts the first node before the second node in this nodes childNodes collection.
6945 * @param {Node} node The node to insert
6946 * @param {Node} refNode The node to insert before (if null the node is appended)
6947 * @return {Node} The inserted node
6949 insertBefore : function(node, refNode){
6950 if(!refNode){ // like standard Dom, refNode can be null for append
6951 return this.appendChild(node);
6954 if(node == refNode){
6958 if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
6961 var index = this.childNodes.indexOf(refNode);
6962 var oldParent = node.parentNode;
6963 var refIndex = index;
6965 // when moving internally, indexes will change after remove
6966 if(oldParent == this && this.childNodes.indexOf(node) < index){
6970 // it's a move, make sure we move it cleanly
6972 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
6975 oldParent.removeChild(node);
6978 this.setFirstChild(node);
6980 this.childNodes.splice(refIndex, 0, node);
6981 node.parentNode = this;
6982 var ps = this.childNodes[refIndex-1];
6984 node.previousSibling = ps;
6985 ps.nextSibling = node;
6987 node.previousSibling = null;
6989 node.nextSibling = refNode;
6990 refNode.previousSibling = node;
6991 node.setOwnerTree(this.getOwnerTree());
6992 this.fireEvent("insert", this.ownerTree, this, node, refNode);
6994 node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
7000 * Returns the child node at the specified index.
7001 * @param {Number} index
7004 item : function(index){
7005 return this.childNodes[index];
7009 * Replaces one child node in this node with another.
7010 * @param {Node} newChild The replacement node
7011 * @param {Node} oldChild The node to replace
7012 * @return {Node} The replaced node
7014 replaceChild : function(newChild, oldChild){
7015 this.insertBefore(newChild, oldChild);
7016 this.removeChild(oldChild);
7021 * Returns the index of a child node
7022 * @param {Node} node
7023 * @return {Number} The index of the node or -1 if it was not found
7025 indexOf : function(child){
7026 return this.childNodes.indexOf(child);
7030 * Returns the tree this node is in.
7033 getOwnerTree : function(){
7034 // if it doesn't have one, look for one
7035 if(!this.ownerTree){
7039 this.ownerTree = p.ownerTree;
7045 return this.ownerTree;
7049 * Returns depth of this node (the root node has a depth of 0)
7052 getDepth : function(){
7055 while(p.parentNode){
7063 setOwnerTree : function(tree){
7064 // if it's move, we need to update everyone
7065 if(tree != this.ownerTree){
7067 this.ownerTree.unregisterNode(this);
7069 this.ownerTree = tree;
7070 var cs = this.childNodes;
7071 for(var i = 0, len = cs.length; i < len; i++) {
7072 cs[i].setOwnerTree(tree);
7075 tree.registerNode(this);
7081 * Returns the path for this node. The path can be used to expand or select this node programmatically.
7082 * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
7083 * @return {String} The path
7085 getPath : function(attr){
7086 attr = attr || "id";
7087 var p = this.parentNode;
7088 var b = [this.attributes[attr]];
7090 b.unshift(p.attributes[attr]);
7093 var sep = this.getOwnerTree().pathSeparator;
7094 return sep + b.join(sep);
7098 * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
7099 * function call will be the scope provided or the current node. The arguments to the function
7100 * will be the args provided or the current node. If the function returns false at any point,
7101 * the bubble is stopped.
7102 * @param {Function} fn The function to call
7103 * @param {Object} scope (optional) The scope of the function (defaults to current node)
7104 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
7106 bubble : function(fn, scope, args){
7109 if(fn.call(scope || p, args || p) === false){
7117 * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
7118 * function call will be the scope provided or the current node. The arguments to the function
7119 * will be the args provided or the current node. If the function returns false at any point,
7120 * the cascade is stopped on that branch.
7121 * @param {Function} fn The function to call
7122 * @param {Object} scope (optional) The scope of the function (defaults to current node)
7123 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
7125 cascade : function(fn, scope, args){
7126 if(fn.call(scope || this, args || this) !== false){
7127 var cs = this.childNodes;
7128 for(var i = 0, len = cs.length; i < len; i++) {
7129 cs[i].cascade(fn, scope, args);
7135 * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
7136 * function call will be the scope provided or the current node. The arguments to the function
7137 * will be the args provided or the current node. If the function returns false at any point,
7138 * the iteration stops.
7139 * @param {Function} fn The function to call
7140 * @param {Object} scope (optional) The scope of the function (defaults to current node)
7141 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
7143 eachChild : function(fn, scope, args){
7144 var cs = this.childNodes;
7145 for(var i = 0, len = cs.length; i < len; i++) {
7146 if(fn.call(scope || this, args || cs[i]) === false){
7153 * Finds the first child that has the attribute with the specified value.
7154 * @param {String} attribute The attribute name
7155 * @param {Mixed} value The value to search for
7156 * @return {Node} The found child or null if none was found
7158 findChild : function(attribute, value){
7159 var cs = this.childNodes;
7160 for(var i = 0, len = cs.length; i < len; i++) {
7161 if(cs[i].attributes[attribute] == value){
7169 * Finds the first child by a custom function. The child matches if the function passed
7171 * @param {Function} fn
7172 * @param {Object} scope (optional)
7173 * @return {Node} The found child or null if none was found
7175 findChildBy : function(fn, scope){
7176 var cs = this.childNodes;
7177 for(var i = 0, len = cs.length; i < len; i++) {
7178 if(fn.call(scope||cs[i], cs[i]) === true){
7186 * Sorts this nodes children using the supplied sort function
7187 * @param {Function} fn
7188 * @param {Object} scope (optional)
7190 sort : function(fn, scope){
7191 var cs = this.childNodes;
7192 var len = cs.length;
7194 var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
7196 for(var i = 0; i < len; i++){
7198 n.previousSibling = cs[i-1];
7199 n.nextSibling = cs[i+1];
7201 this.setFirstChild(n);
7204 this.setLastChild(n);
7211 * Returns true if this node is an ancestor (at any point) of the passed node.
7212 * @param {Node} node
7215 contains : function(node){
7216 return node.isAncestor(this);
7220 * Returns true if the passed node is an ancestor (at any point) of this node.
7221 * @param {Node} node
7224 isAncestor : function(node){
7225 var p = this.parentNode;
7235 toString : function(){
7236 return "[Node"+(this.id?" "+this.id:"")+"]";
7240 * Ext JS Library 1.1.1
7241 * Copyright(c) 2006-2007, Ext JS, LLC.
7243 * Originally Released Under LGPL - original licence link has changed is not relivant.
7246 * <script type="text/javascript">
7251 * @class Roo.ComponentMgr
7252 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
7255 Roo.ComponentMgr = function(){
7256 var all = new Roo.util.MixedCollection();
7260 * Registers a component.
7261 * @param {Roo.Component} c The component
7263 register : function(c){
7268 * Unregisters a component.
7269 * @param {Roo.Component} c The component
7271 unregister : function(c){
7276 * Returns a component by id
7277 * @param {String} id The component id
7284 * Registers a function that will be called when a specified component is added to ComponentMgr
7285 * @param {String} id The component id
7286 * @param {Funtction} fn The callback function
7287 * @param {Object} scope The scope of the callback
7289 onAvailable : function(id, fn, scope){
7290 all.on("add", function(index, o){
7292 fn.call(scope || o, o);
7293 all.un("add", fn, scope);
7300 * Ext JS Library 1.1.1
7301 * Copyright(c) 2006-2007, Ext JS, LLC.
7303 * Originally Released Under LGPL - original licence link has changed is not relivant.
7306 * <script type="text/javascript">
7310 * @class Roo.Component
7311 * @extends Roo.util.Observable
7312 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
7313 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
7314 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
7315 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
7316 * All visual components (widgets) that require rendering into a layout should subclass Component.
7318 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
7319 * element and its id used as the component id. If a string is passed, it is assumed to be the id of an existing element
7320 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
7322 Roo.Component = function(config){
7323 config = config || {};
7324 if(config.tagName || config.dom || typeof config == "string"){ // element object
7325 config = {el: config, id: config.id || config};
7327 this.initialConfig = config;
7329 Roo.apply(this, config);
7333 * Fires after the component is disabled.
7334 * @param {Roo.Component} this
7339 * Fires after the component is enabled.
7340 * @param {Roo.Component} this
7345 * Fires before the component is shown. Return false to stop the show.
7346 * @param {Roo.Component} this
7351 * Fires after the component is shown.
7352 * @param {Roo.Component} this
7357 * Fires before the component is hidden. Return false to stop the hide.
7358 * @param {Roo.Component} this
7363 * Fires after the component is hidden.
7364 * @param {Roo.Component} this
7368 * @event beforerender
7369 * Fires before the component is rendered. Return false to stop the render.
7370 * @param {Roo.Component} this
7372 beforerender : true,
7375 * Fires after the component is rendered.
7376 * @param {Roo.Component} this
7380 * @event beforedestroy
7381 * Fires before the component is destroyed. Return false to stop the destroy.
7382 * @param {Roo.Component} this
7384 beforedestroy : true,
7387 * Fires after the component is destroyed.
7388 * @param {Roo.Component} this
7393 this.id = "ext-comp-" + (++Roo.Component.AUTO_ID);
7395 Roo.ComponentMgr.register(this);
7396 Roo.Component.superclass.constructor.call(this);
7397 this.initComponent();
7398 if(this.renderTo){ // not supported by all components yet. use at your own risk!
7399 this.render(this.renderTo);
7400 delete this.renderTo;
7405 Roo.Component.AUTO_ID = 1000;
7407 Roo.extend(Roo.Component, Roo.util.Observable, {
7409 * @scope Roo.Component.prototype
7411 * true if this component is hidden. Read-only.
7416 * true if this component is disabled. Read-only.
7421 * true if this component has been rendered. Read-only.
7425 /** @cfg {String} disableClass
7426 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
7428 disabledClass : "x-item-disabled",
7429 /** @cfg {Boolean} allowDomMove
7430 * Whether the component can move the Dom node when rendering (defaults to true).
7432 allowDomMove : true,
7433 /** @cfg {String} hideMode
7434 * How this component should hidden. Supported values are
7435 * "visibility" (css visibility), "offsets" (negative offset position) and
7436 * "display" (css display) - defaults to "display".
7438 hideMode: 'display',
7441 ctype : "Roo.Component",
7444 * @cfg {String} actionMode
7445 * which property holds the element that used for hide() / show() / disable() / enable()
7451 getActionEl : function(){
7452 return this[this.actionMode];
7455 initComponent : Roo.emptyFn,
7457 * If this is a lazy rendering component, render it to its container element.
7458 * @param {String/HTMLElement/Element} container (optional) The element this component should be rendered into. If it is being applied to existing markup, this should be left off.
7460 render : function(container, position){
7461 if(!this.rendered && this.fireEvent("beforerender", this) !== false){
7462 if(!container && this.el){
7463 this.el = Roo.get(this.el);
7464 container = this.el.dom.parentNode;
7465 this.allowDomMove = false;
7467 this.container = Roo.get(container);
7468 this.rendered = true;
7469 if(position !== undefined){
7470 if(typeof position == 'number'){
7471 position = this.container.dom.childNodes[position];
7473 position = Roo.getDom(position);
7476 this.onRender(this.container, position || null);
7478 this.el.addClass(this.cls);
7482 this.el.applyStyles(this.style);
7485 this.fireEvent("render", this);
7486 this.afterRender(this.container);
7498 // default function is not really useful
7499 onRender : function(ct, position){
7501 this.el = Roo.get(this.el);
7502 if(this.allowDomMove !== false){
7503 ct.dom.insertBefore(this.el.dom, position);
7509 getAutoCreate : function(){
7510 var cfg = typeof this.autoCreate == "object" ?
7511 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
7512 if(this.id && !cfg.id){
7519 afterRender : Roo.emptyFn,
7522 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
7523 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
7525 destroy : function(){
7526 if(this.fireEvent("beforedestroy", this) !== false){
7527 this.purgeListeners();
7528 this.beforeDestroy();
7530 this.el.removeAllListeners();
7532 if(this.actionMode == "container"){
7533 this.container.remove();
7537 Roo.ComponentMgr.unregister(this);
7538 this.fireEvent("destroy", this);
7543 beforeDestroy : function(){
7548 onDestroy : function(){
7553 * Returns the underlying {@link Roo.Element}.
7554 * @return {Roo.Element} The element
7561 * Returns the id of this component.
7569 * Try to focus this component.
7570 * @param {Boolean} selectText True to also select the text in this component (if applicable)
7571 * @return {Roo.Component} this
7573 focus : function(selectText){
7576 if(selectText === true){
7577 this.el.dom.select();
7592 * Disable this component.
7593 * @return {Roo.Component} this
7595 disable : function(){
7599 this.disabled = true;
7600 this.fireEvent("disable", this);
7605 onDisable : function(){
7606 this.getActionEl().addClass(this.disabledClass);
7607 this.el.dom.disabled = true;
7611 * Enable this component.
7612 * @return {Roo.Component} this
7614 enable : function(){
7618 this.disabled = false;
7619 this.fireEvent("enable", this);
7624 onEnable : function(){
7625 this.getActionEl().removeClass(this.disabledClass);
7626 this.el.dom.disabled = false;
7630 * Convenience function for setting disabled/enabled by boolean.
7631 * @param {Boolean} disabled
7633 setDisabled : function(disabled){
7634 this[disabled ? "disable" : "enable"]();
7638 * Show this component.
7639 * @return {Roo.Component} this
7642 if(this.fireEvent("beforeshow", this) !== false){
7643 this.hidden = false;
7647 this.fireEvent("show", this);
7653 onShow : function(){
7654 var ae = this.getActionEl();
7655 if(this.hideMode == 'visibility'){
7656 ae.dom.style.visibility = "visible";
7657 }else if(this.hideMode == 'offsets'){
7658 ae.removeClass('x-hidden');
7660 ae.dom.style.display = "";
7665 * Hide this component.
7666 * @return {Roo.Component} this
7669 if(this.fireEvent("beforehide", this) !== false){
7674 this.fireEvent("hide", this);
7680 onHide : function(){
7681 var ae = this.getActionEl();
7682 if(this.hideMode == 'visibility'){
7683 ae.dom.style.visibility = "hidden";
7684 }else if(this.hideMode == 'offsets'){
7685 ae.addClass('x-hidden');
7687 ae.dom.style.display = "none";
7692 * Convenience function to hide or show this component by boolean.
7693 * @param {Boolean} visible True to show, false to hide
7694 * @return {Roo.Component} this
7696 setVisible: function(visible){
7706 * Returns true if this component is visible.
7708 isVisible : function(){
7709 return this.getActionEl().isVisible();
7712 cloneConfig : function(overrides){
7713 overrides = overrides || {};
7714 var id = overrides.id || Roo.id();
7715 var cfg = Roo.applyIf(overrides, this.initialConfig);
7716 cfg.id = id; // prevent dup id
7717 return new this.constructor(cfg);
7721 * Ext JS Library 1.1.1
7722 * Copyright(c) 2006-2007, Ext JS, LLC.
7724 * Originally Released Under LGPL - original licence link has changed is not relivant.
7727 * <script type="text/javascript">
7732 * @extends Roo.Element
7733 * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
7734 * automatic maintaining of shadow/shim positions.
7735 * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
7736 * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
7737 * you can pass a string with a CSS class name. False turns off the shadow.
7738 * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
7739 * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
7740 * @cfg {String} cls CSS class to add to the element
7741 * @cfg {Number} zindex Starting z-index (defaults to 11000)
7742 * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
7744 * @param {Object} config An object with config options.
7745 * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
7748 Roo.Layer = function(config, existingEl){
7749 config = config || {};
7750 var dh = Roo.DomHelper;
7751 var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
7753 this.dom = Roo.getDom(existingEl);
7756 var o = config.dh || {tag: "div", cls: "x-layer"};
7757 this.dom = dh.append(pel, o);
7760 this.addClass(config.cls);
7762 this.constrain = config.constrain !== false;
7763 this.visibilityMode = Roo.Element.VISIBILITY;
7765 this.id = this.dom.id = config.id;
7767 this.id = Roo.id(this.dom);
7769 this.zindex = config.zindex || this.getZIndex();
7770 this.position("absolute", this.zindex);
7772 this.shadowOffset = config.shadowOffset || 4;
7773 this.shadow = new Roo.Shadow({
7774 offset : this.shadowOffset,
7775 mode : config.shadow
7778 this.shadowOffset = 0;
7780 this.useShim = config.shim !== false && Roo.useShims;
7781 this.useDisplay = config.useDisplay;
7785 var supr = Roo.Element.prototype;
7787 // shims are shared among layer to keep from having 100 iframes
7790 Roo.extend(Roo.Layer, Roo.Element, {
7792 getZIndex : function(){
7793 return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
7796 getShim : function(){
7803 var shim = shims.shift();
7805 shim = this.createShim();
7806 shim.enableDisplayMode('block');
7807 shim.dom.style.display = 'none';
7808 shim.dom.style.visibility = 'visible';
7810 var pn = this.dom.parentNode;
7811 if(shim.dom.parentNode != pn){
7812 pn.insertBefore(shim.dom, this.dom);
7814 shim.setStyle('z-index', this.getZIndex()-2);
7819 hideShim : function(){
7821 this.shim.setDisplayed(false);
7822 shims.push(this.shim);
7827 disableShadow : function(){
7829 this.shadowDisabled = true;
7831 this.lastShadowOffset = this.shadowOffset;
7832 this.shadowOffset = 0;
7836 enableShadow : function(show){
7838 this.shadowDisabled = false;
7839 this.shadowOffset = this.lastShadowOffset;
7840 delete this.lastShadowOffset;
7848 // this code can execute repeatedly in milliseconds (i.e. during a drag) so
7849 // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
7850 sync : function(doShow){
7851 var sw = this.shadow;
7852 if(!this.updating && this.isVisible() && (sw || this.useShim)){
7853 var sh = this.getShim();
7855 var w = this.getWidth(),
7856 h = this.getHeight();
7858 var l = this.getLeft(true),
7859 t = this.getTop(true);
7861 if(sw && !this.shadowDisabled){
7862 if(doShow && !sw.isVisible()){
7865 sw.realign(l, t, w, h);
7871 // fit the shim behind the shadow, so it is shimmed too
7872 var a = sw.adjusts, s = sh.dom.style;
7873 s.left = (Math.min(l, l+a.l))+"px";
7874 s.top = (Math.min(t, t+a.t))+"px";
7875 s.width = (w+a.w)+"px";
7876 s.height = (h+a.h)+"px";
7883 sh.setLeftTop(l, t);
7890 destroy : function(){
7895 this.removeAllListeners();
7896 var pn = this.dom.parentNode;
7898 pn.removeChild(this.dom);
7900 Roo.Element.uncache(this.id);
7903 remove : function(){
7908 beginUpdate : function(){
7909 this.updating = true;
7913 endUpdate : function(){
7914 this.updating = false;
7919 hideUnders : function(negOffset){
7927 constrainXY : function(){
7929 var vw = Roo.lib.Dom.getViewWidth(),
7930 vh = Roo.lib.Dom.getViewHeight();
7931 var s = Roo.get(document).getScroll();
7933 var xy = this.getXY();
7934 var x = xy[0], y = xy[1];
7935 var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
7936 // only move it if it needs it
7938 // first validate right/bottom
7939 if((x + w) > vw+s.left){
7940 x = vw - w - this.shadowOffset;
7943 if((y + h) > vh+s.top){
7944 y = vh - h - this.shadowOffset;
7947 // then make sure top/left isn't negative
7958 var ay = this.avoidY;
7959 if(y <= ay && (y+h) >= ay){
7965 supr.setXY.call(this, xy);
7971 isVisible : function(){
7972 return this.visible;
7976 showAction : function(){
7977 this.visible = true; // track visibility to prevent getStyle calls
7978 if(this.useDisplay === true){
7979 this.setDisplayed("");
7980 }else if(this.lastXY){
7981 supr.setXY.call(this, this.lastXY);
7982 }else if(this.lastLT){
7983 supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
7988 hideAction : function(){
7989 this.visible = false;
7990 if(this.useDisplay === true){
7991 this.setDisplayed(false);
7993 this.setLeftTop(-10000,-10000);
7997 // overridden Element method
7998 setVisible : function(v, a, d, c, e){
8003 var cb = function(){
8008 }.createDelegate(this);
8009 supr.setVisible.call(this, true, true, d, cb, e);
8012 this.hideUnders(true);
8021 }.createDelegate(this);
8023 supr.setVisible.call(this, v, a, d, cb, e);
8032 storeXY : function(xy){
8037 storeLeftTop : function(left, top){
8039 this.lastLT = [left, top];
8043 beforeFx : function(){
8044 this.beforeAction();
8045 return Roo.Layer.superclass.beforeFx.apply(this, arguments);
8049 afterFx : function(){
8050 Roo.Layer.superclass.afterFx.apply(this, arguments);
8051 this.sync(this.isVisible());
8055 beforeAction : function(){
8056 if(!this.updating && this.shadow){
8061 // overridden Element method
8062 setLeft : function(left){
8063 this.storeLeftTop(left, this.getTop(true));
8064 supr.setLeft.apply(this, arguments);
8068 setTop : function(top){
8069 this.storeLeftTop(this.getLeft(true), top);
8070 supr.setTop.apply(this, arguments);
8074 setLeftTop : function(left, top){
8075 this.storeLeftTop(left, top);
8076 supr.setLeftTop.apply(this, arguments);
8080 setXY : function(xy, a, d, c, e){
8082 this.beforeAction();
8084 var cb = this.createCB(c);
8085 supr.setXY.call(this, xy, a, d, cb, e);
8092 createCB : function(c){
8103 // overridden Element method
8104 setX : function(x, a, d, c, e){
8105 this.setXY([x, this.getY()], a, d, c, e);
8108 // overridden Element method
8109 setY : function(y, a, d, c, e){
8110 this.setXY([this.getX(), y], a, d, c, e);
8113 // overridden Element method
8114 setSize : function(w, h, a, d, c, e){
8115 this.beforeAction();
8116 var cb = this.createCB(c);
8117 supr.setSize.call(this, w, h, a, d, cb, e);
8123 // overridden Element method
8124 setWidth : function(w, a, d, c, e){
8125 this.beforeAction();
8126 var cb = this.createCB(c);
8127 supr.setWidth.call(this, w, a, d, cb, e);
8133 // overridden Element method
8134 setHeight : function(h, a, d, c, e){
8135 this.beforeAction();
8136 var cb = this.createCB(c);
8137 supr.setHeight.call(this, h, a, d, cb, e);
8143 // overridden Element method
8144 setBounds : function(x, y, w, h, a, d, c, e){
8145 this.beforeAction();
8146 var cb = this.createCB(c);
8148 this.storeXY([x, y]);
8149 supr.setXY.call(this, [x, y]);
8150 supr.setSize.call(this, w, h, a, d, cb, e);
8153 supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
8159 * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
8160 * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
8161 * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
8162 * @param {Number} zindex The new z-index to set
8163 * @return {this} The Layer
8165 setZIndex : function(zindex){
8166 this.zindex = zindex;
8167 this.setStyle("z-index", zindex + 2);
8169 this.shadow.setZIndex(zindex + 1);
8172 this.shim.setStyle("z-index", zindex);
8178 * Ext JS Library 1.1.1
8179 * Copyright(c) 2006-2007, Ext JS, LLC.
8181 * Originally Released Under LGPL - original licence link has changed is not relivant.
8184 * <script type="text/javascript">
8190 * Simple class that can provide a shadow effect for any element. Note that the element MUST be absolutely positioned,
8191 * and the shadow does not provide any shimming. This should be used only in simple cases -- for more advanced
8192 * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
8194 * Create a new Shadow
8195 * @param {Object} config The config object
8197 Roo.Shadow = function(config){
8198 Roo.apply(this, config);
8199 if(typeof this.mode != "string"){
8200 this.mode = this.defaultMode;
8202 var o = this.offset, a = {h: 0};
8203 var rad = Math.floor(this.offset/2);
8204 switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
8210 a.l -= this.offset + rad;
8211 a.t -= this.offset + rad;
8222 a.l -= (this.offset - rad);
8223 a.t -= this.offset + rad;
8225 a.w -= (this.offset - rad)*2;
8236 a.l -= (this.offset - rad);
8237 a.t -= (this.offset - rad);
8239 a.w -= (this.offset + rad + 1);
8240 a.h -= (this.offset + rad);
8249 Roo.Shadow.prototype = {
8251 * @cfg {String} mode
8252 * The shadow display mode. Supports the following options:<br />
8253 * sides: Shadow displays on both sides and bottom only<br />
8254 * frame: Shadow displays equally on all four sides<br />
8255 * drop: Traditional bottom-right drop shadow (default)
8258 * @cfg {String} offset
8259 * The number of pixels to offset the shadow from the element (defaults to 4)
8264 defaultMode: "drop",
8267 * Displays the shadow under the target element
8268 * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
8270 show : function(target){
8271 target = Roo.get(target);
8273 this.el = Roo.Shadow.Pool.pull();
8274 if(this.el.dom.nextSibling != target.dom){
8275 this.el.insertBefore(target);
8278 this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
8280 this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
8283 target.getLeft(true),
8284 target.getTop(true),
8288 this.el.dom.style.display = "block";
8292 * Returns true if the shadow is visible, else false
8294 isVisible : function(){
8295 return this.el ? true : false;
8299 * Direct alignment when values are already available. Show must be called at least once before
8300 * calling this method to ensure it is initialized.
8301 * @param {Number} left The target element left position
8302 * @param {Number} top The target element top position
8303 * @param {Number} width The target element width
8304 * @param {Number} height The target element height
8306 realign : function(l, t, w, h){
8310 var a = this.adjusts, d = this.el.dom, s = d.style;
8312 s.left = (l+a.l)+"px";
8313 s.top = (t+a.t)+"px";
8314 var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
8316 if(s.width != sws || s.height != shs){
8320 var cn = d.childNodes;
8321 var sww = Math.max(0, (sw-12))+"px";
8322 cn[0].childNodes[1].style.width = sww;
8323 cn[1].childNodes[1].style.width = sww;
8324 cn[2].childNodes[1].style.width = sww;
8325 cn[1].style.height = Math.max(0, (sh-12))+"px";
8335 this.el.dom.style.display = "none";
8336 Roo.Shadow.Pool.push(this.el);
8342 * Adjust the z-index of this shadow
8343 * @param {Number} zindex The new z-index
8345 setZIndex : function(z){
8348 this.el.setStyle("z-index", z);
8353 // Private utility class that manages the internal Shadow cache
8354 Roo.Shadow.Pool = function(){
8356 var markup = Roo.isIE ?
8357 '<div class="x-ie-shadow"></div>' :
8358 '<div class="x-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>';
8363 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
8364 sh.autoBoxAdjust = false;
8369 push : function(sh){
8375 * Ext JS Library 1.1.1
8376 * Copyright(c) 2006-2007, Ext JS, LLC.
8378 * Originally Released Under LGPL - original licence link has changed is not relivant.
8381 * <script type="text/javascript">
8385 * @class Roo.BoxComponent
8386 * @extends Roo.Component
8387 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
8388 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
8389 * container classes should subclass BoxComponent so that they will work consistently when nested within other Ext
8390 * layout containers.
8392 * @param {Roo.Element/String/Object} config The configuration options.
8394 Roo.BoxComponent = function(config){
8395 Roo.Component.call(this, config);
8399 * Fires after the component is resized.
8400 * @param {Roo.Component} this
8401 * @param {Number} adjWidth The box-adjusted width that was set
8402 * @param {Number} adjHeight The box-adjusted height that was set
8403 * @param {Number} rawWidth The width that was originally specified
8404 * @param {Number} rawHeight The height that was originally specified
8409 * Fires after the component is moved.
8410 * @param {Roo.Component} this
8411 * @param {Number} x The new x position
8412 * @param {Number} y The new y position
8418 Roo.extend(Roo.BoxComponent, Roo.Component, {
8419 // private, set in afterRender to signify that the component has been rendered
8421 // private, used to defer height settings to subclasses
8423 /** @cfg {Number} width
8424 * width (optional) size of component
8426 /** @cfg {Number} height
8427 * height (optional) size of component
8431 * Sets the width and height of the component. This method fires the resize event. This method can accept
8432 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
8433 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
8434 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
8435 * @return {Roo.BoxComponent} this
8437 setSize : function(w, h){
8438 // support for standard size objects
8439 if(typeof w == 'object'){
8450 // prevent recalcs when not needed
8451 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
8454 this.lastSize = {width: w, height: h};
8456 var adj = this.adjustSize(w, h);
8457 var aw = adj.width, ah = adj.height;
8458 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
8459 var rz = this.getResizeEl();
8460 if(!this.deferHeight && aw !== undefined && ah !== undefined){
8462 }else if(!this.deferHeight && ah !== undefined){
8464 }else if(aw !== undefined){
8467 this.onResize(aw, ah, w, h);
8468 this.fireEvent('resize', this, aw, ah, w, h);
8474 * Gets the current size of the component's underlying element.
8475 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
8477 getSize : function(){
8478 return this.el.getSize();
8482 * Gets the current XY position of the component's underlying element.
8483 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
8484 * @return {Array} The XY position of the element (e.g., [100, 200])
8486 getPosition : function(local){
8488 return [this.el.getLeft(true), this.el.getTop(true)];
8490 return this.xy || this.el.getXY();
8494 * Gets the current box measurements of the component's underlying element.
8495 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
8496 * @returns {Object} box An object in the format {x, y, width, height}
8498 getBox : function(local){
8499 var s = this.el.getSize();
8501 s.x = this.el.getLeft(true);
8502 s.y = this.el.getTop(true);
8504 var xy = this.xy || this.el.getXY();
8512 * Sets the current box measurements of the component's underlying element.
8513 * @param {Object} box An object in the format {x, y, width, height}
8514 * @returns {Roo.BoxComponent} this
8516 updateBox : function(box){
8517 this.setSize(box.width, box.height);
8518 this.setPagePosition(box.x, box.y);
8523 getResizeEl : function(){
8524 return this.resizeEl || this.el;
8528 getPositionEl : function(){
8529 return this.positionEl || this.el;
8533 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
8534 * This method fires the move event.
8535 * @param {Number} left The new left
8536 * @param {Number} top The new top
8537 * @returns {Roo.BoxComponent} this
8539 setPosition : function(x, y){
8545 var adj = this.adjustPosition(x, y);
8546 var ax = adj.x, ay = adj.y;
8548 var el = this.getPositionEl();
8549 if(ax !== undefined || ay !== undefined){
8550 if(ax !== undefined && ay !== undefined){
8551 el.setLeftTop(ax, ay);
8552 }else if(ax !== undefined){
8554 }else if(ay !== undefined){
8557 this.onPosition(ax, ay);
8558 this.fireEvent('move', this, ax, ay);
8564 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
8565 * This method fires the move event.
8566 * @param {Number} x The new x position
8567 * @param {Number} y The new y position
8568 * @returns {Roo.BoxComponent} this
8570 setPagePosition : function(x, y){
8576 if(x === undefined || y === undefined){ // cannot translate undefined points
8579 var p = this.el.translatePoints(x, y);
8580 this.setPosition(p.left, p.top);
8585 onRender : function(ct, position){
8586 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
8588 this.resizeEl = Roo.get(this.resizeEl);
8590 if(this.positionEl){
8591 this.positionEl = Roo.get(this.positionEl);
8596 afterRender : function(){
8597 Roo.BoxComponent.superclass.afterRender.call(this);
8598 this.boxReady = true;
8599 this.setSize(this.width, this.height);
8600 if(this.x || this.y){
8601 this.setPosition(this.x, this.y);
8603 if(this.pageX || this.pageY){
8604 this.setPagePosition(this.pageX, this.pageY);
8609 * Force the component's size to recalculate based on the underlying element's current height and width.
8610 * @returns {Roo.BoxComponent} this
8612 syncSize : function(){
8613 delete this.lastSize;
8614 this.setSize(this.el.getWidth(), this.el.getHeight());
8619 * Called after the component is resized, this method is empty by default but can be implemented by any
8620 * subclass that needs to perform custom logic after a resize occurs.
8621 * @param {Number} adjWidth The box-adjusted width that was set
8622 * @param {Number} adjHeight The box-adjusted height that was set
8623 * @param {Number} rawWidth The width that was originally specified
8624 * @param {Number} rawHeight The height that was originally specified
8626 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
8631 * Called after the component is moved, this method is empty by default but can be implemented by any
8632 * subclass that needs to perform custom logic after a move occurs.
8633 * @param {Number} x The new x position
8634 * @param {Number} y The new y position
8636 onPosition : function(x, y){
8641 adjustSize : function(w, h){
8645 if(this.autoHeight){
8648 return {width : w, height: h};
8652 adjustPosition : function(x, y){
8653 return {x : x, y: y};
8657 * Ext JS Library 1.1.1
8658 * Copyright(c) 2006-2007, Ext JS, LLC.
8660 * Originally Released Under LGPL - original licence link has changed is not relivant.
8663 * <script type="text/javascript">
8668 * @class Roo.SplitBar
8669 * @extends Roo.util.Observable
8670 * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
8674 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
8675 Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
8676 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
8677 split.minSize = 100;
8678 split.maxSize = 600;
8679 split.animate = true;
8680 split.on('moved', splitterMoved);
8683 * Create a new SplitBar
8684 * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar.
8685 * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged
8686 * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
8687 * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or
8688 Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
8689 position of the SplitBar).
8691 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
8694 this.el = Roo.get(dragElement, true);
8695 this.el.dom.unselectable = "on";
8697 this.resizingEl = Roo.get(resizingElement, true);
8701 * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
8702 * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
8705 this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
8708 * The minimum size of the resizing element. (Defaults to 0)
8714 * The maximum size of the resizing element. (Defaults to 2000)
8717 this.maxSize = 2000;
8720 * Whether to animate the transition to the new size
8723 this.animate = false;
8726 * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
8729 this.useShim = false;
8736 this.proxy = Roo.SplitBar.createProxy(this.orientation);
8738 this.proxy = Roo.get(existingProxy).dom;
8741 this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
8744 this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
8747 this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
8750 this.dragSpecs = {};
8753 * @private The adapter to use to positon and resize elements
8755 this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
8756 this.adapter.init(this);
8758 if(this.orientation == Roo.SplitBar.HORIZONTAL){
8760 this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
8761 this.el.addClass("x-splitbar-h");
8764 this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
8765 this.el.addClass("x-splitbar-v");
8771 * Fires when the splitter is moved (alias for {@link #event-moved})
8772 * @param {Roo.SplitBar} this
8773 * @param {Number} newSize the new width or height
8778 * Fires when the splitter is moved
8779 * @param {Roo.SplitBar} this
8780 * @param {Number} newSize the new width or height
8784 * @event beforeresize
8785 * Fires before the splitter is dragged
8786 * @param {Roo.SplitBar} this
8788 "beforeresize" : true,
8790 "beforeapply" : true
8793 Roo.util.Observable.call(this);
8796 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
8797 onStartProxyDrag : function(x, y){
8798 this.fireEvent("beforeresize", this);
8800 var o = Roo.DomHelper.insertFirst(document.body, {cls: "x-drag-overlay", html: " "}, true);
8802 o.enableDisplayMode("block");
8803 // all splitbars share the same overlay
8804 Roo.SplitBar.prototype.overlay = o;
8806 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
8807 this.overlay.show();
8808 Roo.get(this.proxy).setDisplayed("block");
8809 var size = this.adapter.getElementSize(this);
8810 this.activeMinSize = this.getMinimumSize();;
8811 this.activeMaxSize = this.getMaximumSize();;
8812 var c1 = size - this.activeMinSize;
8813 var c2 = Math.max(this.activeMaxSize - size, 0);
8814 if(this.orientation == Roo.SplitBar.HORIZONTAL){
8815 this.dd.resetConstraints();
8816 this.dd.setXConstraint(
8817 this.placement == Roo.SplitBar.LEFT ? c1 : c2,
8818 this.placement == Roo.SplitBar.LEFT ? c2 : c1
8820 this.dd.setYConstraint(0, 0);
8822 this.dd.resetConstraints();
8823 this.dd.setXConstraint(0, 0);
8824 this.dd.setYConstraint(
8825 this.placement == Roo.SplitBar.TOP ? c1 : c2,
8826 this.placement == Roo.SplitBar.TOP ? c2 : c1
8829 this.dragSpecs.startSize = size;
8830 this.dragSpecs.startPoint = [x, y];
8831 Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
8835 * @private Called after the drag operation by the DDProxy
8837 onEndProxyDrag : function(e){
8838 Roo.get(this.proxy).setDisplayed(false);
8839 var endPoint = Roo.lib.Event.getXY(e);
8841 this.overlay.hide();
8844 if(this.orientation == Roo.SplitBar.HORIZONTAL){
8845 newSize = this.dragSpecs.startSize +
8846 (this.placement == Roo.SplitBar.LEFT ?
8847 endPoint[0] - this.dragSpecs.startPoint[0] :
8848 this.dragSpecs.startPoint[0] - endPoint[0]
8851 newSize = this.dragSpecs.startSize +
8852 (this.placement == Roo.SplitBar.TOP ?
8853 endPoint[1] - this.dragSpecs.startPoint[1] :
8854 this.dragSpecs.startPoint[1] - endPoint[1]
8857 newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
8858 if(newSize != this.dragSpecs.startSize){
8859 if(this.fireEvent('beforeapply', this, newSize) !== false){
8860 this.adapter.setElementSize(this, newSize);
8861 this.fireEvent("moved", this, newSize);
8862 this.fireEvent("resize", this, newSize);
8868 * Get the adapter this SplitBar uses
8869 * @return The adapter object
8871 getAdapter : function(){
8872 return this.adapter;
8876 * Set the adapter this SplitBar uses
8877 * @param {Object} adapter A SplitBar adapter object
8879 setAdapter : function(adapter){
8880 this.adapter = adapter;
8881 this.adapter.init(this);
8885 * Gets the minimum size for the resizing element
8886 * @return {Number} The minimum size
8888 getMinimumSize : function(){
8889 return this.minSize;
8893 * Sets the minimum size for the resizing element
8894 * @param {Number} minSize The minimum size
8896 setMinimumSize : function(minSize){
8897 this.minSize = minSize;
8901 * Gets the maximum size for the resizing element
8902 * @return {Number} The maximum size
8904 getMaximumSize : function(){
8905 return this.maxSize;
8909 * Sets the maximum size for the resizing element
8910 * @param {Number} maxSize The maximum size
8912 setMaximumSize : function(maxSize){
8913 this.maxSize = maxSize;
8917 * Sets the initialize size for the resizing element
8918 * @param {Number} size The initial size
8920 setCurrentSize : function(size){
8921 var oldAnimate = this.animate;
8922 this.animate = false;
8923 this.adapter.setElementSize(this, size);
8924 this.animate = oldAnimate;
8928 * Destroy this splitbar.
8929 * @param {Boolean} removeEl True to remove the element
8931 destroy : function(removeEl){
8936 this.proxy.parentNode.removeChild(this.proxy);
8944 * @private static Create our own proxy element element. So it will be the same same size on all browsers, we won't use borders. Instead we use a background color.
8946 Roo.SplitBar.createProxy = function(dir){
8947 var proxy = new Roo.Element(document.createElement("div"));
8948 proxy.unselectable();
8949 var cls = 'x-splitbar-proxy';
8950 proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
8951 document.body.appendChild(proxy.dom);
8956 * @class Roo.SplitBar.BasicLayoutAdapter
8957 * Default Adapter. It assumes the splitter and resizing element are not positioned
8958 * elements and only gets/sets the width of the element. Generally used for table based layouts.
8960 Roo.SplitBar.BasicLayoutAdapter = function(){
8963 Roo.SplitBar.BasicLayoutAdapter.prototype = {
8964 // do nothing for now
8969 * Called before drag operations to get the current size of the resizing element.
8970 * @param {Roo.SplitBar} s The SplitBar using this adapter
8972 getElementSize : function(s){
8973 if(s.orientation == Roo.SplitBar.HORIZONTAL){
8974 return s.resizingEl.getWidth();
8976 return s.resizingEl.getHeight();
8981 * Called after drag operations to set the size of the resizing element.
8982 * @param {Roo.SplitBar} s The SplitBar using this adapter
8983 * @param {Number} newSize The new size to set
8984 * @param {Function} onComplete A function to be invoked when resizing is complete
8986 setElementSize : function(s, newSize, onComplete){
8987 if(s.orientation == Roo.SplitBar.HORIZONTAL){
8989 s.resizingEl.setWidth(newSize);
8991 onComplete(s, newSize);
8994 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
8999 s.resizingEl.setHeight(newSize);
9001 onComplete(s, newSize);
9004 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
9011 *@class Roo.SplitBar.AbsoluteLayoutAdapter
9012 * @extends Roo.SplitBar.BasicLayoutAdapter
9013 * Adapter that moves the splitter element to align with the resized sizing element.
9014 * Used with an absolute positioned SplitBar.
9015 * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
9016 * document.body, make sure you assign an id to the body element.
9018 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
9019 this.basic = new Roo.SplitBar.BasicLayoutAdapter();
9020 this.container = Roo.get(container);
9023 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
9028 getElementSize : function(s){
9029 return this.basic.getElementSize(s);
9032 setElementSize : function(s, newSize, onComplete){
9033 this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
9036 moveSplitter : function(s){
9037 var yes = Roo.SplitBar;
9038 switch(s.placement){
9040 s.el.setX(s.resizingEl.getRight());
9043 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
9046 s.el.setY(s.resizingEl.getBottom());
9049 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
9056 * Orientation constant - Create a vertical SplitBar
9060 Roo.SplitBar.VERTICAL = 1;
9063 * Orientation constant - Create a horizontal SplitBar
9067 Roo.SplitBar.HORIZONTAL = 2;
9070 * Placement constant - The resizing element is to the left of the splitter element
9074 Roo.SplitBar.LEFT = 1;
9077 * Placement constant - The resizing element is to the right of the splitter element
9081 Roo.SplitBar.RIGHT = 2;
9084 * Placement constant - The resizing element is positioned above the splitter element
9088 Roo.SplitBar.TOP = 3;
9091 * Placement constant - The resizing element is positioned under splitter element
9095 Roo.SplitBar.BOTTOM = 4;
9098 * Ext JS Library 1.1.1
9099 * Copyright(c) 2006-2007, Ext JS, LLC.
9101 * Originally Released Under LGPL - original licence link has changed is not relivant.
9104 * <script type="text/javascript">
9109 * @extends Roo.util.Observable
9110 * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template.
9111 * This class also supports single and multi selection modes. <br>
9112 * Create a data model bound view:
9114 var store = new Roo.data.Store(...);
9116 var view = new Roo.View({
9118 tpl : '<div id="{0}">{2} - {1}</div>', // auto create template
9121 selectedClass: "ydataview-selected",
9125 // listen for node click?
9126 view.on("click", function(vw, index, node, e){
9127 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
9131 dataModel.load("foobar.xml");
9133 For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
9135 * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
9136 * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
9138 * Note: old style constructor is still suported (container, template, config)
9142 * @param {Object} config The config object
9145 Roo.View = function(config, depreciated_tpl, depreciated_config){
9147 if (typeof(depreciated_tpl) == 'undefined') {
9148 // new way.. - universal constructor.
9149 Roo.apply(this, config);
9150 this.el = Roo.get(this.el);
9153 this.el = Roo.get(config);
9154 this.tpl = depreciated_tpl;
9155 Roo.apply(this, depreciated_config);
9159 if(typeof(this.tpl) == "string"){
9160 this.tpl = new Roo.Template(this.tpl);
9162 // support xtype ctors..
9163 this.tpl = new Roo.factory(this.tpl, Roo);
9174 * @event beforeclick
9175 * Fires before a click is processed. Returns false to cancel the default action.
9176 * @param {Roo.View} this
9177 * @param {Number} index The index of the target node
9178 * @param {HTMLElement} node The target node
9179 * @param {Roo.EventObject} e The raw event object
9181 "beforeclick" : true,
9184 * Fires when a template node is clicked.
9185 * @param {Roo.View} this
9186 * @param {Number} index The index of the target node
9187 * @param {HTMLElement} node The target node
9188 * @param {Roo.EventObject} e The raw event object
9193 * Fires when a template node is double clicked.
9194 * @param {Roo.View} this
9195 * @param {Number} index The index of the target node
9196 * @param {HTMLElement} node The target node
9197 * @param {Roo.EventObject} e The raw event object
9201 * @event contextmenu
9202 * Fires when a template node is right clicked.
9203 * @param {Roo.View} this
9204 * @param {Number} index The index of the target node
9205 * @param {HTMLElement} node The target node
9206 * @param {Roo.EventObject} e The raw event object
9208 "contextmenu" : true,
9210 * @event selectionchange
9211 * Fires when the selected nodes change.
9212 * @param {Roo.View} this
9213 * @param {Array} selections Array of the selected nodes
9215 "selectionchange" : true,
9218 * @event beforeselect
9219 * Fires before a selection is made. If any handlers return false, the selection is cancelled.
9220 * @param {Roo.View} this
9221 * @param {HTMLElement} node The node to be selected
9222 * @param {Array} selections Array of currently selected nodes
9224 "beforeselect" : true,
9226 * @event preparedata
9227 * Fires on every row to render, to allow you to change the data.
9228 * @param {Roo.View} this
9229 * @param {Object} data to be rendered (change this)
9231 "preparedata" : true
9235 "click": this.onClick,
9236 "dblclick": this.onDblClick,
9237 "contextmenu": this.onContextMenu,
9241 this.selections = [];
9243 this.cmp = new Roo.CompositeElementLite([]);
9245 this.store = Roo.factory(this.store, Roo.data);
9246 this.setStore(this.store, true);
9248 Roo.View.superclass.constructor.call(this);
9251 Roo.extend(Roo.View, Roo.util.Observable, {
9254 * @cfg {Roo.data.Store} store Data store to load data from.
9259 * @cfg {String|Roo.Element} el The container element.
9264 * @cfg {String|Roo.Template} tpl The template used by this View
9268 * @cfg {String} dataName the named area of the template to use as the data area
9269 * Works with domtemplates roo-name="name"
9273 * @cfg {String} selectedClass The css class to add to selected nodes
9275 selectedClass : "x-view-selected",
9277 * @cfg {String} emptyText The empty text to show when nothing is loaded.
9281 * @cfg {Boolean} multiSelect Allow multiple selection
9283 multiSelect : false,
9285 * @cfg {Boolean} singleSelect Allow single selection
9287 singleSelect: false,
9290 * @cfg {Boolean} toggleSelect - selecting
9292 toggleSelect : false,
9295 * Returns the element this view is bound to.
9296 * @return {Roo.Element}
9303 * Refreshes the view.
9305 refresh : function(){
9308 // if we are using something like 'domtemplate', then
9309 // the what gets used is:
9310 // t.applySubtemplate(NAME, data, wrapping data..)
9311 // the outer template then get' applied with
9312 // the store 'extra data'
9313 // and the body get's added to the
9314 // roo-name="data" node?
9315 // <span class='roo-tpl-{name}'></span> ?????
9319 this.clearSelections();
9322 var records = this.store.getRange();
9323 if(records.length < 1) {
9325 // is this valid?? = should it render a template??
9327 this.el.update(this.emptyText);
9331 if (this.dataName) {
9332 this.el.update(t.apply(this.store.meta)); //????
9333 el = this.el.child('.roo-tpl-' + this.dataName);
9336 for(var i = 0, len = records.length; i < len; i++){
9337 var data = this.prepareData(records[i].data, i, records[i]);
9338 this.fireEvent("preparedata", this, data, i, records[i]);
9339 html[html.length] = Roo.util.Format.trim(
9341 t.applySubtemplate(this.dataName, data, this.store.meta) :
9348 el.update(html.join(""));
9349 this.nodes = el.dom.childNodes;
9350 this.updateIndexes(0);
9354 * Function to override to reformat the data that is sent to
9355 * the template for each node.
9356 * DEPRICATED - use the preparedata event handler.
9357 * @param {Array/Object} data The raw data (array of colData for a data model bound view or
9358 * a JSON object for an UpdateManager bound view).
9360 prepareData : function(data, index, record)
9362 this.fireEvent("preparedata", this, data, index, record);
9366 onUpdate : function(ds, record){
9367 this.clearSelections();
9368 var index = this.store.indexOf(record);
9369 var n = this.nodes[index];
9370 this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
9371 n.parentNode.removeChild(n);
9372 this.updateIndexes(index, index);
9378 onAdd : function(ds, records, index)
9380 this.clearSelections();
9381 if(this.nodes.length == 0){
9385 var n = this.nodes[index];
9386 for(var i = 0, len = records.length; i < len; i++){
9387 var d = this.prepareData(records[i].data, i, records[i]);
9389 this.tpl.insertBefore(n, d);
9392 this.tpl.append(this.el, d);
9395 this.updateIndexes(index);
9398 onRemove : function(ds, record, index){
9399 this.clearSelections();
9400 var el = this.dataName ?
9401 this.el.child('.roo-tpl-' + this.dataName) :
9403 el.dom.removeChild(this.nodes[index]);
9404 this.updateIndexes(index);
9408 * Refresh an individual node.
9409 * @param {Number} index
9411 refreshNode : function(index){
9412 this.onUpdate(this.store, this.store.getAt(index));
9415 updateIndexes : function(startIndex, endIndex){
9416 var ns = this.nodes;
9417 startIndex = startIndex || 0;
9418 endIndex = endIndex || ns.length - 1;
9419 for(var i = startIndex; i <= endIndex; i++){
9420 ns[i].nodeIndex = i;
9425 * Changes the data store this view uses and refresh the view.
9426 * @param {Store} store
9428 setStore : function(store, initial){
9429 if(!initial && this.store){
9430 this.store.un("datachanged", this.refresh);
9431 this.store.un("add", this.onAdd);
9432 this.store.un("remove", this.onRemove);
9433 this.store.un("update", this.onUpdate);
9434 this.store.un("clear", this.refresh);
9438 store.on("datachanged", this.refresh, this);
9439 store.on("add", this.onAdd, this);
9440 store.on("remove", this.onRemove, this);
9441 store.on("update", this.onUpdate, this);
9442 store.on("clear", this.refresh, this);
9451 * Returns the template node the passed child belongs to or null if it doesn't belong to one.
9452 * @param {HTMLElement} node
9453 * @return {HTMLElement} The template node
9455 findItemFromChild : function(node){
9456 var el = this.dataName ?
9457 this.el.child('.roo-tpl-' + this.dataName,true) :
9460 if(!node || node.parentNode == el){
9463 var p = node.parentNode;
9464 while(p && p != el){
9465 if(p.parentNode == el){
9474 onClick : function(e){
9475 var item = this.findItemFromChild(e.getTarget());
9477 var index = this.indexOf(item);
9478 if(this.onItemClick(item, index, e) !== false){
9479 this.fireEvent("click", this, index, item, e);
9482 this.clearSelections();
9487 onContextMenu : function(e){
9488 var item = this.findItemFromChild(e.getTarget());
9490 this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
9495 onDblClick : function(e){
9496 var item = this.findItemFromChild(e.getTarget());
9498 this.fireEvent("dblclick", this, this.indexOf(item), item, e);
9502 onItemClick : function(item, index, e)
9504 if(this.fireEvent("beforeclick", this, index, item, e) === false){
9507 if (this.toggleSelect) {
9508 var m = this.isSelected(item) ? 'unselect' : 'select';
9511 _t[m](item, true, false);
9514 if(this.multiSelect || this.singleSelect){
9515 if(this.multiSelect && e.shiftKey && this.lastSelection){
9516 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
9518 this.select(item, this.multiSelect && e.ctrlKey);
9519 this.lastSelection = item;
9527 * Get the number of selected nodes.
9530 getSelectionCount : function(){
9531 return this.selections.length;
9535 * Get the currently selected nodes.
9536 * @return {Array} An array of HTMLElements
9538 getSelectedNodes : function(){
9539 return this.selections;
9543 * Get the indexes of the selected nodes.
9546 getSelectedIndexes : function(){
9547 var indexes = [], s = this.selections;
9548 for(var i = 0, len = s.length; i < len; i++){
9549 indexes.push(s[i].nodeIndex);
9555 * Clear all selections
9556 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
9558 clearSelections : function(suppressEvent){
9559 if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
9560 this.cmp.elements = this.selections;
9561 this.cmp.removeClass(this.selectedClass);
9562 this.selections = [];
9564 this.fireEvent("selectionchange", this, this.selections);
9570 * Returns true if the passed node is selected
9571 * @param {HTMLElement/Number} node The node or node index
9574 isSelected : function(node){
9575 var s = this.selections;
9579 node = this.getNode(node);
9580 return s.indexOf(node) !== -1;
9585 * @param {Array/HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node, id of a template node or an array of any of those to select
9586 * @param {Boolean} keepExisting (optional) true to keep existing selections
9587 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
9589 select : function(nodeInfo, keepExisting, suppressEvent){
9590 if(nodeInfo instanceof Array){
9592 this.clearSelections(true);
9594 for(var i = 0, len = nodeInfo.length; i < len; i++){
9595 this.select(nodeInfo[i], true, true);
9599 var node = this.getNode(nodeInfo);
9600 if(!node || this.isSelected(node)){
9601 return; // already selected.
9604 this.clearSelections(true);
9606 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
9607 Roo.fly(node).addClass(this.selectedClass);
9608 this.selections.push(node);
9610 this.fireEvent("selectionchange", this, this.selections);
9618 * @param {Array/HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node, id of a template node or an array of any of those to select
9619 * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
9620 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
9622 unselect : function(nodeInfo, keepExisting, suppressEvent)
9624 if(nodeInfo instanceof Array){
9625 Roo.each(this.selections, function(s) {
9626 this.unselect(s, nodeInfo);
9630 var node = this.getNode(nodeInfo);
9631 if(!node || !this.isSelected(node)){
9632 Roo.log("not selected");
9633 return; // not selected.
9637 Roo.each(this.selections, function(s) {
9639 Roo.fly(node).removeClass(this.selectedClass);
9646 this.selections= ns;
9647 this.fireEvent("selectionchange", this, this.selections);
9651 * Gets a template node.
9652 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
9653 * @return {HTMLElement} The node or null if it wasn't found
9655 getNode : function(nodeInfo){
9656 if(typeof nodeInfo == "string"){
9657 return document.getElementById(nodeInfo);
9658 }else if(typeof nodeInfo == "number"){
9659 return this.nodes[nodeInfo];
9665 * Gets a range template nodes.
9666 * @param {Number} startIndex
9667 * @param {Number} endIndex
9668 * @return {Array} An array of nodes
9670 getNodes : function(start, end){
9671 var ns = this.nodes;
9673 end = typeof end == "undefined" ? ns.length - 1 : end;
9676 for(var i = start; i <= end; i++){
9680 for(var i = start; i >= end; i--){
9688 * Finds the index of the passed node
9689 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
9690 * @return {Number} The index of the node or -1
9692 indexOf : function(node){
9693 node = this.getNode(node);
9694 if(typeof node.nodeIndex == "number"){
9695 return node.nodeIndex;
9697 var ns = this.nodes;
9698 for(var i = 0, len = ns.length; i < len; i++){
9708 * Ext JS Library 1.1.1
9709 * Copyright(c) 2006-2007, Ext JS, LLC.
9711 * Originally Released Under LGPL - original licence link has changed is not relivant.
9714 * <script type="text/javascript">
9718 * @class Roo.JsonView
9720 * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
9722 var view = new Roo.JsonView({
9723 container: "my-element",
9724 tpl: '<div id="{id}">{foo} - {bar}</div>', // auto create template
9729 // listen for node click?
9730 view.on("click", function(vw, index, node, e){
9731 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
9734 // direct load of JSON data
9735 view.load("foobar.php");
9737 // Example from my blog list
9738 var tpl = new Roo.Template(
9739 '<div class="entry">' +
9740 '<a class="entry-title" href="{link}">{title}</a>' +
9741 "<h4>{date} by {author} | {comments} Comments</h4>{description}" +
9742 "</div><hr />"
9745 var moreView = new Roo.JsonView({
9746 container : "entry-list",
9750 moreView.on("beforerender", this.sortEntries, this);
9752 url: "/blog/get-posts.php",
9753 params: "allposts=true",
9754 text: "Loading Blog Entries..."
9758 * Note: old code is supported with arguments : (container, template, config)
9762 * Create a new JsonView
9764 * @param {Object} config The config object
9767 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
9770 Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
9772 var um = this.el.getUpdateManager();
9773 um.setRenderer(this);
9774 um.on("update", this.onLoad, this);
9775 um.on("failure", this.onLoadException, this);
9778 * @event beforerender
9779 * Fires before rendering of the downloaded JSON data.
9780 * @param {Roo.JsonView} this
9781 * @param {Object} data The JSON data loaded
9785 * Fires when data is loaded.
9786 * @param {Roo.JsonView} this
9787 * @param {Object} data The JSON data loaded
9788 * @param {Object} response The raw Connect response object
9791 * @event loadexception
9792 * Fires when loading fails.
9793 * @param {Roo.JsonView} this
9794 * @param {Object} response The raw Connect response object
9797 'beforerender' : true,
9799 'loadexception' : true
9802 Roo.extend(Roo.JsonView, Roo.View, {
9804 * @type {String} The root property in the loaded JSON object that contains the data
9809 * Refreshes the view.
9811 refresh : function(){
9812 this.clearSelections();
9815 var o = this.jsonData;
9816 if(o && o.length > 0){
9817 for(var i = 0, len = o.length; i < len; i++){
9818 var data = this.prepareData(o[i], i, o);
9819 html[html.length] = this.tpl.apply(data);
9822 html.push(this.emptyText);
9824 this.el.update(html.join(""));
9825 this.nodes = this.el.dom.childNodes;
9826 this.updateIndexes(0);
9830 * Performs an async HTTP request, and loads the JSON from the response. If <i>params</i> are specified it uses POST, otherwise it uses GET.
9831 * @param {Object/String/Function} url The URL for this request, or a function to call to get the URL, or a config object containing any of the following options:
9834 url: "your-url.php",
9835 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
9836 callback: yourFunction,
9837 scope: yourObject, //(optional scope)
9845 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
9846 * are respectively shorthand for <i>disableCaching</i>, <i>indicatorText</i>, and <i>loadScripts</i> and are used to set their associated property on this UpdateManager instance.
9847 * @param {String/Object} params (optional) The parameters to pass, as either a URL encoded string "param1=1&param2=2" or an object {param1: 1, param2: 2}
9848 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
9849 * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used URL. If true, it will not store the URL.
9852 var um = this.el.getUpdateManager();
9853 um.update.apply(um, arguments);
9856 render : function(el, response){
9857 this.clearSelections();
9861 o = Roo.util.JSON.decode(response.responseText);
9864 o = o[this.jsonRoot];
9869 * The current JSON data or null
9872 this.beforeRender();
9877 * Get the number of records in the current JSON dataset
9880 getCount : function(){
9881 return this.jsonData ? this.jsonData.length : 0;
9885 * Returns the JSON object for the specified node(s)
9886 * @param {HTMLElement/Array} node The node or an array of nodes
9887 * @return {Object/Array} If you pass in an array, you get an array back, otherwise
9888 * you get the JSON object for the node
9890 getNodeData : function(node){
9891 if(node instanceof Array){
9893 for(var i = 0, len = node.length; i < len; i++){
9894 data.push(this.getNodeData(node[i]));
9898 return this.jsonData[this.indexOf(node)] || null;
9901 beforeRender : function(){
9902 this.snapshot = this.jsonData;
9904 this.sort.apply(this, this.sortInfo);
9906 this.fireEvent("beforerender", this, this.jsonData);
9909 onLoad : function(el, o){
9910 this.fireEvent("load", this, this.jsonData, o);
9913 onLoadException : function(el, o){
9914 this.fireEvent("loadexception", this, o);
9918 * Filter the data by a specific property.
9919 * @param {String} property A property on your JSON objects
9920 * @param {String/RegExp} value Either string that the property values
9921 * should start with, or a RegExp to test against the property
9923 filter : function(property, value){
9926 var ss = this.snapshot;
9927 if(typeof value == "string"){
9928 var vlen = value.length;
9933 value = value.toLowerCase();
9934 for(var i = 0, len = ss.length; i < len; i++){
9936 if(o[property].substr(0, vlen).toLowerCase() == value){
9940 } else if(value.exec){ // regex?
9941 for(var i = 0, len = ss.length; i < len; i++){
9943 if(value.test(o[property])){
9950 this.jsonData = data;
9956 * Filter by a function. The passed function will be called with each
9957 * object in the current dataset. If the function returns true the value is kept,
9958 * otherwise it is filtered.
9959 * @param {Function} fn
9960 * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
9962 filterBy : function(fn, scope){
9965 var ss = this.snapshot;
9966 for(var i = 0, len = ss.length; i < len; i++){
9968 if(fn.call(scope || this, o)){
9972 this.jsonData = data;
9978 * Clears the current filter.
9980 clearFilter : function(){
9981 if(this.snapshot && this.jsonData != this.snapshot){
9982 this.jsonData = this.snapshot;
9989 * Sorts the data for this view and refreshes it.
9990 * @param {String} property A property on your JSON objects to sort on
9991 * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
9992 * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
9994 sort : function(property, dir, sortType){
9995 this.sortInfo = Array.prototype.slice.call(arguments, 0);
9998 var dsc = dir && dir.toLowerCase() == "desc";
9999 var f = function(o1, o2){
10000 var v1 = sortType ? sortType(o1[p]) : o1[p];
10001 var v2 = sortType ? sortType(o2[p]) : o2[p];
10004 return dsc ? +1 : -1;
10005 } else if(v1 > v2){
10006 return dsc ? -1 : +1;
10011 this.jsonData.sort(f);
10013 if(this.jsonData != this.snapshot){
10014 this.snapshot.sort(f);
10020 * Ext JS Library 1.1.1
10021 * Copyright(c) 2006-2007, Ext JS, LLC.
10023 * Originally Released Under LGPL - original licence link has changed is not relivant.
10026 * <script type="text/javascript">
10031 * @class Roo.ColorPalette
10032 * @extends Roo.Component
10033 * Simple color palette class for choosing colors. The palette can be rendered to any container.<br />
10034 * Here's an example of typical usage:
10036 var cp = new Roo.ColorPalette({value:'993300'}); // initial selected color
10037 cp.render('my-div');
10039 cp.on('select', function(palette, selColor){
10040 // do something with selColor
10044 * Create a new ColorPalette
10045 * @param {Object} config The config object
10047 Roo.ColorPalette = function(config){
10048 Roo.ColorPalette.superclass.constructor.call(this, config);
10052 * Fires when a color is selected
10053 * @param {ColorPalette} this
10054 * @param {String} color The 6-digit color hex code (without the # symbol)
10060 this.on("select", this.handler, this.scope, true);
10063 Roo.extend(Roo.ColorPalette, Roo.Component, {
10065 * @cfg {String} itemCls
10066 * The CSS class to apply to the containing element (defaults to "x-color-palette")
10068 itemCls : "x-color-palette",
10070 * @cfg {String} value
10071 * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol). Note that
10072 * the hex codes are case-sensitive.
10075 clickEvent:'click',
10077 ctype: "Roo.ColorPalette",
10080 * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
10082 allowReselect : false,
10085 * <p>An array of 6-digit color hex code strings (without the # symbol). This array can contain any number
10086 * of colors, and each hex code should be unique. The width of the palette is controlled via CSS by adjusting
10087 * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
10088 * of colors with the width setting until the box is symmetrical.</p>
10089 * <p>You can override individual colors if needed:</p>
10091 var cp = new Roo.ColorPalette();
10092 cp.colors[0] = "FF0000"; // change the first box to red
10095 Or you can provide a custom array of your own for complete control:
10097 var cp = new Roo.ColorPalette();
10098 cp.colors = ["000000", "993300", "333300"];
10103 "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
10104 "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
10105 "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
10106 "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
10107 "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
10111 onRender : function(container, position){
10112 var t = new Roo.MasterTemplate(
10113 '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on"> </span></em></a></tpl>'
10115 var c = this.colors;
10116 for(var i = 0, len = c.length; i < len; i++){
10119 var el = document.createElement("div");
10120 el.className = this.itemCls;
10122 container.dom.insertBefore(el, position);
10123 this.el = Roo.get(el);
10124 this.el.on(this.clickEvent, this.handleClick, this, {delegate: "a"});
10125 if(this.clickEvent != 'click'){
10126 this.el.on('click', Roo.emptyFn, this, {delegate: "a", preventDefault:true});
10131 afterRender : function(){
10132 Roo.ColorPalette.superclass.afterRender.call(this);
10134 var s = this.value;
10141 handleClick : function(e, t){
10142 e.preventDefault();
10143 if(!this.disabled){
10144 var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
10145 this.select(c.toUpperCase());
10150 * Selects the specified color in the palette (fires the select event)
10151 * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
10153 select : function(color){
10154 color = color.replace("#", "");
10155 if(color != this.value || this.allowReselect){
10158 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
10160 el.child("a.color-"+color).addClass("x-color-palette-sel");
10161 this.value = color;
10162 this.fireEvent("select", this, color);
10167 * Ext JS Library 1.1.1
10168 * Copyright(c) 2006-2007, Ext JS, LLC.
10170 * Originally Released Under LGPL - original licence link has changed is not relivant.
10173 * <script type="text/javascript">
10177 * @class Roo.DatePicker
10178 * @extends Roo.Component
10179 * Simple date picker class.
10181 * Create a new DatePicker
10182 * @param {Object} config The config object
10184 Roo.DatePicker = function(config){
10185 Roo.DatePicker.superclass.constructor.call(this, config);
10187 this.value = config && config.value ?
10188 config.value.clearTime() : new Date().clearTime();
10193 * Fires when a date is selected
10194 * @param {DatePicker} this
10195 * @param {Date} date The selected date
10199 * @event monthchange
10200 * Fires when the displayed month changes
10201 * @param {DatePicker} this
10202 * @param {Date} date The selected month
10204 'monthchange': true
10208 this.on("select", this.handler, this.scope || this);
10210 // build the disabledDatesRE
10211 if(!this.disabledDatesRE && this.disabledDates){
10212 var dd = this.disabledDates;
10214 for(var i = 0; i < dd.length; i++){
10216 if(i != dd.length-1) re += "|";
10218 this.disabledDatesRE = new RegExp(re + ")");
10222 Roo.extend(Roo.DatePicker, Roo.Component, {
10224 * @cfg {String} todayText
10225 * The text to display on the button that selects the current date (defaults to "Today")
10227 todayText : "Today",
10229 * @cfg {String} okText
10230 * The text to display on the ok button
10232 okText : " OK ", //   to give the user extra clicking room
10234 * @cfg {String} cancelText
10235 * The text to display on the cancel button
10237 cancelText : "Cancel",
10239 * @cfg {String} todayTip
10240 * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
10242 todayTip : "{0} (Spacebar)",
10244 * @cfg {Date} minDate
10245 * Minimum allowable date (JavaScript date object, defaults to null)
10249 * @cfg {Date} maxDate
10250 * Maximum allowable date (JavaScript date object, defaults to null)
10254 * @cfg {String} minText
10255 * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
10257 minText : "This date is before the minimum date",
10259 * @cfg {String} maxText
10260 * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
10262 maxText : "This date is after the maximum date",
10264 * @cfg {String} format
10265 * The default date format string which can be overriden for localization support. The format must be
10266 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
10270 * @cfg {Array} disabledDays
10271 * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
10273 disabledDays : null,
10275 * @cfg {String} disabledDaysText
10276 * The tooltip to display when the date falls on a disabled day (defaults to "")
10278 disabledDaysText : "",
10280 * @cfg {RegExp} disabledDatesRE
10281 * JavaScript regular expression used to disable a pattern of dates (defaults to null)
10283 disabledDatesRE : null,
10285 * @cfg {String} disabledDatesText
10286 * The tooltip text to display when the date falls on a disabled date (defaults to "")
10288 disabledDatesText : "",
10290 * @cfg {Boolean} constrainToViewport
10291 * True to constrain the date picker to the viewport (defaults to true)
10293 constrainToViewport : true,
10295 * @cfg {Array} monthNames
10296 * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
10298 monthNames : Date.monthNames,
10300 * @cfg {Array} dayNames
10301 * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
10303 dayNames : Date.dayNames,
10305 * @cfg {String} nextText
10306 * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
10308 nextText: 'Next Month (Control+Right)',
10310 * @cfg {String} prevText
10311 * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
10313 prevText: 'Previous Month (Control+Left)',
10315 * @cfg {String} monthYearText
10316 * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
10318 monthYearText: 'Choose a month (Control+Up/Down to move years)',
10320 * @cfg {Number} startDay
10321 * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
10325 * @cfg {Bool} showClear
10326 * Show a clear button (usefull for date form elements that can be blank.)
10332 * Sets the value of the date field
10333 * @param {Date} value The date to set
10335 setValue : function(value){
10336 var old = this.value;
10337 this.value = value.clearTime(true);
10339 this.update(this.value);
10344 * Gets the current selected value of the date field
10345 * @return {Date} The selected date
10347 getValue : function(){
10352 focus : function(){
10354 this.update(this.activeDate);
10359 onRender : function(container, position){
10361 '<table cellspacing="0">',
10362 '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'"> </a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'"> </a></td></tr>',
10363 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
10364 var dn = this.dayNames;
10365 for(var i = 0; i < 7; i++){
10366 var d = this.startDay+i;
10370 m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
10372 m[m.length] = "</tr></thead><tbody><tr>";
10373 for(var i = 0; i < 42; i++) {
10374 if(i % 7 == 0 && i != 0){
10375 m[m.length] = "</tr><tr>";
10377 m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
10379 m[m.length] = '</tr></tbody></table></td></tr><tr>'+
10380 '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
10382 var el = document.createElement("div");
10383 el.className = "x-date-picker";
10384 el.innerHTML = m.join("");
10386 container.dom.insertBefore(el, position);
10388 this.el = Roo.get(el);
10389 this.eventEl = Roo.get(el.firstChild);
10391 new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
10392 handler: this.showPrevMonth,
10394 preventDefault:true,
10398 new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
10399 handler: this.showNextMonth,
10401 preventDefault:true,
10405 this.eventEl.on("mousewheel", this.handleMouseWheel, this);
10407 this.monthPicker = this.el.down('div.x-date-mp');
10408 this.monthPicker.enableDisplayMode('block');
10410 var kn = new Roo.KeyNav(this.eventEl, {
10411 "left" : function(e){
10413 this.showPrevMonth() :
10414 this.update(this.activeDate.add("d", -1));
10417 "right" : function(e){
10419 this.showNextMonth() :
10420 this.update(this.activeDate.add("d", 1));
10423 "up" : function(e){
10425 this.showNextYear() :
10426 this.update(this.activeDate.add("d", -7));
10429 "down" : function(e){
10431 this.showPrevYear() :
10432 this.update(this.activeDate.add("d", 7));
10435 "pageUp" : function(e){
10436 this.showNextMonth();
10439 "pageDown" : function(e){
10440 this.showPrevMonth();
10443 "enter" : function(e){
10444 e.stopPropagation();
10451 this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"});
10453 this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday, this);
10455 this.el.unselectable();
10457 this.cells = this.el.select("table.x-date-inner tbody td");
10458 this.textNodes = this.el.query("table.x-date-inner tbody span");
10460 this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
10462 tooltip: this.monthYearText
10465 this.mbtn.on('click', this.showMonthPicker, this);
10466 this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
10469 var today = (new Date()).dateFormat(this.format);
10471 var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
10472 if (this.showClear) {
10473 baseTb.add( new Roo.Toolbar.Fill());
10476 text: String.format(this.todayText, today),
10477 tooltip: String.format(this.todayTip, today),
10478 handler: this.selectToday,
10482 //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
10485 if (this.showClear) {
10487 baseTb.add( new Roo.Toolbar.Fill());
10490 cls: 'x-btn-icon x-btn-clear',
10491 handler: function() {
10493 this.fireEvent("select", this, '');
10503 this.update(this.value);
10506 createMonthPicker : function(){
10507 if(!this.monthPicker.dom.firstChild){
10508 var buf = ['<table border="0" cellspacing="0">'];
10509 for(var i = 0; i < 6; i++){
10511 '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
10512 '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
10514 '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
10515 '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
10519 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
10521 '</button><button type="button" class="x-date-mp-cancel">',
10523 '</button></td></tr>',
10526 this.monthPicker.update(buf.join(''));
10527 this.monthPicker.on('click', this.onMonthClick, this);
10528 this.monthPicker.on('dblclick', this.onMonthDblClick, this);
10530 this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
10531 this.mpYears = this.monthPicker.select('td.x-date-mp-year');
10533 this.mpMonths.each(function(m, a, i){
10536 m.dom.xmonth = 5 + Math.round(i * .5);
10538 m.dom.xmonth = Math.round((i-1) * .5);
10544 showMonthPicker : function(){
10545 this.createMonthPicker();
10546 var size = this.el.getSize();
10547 this.monthPicker.setSize(size);
10548 this.monthPicker.child('table').setSize(size);
10550 this.mpSelMonth = (this.activeDate || this.value).getMonth();
10551 this.updateMPMonth(this.mpSelMonth);
10552 this.mpSelYear = (this.activeDate || this.value).getFullYear();
10553 this.updateMPYear(this.mpSelYear);
10555 this.monthPicker.slideIn('t', {duration:.2});
10558 updateMPYear : function(y){
10560 var ys = this.mpYears.elements;
10561 for(var i = 1; i <= 10; i++){
10562 var td = ys[i-1], y2;
10564 y2 = y + Math.round(i * .5);
10565 td.firstChild.innerHTML = y2;
10568 y2 = y - (5-Math.round(i * .5));
10569 td.firstChild.innerHTML = y2;
10572 this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
10576 updateMPMonth : function(sm){
10577 this.mpMonths.each(function(m, a, i){
10578 m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
10582 selectMPMonth: function(m){
10586 onMonthClick : function(e, t){
10588 var el = new Roo.Element(t), pn;
10589 if(el.is('button.x-date-mp-cancel')){
10590 this.hideMonthPicker();
10592 else if(el.is('button.x-date-mp-ok')){
10593 this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
10594 this.hideMonthPicker();
10596 else if(pn = el.up('td.x-date-mp-month', 2)){
10597 this.mpMonths.removeClass('x-date-mp-sel');
10598 pn.addClass('x-date-mp-sel');
10599 this.mpSelMonth = pn.dom.xmonth;
10601 else if(pn = el.up('td.x-date-mp-year', 2)){
10602 this.mpYears.removeClass('x-date-mp-sel');
10603 pn.addClass('x-date-mp-sel');
10604 this.mpSelYear = pn.dom.xyear;
10606 else if(el.is('a.x-date-mp-prev')){
10607 this.updateMPYear(this.mpyear-10);
10609 else if(el.is('a.x-date-mp-next')){
10610 this.updateMPYear(this.mpyear+10);
10614 onMonthDblClick : function(e, t){
10616 var el = new Roo.Element(t), pn;
10617 if(pn = el.up('td.x-date-mp-month', 2)){
10618 this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
10619 this.hideMonthPicker();
10621 else if(pn = el.up('td.x-date-mp-year', 2)){
10622 this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
10623 this.hideMonthPicker();
10627 hideMonthPicker : function(disableAnim){
10628 if(this.monthPicker){
10629 if(disableAnim === true){
10630 this.monthPicker.hide();
10632 this.monthPicker.slideOut('t', {duration:.2});
10638 showPrevMonth : function(e){
10639 this.update(this.activeDate.add("mo", -1));
10643 showNextMonth : function(e){
10644 this.update(this.activeDate.add("mo", 1));
10648 showPrevYear : function(){
10649 this.update(this.activeDate.add("y", -1));
10653 showNextYear : function(){
10654 this.update(this.activeDate.add("y", 1));
10658 handleMouseWheel : function(e){
10659 var delta = e.getWheelDelta();
10661 this.showPrevMonth();
10663 } else if(delta < 0){
10664 this.showNextMonth();
10670 handleDateClick : function(e, t){
10672 if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
10673 this.setValue(new Date(t.dateValue));
10674 this.fireEvent("select", this, this.value);
10679 selectToday : function(){
10680 this.setValue(new Date().clearTime());
10681 this.fireEvent("select", this, this.value);
10685 update : function(date)
10687 var vd = this.activeDate;
10688 this.activeDate = date;
10690 var t = date.getTime();
10691 if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
10692 this.cells.removeClass("x-date-selected");
10693 this.cells.each(function(c){
10694 if(c.dom.firstChild.dateValue == t){
10695 c.addClass("x-date-selected");
10696 setTimeout(function(){
10697 try{c.dom.firstChild.focus();}catch(e){}
10706 var days = date.getDaysInMonth();
10707 var firstOfMonth = date.getFirstDateOfMonth();
10708 var startingPos = firstOfMonth.getDay()-this.startDay;
10710 if(startingPos <= this.startDay){
10714 var pm = date.add("mo", -1);
10715 var prevStart = pm.getDaysInMonth()-startingPos;
10717 var cells = this.cells.elements;
10718 var textEls = this.textNodes;
10719 days += startingPos;
10721 // convert everything to numbers so it's fast
10722 var day = 86400000;
10723 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
10724 var today = new Date().clearTime().getTime();
10725 var sel = date.clearTime().getTime();
10726 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
10727 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
10728 var ddMatch = this.disabledDatesRE;
10729 var ddText = this.disabledDatesText;
10730 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
10731 var ddaysText = this.disabledDaysText;
10732 var format = this.format;
10734 var setCellClass = function(cal, cell){
10736 var t = d.getTime();
10737 cell.firstChild.dateValue = t;
10739 cell.className += " x-date-today";
10740 cell.title = cal.todayText;
10743 cell.className += " x-date-selected";
10744 setTimeout(function(){
10745 try{cell.firstChild.focus();}catch(e){}
10750 cell.className = " x-date-disabled";
10751 cell.title = cal.minText;
10755 cell.className = " x-date-disabled";
10756 cell.title = cal.maxText;
10760 if(ddays.indexOf(d.getDay()) != -1){
10761 cell.title = ddaysText;
10762 cell.className = " x-date-disabled";
10765 if(ddMatch && format){
10766 var fvalue = d.dateFormat(format);
10767 if(ddMatch.test(fvalue)){
10768 cell.title = ddText.replace("%0", fvalue);
10769 cell.className = " x-date-disabled";
10775 for(; i < startingPos; i++) {
10776 textEls[i].innerHTML = (++prevStart);
10777 d.setDate(d.getDate()+1);
10778 cells[i].className = "x-date-prevday";
10779 setCellClass(this, cells[i]);
10781 for(; i < days; i++){
10782 intDay = i - startingPos + 1;
10783 textEls[i].innerHTML = (intDay);
10784 d.setDate(d.getDate()+1);
10785 cells[i].className = "x-date-active";
10786 setCellClass(this, cells[i]);
10789 for(; i < 42; i++) {
10790 textEls[i].innerHTML = (++extraDays);
10791 d.setDate(d.getDate()+1);
10792 cells[i].className = "x-date-nextday";
10793 setCellClass(this, cells[i]);
10796 this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
10797 this.fireEvent('monthchange', this, date);
10799 if(!this.internalRender){
10800 var main = this.el.dom.firstChild;
10801 var w = main.offsetWidth;
10802 this.el.setWidth(w + this.el.getBorderWidth("lr"));
10803 Roo.fly(main).setWidth(w);
10804 this.internalRender = true;
10805 // opera does not respect the auto grow header center column
10806 // then, after it gets a width opera refuses to recalculate
10807 // without a second pass
10808 if(Roo.isOpera && !this.secondPass){
10809 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
10810 this.secondPass = true;
10811 this.update.defer(10, this, [date]);
10819 * Ext JS Library 1.1.1
10820 * Copyright(c) 2006-2007, Ext JS, LLC.
10822 * Originally Released Under LGPL - original licence link has changed is not relivant.
10825 * <script type="text/javascript">
10828 * @class Roo.TabPanel
10829 * @extends Roo.util.Observable
10830 * A lightweight tab container.
10834 // basic tabs 1, built from existing content
10835 var tabs = new Roo.TabPanel("tabs1");
10836 tabs.addTab("script", "View Script");
10837 tabs.addTab("markup", "View Markup");
10838 tabs.activate("script");
10840 // more advanced tabs, built from javascript
10841 var jtabs = new Roo.TabPanel("jtabs");
10842 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
10844 // set up the UpdateManager
10845 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
10846 var updater = tab2.getUpdateManager();
10847 updater.setDefaultUrl("ajax1.htm");
10848 tab2.on('activate', updater.refresh, updater, true);
10850 // Use setUrl for Ajax loading
10851 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
10852 tab3.setUrl("ajax2.htm", null, true);
10855 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
10858 jtabs.activate("jtabs-1");
10861 * Create a new TabPanel.
10862 * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
10863 * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
10865 Roo.TabPanel = function(container, config){
10867 * The container element for this TabPanel.
10868 * @type Roo.Element
10870 this.el = Roo.get(container, true);
10872 if(typeof config == "boolean"){
10873 this.tabPosition = config ? "bottom" : "top";
10875 Roo.apply(this, config);
10878 if(this.tabPosition == "bottom"){
10879 this.bodyEl = Roo.get(this.createBody(this.el.dom));
10880 this.el.addClass("x-tabs-bottom");
10882 this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
10883 this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
10884 this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
10886 Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
10888 if(this.tabPosition != "bottom"){
10889 /** The body element that contains {@link Roo.TabPanelItem} bodies. +
10890 * @type Roo.Element
10892 this.bodyEl = Roo.get(this.createBody(this.el.dom));
10893 this.el.addClass("x-tabs-top");
10897 this.bodyEl.setStyle("position", "relative");
10899 this.active = null;
10900 this.activateDelegate = this.activate.createDelegate(this);
10905 * Fires when the active tab changes
10906 * @param {Roo.TabPanel} this
10907 * @param {Roo.TabPanelItem} activePanel The new active tab
10911 * @event beforetabchange
10912 * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
10913 * @param {Roo.TabPanel} this
10914 * @param {Object} e Set cancel to true on this object to cancel the tab change
10915 * @param {Roo.TabPanelItem} tab The tab being changed to
10917 "beforetabchange" : true
10920 Roo.EventManager.onWindowResize(this.onResize, this);
10921 this.cpad = this.el.getPadding("lr");
10922 this.hiddenCount = 0;
10925 // toolbar on the tabbar support...
10926 if (this.toolbar) {
10927 var tcfg = this.toolbar;
10928 tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');
10929 this.toolbar = new Roo.Toolbar(tcfg);
10930 if (Roo.isSafari) {
10931 var tbl = tcfg.container.child('table', true);
10932 tbl.setAttribute('width', '100%');
10939 Roo.TabPanel.superclass.constructor.call(this);
10942 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
10944 *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
10946 tabPosition : "top",
10948 *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
10950 currentTabWidth : 0,
10952 *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
10956 *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
10960 *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
10962 preferredTabWidth : 175,
10964 *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
10966 resizeTabs : false,
10968 *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
10970 monitorResize : true,
10972 *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar.
10977 * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
10978 * @param {String} id The id of the div to use <b>or create</b>
10979 * @param {String} text The text for the tab
10980 * @param {String} content (optional) Content to put in the TabPanelItem body
10981 * @param {Boolean} closable (optional) True to create a close icon on the tab
10982 * @return {Roo.TabPanelItem} The created TabPanelItem
10984 addTab : function(id, text, content, closable){
10985 var item = new Roo.TabPanelItem(this, id, text, closable);
10986 this.addTabItem(item);
10988 item.setContent(content);
10994 * Returns the {@link Roo.TabPanelItem} with the specified id/index
10995 * @param {String/Number} id The id or index of the TabPanelItem to fetch.
10996 * @return {Roo.TabPanelItem}
10998 getTab : function(id){
10999 return this.items[id];
11003 * Hides the {@link Roo.TabPanelItem} with the specified id/index
11004 * @param {String/Number} id The id or index of the TabPanelItem to hide.
11006 hideTab : function(id){
11007 var t = this.items[id];
11010 this.hiddenCount++;
11011 this.autoSizeTabs();
11016 * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
11017 * @param {String/Number} id The id or index of the TabPanelItem to unhide.
11019 unhideTab : function(id){
11020 var t = this.items[id];
11022 t.setHidden(false);
11023 this.hiddenCount--;
11024 this.autoSizeTabs();
11029 * Adds an existing {@link Roo.TabPanelItem}.
11030 * @param {Roo.TabPanelItem} item The TabPanelItem to add
11032 addTabItem : function(item){
11033 this.items[item.id] = item;
11034 this.items.push(item);
11035 if(this.resizeTabs){
11036 item.setWidth(this.currentTabWidth || this.preferredTabWidth);
11037 this.autoSizeTabs();
11044 * Removes a {@link Roo.TabPanelItem}.
11045 * @param {String/Number} id The id or index of the TabPanelItem to remove.
11047 removeTab : function(id){
11048 var items = this.items;
11049 var tab = items[id];
11050 if(!tab) { return; }
11051 var index = items.indexOf(tab);
11052 if(this.active == tab && items.length > 1){
11053 var newTab = this.getNextAvailable(index);
11058 this.stripEl.dom.removeChild(tab.pnode.dom);
11059 if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
11060 this.bodyEl.dom.removeChild(tab.bodyEl.dom);
11062 items.splice(index, 1);
11063 delete this.items[tab.id];
11064 tab.fireEvent("close", tab);
11065 tab.purgeListeners();
11066 this.autoSizeTabs();
11069 getNextAvailable : function(start){
11070 var items = this.items;
11072 // look for a next tab that will slide over to
11073 // replace the one being removed
11074 while(index < items.length){
11075 var item = items[++index];
11076 if(item && !item.isHidden()){
11080 // if one isn't found select the previous tab (on the left)
11083 var item = items[--index];
11084 if(item && !item.isHidden()){
11092 * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
11093 * @param {String/Number} id The id or index of the TabPanelItem to disable.
11095 disableTab : function(id){
11096 var tab = this.items[id];
11097 if(tab && this.active != tab){
11103 * Enables a {@link Roo.TabPanelItem} that is disabled.
11104 * @param {String/Number} id The id or index of the TabPanelItem to enable.
11106 enableTab : function(id){
11107 var tab = this.items[id];
11112 * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
11113 * @param {String/Number} id The id or index of the TabPanelItem to activate.
11114 * @return {Roo.TabPanelItem} The TabPanelItem.
11116 activate : function(id){
11117 var tab = this.items[id];
11121 if(tab == this.active || tab.disabled){
11125 this.fireEvent("beforetabchange", this, e, tab);
11126 if(e.cancel !== true && !tab.disabled){
11128 this.active.hide();
11130 this.active = this.items[id];
11131 this.active.show();
11132 this.fireEvent("tabchange", this, this.active);
11138 * Gets the active {@link Roo.TabPanelItem}.
11139 * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
11141 getActiveTab : function(){
11142 return this.active;
11146 * Updates the tab body element to fit the height of the container element
11147 * for overflow scrolling
11148 * @param {Number} targetHeight (optional) Override the starting height from the elements height
11150 syncHeight : function(targetHeight){
11151 var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
11152 var bm = this.bodyEl.getMargins();
11153 var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
11154 this.bodyEl.setHeight(newHeight);
11158 onResize : function(){
11159 if(this.monitorResize){
11160 this.autoSizeTabs();
11165 * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
11167 beginUpdate : function(){
11168 this.updating = true;
11172 * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
11174 endUpdate : function(){
11175 this.updating = false;
11176 this.autoSizeTabs();
11180 * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
11182 autoSizeTabs : function(){
11183 var count = this.items.length;
11184 var vcount = count - this.hiddenCount;
11185 if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) return;
11186 var w = Math.max(this.el.getWidth() - this.cpad, 10);
11187 var availWidth = Math.floor(w / vcount);
11188 var b = this.stripBody;
11189 if(b.getWidth() > w){
11190 var tabs = this.items;
11191 this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
11192 if(availWidth < this.minTabWidth){
11193 /*if(!this.sleft){ // incomplete scrolling code
11194 this.createScrollButtons();
11197 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
11200 if(this.currentTabWidth < this.preferredTabWidth){
11201 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
11207 * Returns the number of tabs in this TabPanel.
11210 getCount : function(){
11211 return this.items.length;
11215 * Resizes all the tabs to the passed width
11216 * @param {Number} The new width
11218 setTabWidth : function(width){
11219 this.currentTabWidth = width;
11220 for(var i = 0, len = this.items.length; i < len; i++) {
11221 if(!this.items[i].isHidden())this.items[i].setWidth(width);
11226 * Destroys this TabPanel
11227 * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
11229 destroy : function(removeEl){
11230 Roo.EventManager.removeResizeListener(this.onResize, this);
11231 for(var i = 0, len = this.items.length; i < len; i++){
11232 this.items[i].purgeListeners();
11234 if(removeEl === true){
11235 this.el.update("");
11242 * @class Roo.TabPanelItem
11243 * @extends Roo.util.Observable
11244 * Represents an individual item (tab plus body) in a TabPanel.
11245 * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
11246 * @param {String} id The id of this TabPanelItem
11247 * @param {String} text The text for the tab of this TabPanelItem
11248 * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
11250 Roo.TabPanelItem = function(tabPanel, id, text, closable){
11252 * The {@link Roo.TabPanel} this TabPanelItem belongs to
11253 * @type Roo.TabPanel
11255 this.tabPanel = tabPanel;
11257 * The id for this TabPanelItem
11262 this.disabled = false;
11266 this.loaded = false;
11267 this.closable = closable;
11270 * The body element for this TabPanelItem.
11271 * @type Roo.Element
11273 this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
11274 this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
11275 this.bodyEl.setStyle("display", "block");
11276 this.bodyEl.setStyle("zoom", "1");
11279 var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
11281 this.el = Roo.get(els.el, true);
11282 this.inner = Roo.get(els.inner, true);
11283 this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
11284 this.pnode = Roo.get(els.el.parentNode, true);
11285 this.el.on("mousedown", this.onTabMouseDown, this);
11286 this.el.on("click", this.onTabClick, this);
11289 var c = Roo.get(els.close, true);
11290 c.dom.title = this.closeText;
11291 c.addClassOnOver("close-over");
11292 c.on("click", this.closeClick, this);
11298 * Fires when this tab becomes the active tab.
11299 * @param {Roo.TabPanel} tabPanel The parent TabPanel
11300 * @param {Roo.TabPanelItem} this
11304 * @event beforeclose
11305 * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
11306 * @param {Roo.TabPanelItem} this
11307 * @param {Object} e Set cancel to true on this object to cancel the close.
11309 "beforeclose": true,
11312 * Fires when this tab is closed.
11313 * @param {Roo.TabPanelItem} this
11317 * @event deactivate
11318 * Fires when this tab is no longer the active tab.
11319 * @param {Roo.TabPanel} tabPanel The parent TabPanel
11320 * @param {Roo.TabPanelItem} this
11322 "deactivate" : true
11324 this.hidden = false;
11326 Roo.TabPanelItem.superclass.constructor.call(this);
11329 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
11330 purgeListeners : function(){
11331 Roo.util.Observable.prototype.purgeListeners.call(this);
11332 this.el.removeAllListeners();
11335 * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
11338 this.pnode.addClass("on");
11341 this.tabPanel.stripWrap.repaint();
11343 this.fireEvent("activate", this.tabPanel, this);
11347 * Returns true if this tab is the active tab.
11348 * @return {Boolean}
11350 isActive : function(){
11351 return this.tabPanel.getActiveTab() == this;
11355 * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
11358 this.pnode.removeClass("on");
11360 this.fireEvent("deactivate", this.tabPanel, this);
11363 hideAction : function(){
11364 this.bodyEl.hide();
11365 this.bodyEl.setStyle("position", "absolute");
11366 this.bodyEl.setLeft("-20000px");
11367 this.bodyEl.setTop("-20000px");
11370 showAction : function(){
11371 this.bodyEl.setStyle("position", "relative");
11372 this.bodyEl.setTop("");
11373 this.bodyEl.setLeft("");
11374 this.bodyEl.show();
11378 * Set the tooltip for the tab.
11379 * @param {String} tooltip The tab's tooltip
11381 setTooltip : function(text){
11382 if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
11383 this.textEl.dom.qtip = text;
11384 this.textEl.dom.removeAttribute('title');
11386 this.textEl.dom.title = text;
11390 onTabClick : function(e){
11391 e.preventDefault();
11392 this.tabPanel.activate(this.id);
11395 onTabMouseDown : function(e){
11396 e.preventDefault();
11397 this.tabPanel.activate(this.id);
11400 getWidth : function(){
11401 return this.inner.getWidth();
11404 setWidth : function(width){
11405 var iwidth = width - this.pnode.getPadding("lr");
11406 this.inner.setWidth(iwidth);
11407 this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
11408 this.pnode.setWidth(width);
11412 * Show or hide the tab
11413 * @param {Boolean} hidden True to hide or false to show.
11415 setHidden : function(hidden){
11416 this.hidden = hidden;
11417 this.pnode.setStyle("display", hidden ? "none" : "");
11421 * Returns true if this tab is "hidden"
11422 * @return {Boolean}
11424 isHidden : function(){
11425 return this.hidden;
11429 * Returns the text for this tab
11432 getText : function(){
11436 autoSize : function(){
11437 //this.el.beginMeasure();
11438 this.textEl.setWidth(1);
11439 this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr"));
11440 //this.el.endMeasure();
11444 * Sets the text for the tab (Note: this also sets the tooltip text)
11445 * @param {String} text The tab's text and tooltip
11447 setText : function(text){
11449 this.textEl.update(text);
11450 this.setTooltip(text);
11451 if(!this.tabPanel.resizeTabs){
11456 * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
11458 activate : function(){
11459 this.tabPanel.activate(this.id);
11463 * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
11465 disable : function(){
11466 if(this.tabPanel.active != this){
11467 this.disabled = true;
11468 this.pnode.addClass("disabled");
11473 * Enables this TabPanelItem if it was previously disabled.
11475 enable : function(){
11476 this.disabled = false;
11477 this.pnode.removeClass("disabled");
11481 * Sets the content for this TabPanelItem.
11482 * @param {String} content The content
11483 * @param {Boolean} loadScripts true to look for and load scripts
11485 setContent : function(content, loadScripts){
11486 this.bodyEl.update(content, loadScripts);
11490 * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
11491 * @return {Roo.UpdateManager} The UpdateManager
11493 getUpdateManager : function(){
11494 return this.bodyEl.getUpdateManager();
11498 * Set a URL to be used to load the content for this TabPanelItem.
11499 * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
11500 * @param {String/Object} params (optional) The string params for the update call or an object of the params. See {@link Roo.UpdateManager#update} for more details. (Defaults to null)
11501 * @param {Boolean} loadOnce (optional) Whether to only load the content once. If this is false it makes the Ajax call every time this TabPanelItem is activated. (Defaults to false)
11502 * @return {Roo.UpdateManager} The UpdateManager
11504 setUrl : function(url, params, loadOnce){
11505 if(this.refreshDelegate){
11506 this.un('activate', this.refreshDelegate);
11508 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
11509 this.on("activate", this.refreshDelegate);
11510 return this.bodyEl.getUpdateManager();
11514 _handleRefresh : function(url, params, loadOnce){
11515 if(!loadOnce || !this.loaded){
11516 var updater = this.bodyEl.getUpdateManager();
11517 updater.update(url, params, this._setLoaded.createDelegate(this));
11522 * Forces a content refresh from the URL specified in the {@link #setUrl} method.
11523 * Will fail silently if the setUrl method has not been called.
11524 * This does not activate the panel, just updates its content.
11526 refresh : function(){
11527 if(this.refreshDelegate){
11528 this.loaded = false;
11529 this.refreshDelegate();
11534 _setLoaded : function(){
11535 this.loaded = true;
11539 closeClick : function(e){
11542 this.fireEvent("beforeclose", this, o);
11543 if(o.cancel !== true){
11544 this.tabPanel.removeTab(this.id);
11548 * The text displayed in the tooltip for the close icon.
11551 closeText : "Close this tab"
11555 Roo.TabPanel.prototype.createStrip = function(container){
11556 var strip = document.createElement("div");
11557 strip.className = "x-tabs-wrap";
11558 container.appendChild(strip);
11562 Roo.TabPanel.prototype.createStripList = function(strip){
11563 // div wrapper for retard IE
11564 // returns the "tr" element.
11565 strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
11566 '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
11567 '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
11568 return strip.firstChild.firstChild.firstChild.firstChild;
11571 Roo.TabPanel.prototype.createBody = function(container){
11572 var body = document.createElement("div");
11573 Roo.id(body, "tab-body");
11574 Roo.fly(body).addClass("x-tabs-body");
11575 container.appendChild(body);
11579 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
11580 var body = Roo.getDom(id);
11582 body = document.createElement("div");
11585 Roo.fly(body).addClass("x-tabs-item-body");
11586 bodyEl.insertBefore(body, bodyEl.firstChild);
11590 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
11591 var td = document.createElement("td");
11592 stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
11593 //stripEl.appendChild(td);
11595 td.className = "x-tabs-closable";
11596 if(!this.closeTpl){
11597 this.closeTpl = new Roo.Template(
11598 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
11599 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
11600 '<div unselectable="on" class="close-icon"> </div></em></span></a>'
11603 var el = this.closeTpl.overwrite(td, {"text": text});
11604 var close = el.getElementsByTagName("div")[0];
11605 var inner = el.getElementsByTagName("em")[0];
11606 return {"el": el, "close": close, "inner": inner};
11609 this.tabTpl = new Roo.Template(
11610 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
11611 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
11614 var el = this.tabTpl.overwrite(td, {"text": text});
11615 var inner = el.getElementsByTagName("em")[0];
11616 return {"el": el, "inner": inner};
11620 * Ext JS Library 1.1.1
11621 * Copyright(c) 2006-2007, Ext JS, LLC.
11623 * Originally Released Under LGPL - original licence link has changed is not relivant.
11626 * <script type="text/javascript">
11630 * @class Roo.Button
11631 * @extends Roo.util.Observable
11632 * Simple Button class
11633 * @cfg {String} text The button text
11634 * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
11635 * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
11636 * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
11637 * @cfg {Object} scope The scope of the handler
11638 * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
11639 * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
11640 * @cfg {Boolean} hidden True to start hidden (defaults to false)
11641 * @cfg {Boolean} disabled True to start disabled (defaults to false)
11642 * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
11643 * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
11644 applies if enableToggle = true)
11645 * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
11646 * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
11647 an {@link Roo.util.ClickRepeater} config object (defaults to false).
11649 * Create a new button
11650 * @param {Object} config The config object
11652 Roo.Button = function(renderTo, config)
11656 renderTo = config.renderTo || false;
11659 Roo.apply(this, config);
11663 * Fires when this button is clicked
11664 * @param {Button} this
11665 * @param {EventObject} e The click event
11670 * Fires when the "pressed" state of this button changes (only if enableToggle = true)
11671 * @param {Button} this
11672 * @param {Boolean} pressed
11677 * Fires when the mouse hovers over the button
11678 * @param {Button} this
11679 * @param {Event} e The event object
11681 'mouseover' : true,
11684 * Fires when the mouse exits the button
11685 * @param {Button} this
11686 * @param {Event} e The event object
11691 * Fires when the button is rendered
11692 * @param {Button} this
11697 this.menu = Roo.menu.MenuMgr.get(this.menu);
11699 // register listeners first!! - so render can be captured..
11700 Roo.util.Observable.call(this);
11702 this.render(renderTo);
11708 Roo.extend(Roo.Button, Roo.util.Observable, {
11714 * Read-only. True if this button is hidden
11719 * Read-only. True if this button is disabled
11724 * Read-only. True if this button is pressed (only if enableToggle = true)
11730 * @cfg {Number} tabIndex
11731 * The DOM tabIndex for this button (defaults to undefined)
11733 tabIndex : undefined,
11736 * @cfg {Boolean} enableToggle
11737 * True to enable pressed/not pressed toggling (defaults to false)
11739 enableToggle: false,
11741 * @cfg {Mixed} menu
11742 * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
11746 * @cfg {String} menuAlign
11747 * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
11749 menuAlign : "tl-bl?",
11752 * @cfg {String} iconCls
11753 * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
11755 iconCls : undefined,
11757 * @cfg {String} type
11758 * The button's type, corresponding to the DOM input element type attribute. Either "submit," "reset" or "button" (default).
11763 menuClassTarget: 'tr',
11766 * @cfg {String} clickEvent
11767 * The type of event to map to the button's event handler (defaults to 'click')
11769 clickEvent : 'click',
11772 * @cfg {Boolean} handleMouseEvents
11773 * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
11775 handleMouseEvents : true,
11778 * @cfg {String} tooltipType
11779 * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
11781 tooltipType : 'qtip',
11784 * @cfg {String} cls
11785 * A CSS class to apply to the button's main element.
11789 * @cfg {Roo.Template} template (Optional)
11790 * An {@link Roo.Template} with which to create the Button's main element. This Template must
11791 * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
11792 * require code modifications if required elements (e.g. a button) aren't present.
11796 render : function(renderTo){
11798 if(this.hideParent){
11799 this.parentEl = Roo.get(renderTo);
11801 if(!this.dhconfig){
11802 if(!this.template){
11803 if(!Roo.Button.buttonTemplate){
11804 // hideous table template
11805 Roo.Button.buttonTemplate = new Roo.Template(
11806 '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
11807 '<td class="x-btn-left"><i> </i></td><td class="x-btn-center"><em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td><td class="x-btn-right"><i> </i></td>',
11808 "</tr></tbody></table>");
11810 this.template = Roo.Button.buttonTemplate;
11812 btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
11813 var btnEl = btn.child("button:first");
11814 btnEl.on('focus', this.onFocus, this);
11815 btnEl.on('blur', this.onBlur, this);
11817 btn.addClass(this.cls);
11820 btnEl.setStyle('background-image', 'url(' +this.icon +')');
11823 btnEl.addClass(this.iconCls);
11825 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
11828 if(this.tabIndex !== undefined){
11829 btnEl.dom.tabIndex = this.tabIndex;
11832 if(typeof this.tooltip == 'object'){
11833 Roo.QuickTips.tips(Roo.apply({
11837 btnEl.dom[this.tooltipType] = this.tooltip;
11841 btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
11845 this.el.dom.id = this.el.id = this.id;
11848 this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
11849 this.menu.on("show", this.onMenuShow, this);
11850 this.menu.on("hide", this.onMenuHide, this);
11852 btn.addClass("x-btn");
11853 if(Roo.isIE && !Roo.isIE7){
11854 this.autoWidth.defer(1, this);
11858 if(this.handleMouseEvents){
11859 btn.on("mouseover", this.onMouseOver, this);
11860 btn.on("mouseout", this.onMouseOut, this);
11861 btn.on("mousedown", this.onMouseDown, this);
11863 btn.on(this.clickEvent, this.onClick, this);
11864 //btn.on("mouseup", this.onMouseUp, this);
11871 Roo.ButtonToggleMgr.register(this);
11873 this.el.addClass("x-btn-pressed");
11876 var repeater = new Roo.util.ClickRepeater(btn,
11877 typeof this.repeat == "object" ? this.repeat : {}
11879 repeater.on("click", this.onClick, this);
11882 this.fireEvent('render', this);
11886 * Returns the button's underlying element
11887 * @return {Roo.Element} The element
11889 getEl : function(){
11894 * Destroys this Button and removes any listeners.
11896 destroy : function(){
11897 Roo.ButtonToggleMgr.unregister(this);
11898 this.el.removeAllListeners();
11899 this.purgeListeners();
11904 autoWidth : function(){
11906 this.el.setWidth("auto");
11907 if(Roo.isIE7 && Roo.isStrict){
11908 var ib = this.el.child('button');
11909 if(ib && ib.getWidth() > 20){
11911 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
11916 this.el.beginMeasure();
11918 if(this.el.getWidth() < this.minWidth){
11919 this.el.setWidth(this.minWidth);
11922 this.el.endMeasure();
11929 * Assigns this button's click handler
11930 * @param {Function} handler The function to call when the button is clicked
11931 * @param {Object} scope (optional) Scope for the function passed in
11933 setHandler : function(handler, scope){
11934 this.handler = handler;
11935 this.scope = scope;
11939 * Sets this button's text
11940 * @param {String} text The button text
11942 setText : function(text){
11945 this.el.child("td.x-btn-center button.x-btn-text").update(text);
11951 * Gets the text for this button
11952 * @return {String} The button text
11954 getText : function(){
11962 this.hidden = false;
11964 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
11972 this.hidden = true;
11974 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
11979 * Convenience function for boolean show/hide
11980 * @param {Boolean} visible True to show, false to hide
11982 setVisible: function(visible){
11991 * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
11992 * @param {Boolean} state (optional) Force a particular state
11994 toggle : function(state){
11995 state = state === undefined ? !this.pressed : state;
11996 if(state != this.pressed){
11998 this.el.addClass("x-btn-pressed");
11999 this.pressed = true;
12000 this.fireEvent("toggle", this, true);
12002 this.el.removeClass("x-btn-pressed");
12003 this.pressed = false;
12004 this.fireEvent("toggle", this, false);
12006 if(this.toggleHandler){
12007 this.toggleHandler.call(this.scope || this, this, state);
12015 focus : function(){
12016 this.el.child('button:first').focus();
12020 * Disable this button
12022 disable : function(){
12024 this.el.addClass("x-btn-disabled");
12026 this.disabled = true;
12030 * Enable this button
12032 enable : function(){
12034 this.el.removeClass("x-btn-disabled");
12036 this.disabled = false;
12040 * Convenience function for boolean enable/disable
12041 * @param {Boolean} enabled True to enable, false to disable
12043 setDisabled : function(v){
12044 this[v !== true ? "enable" : "disable"]();
12048 onClick : function(e){
12050 e.preventDefault();
12055 if(!this.disabled){
12056 if(this.enableToggle){
12059 if(this.menu && !this.menu.isVisible()){
12060 this.menu.show(this.el, this.menuAlign);
12062 this.fireEvent("click", this, e);
12064 this.el.removeClass("x-btn-over");
12065 this.handler.call(this.scope || this, this, e);
12070 onMouseOver : function(e){
12071 if(!this.disabled){
12072 this.el.addClass("x-btn-over");
12073 this.fireEvent('mouseover', this, e);
12077 onMouseOut : function(e){
12078 if(!e.within(this.el, true)){
12079 this.el.removeClass("x-btn-over");
12080 this.fireEvent('mouseout', this, e);
12084 onFocus : function(e){
12085 if(!this.disabled){
12086 this.el.addClass("x-btn-focus");
12090 onBlur : function(e){
12091 this.el.removeClass("x-btn-focus");
12094 onMouseDown : function(e){
12095 if(!this.disabled && e.button == 0){
12096 this.el.addClass("x-btn-click");
12097 Roo.get(document).on('mouseup', this.onMouseUp, this);
12101 onMouseUp : function(e){
12103 this.el.removeClass("x-btn-click");
12104 Roo.get(document).un('mouseup', this.onMouseUp, this);
12108 onMenuShow : function(e){
12109 this.el.addClass("x-btn-menu-active");
12112 onMenuHide : function(e){
12113 this.el.removeClass("x-btn-menu-active");
12117 // Private utility class used by Button
12118 Roo.ButtonToggleMgr = function(){
12121 function toggleGroup(btn, state){
12123 var g = groups[btn.toggleGroup];
12124 for(var i = 0, l = g.length; i < l; i++){
12126 g[i].toggle(false);
12133 register : function(btn){
12134 if(!btn.toggleGroup){
12137 var g = groups[btn.toggleGroup];
12139 g = groups[btn.toggleGroup] = [];
12142 btn.on("toggle", toggleGroup);
12145 unregister : function(btn){
12146 if(!btn.toggleGroup){
12149 var g = groups[btn.toggleGroup];
12152 btn.un("toggle", toggleGroup);
12158 * Ext JS Library 1.1.1
12159 * Copyright(c) 2006-2007, Ext JS, LLC.
12161 * Originally Released Under LGPL - original licence link has changed is not relivant.
12164 * <script type="text/javascript">
12168 * @class Roo.SplitButton
12169 * @extends Roo.Button
12170 * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
12171 * click event of the button. Typically this would be used to display a dropdown menu that provides additional
12172 * options to the primary button action, but any custom handler can provide the arrowclick implementation.
12173 * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
12174 * @cfg {String} arrowTooltip The title attribute of the arrow
12176 * Create a new menu button
12177 * @param {String/HTMLElement/Element} renderTo The element to append the button to
12178 * @param {Object} config The config object
12180 Roo.SplitButton = function(renderTo, config){
12181 Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
12183 * @event arrowclick
12184 * Fires when this button's arrow is clicked
12185 * @param {SplitButton} this
12186 * @param {EventObject} e The click event
12188 this.addEvents({"arrowclick":true});
12191 Roo.extend(Roo.SplitButton, Roo.Button, {
12192 render : function(renderTo){
12193 // this is one sweet looking template!
12194 var tpl = new Roo.Template(
12195 '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
12196 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
12197 '<tr><td class="x-btn-left"><i> </i></td><td class="x-btn-center"><button class="x-btn-text" type="{1}">{0}</button></td></tr>',
12198 "</tbody></table></td><td>",
12199 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
12200 '<tr><td class="x-btn-center"><button class="x-btn-menu-arrow-el" type="button"> </button></td><td class="x-btn-right"><i> </i></td></tr>',
12201 "</tbody></table></td></tr></table>"
12203 var btn = tpl.append(renderTo, [this.text, this.type], true);
12204 var btnEl = btn.child("button");
12206 btn.addClass(this.cls);
12209 btnEl.setStyle('background-image', 'url(' +this.icon +')');
12212 btnEl.addClass(this.iconCls);
12214 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
12218 if(this.handleMouseEvents){
12219 btn.on("mouseover", this.onMouseOver, this);
12220 btn.on("mouseout", this.onMouseOut, this);
12221 btn.on("mousedown", this.onMouseDown, this);
12222 btn.on("mouseup", this.onMouseUp, this);
12224 btn.on(this.clickEvent, this.onClick, this);
12226 if(typeof this.tooltip == 'object'){
12227 Roo.QuickTips.tips(Roo.apply({
12231 btnEl.dom[this.tooltipType] = this.tooltip;
12234 if(this.arrowTooltip){
12235 btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
12244 this.el.addClass("x-btn-pressed");
12246 if(Roo.isIE && !Roo.isIE7){
12247 this.autoWidth.defer(1, this);
12252 this.menu.on("show", this.onMenuShow, this);
12253 this.menu.on("hide", this.onMenuHide, this);
12255 this.fireEvent('render', this);
12259 autoWidth : function(){
12261 var tbl = this.el.child("table:first");
12262 var tbl2 = this.el.child("table:last");
12263 this.el.setWidth("auto");
12264 tbl.setWidth("auto");
12265 if(Roo.isIE7 && Roo.isStrict){
12266 var ib = this.el.child('button:first');
12267 if(ib && ib.getWidth() > 20){
12269 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
12274 this.el.beginMeasure();
12276 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
12277 tbl.setWidth(this.minWidth-tbl2.getWidth());
12280 this.el.endMeasure();
12283 this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
12287 * Sets this button's click handler
12288 * @param {Function} handler The function to call when the button is clicked
12289 * @param {Object} scope (optional) Scope for the function passed above
12291 setHandler : function(handler, scope){
12292 this.handler = handler;
12293 this.scope = scope;
12297 * Sets this button's arrow click handler
12298 * @param {Function} handler The function to call when the arrow is clicked
12299 * @param {Object} scope (optional) Scope for the function passed above
12301 setArrowHandler : function(handler, scope){
12302 this.arrowHandler = handler;
12303 this.scope = scope;
12309 focus : function(){
12311 this.el.child("button:first").focus();
12316 onClick : function(e){
12317 e.preventDefault();
12318 if(!this.disabled){
12319 if(e.getTarget(".x-btn-menu-arrow-wrap")){
12320 if(this.menu && !this.menu.isVisible()){
12321 this.menu.show(this.el, this.menuAlign);
12323 this.fireEvent("arrowclick", this, e);
12324 if(this.arrowHandler){
12325 this.arrowHandler.call(this.scope || this, this, e);
12328 this.fireEvent("click", this, e);
12330 this.handler.call(this.scope || this, this, e);
12336 onMouseDown : function(e){
12337 if(!this.disabled){
12338 Roo.fly(e.getTarget("table")).addClass("x-btn-click");
12342 onMouseUp : function(e){
12343 Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
12348 // backwards compat
12349 Roo.MenuButton = Roo.SplitButton;/*
12351 * Ext JS Library 1.1.1
12352 * Copyright(c) 2006-2007, Ext JS, LLC.
12354 * Originally Released Under LGPL - original licence link has changed is not relivant.
12357 * <script type="text/javascript">
12361 * @class Roo.Toolbar
12362 * Basic Toolbar class.
12364 * Creates a new Toolbar
12365 * @param {Object} container The config object
12367 Roo.Toolbar = function(container, buttons, config)
12369 /// old consturctor format still supported..
12370 if(container instanceof Array){ // omit the container for later rendering
12371 buttons = container;
12375 if (typeof(container) == 'object' && container.xtype) {
12376 config = container;
12377 container = config.container;
12378 buttons = config.buttons || []; // not really - use items!!
12381 if (config && config.items) {
12382 xitems = config.items;
12383 delete config.items;
12385 Roo.apply(this, config);
12386 this.buttons = buttons;
12389 this.render(container);
12391 this.xitems = xitems;
12392 Roo.each(xitems, function(b) {
12398 Roo.Toolbar.prototype = {
12400 * @cfg {Array} items
12401 * array of button configs or elements to add (will be converted to a MixedCollection)
12405 * @cfg {String/HTMLElement/Element} container
12406 * The id or element that will contain the toolbar
12409 render : function(ct){
12410 this.el = Roo.get(ct);
12412 this.el.addClass(this.cls);
12414 // using a table allows for vertical alignment
12415 // 100% width is needed by Safari...
12416 this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
12417 this.tr = this.el.child("tr", true);
12419 this.items = new Roo.util.MixedCollection(false, function(o){
12420 return o.id || ("item" + (++autoId));
12423 this.add.apply(this, this.buttons);
12424 delete this.buttons;
12429 * Adds element(s) to the toolbar -- this function takes a variable number of
12430 * arguments of mixed type and adds them to the toolbar.
12431 * @param {Mixed} arg1 The following types of arguments are all valid:<br />
12433 * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
12434 * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
12435 * <li>Field: Any form field (equivalent to {@link #addField})</li>
12436 * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
12437 * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
12438 * Note that there are a few special strings that are treated differently as explained nRoo.</li>
12439 * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
12440 * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
12441 * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
12443 * @param {Mixed} arg2
12444 * @param {Mixed} etc.
12447 var a = arguments, l = a.length;
12448 for(var i = 0; i < l; i++){
12453 _add : function(el) {
12456 el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
12459 if (el.applyTo){ // some kind of form field
12460 return this.addField(el);
12462 if (el.render){ // some kind of Toolbar.Item
12463 return this.addItem(el);
12465 if (typeof el == "string"){ // string
12466 if(el == "separator" || el == "-"){
12467 return this.addSeparator();
12470 return this.addSpacer();
12473 return this.addFill();
12475 return this.addText(el);
12478 if(el.tagName){ // element
12479 return this.addElement(el);
12481 if(typeof el == "object"){ // must be button config?
12482 return this.addButton(el);
12484 // and now what?!?!
12490 * Add an Xtype element
12491 * @param {Object} xtype Xtype Object
12492 * @return {Object} created Object
12494 addxtype : function(e){
12495 return this.add(e);
12499 * Returns the Element for this toolbar.
12500 * @return {Roo.Element}
12502 getEl : function(){
12508 * @return {Roo.Toolbar.Item} The separator item
12510 addSeparator : function(){
12511 return this.addItem(new Roo.Toolbar.Separator());
12515 * Adds a spacer element
12516 * @return {Roo.Toolbar.Spacer} The spacer item
12518 addSpacer : function(){
12519 return this.addItem(new Roo.Toolbar.Spacer());
12523 * Adds a fill element that forces subsequent additions to the right side of the toolbar
12524 * @return {Roo.Toolbar.Fill} The fill item
12526 addFill : function(){
12527 return this.addItem(new Roo.Toolbar.Fill());
12531 * Adds any standard HTML element to the toolbar
12532 * @param {String/HTMLElement/Element} el The element or id of the element to add
12533 * @return {Roo.Toolbar.Item} The element's item
12535 addElement : function(el){
12536 return this.addItem(new Roo.Toolbar.Item(el));
12539 * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
12540 * @type Roo.util.MixedCollection
12545 * Adds any Toolbar.Item or subclass
12546 * @param {Roo.Toolbar.Item} item
12547 * @return {Roo.Toolbar.Item} The item
12549 addItem : function(item){
12550 var td = this.nextBlock();
12552 this.items.add(item);
12557 * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
12558 * @param {Object/Array} config A button config or array of configs
12559 * @return {Roo.Toolbar.Button/Array}
12561 addButton : function(config){
12562 if(config instanceof Array){
12564 for(var i = 0, len = config.length; i < len; i++) {
12565 buttons.push(this.addButton(config[i]));
12570 if(!(config instanceof Roo.Toolbar.Button)){
12572 new Roo.Toolbar.SplitButton(config) :
12573 new Roo.Toolbar.Button(config);
12575 var td = this.nextBlock();
12582 * Adds text to the toolbar
12583 * @param {String} text The text to add
12584 * @return {Roo.Toolbar.Item} The element's item
12586 addText : function(text){
12587 return this.addItem(new Roo.Toolbar.TextItem(text));
12591 * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
12592 * @param {Number} index The index where the item is to be inserted
12593 * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
12594 * @return {Roo.Toolbar.Button/Item}
12596 insertButton : function(index, item){
12597 if(item instanceof Array){
12599 for(var i = 0, len = item.length; i < len; i++) {
12600 buttons.push(this.insertButton(index + i, item[i]));
12604 if (!(item instanceof Roo.Toolbar.Button)){
12605 item = new Roo.Toolbar.Button(item);
12607 var td = document.createElement("td");
12608 this.tr.insertBefore(td, this.tr.childNodes[index]);
12610 this.items.insert(index, item);
12615 * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
12616 * @param {Object} config
12617 * @return {Roo.Toolbar.Item} The element's item
12619 addDom : function(config, returnEl){
12620 var td = this.nextBlock();
12621 Roo.DomHelper.overwrite(td, config);
12622 var ti = new Roo.Toolbar.Item(td.firstChild);
12624 this.items.add(ti);
12629 * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
12630 * @type Roo.util.MixedCollection
12635 * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
12636 * Note: the field should not have been rendered yet. For a field that has already been
12637 * rendered, use {@link #addElement}.
12638 * @param {Roo.form.Field} field
12639 * @return {Roo.ToolbarItem}
12643 addField : function(field) {
12644 if (!this.fields) {
12646 this.fields = new Roo.util.MixedCollection(false, function(o){
12647 return o.id || ("item" + (++autoId));
12652 var td = this.nextBlock();
12654 var ti = new Roo.Toolbar.Item(td.firstChild);
12656 this.items.add(ti);
12657 this.fields.add(field);
12668 this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
12669 this.el.child('div').hide();
12677 this.el.child('div').show();
12681 nextBlock : function(){
12682 var td = document.createElement("td");
12683 this.tr.appendChild(td);
12688 destroy : function(){
12689 if(this.items){ // rendered?
12690 Roo.destroy.apply(Roo, this.items.items);
12692 if(this.fields){ // rendered?
12693 Roo.destroy.apply(Roo, this.fields.items);
12695 Roo.Element.uncache(this.el, this.tr);
12700 * @class Roo.Toolbar.Item
12701 * The base class that other classes should extend in order to get some basic common toolbar item functionality.
12703 * Creates a new Item
12704 * @param {HTMLElement} el
12706 Roo.Toolbar.Item = function(el){
12707 this.el = Roo.getDom(el);
12708 this.id = Roo.id(this.el);
12709 this.hidden = false;
12712 Roo.Toolbar.Item.prototype = {
12715 * Get this item's HTML Element
12716 * @return {HTMLElement}
12718 getEl : function(){
12723 render : function(td){
12725 td.appendChild(this.el);
12729 * Removes and destroys this item.
12731 destroy : function(){
12732 this.td.parentNode.removeChild(this.td);
12739 this.hidden = false;
12740 this.td.style.display = "";
12747 this.hidden = true;
12748 this.td.style.display = "none";
12752 * Convenience function for boolean show/hide.
12753 * @param {Boolean} visible true to show/false to hide
12755 setVisible: function(visible){
12764 * Try to focus this item.
12766 focus : function(){
12767 Roo.fly(this.el).focus();
12771 * Disables this item.
12773 disable : function(){
12774 Roo.fly(this.td).addClass("x-item-disabled");
12775 this.disabled = true;
12776 this.el.disabled = true;
12780 * Enables this item.
12782 enable : function(){
12783 Roo.fly(this.td).removeClass("x-item-disabled");
12784 this.disabled = false;
12785 this.el.disabled = false;
12791 * @class Roo.Toolbar.Separator
12792 * @extends Roo.Toolbar.Item
12793 * A simple toolbar separator class
12795 * Creates a new Separator
12797 Roo.Toolbar.Separator = function(){
12798 var s = document.createElement("span");
12799 s.className = "ytb-sep";
12800 Roo.Toolbar.Separator.superclass.constructor.call(this, s);
12802 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
12803 enable:Roo.emptyFn,
12804 disable:Roo.emptyFn,
12809 * @class Roo.Toolbar.Spacer
12810 * @extends Roo.Toolbar.Item
12811 * A simple element that adds extra horizontal space to a toolbar.
12813 * Creates a new Spacer
12815 Roo.Toolbar.Spacer = function(){
12816 var s = document.createElement("div");
12817 s.className = "ytb-spacer";
12818 Roo.Toolbar.Spacer.superclass.constructor.call(this, s);
12820 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
12821 enable:Roo.emptyFn,
12822 disable:Roo.emptyFn,
12827 * @class Roo.Toolbar.Fill
12828 * @extends Roo.Toolbar.Spacer
12829 * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
12831 * Creates a new Spacer
12833 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
12835 render : function(td){
12836 td.style.width = '100%';
12837 Roo.Toolbar.Fill.superclass.render.call(this, td);
12842 * @class Roo.Toolbar.TextItem
12843 * @extends Roo.Toolbar.Item
12844 * A simple class that renders text directly into a toolbar.
12846 * Creates a new TextItem
12847 * @param {String} text
12849 Roo.Toolbar.TextItem = function(text){
12850 if (typeof(text) == 'object') {
12853 var s = document.createElement("span");
12854 s.className = "ytb-text";
12855 s.innerHTML = text;
12856 Roo.Toolbar.TextItem.superclass.constructor.call(this, s);
12858 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
12859 enable:Roo.emptyFn,
12860 disable:Roo.emptyFn,
12865 * @class Roo.Toolbar.Button
12866 * @extends Roo.Button
12867 * A button that renders into a toolbar.
12869 * Creates a new Button
12870 * @param {Object} config A standard {@link Roo.Button} config object
12872 Roo.Toolbar.Button = function(config){
12873 Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
12875 Roo.extend(Roo.Toolbar.Button, Roo.Button, {
12876 render : function(td){
12878 Roo.Toolbar.Button.superclass.render.call(this, td);
12882 * Removes and destroys this button
12884 destroy : function(){
12885 Roo.Toolbar.Button.superclass.destroy.call(this);
12886 this.td.parentNode.removeChild(this.td);
12890 * Shows this button
12893 this.hidden = false;
12894 this.td.style.display = "";
12898 * Hides this button
12901 this.hidden = true;
12902 this.td.style.display = "none";
12906 * Disables this item
12908 disable : function(){
12909 Roo.fly(this.td).addClass("x-item-disabled");
12910 this.disabled = true;
12914 * Enables this item
12916 enable : function(){
12917 Roo.fly(this.td).removeClass("x-item-disabled");
12918 this.disabled = false;
12921 // backwards compat
12922 Roo.ToolbarButton = Roo.Toolbar.Button;
12925 * @class Roo.Toolbar.SplitButton
12926 * @extends Roo.SplitButton
12927 * A menu button that renders into a toolbar.
12929 * Creates a new SplitButton
12930 * @param {Object} config A standard {@link Roo.SplitButton} config object
12932 Roo.Toolbar.SplitButton = function(config){
12933 Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
12935 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
12936 render : function(td){
12938 Roo.Toolbar.SplitButton.superclass.render.call(this, td);
12942 * Removes and destroys this button
12944 destroy : function(){
12945 Roo.Toolbar.SplitButton.superclass.destroy.call(this);
12946 this.td.parentNode.removeChild(this.td);
12950 * Shows this button
12953 this.hidden = false;
12954 this.td.style.display = "";
12958 * Hides this button
12961 this.hidden = true;
12962 this.td.style.display = "none";
12966 // backwards compat
12967 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
12969 * Ext JS Library 1.1.1
12970 * Copyright(c) 2006-2007, Ext JS, LLC.
12972 * Originally Released Under LGPL - original licence link has changed is not relivant.
12975 * <script type="text/javascript">
12979 * @class Roo.PagingToolbar
12980 * @extends Roo.Toolbar
12981 * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
12983 * Create a new PagingToolbar
12984 * @param {Object} config The config object
12986 Roo.PagingToolbar = function(el, ds, config)
12988 // old args format still supported... - xtype is prefered..
12989 if (typeof(el) == 'object' && el.xtype) {
12990 // created from xtype...
12992 ds = el.dataSource;
12993 el = config.container;
12996 if (config.items) {
12997 items = config.items;
13001 Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
13004 this.renderButtons(this.el);
13007 // supprot items array.
13009 Roo.each(items, function(e) {
13010 this.add(Roo.factory(e));
13015 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
13017 * @cfg {Roo.data.Store} dataSource
13018 * The underlying data store providing the paged data
13021 * @cfg {String/HTMLElement/Element} container
13022 * container The id or element that will contain the toolbar
13025 * @cfg {Boolean} displayInfo
13026 * True to display the displayMsg (defaults to false)
13029 * @cfg {Number} pageSize
13030 * The number of records to display per page (defaults to 20)
13034 * @cfg {String} displayMsg
13035 * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
13037 displayMsg : 'Displaying {0} - {1} of {2}',
13039 * @cfg {String} emptyMsg
13040 * The message to display when no records are found (defaults to "No data to display")
13042 emptyMsg : 'No data to display',
13044 * Customizable piece of the default paging text (defaults to "Page")
13047 beforePageText : "Page",
13049 * Customizable piece of the default paging text (defaults to "of %0")
13052 afterPageText : "of {0}",
13054 * Customizable piece of the default paging text (defaults to "First Page")
13057 firstText : "First Page",
13059 * Customizable piece of the default paging text (defaults to "Previous Page")
13062 prevText : "Previous Page",
13064 * Customizable piece of the default paging text (defaults to "Next Page")
13067 nextText : "Next Page",
13069 * Customizable piece of the default paging text (defaults to "Last Page")
13072 lastText : "Last Page",
13074 * Customizable piece of the default paging text (defaults to "Refresh")
13077 refreshText : "Refresh",
13080 renderButtons : function(el){
13081 Roo.PagingToolbar.superclass.render.call(this, el);
13082 this.first = this.addButton({
13083 tooltip: this.firstText,
13084 cls: "x-btn-icon x-grid-page-first",
13086 handler: this.onClick.createDelegate(this, ["first"])
13088 this.prev = this.addButton({
13089 tooltip: this.prevText,
13090 cls: "x-btn-icon x-grid-page-prev",
13092 handler: this.onClick.createDelegate(this, ["prev"])
13094 //this.addSeparator();
13095 this.add(this.beforePageText);
13096 this.field = Roo.get(this.addDom({
13101 cls: "x-grid-page-number"
13103 this.field.on("keydown", this.onPagingKeydown, this);
13104 this.field.on("focus", function(){this.dom.select();});
13105 this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
13106 this.field.setHeight(18);
13107 //this.addSeparator();
13108 this.next = this.addButton({
13109 tooltip: this.nextText,
13110 cls: "x-btn-icon x-grid-page-next",
13112 handler: this.onClick.createDelegate(this, ["next"])
13114 this.last = this.addButton({
13115 tooltip: this.lastText,
13116 cls: "x-btn-icon x-grid-page-last",
13118 handler: this.onClick.createDelegate(this, ["last"])
13120 //this.addSeparator();
13121 this.loading = this.addButton({
13122 tooltip: this.refreshText,
13123 cls: "x-btn-icon x-grid-loading",
13124 handler: this.onClick.createDelegate(this, ["refresh"])
13127 if(this.displayInfo){
13128 this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
13133 updateInfo : function(){
13134 if(this.displayEl){
13135 var count = this.ds.getCount();
13136 var msg = count == 0 ?
13140 this.cursor+1, this.cursor+count, this.ds.getTotalCount()
13142 this.displayEl.update(msg);
13147 onLoad : function(ds, r, o){
13148 this.cursor = o.params ? o.params.start : 0;
13149 var d = this.getPageData(), ap = d.activePage, ps = d.pages;
13151 this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
13152 this.field.dom.value = ap;
13153 this.first.setDisabled(ap == 1);
13154 this.prev.setDisabled(ap == 1);
13155 this.next.setDisabled(ap == ps);
13156 this.last.setDisabled(ap == ps);
13157 this.loading.enable();
13162 getPageData : function(){
13163 var total = this.ds.getTotalCount();
13166 activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
13167 pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
13172 onLoadError : function(){
13173 this.loading.enable();
13177 onPagingKeydown : function(e){
13178 var k = e.getKey();
13179 var d = this.getPageData();
13181 var v = this.field.dom.value, pageNum;
13182 if(!v || isNaN(pageNum = parseInt(v, 10))){
13183 this.field.dom.value = d.activePage;
13186 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
13187 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
13190 else if(k == e.HOME || (k == e.UP && e.ctrlKey) || (k == e.PAGEUP && e.ctrlKey) || (k == e.RIGHT && e.ctrlKey) || k == e.END || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey))
13192 var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
13193 this.field.dom.value = pageNum;
13194 this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
13197 else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
13199 var v = this.field.dom.value, pageNum;
13200 var increment = (e.shiftKey) ? 10 : 1;
13201 if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
13203 if(!v || isNaN(pageNum = parseInt(v, 10))) {
13204 this.field.dom.value = d.activePage;
13207 else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
13209 this.field.dom.value = parseInt(v, 10) + increment;
13210 pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
13211 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
13218 beforeLoad : function(){
13220 this.loading.disable();
13225 onClick : function(which){
13229 ds.load({params:{start: 0, limit: this.pageSize}});
13232 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
13235 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
13238 var total = ds.getTotalCount();
13239 var extra = total % this.pageSize;
13240 var lastStart = extra ? (total - extra) : total-this.pageSize;
13241 ds.load({params:{start: lastStart, limit: this.pageSize}});
13244 ds.load({params:{start: this.cursor, limit: this.pageSize}});
13250 * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
13251 * @param {Roo.data.Store} store The data store to unbind
13253 unbind : function(ds){
13254 ds.un("beforeload", this.beforeLoad, this);
13255 ds.un("load", this.onLoad, this);
13256 ds.un("loadexception", this.onLoadError, this);
13257 ds.un("remove", this.updateInfo, this);
13258 ds.un("add", this.updateInfo, this);
13259 this.ds = undefined;
13263 * Binds the paging toolbar to the specified {@link Roo.data.Store}
13264 * @param {Roo.data.Store} store The data store to bind
13266 bind : function(ds){
13267 ds.on("beforeload", this.beforeLoad, this);
13268 ds.on("load", this.onLoad, this);
13269 ds.on("loadexception", this.onLoadError, this);
13270 ds.on("remove", this.updateInfo, this);
13271 ds.on("add", this.updateInfo, this);
13276 * Ext JS Library 1.1.1
13277 * Copyright(c) 2006-2007, Ext JS, LLC.
13279 * Originally Released Under LGPL - original licence link has changed is not relivant.
13282 * <script type="text/javascript">
13286 * @class Roo.Resizable
13287 * @extends Roo.util.Observable
13288 * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
13289 * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
13290 * the textarea in a div and set "resizeChild" to true (or to the id of the element), <b>or</b> set wrap:true in your config and
13291 * the element will be wrapped for you automatically.</p>
13292 * <p>Here is the list of valid resize handles:</p>
13295 ------ -------------------
13304 'hd' horizontal drag
13307 * <p>Here's an example showing the creation of a typical Resizable:</p>
13309 var resizer = new Roo.Resizable("element-id", {
13317 resizer.on("resize", myHandler);
13319 * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
13320 * resizer.east.setDisplayed(false);</p>
13321 * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
13322 * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
13323 * resize operation's new size (defaults to [0, 0])
13324 * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
13325 * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
13326 * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
13327 * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
13328 * @cfg {Boolean} enabled False to disable resizing (defaults to true)
13329 * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
13330 * @cfg {Number} width The width of the element in pixels (defaults to null)
13331 * @cfg {Number} height The height of the element in pixels (defaults to null)
13332 * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
13333 * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
13334 * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
13335 * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
13336 * @cfg {Boolean} multiDirectional <b>Deprecated</b>. The old style of adding multi-direction resize handles, deprecated
13337 * in favor of the handles config option (defaults to false)
13338 * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
13339 * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
13340 * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
13341 * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
13342 * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
13343 * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
13344 * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
13345 * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
13346 * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
13347 * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
13348 * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
13350 * Create a new resizable component
13351 * @param {String/HTMLElement/Roo.Element} el The id or element to resize
13352 * @param {Object} config configuration options
13354 Roo.Resizable = function(el, config)
13356 this.el = Roo.get(el);
13358 if(config && config.wrap){
13359 config.resizeChild = this.el;
13360 this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
13361 this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
13362 this.el.setStyle("overflow", "hidden");
13363 this.el.setPositioning(config.resizeChild.getPositioning());
13364 config.resizeChild.clearPositioning();
13365 if(!config.width || !config.height){
13366 var csize = config.resizeChild.getSize();
13367 this.el.setSize(csize.width, csize.height);
13369 if(config.pinned && !config.adjustments){
13370 config.adjustments = "auto";
13374 this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
13375 this.proxy.unselectable();
13376 this.proxy.enableDisplayMode('block');
13378 Roo.apply(this, config);
13381 this.disableTrackOver = true;
13382 this.el.addClass("x-resizable-pinned");
13384 // if the element isn't positioned, make it relative
13385 var position = this.el.getStyle("position");
13386 if(position != "absolute" && position != "fixed"){
13387 this.el.setStyle("position", "relative");
13389 if(!this.handles){ // no handles passed, must be legacy style
13390 this.handles = 's,e,se';
13391 if(this.multiDirectional){
13392 this.handles += ',n,w';
13395 if(this.handles == "all"){
13396 this.handles = "n s e w ne nw se sw";
13398 var hs = this.handles.split(/\s*?[,;]\s*?| /);
13399 var ps = Roo.Resizable.positions;
13400 for(var i = 0, len = hs.length; i < len; i++){
13401 if(hs[i] && ps[hs[i]]){
13402 var pos = ps[hs[i]];
13403 this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
13407 this.corner = this.southeast;
13409 // updateBox = the box can move..
13410 if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
13411 this.updateBox = true;
13414 this.activeHandle = null;
13416 if(this.resizeChild){
13417 if(typeof this.resizeChild == "boolean"){
13418 this.resizeChild = Roo.get(this.el.dom.firstChild, true);
13420 this.resizeChild = Roo.get(this.resizeChild, true);
13424 if(this.adjustments == "auto"){
13425 var rc = this.resizeChild;
13426 var hw = this.west, he = this.east, hn = this.north, hs = this.south;
13427 if(rc && (hw || hn)){
13428 rc.position("relative");
13429 rc.setLeft(hw ? hw.el.getWidth() : 0);
13430 rc.setTop(hn ? hn.el.getHeight() : 0);
13432 this.adjustments = [
13433 (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
13434 (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
13438 if(this.draggable){
13439 this.dd = this.dynamic ?
13440 this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
13441 this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
13447 * @event beforeresize
13448 * Fired before resize is allowed. Set enabled to false to cancel resize.
13449 * @param {Roo.Resizable} this
13450 * @param {Roo.EventObject} e The mousedown event
13452 "beforeresize" : true,
13455 * Fired after a resize.
13456 * @param {Roo.Resizable} this
13457 * @param {Number} width The new width
13458 * @param {Number} height The new height
13459 * @param {Roo.EventObject} e The mouseup event
13464 if(this.width !== null && this.height !== null){
13465 this.resizeTo(this.width, this.height);
13467 this.updateChildSize();
13470 this.el.dom.style.zoom = 1;
13472 Roo.Resizable.superclass.constructor.call(this);
13475 Roo.extend(Roo.Resizable, Roo.util.Observable, {
13476 resizeChild : false,
13477 adjustments : [0, 0],
13487 multiDirectional : false,
13488 disableTrackOver : false,
13489 easing : 'easeOutStrong',
13490 widthIncrement : 0,
13491 heightIncrement : 0,
13495 preserveRatio : false,
13496 transparent: false,
13502 * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
13504 constrainTo: undefined,
13506 * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
13508 resizeRegion: undefined,
13512 * Perform a manual resize
13513 * @param {Number} width
13514 * @param {Number} height
13516 resizeTo : function(width, height){
13517 this.el.setSize(width, height);
13518 this.updateChildSize();
13519 this.fireEvent("resize", this, width, height, null);
13523 startSizing : function(e, handle){
13524 this.fireEvent("beforeresize", this, e);
13525 if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
13528 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: " "});
13529 this.overlay.unselectable();
13530 this.overlay.enableDisplayMode("block");
13531 this.overlay.on("mousemove", this.onMouseMove, this);
13532 this.overlay.on("mouseup", this.onMouseUp, this);
13534 this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
13536 this.resizing = true;
13537 this.startBox = this.el.getBox();
13538 this.startPoint = e.getXY();
13539 this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
13540 (this.startBox.y + this.startBox.height) - this.startPoint[1]];
13542 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
13543 this.overlay.show();
13545 if(this.constrainTo) {
13546 var ct = Roo.get(this.constrainTo);
13547 this.resizeRegion = ct.getRegion().adjust(
13548 ct.getFrameWidth('t'),
13549 ct.getFrameWidth('l'),
13550 -ct.getFrameWidth('b'),
13551 -ct.getFrameWidth('r')
13555 this.proxy.setStyle('visibility', 'hidden'); // workaround display none
13557 this.proxy.setBox(this.startBox);
13559 this.proxy.setStyle('visibility', 'visible');
13565 onMouseDown : function(handle, e){
13568 this.activeHandle = handle;
13569 this.startSizing(e, handle);
13574 onMouseUp : function(e){
13575 var size = this.resizeElement();
13576 this.resizing = false;
13578 this.overlay.hide();
13580 this.fireEvent("resize", this, size.width, size.height, e);
13584 updateChildSize : function(){
13585 if(this.resizeChild){
13587 var child = this.resizeChild;
13588 var adj = this.adjustments;
13589 if(el.dom.offsetWidth){
13590 var b = el.getSize(true);
13591 child.setSize(b.width+adj[0], b.height+adj[1]);
13593 // Second call here for IE
13594 // The first call enables instant resizing and
13595 // the second call corrects scroll bars if they
13598 setTimeout(function(){
13599 if(el.dom.offsetWidth){
13600 var b = el.getSize(true);
13601 child.setSize(b.width+adj[0], b.height+adj[1]);
13609 snap : function(value, inc, min){
13610 if(!inc || !value) return value;
13611 var newValue = value;
13612 var m = value % inc;
13615 newValue = value + (inc-m);
13617 newValue = value - m;
13620 return Math.max(min, newValue);
13624 resizeElement : function(){
13625 var box = this.proxy.getBox();
13626 if(this.updateBox){
13627 this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
13629 this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
13631 this.updateChildSize();
13639 constrain : function(v, diff, m, mx){
13642 }else if(v - diff > mx){
13649 onMouseMove : function(e){
13651 try{// try catch so if something goes wrong the user doesn't get hung
13653 if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
13657 //var curXY = this.startPoint;
13658 var curSize = this.curSize || this.startBox;
13659 var x = this.startBox.x, y = this.startBox.y;
13660 var ox = x, oy = y;
13661 var w = curSize.width, h = curSize.height;
13662 var ow = w, oh = h;
13663 var mw = this.minWidth, mh = this.minHeight;
13664 var mxw = this.maxWidth, mxh = this.maxHeight;
13665 var wi = this.widthIncrement;
13666 var hi = this.heightIncrement;
13668 var eventXY = e.getXY();
13669 var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
13670 var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
13672 var pos = this.activeHandle.position;
13677 w = Math.min(Math.max(mw, w), mxw);
13682 h = Math.min(Math.max(mh, h), mxh);
13687 w = Math.min(Math.max(mw, w), mxw);
13688 h = Math.min(Math.max(mh, h), mxh);
13691 diffY = this.constrain(h, diffY, mh, mxh);
13698 var adiffX = Math.abs(diffX);
13699 var sub = (adiffX % wi); // how much
13700 if (sub > (wi/2)) { // far enough to snap
13701 diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
13703 // remove difference..
13704 diffX = (diffX > 0) ? diffX-sub : diffX+sub;
13708 x = Math.max(this.minX, x);
13711 diffX = this.constrain(w, diffX, mw, mxw);
13717 w = Math.min(Math.max(mw, w), mxw);
13718 diffY = this.constrain(h, diffY, mh, mxh);
13723 diffX = this.constrain(w, diffX, mw, mxw);
13724 diffY = this.constrain(h, diffY, mh, mxh);
13731 diffX = this.constrain(w, diffX, mw, mxw);
13733 h = Math.min(Math.max(mh, h), mxh);
13739 var sw = this.snap(w, wi, mw);
13740 var sh = this.snap(h, hi, mh);
13741 if(sw != w || sh != h){
13764 if(this.preserveRatio){
13769 h = Math.min(Math.max(mh, h), mxh);
13774 w = Math.min(Math.max(mw, w), mxw);
13779 w = Math.min(Math.max(mw, w), mxw);
13785 w = Math.min(Math.max(mw, w), mxw);
13791 h = Math.min(Math.max(mh, h), mxh);
13799 h = Math.min(Math.max(mh, h), mxh);
13809 h = Math.min(Math.max(mh, h), mxh);
13817 if (pos == 'hdrag') {
13820 this.proxy.setBounds(x, y, w, h);
13822 this.resizeElement();
13829 handleOver : function(){
13831 this.el.addClass("x-resizable-over");
13836 handleOut : function(){
13837 if(!this.resizing){
13838 this.el.removeClass("x-resizable-over");
13843 * Returns the element this component is bound to.
13844 * @return {Roo.Element}
13846 getEl : function(){
13851 * Returns the resizeChild element (or null).
13852 * @return {Roo.Element}
13854 getResizeChild : function(){
13855 return this.resizeChild;
13859 * Destroys this resizable. If the element was wrapped and
13860 * removeEl is not true then the element remains.
13861 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
13863 destroy : function(removeEl){
13864 this.proxy.remove();
13866 this.overlay.removeAllListeners();
13867 this.overlay.remove();
13869 var ps = Roo.Resizable.positions;
13871 if(typeof ps[k] != "function" && this[ps[k]]){
13872 var h = this[ps[k]];
13873 h.el.removeAllListeners();
13878 this.el.update("");
13885 // hash to map config positions to true positions
13886 Roo.Resizable.positions = {
13887 n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast",
13892 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
13894 // only initialize the template if resizable is used
13895 var tpl = Roo.DomHelper.createTemplate(
13896 {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
13899 Roo.Resizable.Handle.prototype.tpl = tpl;
13901 this.position = pos;
13903 // show north drag fro topdra
13904 var handlepos = pos == 'hdrag' ? 'north' : pos;
13906 this.el = this.tpl.append(rz.el.dom, [handlepos], true);
13907 if (pos == 'hdrag') {
13908 this.el.setStyle('cursor', 'pointer');
13910 this.el.unselectable();
13912 this.el.setOpacity(0);
13914 this.el.on("mousedown", this.onMouseDown, this);
13915 if(!disableTrackOver){
13916 this.el.on("mouseover", this.onMouseOver, this);
13917 this.el.on("mouseout", this.onMouseOut, this);
13922 Roo.Resizable.Handle.prototype = {
13923 afterResize : function(rz){
13927 onMouseDown : function(e){
13928 this.rz.onMouseDown(this, e);
13931 onMouseOver : function(e){
13932 this.rz.handleOver(this, e);
13935 onMouseOut : function(e){
13936 this.rz.handleOut(this, e);
13940 * Ext JS Library 1.1.1
13941 * Copyright(c) 2006-2007, Ext JS, LLC.
13943 * Originally Released Under LGPL - original licence link has changed is not relivant.
13946 * <script type="text/javascript">
13950 * @class Roo.Editor
13951 * @extends Roo.Component
13952 * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
13954 * Create a new Editor
13955 * @param {Roo.form.Field} field The Field object (or descendant)
13956 * @param {Object} config The config object
13958 Roo.Editor = function(field, config){
13959 Roo.Editor.superclass.constructor.call(this, config);
13960 this.field = field;
13963 * @event beforestartedit
13964 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
13965 * false from the handler of this event.
13966 * @param {Editor} this
13967 * @param {Roo.Element} boundEl The underlying element bound to this editor
13968 * @param {Mixed} value The field value being set
13970 "beforestartedit" : true,
13973 * Fires when this editor is displayed
13974 * @param {Roo.Element} boundEl The underlying element bound to this editor
13975 * @param {Mixed} value The starting field value
13977 "startedit" : true,
13979 * @event beforecomplete
13980 * Fires after a change has been made to the field, but before the change is reflected in the underlying
13981 * field. Saving the change to the field can be canceled by returning false from the handler of this event.
13982 * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
13983 * event will not fire since no edit actually occurred.
13984 * @param {Editor} this
13985 * @param {Mixed} value The current field value
13986 * @param {Mixed} startValue The original field value
13988 "beforecomplete" : true,
13991 * Fires after editing is complete and any changed value has been written to the underlying field.
13992 * @param {Editor} this
13993 * @param {Mixed} value The current field value
13994 * @param {Mixed} startValue The original field value
13998 * @event specialkey
13999 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
14000 * {@link Roo.EventObject#getKey} to determine which key was pressed.
14001 * @param {Roo.form.Field} this
14002 * @param {Roo.EventObject} e The event object
14004 "specialkey" : true
14008 Roo.extend(Roo.Editor, Roo.Component, {
14010 * @cfg {Boolean/String} autosize
14011 * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
14012 * or "height" to adopt the height only (defaults to false)
14015 * @cfg {Boolean} revertInvalid
14016 * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
14017 * validation fails (defaults to true)
14020 * @cfg {Boolean} ignoreNoChange
14021 * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
14022 * the value has not changed (defaults to false). Applies only to string values - edits for other data types
14023 * will never be ignored.
14026 * @cfg {Boolean} hideEl
14027 * False to keep the bound element visible while the editor is displayed (defaults to true)
14030 * @cfg {Mixed} value
14031 * The data value of the underlying field (defaults to "")
14035 * @cfg {String} alignment
14036 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
14040 * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
14041 * for bottom-right shadow (defaults to "frame")
14045 * @cfg {Boolean} constrain True to constrain the editor to the viewport
14049 * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
14051 completeOnEnter : false,
14053 * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
14055 cancelOnEsc : false,
14057 * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
14062 onRender : function(ct, position){
14063 this.el = new Roo.Layer({
14064 shadow: this.shadow,
14070 constrain: this.constrain
14072 this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
14073 if(this.field.msgTarget != 'title'){
14074 this.field.msgTarget = 'qtip';
14076 this.field.render(this.el);
14078 this.field.el.dom.setAttribute('autocomplete', 'off');
14080 this.field.on("specialkey", this.onSpecialKey, this);
14081 if(this.swallowKeys){
14082 this.field.el.swallowEvent(['keydown','keypress']);
14085 this.field.on("blur", this.onBlur, this);
14086 if(this.field.grow){
14087 this.field.on("autosize", this.el.sync, this.el, {delay:1});
14091 onSpecialKey : function(field, e)
14093 //Roo.log('editor onSpecialKey');
14094 if(this.completeOnEnter && e.getKey() == e.ENTER){
14096 this.completeEdit();
14099 // do not fire special key otherwise it might hide close the editor...
14100 if(e.getKey() == e.ENTER){
14103 if(this.cancelOnEsc && e.getKey() == e.ESC){
14107 this.fireEvent('specialkey', field, e);
14112 * Starts the editing process and shows the editor.
14113 * @param {String/HTMLElement/Element} el The element to edit
14114 * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
14115 * to the innerHTML of el.
14117 startEdit : function(el, value){
14119 this.completeEdit();
14121 this.boundEl = Roo.get(el);
14122 var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
14123 if(!this.rendered){
14124 this.render(this.parentEl || document.body);
14126 if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
14129 this.startValue = v;
14130 this.field.setValue(v);
14132 var sz = this.boundEl.getSize();
14133 switch(this.autoSize){
14135 this.setSize(sz.width, "");
14138 this.setSize("", sz.height);
14141 this.setSize(sz.width, sz.height);
14144 this.el.alignTo(this.boundEl, this.alignment);
14145 this.editing = true;
14147 Roo.QuickTips.disable();
14153 * Sets the height and width of this editor.
14154 * @param {Number} width The new width
14155 * @param {Number} height The new height
14157 setSize : function(w, h){
14158 this.field.setSize(w, h);
14165 * Realigns the editor to the bound field based on the current alignment config value.
14167 realign : function(){
14168 this.el.alignTo(this.boundEl, this.alignment);
14172 * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
14173 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
14175 completeEdit : function(remainVisible){
14179 var v = this.getValue();
14180 if(this.revertInvalid !== false && !this.field.isValid()){
14181 v = this.startValue;
14182 this.cancelEdit(true);
14184 if(String(v) === String(this.startValue) && this.ignoreNoChange){
14185 this.editing = false;
14189 if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
14190 this.editing = false;
14191 if(this.updateEl && this.boundEl){
14192 this.boundEl.update(v);
14194 if(remainVisible !== true){
14197 this.fireEvent("complete", this, v, this.startValue);
14202 onShow : function(){
14204 if(this.hideEl !== false){
14205 this.boundEl.hide();
14208 if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
14209 this.fixIEFocus = true;
14210 this.deferredFocus.defer(50, this);
14212 this.field.focus();
14214 this.fireEvent("startedit", this.boundEl, this.startValue);
14217 deferredFocus : function(){
14219 this.field.focus();
14224 * Cancels the editing process and hides the editor without persisting any changes. The field value will be
14225 * reverted to the original starting value.
14226 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
14227 * cancel (defaults to false)
14229 cancelEdit : function(remainVisible){
14231 this.setValue(this.startValue);
14232 if(remainVisible !== true){
14239 onBlur : function(){
14240 if(this.allowBlur !== true && this.editing){
14241 this.completeEdit();
14246 onHide : function(){
14248 this.completeEdit();
14252 if(this.field.collapse){
14253 this.field.collapse();
14256 if(this.hideEl !== false){
14257 this.boundEl.show();
14260 Roo.QuickTips.enable();
14265 * Sets the data value of the editor
14266 * @param {Mixed} value Any valid value supported by the underlying field
14268 setValue : function(v){
14269 this.field.setValue(v);
14273 * Gets the data value of the editor
14274 * @return {Mixed} The data value
14276 getValue : function(){
14277 return this.field.getValue();
14281 * Ext JS Library 1.1.1
14282 * Copyright(c) 2006-2007, Ext JS, LLC.
14284 * Originally Released Under LGPL - original licence link has changed is not relivant.
14287 * <script type="text/javascript">
14291 * @class Roo.BasicDialog
14292 * @extends Roo.util.Observable
14293 * Lightweight Dialog Class. The code below shows the creation of a typical dialog using existing HTML markup:
14295 var dlg = new Roo.BasicDialog("my-dlg", {
14304 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
14305 dlg.addButton('OK', dlg.hide, dlg); // Could call a save function instead of hiding
14306 dlg.addButton('Cancel', dlg.hide, dlg);
14309 <b>A Dialog should always be a direct child of the body element.</b>
14310 * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
14311 * @cfg {String} title Default text to display in the title bar (defaults to null)
14312 * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
14313 * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
14314 * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
14315 * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
14316 * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
14317 * (defaults to null with no animation)
14318 * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
14319 * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
14320 * property for valid values (defaults to 'all')
14321 * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
14322 * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
14323 * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
14324 * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
14325 * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
14326 * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
14327 * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
14328 * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
14329 * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
14330 * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
14331 * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
14332 * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
14333 * draggable = true (defaults to false)
14334 * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
14335 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
14336 * shadow (defaults to false)
14337 * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
14338 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
14339 * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
14340 * @cfg {Array} buttons Array of buttons
14341 * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
14343 * Create a new BasicDialog.
14344 * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
14345 * @param {Object} config Configuration options
14347 Roo.BasicDialog = function(el, config){
14348 this.el = Roo.get(el);
14349 var dh = Roo.DomHelper;
14350 if(!this.el && config && config.autoCreate){
14351 if(typeof config.autoCreate == "object"){
14352 if(!config.autoCreate.id){
14353 config.autoCreate.id = el;
14355 this.el = dh.append(document.body,
14356 config.autoCreate, true);
14358 this.el = dh.append(document.body,
14359 {tag: "div", id: el, style:'visibility:hidden;'}, true);
14363 el.setDisplayed(true);
14364 el.hide = this.hideAction;
14366 el.addClass("x-dlg");
14368 Roo.apply(this, config);
14370 this.proxy = el.createProxy("x-dlg-proxy");
14371 this.proxy.hide = this.hideAction;
14372 this.proxy.setOpacity(.5);
14376 el.setWidth(config.width);
14379 el.setHeight(config.height);
14381 this.size = el.getSize();
14382 if(typeof config.x != "undefined" && typeof config.y != "undefined"){
14383 this.xy = [config.x,config.y];
14385 this.xy = el.getCenterXY(true);
14387 /** The header element @type Roo.Element */
14388 this.header = el.child("> .x-dlg-hd");
14389 /** The body element @type Roo.Element */
14390 this.body = el.child("> .x-dlg-bd");
14391 /** The footer element @type Roo.Element */
14392 this.footer = el.child("> .x-dlg-ft");
14395 this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
14398 this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
14401 this.header.unselectable();
14403 this.header.update(this.title);
14405 // this element allows the dialog to be focused for keyboard event
14406 this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
14407 this.focusEl.swallowEvent("click", true);
14409 this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
14411 // wrap the body and footer for special rendering
14412 this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
14414 this.bwrap.dom.appendChild(this.footer.dom);
14417 this.bg = this.el.createChild({
14418 tag: "div", cls:"x-dlg-bg",
14419 html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
14421 this.centerBg = this.bg.child("div.x-dlg-bg-center");
14424 if(this.autoScroll !== false && !this.autoTabs){
14425 this.body.setStyle("overflow", "auto");
14428 this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
14430 if(this.closable !== false){
14431 this.el.addClass("x-dlg-closable");
14432 this.close = this.toolbox.createChild({cls:"x-dlg-close"});
14433 this.close.on("click", this.closeClick, this);
14434 this.close.addClassOnOver("x-dlg-close-over");
14436 if(this.collapsible !== false){
14437 this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
14438 this.collapseBtn.on("click", this.collapseClick, this);
14439 this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
14440 this.header.on("dblclick", this.collapseClick, this);
14442 if(this.resizable !== false){
14443 this.el.addClass("x-dlg-resizable");
14444 this.resizer = new Roo.Resizable(el, {
14445 minWidth: this.minWidth || 80,
14446 minHeight:this.minHeight || 80,
14447 handles: this.resizeHandles || "all",
14450 this.resizer.on("beforeresize", this.beforeResize, this);
14451 this.resizer.on("resize", this.onResize, this);
14453 if(this.draggable !== false){
14454 el.addClass("x-dlg-draggable");
14455 if (!this.proxyDrag) {
14456 var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
14459 var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
14461 dd.setHandleElId(this.header.id);
14462 dd.endDrag = this.endMove.createDelegate(this);
14463 dd.startDrag = this.startMove.createDelegate(this);
14464 dd.onDrag = this.onDrag.createDelegate(this);
14469 this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
14470 this.mask.enableDisplayMode("block");
14472 this.el.addClass("x-dlg-modal");
14475 this.shadow = new Roo.Shadow({
14476 mode : typeof this.shadow == "string" ? this.shadow : "sides",
14477 offset : this.shadowOffset
14480 this.shadowOffset = 0;
14482 if(Roo.useShims && this.shim !== false){
14483 this.shim = this.el.createShim();
14484 this.shim.hide = this.hideAction;
14492 if (this.buttons) {
14493 var bts= this.buttons;
14495 Roo.each(bts, function(b) {
14504 * Fires when a key is pressed
14505 * @param {Roo.BasicDialog} this
14506 * @param {Roo.EventObject} e
14511 * Fires when this dialog is moved by the user.
14512 * @param {Roo.BasicDialog} this
14513 * @param {Number} x The new page X
14514 * @param {Number} y The new page Y
14519 * Fires when this dialog is resized by the user.
14520 * @param {Roo.BasicDialog} this
14521 * @param {Number} width The new width
14522 * @param {Number} height The new height
14526 * @event beforehide
14527 * Fires before this dialog is hidden.
14528 * @param {Roo.BasicDialog} this
14530 "beforehide" : true,
14533 * Fires when this dialog is hidden.
14534 * @param {Roo.BasicDialog} this
14538 * @event beforeshow
14539 * Fires before this dialog is shown.
14540 * @param {Roo.BasicDialog} this
14542 "beforeshow" : true,
14545 * Fires when this dialog is shown.
14546 * @param {Roo.BasicDialog} this
14550 el.on("keydown", this.onKeyDown, this);
14551 el.on("mousedown", this.toFront, this);
14552 Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
14554 Roo.DialogManager.register(this);
14555 Roo.BasicDialog.superclass.constructor.call(this);
14558 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
14559 shadowOffset: Roo.isIE ? 6 : 5,
14562 minButtonWidth: 75,
14563 defaultButton: null,
14564 buttonAlign: "right",
14569 * Sets the dialog title text
14570 * @param {String} text The title text to display
14571 * @return {Roo.BasicDialog} this
14573 setTitle : function(text){
14574 this.header.update(text);
14579 closeClick : function(){
14584 collapseClick : function(){
14585 this[this.collapsed ? "expand" : "collapse"]();
14589 * Collapses the dialog to its minimized state (only the title bar is visible).
14590 * Equivalent to the user clicking the collapse dialog button.
14592 collapse : function(){
14593 if(!this.collapsed){
14594 this.collapsed = true;
14595 this.el.addClass("x-dlg-collapsed");
14596 this.restoreHeight = this.el.getHeight();
14597 this.resizeTo(this.el.getWidth(), this.header.getHeight());
14602 * Expands a collapsed dialog back to its normal state. Equivalent to the user
14603 * clicking the expand dialog button.
14605 expand : function(){
14606 if(this.collapsed){
14607 this.collapsed = false;
14608 this.el.removeClass("x-dlg-collapsed");
14609 this.resizeTo(this.el.getWidth(), this.restoreHeight);
14614 * Reinitializes the tabs component, clearing out old tabs and finding new ones.
14615 * @return {Roo.TabPanel} The tabs component
14617 initTabs : function(){
14618 var tabs = this.getTabs();
14619 while(tabs.getTab(0)){
14622 this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
14624 tabs.addTab(Roo.id(dom), dom.title);
14632 beforeResize : function(){
14633 this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
14637 onResize : function(){
14638 this.refreshSize();
14639 this.syncBodyHeight();
14640 this.adjustAssets();
14642 this.fireEvent("resize", this, this.size.width, this.size.height);
14646 onKeyDown : function(e){
14647 if(this.isVisible()){
14648 this.fireEvent("keydown", this, e);
14653 * Resizes the dialog.
14654 * @param {Number} width
14655 * @param {Number} height
14656 * @return {Roo.BasicDialog} this
14658 resizeTo : function(width, height){
14659 this.el.setSize(width, height);
14660 this.size = {width: width, height: height};
14661 this.syncBodyHeight();
14662 if(this.fixedcenter){
14665 if(this.isVisible()){
14666 this.constrainXY();
14667 this.adjustAssets();
14669 this.fireEvent("resize", this, width, height);
14675 * Resizes the dialog to fit the specified content size.
14676 * @param {Number} width
14677 * @param {Number} height
14678 * @return {Roo.BasicDialog} this
14680 setContentSize : function(w, h){
14681 h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
14682 w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
14683 //if(!this.el.isBorderBox()){
14684 h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
14685 w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
14688 h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
14689 w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
14691 this.resizeTo(w, h);
14696 * Adds a key listener for when this dialog is displayed. This allows you to hook in a function that will be
14697 * executed in response to a particular key being pressed while the dialog is active.
14698 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
14699 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
14700 * @param {Function} fn The function to call
14701 * @param {Object} scope (optional) The scope of the function
14702 * @return {Roo.BasicDialog} this
14704 addKeyListener : function(key, fn, scope){
14705 var keyCode, shift, ctrl, alt;
14706 if(typeof key == "object" && !(key instanceof Array)){
14707 keyCode = key["key"];
14708 shift = key["shift"];
14709 ctrl = key["ctrl"];
14714 var handler = function(dlg, e){
14715 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
14716 var k = e.getKey();
14717 if(keyCode instanceof Array){
14718 for(var i = 0, len = keyCode.length; i < len; i++){
14719 if(keyCode[i] == k){
14720 fn.call(scope || window, dlg, k, e);
14726 fn.call(scope || window, dlg, k, e);
14731 this.on("keydown", handler);
14736 * Returns the TabPanel component (creates it if it doesn't exist).
14737 * Note: If you wish to simply check for the existence of tabs without creating them,
14738 * check for a null 'tabs' property.
14739 * @return {Roo.TabPanel} The tabs component
14741 getTabs : function(){
14743 this.el.addClass("x-dlg-auto-tabs");
14744 this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
14745 this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
14751 * Adds a button to the footer section of the dialog.
14752 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
14753 * object or a valid Roo.DomHelper element config
14754 * @param {Function} handler The function called when the button is clicked
14755 * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
14756 * @return {Roo.Button} The new button
14758 addButton : function(config, handler, scope){
14759 var dh = Roo.DomHelper;
14761 this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
14763 if(!this.btnContainer){
14764 var tb = this.footer.createChild({
14766 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
14767 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
14769 this.btnContainer = tb.firstChild.firstChild.firstChild;
14774 minWidth: this.minButtonWidth,
14777 if(typeof config == "string"){
14778 bconfig.text = config;
14781 bconfig.dhconfig = config;
14783 Roo.apply(bconfig, config);
14787 if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
14788 bconfig.position = Math.max(0, bconfig.position);
14789 fc = this.btnContainer.childNodes[bconfig.position];
14792 var btn = new Roo.Button(
14794 this.btnContainer.insertBefore(document.createElement("td"),fc)
14795 : this.btnContainer.appendChild(document.createElement("td")),
14796 //Roo.get(this.btnContainer).createChild( { tag: 'td'}, fc ),
14799 this.syncBodyHeight();
14802 * Array of all the buttons that have been added to this dialog via addButton
14807 this.buttons.push(btn);
14812 * Sets the default button to be focused when the dialog is displayed.
14813 * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
14814 * @return {Roo.BasicDialog} this
14816 setDefaultButton : function(btn){
14817 this.defaultButton = btn;
14822 getHeaderFooterHeight : function(safe){
14825 height += this.header.getHeight();
14828 var fm = this.footer.getMargins();
14829 height += (this.footer.getHeight()+fm.top+fm.bottom);
14831 height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
14832 height += this.centerBg.getPadding("tb");
14837 syncBodyHeight : function(){
14838 var bd = this.body, cb = this.centerBg, bw = this.bwrap;
14839 var height = this.size.height - this.getHeaderFooterHeight(false);
14840 bd.setHeight(height-bd.getMargins("tb"));
14841 var hh = this.header.getHeight();
14842 var h = this.size.height-hh;
14844 bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
14845 bw.setHeight(h-cb.getPadding("tb"));
14846 bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
14847 bd.setWidth(bw.getWidth(true));
14849 this.tabs.syncHeight();
14851 this.tabs.el.repaint();
14857 * Restores the previous state of the dialog if Roo.state is configured.
14858 * @return {Roo.BasicDialog} this
14860 restoreState : function(){
14861 var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
14862 if(box && box.width){
14863 this.xy = [box.x, box.y];
14864 this.resizeTo(box.width, box.height);
14870 beforeShow : function(){
14872 if(this.fixedcenter){
14873 this.xy = this.el.getCenterXY(true);
14876 Roo.get(document.body).addClass("x-body-masked");
14877 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
14880 this.constrainXY();
14884 animShow : function(){
14885 var b = Roo.get(this.animateTarget).getBox();
14886 this.proxy.setSize(b.width, b.height);
14887 this.proxy.setLocation(b.x, b.y);
14889 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
14890 true, .35, this.showEl.createDelegate(this));
14894 * Shows the dialog.
14895 * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
14896 * @return {Roo.BasicDialog} this
14898 show : function(animateTarget){
14899 if (this.fireEvent("beforeshow", this) === false){
14902 if(this.syncHeightBeforeShow){
14903 this.syncBodyHeight();
14904 }else if(this.firstShow){
14905 this.firstShow = false;
14906 this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
14908 this.animateTarget = animateTarget || this.animateTarget;
14909 if(!this.el.isVisible()){
14911 if(this.animateTarget && Roo.get(this.animateTarget)){
14921 showEl : function(){
14923 this.el.setXY(this.xy);
14925 this.adjustAssets(true);
14928 // IE peekaboo bug - fix found by Dave Fenwick
14932 this.fireEvent("show", this);
14936 * Focuses the dialog. If a defaultButton is set, it will receive focus, otherwise the
14937 * dialog itself will receive focus.
14939 focus : function(){
14940 if(this.defaultButton){
14941 this.defaultButton.focus();
14943 this.focusEl.focus();
14948 constrainXY : function(){
14949 if(this.constraintoviewport !== false){
14950 if(!this.viewSize){
14951 if(this.container){
14952 var s = this.container.getSize();
14953 this.viewSize = [s.width, s.height];
14955 this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
14958 var s = Roo.get(this.container||document).getScroll();
14960 var x = this.xy[0], y = this.xy[1];
14961 var w = this.size.width, h = this.size.height;
14962 var vw = this.viewSize[0], vh = this.viewSize[1];
14963 // only move it if it needs it
14965 // first validate right/bottom
14966 if(x + w > vw+s.left){
14970 if(y + h > vh+s.top){
14974 // then make sure top/left isn't negative
14986 if(this.isVisible()){
14987 this.el.setLocation(x, y);
14988 this.adjustAssets();
14995 onDrag : function(){
14996 if(!this.proxyDrag){
14997 this.xy = this.el.getXY();
14998 this.adjustAssets();
15003 adjustAssets : function(doShow){
15004 var x = this.xy[0], y = this.xy[1];
15005 var w = this.size.width, h = this.size.height;
15006 if(doShow === true){
15008 this.shadow.show(this.el);
15014 if(this.shadow && this.shadow.isVisible()){
15015 this.shadow.show(this.el);
15017 if(this.shim && this.shim.isVisible()){
15018 this.shim.setBounds(x, y, w, h);
15023 adjustViewport : function(w, h){
15025 w = Roo.lib.Dom.getViewWidth();
15026 h = Roo.lib.Dom.getViewHeight();
15029 this.viewSize = [w, h];
15030 if(this.modal && this.mask.isVisible()){
15031 this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
15032 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
15034 if(this.isVisible()){
15035 this.constrainXY();
15040 * Destroys this dialog and all its supporting elements (including any tabs, shim,
15041 * shadow, proxy, mask, etc.) Also removes all event listeners.
15042 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
15044 destroy : function(removeEl){
15045 if(this.isVisible()){
15046 this.animateTarget = null;
15049 Roo.EventManager.removeResizeListener(this.adjustViewport, this);
15051 this.tabs.destroy(removeEl);
15064 for(var i = 0, len = this.buttons.length; i < len; i++){
15065 this.buttons[i].destroy();
15068 this.el.removeAllListeners();
15069 if(removeEl === true){
15070 this.el.update("");
15073 Roo.DialogManager.unregister(this);
15077 startMove : function(){
15078 if(this.proxyDrag){
15081 if(this.constraintoviewport !== false){
15082 this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
15087 endMove : function(){
15088 if(!this.proxyDrag){
15089 Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
15091 Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
15094 this.refreshSize();
15095 this.adjustAssets();
15097 this.fireEvent("move", this, this.xy[0], this.xy[1]);
15101 * Brings this dialog to the front of any other visible dialogs
15102 * @return {Roo.BasicDialog} this
15104 toFront : function(){
15105 Roo.DialogManager.bringToFront(this);
15110 * Sends this dialog to the back (under) of any other visible dialogs
15111 * @return {Roo.BasicDialog} this
15113 toBack : function(){
15114 Roo.DialogManager.sendToBack(this);
15119 * Centers this dialog in the viewport
15120 * @return {Roo.BasicDialog} this
15122 center : function(){
15123 var xy = this.el.getCenterXY(true);
15124 this.moveTo(xy[0], xy[1]);
15129 * Moves the dialog's top-left corner to the specified point
15130 * @param {Number} x
15131 * @param {Number} y
15132 * @return {Roo.BasicDialog} this
15134 moveTo : function(x, y){
15136 if(this.isVisible()){
15137 this.el.setXY(this.xy);
15138 this.adjustAssets();
15144 * Aligns the dialog to the specified element
15145 * @param {String/HTMLElement/Roo.Element} element The element to align to.
15146 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
15147 * @param {Array} offsets (optional) Offset the positioning by [x, y]
15148 * @return {Roo.BasicDialog} this
15150 alignTo : function(element, position, offsets){
15151 this.xy = this.el.getAlignToXY(element, position, offsets);
15152 if(this.isVisible()){
15153 this.el.setXY(this.xy);
15154 this.adjustAssets();
15160 * Anchors an element to another element and realigns it when the window is resized.
15161 * @param {String/HTMLElement/Roo.Element} element The element to align to.
15162 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
15163 * @param {Array} offsets (optional) Offset the positioning by [x, y]
15164 * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
15165 * is a number, it is used as the buffer delay (defaults to 50ms).
15166 * @return {Roo.BasicDialog} this
15168 anchorTo : function(el, alignment, offsets, monitorScroll){
15169 var action = function(){
15170 this.alignTo(el, alignment, offsets);
15172 Roo.EventManager.onWindowResize(action, this);
15173 var tm = typeof monitorScroll;
15174 if(tm != 'undefined'){
15175 Roo.EventManager.on(window, 'scroll', action, this,
15176 {buffer: tm == 'number' ? monitorScroll : 50});
15183 * Returns true if the dialog is visible
15184 * @return {Boolean}
15186 isVisible : function(){
15187 return this.el.isVisible();
15191 animHide : function(callback){
15192 var b = Roo.get(this.animateTarget).getBox();
15194 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
15196 this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
15197 this.hideEl.createDelegate(this, [callback]));
15201 * Hides the dialog.
15202 * @param {Function} callback (optional) Function to call when the dialog is hidden
15203 * @return {Roo.BasicDialog} this
15205 hide : function(callback){
15206 if (this.fireEvent("beforehide", this) === false){
15210 this.shadow.hide();
15215 // sometimes animateTarget seems to get set.. causing problems...
15216 // this just double checks..
15217 if(this.animateTarget && Roo.get(this.animateTarget)) {
15218 this.animHide(callback);
15221 this.hideEl(callback);
15227 hideEl : function(callback){
15231 Roo.get(document.body).removeClass("x-body-masked");
15233 this.fireEvent("hide", this);
15234 if(typeof callback == "function"){
15240 hideAction : function(){
15241 this.setLeft("-10000px");
15242 this.setTop("-10000px");
15243 this.setStyle("visibility", "hidden");
15247 refreshSize : function(){
15248 this.size = this.el.getSize();
15249 this.xy = this.el.getXY();
15250 Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
15254 // z-index is managed by the DialogManager and may be overwritten at any time
15255 setZIndex : function(index){
15257 this.mask.setStyle("z-index", index);
15260 this.shim.setStyle("z-index", ++index);
15263 this.shadow.setZIndex(++index);
15265 this.el.setStyle("z-index", ++index);
15267 this.proxy.setStyle("z-index", ++index);
15270 this.resizer.proxy.setStyle("z-index", ++index);
15273 this.lastZIndex = index;
15277 * Returns the element for this dialog
15278 * @return {Roo.Element} The underlying dialog Element
15280 getEl : function(){
15286 * @class Roo.DialogManager
15287 * Provides global access to BasicDialogs that have been created and
15288 * support for z-indexing (layering) multiple open dialogs.
15290 Roo.DialogManager = function(){
15292 var accessList = [];
15296 var sortDialogs = function(d1, d2){
15297 return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
15301 var orderDialogs = function(){
15302 accessList.sort(sortDialogs);
15303 var seed = Roo.DialogManager.zseed;
15304 for(var i = 0, len = accessList.length; i < len; i++){
15305 var dlg = accessList[i];
15307 dlg.setZIndex(seed + (i*10));
15314 * The starting z-index for BasicDialogs (defaults to 9000)
15315 * @type Number The z-index value
15320 register : function(dlg){
15321 list[dlg.id] = dlg;
15322 accessList.push(dlg);
15326 unregister : function(dlg){
15327 delete list[dlg.id];
15330 if(!accessList.indexOf){
15331 for( i = 0, len = accessList.length; i < len; i++){
15332 if(accessList[i] == dlg){
15333 accessList.splice(i, 1);
15338 i = accessList.indexOf(dlg);
15340 accessList.splice(i, 1);
15346 * Gets a registered dialog by id
15347 * @param {String/Object} id The id of the dialog or a dialog
15348 * @return {Roo.BasicDialog} this
15350 get : function(id){
15351 return typeof id == "object" ? id : list[id];
15355 * Brings the specified dialog to the front
15356 * @param {String/Object} dlg The id of the dialog or a dialog
15357 * @return {Roo.BasicDialog} this
15359 bringToFront : function(dlg){
15360 dlg = this.get(dlg);
15363 dlg._lastAccess = new Date().getTime();
15370 * Sends the specified dialog to the back
15371 * @param {String/Object} dlg The id of the dialog or a dialog
15372 * @return {Roo.BasicDialog} this
15374 sendToBack : function(dlg){
15375 dlg = this.get(dlg);
15376 dlg._lastAccess = -(new Date().getTime());
15382 * Hides all dialogs
15384 hideAll : function(){
15385 for(var id in list){
15386 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
15395 * @class Roo.LayoutDialog
15396 * @extends Roo.BasicDialog
15397 * Dialog which provides adjustments for working with a layout in a Dialog.
15398 * Add your necessary layout config options to the dialog's config.<br>
15399 * Example usage (including a nested layout):
15402 dialog = new Roo.LayoutDialog("download-dlg", {
15411 // layout config merges with the dialog config
15413 tabPosition: "top",
15414 alwaysShowTabs: true
15417 dialog.addKeyListener(27, dialog.hide, dialog);
15418 dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
15419 dialog.addButton("Build It!", this.getDownload, this);
15421 // we can even add nested layouts
15422 var innerLayout = new Roo.BorderLayout("dl-inner", {
15432 innerLayout.beginUpdate();
15433 innerLayout.add("east", new Roo.ContentPanel("dl-details"));
15434 innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
15435 innerLayout.endUpdate(true);
15437 var layout = dialog.getLayout();
15438 layout.beginUpdate();
15439 layout.add("center", new Roo.ContentPanel("standard-panel",
15440 {title: "Download the Source", fitToFrame:true}));
15441 layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
15442 {title: "Build your own roo.js"}));
15443 layout.getRegion("center").showPanel(sp);
15444 layout.endUpdate();
15448 * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
15449 * @param {Object} config configuration options
15451 Roo.LayoutDialog = function(el, cfg){
15454 if (typeof(cfg) == 'undefined') {
15455 config = Roo.apply({}, el);
15456 // not sure why we use documentElement here.. - it should always be body.
15457 // IE7 borks horribly if we use documentElement.
15458 // webkit also does not like documentElement - it creates a body element...
15459 el = Roo.get( document.body || document.documentElement ).createChild();
15460 //config.autoCreate = true;
15464 config.autoTabs = false;
15465 Roo.LayoutDialog.superclass.constructor.call(this, el, config);
15466 this.body.setStyle({overflow:"hidden", position:"relative"});
15467 this.layout = new Roo.BorderLayout(this.body.dom, config);
15468 this.layout.monitorWindowResize = false;
15469 this.el.addClass("x-dlg-auto-layout");
15470 // fix case when center region overwrites center function
15471 this.center = Roo.BasicDialog.prototype.center;
15472 this.on("show", this.layout.layout, this.layout, true);
15473 if (config.items) {
15474 var xitems = config.items;
15475 delete config.items;
15476 Roo.each(xitems, this.addxtype, this);
15481 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
15483 * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
15486 endUpdate : function(){
15487 this.layout.endUpdate();
15491 * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
15494 beginUpdate : function(){
15495 this.layout.beginUpdate();
15499 * Get the BorderLayout for this dialog
15500 * @return {Roo.BorderLayout}
15502 getLayout : function(){
15503 return this.layout;
15506 showEl : function(){
15507 Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
15509 this.layout.layout();
15514 // Use the syncHeightBeforeShow config option to control this automatically
15515 syncBodyHeight : function(){
15516 Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
15517 if(this.layout){this.layout.layout();}
15521 * Add an xtype element (actually adds to the layout.)
15522 * @return {Object} xdata xtype object data.
15525 addxtype : function(c) {
15526 return this.layout.addxtype(c);
15530 * Ext JS Library 1.1.1
15531 * Copyright(c) 2006-2007, Ext JS, LLC.
15533 * Originally Released Under LGPL - original licence link has changed is not relivant.
15536 * <script type="text/javascript">
15540 * @class Roo.MessageBox
15541 * Utility class for generating different styles of message boxes. The alias Roo.Msg can also be used.
15545 Roo.Msg.alert('Status', 'Changes saved successfully.');
15547 // Prompt for user data:
15548 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
15550 // process text value...
15554 // Show a dialog using config options:
15556 title:'Save Changes?',
15557 msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
15558 buttons: Roo.Msg.YESNOCANCEL,
15565 Roo.MessageBox = function(){
15566 var dlg, opt, mask, waitTimer;
15567 var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
15568 var buttons, activeTextEl, bwidth;
15571 var handleButton = function(button){
15573 Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
15577 var handleHide = function(){
15578 if(opt && opt.cls){
15579 dlg.el.removeClass(opt.cls);
15582 Roo.TaskMgr.stop(waitTimer);
15588 var updateButtons = function(b){
15591 buttons["ok"].hide();
15592 buttons["cancel"].hide();
15593 buttons["yes"].hide();
15594 buttons["no"].hide();
15595 dlg.footer.dom.style.display = 'none';
15598 dlg.footer.dom.style.display = '';
15599 for(var k in buttons){
15600 if(typeof buttons[k] != "function"){
15603 buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
15604 width += buttons[k].el.getWidth()+15;
15614 var handleEsc = function(d, k, e){
15615 if(opt && opt.closable !== false){
15625 * Returns a reference to the underlying {@link Roo.BasicDialog} element
15626 * @return {Roo.BasicDialog} The BasicDialog element
15628 getDialog : function(){
15630 dlg = new Roo.BasicDialog("x-msg-box", {
15635 constraintoviewport:false,
15637 collapsible : false,
15640 width:400, height:100,
15641 buttonAlign:"center",
15642 closeClick : function(){
15643 if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
15644 handleButton("no");
15646 handleButton("cancel");
15650 dlg.on("hide", handleHide);
15652 dlg.addKeyListener(27, handleEsc);
15654 var bt = this.buttonText;
15655 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
15656 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
15657 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
15658 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
15659 bodyEl = dlg.body.createChild({
15661 html:'<span class="roo-mb-text"></span><br /><input type="text" class="roo-mb-input" /><textarea class="roo-mb-textarea"></textarea><div class="roo-mb-progress-wrap"><div class="roo-mb-progress"><div class="roo-mb-progress-bar"> </div></div></div>'
15663 msgEl = bodyEl.dom.firstChild;
15664 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
15665 textboxEl.enableDisplayMode();
15666 textboxEl.addKeyListener([10,13], function(){
15667 if(dlg.isVisible() && opt && opt.buttons){
15668 if(opt.buttons.ok){
15669 handleButton("ok");
15670 }else if(opt.buttons.yes){
15671 handleButton("yes");
15675 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
15676 textareaEl.enableDisplayMode();
15677 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
15678 progressEl.enableDisplayMode();
15679 var pf = progressEl.dom.firstChild;
15681 pp = Roo.get(pf.firstChild);
15682 pp.setHeight(pf.offsetHeight);
15690 * Updates the message box body text
15691 * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
15692 * the XHTML-compliant non-breaking space character '&#160;')
15693 * @return {Roo.MessageBox} This message box
15695 updateText : function(text){
15696 if(!dlg.isVisible() && !opt.width){
15697 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
15699 msgEl.innerHTML = text || ' ';
15701 var cw = Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
15702 //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
15704 Math.min(opt.width || cw , this.maxWidth),
15705 Math.max(opt.minWidth || this.minWidth, bwidth)
15708 activeTextEl.setWidth(w);
15710 if(dlg.isVisible()){
15711 dlg.fixedcenter = false;
15713 // to big, make it scroll. = But as usual stupid IE does not support
15716 if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
15717 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
15718 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
15720 bodyEl.dom.style.height = '';
15721 bodyEl.dom.style.overflowY = '';
15724 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
15726 bodyEl.dom.style.overflowX = '';
15729 dlg.setContentSize(w, bodyEl.getHeight());
15730 if(dlg.isVisible()){
15731 dlg.fixedcenter = true;
15737 * Updates a progress-style message box's text and progress bar. Only relevant on message boxes
15738 * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
15739 * @param {Number} value Any number between 0 and 1 (e.g., .5)
15740 * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
15741 * @return {Roo.MessageBox} This message box
15743 updateProgress : function(value, text){
15745 this.updateText(text);
15747 if (pp) { // weird bug on my firefox - for some reason this is not defined
15748 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
15754 * Returns true if the message box is currently displayed
15755 * @return {Boolean} True if the message box is visible, else false
15757 isVisible : function(){
15758 return dlg && dlg.isVisible();
15762 * Hides the message box if it is displayed
15765 if(this.isVisible()){
15771 * Displays a new message box, or reinitializes an existing message box, based on the config options
15772 * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
15773 * The following config object properties are supported:
15775 Property Type Description
15776 ---------- --------------- ------------------------------------------------------------------------------------
15777 animEl String/Element An id or Element from which the message box should animate as it opens and
15778 closes (defaults to undefined)
15779 buttons Object/Boolean A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
15780 cancel:'Bar'}), or false to not show any buttons (defaults to false)
15781 closable Boolean False to hide the top-right close button (defaults to true). Note that
15782 progress and wait dialogs will ignore this property and always hide the
15783 close button as they can only be closed programmatically.
15784 cls String A custom CSS class to apply to the message box element
15785 defaultTextHeight Number The default height in pixels of the message box's multiline textarea if
15786 displayed (defaults to 75)
15787 fn Function A callback function to execute after closing the dialog. The arguments to the
15788 function will be btn (the name of the button that was clicked, if applicable,
15789 e.g. "ok"), and text (the value of the active text field, if applicable).
15790 Progress and wait dialogs will ignore this option since they do not respond to
15791 user actions and can only be closed programmatically, so any required function
15792 should be called by the same code after it closes the dialog.
15793 icon String A CSS class that provides a background image to be used as an icon for
15794 the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
15795 maxWidth Number The maximum width in pixels of the message box (defaults to 600)
15796 minWidth Number The minimum width in pixels of the message box (defaults to 100)
15797 modal Boolean False to allow user interaction with the page while the message box is
15798 displayed (defaults to true)
15799 msg String A string that will replace the existing message box body text (defaults
15800 to the XHTML-compliant non-breaking space character ' ')
15801 multiline Boolean True to prompt the user to enter multi-line text (defaults to false)
15802 progress Boolean True to display a progress bar (defaults to false)
15803 progressText String The text to display inside the progress bar if progress = true (defaults to '')
15804 prompt Boolean True to prompt the user to enter single-line text (defaults to false)
15805 proxyDrag Boolean True to display a lightweight proxy while dragging (defaults to false)
15806 title String The title text
15807 value String The string value to set into the active textbox element if displayed
15808 wait Boolean True to display a progress bar (defaults to false)
15809 width Number The width of the dialog in pixels
15816 msg: 'Please enter your address:',
15818 buttons: Roo.MessageBox.OKCANCEL,
15821 animEl: 'addAddressBtn'
15824 * @param {Object} config Configuration options
15825 * @return {Roo.MessageBox} This message box
15827 show : function(options)
15830 // this causes nightmares if you show one dialog after another
15831 // especially on callbacks..
15833 if(this.isVisible()){
15836 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
15837 Roo.log("Old Dialog Message:" + msgEl.innerHTML );
15838 Roo.log("New Dialog Message:" + options.msg )
15839 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
15840 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
15843 var d = this.getDialog();
15845 d.setTitle(opt.title || " ");
15846 d.close.setDisplayed(opt.closable !== false);
15847 activeTextEl = textboxEl;
15848 opt.prompt = opt.prompt || (opt.multiline ? true : false);
15853 textareaEl.setHeight(typeof opt.multiline == "number" ?
15854 opt.multiline : this.defaultTextHeight);
15855 activeTextEl = textareaEl;
15864 progressEl.setDisplayed(opt.progress === true);
15865 this.updateProgress(0);
15866 activeTextEl.dom.value = opt.value || "";
15868 dlg.setDefaultButton(activeTextEl);
15870 var bs = opt.buttons;
15873 db = buttons["ok"];
15874 }else if(bs && bs.yes){
15875 db = buttons["yes"];
15877 dlg.setDefaultButton(db);
15879 bwidth = updateButtons(opt.buttons);
15880 this.updateText(opt.msg);
15882 d.el.addClass(opt.cls);
15884 d.proxyDrag = opt.proxyDrag === true;
15885 d.modal = opt.modal !== false;
15886 d.mask = opt.modal !== false ? mask : false;
15887 if(!d.isVisible()){
15888 // force it to the end of the z-index stack so it gets a cursor in FF
15889 document.body.appendChild(dlg.el.dom);
15890 d.animateTarget = null;
15891 d.show(options.animEl);
15897 * Displays a message box with a progress bar. This message box has no buttons and is not closeable by
15898 * the user. You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
15899 * and closing the message box when the process is complete.
15900 * @param {String} title The title bar text
15901 * @param {String} msg The message box body text
15902 * @return {Roo.MessageBox} This message box
15904 progress : function(title, msg){
15911 minWidth: this.minProgressWidth,
15918 * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
15919 * If a callback function is passed it will be called after the user clicks the button, and the
15920 * id of the button that was clicked will be passed as the only parameter to the callback
15921 * (could also be the top-right close button).
15922 * @param {String} title The title bar text
15923 * @param {String} msg The message box body text
15924 * @param {Function} fn (optional) The callback function invoked after the message box is closed
15925 * @param {Object} scope (optional) The scope of the callback function
15926 * @return {Roo.MessageBox} This message box
15928 alert : function(title, msg, fn, scope){
15941 * Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
15942 * interaction while waiting for a long-running process to complete that does not have defined intervals.
15943 * You are responsible for closing the message box when the process is complete.
15944 * @param {String} msg The message box body text
15945 * @param {String} title (optional) The title bar text
15946 * @return {Roo.MessageBox} This message box
15948 wait : function(msg, title){
15959 waitTimer = Roo.TaskMgr.start({
15961 Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
15969 * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
15970 * If a callback function is passed it will be called after the user clicks either button, and the id of the
15971 * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
15972 * @param {String} title The title bar text
15973 * @param {String} msg The message box body text
15974 * @param {Function} fn (optional) The callback function invoked after the message box is closed
15975 * @param {Object} scope (optional) The scope of the callback function
15976 * @return {Roo.MessageBox} This message box
15978 confirm : function(title, msg, fn, scope){
15982 buttons: this.YESNO,
15991 * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
15992 * JavaScript's Window.prompt). The prompt can be a single-line or multi-line textbox. If a callback function
15993 * is passed it will be called after the user clicks either button, and the id of the button that was clicked
15994 * (could also be the top-right close button) and the text that was entered will be passed as the two
15995 * parameters to the callback.
15996 * @param {String} title The title bar text
15997 * @param {String} msg The message box body text
15998 * @param {Function} fn (optional) The callback function invoked after the message box is closed
15999 * @param {Object} scope (optional) The scope of the callback function
16000 * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
16001 * property, or the height in pixels to create the textbox (defaults to false / single-line)
16002 * @return {Roo.MessageBox} This message box
16004 prompt : function(title, msg, fn, scope, multiline){
16008 buttons: this.OKCANCEL,
16013 multiline: multiline,
16020 * Button config that displays a single OK button
16025 * Button config that displays Yes and No buttons
16028 YESNO : {yes:true, no:true},
16030 * Button config that displays OK and Cancel buttons
16033 OKCANCEL : {ok:true, cancel:true},
16035 * Button config that displays Yes, No and Cancel buttons
16038 YESNOCANCEL : {yes:true, no:true, cancel:true},
16041 * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
16044 defaultTextHeight : 75,
16046 * The maximum width in pixels of the message box (defaults to 600)
16051 * The minimum width in pixels of the message box (defaults to 100)
16056 * The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
16057 * for setting a different minimum width than text-only dialogs may need (defaults to 250)
16060 minProgressWidth : 250,
16062 * An object containing the default button text strings that can be overriden for localized language support.
16063 * Supported properties are: ok, cancel, yes and no.
16064 * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
16077 * Shorthand for {@link Roo.MessageBox}
16079 Roo.Msg = Roo.MessageBox;/*
16081 * Ext JS Library 1.1.1
16082 * Copyright(c) 2006-2007, Ext JS, LLC.
16084 * Originally Released Under LGPL - original licence link has changed is not relivant.
16087 * <script type="text/javascript">
16090 * @class Roo.QuickTips
16091 * Provides attractive and customizable tooltips for any element.
16094 Roo.QuickTips = function(){
16095 var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
16096 var ce, bd, xy, dd;
16097 var visible = false, disabled = true, inited = false;
16098 var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
16100 var onOver = function(e){
16104 var t = e.getTarget();
16105 if(!t || t.nodeType !== 1 || t == document || t == document.body){
16108 if(ce && t == ce.el){
16109 clearTimeout(hideProc);
16112 if(t && tagEls[t.id]){
16113 tagEls[t.id].el = t;
16114 showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
16117 var ttp, et = Roo.fly(t);
16118 var ns = cfg.namespace;
16119 if(tm.interceptTitles && t.title){
16122 t.removeAttribute("title");
16123 e.preventDefault();
16125 ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute);
16128 showProc = show.defer(tm.showDelay, tm, [{
16131 width: et.getAttributeNS(ns, cfg.width),
16132 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
16133 title: et.getAttributeNS(ns, cfg.title),
16134 cls: et.getAttributeNS(ns, cfg.cls)
16139 var onOut = function(e){
16140 clearTimeout(showProc);
16141 var t = e.getTarget();
16142 if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
16143 hideProc = setTimeout(hide, tm.hideDelay);
16147 var onMove = function(e){
16153 if(tm.trackMouse && ce){
16158 var onDown = function(e){
16159 clearTimeout(showProc);
16160 clearTimeout(hideProc);
16162 if(tm.hideOnClick){
16165 tm.enable.defer(100, tm);
16170 var getPad = function(){
16171 return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
16174 var show = function(o){
16178 clearTimeout(dismissProc);
16180 if(removeCls){ // in case manually hidden
16181 el.removeClass(removeCls);
16185 el.addClass(ce.cls);
16186 removeCls = ce.cls;
16189 tipTitle.update(ce.title);
16192 tipTitle.update('');
16195 el.dom.style.width = tm.maxWidth+'px';
16196 //tipBody.dom.style.width = '';
16197 tipBodyText.update(o.text);
16198 var p = getPad(), w = ce.width;
16200 var td = tipBodyText.dom;
16201 var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
16202 if(aw > tm.maxWidth){
16204 }else if(aw < tm.minWidth){
16210 //tipBody.setWidth(w);
16211 el.setWidth(parseInt(w, 10) + p);
16212 if(ce.autoHide === false){
16213 close.setDisplayed(true);
16218 close.setDisplayed(false);
16224 el.avoidY = xy[1]-18;
16229 el.setStyle("visibility", "visible");
16230 el.fadeIn({callback: afterShow});
16236 var afterShow = function(){
16240 if(tm.autoDismiss && ce.autoHide !== false){
16241 dismissProc = setTimeout(hide, tm.autoDismissDelay);
16246 var hide = function(noanim){
16247 clearTimeout(dismissProc);
16248 clearTimeout(hideProc);
16250 if(el.isVisible()){
16252 if(noanim !== true && tm.animate){
16253 el.fadeOut({callback: afterHide});
16260 var afterHide = function(){
16263 el.removeClass(removeCls);
16270 * @cfg {Number} minWidth
16271 * The minimum width of the quick tip (defaults to 40)
16275 * @cfg {Number} maxWidth
16276 * The maximum width of the quick tip (defaults to 300)
16280 * @cfg {Boolean} interceptTitles
16281 * True to automatically use the element's DOM title value if available (defaults to false)
16283 interceptTitles : false,
16285 * @cfg {Boolean} trackMouse
16286 * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
16288 trackMouse : false,
16290 * @cfg {Boolean} hideOnClick
16291 * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
16293 hideOnClick : true,
16295 * @cfg {Number} showDelay
16296 * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
16300 * @cfg {Number} hideDelay
16301 * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
16305 * @cfg {Boolean} autoHide
16306 * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
16307 * Used in conjunction with hideDelay.
16312 * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
16313 * (defaults to true). Used in conjunction with autoDismissDelay.
16315 autoDismiss : true,
16318 * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
16320 autoDismissDelay : 5000,
16322 * @cfg {Boolean} animate
16323 * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
16328 * @cfg {String} title
16329 * Title text to display (defaults to ''). This can be any valid HTML markup.
16333 * @cfg {String} text
16334 * Body text to display (defaults to ''). This can be any valid HTML markup.
16338 * @cfg {String} cls
16339 * A CSS class to apply to the base quick tip element (defaults to '').
16343 * @cfg {Number} width
16344 * Width in pixels of the quick tip (defaults to auto). Width will be ignored if it exceeds the bounds of
16345 * minWidth or maxWidth.
16350 * Initialize and enable QuickTips for first use. This should be called once before the first attempt to access
16351 * or display QuickTips in a page.
16354 tm = Roo.QuickTips;
16355 cfg = tm.tagConfig;
16357 if(!Roo.isReady){ // allow calling of init() before onReady
16358 Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
16361 el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
16362 el.fxDefaults = {stopFx: true};
16363 // maximum custom styling
16364 //el.update('<div class="x-tip-top-left"><div class="x-tip-top-right"><div class="x-tip-top"></div></div></div><div class="x-tip-bd-left"><div class="x-tip-bd-right"><div class="x-tip-bd"><div class="x-tip-close"></div><h3></h3><div class="x-tip-bd-inner"></div><div class="x-clear"></div></div></div></div><div class="x-tip-ft-left"><div class="x-tip-ft-right"><div class="x-tip-ft"></div></div></div>');
16365 el.update('<div class="x-tip-bd"><div class="x-tip-close"></div><h3></h3><div class="x-tip-bd-inner"></div><div class="x-clear"></div></div>');
16366 tipTitle = el.child('h3');
16367 tipTitle.enableDisplayMode("block");
16368 tipBody = el.child('div.x-tip-bd');
16369 tipBodyText = el.child('div.x-tip-bd-inner');
16370 //bdLeft = el.child('div.x-tip-bd-left');
16371 //bdRight = el.child('div.x-tip-bd-right');
16372 close = el.child('div.x-tip-close');
16373 close.enableDisplayMode("block");
16374 close.on("click", hide);
16375 var d = Roo.get(document);
16376 d.on("mousedown", onDown);
16377 d.on("mouseover", onOver);
16378 d.on("mouseout", onOut);
16379 d.on("mousemove", onMove);
16380 esc = d.addKeyListener(27, hide);
16383 dd = el.initDD("default", null, {
16384 onDrag : function(){
16388 dd.setHandleElId(tipTitle.id);
16397 * Configures a new quick tip instance and assigns it to a target element. The following config options
16400 Property Type Description
16401 ---------- --------------------- ------------------------------------------------------------------------
16402 target Element/String/Array An Element, id or array of ids that this quick tip should be tied to
16404 * @param {Object} config The config object
16406 register : function(config){
16407 var cs = config instanceof Array ? config : arguments;
16408 for(var i = 0, len = cs.length; i < len; i++) {
16410 var target = c.target;
16412 if(target instanceof Array){
16413 for(var j = 0, jlen = target.length; j < jlen; j++){
16414 tagEls[target[j]] = c;
16417 tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
16424 * Removes this quick tip from its element and destroys it.
16425 * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
16427 unregister : function(el){
16428 delete tagEls[Roo.id(el)];
16432 * Enable this quick tip.
16434 enable : function(){
16435 if(inited && disabled){
16437 if(locks.length < 1){
16444 * Disable this quick tip.
16446 disable : function(){
16448 clearTimeout(showProc);
16449 clearTimeout(hideProc);
16450 clearTimeout(dismissProc);
16458 * Returns true if the quick tip is enabled, else false.
16460 isEnabled : function(){
16467 attribute : "qtip",
16477 // backwards compat
16478 Roo.QuickTips.tips = Roo.QuickTips.register;/*
16480 * Ext JS Library 1.1.1
16481 * Copyright(c) 2006-2007, Ext JS, LLC.
16483 * Originally Released Under LGPL - original licence link has changed is not relivant.
16486 * <script type="text/javascript">
16491 * @class Roo.tree.TreePanel
16492 * @extends Roo.data.Tree
16494 * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
16495 * @cfg {Boolean} lines false to disable tree lines (defaults to true)
16496 * @cfg {Boolean} enableDD true to enable drag and drop
16497 * @cfg {Boolean} enableDrag true to enable just drag
16498 * @cfg {Boolean} enableDrop true to enable just drop
16499 * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
16500 * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
16501 * @cfg {String} ddGroup The DD group this TreePanel belongs to
16502 * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
16503 * @cfg {Boolean} ddScroll true to enable YUI body scrolling
16504 * @cfg {Boolean} containerScroll true to register this container with ScrollManager
16505 * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
16506 * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
16507 * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
16508 * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
16509 * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
16510 * @cfg {Boolean} loader A TreeLoader for use with this TreePanel
16511 * @cfg {Object|Roo.tree.TreeEditor} editor The TreeEditor or xtype data to display when clicked.
16512 * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
16513 * @cfg {Function} renderer DEPRECATED - use TreeLoader:create event / Sets the rendering (formatting) function for the nodes. to return HTML markup for the tree view. The render function is called with the following parameters:<ul><li>The {Object} The data for the node.</li></ul>
16514 * @cfg {Function} rendererTip DEPRECATED - use TreeLoader:create event / Sets the rendering (formatting) function for the nodes hovertip to return HTML markup for the tree view. The render function is called with the following parameters:<ul><li>The {Object} The data for the node.</li></ul>
16517 * @param {String/HTMLElement/Element} el The container element
16518 * @param {Object} config
16520 Roo.tree.TreePanel = function(el, config){
16522 var loader = false;
16524 root = config.root;
16525 delete config.root;
16527 if (config.loader) {
16528 loader = config.loader;
16529 delete config.loader;
16532 Roo.apply(this, config);
16533 Roo.tree.TreePanel.superclass.constructor.call(this);
16534 this.el = Roo.get(el);
16535 this.el.addClass('x-tree');
16536 //console.log(root);
16538 this.setRootNode( Roo.factory(root, Roo.tree));
16541 this.loader = Roo.factory(loader, Roo.tree);
16544 * Read-only. The id of the container element becomes this TreePanel's id.
16546 this.id = this.el.id;
16549 * @event beforeload
16550 * Fires before a node is loaded, return false to cancel
16551 * @param {Node} node The node being loaded
16553 "beforeload" : true,
16556 * Fires when a node is loaded
16557 * @param {Node} node The node that was loaded
16561 * @event textchange
16562 * Fires when the text for a node is changed
16563 * @param {Node} node The node
16564 * @param {String} text The new text
16565 * @param {String} oldText The old text
16567 "textchange" : true,
16569 * @event beforeexpand
16570 * Fires before a node is expanded, return false to cancel.
16571 * @param {Node} node The node
16572 * @param {Boolean} deep
16573 * @param {Boolean} anim
16575 "beforeexpand" : true,
16577 * @event beforecollapse
16578 * Fires before a node is collapsed, return false to cancel.
16579 * @param {Node} node The node
16580 * @param {Boolean} deep
16581 * @param {Boolean} anim
16583 "beforecollapse" : true,
16586 * Fires when a node is expanded
16587 * @param {Node} node The node
16591 * @event disabledchange
16592 * Fires when the disabled status of a node changes
16593 * @param {Node} node The node
16594 * @param {Boolean} disabled
16596 "disabledchange" : true,
16599 * Fires when a node is collapsed
16600 * @param {Node} node The node
16604 * @event beforeclick
16605 * Fires before click processing on a node. Return false to cancel the default action.
16606 * @param {Node} node The node
16607 * @param {Roo.EventObject} e The event object
16609 "beforeclick":true,
16611 * @event checkchange
16612 * Fires when a node with a checkbox's checked property changes
16613 * @param {Node} this This node
16614 * @param {Boolean} checked
16616 "checkchange":true,
16619 * Fires when a node is clicked
16620 * @param {Node} node The node
16621 * @param {Roo.EventObject} e The event object
16626 * Fires when a node is double clicked
16627 * @param {Node} node The node
16628 * @param {Roo.EventObject} e The event object
16632 * @event contextmenu
16633 * Fires when a node is right clicked
16634 * @param {Node} node The node
16635 * @param {Roo.EventObject} e The event object
16637 "contextmenu":true,
16639 * @event beforechildrenrendered
16640 * Fires right before the child nodes for a node are rendered
16641 * @param {Node} node The node
16643 "beforechildrenrendered":true,
16646 * Fires when a node starts being dragged
16647 * @param {Roo.tree.TreePanel} this
16648 * @param {Roo.tree.TreeNode} node
16649 * @param {event} e The raw browser event
16651 "startdrag" : true,
16654 * Fires when a drag operation is complete
16655 * @param {Roo.tree.TreePanel} this
16656 * @param {Roo.tree.TreeNode} node
16657 * @param {event} e The raw browser event
16662 * Fires when a dragged node is dropped on a valid DD target
16663 * @param {Roo.tree.TreePanel} this
16664 * @param {Roo.tree.TreeNode} node
16665 * @param {DD} dd The dd it was dropped on
16666 * @param {event} e The raw browser event
16670 * @event beforenodedrop
16671 * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
16672 * passed to handlers has the following properties:<br />
16673 * <ul style="padding:5px;padding-left:16px;">
16674 * <li>tree - The TreePanel</li>
16675 * <li>target - The node being targeted for the drop</li>
16676 * <li>data - The drag data from the drag source</li>
16677 * <li>point - The point of the drop - append, above or below</li>
16678 * <li>source - The drag source</li>
16679 * <li>rawEvent - Raw mouse event</li>
16680 * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
16681 * to be inserted by setting them on this object.</li>
16682 * <li>cancel - Set this to true to cancel the drop.</li>
16684 * @param {Object} dropEvent
16686 "beforenodedrop" : true,
16689 * Fires after a DD object is dropped on a node in this tree. The dropEvent
16690 * passed to handlers has the following properties:<br />
16691 * <ul style="padding:5px;padding-left:16px;">
16692 * <li>tree - The TreePanel</li>
16693 * <li>target - The node being targeted for the drop</li>
16694 * <li>data - The drag data from the drag source</li>
16695 * <li>point - The point of the drop - append, above or below</li>
16696 * <li>source - The drag source</li>
16697 * <li>rawEvent - Raw mouse event</li>
16698 * <li>dropNode - Dropped node(s).</li>
16700 * @param {Object} dropEvent
16704 * @event nodedragover
16705 * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
16706 * passed to handlers has the following properties:<br />
16707 * <ul style="padding:5px;padding-left:16px;">
16708 * <li>tree - The TreePanel</li>
16709 * <li>target - The node being targeted for the drop</li>
16710 * <li>data - The drag data from the drag source</li>
16711 * <li>point - The point of the drop - append, above or below</li>
16712 * <li>source - The drag source</li>
16713 * <li>rawEvent - Raw mouse event</li>
16714 * <li>dropNode - Drop node(s) provided by the source.</li>
16715 * <li>cancel - Set this to true to signal drop not allowed.</li>
16717 * @param {Object} dragOverEvent
16719 "nodedragover" : true
16722 if(this.singleExpand){
16723 this.on("beforeexpand", this.restrictExpand, this);
16726 this.editor.tree = this;
16727 this.editor = Roo.factory(this.editor, Roo.tree);
16730 if (this.selModel) {
16731 this.selModel = Roo.factory(this.selModel, Roo.tree);
16735 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
16736 rootVisible : true,
16737 animate: Roo.enableFx,
16740 hlDrop : Roo.enableFx,
16744 rendererTip: false,
16746 restrictExpand : function(node){
16747 var p = node.parentNode;
16749 if(p.expandedChild && p.expandedChild.parentNode == p){
16750 p.expandedChild.collapse();
16752 p.expandedChild = node;
16756 // private override
16757 setRootNode : function(node){
16758 Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
16759 if(!this.rootVisible){
16760 node.ui = new Roo.tree.RootTreeNodeUI(node);
16766 * Returns the container element for this TreePanel
16768 getEl : function(){
16773 * Returns the default TreeLoader for this TreePanel
16775 getLoader : function(){
16776 return this.loader;
16782 expandAll : function(){
16783 this.root.expand(true);
16787 * Collapse all nodes
16789 collapseAll : function(){
16790 this.root.collapse(true);
16794 * Returns the selection model used by this TreePanel
16796 getSelectionModel : function(){
16797 if(!this.selModel){
16798 this.selModel = new Roo.tree.DefaultSelectionModel();
16800 return this.selModel;
16804 * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
16805 * @param {String} attribute (optional) Defaults to null (return the actual nodes)
16806 * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
16809 getChecked : function(a, startNode){
16810 startNode = startNode || this.root;
16812 var f = function(){
16813 if(this.attributes.checked){
16814 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
16817 startNode.cascade(f);
16822 * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
16823 * @param {String} path
16824 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
16825 * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
16826 * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
16828 expandPath : function(path, attr, callback){
16829 attr = attr || "id";
16830 var keys = path.split(this.pathSeparator);
16831 var curNode = this.root;
16832 if(curNode.attributes[attr] != keys[1]){ // invalid root
16834 callback(false, null);
16839 var f = function(){
16840 if(++index == keys.length){
16842 callback(true, curNode);
16846 var c = curNode.findChild(attr, keys[index]);
16849 callback(false, curNode);
16854 c.expand(false, false, f);
16856 curNode.expand(false, false, f);
16860 * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
16861 * @param {String} path
16862 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
16863 * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
16864 * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
16866 selectPath : function(path, attr, callback){
16867 attr = attr || "id";
16868 var keys = path.split(this.pathSeparator);
16869 var v = keys.pop();
16870 if(keys.length > 0){
16871 var f = function(success, node){
16872 if(success && node){
16873 var n = node.findChild(attr, v);
16879 }else if(callback){
16880 callback(false, n);
16884 callback(false, n);
16888 this.expandPath(keys.join(this.pathSeparator), attr, f);
16890 this.root.select();
16892 callback(true, this.root);
16897 getTreeEl : function(){
16902 * Trigger rendering of this TreePanel
16904 render : function(){
16905 if (this.innerCt) {
16906 return this; // stop it rendering more than once!!
16909 this.innerCt = this.el.createChild({tag:"ul",
16910 cls:"x-tree-root-ct " +
16911 (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
16913 if(this.containerScroll){
16914 Roo.dd.ScrollManager.register(this.el);
16916 if((this.enableDD || this.enableDrop) && !this.dropZone){
16918 * The dropZone used by this tree if drop is enabled
16919 * @type Roo.tree.TreeDropZone
16921 this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
16922 ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
16925 if((this.enableDD || this.enableDrag) && !this.dragZone){
16927 * The dragZone used by this tree if drag is enabled
16928 * @type Roo.tree.TreeDragZone
16930 this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
16931 ddGroup: this.ddGroup || "TreeDD",
16932 scroll: this.ddScroll
16935 this.getSelectionModel().init(this);
16937 Roo.log("ROOT not set in tree");
16940 this.root.render();
16941 if(!this.rootVisible){
16942 this.root.renderChildren();
16948 * Ext JS Library 1.1.1
16949 * Copyright(c) 2006-2007, Ext JS, LLC.
16951 * Originally Released Under LGPL - original licence link has changed is not relivant.
16954 * <script type="text/javascript">
16959 * @class Roo.tree.DefaultSelectionModel
16960 * @extends Roo.util.Observable
16961 * The default single selection for a TreePanel.
16962 * @param {Object} cfg Configuration
16964 Roo.tree.DefaultSelectionModel = function(cfg){
16965 this.selNode = null;
16971 * @event selectionchange
16972 * Fires when the selected node changes
16973 * @param {DefaultSelectionModel} this
16974 * @param {TreeNode} node the new selection
16976 "selectionchange" : true,
16979 * @event beforeselect
16980 * Fires before the selected node changes, return false to cancel the change
16981 * @param {DefaultSelectionModel} this
16982 * @param {TreeNode} node the new selection
16983 * @param {TreeNode} node the old selection
16985 "beforeselect" : true
16988 Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
16991 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
16992 init : function(tree){
16994 tree.getTreeEl().on("keydown", this.onKeyDown, this);
16995 tree.on("click", this.onNodeClick, this);
16998 onNodeClick : function(node, e){
16999 if (e.ctrlKey && this.selNode == node) {
17000 this.unselect(node);
17008 * @param {TreeNode} node The node to select
17009 * @return {TreeNode} The selected node
17011 select : function(node){
17012 var last = this.selNode;
17013 if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
17015 last.ui.onSelectedChange(false);
17017 this.selNode = node;
17018 node.ui.onSelectedChange(true);
17019 this.fireEvent("selectionchange", this, node, last);
17026 * @param {TreeNode} node The node to unselect
17028 unselect : function(node){
17029 if(this.selNode == node){
17030 this.clearSelections();
17035 * Clear all selections
17037 clearSelections : function(){
17038 var n = this.selNode;
17040 n.ui.onSelectedChange(false);
17041 this.selNode = null;
17042 this.fireEvent("selectionchange", this, null);
17048 * Get the selected node
17049 * @return {TreeNode} The selected node
17051 getSelectedNode : function(){
17052 return this.selNode;
17056 * Returns true if the node is selected
17057 * @param {TreeNode} node The node to check
17058 * @return {Boolean}
17060 isSelected : function(node){
17061 return this.selNode == node;
17065 * Selects the node above the selected node in the tree, intelligently walking the nodes
17066 * @return TreeNode The new selection
17068 selectPrevious : function(){
17069 var s = this.selNode || this.lastSelNode;
17073 var ps = s.previousSibling;
17075 if(!ps.isExpanded() || ps.childNodes.length < 1){
17076 return this.select(ps);
17078 var lc = ps.lastChild;
17079 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
17082 return this.select(lc);
17084 } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
17085 return this.select(s.parentNode);
17091 * Selects the node above the selected node in the tree, intelligently walking the nodes
17092 * @return TreeNode The new selection
17094 selectNext : function(){
17095 var s = this.selNode || this.lastSelNode;
17099 if(s.firstChild && s.isExpanded()){
17100 return this.select(s.firstChild);
17101 }else if(s.nextSibling){
17102 return this.select(s.nextSibling);
17103 }else if(s.parentNode){
17105 s.parentNode.bubble(function(){
17106 if(this.nextSibling){
17107 newS = this.getOwnerTree().selModel.select(this.nextSibling);
17116 onKeyDown : function(e){
17117 var s = this.selNode || this.lastSelNode;
17118 // undesirable, but required
17123 var k = e.getKey();
17131 this.selectPrevious();
17134 e.preventDefault();
17135 if(s.hasChildNodes()){
17136 if(!s.isExpanded()){
17138 }else if(s.firstChild){
17139 this.select(s.firstChild, e);
17144 e.preventDefault();
17145 if(s.hasChildNodes() && s.isExpanded()){
17147 }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
17148 this.select(s.parentNode, e);
17156 * @class Roo.tree.MultiSelectionModel
17157 * @extends Roo.util.Observable
17158 * Multi selection for a TreePanel.
17159 * @param {Object} cfg Configuration
17161 Roo.tree.MultiSelectionModel = function(){
17162 this.selNodes = [];
17166 * @event selectionchange
17167 * Fires when the selected nodes change
17168 * @param {MultiSelectionModel} this
17169 * @param {Array} nodes Array of the selected nodes
17171 "selectionchange" : true
17173 Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
17177 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
17178 init : function(tree){
17180 tree.getTreeEl().on("keydown", this.onKeyDown, this);
17181 tree.on("click", this.onNodeClick, this);
17184 onNodeClick : function(node, e){
17185 this.select(node, e, e.ctrlKey);
17190 * @param {TreeNode} node The node to select
17191 * @param {EventObject} e (optional) An event associated with the selection
17192 * @param {Boolean} keepExisting True to retain existing selections
17193 * @return {TreeNode} The selected node
17195 select : function(node, e, keepExisting){
17196 if(keepExisting !== true){
17197 this.clearSelections(true);
17199 if(this.isSelected(node)){
17200 this.lastSelNode = node;
17203 this.selNodes.push(node);
17204 this.selMap[node.id] = node;
17205 this.lastSelNode = node;
17206 node.ui.onSelectedChange(true);
17207 this.fireEvent("selectionchange", this, this.selNodes);
17213 * @param {TreeNode} node The node to unselect
17215 unselect : function(node){
17216 if(this.selMap[node.id]){
17217 node.ui.onSelectedChange(false);
17218 var sn = this.selNodes;
17221 index = sn.indexOf(node);
17223 for(var i = 0, len = sn.length; i < len; i++){
17231 this.selNodes.splice(index, 1);
17233 delete this.selMap[node.id];
17234 this.fireEvent("selectionchange", this, this.selNodes);
17239 * Clear all selections
17241 clearSelections : function(suppressEvent){
17242 var sn = this.selNodes;
17244 for(var i = 0, len = sn.length; i < len; i++){
17245 sn[i].ui.onSelectedChange(false);
17247 this.selNodes = [];
17249 if(suppressEvent !== true){
17250 this.fireEvent("selectionchange", this, this.selNodes);
17256 * Returns true if the node is selected
17257 * @param {TreeNode} node The node to check
17258 * @return {Boolean}
17260 isSelected : function(node){
17261 return this.selMap[node.id] ? true : false;
17265 * Returns an array of the selected nodes
17268 getSelectedNodes : function(){
17269 return this.selNodes;
17272 onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
17274 selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
17276 selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
17279 * Ext JS Library 1.1.1
17280 * Copyright(c) 2006-2007, Ext JS, LLC.
17282 * Originally Released Under LGPL - original licence link has changed is not relivant.
17285 * <script type="text/javascript">
17289 * @class Roo.tree.TreeNode
17290 * @extends Roo.data.Node
17291 * @cfg {String} text The text for this node
17292 * @cfg {Boolean} expanded true to start the node expanded
17293 * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
17294 * @cfg {Boolean} allowDrop false if this node cannot be drop on
17295 * @cfg {Boolean} disabled true to start the node disabled
17296 * @cfg {String} icon The path to an icon for the node. The preferred way to do this
17297 * is to use the cls or iconCls attributes and add the icon via a CSS background image.
17298 * @cfg {String} cls A css class to be added to the node
17299 * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
17300 * @cfg {String} href URL of the link used for the node (defaults to #)
17301 * @cfg {String} hrefTarget target frame for the link
17302 * @cfg {String} qtip An Ext QuickTip for the node
17303 * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
17304 * @cfg {Boolean} singleClickExpand True for single click expand on this node
17305 * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
17306 * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
17307 * (defaults to undefined with no checkbox rendered)
17309 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
17311 Roo.tree.TreeNode = function(attributes){
17312 attributes = attributes || {};
17313 if(typeof attributes == "string"){
17314 attributes = {text: attributes};
17316 this.childrenRendered = false;
17317 this.rendered = false;
17318 Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
17319 this.expanded = attributes.expanded === true;
17320 this.isTarget = attributes.isTarget !== false;
17321 this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
17322 this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
17325 * Read-only. The text for this node. To change it use setText().
17328 this.text = attributes.text;
17330 * True if this node is disabled.
17333 this.disabled = attributes.disabled === true;
17337 * @event textchange
17338 * Fires when the text for this node is changed
17339 * @param {Node} this This node
17340 * @param {String} text The new text
17341 * @param {String} oldText The old text
17343 "textchange" : true,
17345 * @event beforeexpand
17346 * Fires before this node is expanded, return false to cancel.
17347 * @param {Node} this This node
17348 * @param {Boolean} deep
17349 * @param {Boolean} anim
17351 "beforeexpand" : true,
17353 * @event beforecollapse
17354 * Fires before this node is collapsed, return false to cancel.
17355 * @param {Node} this This node
17356 * @param {Boolean} deep
17357 * @param {Boolean} anim
17359 "beforecollapse" : true,
17362 * Fires when this node is expanded
17363 * @param {Node} this This node
17367 * @event disabledchange
17368 * Fires when the disabled status of this node changes
17369 * @param {Node} this This node
17370 * @param {Boolean} disabled
17372 "disabledchange" : true,
17375 * Fires when this node is collapsed
17376 * @param {Node} this This node
17380 * @event beforeclick
17381 * Fires before click processing. Return false to cancel the default action.
17382 * @param {Node} this This node
17383 * @param {Roo.EventObject} e The event object
17385 "beforeclick":true,
17387 * @event checkchange
17388 * Fires when a node with a checkbox's checked property changes
17389 * @param {Node} this This node
17390 * @param {Boolean} checked
17392 "checkchange":true,
17395 * Fires when this node is clicked
17396 * @param {Node} this This node
17397 * @param {Roo.EventObject} e The event object
17402 * Fires when this node is double clicked
17403 * @param {Node} this This node
17404 * @param {Roo.EventObject} e The event object
17408 * @event contextmenu
17409 * Fires when this node is right clicked
17410 * @param {Node} this This node
17411 * @param {Roo.EventObject} e The event object
17413 "contextmenu":true,
17415 * @event beforechildrenrendered
17416 * Fires right before the child nodes for this node are rendered
17417 * @param {Node} this This node
17419 "beforechildrenrendered":true
17422 var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
17425 * Read-only. The UI for this node
17428 this.ui = new uiClass(this);
17430 // finally support items[]
17431 if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
17436 Roo.each(this.attributes.items, function(c) {
17437 this.appendChild(Roo.factory(c,Roo.Tree));
17439 delete this.attributes.items;
17444 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
17445 preventHScroll: true,
17447 * Returns true if this node is expanded
17448 * @return {Boolean}
17450 isExpanded : function(){
17451 return this.expanded;
17455 * Returns the UI object for this node
17456 * @return {TreeNodeUI}
17458 getUI : function(){
17462 // private override
17463 setFirstChild : function(node){
17464 var of = this.firstChild;
17465 Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
17466 if(this.childrenRendered && of && node != of){
17467 of.renderIndent(true, true);
17470 this.renderIndent(true, true);
17474 // private override
17475 setLastChild : function(node){
17476 var ol = this.lastChild;
17477 Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
17478 if(this.childrenRendered && ol && node != ol){
17479 ol.renderIndent(true, true);
17482 this.renderIndent(true, true);
17486 // these methods are overridden to provide lazy rendering support
17487 // private override
17488 appendChild : function()
17490 var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
17491 if(node && this.childrenRendered){
17494 this.ui.updateExpandIcon();
17498 // private override
17499 removeChild : function(node){
17500 this.ownerTree.getSelectionModel().unselect(node);
17501 Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
17502 // if it's been rendered remove dom node
17503 if(this.childrenRendered){
17506 if(this.childNodes.length < 1){
17507 this.collapse(false, false);
17509 this.ui.updateExpandIcon();
17511 if(!this.firstChild) {
17512 this.childrenRendered = false;
17517 // private override
17518 insertBefore : function(node, refNode){
17519 var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
17520 if(newNode && refNode && this.childrenRendered){
17523 this.ui.updateExpandIcon();
17528 * Sets the text for this node
17529 * @param {String} text
17531 setText : function(text){
17532 var oldText = this.text;
17534 this.attributes.text = text;
17535 if(this.rendered){ // event without subscribing
17536 this.ui.onTextChange(this, text, oldText);
17538 this.fireEvent("textchange", this, text, oldText);
17542 * Triggers selection of this node
17544 select : function(){
17545 this.getOwnerTree().getSelectionModel().select(this);
17549 * Triggers deselection of this node
17551 unselect : function(){
17552 this.getOwnerTree().getSelectionModel().unselect(this);
17556 * Returns true if this node is selected
17557 * @return {Boolean}
17559 isSelected : function(){
17560 return this.getOwnerTree().getSelectionModel().isSelected(this);
17564 * Expand this node.
17565 * @param {Boolean} deep (optional) True to expand all children as well
17566 * @param {Boolean} anim (optional) false to cancel the default animation
17567 * @param {Function} callback (optional) A callback to be called when
17568 * expanding this node completes (does not wait for deep expand to complete).
17569 * Called with 1 parameter, this node.
17571 expand : function(deep, anim, callback){
17572 if(!this.expanded){
17573 if(this.fireEvent("beforeexpand", this, deep, anim) === false){
17576 if(!this.childrenRendered){
17577 this.renderChildren();
17579 this.expanded = true;
17580 if(!this.isHiddenRoot() && (this.getOwnerTree().animate && anim !== false) || anim){
17581 this.ui.animExpand(function(){
17582 this.fireEvent("expand", this);
17583 if(typeof callback == "function"){
17587 this.expandChildNodes(true);
17589 }.createDelegate(this));
17593 this.fireEvent("expand", this);
17594 if(typeof callback == "function"){
17599 if(typeof callback == "function"){
17604 this.expandChildNodes(true);
17608 isHiddenRoot : function(){
17609 return this.isRoot && !this.getOwnerTree().rootVisible;
17613 * Collapse this node.
17614 * @param {Boolean} deep (optional) True to collapse all children as well
17615 * @param {Boolean} anim (optional) false to cancel the default animation
17617 collapse : function(deep, anim){
17618 if(this.expanded && !this.isHiddenRoot()){
17619 if(this.fireEvent("beforecollapse", this, deep, anim) === false){
17622 this.expanded = false;
17623 if((this.getOwnerTree().animate && anim !== false) || anim){
17624 this.ui.animCollapse(function(){
17625 this.fireEvent("collapse", this);
17627 this.collapseChildNodes(true);
17629 }.createDelegate(this));
17632 this.ui.collapse();
17633 this.fireEvent("collapse", this);
17637 var cs = this.childNodes;
17638 for(var i = 0, len = cs.length; i < len; i++) {
17639 cs[i].collapse(true, false);
17645 delayedExpand : function(delay){
17646 if(!this.expandProcId){
17647 this.expandProcId = this.expand.defer(delay, this);
17652 cancelExpand : function(){
17653 if(this.expandProcId){
17654 clearTimeout(this.expandProcId);
17656 this.expandProcId = false;
17660 * Toggles expanded/collapsed state of the node
17662 toggle : function(){
17671 * Ensures all parent nodes are expanded
17673 ensureVisible : function(callback){
17674 var tree = this.getOwnerTree();
17675 tree.expandPath(this.parentNode.getPath(), false, function(){
17676 tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
17677 Roo.callback(callback);
17678 }.createDelegate(this));
17682 * Expand all child nodes
17683 * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
17685 expandChildNodes : function(deep){
17686 var cs = this.childNodes;
17687 for(var i = 0, len = cs.length; i < len; i++) {
17688 cs[i].expand(deep);
17693 * Collapse all child nodes
17694 * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
17696 collapseChildNodes : function(deep){
17697 var cs = this.childNodes;
17698 for(var i = 0, len = cs.length; i < len; i++) {
17699 cs[i].collapse(deep);
17704 * Disables this node
17706 disable : function(){
17707 this.disabled = true;
17709 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
17710 this.ui.onDisableChange(this, true);
17712 this.fireEvent("disabledchange", this, true);
17716 * Enables this node
17718 enable : function(){
17719 this.disabled = false;
17720 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
17721 this.ui.onDisableChange(this, false);
17723 this.fireEvent("disabledchange", this, false);
17727 renderChildren : function(suppressEvent){
17728 if(suppressEvent !== false){
17729 this.fireEvent("beforechildrenrendered", this);
17731 var cs = this.childNodes;
17732 for(var i = 0, len = cs.length; i < len; i++){
17733 cs[i].render(true);
17735 this.childrenRendered = true;
17739 sort : function(fn, scope){
17740 Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
17741 if(this.childrenRendered){
17742 var cs = this.childNodes;
17743 for(var i = 0, len = cs.length; i < len; i++){
17744 cs[i].render(true);
17750 render : function(bulkRender){
17751 this.ui.render(bulkRender);
17752 if(!this.rendered){
17753 this.rendered = true;
17755 this.expanded = false;
17756 this.expand(false, false);
17762 renderIndent : function(deep, refresh){
17764 this.ui.childIndent = null;
17766 this.ui.renderIndent();
17767 if(deep === true && this.childrenRendered){
17768 var cs = this.childNodes;
17769 for(var i = 0, len = cs.length; i < len; i++){
17770 cs[i].renderIndent(true, refresh);
17776 * Ext JS Library 1.1.1
17777 * Copyright(c) 2006-2007, Ext JS, LLC.
17779 * Originally Released Under LGPL - original licence link has changed is not relivant.
17782 * <script type="text/javascript">
17786 * @class Roo.tree.AsyncTreeNode
17787 * @extends Roo.tree.TreeNode
17788 * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
17790 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
17792 Roo.tree.AsyncTreeNode = function(config){
17793 this.loaded = false;
17794 this.loading = false;
17795 Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
17797 * @event beforeload
17798 * Fires before this node is loaded, return false to cancel
17799 * @param {Node} this This node
17801 this.addEvents({'beforeload':true, 'load': true});
17804 * Fires when this node is loaded
17805 * @param {Node} this This node
17808 * The loader used by this node (defaults to using the tree's defined loader)
17813 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
17814 expand : function(deep, anim, callback){
17815 if(this.loading){ // if an async load is already running, waiting til it's done
17817 var f = function(){
17818 if(!this.loading){ // done loading
17819 clearInterval(timer);
17820 this.expand(deep, anim, callback);
17822 }.createDelegate(this);
17823 timer = setInterval(f, 200);
17827 if(this.fireEvent("beforeload", this) === false){
17830 this.loading = true;
17831 this.ui.beforeLoad(this);
17832 var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
17834 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
17838 Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
17842 * Returns true if this node is currently loading
17843 * @return {Boolean}
17845 isLoading : function(){
17846 return this.loading;
17849 loadComplete : function(deep, anim, callback){
17850 this.loading = false;
17851 this.loaded = true;
17852 this.ui.afterLoad(this);
17853 this.fireEvent("load", this);
17854 this.expand(deep, anim, callback);
17858 * Returns true if this node has been loaded
17859 * @return {Boolean}
17861 isLoaded : function(){
17862 return this.loaded;
17865 hasChildNodes : function(){
17866 if(!this.isLeaf() && !this.loaded){
17869 return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
17874 * Trigger a reload for this node
17875 * @param {Function} callback
17877 reload : function(callback){
17878 this.collapse(false, false);
17879 while(this.firstChild){
17880 this.removeChild(this.firstChild);
17882 this.childrenRendered = false;
17883 this.loaded = false;
17884 if(this.isHiddenRoot()){
17885 this.expanded = false;
17887 this.expand(false, false, callback);
17891 * Ext JS Library 1.1.1
17892 * Copyright(c) 2006-2007, Ext JS, LLC.
17894 * Originally Released Under LGPL - original licence link has changed is not relivant.
17897 * <script type="text/javascript">
17901 * @class Roo.tree.TreeNodeUI
17903 * @param {Object} node The node to render
17904 * The TreeNode UI implementation is separate from the
17905 * tree implementation. Unless you are customizing the tree UI,
17906 * you should never have to use this directly.
17908 Roo.tree.TreeNodeUI = function(node){
17910 this.rendered = false;
17911 this.animating = false;
17912 this.emptyIcon = Roo.BLANK_IMAGE_URL;
17915 Roo.tree.TreeNodeUI.prototype = {
17916 removeChild : function(node){
17918 this.ctNode.removeChild(node.ui.getEl());
17922 beforeLoad : function(){
17923 this.addClass("x-tree-node-loading");
17926 afterLoad : function(){
17927 this.removeClass("x-tree-node-loading");
17930 onTextChange : function(node, text, oldText){
17932 this.textNode.innerHTML = text;
17936 onDisableChange : function(node, state){
17937 this.disabled = state;
17939 this.addClass("x-tree-node-disabled");
17941 this.removeClass("x-tree-node-disabled");
17945 onSelectedChange : function(state){
17948 this.addClass("x-tree-selected");
17951 this.removeClass("x-tree-selected");
17955 onMove : function(tree, node, oldParent, newParent, index, refNode){
17956 this.childIndent = null;
17958 var targetNode = newParent.ui.getContainer();
17959 if(!targetNode){//target not rendered
17960 this.holder = document.createElement("div");
17961 this.holder.appendChild(this.wrap);
17964 var insertBefore = refNode ? refNode.ui.getEl() : null;
17966 targetNode.insertBefore(this.wrap, insertBefore);
17968 targetNode.appendChild(this.wrap);
17970 this.node.renderIndent(true);
17974 addClass : function(cls){
17976 Roo.fly(this.elNode).addClass(cls);
17980 removeClass : function(cls){
17982 Roo.fly(this.elNode).removeClass(cls);
17986 remove : function(){
17988 this.holder = document.createElement("div");
17989 this.holder.appendChild(this.wrap);
17993 fireEvent : function(){
17994 return this.node.fireEvent.apply(this.node, arguments);
17997 initEvents : function(){
17998 this.node.on("move", this.onMove, this);
17999 var E = Roo.EventManager;
18000 var a = this.anchor;
18002 var el = Roo.fly(a, '_treeui');
18004 if(Roo.isOpera){ // opera render bug ignores the CSS
18005 el.setStyle("text-decoration", "none");
18008 el.on("click", this.onClick, this);
18009 el.on("dblclick", this.onDblClick, this);
18012 Roo.EventManager.on(this.checkbox,
18013 Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
18016 el.on("contextmenu", this.onContextMenu, this);
18018 var icon = Roo.fly(this.iconNode);
18019 icon.on("click", this.onClick, this);
18020 icon.on("dblclick", this.onDblClick, this);
18021 icon.on("contextmenu", this.onContextMenu, this);
18022 E.on(this.ecNode, "click", this.ecClick, this, true);
18024 if(this.node.disabled){
18025 this.addClass("x-tree-node-disabled");
18027 if(this.node.hidden){
18028 this.addClass("x-tree-node-disabled");
18030 var ot = this.node.getOwnerTree();
18031 var dd = ot.enableDD || ot.enableDrag || ot.enableDrop;
18032 if(dd && (!this.node.isRoot || ot.rootVisible)){
18033 Roo.dd.Registry.register(this.elNode, {
18035 handles: this.getDDHandles(),
18041 getDDHandles : function(){
18042 return [this.iconNode, this.textNode];
18047 this.wrap.style.display = "none";
18053 this.wrap.style.display = "";
18057 onContextMenu : function(e){
18058 if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
18059 e.preventDefault();
18061 this.fireEvent("contextmenu", this.node, e);
18065 onClick : function(e){
18070 if(this.fireEvent("beforeclick", this.node, e) !== false){
18071 if(!this.disabled && this.node.attributes.href){
18072 this.fireEvent("click", this.node, e);
18075 e.preventDefault();
18080 if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
18081 this.node.toggle();
18084 this.fireEvent("click", this.node, e);
18090 onDblClick : function(e){
18091 e.preventDefault();
18096 this.toggleCheck();
18098 if(!this.animating && this.node.hasChildNodes()){
18099 this.node.toggle();
18101 this.fireEvent("dblclick", this.node, e);
18104 onCheckChange : function(){
18105 var checked = this.checkbox.checked;
18106 this.node.attributes.checked = checked;
18107 this.fireEvent('checkchange', this.node, checked);
18110 ecClick : function(e){
18111 if(!this.animating && this.node.hasChildNodes()){
18112 this.node.toggle();
18116 startDrop : function(){
18117 this.dropping = true;
18120 // delayed drop so the click event doesn't get fired on a drop
18121 endDrop : function(){
18122 setTimeout(function(){
18123 this.dropping = false;
18124 }.createDelegate(this), 50);
18127 expand : function(){
18128 this.updateExpandIcon();
18129 this.ctNode.style.display = "";
18132 focus : function(){
18133 if(!this.node.preventHScroll){
18134 try{this.anchor.focus();
18136 }else if(!Roo.isIE){
18138 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
18139 var l = noscroll.scrollLeft;
18140 this.anchor.focus();
18141 noscroll.scrollLeft = l;
18146 toggleCheck : function(value){
18147 var cb = this.checkbox;
18149 cb.checked = (value === undefined ? !cb.checked : value);
18155 this.anchor.blur();
18159 animExpand : function(callback){
18160 var ct = Roo.get(this.ctNode);
18162 if(!this.node.hasChildNodes()){
18163 this.updateExpandIcon();
18164 this.ctNode.style.display = "";
18165 Roo.callback(callback);
18168 this.animating = true;
18169 this.updateExpandIcon();
18172 callback : function(){
18173 this.animating = false;
18174 Roo.callback(callback);
18177 duration: this.node.ownerTree.duration || .25
18181 highlight : function(){
18182 var tree = this.node.getOwnerTree();
18183 Roo.fly(this.wrap).highlight(
18184 tree.hlColor || "C3DAF9",
18185 {endColor: tree.hlBaseColor}
18189 collapse : function(){
18190 this.updateExpandIcon();
18191 this.ctNode.style.display = "none";
18194 animCollapse : function(callback){
18195 var ct = Roo.get(this.ctNode);
18196 ct.enableDisplayMode('block');
18199 this.animating = true;
18200 this.updateExpandIcon();
18203 callback : function(){
18204 this.animating = false;
18205 Roo.callback(callback);
18208 duration: this.node.ownerTree.duration || .25
18212 getContainer : function(){
18213 return this.ctNode;
18216 getEl : function(){
18220 appendDDGhost : function(ghostNode){
18221 ghostNode.appendChild(this.elNode.cloneNode(true));
18224 getDDRepairXY : function(){
18225 return Roo.lib.Dom.getXY(this.iconNode);
18228 onRender : function(){
18232 render : function(bulkRender){
18233 var n = this.node, a = n.attributes;
18234 var targetNode = n.parentNode ?
18235 n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
18237 if(!this.rendered){
18238 this.rendered = true;
18240 this.renderElements(n, a, targetNode, bulkRender);
18243 if(this.textNode.setAttributeNS){
18244 this.textNode.setAttributeNS("ext", "qtip", a.qtip);
18246 this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
18249 this.textNode.setAttribute("ext:qtip", a.qtip);
18251 this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
18254 }else if(a.qtipCfg){
18255 a.qtipCfg.target = Roo.id(this.textNode);
18256 Roo.QuickTips.register(a.qtipCfg);
18259 if(!this.node.expanded){
18260 this.updateExpandIcon();
18263 if(bulkRender === true) {
18264 targetNode.appendChild(this.wrap);
18269 renderElements : function(n, a, targetNode, bulkRender)
18271 // add some indent caching, this helps performance when rendering a large tree
18272 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
18273 var t = n.getOwnerTree();
18274 var txt = t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
18275 if (typeof(n.attributes.html) != 'undefined') {
18276 txt = n.attributes.html;
18278 var tip = t.rendererTip ? t.rendererTip(n.attributes) : txt;
18279 var cb = typeof a.checked == 'boolean';
18280 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
18281 var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
18282 '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
18283 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
18284 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
18285 cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
18286 '<a hidefocus="on" href="',href,'" tabIndex="1" ',
18287 a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "",
18288 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
18289 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
18292 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
18293 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
18294 n.nextSibling.ui.getEl(), buf.join(""));
18296 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
18299 this.elNode = this.wrap.childNodes[0];
18300 this.ctNode = this.wrap.childNodes[1];
18301 var cs = this.elNode.childNodes;
18302 this.indentNode = cs[0];
18303 this.ecNode = cs[1];
18304 this.iconNode = cs[2];
18307 this.checkbox = cs[3];
18310 this.anchor = cs[index];
18311 this.textNode = cs[index].firstChild;
18314 getAnchor : function(){
18315 return this.anchor;
18318 getTextEl : function(){
18319 return this.textNode;
18322 getIconEl : function(){
18323 return this.iconNode;
18326 isChecked : function(){
18327 return this.checkbox ? this.checkbox.checked : false;
18330 updateExpandIcon : function(){
18332 var n = this.node, c1, c2;
18333 var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
18334 var hasChild = n.hasChildNodes();
18338 c1 = "x-tree-node-collapsed";
18339 c2 = "x-tree-node-expanded";
18342 c1 = "x-tree-node-expanded";
18343 c2 = "x-tree-node-collapsed";
18346 this.removeClass("x-tree-node-leaf");
18347 this.wasLeaf = false;
18349 if(this.c1 != c1 || this.c2 != c2){
18350 Roo.fly(this.elNode).replaceClass(c1, c2);
18351 this.c1 = c1; this.c2 = c2;
18354 // this changes non-leafs into leafs if they have no children.
18355 // it's not very rational behaviour..
18357 if(!this.wasLeaf && this.node.leaf){
18358 Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
18361 this.wasLeaf = true;
18364 var ecc = "x-tree-ec-icon "+cls;
18365 if(this.ecc != ecc){
18366 this.ecNode.className = ecc;
18372 getChildIndent : function(){
18373 if(!this.childIndent){
18377 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
18379 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
18381 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
18386 this.childIndent = buf.join("");
18388 return this.childIndent;
18391 renderIndent : function(){
18394 var p = this.node.parentNode;
18396 indent = p.ui.getChildIndent();
18398 if(this.indentMarkup != indent){ // don't rerender if not required
18399 this.indentNode.innerHTML = indent;
18400 this.indentMarkup = indent;
18402 this.updateExpandIcon();
18407 Roo.tree.RootTreeNodeUI = function(){
18408 Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
18410 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
18411 render : function(){
18412 if(!this.rendered){
18413 var targetNode = this.node.ownerTree.innerCt.dom;
18414 this.node.expanded = true;
18415 targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
18416 this.wrap = this.ctNode = targetNode.firstChild;
18419 collapse : function(){
18421 expand : function(){
18425 * Ext JS Library 1.1.1
18426 * Copyright(c) 2006-2007, Ext JS, LLC.
18428 * Originally Released Under LGPL - original licence link has changed is not relivant.
18431 * <script type="text/javascript">
18434 * @class Roo.tree.TreeLoader
18435 * @extends Roo.util.Observable
18436 * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
18437 * nodes from a specified URL. The response must be a javascript Array definition
18438 * who's elements are node definition objects. eg:
18443 { 'id': 1, 'text': 'A folder Node', 'leaf': false },
18444 { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
18451 * The old style respose with just an array is still supported, but not recommended.
18454 * A server request is sent, and child nodes are loaded only when a node is expanded.
18455 * The loading node's id is passed to the server under the parameter name "node" to
18456 * enable the server to produce the correct child nodes.
18458 * To pass extra parameters, an event handler may be attached to the "beforeload"
18459 * event, and the parameters specified in the TreeLoader's baseParams property:
18461 myTreeLoader.on("beforeload", function(treeLoader, node) {
18462 this.baseParams.category = node.attributes.category;
18465 * This would pass an HTTP parameter called "category" to the server containing
18466 * the value of the Node's "category" attribute.
18468 * Creates a new Treeloader.
18469 * @param {Object} config A config object containing config properties.
18471 Roo.tree.TreeLoader = function(config){
18472 this.baseParams = {};
18473 this.requestMethod = "POST";
18474 Roo.apply(this, config);
18479 * @event beforeload
18480 * Fires before a network request is made to retrieve the Json text which specifies a node's children.
18481 * @param {Object} This TreeLoader object.
18482 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
18483 * @param {Object} callback The callback function specified in the {@link #load} call.
18488 * Fires when the node has been successfuly loaded.
18489 * @param {Object} This TreeLoader object.
18490 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
18491 * @param {Object} response The response object containing the data from the server.
18495 * @event loadexception
18496 * Fires if the network request failed.
18497 * @param {Object} This TreeLoader object.
18498 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
18499 * @param {Object} response The response object containing the data from the server.
18501 loadexception : true,
18504 * Fires before a node is created, enabling you to return custom Node types
18505 * @param {Object} This TreeLoader object.
18506 * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
18511 Roo.tree.TreeLoader.superclass.constructor.call(this);
18514 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
18516 * @cfg {String} dataUrl The URL from which to request a Json string which
18517 * specifies an array of node definition object representing the child nodes
18521 * @cfg {String} requestMethod either GET or POST
18522 * defaults to POST (due to BC)
18526 * @cfg {Object} baseParams (optional) An object containing properties which
18527 * specify HTTP parameters to be passed to each request for child nodes.
18530 * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
18531 * created by this loader. If the attributes sent by the server have an attribute in this object,
18532 * they take priority.
18535 * @cfg {Object} uiProviders (optional) An object containing properties which
18537 * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
18538 * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
18539 * <i>uiProvider</i> attribute of a returned child node is a string rather
18540 * than a reference to a TreeNodeUI implementation, this that string value
18541 * is used as a property name in the uiProviders object. You can define the provider named
18542 * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
18547 * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
18548 * child nodes before loading.
18550 clearOnLoad : true,
18553 * @cfg {String} root (optional) Default to false. Use this to read data from an object
18554 * property on loading, rather than expecting an array. (eg. more compatible to a standard
18555 * Grid query { data : [ .....] }
18560 * @cfg {String} queryParam (optional)
18561 * Name of the query as it will be passed on the querystring (defaults to 'node')
18562 * eg. the request will be ?node=[id]
18569 * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
18570 * This is called automatically when a node is expanded, but may be used to reload
18571 * a node (or append new children if the {@link #clearOnLoad} option is false.)
18572 * @param {Roo.tree.TreeNode} node
18573 * @param {Function} callback
18575 load : function(node, callback){
18576 if(this.clearOnLoad){
18577 while(node.firstChild){
18578 node.removeChild(node.firstChild);
18581 if(node.attributes.children){ // preloaded json children
18582 var cs = node.attributes.children;
18583 for(var i = 0, len = cs.length; i < len; i++){
18584 node.appendChild(this.createNode(cs[i]));
18586 if(typeof callback == "function"){
18589 }else if(this.dataUrl){
18590 this.requestData(node, callback);
18594 getParams: function(node){
18595 var buf = [], bp = this.baseParams;
18596 for(var key in bp){
18597 if(typeof bp[key] != "function"){
18598 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
18601 var n = this.queryParam === false ? 'node' : this.queryParam;
18602 buf.push(n + "=", encodeURIComponent(node.id));
18603 return buf.join("");
18606 requestData : function(node, callback){
18607 if(this.fireEvent("beforeload", this, node, callback) !== false){
18608 this.transId = Roo.Ajax.request({
18609 method:this.requestMethod,
18610 url: this.dataUrl||this.url,
18611 success: this.handleResponse,
18612 failure: this.handleFailure,
18614 argument: {callback: callback, node: node},
18615 params: this.getParams(node)
18618 // if the load is cancelled, make sure we notify
18619 // the node that we are done
18620 if(typeof callback == "function"){
18626 isLoading : function(){
18627 return this.transId ? true : false;
18630 abort : function(){
18631 if(this.isLoading()){
18632 Roo.Ajax.abort(this.transId);
18637 createNode : function(attr)
18639 // apply baseAttrs, nice idea Corey!
18640 if(this.baseAttrs){
18641 Roo.applyIf(attr, this.baseAttrs);
18643 if(this.applyLoader !== false){
18644 attr.loader = this;
18646 // uiProvider = depreciated..
18648 if(typeof(attr.uiProvider) == 'string'){
18649 attr.uiProvider = this.uiProviders[attr.uiProvider] ||
18650 /** eval:var:attr */ eval(attr.uiProvider);
18652 if(typeof(this.uiProviders['default']) != 'undefined') {
18653 attr.uiProvider = this.uiProviders['default'];
18656 this.fireEvent('create', this, attr);
18658 attr.leaf = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
18660 new Roo.tree.TreeNode(attr) :
18661 new Roo.tree.AsyncTreeNode(attr));
18664 processResponse : function(response, node, callback)
18666 var json = response.responseText;
18669 var o = Roo.decode(json);
18671 if (this.root === false && typeof(o.success) != undefined) {
18672 this.root = 'data'; // the default behaviour for list like data..
18675 if (this.root !== false && !o.success) {
18676 // it's a failure condition.
18677 var a = response.argument;
18678 this.fireEvent("loadexception", this, a.node, response);
18679 Roo.log("Load failed - should have a handler really");
18685 if (this.root !== false) {
18689 for(var i = 0, len = o.length; i < len; i++){
18690 var n = this.createNode(o[i]);
18692 node.appendChild(n);
18695 if(typeof callback == "function"){
18696 callback(this, node);
18699 this.handleFailure(response);
18703 handleResponse : function(response){
18704 this.transId = false;
18705 var a = response.argument;
18706 this.processResponse(response, a.node, a.callback);
18707 this.fireEvent("load", this, a.node, response);
18710 handleFailure : function(response)
18712 // should handle failure better..
18713 this.transId = false;
18714 var a = response.argument;
18715 this.fireEvent("loadexception", this, a.node, response);
18716 if(typeof a.callback == "function"){
18717 a.callback(this, a.node);
18722 * Ext JS Library 1.1.1
18723 * Copyright(c) 2006-2007, Ext JS, LLC.
18725 * Originally Released Under LGPL - original licence link has changed is not relivant.
18728 * <script type="text/javascript">
18732 * @class Roo.tree.TreeFilter
18733 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
18734 * @param {TreePanel} tree
18735 * @param {Object} config (optional)
18737 Roo.tree.TreeFilter = function(tree, config){
18739 this.filtered = {};
18740 Roo.apply(this, config);
18743 Roo.tree.TreeFilter.prototype = {
18750 * Filter the data by a specific attribute.
18751 * @param {String/RegExp} value Either string that the attribute value
18752 * should start with or a RegExp to test against the attribute
18753 * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
18754 * @param {TreeNode} startNode (optional) The node to start the filter at.
18756 filter : function(value, attr, startNode){
18757 attr = attr || "text";
18759 if(typeof value == "string"){
18760 var vlen = value.length;
18761 // auto clear empty filter
18762 if(vlen == 0 && this.clearBlank){
18766 value = value.toLowerCase();
18768 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
18770 }else if(value.exec){ // regex?
18772 return value.test(n.attributes[attr]);
18775 throw 'Illegal filter type, must be string or regex';
18777 this.filterBy(f, null, startNode);
18781 * Filter by a function. The passed function will be called with each
18782 * node in the tree (or from the startNode). If the function returns true, the node is kept
18783 * otherwise it is filtered. If a node is filtered, its children are also filtered.
18784 * @param {Function} fn The filter function
18785 * @param {Object} scope (optional) The scope of the function (defaults to the current node)
18787 filterBy : function(fn, scope, startNode){
18788 startNode = startNode || this.tree.root;
18789 if(this.autoClear){
18792 var af = this.filtered, rv = this.reverse;
18793 var f = function(n){
18794 if(n == startNode){
18800 var m = fn.call(scope || n, n);
18808 startNode.cascade(f);
18811 if(typeof id != "function"){
18813 if(n && n.parentNode){
18814 n.parentNode.removeChild(n);
18822 * Clears the current filter. Note: with the "remove" option
18823 * set a filter cannot be cleared.
18825 clear : function(){
18827 var af = this.filtered;
18829 if(typeof id != "function"){
18836 this.filtered = {};
18841 * Ext JS Library 1.1.1
18842 * Copyright(c) 2006-2007, Ext JS, LLC.
18844 * Originally Released Under LGPL - original licence link has changed is not relivant.
18847 * <script type="text/javascript">
18852 * @class Roo.tree.TreeSorter
18853 * Provides sorting of nodes in a TreePanel
18855 * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
18856 * @cfg {String} property The named attribute on the node to sort by (defaults to text)
18857 * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
18858 * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
18859 * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
18860 * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
18862 * @param {TreePanel} tree
18863 * @param {Object} config
18865 Roo.tree.TreeSorter = function(tree, config){
18866 Roo.apply(this, config);
18867 tree.on("beforechildrenrendered", this.doSort, this);
18868 tree.on("append", this.updateSort, this);
18869 tree.on("insert", this.updateSort, this);
18871 var dsc = this.dir && this.dir.toLowerCase() == "desc";
18872 var p = this.property || "text";
18873 var sortType = this.sortType;
18874 var fs = this.folderSort;
18875 var cs = this.caseSensitive === true;
18876 var leafAttr = this.leafAttr || 'leaf';
18878 this.sortFn = function(n1, n2){
18880 if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
18883 if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
18887 var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
18888 var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
18890 return dsc ? +1 : -1;
18892 return dsc ? -1 : +1;
18899 Roo.tree.TreeSorter.prototype = {
18900 doSort : function(node){
18901 node.sort(this.sortFn);
18904 compareNodes : function(n1, n2){
18905 return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
18908 updateSort : function(tree, node){
18909 if(node.childrenRendered){
18910 this.doSort.defer(1, this, [node]);
18915 * Ext JS Library 1.1.1
18916 * Copyright(c) 2006-2007, Ext JS, LLC.
18918 * Originally Released Under LGPL - original licence link has changed is not relivant.
18921 * <script type="text/javascript">
18924 if(Roo.dd.DropZone){
18926 Roo.tree.TreeDropZone = function(tree, config){
18927 this.allowParentInsert = false;
18928 this.allowContainerDrop = false;
18929 this.appendOnly = false;
18930 Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
18932 this.lastInsertClass = "x-tree-no-status";
18933 this.dragOverData = {};
18936 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
18937 ddGroup : "TreeDD",
18939 expandDelay : 1000,
18941 expandNode : function(node){
18942 if(node.hasChildNodes() && !node.isExpanded()){
18943 node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
18947 queueExpand : function(node){
18948 this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
18951 cancelExpand : function(){
18952 if(this.expandProcId){
18953 clearTimeout(this.expandProcId);
18954 this.expandProcId = false;
18958 isValidDropPoint : function(n, pt, dd, e, data){
18959 if(!n || !data){ return false; }
18960 var targetNode = n.node;
18961 var dropNode = data.node;
18962 // default drop rules
18963 if(!(targetNode && targetNode.isTarget && pt)){
18966 if(pt == "append" && targetNode.allowChildren === false){
18969 if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
18972 if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
18975 // reuse the object
18976 var overEvent = this.dragOverData;
18977 overEvent.tree = this.tree;
18978 overEvent.target = targetNode;
18979 overEvent.data = data;
18980 overEvent.point = pt;
18981 overEvent.source = dd;
18982 overEvent.rawEvent = e;
18983 overEvent.dropNode = dropNode;
18984 overEvent.cancel = false;
18985 var result = this.tree.fireEvent("nodedragover", overEvent);
18986 return overEvent.cancel === false && result !== false;
18989 getDropPoint : function(e, n, dd)
18993 return tn.allowChildren !== false ? "append" : false; // always append for root
18995 var dragEl = n.ddel;
18996 var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
18997 var y = Roo.lib.Event.getPageY(e);
18998 //var noAppend = tn.allowChildren === false || tn.isLeaf();
19000 // we may drop nodes anywhere, as long as allowChildren has not been set to false..
19001 var noAppend = tn.allowChildren === false;
19002 if(this.appendOnly || tn.parentNode.allowChildren === false){
19003 return noAppend ? false : "append";
19005 var noBelow = false;
19006 if(!this.allowParentInsert){
19007 noBelow = tn.hasChildNodes() && tn.isExpanded();
19009 var q = (b - t) / (noAppend ? 2 : 3);
19010 if(y >= t && y < (t + q)){
19012 }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
19019 onNodeEnter : function(n, dd, e, data)
19021 this.cancelExpand();
19024 onNodeOver : function(n, dd, e, data)
19027 var pt = this.getDropPoint(e, n, dd);
19030 // auto node expand check
19031 if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
19032 this.queueExpand(node);
19033 }else if(pt != "append"){
19034 this.cancelExpand();
19037 // set the insert point style on the target node
19038 var returnCls = this.dropNotAllowed;
19039 if(this.isValidDropPoint(n, pt, dd, e, data)){
19044 returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
19045 cls = "x-tree-drag-insert-above";
19046 }else if(pt == "below"){
19047 returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
19048 cls = "x-tree-drag-insert-below";
19050 returnCls = "x-tree-drop-ok-append";
19051 cls = "x-tree-drag-append";
19053 if(this.lastInsertClass != cls){
19054 Roo.fly(el).replaceClass(this.lastInsertClass, cls);
19055 this.lastInsertClass = cls;
19062 onNodeOut : function(n, dd, e, data){
19064 this.cancelExpand();
19065 this.removeDropIndicators(n);
19068 onNodeDrop : function(n, dd, e, data){
19069 var point = this.getDropPoint(e, n, dd);
19070 var targetNode = n.node;
19071 targetNode.ui.startDrop();
19072 if(!this.isValidDropPoint(n, point, dd, e, data)){
19073 targetNode.ui.endDrop();
19076 // first try to find the drop node
19077 var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
19080 target: targetNode,
19085 dropNode: dropNode,
19088 var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
19089 if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
19090 targetNode.ui.endDrop();
19093 // allow target changing
19094 targetNode = dropEvent.target;
19095 if(point == "append" && !targetNode.isExpanded()){
19096 targetNode.expand(false, null, function(){
19097 this.completeDrop(dropEvent);
19098 }.createDelegate(this));
19100 this.completeDrop(dropEvent);
19105 completeDrop : function(de){
19106 var ns = de.dropNode, p = de.point, t = de.target;
19107 if(!(ns instanceof Array)){
19111 for(var i = 0, len = ns.length; i < len; i++){
19114 t.parentNode.insertBefore(n, t);
19115 }else if(p == "below"){
19116 t.parentNode.insertBefore(n, t.nextSibling);
19122 if(this.tree.hlDrop){
19126 this.tree.fireEvent("nodedrop", de);
19129 afterNodeMoved : function(dd, data, e, targetNode, dropNode){
19130 if(this.tree.hlDrop){
19131 dropNode.ui.focus();
19132 dropNode.ui.highlight();
19134 this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
19137 getTree : function(){
19141 removeDropIndicators : function(n){
19144 Roo.fly(el).removeClass([
19145 "x-tree-drag-insert-above",
19146 "x-tree-drag-insert-below",
19147 "x-tree-drag-append"]);
19148 this.lastInsertClass = "_noclass";
19152 beforeDragDrop : function(target, e, id){
19153 this.cancelExpand();
19157 afterRepair : function(data){
19158 if(data && Roo.enableFx){
19159 data.node.ui.highlight();
19169 * Ext JS Library 1.1.1
19170 * Copyright(c) 2006-2007, Ext JS, LLC.
19172 * Originally Released Under LGPL - original licence link has changed is not relivant.
19175 * <script type="text/javascript">
19179 if(Roo.dd.DragZone){
19180 Roo.tree.TreeDragZone = function(tree, config){
19181 Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
19185 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
19186 ddGroup : "TreeDD",
19188 onBeforeDrag : function(data, e){
19190 return n && n.draggable && !n.disabled;
19194 onInitDrag : function(e){
19195 var data = this.dragData;
19196 this.tree.getSelectionModel().select(data.node);
19197 this.proxy.update("");
19198 data.node.ui.appendDDGhost(this.proxy.ghost.dom);
19199 this.tree.fireEvent("startdrag", this.tree, data.node, e);
19202 getRepairXY : function(e, data){
19203 return data.node.ui.getDDRepairXY();
19206 onEndDrag : function(data, e){
19207 this.tree.fireEvent("enddrag", this.tree, data.node, e);
19208 if (this.scroller !== false) {
19209 Roo.log('clear scroller');
19210 window.clearInterval(this.scroller);
19211 this.scroller =false;
19217 onValidDrop : function(dd, e, id){
19218 this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
19222 beforeInvalidDrop : function(e, id){
19223 // this scrolls the original position back into view
19224 var sm = this.tree.getSelectionModel();
19225 sm.clearSelections();
19226 sm.select(this.dragData.node);
19228 autoScroll: function(x, y, h, w) {
19229 Roo.log("drop zone - autoscroll called");
19231 Roo.log(this.scroll ? "scroll=y": "scroll=m" );
19233 // The client height
19234 var clientH = Roo.lib.Dom.getViewWidth();
19236 // The client width
19237 var clientW = Roo.lib.Dom.getViewHeight();
19239 // The amt scrolled down
19240 var st = this.DDM.getScrollTop();
19242 // The amt scrolled right
19243 var sl = this.DDM.getScrollLeft();
19245 // Location of the bottom of the element
19248 // Location of the right of the element
19251 // The distance from the cursor to the bottom of the visible area,
19252 // adjusted so that we don't scroll if the cursor is beyond the
19253 // element drag constraints
19254 var toBot = (clientH + st - y - this.deltaY);
19256 // The distance from the cursor to the right of the visible area
19257 var toRight = (clientW + sl - x - this.deltaX);
19260 // How close to the edge the cursor must be before we scroll
19261 // var thresh = (document.all) ? 100 : 40;
19264 // How many pixels to scroll per autoscroll op. This helps to reduce
19265 // clunky scrolling. IE is more sensitive about this ... it needs this
19266 // value to be higher.
19267 var scrAmt = (document.all) ? 80 : 30;
19269 // Scroll down if we are near the bottom of the visible page and the
19270 // obj extends below the crease
19271 if ( bot > clientH && toBot < thresh ) {
19272 window.scrollTo(sl, st + scrAmt);
19275 // Scroll up if the window is scrolled down and the top of the object
19276 // goes above the top border
19277 if ( y < st && st > 0 && y - st < thresh ) {
19278 window.scrollTo(sl, st - scrAmt);
19281 // Scroll right if the obj is beyond the right border and the cursor is
19282 // near the border.
19283 if ( right > clientW && toRight < thresh ) {
19284 window.scrollTo(sl + scrAmt, st);
19287 // Scroll left if the window has been scrolled to the right and the obj
19288 // extends past the left border
19289 if ( x < sl && sl > 0 && x - sl < thresh ) {
19290 window.scrollTo(sl - scrAmt, st);
19297 * Ext JS Library 1.1.1
19298 * Copyright(c) 2006-2007, Ext JS, LLC.
19300 * Originally Released Under LGPL - original licence link has changed is not relivant.
19303 * <script type="text/javascript">
19306 * @class Roo.tree.TreeEditor
19307 * @extends Roo.Editor
19308 * Provides editor functionality for inline tree node editing. Any valid {@link Roo.form.Field} can be used
19309 * as the editor field.
19311 * @param {Object} config (used to be the tree panel.)
19312 * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
19314 * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
19315 * @cfg {Roo.form.TextField|Object} field The field configuration
19319 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
19322 if (oldconfig) { // old style..
19323 field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
19326 tree = config.tree;
19327 config.field = config.field || {};
19328 config.field.xtype = 'TextField';
19329 field = Roo.factory(config.field, Roo.form);
19331 config = config || {};
19336 * @event beforenodeedit
19337 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
19338 * false from the handler of this event.
19339 * @param {Editor} this
19340 * @param {Roo.tree.Node} node
19342 "beforenodeedit" : true
19346 Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
19350 tree.on('beforeclick', this.beforeNodeClick, this);
19351 tree.getTreeEl().on('mousedown', this.hide, this);
19352 this.on('complete', this.updateNode, this);
19353 this.on('beforestartedit', this.fitToTree, this);
19354 this.on('startedit', this.bindScroll, this, {delay:10});
19355 this.on('specialkey', this.onSpecialKey, this);
19358 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
19360 * @cfg {String} alignment
19361 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
19367 * @cfg {Boolean} hideEl
19368 * True to hide the bound element while the editor is displayed (defaults to false)
19372 * @cfg {String} cls
19373 * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
19375 cls: "x-small-editor x-tree-editor",
19377 * @cfg {Boolean} shim
19378 * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
19384 * @cfg {Number} maxWidth
19385 * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed
19386 * the containing tree element's size, it will be automatically limited for you to the container width, taking
19387 * scroll and client offsets into account prior to each edit.
19394 fitToTree : function(ed, el){
19395 var td = this.tree.getTreeEl().dom, nd = el.dom;
19396 if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible
19397 td.scrollLeft = nd.offsetLeft;
19401 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
19402 this.setSize(w, '');
19404 return this.fireEvent('beforenodeedit', this, this.editNode);
19409 triggerEdit : function(node){
19410 this.completeEdit();
19411 this.editNode = node;
19412 this.startEdit(node.ui.textNode, node.text);
19416 bindScroll : function(){
19417 this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
19421 beforeNodeClick : function(node, e){
19422 var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
19423 this.lastClick = new Date();
19424 if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
19426 this.triggerEdit(node);
19433 updateNode : function(ed, value){
19434 this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
19435 this.editNode.setText(value);
19439 onHide : function(){
19440 Roo.tree.TreeEditor.superclass.onHide.call(this);
19442 this.editNode.ui.focus();
19447 onSpecialKey : function(field, e){
19448 var k = e.getKey();
19452 }else if(k == e.ENTER && !e.hasModifier()){
19454 this.completeEdit();
19457 });//<Script type="text/javascript">
19460 * Ext JS Library 1.1.1
19461 * Copyright(c) 2006-2007, Ext JS, LLC.
19463 * Originally Released Under LGPL - original licence link has changed is not relivant.
19466 * <script type="text/javascript">
19470 * Not documented??? - probably should be...
19473 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
19474 //focus: Roo.emptyFn, // prevent odd scrolling behavior
19476 renderElements : function(n, a, targetNode, bulkRender){
19477 //consel.log("renderElements?");
19478 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
19480 var t = n.getOwnerTree();
19481 var tid = Pman.Tab.Document_TypesTree.tree.el.id;
19483 var cols = t.columns;
19484 var bw = t.borderWidth;
19486 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
19487 var cb = typeof a.checked == "boolean";
19488 var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
19489 var colcls = 'x-t-' + tid + '-c0';
19491 '<li class="x-tree-node">',
19494 '<div class="x-tree-node-el ', a.cls,'">',
19496 '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
19499 '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
19500 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon " />',
19501 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
19502 (a.icon ? ' x-tree-node-inline-icon' : ''),
19503 (a.iconCls ? ' '+a.iconCls : ''),
19504 '" unselectable="on" />',
19505 (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' +
19506 (a.checked ? 'checked="checked" />' : ' />')) : ''),
19508 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
19509 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
19510 '<span unselectable="on" qtip="' + tx + '">',
19514 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
19515 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
19517 for(var i = 1, len = cols.length; i < len; i++){
19519 colcls = 'x-t-' + tid + '-c' +i;
19520 tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
19521 buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
19522 '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
19528 '<div class="x-clear"></div></div>',
19529 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
19532 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
19533 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
19534 n.nextSibling.ui.getEl(), buf.join(""));
19536 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
19538 var el = this.wrap.firstChild;
19540 this.elNode = el.firstChild;
19541 this.ranchor = el.childNodes[1];
19542 this.ctNode = this.wrap.childNodes[1];
19543 var cs = el.firstChild.childNodes;
19544 this.indentNode = cs[0];
19545 this.ecNode = cs[1];
19546 this.iconNode = cs[2];
19549 this.checkbox = cs[3];
19552 this.anchor = cs[index];
19554 this.textNode = cs[index].firstChild;
19556 //el.on("click", this.onClick, this);
19557 //el.on("dblclick", this.onDblClick, this);
19560 // console.log(this);
19562 initEvents : function(){
19563 Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
19566 var a = this.ranchor;
19568 var el = Roo.get(a);
19570 if(Roo.isOpera){ // opera render bug ignores the CSS
19571 el.setStyle("text-decoration", "none");
19574 el.on("click", this.onClick, this);
19575 el.on("dblclick", this.onDblClick, this);
19576 el.on("contextmenu", this.onContextMenu, this);
19580 /*onSelectedChange : function(state){
19583 this.addClass("x-tree-selected");
19586 this.removeClass("x-tree-selected");
19589 addClass : function(cls){
19591 Roo.fly(this.elRow).addClass(cls);
19597 removeClass : function(cls){
19599 Roo.fly(this.elRow).removeClass(cls);
19605 });//<Script type="text/javascript">
19609 * Ext JS Library 1.1.1
19610 * Copyright(c) 2006-2007, Ext JS, LLC.
19612 * Originally Released Under LGPL - original licence link has changed is not relivant.
19615 * <script type="text/javascript">
19620 * @class Roo.tree.ColumnTree
19621 * @extends Roo.data.TreePanel
19622 * @cfg {Object} columns Including width, header, renderer, cls, dataIndex
19623 * @cfg {int} borderWidth compined right/left border allowance
19625 * @param {String/HTMLElement/Element} el The container element
19626 * @param {Object} config
19628 Roo.tree.ColumnTree = function(el, config)
19630 Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
19634 * Fire this event on a container when it resizes
19635 * @param {int} w Width
19636 * @param {int} h Height
19640 this.on('resize', this.onResize, this);
19643 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
19647 borderWidth: Roo.isBorderBox ? 0 : 2,
19650 render : function(){
19651 // add the header.....
19653 Roo.tree.ColumnTree.superclass.render.apply(this);
19655 this.el.addClass('x-column-tree');
19657 this.headers = this.el.createChild(
19658 {cls:'x-tree-headers'},this.innerCt.dom);
19660 var cols = this.columns, c;
19661 var totalWidth = 0;
19663 var len = cols.length;
19664 for(var i = 0; i < len; i++){
19666 totalWidth += c.width;
19667 this.headEls.push(this.headers.createChild({
19668 cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
19670 cls:'x-tree-hd-text',
19673 style:'width:'+(c.width-this.borderWidth)+'px;'
19676 this.headers.createChild({cls:'x-clear'});
19677 // prevent floats from wrapping when clipped
19678 this.headers.setWidth(totalWidth);
19679 //this.innerCt.setWidth(totalWidth);
19680 this.innerCt.setStyle({ overflow: 'auto' });
19681 this.onResize(this.width, this.height);
19685 onResize : function(w,h)
19690 this.innerCt.setWidth(this.width);
19691 this.innerCt.setHeight(this.height-20);
19694 var cols = this.columns, c;
19695 var totalWidth = 0;
19697 var len = cols.length;
19698 for(var i = 0; i < len; i++){
19700 if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
19701 // it's the expander..
19702 expEl = this.headEls[i];
19705 totalWidth += c.width;
19709 expEl.setWidth( ((w - totalWidth)-this.borderWidth - 20));
19711 this.headers.setWidth(w-20);
19720 * Ext JS Library 1.1.1
19721 * Copyright(c) 2006-2007, Ext JS, LLC.
19723 * Originally Released Under LGPL - original licence link has changed is not relivant.
19726 * <script type="text/javascript">
19730 * @class Roo.menu.Menu
19731 * @extends Roo.util.Observable
19732 * A menu object. This is the container to which you add all other menu items. Menu can also serve a as a base class
19733 * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
19735 * Creates a new Menu
19736 * @param {Object} config Configuration options
19738 Roo.menu.Menu = function(config){
19739 Roo.apply(this, config);
19740 this.id = this.id || Roo.id();
19743 * @event beforeshow
19744 * Fires before this menu is displayed
19745 * @param {Roo.menu.Menu} this
19749 * @event beforehide
19750 * Fires before this menu is hidden
19751 * @param {Roo.menu.Menu} this
19756 * Fires after this menu is displayed
19757 * @param {Roo.menu.Menu} this
19762 * Fires after this menu is hidden
19763 * @param {Roo.menu.Menu} this
19768 * Fires when this menu is clicked (or when the enter key is pressed while it is active)
19769 * @param {Roo.menu.Menu} this
19770 * @param {Roo.menu.Item} menuItem The menu item that was clicked
19771 * @param {Roo.EventObject} e
19776 * Fires when the mouse is hovering over this menu
19777 * @param {Roo.menu.Menu} this
19778 * @param {Roo.EventObject} e
19779 * @param {Roo.menu.Item} menuItem The menu item that was clicked
19784 * Fires when the mouse exits this menu
19785 * @param {Roo.menu.Menu} this
19786 * @param {Roo.EventObject} e
19787 * @param {Roo.menu.Item} menuItem The menu item that was clicked
19792 * Fires when a menu item contained in this menu is clicked
19793 * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
19794 * @param {Roo.EventObject} e
19798 if (this.registerMenu) {
19799 Roo.menu.MenuMgr.register(this);
19802 var mis = this.items;
19803 this.items = new Roo.util.MixedCollection();
19805 this.add.apply(this, mis);
19809 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
19811 * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
19815 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
19816 * for bottom-right shadow (defaults to "sides")
19820 * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
19821 * this menu (defaults to "tl-tr?")
19823 subMenuAlign : "tl-tr?",
19825 * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
19826 * relative to its element of origin (defaults to "tl-bl?")
19828 defaultAlign : "tl-bl?",
19830 * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
19832 allowOtherMenus : false,
19834 * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
19836 registerMenu : true,
19841 render : function(){
19845 var el = this.el = new Roo.Layer({
19847 shadow:this.shadow,
19849 parentEl: this.parentEl || document.body,
19853 this.keyNav = new Roo.menu.MenuNav(this);
19856 el.addClass("x-menu-plain");
19859 el.addClass(this.cls);
19861 // generic focus element
19862 this.focusEl = el.createChild({
19863 tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
19865 var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
19866 ul.on("click", this.onClick, this);
19867 ul.on("mouseover", this.onMouseOver, this);
19868 ul.on("mouseout", this.onMouseOut, this);
19869 this.items.each(function(item){
19870 var li = document.createElement("li");
19871 li.className = "x-menu-list-item";
19872 ul.dom.appendChild(li);
19873 item.render(li, this);
19880 autoWidth : function(){
19881 var el = this.el, ul = this.ul;
19885 var w = this.width;
19888 }else if(Roo.isIE){
19889 el.setWidth(this.minWidth);
19890 var t = el.dom.offsetWidth; // force recalc
19891 el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
19896 delayAutoWidth : function(){
19899 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
19901 this.awTask.delay(20);
19906 findTargetItem : function(e){
19907 var t = e.getTarget(".x-menu-list-item", this.ul, true);
19908 if(t && t.menuItemId){
19909 return this.items.get(t.menuItemId);
19914 onClick : function(e){
19916 if(t = this.findTargetItem(e)){
19918 this.fireEvent("click", this, t, e);
19923 setActiveItem : function(item, autoExpand){
19924 if(item != this.activeItem){
19925 if(this.activeItem){
19926 this.activeItem.deactivate();
19928 this.activeItem = item;
19929 item.activate(autoExpand);
19930 }else if(autoExpand){
19936 tryActivate : function(start, step){
19937 var items = this.items;
19938 for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
19939 var item = items.get(i);
19940 if(!item.disabled && item.canActivate){
19941 this.setActiveItem(item, false);
19949 onMouseOver : function(e){
19951 if(t = this.findTargetItem(e)){
19952 if(t.canActivate && !t.disabled){
19953 this.setActiveItem(t, true);
19956 this.fireEvent("mouseover", this, e, t);
19960 onMouseOut : function(e){
19962 if(t = this.findTargetItem(e)){
19963 if(t == this.activeItem && t.shouldDeactivate(e)){
19964 this.activeItem.deactivate();
19965 delete this.activeItem;
19968 this.fireEvent("mouseout", this, e, t);
19972 * Read-only. Returns true if the menu is currently displayed, else false.
19975 isVisible : function(){
19976 return this.el && !this.hidden;
19980 * Displays this menu relative to another element
19981 * @param {String/HTMLElement/Roo.Element} element The element to align to
19982 * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
19983 * the element (defaults to this.defaultAlign)
19984 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
19986 show : function(el, pos, parentMenu){
19987 this.parentMenu = parentMenu;
19991 this.fireEvent("beforeshow", this);
19992 this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
19996 * Displays this menu at a specific xy position
19997 * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
19998 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
20000 showAt : function(xy, parentMenu, /* private: */_e){
20001 this.parentMenu = parentMenu;
20006 this.fireEvent("beforeshow", this);
20007 xy = this.el.adjustForConstraints(xy);
20011 this.hidden = false;
20013 this.fireEvent("show", this);
20016 focus : function(){
20018 this.doFocus.defer(50, this);
20022 doFocus : function(){
20024 this.focusEl.focus();
20029 * Hides this menu and optionally all parent menus
20030 * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
20032 hide : function(deep){
20033 if(this.el && this.isVisible()){
20034 this.fireEvent("beforehide", this);
20035 if(this.activeItem){
20036 this.activeItem.deactivate();
20037 this.activeItem = null;
20040 this.hidden = true;
20041 this.fireEvent("hide", this);
20043 if(deep === true && this.parentMenu){
20044 this.parentMenu.hide(true);
20049 * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
20050 * Any of the following are valid:
20052 * <li>Any menu item object based on {@link Roo.menu.Item}</li>
20053 * <li>An HTMLElement object which will be converted to a menu item</li>
20054 * <li>A menu item config object that will be created as a new menu item</li>
20055 * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
20056 * it will be converted into a {@link Roo.menu.TextItem} and added</li>
20061 var menu = new Roo.menu.Menu();
20063 // Create a menu item to add by reference
20064 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
20066 // Add a bunch of items at once using different methods.
20067 // Only the last item added will be returned.
20068 var item = menu.add(
20069 menuItem, // add existing item by ref
20070 'Dynamic Item', // new TextItem
20071 '-', // new separator
20072 { text: 'Config Item' } // new item by config
20075 * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
20076 * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
20079 var a = arguments, l = a.length, item;
20080 for(var i = 0; i < l; i++){
20082 if ((typeof(el) == "object") && el.xtype && el.xns) {
20083 el = Roo.factory(el, Roo.menu);
20086 if(el.render){ // some kind of Item
20087 item = this.addItem(el);
20088 }else if(typeof el == "string"){ // string
20089 if(el == "separator" || el == "-"){
20090 item = this.addSeparator();
20092 item = this.addText(el);
20094 }else if(el.tagName || el.el){ // element
20095 item = this.addElement(el);
20096 }else if(typeof el == "object"){ // must be menu item config?
20097 item = this.addMenuItem(el);
20104 * Returns this menu's underlying {@link Roo.Element} object
20105 * @return {Roo.Element} The element
20107 getEl : function(){
20115 * Adds a separator bar to the menu
20116 * @return {Roo.menu.Item} The menu item that was added
20118 addSeparator : function(){
20119 return this.addItem(new Roo.menu.Separator());
20123 * Adds an {@link Roo.Element} object to the menu
20124 * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
20125 * @return {Roo.menu.Item} The menu item that was added
20127 addElement : function(el){
20128 return this.addItem(new Roo.menu.BaseItem(el));
20132 * Adds an existing object based on {@link Roo.menu.Item} to the menu
20133 * @param {Roo.menu.Item} item The menu item to add
20134 * @return {Roo.menu.Item} The menu item that was added
20136 addItem : function(item){
20137 this.items.add(item);
20139 var li = document.createElement("li");
20140 li.className = "x-menu-list-item";
20141 this.ul.dom.appendChild(li);
20142 item.render(li, this);
20143 this.delayAutoWidth();
20149 * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
20150 * @param {Object} config A MenuItem config object
20151 * @return {Roo.menu.Item} The menu item that was added
20153 addMenuItem : function(config){
20154 if(!(config instanceof Roo.menu.Item)){
20155 if(typeof config.checked == "boolean"){ // must be check menu item config?
20156 config = new Roo.menu.CheckItem(config);
20158 config = new Roo.menu.Item(config);
20161 return this.addItem(config);
20165 * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
20166 * @param {String} text The text to display in the menu item
20167 * @return {Roo.menu.Item} The menu item that was added
20169 addText : function(text){
20170 return this.addItem(new Roo.menu.TextItem({ text : text }));
20174 * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
20175 * @param {Number} index The index in the menu's list of current items where the new item should be inserted
20176 * @param {Roo.menu.Item} item The menu item to add
20177 * @return {Roo.menu.Item} The menu item that was added
20179 insert : function(index, item){
20180 this.items.insert(index, item);
20182 var li = document.createElement("li");
20183 li.className = "x-menu-list-item";
20184 this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
20185 item.render(li, this);
20186 this.delayAutoWidth();
20192 * Removes an {@link Roo.menu.Item} from the menu and destroys the object
20193 * @param {Roo.menu.Item} item The menu item to remove
20195 remove : function(item){
20196 this.items.removeKey(item.id);
20201 * Removes and destroys all items in the menu
20203 removeAll : function(){
20205 while(f = this.items.first()){
20211 // MenuNav is a private utility class used internally by the Menu
20212 Roo.menu.MenuNav = function(menu){
20213 Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
20214 this.scope = this.menu = menu;
20217 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
20218 doRelay : function(e, h){
20219 var k = e.getKey();
20220 if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
20221 this.menu.tryActivate(0, 1);
20224 return h.call(this.scope || this, e, this.menu);
20227 up : function(e, m){
20228 if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
20229 m.tryActivate(m.items.length-1, -1);
20233 down : function(e, m){
20234 if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
20235 m.tryActivate(0, 1);
20239 right : function(e, m){
20241 m.activeItem.expandMenu(true);
20245 left : function(e, m){
20247 if(m.parentMenu && m.parentMenu.activeItem){
20248 m.parentMenu.activeItem.activate();
20252 enter : function(e, m){
20254 e.stopPropagation();
20255 m.activeItem.onClick(e);
20256 m.fireEvent("click", this, m.activeItem);
20262 * Ext JS Library 1.1.1
20263 * Copyright(c) 2006-2007, Ext JS, LLC.
20265 * Originally Released Under LGPL - original licence link has changed is not relivant.
20268 * <script type="text/javascript">
20272 * @class Roo.menu.MenuMgr
20273 * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
20276 Roo.menu.MenuMgr = function(){
20277 var menus, active, groups = {}, attached = false, lastShow = new Date();
20279 // private - called when first menu is created
20282 active = new Roo.util.MixedCollection();
20283 Roo.get(document).addKeyListener(27, function(){
20284 if(active.length > 0){
20291 function hideAll(){
20292 if(active && active.length > 0){
20293 var c = active.clone();
20294 c.each(function(m){
20301 function onHide(m){
20303 if(active.length < 1){
20304 Roo.get(document).un("mousedown", onMouseDown);
20310 function onShow(m){
20311 var last = active.last();
20312 lastShow = new Date();
20315 Roo.get(document).on("mousedown", onMouseDown);
20319 m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
20320 m.parentMenu.activeChild = m;
20321 }else if(last && last.isVisible()){
20322 m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
20327 function onBeforeHide(m){
20329 m.activeChild.hide();
20331 if(m.autoHideTimer){
20332 clearTimeout(m.autoHideTimer);
20333 delete m.autoHideTimer;
20338 function onBeforeShow(m){
20339 var pm = m.parentMenu;
20340 if(!pm && !m.allowOtherMenus){
20342 }else if(pm && pm.activeChild && active != m){
20343 pm.activeChild.hide();
20348 function onMouseDown(e){
20349 if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
20355 function onBeforeCheck(mi, state){
20357 var g = groups[mi.group];
20358 for(var i = 0, l = g.length; i < l; i++){
20360 g[i].setChecked(false);
20369 * Hides all menus that are currently visible
20371 hideAll : function(){
20376 register : function(menu){
20380 menus[menu.id] = menu;
20381 menu.on("beforehide", onBeforeHide);
20382 menu.on("hide", onHide);
20383 menu.on("beforeshow", onBeforeShow);
20384 menu.on("show", onShow);
20385 var g = menu.group;
20386 if(g && menu.events["checkchange"]){
20390 groups[g].push(menu);
20391 menu.on("checkchange", onCheck);
20396 * Returns a {@link Roo.menu.Menu} object
20397 * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
20398 * be used to generate and return a new Menu instance.
20400 get : function(menu){
20401 if(typeof menu == "string"){ // menu id
20402 return menus[menu];
20403 }else if(menu.events){ // menu instance
20405 }else if(typeof menu.length == 'number'){ // array of menu items?
20406 return new Roo.menu.Menu({items:menu});
20407 }else{ // otherwise, must be a config
20408 return new Roo.menu.Menu(menu);
20413 unregister : function(menu){
20414 delete menus[menu.id];
20415 menu.un("beforehide", onBeforeHide);
20416 menu.un("hide", onHide);
20417 menu.un("beforeshow", onBeforeShow);
20418 menu.un("show", onShow);
20419 var g = menu.group;
20420 if(g && menu.events["checkchange"]){
20421 groups[g].remove(menu);
20422 menu.un("checkchange", onCheck);
20427 registerCheckable : function(menuItem){
20428 var g = menuItem.group;
20433 groups[g].push(menuItem);
20434 menuItem.on("beforecheckchange", onBeforeCheck);
20439 unregisterCheckable : function(menuItem){
20440 var g = menuItem.group;
20442 groups[g].remove(menuItem);
20443 menuItem.un("beforecheckchange", onBeforeCheck);
20449 * Ext JS Library 1.1.1
20450 * Copyright(c) 2006-2007, Ext JS, LLC.
20452 * Originally Released Under LGPL - original licence link has changed is not relivant.
20455 * <script type="text/javascript">
20460 * @class Roo.menu.BaseItem
20461 * @extends Roo.Component
20462 * The base class for all items that render into menus. BaseItem provides default rendering, activated state
20463 * management and base configuration options shared by all menu components.
20465 * Creates a new BaseItem
20466 * @param {Object} config Configuration options
20468 Roo.menu.BaseItem = function(config){
20469 Roo.menu.BaseItem.superclass.constructor.call(this, config);
20474 * Fires when this item is clicked
20475 * @param {Roo.menu.BaseItem} this
20476 * @param {Roo.EventObject} e
20481 * Fires when this item is activated
20482 * @param {Roo.menu.BaseItem} this
20486 * @event deactivate
20487 * Fires when this item is deactivated
20488 * @param {Roo.menu.BaseItem} this
20494 this.on("click", this.handler, this.scope, true);
20498 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
20500 * @cfg {Function} handler
20501 * A function that will handle the click event of this menu item (defaults to undefined)
20504 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
20506 canActivate : false,
20508 * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
20510 activeClass : "x-menu-item-active",
20512 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
20514 hideOnClick : true,
20516 * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
20521 ctype: "Roo.menu.BaseItem",
20524 actionMode : "container",
20527 render : function(container, parentMenu){
20528 this.parentMenu = parentMenu;
20529 Roo.menu.BaseItem.superclass.render.call(this, container);
20530 this.container.menuItemId = this.id;
20534 onRender : function(container, position){
20535 this.el = Roo.get(this.el);
20536 container.dom.appendChild(this.el.dom);
20540 onClick : function(e){
20541 if(!this.disabled && this.fireEvent("click", this, e) !== false
20542 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
20543 this.handleClick(e);
20550 activate : function(){
20554 var li = this.container;
20555 li.addClass(this.activeClass);
20556 this.region = li.getRegion().adjust(2, 2, -2, -2);
20557 this.fireEvent("activate", this);
20562 deactivate : function(){
20563 this.container.removeClass(this.activeClass);
20564 this.fireEvent("deactivate", this);
20568 shouldDeactivate : function(e){
20569 return !this.region || !this.region.contains(e.getPoint());
20573 handleClick : function(e){
20574 if(this.hideOnClick){
20575 this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
20580 expandMenu : function(autoActivate){
20585 hideMenu : function(){
20590 * Ext JS Library 1.1.1
20591 * Copyright(c) 2006-2007, Ext JS, LLC.
20593 * Originally Released Under LGPL - original licence link has changed is not relivant.
20596 * <script type="text/javascript">
20600 * @class Roo.menu.Adapter
20601 * @extends Roo.menu.BaseItem
20602 * A base utility class that adapts a non-menu component so that it can be wrapped by a menu item and added to a menu.
20603 * It provides basic rendering, activation management and enable/disable logic required to work in menus.
20605 * Creates a new Adapter
20606 * @param {Object} config Configuration options
20608 Roo.menu.Adapter = function(component, config){
20609 Roo.menu.Adapter.superclass.constructor.call(this, config);
20610 this.component = component;
20612 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
20614 canActivate : true,
20617 onRender : function(container, position){
20618 this.component.render(container);
20619 this.el = this.component.getEl();
20623 activate : function(){
20627 this.component.focus();
20628 this.fireEvent("activate", this);
20633 deactivate : function(){
20634 this.fireEvent("deactivate", this);
20638 disable : function(){
20639 this.component.disable();
20640 Roo.menu.Adapter.superclass.disable.call(this);
20644 enable : function(){
20645 this.component.enable();
20646 Roo.menu.Adapter.superclass.enable.call(this);
20650 * Ext JS Library 1.1.1
20651 * Copyright(c) 2006-2007, Ext JS, LLC.
20653 * Originally Released Under LGPL - original licence link has changed is not relivant.
20656 * <script type="text/javascript">
20660 * @class Roo.menu.TextItem
20661 * @extends Roo.menu.BaseItem
20662 * Adds a static text string to a menu, usually used as either a heading or group separator.
20663 * Note: old style constructor with text is still supported.
20666 * Creates a new TextItem
20667 * @param {Object} cfg Configuration
20669 Roo.menu.TextItem = function(cfg){
20670 if (typeof(cfg) == 'string') {
20673 Roo.apply(this,cfg);
20676 Roo.menu.TextItem.superclass.constructor.call(this);
20679 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
20681 * @cfg {Boolean} text Text to show on item.
20686 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
20688 hideOnClick : false,
20690 * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
20692 itemCls : "x-menu-text",
20695 onRender : function(){
20696 var s = document.createElement("span");
20697 s.className = this.itemCls;
20698 s.innerHTML = this.text;
20700 Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
20704 * Ext JS Library 1.1.1
20705 * Copyright(c) 2006-2007, Ext JS, LLC.
20707 * Originally Released Under LGPL - original licence link has changed is not relivant.
20710 * <script type="text/javascript">
20714 * @class Roo.menu.Separator
20715 * @extends Roo.menu.BaseItem
20716 * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
20717 * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
20719 * @param {Object} config Configuration options
20721 Roo.menu.Separator = function(config){
20722 Roo.menu.Separator.superclass.constructor.call(this, config);
20725 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
20727 * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
20729 itemCls : "x-menu-sep",
20731 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
20733 hideOnClick : false,
20736 onRender : function(li){
20737 var s = document.createElement("span");
20738 s.className = this.itemCls;
20739 s.innerHTML = " ";
20741 li.addClass("x-menu-sep-li");
20742 Roo.menu.Separator.superclass.onRender.apply(this, arguments);
20746 * Ext JS Library 1.1.1
20747 * Copyright(c) 2006-2007, Ext JS, LLC.
20749 * Originally Released Under LGPL - original licence link has changed is not relivant.
20752 * <script type="text/javascript">
20755 * @class Roo.menu.Item
20756 * @extends Roo.menu.BaseItem
20757 * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
20758 * display items. Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
20759 * activation and click handling.
20761 * Creates a new Item
20762 * @param {Object} config Configuration options
20764 Roo.menu.Item = function(config){
20765 Roo.menu.Item.superclass.constructor.call(this, config);
20767 this.menu = Roo.menu.MenuMgr.get(this.menu);
20770 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
20773 * @cfg {String} text
20774 * The text to show on the menu item.
20778 * @cfg {String} HTML to render in menu
20779 * The text to show on the menu item (HTML version).
20783 * @cfg {String} icon
20784 * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
20788 * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
20790 itemCls : "x-menu-item",
20792 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
20794 canActivate : true,
20796 * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
20799 // doc'd in BaseItem
20803 ctype: "Roo.menu.Item",
20806 onRender : function(container, position){
20807 var el = document.createElement("a");
20808 el.hideFocus = true;
20809 el.unselectable = "on";
20810 el.href = this.href || "#";
20811 if(this.hrefTarget){
20812 el.target = this.hrefTarget;
20814 el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : "");
20816 var html = this.html.length ? this.html : String.format('{0}',this.text);
20818 el.innerHTML = String.format(
20819 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
20820 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
20822 Roo.menu.Item.superclass.onRender.call(this, container, position);
20826 * Sets the text to display in this menu item
20827 * @param {String} text The text to display
20828 * @param {Boolean} isHTML true to indicate text is pure html.
20830 setText : function(text, isHTML){
20838 var html = this.html.length ? this.html : String.format('{0}',this.text);
20840 this.el.update(String.format(
20841 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
20842 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
20843 this.parentMenu.autoWidth();
20848 handleClick : function(e){
20849 if(!this.href){ // if no link defined, stop the event automatically
20852 Roo.menu.Item.superclass.handleClick.apply(this, arguments);
20856 activate : function(autoExpand){
20857 if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
20867 shouldDeactivate : function(e){
20868 if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
20869 if(this.menu && this.menu.isVisible()){
20870 return !this.menu.getEl().getRegion().contains(e.getPoint());
20878 deactivate : function(){
20879 Roo.menu.Item.superclass.deactivate.apply(this, arguments);
20884 expandMenu : function(autoActivate){
20885 if(!this.disabled && this.menu){
20886 clearTimeout(this.hideTimer);
20887 delete this.hideTimer;
20888 if(!this.menu.isVisible() && !this.showTimer){
20889 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
20890 }else if (this.menu.isVisible() && autoActivate){
20891 this.menu.tryActivate(0, 1);
20897 deferExpand : function(autoActivate){
20898 delete this.showTimer;
20899 this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
20901 this.menu.tryActivate(0, 1);
20906 hideMenu : function(){
20907 clearTimeout(this.showTimer);
20908 delete this.showTimer;
20909 if(!this.hideTimer && this.menu && this.menu.isVisible()){
20910 this.hideTimer = this.deferHide.defer(this.hideDelay, this);
20915 deferHide : function(){
20916 delete this.hideTimer;
20921 * Ext JS Library 1.1.1
20922 * Copyright(c) 2006-2007, Ext JS, LLC.
20924 * Originally Released Under LGPL - original licence link has changed is not relivant.
20927 * <script type="text/javascript">
20931 * @class Roo.menu.CheckItem
20932 * @extends Roo.menu.Item
20933 * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
20935 * Creates a new CheckItem
20936 * @param {Object} config Configuration options
20938 Roo.menu.CheckItem = function(config){
20939 Roo.menu.CheckItem.superclass.constructor.call(this, config);
20942 * @event beforecheckchange
20943 * Fires before the checked value is set, providing an opportunity to cancel if needed
20944 * @param {Roo.menu.CheckItem} this
20945 * @param {Boolean} checked The new checked value that will be set
20947 "beforecheckchange" : true,
20949 * @event checkchange
20950 * Fires after the checked value has been set
20951 * @param {Roo.menu.CheckItem} this
20952 * @param {Boolean} checked The checked value that was set
20954 "checkchange" : true
20956 if(this.checkHandler){
20957 this.on('checkchange', this.checkHandler, this.scope);
20960 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
20962 * @cfg {String} group
20963 * All check items with the same group name will automatically be grouped into a single-select
20964 * radio button group (defaults to '')
20967 * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
20969 itemCls : "x-menu-item x-menu-check-item",
20971 * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
20973 groupClass : "x-menu-group-item",
20976 * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false). Note that
20977 * if this checkbox is part of a radio group (group = true) only the last item in the group that is
20978 * initialized with checked = true will be rendered as checked.
20983 ctype: "Roo.menu.CheckItem",
20986 onRender : function(c){
20987 Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
20989 this.el.addClass(this.groupClass);
20991 Roo.menu.MenuMgr.registerCheckable(this);
20993 this.checked = false;
20994 this.setChecked(true, true);
20999 destroy : function(){
21001 Roo.menu.MenuMgr.unregisterCheckable(this);
21003 Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
21007 * Set the checked state of this item
21008 * @param {Boolean} checked The new checked value
21009 * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
21011 setChecked : function(state, suppressEvent){
21012 if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
21013 if(this.container){
21014 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
21016 this.checked = state;
21017 if(suppressEvent !== true){
21018 this.fireEvent("checkchange", this, state);
21024 handleClick : function(e){
21025 if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
21026 this.setChecked(!this.checked);
21028 Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
21032 * Ext JS Library 1.1.1
21033 * Copyright(c) 2006-2007, Ext JS, LLC.
21035 * Originally Released Under LGPL - original licence link has changed is not relivant.
21038 * <script type="text/javascript">
21042 * @class Roo.menu.DateItem
21043 * @extends Roo.menu.Adapter
21044 * A menu item that wraps the {@link Roo.DatPicker} component.
21046 * Creates a new DateItem
21047 * @param {Object} config Configuration options
21049 Roo.menu.DateItem = function(config){
21050 Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
21051 /** The Roo.DatePicker object @type Roo.DatePicker */
21052 this.picker = this.component;
21053 this.addEvents({select: true});
21055 this.picker.on("render", function(picker){
21056 picker.getEl().swallowEvent("click");
21057 picker.container.addClass("x-menu-date-item");
21060 this.picker.on("select", this.onSelect, this);
21063 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
21065 onSelect : function(picker, date){
21066 this.fireEvent("select", this, date, picker);
21067 Roo.menu.DateItem.superclass.handleClick.call(this);
21071 * Ext JS Library 1.1.1
21072 * Copyright(c) 2006-2007, Ext JS, LLC.
21074 * Originally Released Under LGPL - original licence link has changed is not relivant.
21077 * <script type="text/javascript">
21081 * @class Roo.menu.ColorItem
21082 * @extends Roo.menu.Adapter
21083 * A menu item that wraps the {@link Roo.ColorPalette} component.
21085 * Creates a new ColorItem
21086 * @param {Object} config Configuration options
21088 Roo.menu.ColorItem = function(config){
21089 Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
21090 /** The Roo.ColorPalette object @type Roo.ColorPalette */
21091 this.palette = this.component;
21092 this.relayEvents(this.palette, ["select"]);
21093 if(this.selectHandler){
21094 this.on('select', this.selectHandler, this.scope);
21097 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
21099 * Ext JS Library 1.1.1
21100 * Copyright(c) 2006-2007, Ext JS, LLC.
21102 * Originally Released Under LGPL - original licence link has changed is not relivant.
21105 * <script type="text/javascript">
21110 * @class Roo.menu.DateMenu
21111 * @extends Roo.menu.Menu
21112 * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
21114 * Creates a new DateMenu
21115 * @param {Object} config Configuration options
21117 Roo.menu.DateMenu = function(config){
21118 Roo.menu.DateMenu.superclass.constructor.call(this, config);
21120 var di = new Roo.menu.DateItem(config);
21123 * The {@link Roo.DatePicker} instance for this DateMenu
21126 this.picker = di.picker;
21129 * @param {DatePicker} picker
21130 * @param {Date} date
21132 this.relayEvents(di, ["select"]);
21134 this.on('beforeshow', function(){
21136 this.picker.hideMonthPicker(true);
21140 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
21144 * Ext JS Library 1.1.1
21145 * Copyright(c) 2006-2007, Ext JS, LLC.
21147 * Originally Released Under LGPL - original licence link has changed is not relivant.
21150 * <script type="text/javascript">
21155 * @class Roo.menu.ColorMenu
21156 * @extends Roo.menu.Menu
21157 * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
21159 * Creates a new ColorMenu
21160 * @param {Object} config Configuration options
21162 Roo.menu.ColorMenu = function(config){
21163 Roo.menu.ColorMenu.superclass.constructor.call(this, config);
21165 var ci = new Roo.menu.ColorItem(config);
21168 * The {@link Roo.ColorPalette} instance for this ColorMenu
21169 * @type ColorPalette
21171 this.palette = ci.palette;
21174 * @param {ColorPalette} palette
21175 * @param {String} color
21177 this.relayEvents(ci, ["select"]);
21179 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
21181 * Ext JS Library 1.1.1
21182 * Copyright(c) 2006-2007, Ext JS, LLC.
21184 * Originally Released Under LGPL - original licence link has changed is not relivant.
21187 * <script type="text/javascript">
21191 * @class Roo.form.Field
21192 * @extends Roo.BoxComponent
21193 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
21195 * Creates a new Field
21196 * @param {Object} config Configuration options
21198 Roo.form.Field = function(config){
21199 Roo.form.Field.superclass.constructor.call(this, config);
21202 Roo.extend(Roo.form.Field, Roo.BoxComponent, {
21204 * @cfg {String} fieldLabel Label to use when rendering a form.
21207 * @cfg {String} qtip Mouse over tip
21211 * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
21213 invalidClass : "x-form-invalid",
21215 * @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided (defaults to "The value in this field is invalid")
21217 invalidText : "The value in this field is invalid",
21219 * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
21221 focusClass : "x-form-focus",
21223 * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
21224 automatic validation (defaults to "keyup").
21226 validationEvent : "keyup",
21228 * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
21230 validateOnBlur : true,
21232 * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
21234 validationDelay : 250,
21236 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
21237 * {tag: "input", type: "text", size: "20", autocomplete: "off"})
21239 defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "off"},
21241 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
21243 fieldClass : "x-form-field",
21245 * @cfg {String} msgTarget The location where error text should display. Should be one of the following values (defaults to 'qtip'):
21248 ----------- ----------------------------------------------------------------------
21249 qtip Display a quick tip when the user hovers over the field
21250 title Display a default browser title attribute popup
21251 under Add a block div beneath the field containing the error text
21252 side Add an error icon to the right of the field with a popup on hover
21253 [element id] Add the error text directly to the innerHTML of the specified element
21256 msgTarget : 'qtip',
21258 * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
21263 * @cfg {Boolean} readOnly True to mark the field as readOnly in HTML (defaults to false) -- Note: this only sets the element's readOnly DOM attribute.
21268 * @cfg {Boolean} disabled True to disable the field (defaults to false).
21273 * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
21275 inputType : undefined,
21278 * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered, not those which are built via applyTo (defaults to undefined).
21280 tabIndex : undefined,
21283 isFormField : true,
21288 * @property {Roo.Element} fieldEl
21289 * Element Containing the rendered Field (with label etc.)
21292 * @cfg {Mixed} value A value to initialize this field with.
21297 * @cfg {String} name The field's HTML name attribute.
21300 * @cfg {String} cls A CSS class to apply to the field's underlying element.
21304 initComponent : function(){
21305 Roo.form.Field.superclass.initComponent.call(this);
21309 * Fires when this field receives input focus.
21310 * @param {Roo.form.Field} this
21315 * Fires when this field loses input focus.
21316 * @param {Roo.form.Field} this
21320 * @event specialkey
21321 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
21322 * {@link Roo.EventObject#getKey} to determine which key was pressed.
21323 * @param {Roo.form.Field} this
21324 * @param {Roo.EventObject} e The event object
21329 * Fires just before the field blurs if the field value has changed.
21330 * @param {Roo.form.Field} this
21331 * @param {Mixed} newValue The new value
21332 * @param {Mixed} oldValue The original value
21337 * Fires after the field has been marked as invalid.
21338 * @param {Roo.form.Field} this
21339 * @param {String} msg The validation message
21344 * Fires after the field has been validated with no errors.
21345 * @param {Roo.form.Field} this
21350 * Fires after the key up
21351 * @param {Roo.form.Field} this
21352 * @param {Roo.EventObject} e The event Object
21359 * Returns the name attribute of the field if available
21360 * @return {String} name The field name
21362 getName: function(){
21363 return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
21367 onRender : function(ct, position){
21368 Roo.form.Field.superclass.onRender.call(this, ct, position);
21370 var cfg = this.getAutoCreate();
21372 cfg.name = this.name || this.id;
21374 if(this.inputType){
21375 cfg.type = this.inputType;
21377 this.el = ct.createChild(cfg, position);
21379 var type = this.el.dom.type;
21381 if(type == 'password'){
21384 this.el.addClass('x-form-'+type);
21387 this.el.dom.readOnly = true;
21389 if(this.tabIndex !== undefined){
21390 this.el.dom.setAttribute('tabIndex', this.tabIndex);
21393 this.el.addClass([this.fieldClass, this.cls]);
21398 * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
21399 * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
21400 * @return {Roo.form.Field} this
21402 applyTo : function(target){
21403 this.allowDomMove = false;
21404 this.el = Roo.get(target);
21405 this.render(this.el.dom.parentNode);
21410 initValue : function(){
21411 if(this.value !== undefined){
21412 this.setValue(this.value);
21413 }else if(this.el.dom.value.length > 0){
21414 this.setValue(this.el.dom.value);
21419 * Returns true if this field has been changed since it was originally loaded and is not disabled.
21421 isDirty : function() {
21422 if(this.disabled) {
21425 return String(this.getValue()) !== String(this.originalValue);
21429 afterRender : function(){
21430 Roo.form.Field.superclass.afterRender.call(this);
21435 fireKey : function(e){
21436 //Roo.log('field ' + e.getKey());
21437 if(e.isNavKeyPress()){
21438 this.fireEvent("specialkey", this, e);
21443 * Resets the current field value to the originally loaded value and clears any validation messages
21445 reset : function(){
21446 this.setValue(this.originalValue);
21447 this.clearInvalid();
21451 initEvents : function(){
21452 // safari killled keypress - so keydown is now used..
21453 this.el.on("keydown" , this.fireKey, this);
21454 this.el.on("focus", this.onFocus, this);
21455 this.el.on("blur", this.onBlur, this);
21456 this.el.relayEvent('keyup', this);
21458 // reference to original value for reset
21459 this.originalValue = this.getValue();
21463 onFocus : function(){
21464 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
21465 this.el.addClass(this.focusClass);
21467 if(!this.hasFocus){
21468 this.hasFocus = true;
21469 this.startValue = this.getValue();
21470 this.fireEvent("focus", this);
21474 beforeBlur : Roo.emptyFn,
21477 onBlur : function(){
21479 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
21480 this.el.removeClass(this.focusClass);
21482 this.hasFocus = false;
21483 if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
21486 var v = this.getValue();
21487 if(String(v) !== String(this.startValue)){
21488 this.fireEvent('change', this, v, this.startValue);
21490 this.fireEvent("blur", this);
21494 * Returns whether or not the field value is currently valid
21495 * @param {Boolean} preventMark True to disable marking the field invalid
21496 * @return {Boolean} True if the value is valid, else false
21498 isValid : function(preventMark){
21502 var restore = this.preventMark;
21503 this.preventMark = preventMark === true;
21504 var v = this.validateValue(this.processValue(this.getRawValue()));
21505 this.preventMark = restore;
21510 * Validates the field value
21511 * @return {Boolean} True if the value is valid, else false
21513 validate : function(){
21514 if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
21515 this.clearInvalid();
21521 processValue : function(value){
21526 // Subclasses should provide the validation implementation by overriding this
21527 validateValue : function(value){
21532 * Mark this field as invalid
21533 * @param {String} msg The validation message
21535 markInvalid : function(msg){
21536 if(!this.rendered || this.preventMark){ // not rendered
21539 this.el.addClass(this.invalidClass);
21540 msg = msg || this.invalidText;
21541 switch(this.msgTarget){
21543 this.el.dom.qtip = msg;
21544 this.el.dom.qclass = 'x-form-invalid-tip';
21545 if(Roo.QuickTips){ // fix for floating editors interacting with DND
21546 Roo.QuickTips.enable();
21550 this.el.dom.title = msg;
21554 var elp = this.el.findParent('.x-form-element', 5, true);
21555 this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
21556 this.errorEl.setWidth(elp.getWidth(true)-20);
21558 this.errorEl.update(msg);
21559 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
21562 if(!this.errorIcon){
21563 var elp = this.el.findParent('.x-form-element', 5, true);
21564 this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
21566 this.alignErrorIcon();
21567 this.errorIcon.dom.qtip = msg;
21568 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
21569 this.errorIcon.show();
21570 this.on('resize', this.alignErrorIcon, this);
21573 var t = Roo.getDom(this.msgTarget);
21575 t.style.display = this.msgDisplay;
21578 this.fireEvent('invalid', this, msg);
21582 alignErrorIcon : function(){
21583 this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
21587 * Clear any invalid styles/messages for this field
21589 clearInvalid : function(){
21590 if(!this.rendered || this.preventMark){ // not rendered
21593 this.el.removeClass(this.invalidClass);
21594 switch(this.msgTarget){
21596 this.el.dom.qtip = '';
21599 this.el.dom.title = '';
21603 Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
21607 if(this.errorIcon){
21608 this.errorIcon.dom.qtip = '';
21609 this.errorIcon.hide();
21610 this.un('resize', this.alignErrorIcon, this);
21614 var t = Roo.getDom(this.msgTarget);
21616 t.style.display = 'none';
21619 this.fireEvent('valid', this);
21623 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
21624 * @return {Mixed} value The field value
21626 getRawValue : function(){
21627 var v = this.el.getValue();
21628 if(v === this.emptyText){
21635 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
21636 * @return {Mixed} value The field value
21638 getValue : function(){
21639 var v = this.el.getValue();
21640 if(v === this.emptyText || v === undefined){
21647 * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
21648 * @param {Mixed} value The value to set
21650 setRawValue : function(v){
21651 return this.el.dom.value = (v === null || v === undefined ? '' : v);
21655 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
21656 * @param {Mixed} value The value to set
21658 setValue : function(v){
21661 this.el.dom.value = (v === null || v === undefined ? '' : v);
21666 adjustSize : function(w, h){
21667 var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
21668 s.width = this.adjustWidth(this.el.dom.tagName, s.width);
21672 adjustWidth : function(tag, w){
21673 tag = tag.toLowerCase();
21674 if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
21675 if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
21676 if(tag == 'input'){
21679 if(tag = 'textarea'){
21682 }else if(Roo.isOpera){
21683 if(tag == 'input'){
21686 if(tag = 'textarea'){
21696 // anything other than normal should be considered experimental
21697 Roo.form.Field.msgFx = {
21699 show: function(msgEl, f){
21700 msgEl.setDisplayed('block');
21703 hide : function(msgEl, f){
21704 msgEl.setDisplayed(false).update('');
21709 show: function(msgEl, f){
21710 msgEl.slideIn('t', {stopFx:true});
21713 hide : function(msgEl, f){
21714 msgEl.slideOut('t', {stopFx:true,useDisplay:true});
21719 show: function(msgEl, f){
21720 msgEl.fixDisplay();
21721 msgEl.alignTo(f.el, 'tl-tr');
21722 msgEl.slideIn('l', {stopFx:true});
21725 hide : function(msgEl, f){
21726 msgEl.slideOut('l', {stopFx:true,useDisplay:true});
21731 * Ext JS Library 1.1.1
21732 * Copyright(c) 2006-2007, Ext JS, LLC.
21734 * Originally Released Under LGPL - original licence link has changed is not relivant.
21737 * <script type="text/javascript">
21742 * @class Roo.form.TextField
21743 * @extends Roo.form.Field
21744 * Basic text field. Can be used as a direct replacement for traditional text inputs, or as the base
21745 * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
21747 * Creates a new TextField
21748 * @param {Object} config Configuration options
21750 Roo.form.TextField = function(config){
21751 Roo.form.TextField.superclass.constructor.call(this, config);
21755 * Fires when the autosize function is triggered. The field may or may not have actually changed size
21756 * according to the default logic, but this event provides a hook for the developer to apply additional
21757 * logic at runtime to resize the field if needed.
21758 * @param {Roo.form.Field} this This text field
21759 * @param {Number} width The new field width
21765 Roo.extend(Roo.form.TextField, Roo.form.Field, {
21767 * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
21771 * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
21775 * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
21779 * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
21783 * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
21787 * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
21789 disableKeyFilter : false,
21791 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
21795 * @cfg {Number} minLength Minimum input field length required (defaults to 0)
21799 * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
21801 maxLength : Number.MAX_VALUE,
21803 * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
21805 minLengthText : "The minimum length for this field is {0}",
21807 * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
21809 maxLengthText : "The maximum length for this field is {0}",
21811 * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
21813 selectOnFocus : false,
21815 * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
21817 blankText : "This field is required",
21819 * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
21820 * If available, this function will be called only after the basic validators all return true, and will be passed the
21821 * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
21825 * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
21826 * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
21827 * current field value. If the test fails, the field will be marked invalid using {@link #regexText}.
21831 * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
21835 * @cfg {String} emptyText The default text to display in an empty field (defaults to null).
21839 * @cfg {String} emptyClass The CSS class to apply to an empty field to style the {@link #emptyText} (defaults to
21840 * 'x-form-empty-field'). This class is automatically added and removed as needed depending on the current field value.
21842 emptyClass : 'x-form-empty-field',
21845 initEvents : function(){
21846 Roo.form.TextField.superclass.initEvents.call(this);
21847 if(this.validationEvent == 'keyup'){
21848 this.validationTask = new Roo.util.DelayedTask(this.validate, this);
21849 this.el.on('keyup', this.filterValidation, this);
21851 else if(this.validationEvent !== false){
21852 this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
21854 if(this.selectOnFocus || this.emptyText){
21855 this.on("focus", this.preFocus, this);
21856 if(this.emptyText){
21857 this.on('blur', this.postBlur, this);
21858 this.applyEmptyText();
21861 if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
21862 this.el.on("keypress", this.filterKeys, this);
21865 this.el.on("keyup", this.onKeyUp, this, {buffer:50});
21866 this.el.on("click", this.autoSize, this);
21870 processValue : function(value){
21871 if(this.stripCharsRe){
21872 var newValue = value.replace(this.stripCharsRe, '');
21873 if(newValue !== value){
21874 this.setRawValue(newValue);
21881 filterValidation : function(e){
21882 if(!e.isNavKeyPress()){
21883 this.validationTask.delay(this.validationDelay);
21888 onKeyUp : function(e){
21889 if(!e.isNavKeyPress()){
21895 * Resets the current field value to the originally-loaded value and clears any validation messages.
21896 * Also adds emptyText and emptyClass if the original value was blank.
21898 reset : function(){
21899 Roo.form.TextField.superclass.reset.call(this);
21900 this.applyEmptyText();
21903 applyEmptyText : function(){
21904 if(this.rendered && this.emptyText && this.getRawValue().length < 1){
21905 this.setRawValue(this.emptyText);
21906 this.el.addClass(this.emptyClass);
21911 preFocus : function(){
21912 if(this.emptyText){
21913 if(this.el.dom.value == this.emptyText){
21914 this.setRawValue('');
21916 this.el.removeClass(this.emptyClass);
21918 if(this.selectOnFocus){
21919 this.el.dom.select();
21924 postBlur : function(){
21925 this.applyEmptyText();
21929 filterKeys : function(e){
21930 var k = e.getKey();
21931 if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
21934 var c = e.getCharCode(), cc = String.fromCharCode(c);
21935 if(Roo.isIE && (e.isSpecialKey() || !cc)){
21938 if(!this.maskRe.test(cc)){
21943 setValue : function(v){
21944 if(this.emptyText && this.el && v !== undefined && v !== null && v !== ''){
21945 this.el.removeClass(this.emptyClass);
21947 Roo.form.TextField.superclass.setValue.apply(this, arguments);
21948 this.applyEmptyText();
21953 * Validates a value according to the field's validation rules and marks the field as invalid
21954 * if the validation fails
21955 * @param {Mixed} value The value to validate
21956 * @return {Boolean} True if the value is valid, else false
21958 validateValue : function(value){
21959 if(value.length < 1 || value === this.emptyText){ // if it's blank
21960 if(this.allowBlank){
21961 this.clearInvalid();
21964 this.markInvalid(this.blankText);
21968 if(value.length < this.minLength){
21969 this.markInvalid(String.format(this.minLengthText, this.minLength));
21972 if(value.length > this.maxLength){
21973 this.markInvalid(String.format(this.maxLengthText, this.maxLength));
21977 var vt = Roo.form.VTypes;
21978 if(!vt[this.vtype](value, this)){
21979 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
21983 if(typeof this.validator == "function"){
21984 var msg = this.validator(value);
21986 this.markInvalid(msg);
21990 if(this.regex && !this.regex.test(value)){
21991 this.markInvalid(this.regexText);
21998 * Selects text in this field
21999 * @param {Number} start (optional) The index where the selection should start (defaults to 0)
22000 * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
22002 selectText : function(start, end){
22003 var v = this.getRawValue();
22005 start = start === undefined ? 0 : start;
22006 end = end === undefined ? v.length : end;
22007 var d = this.el.dom;
22008 if(d.setSelectionRange){
22009 d.setSelectionRange(start, end);
22010 }else if(d.createTextRange){
22011 var range = d.createTextRange();
22012 range.moveStart("character", start);
22013 range.moveEnd("character", v.length-end);
22020 * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
22021 * This only takes effect if grow = true, and fires the autosize event.
22023 autoSize : function(){
22024 if(!this.grow || !this.rendered){
22028 this.metrics = Roo.util.TextMetrics.createInstance(this.el);
22031 var v = el.dom.value;
22032 var d = document.createElement('div');
22033 d.appendChild(document.createTextNode(v));
22037 var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
22038 this.el.setWidth(w);
22039 this.fireEvent("autosize", this, w);
22043 * Ext JS Library 1.1.1
22044 * Copyright(c) 2006-2007, Ext JS, LLC.
22046 * Originally Released Under LGPL - original licence link has changed is not relivant.
22049 * <script type="text/javascript">
22053 * @class Roo.form.Hidden
22054 * @extends Roo.form.TextField
22055 * Simple Hidden element used on forms
22057 * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
22060 * Creates a new Hidden form element.
22061 * @param {Object} config Configuration options
22066 // easy hidden field...
22067 Roo.form.Hidden = function(config){
22068 Roo.form.Hidden.superclass.constructor.call(this, config);
22071 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
22073 inputType: 'hidden',
22076 labelSeparator: '',
22078 itemCls : 'x-form-item-display-none'
22086 * Ext JS Library 1.1.1
22087 * Copyright(c) 2006-2007, Ext JS, LLC.
22089 * Originally Released Under LGPL - original licence link has changed is not relivant.
22092 * <script type="text/javascript">
22096 * @class Roo.form.TriggerField
22097 * @extends Roo.form.TextField
22098 * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
22099 * The trigger has no default action, so you must assign a function to implement the trigger click handler by
22100 * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
22101 * for which you can provide a custom implementation. For example:
22103 var trigger = new Roo.form.TriggerField();
22104 trigger.onTriggerClick = myTriggerFn;
22105 trigger.applyTo('my-field');
22108 * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
22109 * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
22110 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
22111 * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
22113 * Create a new TriggerField.
22114 * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
22115 * to the base TextField)
22117 Roo.form.TriggerField = function(config){
22118 this.mimicing = false;
22119 Roo.form.TriggerField.superclass.constructor.call(this, config);
22122 Roo.extend(Roo.form.TriggerField, Roo.form.TextField, {
22124 * @cfg {String} triggerClass A CSS class to apply to the trigger
22127 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
22128 * {tag: "input", type: "text", size: "16", autocomplete: "off"})
22130 defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "off"},
22132 * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
22136 /** @cfg {Boolean} grow @hide */
22137 /** @cfg {Number} growMin @hide */
22138 /** @cfg {Number} growMax @hide */
22144 autoSize: Roo.emptyFn,
22148 deferHeight : true,
22151 actionMode : 'wrap',
22153 onResize : function(w, h){
22154 Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
22155 if(typeof w == 'number'){
22156 var x = w - this.trigger.getWidth();
22157 this.el.setWidth(this.adjustWidth('input', x));
22158 this.trigger.setStyle('left', x+'px');
22163 adjustSize : Roo.BoxComponent.prototype.adjustSize,
22166 getResizeEl : function(){
22171 getPositionEl : function(){
22176 alignErrorIcon : function(){
22177 this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
22181 onRender : function(ct, position){
22182 Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
22183 this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
22184 this.trigger = this.wrap.createChild(this.triggerConfig ||
22185 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
22186 if(this.hideTrigger){
22187 this.trigger.setDisplayed(false);
22189 this.initTrigger();
22191 this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
22196 initTrigger : function(){
22197 this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
22198 this.trigger.addClassOnOver('x-form-trigger-over');
22199 this.trigger.addClassOnClick('x-form-trigger-click');
22203 onDestroy : function(){
22205 this.trigger.removeAllListeners();
22206 this.trigger.remove();
22209 this.wrap.remove();
22211 Roo.form.TriggerField.superclass.onDestroy.call(this);
22215 onFocus : function(){
22216 Roo.form.TriggerField.superclass.onFocus.call(this);
22217 if(!this.mimicing){
22218 this.wrap.addClass('x-trigger-wrap-focus');
22219 this.mimicing = true;
22220 Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
22221 if(this.monitorTab){
22222 this.el.on("keydown", this.checkTab, this);
22228 checkTab : function(e){
22229 if(e.getKey() == e.TAB){
22230 this.triggerBlur();
22235 onBlur : function(){
22240 mimicBlur : function(e, t){
22241 if(!this.wrap.contains(t) && this.validateBlur()){
22242 this.triggerBlur();
22247 triggerBlur : function(){
22248 this.mimicing = false;
22249 Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
22250 if(this.monitorTab){
22251 this.el.un("keydown", this.checkTab, this);
22253 this.wrap.removeClass('x-trigger-wrap-focus');
22254 Roo.form.TriggerField.superclass.onBlur.call(this);
22258 // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
22259 validateBlur : function(e, t){
22264 onDisable : function(){
22265 Roo.form.TriggerField.superclass.onDisable.call(this);
22267 this.wrap.addClass('x-item-disabled');
22272 onEnable : function(){
22273 Roo.form.TriggerField.superclass.onEnable.call(this);
22275 this.wrap.removeClass('x-item-disabled');
22280 onShow : function(){
22281 var ae = this.getActionEl();
22284 ae.dom.style.display = '';
22285 ae.dom.style.visibility = 'visible';
22291 onHide : function(){
22292 var ae = this.getActionEl();
22293 ae.dom.style.display = 'none';
22297 * The function that should handle the trigger's click event. This method does nothing by default until overridden
22298 * by an implementing function.
22300 * @param {EventObject} e
22302 onTriggerClick : Roo.emptyFn
22305 // TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
22306 // to be extended by an implementing class. For an example of implementing this class, see the custom
22307 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
22308 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
22309 initComponent : function(){
22310 Roo.form.TwinTriggerField.superclass.initComponent.call(this);
22312 this.triggerConfig = {
22313 tag:'span', cls:'x-form-twin-triggers', cn:[
22314 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
22315 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
22319 getTrigger : function(index){
22320 return this.triggers[index];
22323 initTrigger : function(){
22324 var ts = this.trigger.select('.x-form-trigger', true);
22325 this.wrap.setStyle('overflow', 'hidden');
22326 var triggerField = this;
22327 ts.each(function(t, all, index){
22328 t.hide = function(){
22329 var w = triggerField.wrap.getWidth();
22330 this.dom.style.display = 'none';
22331 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
22333 t.show = function(){
22334 var w = triggerField.wrap.getWidth();
22335 this.dom.style.display = '';
22336 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
22338 var triggerIndex = 'Trigger'+(index+1);
22340 if(this['hide'+triggerIndex]){
22341 t.dom.style.display = 'none';
22343 t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
22344 t.addClassOnOver('x-form-trigger-over');
22345 t.addClassOnClick('x-form-trigger-click');
22347 this.triggers = ts.elements;
22350 onTrigger1Click : Roo.emptyFn,
22351 onTrigger2Click : Roo.emptyFn
22354 * Ext JS Library 1.1.1
22355 * Copyright(c) 2006-2007, Ext JS, LLC.
22357 * Originally Released Under LGPL - original licence link has changed is not relivant.
22360 * <script type="text/javascript">
22364 * @class Roo.form.TextArea
22365 * @extends Roo.form.TextField
22366 * Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
22367 * support for auto-sizing.
22369 * Creates a new TextArea
22370 * @param {Object} config Configuration options
22372 Roo.form.TextArea = function(config){
22373 Roo.form.TextArea.superclass.constructor.call(this, config);
22374 // these are provided exchanges for backwards compat
22375 // minHeight/maxHeight were replaced by growMin/growMax to be
22376 // compatible with TextField growing config values
22377 if(this.minHeight !== undefined){
22378 this.growMin = this.minHeight;
22380 if(this.maxHeight !== undefined){
22381 this.growMax = this.maxHeight;
22385 Roo.extend(Roo.form.TextArea, Roo.form.TextField, {
22387 * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
22391 * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
22395 * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
22396 * in the field (equivalent to setting overflow: hidden, defaults to false)
22398 preventScrollbars: false,
22400 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
22401 * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
22405 onRender : function(ct, position){
22407 this.defaultAutoCreate = {
22409 style:"width:300px;height:60px;",
22410 autocomplete: "off"
22413 Roo.form.TextArea.superclass.onRender.call(this, ct, position);
22415 this.textSizeEl = Roo.DomHelper.append(document.body, {
22416 tag: "pre", cls: "x-form-grow-sizer"
22418 if(this.preventScrollbars){
22419 this.el.setStyle("overflow", "hidden");
22421 this.el.setHeight(this.growMin);
22425 onDestroy : function(){
22426 if(this.textSizeEl){
22427 this.textSizeEl.parentNode.removeChild(this.textSizeEl);
22429 Roo.form.TextArea.superclass.onDestroy.call(this);
22433 onKeyUp : function(e){
22434 if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
22440 * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
22441 * This only takes effect if grow = true, and fires the autosize event if the height changes.
22443 autoSize : function(){
22444 if(!this.grow || !this.textSizeEl){
22448 var v = el.dom.value;
22449 var ts = this.textSizeEl;
22452 ts.appendChild(document.createTextNode(v));
22455 Roo.fly(ts).setWidth(this.el.getWidth());
22457 v = "  ";
22460 v = v.replace(/\n/g, '<p> </p>');
22462 v += " \n ";
22465 var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
22466 if(h != this.lastHeight){
22467 this.lastHeight = h;
22468 this.el.setHeight(h);
22469 this.fireEvent("autosize", this, h);
22474 * Ext JS Library 1.1.1
22475 * Copyright(c) 2006-2007, Ext JS, LLC.
22477 * Originally Released Under LGPL - original licence link has changed is not relivant.
22480 * <script type="text/javascript">
22485 * @class Roo.form.NumberField
22486 * @extends Roo.form.TextField
22487 * Numeric text field that provides automatic keystroke filtering and numeric validation.
22489 * Creates a new NumberField
22490 * @param {Object} config Configuration options
22492 Roo.form.NumberField = function(config){
22493 Roo.form.NumberField.superclass.constructor.call(this, config);
22496 Roo.extend(Roo.form.NumberField, Roo.form.TextField, {
22498 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
22500 fieldClass: "x-form-field x-form-num-field",
22502 * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
22504 allowDecimals : true,
22506 * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
22508 decimalSeparator : ".",
22510 * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
22512 decimalPrecision : 2,
22514 * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
22516 allowNegative : true,
22518 * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
22520 minValue : Number.NEGATIVE_INFINITY,
22522 * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
22524 maxValue : Number.MAX_VALUE,
22526 * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
22528 minText : "The minimum value for this field is {0}",
22530 * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
22532 maxText : "The maximum value for this field is {0}",
22534 * @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
22535 * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
22537 nanText : "{0} is not a valid number",
22540 initEvents : function(){
22541 Roo.form.NumberField.superclass.initEvents.call(this);
22542 var allowed = "0123456789";
22543 if(this.allowDecimals){
22544 allowed += this.decimalSeparator;
22546 if(this.allowNegative){
22549 this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
22550 var keyPress = function(e){
22551 var k = e.getKey();
22552 if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
22555 var c = e.getCharCode();
22556 if(allowed.indexOf(String.fromCharCode(c)) === -1){
22560 this.el.on("keypress", keyPress, this);
22564 validateValue : function(value){
22565 if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
22568 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
22571 var num = this.parseValue(value);
22573 this.markInvalid(String.format(this.nanText, value));
22576 if(num < this.minValue){
22577 this.markInvalid(String.format(this.minText, this.minValue));
22580 if(num > this.maxValue){
22581 this.markInvalid(String.format(this.maxText, this.maxValue));
22587 getValue : function(){
22588 return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
22592 parseValue : function(value){
22593 value = parseFloat(String(value).replace(this.decimalSeparator, "."));
22594 return isNaN(value) ? '' : value;
22598 fixPrecision : function(value){
22599 var nan = isNaN(value);
22600 if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
22601 return nan ? '' : value;
22603 return parseFloat(value).toFixed(this.decimalPrecision);
22606 setValue : function(v){
22607 v = this.fixPrecision(v);
22608 Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
22612 decimalPrecisionFcn : function(v){
22613 return Math.floor(v);
22616 beforeBlur : function(){
22617 var v = this.parseValue(this.getRawValue());
22624 * Ext JS Library 1.1.1
22625 * Copyright(c) 2006-2007, Ext JS, LLC.
22627 * Originally Released Under LGPL - original licence link has changed is not relivant.
22630 * <script type="text/javascript">
22634 * @class Roo.form.DateField
22635 * @extends Roo.form.TriggerField
22636 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
22638 * Create a new DateField
22639 * @param {Object} config
22641 Roo.form.DateField = function(config){
22642 Roo.form.DateField.superclass.constructor.call(this, config);
22648 * Fires when a date is selected
22649 * @param {Roo.form.DateField} combo This combo box
22650 * @param {Date} date The date selected
22657 if(typeof this.minValue == "string") this.minValue = this.parseDate(this.minValue);
22658 if(typeof this.maxValue == "string") this.maxValue = this.parseDate(this.maxValue);
22659 this.ddMatch = null;
22660 if(this.disabledDates){
22661 var dd = this.disabledDates;
22663 for(var i = 0; i < dd.length; i++){
22665 if(i != dd.length-1) re += "|";
22667 this.ddMatch = new RegExp(re + ")");
22671 Roo.extend(Roo.form.DateField, Roo.form.TriggerField, {
22673 * @cfg {String} format
22674 * The default date format string which can be overriden for localization support. The format must be
22675 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
22679 * @cfg {String} altFormats
22680 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
22681 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
22683 altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
22685 * @cfg {Array} disabledDays
22686 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
22688 disabledDays : null,
22690 * @cfg {String} disabledDaysText
22691 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
22693 disabledDaysText : "Disabled",
22695 * @cfg {Array} disabledDates
22696 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
22697 * expression so they are very powerful. Some examples:
22699 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
22700 * <li>["03/08", "09/16"] would disable those days for every year</li>
22701 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
22702 * <li>["03/../2006"] would disable every day in March 2006</li>
22703 * <li>["^03"] would disable every day in every March</li>
22705 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
22706 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
22708 disabledDates : null,
22710 * @cfg {String} disabledDatesText
22711 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
22713 disabledDatesText : "Disabled",
22715 * @cfg {Date/String} minValue
22716 * The minimum allowed date. Can be either a Javascript date object or a string date in a
22717 * valid format (defaults to null).
22721 * @cfg {Date/String} maxValue
22722 * The maximum allowed date. Can be either a Javascript date object or a string date in a
22723 * valid format (defaults to null).
22727 * @cfg {String} minText
22728 * The error text to display when the date in the cell is before minValue (defaults to
22729 * 'The date in this field must be after {minValue}').
22731 minText : "The date in this field must be equal to or after {0}",
22733 * @cfg {String} maxText
22734 * The error text to display when the date in the cell is after maxValue (defaults to
22735 * 'The date in this field must be before {maxValue}').
22737 maxText : "The date in this field must be equal to or before {0}",
22739 * @cfg {String} invalidText
22740 * The error text to display when the date in the field is invalid (defaults to
22741 * '{value} is not a valid date - it must be in the format {format}').
22743 invalidText : "{0} is not a valid date - it must be in the format {1}",
22745 * @cfg {String} triggerClass
22746 * An additional CSS class used to style the trigger button. The trigger will always get the
22747 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
22748 * which displays a calendar icon).
22750 triggerClass : 'x-form-date-trigger',
22754 * @cfg {bool} useIso
22755 * if enabled, then the date field will use a hidden field to store the
22756 * real value as iso formated date. default (false)
22760 * @cfg {String/Object} autoCreate
22761 * A DomHelper element spec, or true for a default element spec (defaults to
22762 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
22765 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
22768 hiddenField: false,
22770 onRender : function(ct, position)
22772 Roo.form.DateField.superclass.onRender.call(this, ct, position);
22774 this.el.dom.removeAttribute('name');
22775 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
22777 this.hiddenField.value = this.formatDate(this.value, 'Y-m-d');
22778 // prevent input submission
22779 this.hiddenName = this.name;
22786 validateValue : function(value)
22788 value = this.formatDate(value);
22789 if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
22792 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
22795 var svalue = value;
22796 value = this.parseDate(value);
22798 this.markInvalid(String.format(this.invalidText, svalue, this.format));
22801 var time = value.getTime();
22802 if(this.minValue && time < this.minValue.getTime()){
22803 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
22806 if(this.maxValue && time > this.maxValue.getTime()){
22807 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
22810 if(this.disabledDays){
22811 var day = value.getDay();
22812 for(var i = 0; i < this.disabledDays.length; i++) {
22813 if(day === this.disabledDays[i]){
22814 this.markInvalid(this.disabledDaysText);
22819 var fvalue = this.formatDate(value);
22820 if(this.ddMatch && this.ddMatch.test(fvalue)){
22821 this.markInvalid(String.format(this.disabledDatesText, fvalue));
22828 // Provides logic to override the default TriggerField.validateBlur which just returns true
22829 validateBlur : function(){
22830 return !this.menu || !this.menu.isVisible();
22834 * Returns the current date value of the date field.
22835 * @return {Date} The date value
22837 getValue : function(){
22839 return this.hiddenField ? this.hiddenField.value : this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
22843 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
22844 * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
22845 * (the default format used is "m/d/y").
22848 //All of these calls set the same date value (May 4, 2006)
22850 //Pass a date object:
22851 var dt = new Date('5/4/06');
22852 dateField.setValue(dt);
22854 //Pass a date string (default format):
22855 dateField.setValue('5/4/06');
22857 //Pass a date string (custom format):
22858 dateField.format = 'Y-m-d';
22859 dateField.setValue('2006-5-4');
22861 * @param {String/Date} date The date or valid date string
22863 setValue : function(date){
22864 if (this.hiddenField) {
22865 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
22867 Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
22871 parseDate : function(value){
22872 if(!value || value instanceof Date){
22875 var v = Date.parseDate(value, this.format);
22876 if(!v && this.altFormats){
22877 if(!this.altFormatsArray){
22878 this.altFormatsArray = this.altFormats.split("|");
22880 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
22881 v = Date.parseDate(value, this.altFormatsArray[i]);
22888 formatDate : function(date, fmt){
22889 return (!date || !(date instanceof Date)) ?
22890 date : date.dateFormat(fmt || this.format);
22895 select: function(m, d){
22897 this.fireEvent('select', this, d);
22899 show : function(){ // retain focus styling
22903 this.focus.defer(10, this);
22904 var ml = this.menuListeners;
22905 this.menu.un("select", ml.select, this);
22906 this.menu.un("show", ml.show, this);
22907 this.menu.un("hide", ml.hide, this);
22912 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
22913 onTriggerClick : function(){
22917 if(this.menu == null){
22918 this.menu = new Roo.menu.DateMenu();
22920 Roo.apply(this.menu.picker, {
22921 showClear: this.allowBlank,
22922 minDate : this.minValue,
22923 maxDate : this.maxValue,
22924 disabledDatesRE : this.ddMatch,
22925 disabledDatesText : this.disabledDatesText,
22926 disabledDays : this.disabledDays,
22927 disabledDaysText : this.disabledDaysText,
22928 format : this.format,
22929 minText : String.format(this.minText, this.formatDate(this.minValue)),
22930 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
22932 this.menu.on(Roo.apply({}, this.menuListeners, {
22935 this.menu.picker.setValue(this.getValue() || new Date());
22936 this.menu.show(this.el, "tl-bl?");
22939 beforeBlur : function(){
22940 var v = this.parseDate(this.getRawValue());
22946 /** @cfg {Boolean} grow @hide */
22947 /** @cfg {Number} growMin @hide */
22948 /** @cfg {Number} growMax @hide */
22955 * Ext JS Library 1.1.1
22956 * Copyright(c) 2006-2007, Ext JS, LLC.
22958 * Originally Released Under LGPL - original licence link has changed is not relivant.
22961 * <script type="text/javascript">
22966 * @class Roo.form.ComboBox
22967 * @extends Roo.form.TriggerField
22968 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
22970 * Create a new ComboBox.
22971 * @param {Object} config Configuration options
22973 Roo.form.ComboBox = function(config){
22974 Roo.form.ComboBox.superclass.constructor.call(this, config);
22978 * Fires when the dropdown list is expanded
22979 * @param {Roo.form.ComboBox} combo This combo box
22984 * Fires when the dropdown list is collapsed
22985 * @param {Roo.form.ComboBox} combo This combo box
22989 * @event beforeselect
22990 * Fires before a list item is selected. Return false to cancel the selection.
22991 * @param {Roo.form.ComboBox} combo This combo box
22992 * @param {Roo.data.Record} record The data record returned from the underlying store
22993 * @param {Number} index The index of the selected item in the dropdown list
22995 'beforeselect' : true,
22998 * Fires when a list item is selected
22999 * @param {Roo.form.ComboBox} combo This combo box
23000 * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
23001 * @param {Number} index The index of the selected item in the dropdown list
23005 * @event beforequery
23006 * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
23007 * The event object passed has these properties:
23008 * @param {Roo.form.ComboBox} combo This combo box
23009 * @param {String} query The query
23010 * @param {Boolean} forceAll true to force "all" query
23011 * @param {Boolean} cancel true to cancel the query
23012 * @param {Object} e The query event object
23014 'beforequery': true,
23017 * Fires when the 'add' icon is pressed (add a listener to enable add button)
23018 * @param {Roo.form.ComboBox} combo This combo box
23023 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
23024 * @param {Roo.form.ComboBox} combo This combo box
23025 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
23031 if(this.transform){
23032 this.allowDomMove = false;
23033 var s = Roo.getDom(this.transform);
23034 if(!this.hiddenName){
23035 this.hiddenName = s.name;
23038 this.mode = 'local';
23039 var d = [], opts = s.options;
23040 for(var i = 0, len = opts.length;i < len; i++){
23042 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
23044 this.value = value;
23046 d.push([value, o.text]);
23048 this.store = new Roo.data.SimpleStore({
23050 fields: ['value', 'text'],
23053 this.valueField = 'value';
23054 this.displayField = 'text';
23056 s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
23057 if(!this.lazyRender){
23058 this.target = true;
23059 this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
23060 s.parentNode.removeChild(s); // remove it
23061 this.render(this.el.parentNode);
23063 s.parentNode.removeChild(s); // remove it
23068 this.store = Roo.factory(this.store, Roo.data);
23071 this.selectedIndex = -1;
23072 if(this.mode == 'local'){
23073 if(config.queryDelay === undefined){
23074 this.queryDelay = 10;
23076 if(config.minChars === undefined){
23082 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
23084 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
23087 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
23088 * rendering into an Roo.Editor, defaults to false)
23091 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
23092 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
23095 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
23098 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
23099 * the dropdown list (defaults to undefined, with no header element)
23103 * @cfg {String/Roo.Template} tpl The template to use to render the output
23107 defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
23109 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
23111 listWidth: undefined,
23113 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
23114 * mode = 'remote' or 'text' if mode = 'local')
23116 displayField: undefined,
23118 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
23119 * mode = 'remote' or 'value' if mode = 'local').
23120 * Note: use of a valueField requires the user make a selection
23121 * in order for a value to be mapped.
23123 valueField: undefined,
23127 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
23128 * field's data value (defaults to the underlying DOM element's name)
23130 hiddenName: undefined,
23132 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
23136 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
23138 selectedClass: 'x-combo-selected',
23140 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
23141 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
23142 * which displays a downward arrow icon).
23144 triggerClass : 'x-form-arrow-trigger',
23146 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
23150 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
23151 * anchor positions (defaults to 'tl-bl')
23153 listAlign: 'tl-bl?',
23155 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
23159 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
23160 * query specified by the allQuery config option (defaults to 'query')
23162 triggerAction: 'query',
23164 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
23165 * (defaults to 4, does not apply if editable = false)
23169 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
23170 * delay (typeAheadDelay) if it matches a known value (defaults to false)
23174 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
23175 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
23179 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
23180 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
23184 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
23185 * when editable = true (defaults to false)
23187 selectOnFocus:false,
23189 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
23191 queryParam: 'query',
23193 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
23194 * when mode = 'remote' (defaults to 'Loading...')
23196 loadingText: 'Loading...',
23198 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
23202 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
23206 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
23207 * traditional select (defaults to true)
23211 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
23215 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
23219 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
23220 * listWidth has a higher value)
23224 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
23225 * allow the user to set arbitrary text into the field (defaults to false)
23227 forceSelection:false,
23229 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
23230 * if typeAhead = true (defaults to 250)
23232 typeAheadDelay : 250,
23234 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
23235 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
23237 valueNotFoundText : undefined,
23239 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
23241 blockFocus : false,
23244 * @cfg {Boolean} disableClear Disable showing of clear button.
23246 disableClear : false,
23248 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
23250 alwaysQuery : false,
23256 // element that contains real text value.. (when hidden is used..)
23259 onRender : function(ct, position){
23260 Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
23261 if(this.hiddenName){
23262 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
23264 this.hiddenField.value =
23265 this.hiddenValue !== undefined ? this.hiddenValue :
23266 this.value !== undefined ? this.value : '';
23268 // prevent input submission
23269 this.el.dom.removeAttribute('name');
23274 this.el.dom.setAttribute('autocomplete', 'off');
23277 var cls = 'x-combo-list';
23279 this.list = new Roo.Layer({
23280 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
23283 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
23284 this.list.setWidth(lw);
23285 this.list.swallowEvent('mousewheel');
23286 this.assetHeight = 0;
23289 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
23290 this.assetHeight += this.header.getHeight();
23293 this.innerList = this.list.createChild({cls:cls+'-inner'});
23294 this.innerList.on('mouseover', this.onViewOver, this);
23295 this.innerList.on('mousemove', this.onViewMove, this);
23296 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
23298 if(this.allowBlank && !this.pageSize && !this.disableClear){
23299 this.footer = this.list.createChild({cls:cls+'-ft'});
23300 this.pageTb = new Roo.Toolbar(this.footer);
23304 this.footer = this.list.createChild({cls:cls+'-ft'});
23305 this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
23306 {pageSize: this.pageSize});
23310 if (this.pageTb && this.allowBlank && !this.disableClear) {
23312 this.pageTb.add(new Roo.Toolbar.Fill(), {
23313 cls: 'x-btn-icon x-btn-clear',
23315 handler: function()
23318 _this.clearValue();
23319 _this.onSelect(false, -1);
23324 this.assetHeight += this.footer.getHeight();
23329 this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
23332 this.view = new Roo.View(this.innerList, this.tpl, {
23333 singleSelect:true, store: this.store, selectedClass: this.selectedClass
23336 this.view.on('click', this.onViewClick, this);
23338 this.store.on('beforeload', this.onBeforeLoad, this);
23339 this.store.on('load', this.onLoad, this);
23340 this.store.on('loadexception', this.onLoadException, this);
23342 if(this.resizable){
23343 this.resizer = new Roo.Resizable(this.list, {
23344 pinned:true, handles:'se'
23346 this.resizer.on('resize', function(r, w, h){
23347 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
23348 this.listWidth = w;
23349 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
23350 this.restrictHeight();
23352 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
23354 if(!this.editable){
23355 this.editable = true;
23356 this.setEditable(false);
23360 if (typeof(this.events.add.listeners) != 'undefined') {
23362 this.addicon = this.wrap.createChild(
23363 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });
23365 this.addicon.on('click', function(e) {
23366 this.fireEvent('add', this);
23369 if (typeof(this.events.edit.listeners) != 'undefined') {
23371 this.editicon = this.wrap.createChild(
23372 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });
23373 if (this.addicon) {
23374 this.editicon.setStyle('margin-left', '40px');
23376 this.editicon.on('click', function(e) {
23378 // we fire even if inothing is selected..
23379 this.fireEvent('edit', this, this.lastData );
23389 initEvents : function(){
23390 Roo.form.ComboBox.superclass.initEvents.call(this);
23392 this.keyNav = new Roo.KeyNav(this.el, {
23393 "up" : function(e){
23394 this.inKeyMode = true;
23398 "down" : function(e){
23399 if(!this.isExpanded()){
23400 this.onTriggerClick();
23402 this.inKeyMode = true;
23407 "enter" : function(e){
23408 this.onViewClick();
23412 "esc" : function(e){
23416 "tab" : function(e){
23417 this.onViewClick(false);
23418 this.fireEvent("specialkey", this, e);
23424 doRelay : function(foo, bar, hname){
23425 if(hname == 'down' || this.scope.isExpanded()){
23426 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
23433 this.queryDelay = Math.max(this.queryDelay || 10,
23434 this.mode == 'local' ? 10 : 250);
23435 this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
23436 if(this.typeAhead){
23437 this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
23439 if(this.editable !== false){
23440 this.el.on("keyup", this.onKeyUp, this);
23442 if(this.forceSelection){
23443 this.on('blur', this.doForce, this);
23447 onDestroy : function(){
23449 this.view.setStore(null);
23450 this.view.el.removeAllListeners();
23451 this.view.el.remove();
23452 this.view.purgeListeners();
23455 this.list.destroy();
23458 this.store.un('beforeload', this.onBeforeLoad, this);
23459 this.store.un('load', this.onLoad, this);
23460 this.store.un('loadexception', this.onLoadException, this);
23462 Roo.form.ComboBox.superclass.onDestroy.call(this);
23466 fireKey : function(e){
23467 if(e.isNavKeyPress() && !this.list.isVisible()){
23468 this.fireEvent("specialkey", this, e);
23473 onResize: function(w, h){
23474 Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
23476 if(typeof w != 'number'){
23477 // we do not handle it!?!?
23480 var tw = this.trigger.getWidth();
23481 tw += this.addicon ? this.addicon.getWidth() : 0;
23482 tw += this.editicon ? this.editicon.getWidth() : 0;
23484 this.el.setWidth( this.adjustWidth('input', x));
23486 this.trigger.setStyle('left', x+'px');
23488 if(this.list && this.listWidth === undefined){
23489 var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
23490 this.list.setWidth(lw);
23491 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
23499 * Allow or prevent the user from directly editing the field text. If false is passed,
23500 * the user will only be able to select from the items defined in the dropdown list. This method
23501 * is the runtime equivalent of setting the 'editable' config option at config time.
23502 * @param {Boolean} value True to allow the user to directly edit the field text
23504 setEditable : function(value){
23505 if(value == this.editable){
23508 this.editable = value;
23510 this.el.dom.setAttribute('readOnly', true);
23511 this.el.on('mousedown', this.onTriggerClick, this);
23512 this.el.addClass('x-combo-noedit');
23514 this.el.dom.setAttribute('readOnly', false);
23515 this.el.un('mousedown', this.onTriggerClick, this);
23516 this.el.removeClass('x-combo-noedit');
23521 onBeforeLoad : function(){
23522 if(!this.hasFocus){
23525 this.innerList.update(this.loadingText ?
23526 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
23527 this.restrictHeight();
23528 this.selectedIndex = -1;
23532 onLoad : function(){
23533 if(!this.hasFocus){
23536 if(this.store.getCount() > 0){
23538 this.restrictHeight();
23539 if(this.lastQuery == this.allQuery){
23541 this.el.dom.select();
23543 if(!this.selectByValue(this.value, true)){
23544 this.select(0, true);
23548 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
23549 this.taTask.delay(this.typeAheadDelay);
23553 this.onEmptyResults();
23558 onLoadException : function()
23561 Roo.log(this.store.reader.jsonData);
23562 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
23563 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
23569 onTypeAhead : function(){
23570 if(this.store.getCount() > 0){
23571 var r = this.store.getAt(0);
23572 var newValue = r.data[this.displayField];
23573 var len = newValue.length;
23574 var selStart = this.getRawValue().length;
23575 if(selStart != len){
23576 this.setRawValue(newValue);
23577 this.selectText(selStart, newValue.length);
23583 onSelect : function(record, index){
23584 if(this.fireEvent('beforeselect', this, record, index) !== false){
23585 this.setFromData(index > -1 ? record.data : false);
23587 this.fireEvent('select', this, record, index);
23592 * Returns the currently selected field value or empty string if no value is set.
23593 * @return {String} value The selected value
23595 getValue : function(){
23596 if(this.valueField){
23597 return typeof this.value != 'undefined' ? this.value : '';
23599 return Roo.form.ComboBox.superclass.getValue.call(this);
23604 * Clears any text/value currently set in the field
23606 clearValue : function(){
23607 if(this.hiddenField){
23608 this.hiddenField.value = '';
23611 this.setRawValue('');
23612 this.lastSelectionText = '';
23613 this.applyEmptyText();
23617 * Sets the specified value into the field. If the value finds a match, the corresponding record text
23618 * will be displayed in the field. If the value does not match the data value of an existing item,
23619 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
23620 * Otherwise the field will be blank (although the value will still be set).
23621 * @param {String} value The value to match
23623 setValue : function(v){
23625 if(this.valueField){
23626 var r = this.findRecord(this.valueField, v);
23628 text = r.data[this.displayField];
23629 }else if(this.valueNotFoundText !== undefined){
23630 text = this.valueNotFoundText;
23633 this.lastSelectionText = text;
23634 if(this.hiddenField){
23635 this.hiddenField.value = v;
23637 Roo.form.ComboBox.superclass.setValue.call(this, text);
23641 * @property {Object} the last set data for the element
23646 * Sets the value of the field based on a object which is related to the record format for the store.
23647 * @param {Object} value the value to set as. or false on reset?
23649 setFromData : function(o){
23650 var dv = ''; // display value
23651 var vv = ''; // value value..
23653 if (this.displayField) {
23654 dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
23656 // this is an error condition!!!
23657 Roo.log('no displayField value set for '+ (this.name ? this.name : this.id));
23660 if(this.valueField){
23661 vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
23663 if(this.hiddenField){
23664 this.hiddenField.value = vv;
23666 this.lastSelectionText = dv;
23667 Roo.form.ComboBox.superclass.setValue.call(this, dv);
23671 // no hidden field.. - we store the value in 'value', but still display
23672 // display field!!!!
23673 this.lastSelectionText = dv;
23674 Roo.form.ComboBox.superclass.setValue.call(this, dv);
23680 reset : function(){
23681 // overridden so that last data is reset..
23682 this.setValue(this.originalValue);
23683 this.clearInvalid();
23684 this.lastData = false;
23687 findRecord : function(prop, value){
23689 if(this.store.getCount() > 0){
23690 this.store.each(function(r){
23691 if(r.data[prop] == value){
23701 getName: function()
23703 // returns hidden if it's set..
23704 if (!this.rendered) {return ''};
23705 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
23709 onViewMove : function(e, t){
23710 this.inKeyMode = false;
23714 onViewOver : function(e, t){
23715 if(this.inKeyMode){ // prevent key nav and mouse over conflicts
23718 var item = this.view.findItemFromChild(t);
23720 var index = this.view.indexOf(item);
23721 this.select(index, false);
23726 onViewClick : function(doFocus)
23728 var index = this.view.getSelectedIndexes()[0];
23729 var r = this.store.getAt(index);
23731 this.onSelect(r, index);
23733 if(doFocus !== false && !this.blockFocus){
23739 restrictHeight : function(){
23740 this.innerList.dom.style.height = '';
23741 var inner = this.innerList.dom;
23742 var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
23743 this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
23744 this.list.beginUpdate();
23745 this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
23746 this.list.alignTo(this.el, this.listAlign);
23747 this.list.endUpdate();
23751 onEmptyResults : function(){
23756 * Returns true if the dropdown list is expanded, else false.
23758 isExpanded : function(){
23759 return this.list.isVisible();
23763 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
23764 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
23765 * @param {String} value The data value of the item to select
23766 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
23767 * selected item if it is not currently in view (defaults to true)
23768 * @return {Boolean} True if the value matched an item in the list, else false
23770 selectByValue : function(v, scrollIntoView){
23771 if(v !== undefined && v !== null){
23772 var r = this.findRecord(this.valueField || this.displayField, v);
23774 this.select(this.store.indexOf(r), scrollIntoView);
23782 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
23783 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
23784 * @param {Number} index The zero-based index of the list item to select
23785 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
23786 * selected item if it is not currently in view (defaults to true)
23788 select : function(index, scrollIntoView){
23789 this.selectedIndex = index;
23790 this.view.select(index);
23791 if(scrollIntoView !== false){
23792 var el = this.view.getNode(index);
23794 this.innerList.scrollChildIntoView(el, false);
23800 selectNext : function(){
23801 var ct = this.store.getCount();
23803 if(this.selectedIndex == -1){
23805 }else if(this.selectedIndex < ct-1){
23806 this.select(this.selectedIndex+1);
23812 selectPrev : function(){
23813 var ct = this.store.getCount();
23815 if(this.selectedIndex == -1){
23817 }else if(this.selectedIndex != 0){
23818 this.select(this.selectedIndex-1);
23824 onKeyUp : function(e){
23825 if(this.editable !== false && !e.isSpecialKey()){
23826 this.lastKey = e.getKey();
23827 this.dqTask.delay(this.queryDelay);
23832 validateBlur : function(){
23833 return !this.list || !this.list.isVisible();
23837 initQuery : function(){
23838 this.doQuery(this.getRawValue());
23842 doForce : function(){
23843 if(this.el.dom.value.length > 0){
23844 this.el.dom.value =
23845 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
23846 this.applyEmptyText();
23851 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
23852 * query allowing the query action to be canceled if needed.
23853 * @param {String} query The SQL query to execute
23854 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
23855 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
23856 * saved in the current store (defaults to false)
23858 doQuery : function(q, forceAll){
23859 if(q === undefined || q === null){
23864 forceAll: forceAll,
23868 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
23872 forceAll = qe.forceAll;
23873 if(forceAll === true || (q.length >= this.minChars)){
23874 if(this.lastQuery != q || this.alwaysQuery){
23875 this.lastQuery = q;
23876 if(this.mode == 'local'){
23877 this.selectedIndex = -1;
23879 this.store.clearFilter();
23881 this.store.filter(this.displayField, q);
23885 this.store.baseParams[this.queryParam] = q;
23887 params: this.getParams(q)
23892 this.selectedIndex = -1;
23899 getParams : function(q){
23901 //p[this.queryParam] = q;
23904 p.limit = this.pageSize;
23910 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
23912 collapse : function(){
23913 if(!this.isExpanded()){
23917 Roo.get(document).un('mousedown', this.collapseIf, this);
23918 Roo.get(document).un('mousewheel', this.collapseIf, this);
23919 if (!this.editable) {
23920 Roo.get(document).un('keydown', this.listKeyPress, this);
23922 this.fireEvent('collapse', this);
23926 collapseIf : function(e){
23927 if(!e.within(this.wrap) && !e.within(this.list)){
23933 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
23935 expand : function(){
23936 if(this.isExpanded() || !this.hasFocus){
23939 this.list.alignTo(this.el, this.listAlign);
23941 Roo.get(document).on('mousedown', this.collapseIf, this);
23942 Roo.get(document).on('mousewheel', this.collapseIf, this);
23943 if (!this.editable) {
23944 Roo.get(document).on('keydown', this.listKeyPress, this);
23947 this.fireEvent('expand', this);
23951 // Implements the default empty TriggerField.onTriggerClick function
23952 onTriggerClick : function(){
23956 if(this.isExpanded()){
23958 if (!this.blockFocus) {
23963 this.hasFocus = true;
23964 if(this.triggerAction == 'all') {
23965 this.doQuery(this.allQuery, true);
23967 this.doQuery(this.getRawValue());
23969 if (!this.blockFocus) {
23974 listKeyPress : function(e)
23976 //Roo.log('listkeypress');
23977 // scroll to first matching element based on key pres..
23978 if (e.isSpecialKey()) {
23981 var k = String.fromCharCode(e.getKey()).toUpperCase();
23984 var csel = this.view.getSelectedNodes();
23985 var cselitem = false;
23987 var ix = this.view.indexOf(csel[0]);
23988 cselitem = this.store.getAt(ix);
23989 if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
23995 this.store.each(function(v) {
23997 // start at existing selection.
23998 if (cselitem.id == v.id) {
24004 if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
24005 match = this.store.indexOf(v);
24010 if (match === false) {
24011 return true; // no more action?
24014 this.view.select(match);
24015 var sn = Roo.get(this.view.getSelectedNodes()[0])
24016 sn.scrollIntoView(sn.dom.parentNode, false);
24020 * @cfg {Boolean} grow
24024 * @cfg {Number} growMin
24028 * @cfg {Number} growMax
24036 * Copyright(c) 2010-2012, Roo J Solutions Limited
24043 * @class Roo.form.ComboBoxArray
24044 * @extends Roo.form.TextField
24045 * A facebook style adder... for lists of email / people / countries etc...
24046 * pick multiple items from a combo box, and shows each one.
24048 * Fred [x] Brian [x] [Pick another |v]
24051 * For this to work: it needs various extra information
24052 * - normal combo problay has
24054 * + displayField, valueField
24056 * For our purpose...
24059 * If we change from 'extends' to wrapping...
24066 * Create a new ComboBoxArray.
24067 * @param {Object} config Configuration options
24071 Roo.form.ComboBoxArray = function(config)
24074 Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
24076 this.items = new Roo.util.MixedCollection(false);
24078 // construct the child combo...
24088 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
24091 * @cfg {Roo.form.Combo} combo The combo box that is wrapped
24096 // behavies liek a hiddne field
24097 inputType: 'hidden',
24099 * @cfg {Number} width The width of the box that displays the selected element
24106 * @cfg {String} name The name of the visable items on this form (eg. titles not ids)
24110 * @cfg {String} hiddenName The hidden name of the field, often contains an comma seperated list of names
24112 hiddenName : false,
24115 // private the array of items that are displayed..
24117 // private - the hidden field el.
24119 // private - the filed el..
24122 //validateValue : function() { return true; }, // all values are ok!
24123 //onAddClick: function() { },
24125 onRender : function(ct, position)
24128 // create the standard hidden element
24129 //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
24132 // give fake names to child combo;
24133 this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
24134 this.combo.name = this.name? (this.name+'-subcombo') : this.name;
24136 this.combo = Roo.factory(this.combo, Roo.form);
24137 this.combo.onRender(ct, position);
24139 // assigned so form know we need to do this..
24140 this.store = this.combo.store;
24141 this.valueField = this.combo.valueField;
24142 this.displayField = this.combo.displayField ;
24145 this.combo.wrap.addClass('x-cbarray-grp');
24147 var cbwrap = this.combo.wrap.createChild(
24148 {tag: 'div', cls: 'x-cbarray-cb'},
24153 this.hiddenEl = this.combo.wrap.createChild({
24154 tag: 'input', type:'hidden' , name: this.hiddenName, value : ''
24156 this.el = this.combo.wrap.createChild({
24157 tag: 'input', type:'hidden' , name: this.name, value : ''
24159 // this.el.dom.removeAttribute("name");
24162 this.outerWrap = this.combo.wrap;
24163 this.wrap = cbwrap;
24165 this.outerWrap.setWidth(this.width);
24166 this.outerWrap.dom.removeChild(this.el.dom);
24168 this.wrap.dom.appendChild(this.el.dom);
24169 this.outerWrap.dom.removeChild(this.combo.trigger.dom);
24170 this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
24172 this.combo.trigger.setStyle('position','relative');
24173 this.combo.trigger.setStyle('left', '0px');
24174 this.combo.trigger.setStyle('top', '2px');
24176 this.combo.el.setStyle('vertical-align', 'text-bottom');
24178 //this.trigger.setStyle('vertical-align', 'top');
24180 // this should use the code from combo really... on('add' ....)
24184 this.adder = this.outerWrap.createChild(
24185 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});
24187 this.adder.on('click', function(e) {
24188 _t.fireEvent('adderclick', this, e);
24192 //this.adder.on('click', this.onAddClick, _t);
24195 this.combo.on('select', function(cb, rec, ix) {
24196 this.addItem(rec.data);
24199 cb.el.dom.value = '';
24200 //cb.lastData = rec.data;
24209 getName: function()
24211 // returns hidden if it's set..
24212 if (!this.rendered) {return ''};
24213 return this.hiddenName ? this.hiddenName : this.name;
24218 onResize: function(w, h){
24221 // not sure if this is needed..
24222 //this.combo.onResize(w,h);
24224 if(typeof w != 'number'){
24225 // we do not handle it!?!?
24228 var tw = this.combo.trigger.getWidth();
24229 tw += this.addicon ? this.addicon.getWidth() : 0;
24230 tw += this.editicon ? this.editicon.getWidth() : 0;
24232 this.combo.el.setWidth( this.combo.adjustWidth('input', x));
24234 this.combo.trigger.setStyle('left', '0px');
24236 if(this.list && this.listWidth === undefined){
24237 var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
24238 this.list.setWidth(lw);
24239 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
24246 addItem: function(rec)
24248 var valueField = this.combo.valueField;
24249 var displayField = this.combo.displayField;
24250 if (this.items.indexOfKey(rec[valueField]) > -1) {
24251 //console.log("GOT " + rec.data.id);
24255 var x = new Roo.form.ComboBoxArray.Item({
24256 //id : rec[this.idField],
24258 displayField : displayField ,
24259 tipField : displayField ,
24263 this.items.add(rec[valueField],x);
24264 // add it before the element..
24265 this.updateHiddenEl();
24266 x.render(this.outerWrap, this.wrap.dom);
24267 // add the image handler..
24270 updateHiddenEl : function()
24273 if (!this.hiddenEl) {
24277 var idField = this.combo.valueField;
24279 this.items.each(function(f) {
24280 ar.push(f.data[idField]);
24283 this.hiddenEl.dom.value = ar.join(',');
24289 //Roo.form.ComboBoxArray.superclass.reset.call(this);
24290 this.items.each(function(f) {
24293 this.el.dom.value = '';
24294 if (this.hiddenEl) {
24295 this.hiddenEl.dom.value = '';
24299 getValue: function()
24301 return this.hiddenEl ? this.hiddenEl.dom.value : '';
24303 setValue: function(v) // not a valid action - must use addItems..
24310 if (this.store.isLocal && (typeof(v) == 'string')) {
24311 // then we can use the store to find the values..
24312 // comma seperated at present.. this needs to allow JSON based encoding..
24313 this.hiddenEl.value = v;
24315 Roo.each(v.split(','), function(k) {
24316 Roo.log("CHECK " + this.valueField + ',' + k);
24317 var li = this.store.query(this.valueField, k);
24322 add[this.valueField] = k;
24323 add[this.displayField] = li.item(0).data[this.displayField];
24329 if (typeof(v) == 'object') {
24330 // then let's assume it's an array of objects..
24331 Roo.each(v, function(l) {
24339 setFromData: function(v)
24341 // this recieves an object, if setValues is called.
24343 this.el.dom.value = v[this.displayField];
24344 this.hiddenEl.dom.value = v[this.valueField];
24345 if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
24348 var kv = v[this.valueField];
24349 var dv = v[this.displayField];
24350 kv = typeof(kv) != 'string' ? '' : kv;
24351 dv = typeof(dv) != 'string' ? '' : dv;
24354 var keys = kv.split(',');
24355 var display = dv.split(',');
24356 for (var i = 0 ; i < keys.length; i++) {
24359 add[this.valueField] = keys[i];
24360 add[this.displayField] = display[i];
24368 validateValue : function(value){
24369 return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
24378 * @class Roo.form.ComboBoxArray.Item
24379 * @extends Roo.BoxComponent
24380 * A selected item in the list
24381 * Fred [x] Brian [x] [Pick another |v]
24384 * Create a new item.
24385 * @param {Object} config Configuration options
24388 Roo.form.ComboBoxArray.Item = function(config) {
24389 config.id = Roo.id();
24390 Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
24393 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
24396 displayField : false,
24400 defaultAutoCreate : {
24402 cls: 'x-cbarray-item',
24409 src : Roo.BLANK_IMAGE_URL ,
24417 onRender : function(ct, position)
24419 Roo.form.Field.superclass.onRender.call(this, ct, position);
24422 var cfg = this.getAutoCreate();
24423 this.el = ct.createChild(cfg, position);
24426 this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
24428 this.el.child('div').dom.innerHTML = this.cb.renderer ?
24429 this.cb.renderer(this.data) :
24430 String.format('{0}',this.data[this.displayField]);
24433 this.el.child('div').dom.setAttribute('qtip',
24434 String.format('{0}',this.data[this.tipField])
24437 this.el.child('img').on('click', this.remove, this);
24441 remove : function()
24444 this.cb.items.remove(this);
24445 this.el.child('img').un('click', this.remove, this);
24447 this.cb.updateHiddenEl();
24453 * Ext JS Library 1.1.1
24454 * Copyright(c) 2006-2007, Ext JS, LLC.
24456 * Originally Released Under LGPL - original licence link has changed is not relivant.
24459 * <script type="text/javascript">
24462 * @class Roo.form.Checkbox
24463 * @extends Roo.form.Field
24464 * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
24466 * Creates a new Checkbox
24467 * @param {Object} config Configuration options
24469 Roo.form.Checkbox = function(config){
24470 Roo.form.Checkbox.superclass.constructor.call(this, config);
24474 * Fires when the checkbox is checked or unchecked.
24475 * @param {Roo.form.Checkbox} this This checkbox
24476 * @param {Boolean} checked The new checked value
24482 Roo.extend(Roo.form.Checkbox, Roo.form.Field, {
24484 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
24486 focusClass : undefined,
24488 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
24490 fieldClass: "x-form-field",
24492 * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
24496 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
24497 * {tag: "input", type: "checkbox", autocomplete: "off"})
24499 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
24501 * @cfg {String} boxLabel The text that appears beside the checkbox
24505 * @cfg {String} inputValue The value that should go into the generated input element's value attribute
24509 * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
24511 valueOff: '0', // value when not checked..
24513 actionMode : 'viewEl',
24516 itemCls : 'x-menu-check-item x-form-item',
24517 groupClass : 'x-menu-group-item',
24518 inputType : 'hidden',
24521 inSetChecked: false, // check that we are not calling self...
24523 inputElement: false, // real input element?
24524 basedOn: false, // ????
24526 isFormField: true, // not sure where this is needed!!!!
24528 onResize : function(){
24529 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
24530 if(!this.boxLabel){
24531 this.el.alignTo(this.wrap, 'c-c');
24535 initEvents : function(){
24536 Roo.form.Checkbox.superclass.initEvents.call(this);
24537 this.el.on("click", this.onClick, this);
24538 this.el.on("change", this.onClick, this);
24542 getResizeEl : function(){
24546 getPositionEl : function(){
24551 onRender : function(ct, position){
24552 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
24554 if(this.inputValue !== undefined){
24555 this.el.dom.value = this.inputValue;
24558 //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
24559 this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
24560 var viewEl = this.wrap.createChild({
24561 tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
24562 this.viewEl = viewEl;
24563 this.wrap.on('click', this.onClick, this);
24565 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
24566 this.el.on('propertychange', this.setFromHidden, this); //ie
24571 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
24572 // viewEl.on('click', this.onClick, this);
24574 //if(this.checked){
24575 this.setChecked(this.checked);
24577 //this.checked = this.el.dom;
24583 initValue : Roo.emptyFn,
24586 * Returns the checked state of the checkbox.
24587 * @return {Boolean} True if checked, else false
24589 getValue : function(){
24591 return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
24593 return this.valueOff;
24598 onClick : function(){
24599 this.setChecked(!this.checked);
24601 //if(this.el.dom.checked != this.checked){
24602 // this.setValue(this.el.dom.checked);
24607 * Sets the checked state of the checkbox.
24608 * On is always based on a string comparison between inputValue and the param.
24609 * @param {Boolean/String} value - the value to set
24610 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
24612 setValue : function(v,suppressEvent){
24615 //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
24616 //if(this.el && this.el.dom){
24617 // this.el.dom.checked = this.checked;
24618 // this.el.dom.defaultChecked = this.checked;
24620 this.setChecked(String(v) === String(this.inputValue), suppressEvent);
24621 //this.fireEvent("check", this, this.checked);
24624 setChecked : function(state,suppressEvent)
24626 if (this.inSetChecked) {
24627 this.checked = state;
24633 this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
24635 this.checked = state;
24636 if(suppressEvent !== true){
24637 this.fireEvent('check', this, state);
24639 this.inSetChecked = true;
24640 this.el.dom.value = state ? this.inputValue : this.valueOff;
24641 this.inSetChecked = false;
24644 // handle setting of hidden value by some other method!!?!?
24645 setFromHidden: function()
24650 //console.log("SET FROM HIDDEN");
24651 //alert('setFrom hidden');
24652 this.setValue(this.el.dom.value);
24655 onDestroy : function()
24658 Roo.get(this.viewEl).remove();
24661 Roo.form.Checkbox.superclass.onDestroy.call(this);
24666 * Ext JS Library 1.1.1
24667 * Copyright(c) 2006-2007, Ext JS, LLC.
24669 * Originally Released Under LGPL - original licence link has changed is not relivant.
24672 * <script type="text/javascript">
24676 * @class Roo.form.Radio
24677 * @extends Roo.form.Checkbox
24678 * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
24679 * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
24681 * Creates a new Radio
24682 * @param {Object} config Configuration options
24684 Roo.form.Radio = function(){
24685 Roo.form.Radio.superclass.constructor.apply(this, arguments);
24687 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
24688 inputType: 'radio',
24691 * If this radio is part of a group, it will return the selected value
24694 getGroupValue : function(){
24695 return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
24697 });//<script type="text/javascript">
24700 * Ext JS Library 1.1.1
24701 * Copyright(c) 2006-2007, Ext JS, LLC.
24702 * licensing@extjs.com
24704 * http://www.extjs.com/license
24710 * Default CSS appears to render it as fixed text by default (should really be Sans-Serif)
24711 * - IE ? - no idea how much works there.
24719 * @class Ext.form.HtmlEditor
24720 * @extends Ext.form.Field
24721 * Provides a lightweight HTML Editor component.
24723 * This has been tested on Fireforx / Chrome.. IE may not be so great..
24725 * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
24726 * supported by this editor.</b><br/><br/>
24727 * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
24728 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
24730 Roo.form.HtmlEditor = Roo.extend(Roo.form.Field, {
24732 * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
24736 * @cfg {String} createLinkText The default text for the create link prompt
24738 createLinkText : 'Please enter the URL for the link:',
24740 * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
24742 defaultLinkValue : 'http:/'+'/',
24745 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
24750 * @cfg {Number} height (in pixels)
24754 * @cfg {Number} width (in pixels)
24759 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
24762 stylesheets: false,
24767 // private properties
24768 validationEvent : false,
24770 initialized : false,
24772 sourceEditMode : false,
24773 onFocus : Roo.emptyFn,
24775 hideMode:'offsets',
24777 defaultAutoCreate : { // modified by initCompnoent..
24779 style:"width:500px;height:300px;",
24780 autocomplete: "off"
24784 initComponent : function(){
24787 * @event initialize
24788 * Fires when the editor is fully initialized (including the iframe)
24789 * @param {HtmlEditor} this
24794 * Fires when the editor is first receives the focus. Any insertion must wait
24795 * until after this event.
24796 * @param {HtmlEditor} this
24800 * @event beforesync
24801 * Fires before the textarea is updated with content from the editor iframe. Return false
24802 * to cancel the sync.
24803 * @param {HtmlEditor} this
24804 * @param {String} html
24808 * @event beforepush
24809 * Fires before the iframe editor is updated with content from the textarea. Return false
24810 * to cancel the push.
24811 * @param {HtmlEditor} this
24812 * @param {String} html
24817 * Fires when the textarea is updated with content from the editor iframe.
24818 * @param {HtmlEditor} this
24819 * @param {String} html
24824 * Fires when the iframe editor is updated with content from the textarea.
24825 * @param {HtmlEditor} this
24826 * @param {String} html
24830 * @event editmodechange
24831 * Fires when the editor switches edit modes
24832 * @param {HtmlEditor} this
24833 * @param {Boolean} sourceEdit True if source edit, false if standard editing.
24835 editmodechange: true,
24837 * @event editorevent
24838 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
24839 * @param {HtmlEditor} this
24843 this.defaultAutoCreate = {
24845 style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
24846 autocomplete: "off"
24851 * Protected method that will not generally be called directly. It
24852 * is called when the editor creates its toolbar. Override this method if you need to
24853 * add custom toolbar buttons.
24854 * @param {HtmlEditor} editor
24856 createToolbar : function(editor){
24857 if (!editor.toolbars || !editor.toolbars.length) {
24858 editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
24861 for (var i =0 ; i < editor.toolbars.length;i++) {
24862 editor.toolbars[i] = Roo.factory(editor.toolbars[i], Roo.form.HtmlEditor);
24863 editor.toolbars[i].init(editor);
24870 * Protected method that will not generally be called directly. It
24871 * is called when the editor initializes the iframe with HTML contents. Override this method if you
24872 * want to change the initialization markup of the iframe (e.g. to add stylesheets).
24874 getDocMarkup : function(){
24877 if (this.stylesheets === false) {
24879 Roo.get(document.head).select('style').each(function(node) {
24880 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
24883 Roo.get(document.head).select('link').each(function(node) {
24884 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
24887 } else if (!this.stylesheets.length) {
24889 st = '<style type="text/css">' +
24890 'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
24893 Roo.each(this.stylesheets, function(s) {
24894 st += '<link rel="stylesheet" type="text/css" href="' + s +'" />'
24899 st += '<style type="text/css">' +
24900 'IMG { cursor: pointer } ' +
24904 return '<html><head>' + st +
24905 //<style type="text/css">' +
24906 //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
24908 ' </head><body class="roo-htmleditor-body"></body></html>';
24912 onRender : function(ct, position)
24915 Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
24916 this.el.dom.style.border = '0 none';
24917 this.el.dom.setAttribute('tabIndex', -1);
24918 this.el.addClass('x-hidden');
24919 if(Roo.isIE){ // fix IE 1px bogus margin
24920 this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
24922 this.wrap = this.el.wrap({
24923 cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
24926 if (this.resizable) {
24927 this.resizeEl = new Roo.Resizable(this.wrap, {
24931 minHeight : this.height,
24932 height: this.height,
24933 handles : this.resizable,
24936 resize : function(r, w, h) {
24937 _t.onResize(w,h); // -something
24944 this.frameId = Roo.id();
24946 this.createToolbar(this);
24950 var iframe = this.wrap.createChild({
24953 name: this.frameId,
24954 frameBorder : 'no',
24955 'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL : "javascript:false"
24959 // console.log(iframe);
24960 //this.wrap.dom.appendChild(iframe);
24962 this.iframe = iframe.dom;
24964 this.assignDocWin();
24966 this.doc.designMode = 'on';
24969 this.doc.write(this.getDocMarkup());
24973 var task = { // must defer to wait for browser to be ready
24975 //console.log("run task?" + this.doc.readyState);
24976 this.assignDocWin();
24977 if(this.doc.body || this.doc.readyState == 'complete'){
24979 this.doc.designMode="on";
24983 Roo.TaskMgr.stop(task);
24984 this.initEditor.defer(10, this);
24991 Roo.TaskMgr.start(task);
24994 this.setSize(this.wrap.getSize());
24996 if (this.resizeEl) {
24997 this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
24998 // should trigger onReize..
25003 onResize : function(w, h)
25005 //Roo.log('resize: ' +w + ',' + h );
25006 Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
25007 if(this.el && this.iframe){
25008 if(typeof w == 'number'){
25009 var aw = w - this.wrap.getFrameWidth('lr');
25010 this.el.setWidth(this.adjustWidth('textarea', aw));
25011 this.iframe.style.width = aw + 'px';
25013 if(typeof h == 'number'){
25015 for (var i =0; i < this.toolbars.length;i++) {
25016 // fixme - ask toolbars for heights?
25017 tbh += this.toolbars[i].tb.el.getHeight();
25018 if (this.toolbars[i].footer) {
25019 tbh += this.toolbars[i].footer.el.getHeight();
25026 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
25027 ah -= 5; // knock a few pixes off for look..
25028 this.el.setHeight(this.adjustWidth('textarea', ah));
25029 this.iframe.style.height = ah + 'px';
25031 (this.doc.body || this.doc.documentElement).style.height = (ah - (this.iframePad*2)) + 'px';
25038 * Toggles the editor between standard and source edit mode.
25039 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
25041 toggleSourceEdit : function(sourceEditMode){
25043 this.sourceEditMode = sourceEditMode === true;
25045 if(this.sourceEditMode){
25048 this.iframe.className = 'x-hidden';
25049 this.el.removeClass('x-hidden');
25050 this.el.dom.removeAttribute('tabIndex');
25055 this.iframe.className = '';
25056 this.el.addClass('x-hidden');
25057 this.el.dom.setAttribute('tabIndex', -1);
25060 this.setSize(this.wrap.getSize());
25061 this.fireEvent('editmodechange', this, this.sourceEditMode);
25064 // private used internally
25065 createLink : function(){
25066 var url = prompt(this.createLinkText, this.defaultLinkValue);
25067 if(url && url != 'http:/'+'/'){
25068 this.relayCmd('createlink', url);
25072 // private (for BoxComponent)
25073 adjustSize : Roo.BoxComponent.prototype.adjustSize,
25075 // private (for BoxComponent)
25076 getResizeEl : function(){
25080 // private (for BoxComponent)
25081 getPositionEl : function(){
25086 initEvents : function(){
25087 this.originalValue = this.getValue();
25091 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
25094 markInvalid : Roo.emptyFn,
25096 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
25099 clearInvalid : Roo.emptyFn,
25101 setValue : function(v){
25102 Roo.form.HtmlEditor.superclass.setValue.call(this, v);
25107 * Protected method that will not generally be called directly. If you need/want
25108 * custom HTML cleanup, this is the method you should override.
25109 * @param {String} html The HTML to be cleaned
25110 * return {String} The cleaned HTML
25112 cleanHtml : function(html){
25113 html = String(html);
25114 if(html.length > 5){
25115 if(Roo.isSafari){ // strip safari nonsense
25116 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
25119 if(html == ' '){
25126 * Protected method that will not generally be called directly. Syncs the contents
25127 * of the editor iframe with the textarea.
25129 syncValue : function(){
25130 if(this.initialized){
25131 var bd = (this.doc.body || this.doc.documentElement);
25132 //this.cleanUpPaste(); -- this is done else where and causes havoc..
25133 var html = bd.innerHTML;
25135 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
25136 var m = bs.match(/text-align:(.*?);/i);
25138 html = '<div style="'+m[0]+'">' + html + '</div>';
25141 html = this.cleanHtml(html);
25142 // fix up the special chars..
25143 html = html.replace(/([\x80-\uffff])/g, function (a, b) {
25144 return "&#"+b.charCodeAt()+";"
25146 if(this.fireEvent('beforesync', this, html) !== false){
25147 this.el.dom.value = html;
25148 this.fireEvent('sync', this, html);
25154 * Protected method that will not generally be called directly. Pushes the value of the textarea
25155 * into the iframe editor.
25157 pushValue : function(){
25158 if(this.initialized){
25159 var v = this.el.dom.value;
25164 if(this.fireEvent('beforepush', this, v) !== false){
25165 var d = (this.doc.body || this.doc.documentElement);
25167 this.cleanUpPaste();
25168 this.el.dom.value = d.innerHTML;
25169 this.fireEvent('push', this, v);
25175 deferFocus : function(){
25176 this.focus.defer(10, this);
25180 focus : function(){
25181 if(this.win && !this.sourceEditMode){
25188 assignDocWin: function()
25190 var iframe = this.iframe;
25193 this.doc = iframe.contentWindow.document;
25194 this.win = iframe.contentWindow;
25196 if (!Roo.get(this.frameId)) {
25199 this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
25200 this.win = Roo.get(this.frameId).dom.contentWindow;
25205 initEditor : function(){
25206 //console.log("INIT EDITOR");
25207 this.assignDocWin();
25211 this.doc.designMode="on";
25213 this.doc.write(this.getDocMarkup());
25216 var dbody = (this.doc.body || this.doc.documentElement);
25217 //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
25218 // this copies styles from the containing element into thsi one..
25219 // not sure why we need all of this..
25220 var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
25221 ss['background-attachment'] = 'fixed'; // w3c
25222 dbody.bgProperties = 'fixed'; // ie
25223 Roo.DomHelper.applyStyles(dbody, ss);
25224 Roo.EventManager.on(this.doc, {
25225 //'mousedown': this.onEditorEvent,
25226 'mouseup': this.onEditorEvent,
25227 'dblclick': this.onEditorEvent,
25228 'click': this.onEditorEvent,
25229 'keyup': this.onEditorEvent,
25234 Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
25236 if(Roo.isIE || Roo.isSafari || Roo.isOpera){
25237 Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
25239 this.initialized = true;
25241 this.fireEvent('initialize', this);
25246 onDestroy : function(){
25252 for (var i =0; i < this.toolbars.length;i++) {
25253 // fixme - ask toolbars for heights?
25254 this.toolbars[i].onDestroy();
25257 this.wrap.dom.innerHTML = '';
25258 this.wrap.remove();
25263 onFirstFocus : function(){
25265 this.assignDocWin();
25268 this.activated = true;
25269 for (var i =0; i < this.toolbars.length;i++) {
25270 this.toolbars[i].onFirstFocus();
25273 if(Roo.isGecko){ // prevent silly gecko errors
25275 var s = this.win.getSelection();
25276 if(!s.focusNode || s.focusNode.nodeType != 3){
25277 var r = s.getRangeAt(0);
25278 r.selectNodeContents((this.doc.body || this.doc.documentElement));
25283 this.execCmd('useCSS', true);
25284 this.execCmd('styleWithCSS', false);
25287 this.fireEvent('activate', this);
25291 adjustFont: function(btn){
25292 var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
25293 //if(Roo.isSafari){ // safari
25296 var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
25297 if(Roo.isSafari){ // safari
25298 var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
25299 v = (v < 10) ? 10 : v;
25300 v = (v > 48) ? 48 : v;
25301 v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
25306 v = Math.max(1, v+adjust);
25308 this.execCmd('FontSize', v );
25311 onEditorEvent : function(e){
25312 this.fireEvent('editorevent', this, e);
25313 // this.updateToolbar();
25314 this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
25317 insertTag : function(tg)
25319 // could be a bit smarter... -> wrap the current selected tRoo..
25321 this.execCmd("formatblock", tg);
25325 insertText : function(txt)
25329 range = this.createRange();
25330 range.deleteContents();
25331 //alert(Sender.getAttribute('label'));
25333 range.insertNode(this.doc.createTextNode(txt));
25337 relayBtnCmd : function(btn){
25338 this.relayCmd(btn.cmd);
25342 * Executes a Midas editor command on the editor document and performs necessary focus and
25343 * toolbar updates. <b>This should only be called after the editor is initialized.</b>
25344 * @param {String} cmd The Midas command
25345 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
25347 relayCmd : function(cmd, value){
25349 this.execCmd(cmd, value);
25350 this.fireEvent('editorevent', this);
25351 //this.updateToolbar();
25356 * Executes a Midas editor command directly on the editor document.
25357 * For visual commands, you should use {@link #relayCmd} instead.
25358 * <b>This should only be called after the editor is initialized.</b>
25359 * @param {String} cmd The Midas command
25360 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
25362 execCmd : function(cmd, value){
25363 this.doc.execCommand(cmd, false, value === undefined ? null : value);
25370 * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
25372 * @param {String} text | dom node..
25374 insertAtCursor : function(text)
25379 if(!this.activated){
25385 var r = this.doc.selection.createRange();
25396 if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
25400 // from jquery ui (MIT licenced)
25402 var win = this.win;
25404 if (win.getSelection && win.getSelection().getRangeAt) {
25405 range = win.getSelection().getRangeAt(0);
25406 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
25407 range.insertNode(node);
25408 } else if (win.document.selection && win.document.selection.createRange) {
25409 // no firefox support
25410 var txt = typeof(text) == 'string' ? text : text.outerHTML;
25411 win.document.selection.createRange().pasteHTML(txt);
25413 // no firefox support
25414 var txt = typeof(text) == 'string' ? text : text.outerHTML;
25415 this.execCmd('InsertHTML', txt);
25424 mozKeyPress : function(e){
25426 var c = e.getCharCode(), cmd;
25429 c = String.fromCharCode(c).toLowerCase();
25443 this.cleanUpPaste.defer(100, this);
25451 e.preventDefault();
25459 fixKeys : function(){ // load time branching for fastest keydown performance
25461 return function(e){
25462 var k = e.getKey(), r;
25465 r = this.doc.selection.createRange();
25468 r.pasteHTML('    ');
25475 r = this.doc.selection.createRange();
25477 var target = r.parentElement();
25478 if(!target || target.tagName.toLowerCase() != 'li'){
25480 r.pasteHTML('<br />');
25486 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
25487 this.cleanUpPaste.defer(100, this);
25493 }else if(Roo.isOpera){
25494 return function(e){
25495 var k = e.getKey();
25499 this.execCmd('InsertHTML','    ');
25502 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
25503 this.cleanUpPaste.defer(100, this);
25508 }else if(Roo.isSafari){
25509 return function(e){
25510 var k = e.getKey();
25514 this.execCmd('InsertText','\t');
25518 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
25519 this.cleanUpPaste.defer(100, this);
25527 getAllAncestors: function()
25529 var p = this.getSelectedNode();
25532 a.push(p); // push blank onto stack..
25533 p = this.getParentElement();
25537 while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
25541 a.push(this.doc.body);
25545 lastSelNode : false,
25548 getSelection : function()
25550 this.assignDocWin();
25551 return Roo.isIE ? this.doc.selection : this.win.getSelection();
25554 getSelectedNode: function()
25556 // this may only work on Gecko!!!
25558 // should we cache this!!!!
25563 var range = this.createRange(this.getSelection()).cloneRange();
25566 var parent = range.parentElement();
25568 var testRange = range.duplicate();
25569 testRange.moveToElementText(parent);
25570 if (testRange.inRange(range)) {
25573 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
25576 parent = parent.parentElement;
25581 // is ancestor a text element.
25582 var ac = range.commonAncestorContainer;
25583 if (ac.nodeType == 3) {
25584 ac = ac.parentNode;
25587 var ar = ac.childNodes;
25590 var other_nodes = [];
25591 var has_other_nodes = false;
25592 for (var i=0;i<ar.length;i++) {
25593 if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ?
25596 // fullly contained node.
25598 if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
25603 // probably selected..
25604 if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
25605 other_nodes.push(ar[i]);
25609 if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0)) {
25614 has_other_nodes = true;
25616 if (!nodes.length && other_nodes.length) {
25617 nodes= other_nodes;
25619 if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
25625 createRange: function(sel)
25627 // this has strange effects when using with
25628 // top toolbar - not sure if it's a great idea.
25629 //this.editor.contentWindow.focus();
25630 if (typeof sel != "undefined") {
25632 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
25634 return this.doc.createRange();
25637 return this.doc.createRange();
25640 getParentElement: function()
25643 this.assignDocWin();
25644 var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
25646 var range = this.createRange(sel);
25649 var p = range.commonAncestorContainer;
25650 while (p.nodeType == 3) { // text node
25661 * Range intersection.. the hard stuff...
25665 * [ -- selected range --- ]
25669 * if end is before start or hits it. fail.
25670 * if start is after end or hits it fail.
25672 * if either hits (but other is outside. - then it's not
25678 // @see http://www.thismuchiknow.co.uk/?p=64.
25679 rangeIntersectsNode : function(range, node)
25681 var nodeRange = node.ownerDocument.createRange();
25683 nodeRange.selectNode(node);
25685 nodeRange.selectNodeContents(node);
25688 var rangeStartRange = range.cloneRange();
25689 rangeStartRange.collapse(true);
25691 var rangeEndRange = range.cloneRange();
25692 rangeEndRange.collapse(false);
25694 var nodeStartRange = nodeRange.cloneRange();
25695 nodeStartRange.collapse(true);
25697 var nodeEndRange = nodeRange.cloneRange();
25698 nodeEndRange.collapse(false);
25700 return rangeStartRange.compareBoundaryPoints(
25701 Range.START_TO_START, nodeEndRange) == -1 &&
25702 rangeEndRange.compareBoundaryPoints(
25703 Range.START_TO_START, nodeStartRange) == 1;
25707 rangeCompareNode : function(range, node)
25709 var nodeRange = node.ownerDocument.createRange();
25711 nodeRange.selectNode(node);
25713 nodeRange.selectNodeContents(node);
25717 range.collapse(true);
25719 nodeRange.collapse(true);
25721 var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
25722 var ee = range.compareBoundaryPoints( Range.END_TO_END, nodeRange);
25724 //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
25726 var nodeIsBefore = ss == 1;
25727 var nodeIsAfter = ee == -1;
25729 if (nodeIsBefore && nodeIsAfter)
25731 if (!nodeIsBefore && nodeIsAfter)
25732 return 1; //right trailed.
25734 if (nodeIsBefore && !nodeIsAfter)
25735 return 2; // left trailed.
25740 // private? - in a new class?
25741 cleanUpPaste : function()
25743 // cleans up the whole document..
25744 Roo.log('cleanuppaste');
25745 this.cleanUpChildren(this.doc.body);
25746 var clean = this.cleanWordChars(this.doc.body.innerHTML);
25747 if (clean != this.doc.body.innerHTML) {
25748 this.doc.body.innerHTML = clean;
25753 cleanWordChars : function(input) {
25754 var he = Roo.form.HtmlEditor;
25756 var output = input;
25757 Roo.each(he.swapCodes, function(sw) {
25759 var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
25760 output = output.replace(swapper, sw[1]);
25766 cleanUpChildren : function (n)
25768 if (!n.childNodes.length) {
25771 for (var i = n.childNodes.length-1; i > -1 ; i--) {
25772 this.cleanUpChild(n.childNodes[i]);
25779 cleanUpChild : function (node)
25781 //console.log(node);
25782 if (node.nodeName == "#text") {
25783 // clean up silly Windows -- stuff?
25786 if (node.nodeName == "#comment") {
25787 node.parentNode.removeChild(node);
25788 // clean up silly Windows -- stuff?
25792 if (Roo.form.HtmlEditor.black.indexOf(node.tagName.toLowerCase()) > -1) {
25794 node.parentNode.removeChild(node);
25799 var remove_keep_children= Roo.form.HtmlEditor.remove.indexOf(node.tagName.toLowerCase()) > -1;
25801 // remove <a name=....> as rendering on yahoo mailer is bored with this.
25803 if (node.tagName.toLowerCase() == 'a' && !node.hasAttribute('href')) {
25804 remove_keep_children = true;
25807 if (remove_keep_children) {
25808 this.cleanUpChildren(node);
25809 // inserts everything just before this node...
25810 while (node.childNodes.length) {
25811 var cn = node.childNodes[0];
25812 node.removeChild(cn);
25813 node.parentNode.insertBefore(cn, node);
25815 node.parentNode.removeChild(node);
25819 if (!node.attributes || !node.attributes.length) {
25820 this.cleanUpChildren(node);
25824 function cleanAttr(n,v)
25827 if (v.match(/^\./) || v.match(/^\//)) {
25830 if (v.match(/^(http|https):\/\//) || v.match(/^mailto:/)) {
25833 Roo.log("(REMOVE)"+ node.tagName +'.' + n + '=' + v);
25834 node.removeAttribute(n);
25838 function cleanStyle(n,v)
25840 if (v.match(/expression/)) { //XSS?? should we even bother..
25841 node.removeAttribute(n);
25846 var parts = v.split(/;/);
25847 Roo.each(parts, function(p) {
25848 p = p.replace(/\s+/g,'');
25852 var l = p.split(':').shift().replace(/\s+/g,'');
25854 // only allow 'c whitelisted system attributes'
25855 if (Roo.form.HtmlEditor.cwhite.indexOf(l) < 0) {
25856 Roo.log('(REMOVE)' + node.tagName +'.' + n + ':'+l + '=' + v);
25857 node.removeAttribute(n);
25867 for (var i = node.attributes.length-1; i > -1 ; i--) {
25868 var a = node.attributes[i];
25870 if (Roo.form.HtmlEditor.ablack.indexOf(a.name.toLowerCase()) > -1) {
25871 node.removeAttribute(a.name);
25874 if (Roo.form.HtmlEditor.aclean.indexOf(a.name.toLowerCase()) > -1) {
25875 cleanAttr(a.name,a.value); // fixme..
25878 if (a.name == 'style') {
25879 cleanStyle(a.name,a.value);
25881 /// clean up MS crap..
25882 // tecnically this should be a list of valid class'es..
25885 if (a.name == 'class') {
25886 if (a.value.match(/^Mso/)) {
25887 node.className = '';
25890 if (a.value.match(/body/)) {
25891 node.className = '';
25901 this.cleanUpChildren(node);
25907 // hide stuff that is not compatible
25921 * @event specialkey
25925 * @cfg {String} fieldClass @hide
25928 * @cfg {String} focusClass @hide
25931 * @cfg {String} autoCreate @hide
25934 * @cfg {String} inputType @hide
25937 * @cfg {String} invalidClass @hide
25940 * @cfg {String} invalidText @hide
25943 * @cfg {String} msgFx @hide
25946 * @cfg {String} validateOnBlur @hide
25950 Roo.form.HtmlEditor.white = [
25951 'area', 'br', 'img', 'input', 'hr', 'wbr',
25953 'address', 'blockquote', 'center', 'dd', 'dir', 'div',
25954 'dl', 'dt', 'h1', 'h2', 'h3', 'h4',
25955 'h5', 'h6', 'hr', 'isindex', 'listing', 'marquee',
25956 'menu', 'multicol', 'ol', 'p', 'plaintext', 'pre',
25957 'table', 'ul', 'xmp',
25959 'caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
25962 'dir', 'menu', 'ol', 'ul', 'dl',
25968 Roo.form.HtmlEditor.black = [
25969 // 'embed', 'object', // enable - backend responsiblity to clean thiese
25971 'base', 'basefont', 'bgsound', 'blink', 'body',
25972 'frame', 'frameset', 'head', 'html', 'ilayer',
25973 'iframe', 'layer', 'link', 'meta', 'object',
25974 'script', 'style' ,'title', 'xml' // clean later..
25976 Roo.form.HtmlEditor.clean = [
25977 'script', 'style', 'title', 'xml'
25979 Roo.form.HtmlEditor.remove = [
25984 Roo.form.HtmlEditor.ablack = [
25988 Roo.form.HtmlEditor.aclean = [
25989 'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc'
25993 Roo.form.HtmlEditor.pwhite= [
25994 'http', 'https', 'mailto'
25997 // white listed style attributes.
25998 Roo.form.HtmlEditor.cwhite= [
26004 Roo.form.HtmlEditor.swapCodes =[
26015 // <script type="text/javascript">
26018 * Ext JS Library 1.1.1
26019 * Copyright(c) 2006-2007, Ext JS, LLC.
26025 * @class Roo.form.HtmlEditorToolbar1
26030 new Roo.form.HtmlEditor({
26033 new Roo.form.HtmlEditorToolbar1({
26034 disable : { fonts: 1 , format: 1, ..., ... , ...],
26040 * @cfg {Object} disable List of elements to disable..
26041 * @cfg {Array} btns List of additional buttons.
26045 * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
26048 Roo.form.HtmlEditor.ToolbarStandard = function(config)
26051 Roo.apply(this, config);
26053 // default disabled, based on 'good practice'..
26054 this.disable = this.disable || {};
26055 Roo.applyIf(this.disable, {
26058 specialElements : true
26062 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
26063 // dont call parent... till later.
26066 Roo.apply(Roo.form.HtmlEditor.ToolbarStandard.prototype, {
26074 * @cfg {Object} disable List of toolbar elements to disable
26079 * @cfg {Array} fontFamilies An array of available font families
26097 // "á" , ?? a acute?
26102 "°" // , // degrees
26104 // "é" , // e ecute
26105 // "ú" , // u ecute?
26108 specialElements : [
26110 text: "Insert Table",
26113 ihtml : '<table><tr><td>Cell</td></tr></table>'
26117 text: "Insert Image",
26120 ihtml : '<img src="about:blank"/>'
26129 "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password",
26130 "input:submit", "input:button", "select", "textarea", "label" ],
26133 ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"],
26135 ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"]
26138 * @cfg {String} defaultFont default font to use.
26140 defaultFont: 'tahoma',
26142 fontSelect : false,
26145 formatCombo : false,
26147 init : function(editor)
26149 this.editor = editor;
26152 var fid = editor.frameId;
26154 function btn(id, toggle, handler){
26155 var xid = fid + '-'+ id ;
26159 cls : 'x-btn-icon x-edit-'+id,
26160 enableToggle:toggle !== false,
26161 scope: editor, // was editor...
26162 handler:handler||editor.relayBtnCmd,
26163 clickEvent:'mousedown',
26164 tooltip: etb.buttonTips[id] || undefined, ///tips ???
26171 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
26173 // stop form submits
26174 tb.el.on('click', function(e){
26175 e.preventDefault(); // what does this do?
26178 if(!this.disable.font && !Roo.isSafari){
26179 /* why no safari for fonts
26180 editor.fontSelect = tb.el.createChild({
26183 cls:'x-font-select',
26184 html: editor.createFontOptions()
26186 editor.fontSelect.on('change', function(){
26187 var font = editor.fontSelect.dom.value;
26188 editor.relayCmd('fontname', font);
26189 editor.deferFocus();
26192 editor.fontSelect.dom,
26197 if(!this.disable.formats){
26198 this.formatCombo = new Roo.form.ComboBox({
26199 store: new Roo.data.SimpleStore({
26202 data : this.formats // from states.js
26205 //autoCreate : {tag: "div", size: "20"},
26206 displayField:'tag',
26210 triggerAction: 'all',
26211 emptyText:'Add tag',
26212 selectOnFocus:true,
26215 'select': function(c, r, i) {
26216 editor.insertTag(r.get('tag'));
26222 tb.addField(this.formatCombo);
26226 if(!this.disable.format){
26233 if(!this.disable.fontSize){
26238 btn('increasefontsize', false, editor.adjustFont),
26239 btn('decreasefontsize', false, editor.adjustFont)
26244 if(!this.disable.colors){
26247 id:editor.frameId +'-forecolor',
26248 cls:'x-btn-icon x-edit-forecolor',
26249 clickEvent:'mousedown',
26250 tooltip: this.buttonTips['forecolor'] || undefined,
26252 menu : new Roo.menu.ColorMenu({
26253 allowReselect: true,
26254 focus: Roo.emptyFn,
26257 selectHandler: function(cp, color){
26258 editor.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
26259 editor.deferFocus();
26262 clickEvent:'mousedown'
26265 id:editor.frameId +'backcolor',
26266 cls:'x-btn-icon x-edit-backcolor',
26267 clickEvent:'mousedown',
26268 tooltip: this.buttonTips['backcolor'] || undefined,
26270 menu : new Roo.menu.ColorMenu({
26271 focus: Roo.emptyFn,
26274 allowReselect: true,
26275 selectHandler: function(cp, color){
26277 editor.execCmd('useCSS', false);
26278 editor.execCmd('hilitecolor', color);
26279 editor.execCmd('useCSS', true);
26280 editor.deferFocus();
26282 editor.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor',
26283 Roo.isSafari || Roo.isIE ? '#'+color : color);
26284 editor.deferFocus();
26288 clickEvent:'mousedown'
26293 // now add all the items...
26296 if(!this.disable.alignments){
26299 btn('justifyleft'),
26300 btn('justifycenter'),
26301 btn('justifyright')
26305 //if(!Roo.isSafari){
26306 if(!this.disable.links){
26309 btn('createlink', false, editor.createLink) /// MOVE TO HERE?!!?!?!?!
26313 if(!this.disable.lists){
26316 btn('insertorderedlist'),
26317 btn('insertunorderedlist')
26320 if(!this.disable.sourceEdit){
26323 btn('sourceedit', true, function(btn){
26324 this.toggleSourceEdit(btn.pressed);
26331 // special menu.. - needs to be tidied up..
26332 if (!this.disable.special) {
26335 cls: 'x-edit-none',
26341 for (var i =0; i < this.specialChars.length; i++) {
26342 smenu.menu.items.push({
26344 html: this.specialChars[i],
26345 handler: function(a,b) {
26346 editor.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
26347 //editor.insertAtCursor(a.html);
26360 if (!this.disable.specialElements) {
26363 cls: 'x-edit-none',
26368 for (var i =0; i < this.specialElements.length; i++) {
26369 semenu.menu.items.push(
26371 handler: function(a,b) {
26372 editor.insertAtCursor(this.ihtml);
26374 }, this.specialElements[i])
26386 for(var i =0; i< this.btns.length;i++) {
26387 var b = Roo.factory(this.btns[i],Roo.form);
26388 b.cls = 'x-edit-none';
26397 // disable everything...
26399 this.tb.items.each(function(item){
26400 if(item.id != editor.frameId+ '-sourceedit'){
26404 this.rendered = true;
26406 // the all the btns;
26407 editor.on('editorevent', this.updateToolbar, this);
26408 // other toolbars need to implement this..
26409 //editor.on('editmodechange', this.updateToolbar, this);
26415 * Protected method that will not generally be called directly. It triggers
26416 * a toolbar update by reading the markup state of the current selection in the editor.
26418 updateToolbar: function(){
26420 if(!this.editor.activated){
26421 this.editor.onFirstFocus();
26425 var btns = this.tb.items.map,
26426 doc = this.editor.doc,
26427 frameId = this.editor.frameId;
26429 if(!this.disable.font && !Roo.isSafari){
26431 var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
26432 if(name != this.fontSelect.dom.value){
26433 this.fontSelect.dom.value = name;
26437 if(!this.disable.format){
26438 btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
26439 btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
26440 btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
26442 if(!this.disable.alignments){
26443 btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
26444 btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
26445 btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
26447 if(!Roo.isSafari && !this.disable.lists){
26448 btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
26449 btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
26452 var ans = this.editor.getAllAncestors();
26453 if (this.formatCombo) {
26456 var store = this.formatCombo.store;
26457 this.formatCombo.setValue("");
26458 for (var i =0; i < ans.length;i++) {
26459 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
26461 this.formatCombo.setValue(ans[i].tagName.toLowerCase());
26469 // hides menus... - so this cant be on a menu...
26470 Roo.menu.MenuMgr.hideAll();
26472 //this.editorsyncValue();
26476 createFontOptions : function(){
26477 var buf = [], fs = this.fontFamilies, ff, lc;
26478 for(var i = 0, len = fs.length; i< len; i++){
26480 lc = ff.toLowerCase();
26482 '<option value="',lc,'" style="font-family:',ff,';"',
26483 (this.defaultFont == lc ? ' selected="true">' : '>'),
26488 return buf.join('');
26491 toggleSourceEdit : function(sourceEditMode){
26492 if(sourceEditMode === undefined){
26493 sourceEditMode = !this.sourceEditMode;
26495 this.sourceEditMode = sourceEditMode === true;
26496 var btn = this.tb.items.get(this.editor.frameId +'-sourceedit');
26497 // just toggle the button?
26498 if(btn.pressed !== this.editor.sourceEditMode){
26499 btn.toggle(this.editor.sourceEditMode);
26503 if(this.sourceEditMode){
26504 this.tb.items.each(function(item){
26505 if(item.cmd != 'sourceedit'){
26511 if(this.initialized){
26512 this.tb.items.each(function(item){
26518 // tell the editor that it's been pressed..
26519 this.editor.toggleSourceEdit(sourceEditMode);
26523 * Object collection of toolbar tooltips for the buttons in the editor. The key
26524 * is the command id associated with that button and the value is a valid QuickTips object.
26529 title: 'Bold (Ctrl+B)',
26530 text: 'Make the selected text bold.',
26531 cls: 'x-html-editor-tip'
26534 title: 'Italic (Ctrl+I)',
26535 text: 'Make the selected text italic.',
26536 cls: 'x-html-editor-tip'
26544 title: 'Bold (Ctrl+B)',
26545 text: 'Make the selected text bold.',
26546 cls: 'x-html-editor-tip'
26549 title: 'Italic (Ctrl+I)',
26550 text: 'Make the selected text italic.',
26551 cls: 'x-html-editor-tip'
26554 title: 'Underline (Ctrl+U)',
26555 text: 'Underline the selected text.',
26556 cls: 'x-html-editor-tip'
26558 increasefontsize : {
26559 title: 'Grow Text',
26560 text: 'Increase the font size.',
26561 cls: 'x-html-editor-tip'
26563 decreasefontsize : {
26564 title: 'Shrink Text',
26565 text: 'Decrease the font size.',
26566 cls: 'x-html-editor-tip'
26569 title: 'Text Highlight Color',
26570 text: 'Change the background color of the selected text.',
26571 cls: 'x-html-editor-tip'
26574 title: 'Font Color',
26575 text: 'Change the color of the selected text.',
26576 cls: 'x-html-editor-tip'
26579 title: 'Align Text Left',
26580 text: 'Align text to the left.',
26581 cls: 'x-html-editor-tip'
26584 title: 'Center Text',
26585 text: 'Center text in the editor.',
26586 cls: 'x-html-editor-tip'
26589 title: 'Align Text Right',
26590 text: 'Align text to the right.',
26591 cls: 'x-html-editor-tip'
26593 insertunorderedlist : {
26594 title: 'Bullet List',
26595 text: 'Start a bulleted list.',
26596 cls: 'x-html-editor-tip'
26598 insertorderedlist : {
26599 title: 'Numbered List',
26600 text: 'Start a numbered list.',
26601 cls: 'x-html-editor-tip'
26604 title: 'Hyperlink',
26605 text: 'Make the selected text a hyperlink.',
26606 cls: 'x-html-editor-tip'
26609 title: 'Source Edit',
26610 text: 'Switch to source editing mode.',
26611 cls: 'x-html-editor-tip'
26615 onDestroy : function(){
26618 this.tb.items.each(function(item){
26620 item.menu.removeAll();
26622 item.menu.el.destroy();
26630 onFirstFocus: function() {
26631 this.tb.items.each(function(item){
26640 // <script type="text/javascript">
26643 * Ext JS Library 1.1.1
26644 * Copyright(c) 2006-2007, Ext JS, LLC.
26651 * @class Roo.form.HtmlEditor.ToolbarContext
26656 new Roo.form.HtmlEditor({
26659 { xtype: 'ToolbarStandard', styles : {} }
26660 { xtype: 'ToolbarContext', disable : {} }
26666 * @config : {Object} disable List of elements to disable.. (not done yet.)
26667 * @config : {Object} styles Map of styles available.
26671 Roo.form.HtmlEditor.ToolbarContext = function(config)
26674 Roo.apply(this, config);
26675 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
26676 // dont call parent... till later.
26677 this.styles = this.styles || {};
26679 Roo.form.HtmlEditor.ToolbarContext.types = {
26691 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
26753 opts : [[""],[ "left"],[ "center"],[ "right"],[ "justify"],[ "char"]],
26758 opts : [[""],[ "top"],[ "middle"],[ "bottom"],[ "baseline"]],
26812 // should we really allow this??
26813 // should this just be
26828 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype, {
26836 * @cfg {Object} disable List of toolbar elements to disable
26841 * @cfg {Object} styles List of styles
26842 * eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] }
26844 * These must be defined in the page, so they get rendered correctly..
26855 init : function(editor)
26857 this.editor = editor;
26860 var fid = editor.frameId;
26862 function btn(id, toggle, handler){
26863 var xid = fid + '-'+ id ;
26867 cls : 'x-btn-icon x-edit-'+id,
26868 enableToggle:toggle !== false,
26869 scope: editor, // was editor...
26870 handler:handler||editor.relayBtnCmd,
26871 clickEvent:'mousedown',
26872 tooltip: etb.buttonTips[id] || undefined, ///tips ???
26876 // create a new element.
26877 var wdiv = editor.wrap.createChild({
26879 }, editor.wrap.dom.firstChild.nextSibling, true);
26881 // can we do this more than once??
26883 // stop form submits
26886 // disable everything...
26887 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
26888 this.toolbars = {};
26890 for (var i in ty) {
26892 this.toolbars[i] = this.buildToolbar(ty[i],i);
26894 this.tb = this.toolbars.BODY;
26896 this.buildFooter();
26897 this.footer.show();
26898 editor.on('hide', function( ) { this.footer.hide() }, this);
26899 editor.on('show', function( ) { this.footer.show() }, this);
26902 this.rendered = true;
26904 // the all the btns;
26905 editor.on('editorevent', this.updateToolbar, this);
26906 // other toolbars need to implement this..
26907 //editor.on('editmodechange', this.updateToolbar, this);
26913 * Protected method that will not generally be called directly. It triggers
26914 * a toolbar update by reading the markup state of the current selection in the editor.
26916 updateToolbar: function(editor,ev,sel){
26919 // capture mouse up - this is handy for selecting images..
26920 // perhaps should go somewhere else...
26921 if(!this.editor.activated){
26922 this.editor.onFirstFocus();
26926 // http://developer.yahoo.com/yui/docs/simple-editor.js.html
26927 // selectNode - might want to handle IE?
26929 (ev.type == 'mouseup' || ev.type == 'click' ) &&
26930 ev.target && ev.target.tagName == 'IMG') {
26931 // they have click on an image...
26932 // let's see if we can change the selection...
26935 var nodeRange = sel.ownerDocument.createRange();
26937 nodeRange.selectNode(sel);
26939 nodeRange.selectNodeContents(sel);
26941 //nodeRange.collapse(true);
26942 var s = editor.win.getSelection();
26943 s.removeAllRanges();
26944 s.addRange(nodeRange);
26948 var updateFooter = sel ? false : true;
26951 var ans = this.editor.getAllAncestors();
26954 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
26957 sel = ans.length ? (ans[0] ? ans[0] : ans[1]) : this.editor.doc.body;
26958 sel = sel ? sel : this.editor.doc.body;
26959 sel = sel.tagName.length ? sel : this.editor.doc.body;
26962 // pick a menu that exists..
26963 var tn = sel.tagName.toUpperCase();
26964 //sel = typeof(ty[tn]) != 'undefined' ? sel : this.editor.doc.body;
26966 tn = sel.tagName.toUpperCase();
26968 var lastSel = this.tb.selectedNode
26970 this.tb.selectedNode = sel;
26972 // if current menu does not match..
26973 if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode)) {
26976 ///console.log("show: " + tn);
26977 this.tb = typeof(ty[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
26980 this.tb.items.first().el.innerHTML = tn + ': ';
26983 // update attributes
26984 if (this.tb.fields) {
26985 this.tb.fields.each(function(e) {
26986 e.setValue(sel.getAttribute(e.attrname));
26990 var hasStyles = false;
26991 for(var i in this.styles) {
26998 var st = this.tb.fields.item(0);
27000 st.store.removeAll();
27003 var cn = sel.className.split(/\s+/);
27006 if (this.styles['*']) {
27008 Roo.each(this.styles['*'], function(v) {
27009 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
27012 if (this.styles[tn]) {
27013 Roo.each(this.styles[tn], function(v) {
27014 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
27018 st.store.loadData(avs);
27022 // flag our selected Node.
27023 this.tb.selectedNode = sel;
27026 Roo.menu.MenuMgr.hideAll();
27030 if (!updateFooter) {
27033 // update the footer
27037 this.footerEls = ans.reverse();
27038 Roo.each(this.footerEls, function(a,i) {
27039 if (!a) { return; }
27040 html += html.length ? ' > ' : '';
27042 html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
27047 var sz = this.footDisp.up('td').getSize();
27048 this.footDisp.dom.style.width = (sz.width -10) + 'px';
27049 this.footDisp.dom.style.marginLeft = '5px';
27051 this.footDisp.dom.style.overflow = 'hidden';
27053 this.footDisp.dom.innerHTML = html;
27055 //this.editorsyncValue();
27060 onDestroy : function(){
27063 this.tb.items.each(function(item){
27065 item.menu.removeAll();
27067 item.menu.el.destroy();
27075 onFirstFocus: function() {
27076 // need to do this for all the toolbars..
27077 this.tb.items.each(function(item){
27081 buildToolbar: function(tlist, nm)
27083 var editor = this.editor;
27084 // create a new element.
27085 var wdiv = editor.wrap.createChild({
27087 }, editor.wrap.dom.firstChild.nextSibling, true);
27090 var tb = new Roo.Toolbar(wdiv);
27093 tb.add(nm+ ": ");
27096 for(var i in this.styles) {
27101 if (styles && styles.length) {
27103 // this needs a multi-select checkbox...
27104 tb.addField( new Roo.form.ComboBox({
27105 store: new Roo.data.SimpleStore({
27107 fields: ['val', 'selected'],
27110 name : '-roo-edit-className',
27111 attrname : 'className',
27112 displayField:'val',
27116 triggerAction: 'all',
27117 emptyText:'Select Style',
27118 selectOnFocus:true,
27121 'select': function(c, r, i) {
27122 // initial support only for on class per el..
27123 tb.selectedNode.className = r ? r.get('val') : '';
27124 editor.syncValue();
27133 for (var i in tlist) {
27135 var item = tlist[i];
27136 tb.add(item.title + ": ");
27142 // opts == pulldown..
27143 tb.addField( new Roo.form.ComboBox({
27144 store: new Roo.data.SimpleStore({
27149 name : '-roo-edit-' + i,
27151 displayField:'val',
27155 triggerAction: 'all',
27156 emptyText:'Select',
27157 selectOnFocus:true,
27158 width: item.width ? item.width : 130,
27160 'select': function(c, r, i) {
27161 tb.selectedNode.setAttribute(c.attrname, r.get('val'));
27170 tb.addField( new Roo.form.TextField({
27173 //allowBlank:false,
27178 tb.addField( new Roo.form.TextField({
27179 name: '-roo-edit-' + i,
27186 'change' : function(f, nv, ov) {
27187 tb.selectedNode.setAttribute(f.attrname, nv);
27193 tb.el.on('click', function(e){
27194 e.preventDefault(); // what does this do?
27196 tb.el.setVisibilityMode( Roo.Element.DISPLAY);
27199 // dont need to disable them... as they will get hidden
27204 buildFooter : function()
27207 var fel = this.editor.wrap.createChild();
27208 this.footer = new Roo.Toolbar(fel);
27209 // toolbar has scrolly on left / right?
27210 var footDisp= new Roo.Toolbar.Fill();
27216 handler : function() {
27217 _t.footDisp.scrollTo('left',0,true)
27221 this.footer.add( footDisp );
27226 handler : function() {
27228 _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
27232 var fel = Roo.get(footDisp.el);
27233 fel.addClass('x-editor-context');
27234 this.footDispWrap = fel;
27235 this.footDispWrap.overflow = 'hidden';
27237 this.footDisp = fel.createChild();
27238 this.footDispWrap.on('click', this.onContextClick, this)
27242 onContextClick : function (ev,dom)
27244 ev.preventDefault();
27245 var cn = dom.className;
27247 if (!cn.match(/x-ed-loc-/)) {
27250 var n = cn.split('-').pop();
27251 var ans = this.footerEls;
27255 var range = this.editor.createRange();
27257 range.selectNodeContents(sel);
27258 //range.selectNode(sel);
27261 var selection = this.editor.getSelection();
27262 selection.removeAllRanges();
27263 selection.addRange(range);
27267 this.updateToolbar(null, null, sel);
27284 * Ext JS Library 1.1.1
27285 * Copyright(c) 2006-2007, Ext JS, LLC.
27287 * Originally Released Under LGPL - original licence link has changed is not relivant.
27290 * <script type="text/javascript">
27294 * @class Roo.form.BasicForm
27295 * @extends Roo.util.Observable
27296 * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
27298 * @param {String/HTMLElement/Roo.Element} el The form element or its id
27299 * @param {Object} config Configuration options
27301 Roo.form.BasicForm = function(el, config){
27302 this.allItems = [];
27303 this.childForms = [];
27304 Roo.apply(this, config);
27306 * The Roo.form.Field items in this form.
27307 * @type MixedCollection
27311 this.items = new Roo.util.MixedCollection(false, function(o){
27312 return o.id || (o.id = Roo.id());
27316 * @event beforeaction
27317 * Fires before any action is performed. Return false to cancel the action.
27318 * @param {Form} this
27319 * @param {Action} action The action to be performed
27321 beforeaction: true,
27323 * @event actionfailed
27324 * Fires when an action fails.
27325 * @param {Form} this
27326 * @param {Action} action The action that failed
27328 actionfailed : true,
27330 * @event actioncomplete
27331 * Fires when an action is completed.
27332 * @param {Form} this
27333 * @param {Action} action The action that completed
27335 actioncomplete : true
27340 Roo.form.BasicForm.superclass.constructor.call(this);
27343 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
27345 * @cfg {String} method
27346 * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
27349 * @cfg {DataReader} reader
27350 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
27351 * This is optional as there is built-in support for processing JSON.
27354 * @cfg {DataReader} errorReader
27355 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
27356 * This is completely optional as there is built-in support for processing JSON.
27359 * @cfg {String} url
27360 * The URL to use for form actions if one isn't supplied in the action options.
27363 * @cfg {Boolean} fileUpload
27364 * Set to true if this form is a file upload.
27368 * @cfg {Object} baseParams
27369 * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
27374 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
27379 activeAction : null,
27382 * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
27383 * or setValues() data instead of when the form was first created.
27385 trackResetOnLoad : false,
27389 * childForms - used for multi-tab forms
27392 childForms : false,
27395 * allItems - full list of fields.
27401 * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
27402 * element by passing it or its id or mask the form itself by passing in true.
27405 waitMsgTarget : false,
27408 initEl : function(el){
27409 this.el = Roo.get(el);
27410 this.id = this.el.id || Roo.id();
27411 this.el.on('submit', this.onSubmit, this);
27412 this.el.addClass('x-form');
27416 onSubmit : function(e){
27421 * Returns true if client-side validation on the form is successful.
27424 isValid : function(){
27426 this.items.each(function(f){
27435 * Returns true if any fields in this form have changed since their original load.
27438 isDirty : function(){
27440 this.items.each(function(f){
27450 * Performs a predefined action (submit or load) or custom actions you define on this form.
27451 * @param {String} actionName The name of the action type
27452 * @param {Object} options (optional) The options to pass to the action. All of the config options listed
27453 * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
27454 * accept other config options):
27456 Property Type Description
27457 ---------------- --------------- ----------------------------------------------------------------------------------
27458 url String The url for the action (defaults to the form's url)
27459 method String The form method to use (defaults to the form's method, or POST if not defined)
27460 params String/Object The params to pass (defaults to the form's baseParams, or none if not defined)
27461 clientValidation Boolean Applies to submit only. Pass true to call form.isValid() prior to posting to
27462 validate the form on the client (defaults to false)
27464 * @return {BasicForm} this
27466 doAction : function(action, options){
27467 if(typeof action == 'string'){
27468 action = new Roo.form.Action.ACTION_TYPES[action](this, options);
27470 if(this.fireEvent('beforeaction', this, action) !== false){
27471 this.beforeAction(action);
27472 action.run.defer(100, action);
27478 * Shortcut to do a submit action.
27479 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
27480 * @return {BasicForm} this
27482 submit : function(options){
27483 this.doAction('submit', options);
27488 * Shortcut to do a load action.
27489 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
27490 * @return {BasicForm} this
27492 load : function(options){
27493 this.doAction('load', options);
27498 * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
27499 * @param {Record} record The record to edit
27500 * @return {BasicForm} this
27502 updateRecord : function(record){
27503 record.beginEdit();
27504 var fs = record.fields;
27505 fs.each(function(f){
27506 var field = this.findField(f.name);
27508 record.set(f.name, field.getValue());
27516 * Loads an Roo.data.Record into this form.
27517 * @param {Record} record The record to load
27518 * @return {BasicForm} this
27520 loadRecord : function(record){
27521 this.setValues(record.data);
27526 beforeAction : function(action){
27527 var o = action.options;
27530 if(this.waitMsgTarget === true){
27531 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
27532 }else if(this.waitMsgTarget){
27533 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
27534 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
27536 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
27542 afterAction : function(action, success){
27543 this.activeAction = null;
27544 var o = action.options;
27546 if(this.waitMsgTarget === true){
27548 }else if(this.waitMsgTarget){
27549 this.waitMsgTarget.unmask();
27551 Roo.MessageBox.updateProgress(1);
27552 Roo.MessageBox.hide();
27559 Roo.callback(o.success, o.scope, [this, action]);
27560 this.fireEvent('actioncomplete', this, action);
27564 // failure condition..
27565 // we have a scenario where updates need confirming.
27566 // eg. if a locking scenario exists..
27567 // we look for { errors : { needs_confirm : true }} in the response.
27569 (typeof(action.result) != 'undefined') &&
27570 (typeof(action.result.errors) != 'undefined') &&
27571 (typeof(action.result.errors.needs_confirm) != 'undefined')
27574 Roo.MessageBox.confirm(
27575 "Change requires confirmation",
27576 action.result.errorMsg,
27581 _t.doAction('submit', { params : { _submit_confirmed : 1 } } );
27591 Roo.callback(o.failure, o.scope, [this, action]);
27592 // show an error message if no failed handler is set..
27593 if (!this.hasListener('actionfailed')) {
27594 Roo.MessageBox.alert("Error",
27595 (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
27596 action.result.errorMsg :
27597 "Saving Failed, please check your entries or try again"
27601 this.fireEvent('actionfailed', this, action);
27607 * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
27608 * @param {String} id The value to search for
27611 findField : function(id){
27612 var field = this.items.get(id);
27614 this.items.each(function(f){
27615 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
27621 return field || null;
27625 * Add a secondary form to this one,
27626 * Used to provide tabbed forms. One form is primary, with hidden values
27627 * which mirror the elements from the other forms.
27629 * @param {Roo.form.Form} form to add.
27632 addForm : function(form)
27635 if (this.childForms.indexOf(form) > -1) {
27639 this.childForms.push(form);
27641 Roo.each(form.allItems, function (fe) {
27643 n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
27644 if (this.findField(n)) { // already added..
27647 var add = new Roo.form.Hidden({
27650 add.render(this.el);
27657 * Mark fields in this form invalid in bulk.
27658 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
27659 * @return {BasicForm} this
27661 markInvalid : function(errors){
27662 if(errors instanceof Array){
27663 for(var i = 0, len = errors.length; i < len; i++){
27664 var fieldError = errors[i];
27665 var f = this.findField(fieldError.id);
27667 f.markInvalid(fieldError.msg);
27673 if(typeof errors[id] != 'function' && (field = this.findField(id))){
27674 field.markInvalid(errors[id]);
27678 Roo.each(this.childForms || [], function (f) {
27679 f.markInvalid(errors);
27686 * Set values for fields in this form in bulk.
27687 * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
27688 * @return {BasicForm} this
27690 setValues : function(values){
27691 if(values instanceof Array){ // array of objects
27692 for(var i = 0, len = values.length; i < len; i++){
27694 var f = this.findField(v.id);
27696 f.setValue(v.value);
27697 if(this.trackResetOnLoad){
27698 f.originalValue = f.getValue();
27702 }else{ // object hash
27705 if(typeof values[id] != 'function' && (field = this.findField(id))){
27707 if (field.setFromData &&
27708 field.valueField &&
27709 field.displayField &&
27710 // combos' with local stores can
27711 // be queried via setValue()
27712 // to set their value..
27713 (field.store && !field.store.isLocal)
27717 sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
27718 sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
27719 field.setFromData(sd);
27722 field.setValue(values[id]);
27726 if(this.trackResetOnLoad){
27727 field.originalValue = field.getValue();
27733 Roo.each(this.childForms || [], function (f) {
27734 f.setValues(values);
27741 * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
27742 * they are returned as an array.
27743 * @param {Boolean} asString
27746 getValues : function(asString){
27747 if (this.childForms) {
27748 // copy values from the child forms
27749 Roo.each(this.childForms, function (f) {
27750 this.setValues(f.getValues());
27756 var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
27757 if(asString === true){
27760 return Roo.urlDecode(fs);
27764 * Returns the fields in this form as an object with key/value pairs.
27765 * This differs from getValues as it calls getValue on each child item, rather than using dom data.
27768 getFieldValues : function(with_hidden)
27770 if (this.childForms) {
27771 // copy values from the child forms
27772 // should this call getFieldValues - probably not as we do not currently copy
27773 // hidden fields when we generate..
27774 Roo.each(this.childForms, function (f) {
27775 this.setValues(f.getValues());
27780 this.items.each(function(f){
27781 if (!f.getName()) {
27784 var v = f.getValue();
27785 // not sure if this supported any more..
27786 if ((typeof(v) == 'object') && f.getRawValue) {
27787 v = f.getRawValue() ; // dates..
27789 // combo boxes where name != hiddenName...
27790 if (f.name != f.getName()) {
27791 ret[f.name] = f.getRawValue();
27793 ret[f.getName()] = v;
27800 * Clears all invalid messages in this form.
27801 * @return {BasicForm} this
27803 clearInvalid : function(){
27804 this.items.each(function(f){
27808 Roo.each(this.childForms || [], function (f) {
27817 * Resets this form.
27818 * @return {BasicForm} this
27820 reset : function(){
27821 this.items.each(function(f){
27825 Roo.each(this.childForms || [], function (f) {
27834 * Add Roo.form components to this form.
27835 * @param {Field} field1
27836 * @param {Field} field2 (optional)
27837 * @param {Field} etc (optional)
27838 * @return {BasicForm} this
27841 this.items.addAll(Array.prototype.slice.call(arguments, 0));
27847 * Removes a field from the items collection (does NOT remove its markup).
27848 * @param {Field} field
27849 * @return {BasicForm} this
27851 remove : function(field){
27852 this.items.remove(field);
27857 * Looks at the fields in this form, checks them for an id attribute,
27858 * and calls applyTo on the existing dom element with that id.
27859 * @return {BasicForm} this
27861 render : function(){
27862 this.items.each(function(f){
27863 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
27871 * Calls {@link Ext#apply} for all fields in this form with the passed object.
27872 * @param {Object} values
27873 * @return {BasicForm} this
27875 applyToFields : function(o){
27876 this.items.each(function(f){
27883 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
27884 * @param {Object} values
27885 * @return {BasicForm} this
27887 applyIfToFields : function(o){
27888 this.items.each(function(f){
27896 Roo.BasicForm = Roo.form.BasicForm;/*
27898 * Ext JS Library 1.1.1
27899 * Copyright(c) 2006-2007, Ext JS, LLC.
27901 * Originally Released Under LGPL - original licence link has changed is not relivant.
27904 * <script type="text/javascript">
27908 * @class Roo.form.Form
27909 * @extends Roo.form.BasicForm
27910 * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
27912 * @param {Object} config Configuration options
27914 Roo.form.Form = function(config){
27916 if (config.items) {
27917 xitems = config.items;
27918 delete config.items;
27922 Roo.form.Form.superclass.constructor.call(this, null, config);
27923 this.url = this.url || this.action;
27925 this.root = new Roo.form.Layout(Roo.applyIf({
27929 this.active = this.root;
27931 * Array of all the buttons that have been added to this form via {@link addButton}
27935 this.allItems = [];
27938 * @event clientvalidation
27939 * If the monitorValid config option is true, this event fires repetitively to notify of valid state
27940 * @param {Form} this
27941 * @param {Boolean} valid true if the form has passed client-side validation
27943 clientvalidation: true,
27946 * Fires when the form is rendered
27947 * @param {Roo.form.Form} form
27952 if (this.progressUrl) {
27953 // push a hidden field onto the list of fields..
27957 name : 'UPLOAD_IDENTIFIER'
27962 Roo.each(xitems, this.addxtype, this);
27968 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
27970 * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
27973 * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
27976 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
27978 buttonAlign:'center',
27981 * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
27986 * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
27987 * This property cascades to child containers if not set.
27992 * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
27993 * fires a looping event with that state. This is required to bind buttons to the valid
27994 * state using the config value formBind:true on the button.
27996 monitorValid : false,
27999 * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
28004 * @cfg {String} progressUrl - Url to return progress data
28007 progressUrl : false,
28010 * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
28011 * fields are added and the column is closed. If no fields are passed the column remains open
28012 * until end() is called.
28013 * @param {Object} config The config to pass to the column
28014 * @param {Field} field1 (optional)
28015 * @param {Field} field2 (optional)
28016 * @param {Field} etc (optional)
28017 * @return Column The column container object
28019 column : function(c){
28020 var col = new Roo.form.Column(c);
28022 if(arguments.length > 1){ // duplicate code required because of Opera
28023 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
28030 * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
28031 * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
28032 * until end() is called.
28033 * @param {Object} config The config to pass to the fieldset
28034 * @param {Field} field1 (optional)
28035 * @param {Field} field2 (optional)
28036 * @param {Field} etc (optional)
28037 * @return FieldSet The fieldset container object
28039 fieldset : function(c){
28040 var fs = new Roo.form.FieldSet(c);
28042 if(arguments.length > 1){ // duplicate code required because of Opera
28043 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
28050 * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
28051 * fields are added and the container is closed. If no fields are passed the container remains open
28052 * until end() is called.
28053 * @param {Object} config The config to pass to the Layout
28054 * @param {Field} field1 (optional)
28055 * @param {Field} field2 (optional)
28056 * @param {Field} etc (optional)
28057 * @return Layout The container object
28059 container : function(c){
28060 var l = new Roo.form.Layout(c);
28062 if(arguments.length > 1){ // duplicate code required because of Opera
28063 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
28070 * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
28071 * @param {Object} container A Roo.form.Layout or subclass of Layout
28072 * @return {Form} this
28074 start : function(c){
28075 // cascade label info
28076 Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
28077 this.active.stack.push(c);
28078 c.ownerCt = this.active;
28084 * Closes the current open container
28085 * @return {Form} this
28088 if(this.active == this.root){
28091 this.active = this.active.ownerCt;
28096 * Add Roo.form components to the current open container (e.g. column, fieldset, etc.). Fields added via this method
28097 * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
28098 * as the label of the field.
28099 * @param {Field} field1
28100 * @param {Field} field2 (optional)
28101 * @param {Field} etc. (optional)
28102 * @return {Form} this
28105 this.active.stack.push.apply(this.active.stack, arguments);
28106 this.allItems.push.apply(this.allItems,arguments);
28108 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
28109 if(a[i].isFormField){
28114 Roo.form.Form.superclass.add.apply(this, r);
28124 * Find any element that has been added to a form, using it's ID or name
28125 * This can include framesets, columns etc. along with regular fields..
28126 * @param {String} id - id or name to find.
28128 * @return {Element} e - or false if nothing found.
28130 findbyId : function(id)
28136 Roo.each(this.allItems, function(f){
28137 if (f.id == id || f.name == id ){
28148 * Render this form into the passed container. This should only be called once!
28149 * @param {String/HTMLElement/Element} container The element this component should be rendered into
28150 * @return {Form} this
28152 render : function(ct)
28158 var o = this.autoCreate || {
28160 method : this.method || 'POST',
28161 id : this.id || Roo.id()
28163 this.initEl(ct.createChild(o));
28165 this.root.render(this.el);
28169 this.items.each(function(f){
28170 f.render('x-form-el-'+f.id);
28173 if(this.buttons.length > 0){
28174 // tables are required to maintain order and for correct IE layout
28175 var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
28176 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
28177 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
28179 var tr = tb.getElementsByTagName('tr')[0];
28180 for(var i = 0, len = this.buttons.length; i < len; i++) {
28181 var b = this.buttons[i];
28182 var td = document.createElement('td');
28183 td.className = 'x-form-btn-td';
28184 b.render(tr.appendChild(td));
28187 if(this.monitorValid){ // initialize after render
28188 this.startMonitoring();
28190 this.fireEvent('rendered', this);
28195 * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
28196 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
28197 * object or a valid Roo.DomHelper element config
28198 * @param {Function} handler The function called when the button is clicked
28199 * @param {Object} scope (optional) The scope of the handler function
28200 * @return {Roo.Button}
28202 addButton : function(config, handler, scope){
28206 minWidth: this.minButtonWidth,
28209 if(typeof config == "string"){
28212 Roo.apply(bc, config);
28214 var btn = new Roo.Button(null, bc);
28215 this.buttons.push(btn);
28220 * Adds a series of form elements (using the xtype property as the factory method.
28221 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
28222 * @param {Object} config
28225 addxtype : function()
28227 var ar = Array.prototype.slice.call(arguments, 0);
28229 for(var i = 0; i < ar.length; i++) {
28231 continue; // skip -- if this happends something invalid got sent, we
28232 // should ignore it, as basically that interface element will not show up
28233 // and that should be pretty obvious!!
28236 if (Roo.form[ar[i].xtype]) {
28238 var fe = Roo.factory(ar[i], Roo.form);
28244 fe.store.form = this;
28249 this.allItems.push(fe);
28250 if (fe.items && fe.addxtype) {
28251 fe.addxtype.apply(fe, fe.items);
28261 // console.log('adding ' + ar[i].xtype);
28263 if (ar[i].xtype == 'Button') {
28264 //console.log('adding button');
28265 //console.log(ar[i]);
28266 this.addButton(ar[i]);
28267 this.allItems.push(fe);
28271 if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
28272 alert('end is not supported on xtype any more, use items');
28274 // //console.log('adding end');
28282 * Starts monitoring of the valid state of this form. Usually this is done by passing the config
28283 * option "monitorValid"
28285 startMonitoring : function(){
28288 Roo.TaskMgr.start({
28289 run : this.bindHandler,
28290 interval : this.monitorPoll || 200,
28297 * Stops monitoring of the valid state of this form
28299 stopMonitoring : function(){
28300 this.bound = false;
28304 bindHandler : function(){
28306 return false; // stops binding
28309 this.items.each(function(f){
28310 if(!f.isValid(true)){
28315 for(var i = 0, len = this.buttons.length; i < len; i++){
28316 var btn = this.buttons[i];
28317 if(btn.formBind === true && btn.disabled === valid){
28318 btn.setDisabled(!valid);
28321 this.fireEvent('clientvalidation', this, valid);
28335 Roo.Form = Roo.form.Form;
28338 * Ext JS Library 1.1.1
28339 * Copyright(c) 2006-2007, Ext JS, LLC.
28341 * Originally Released Under LGPL - original licence link has changed is not relivant.
28344 * <script type="text/javascript">
28348 * @class Roo.form.Action
28349 * Internal Class used to handle form actions
28351 * @param {Roo.form.BasicForm} el The form element or its id
28352 * @param {Object} config Configuration options
28356 // define the action interface
28357 Roo.form.Action = function(form, options){
28359 this.options = options || {};
28362 * Client Validation Failed
28365 Roo.form.Action.CLIENT_INVALID = 'client';
28367 * Server Validation Failed
28370 Roo.form.Action.SERVER_INVALID = 'server';
28372 * Connect to Server Failed
28375 Roo.form.Action.CONNECT_FAILURE = 'connect';
28377 * Reading Data from Server Failed
28380 Roo.form.Action.LOAD_FAILURE = 'load';
28382 Roo.form.Action.prototype = {
28384 failureType : undefined,
28385 response : undefined,
28386 result : undefined,
28388 // interface method
28389 run : function(options){
28393 // interface method
28394 success : function(response){
28398 // interface method
28399 handleResponse : function(response){
28403 // default connection failure
28404 failure : function(response){
28406 this.response = response;
28407 this.failureType = Roo.form.Action.CONNECT_FAILURE;
28408 this.form.afterAction(this, false);
28411 processResponse : function(response){
28412 this.response = response;
28413 if(!response.responseText){
28416 this.result = this.handleResponse(response);
28417 return this.result;
28420 // utility functions used internally
28421 getUrl : function(appendParams){
28422 var url = this.options.url || this.form.url || this.form.el.dom.action;
28424 var p = this.getParams();
28426 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
28432 getMethod : function(){
28433 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
28436 getParams : function(){
28437 var bp = this.form.baseParams;
28438 var p = this.options.params;
28440 if(typeof p == "object"){
28441 p = Roo.urlEncode(Roo.applyIf(p, bp));
28442 }else if(typeof p == 'string' && bp){
28443 p += '&' + Roo.urlEncode(bp);
28446 p = Roo.urlEncode(bp);
28451 createCallback : function(){
28453 success: this.success,
28454 failure: this.failure,
28456 timeout: (this.form.timeout*1000),
28457 upload: this.form.fileUpload ? this.success : undefined
28462 Roo.form.Action.Submit = function(form, options){
28463 Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
28466 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
28469 haveProgress : false,
28470 uploadComplete : false,
28472 // uploadProgress indicator.
28473 uploadProgress : function()
28475 if (!this.form.progressUrl) {
28479 if (!this.haveProgress) {
28480 Roo.MessageBox.progress("Uploading", "Uploading");
28482 if (this.uploadComplete) {
28483 Roo.MessageBox.hide();
28487 this.haveProgress = true;
28489 var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
28491 var c = new Roo.data.Connection();
28493 url : this.form.progressUrl,
28498 success : function(req){
28499 //console.log(data);
28503 rdata = Roo.decode(req.responseText)
28505 Roo.log("Invalid data from server..");
28509 if (!rdata || !rdata.success) {
28513 var data = rdata.data;
28515 if (this.uploadComplete) {
28516 Roo.MessageBox.hide();
28521 Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
28522 Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
28525 this.uploadProgress.defer(2000,this);
28528 failure: function(data) {
28529 Roo.log('progress url failed ');
28540 // run get Values on the form, so it syncs any secondary forms.
28541 this.form.getValues();
28543 var o = this.options;
28544 var method = this.getMethod();
28545 var isPost = method == 'POST';
28546 if(o.clientValidation === false || this.form.isValid()){
28548 if (this.form.progressUrl) {
28549 this.form.findField('UPLOAD_IDENTIFIER').setValue(
28550 (new Date() * 1) + '' + Math.random());
28555 Roo.Ajax.request(Roo.apply(this.createCallback(), {
28556 form:this.form.el.dom,
28557 url:this.getUrl(!isPost),
28559 params:isPost ? this.getParams() : null,
28560 isUpload: this.form.fileUpload
28563 this.uploadProgress();
28565 }else if (o.clientValidation !== false){ // client validation failed
28566 this.failureType = Roo.form.Action.CLIENT_INVALID;
28567 this.form.afterAction(this, false);
28571 success : function(response)
28573 this.uploadComplete= true;
28574 if (this.haveProgress) {
28575 Roo.MessageBox.hide();
28579 var result = this.processResponse(response);
28580 if(result === true || result.success){
28581 this.form.afterAction(this, true);
28585 this.form.markInvalid(result.errors);
28586 this.failureType = Roo.form.Action.SERVER_INVALID;
28588 this.form.afterAction(this, false);
28590 failure : function(response)
28592 this.uploadComplete= true;
28593 if (this.haveProgress) {
28594 Roo.MessageBox.hide();
28597 this.response = response;
28598 this.failureType = Roo.form.Action.CONNECT_FAILURE;
28599 this.form.afterAction(this, false);
28602 handleResponse : function(response){
28603 if(this.form.errorReader){
28604 var rs = this.form.errorReader.read(response);
28607 for(var i = 0, len = rs.records.length; i < len; i++) {
28608 var r = rs.records[i];
28609 errors[i] = r.data;
28612 if(errors.length < 1){
28616 success : rs.success,
28622 ret = Roo.decode(response.responseText);
28626 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
28636 Roo.form.Action.Load = function(form, options){
28637 Roo.form.Action.Load.superclass.constructor.call(this, form, options);
28638 this.reader = this.form.reader;
28641 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
28646 Roo.Ajax.request(Roo.apply(
28647 this.createCallback(), {
28648 method:this.getMethod(),
28649 url:this.getUrl(false),
28650 params:this.getParams()
28654 success : function(response){
28656 var result = this.processResponse(response);
28657 if(result === true || !result.success || !result.data){
28658 this.failureType = Roo.form.Action.LOAD_FAILURE;
28659 this.form.afterAction(this, false);
28662 this.form.clearInvalid();
28663 this.form.setValues(result.data);
28664 this.form.afterAction(this, true);
28667 handleResponse : function(response){
28668 if(this.form.reader){
28669 var rs = this.form.reader.read(response);
28670 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
28672 success : rs.success,
28676 return Roo.decode(response.responseText);
28680 Roo.form.Action.ACTION_TYPES = {
28681 'load' : Roo.form.Action.Load,
28682 'submit' : Roo.form.Action.Submit
28685 * Ext JS Library 1.1.1
28686 * Copyright(c) 2006-2007, Ext JS, LLC.
28688 * Originally Released Under LGPL - original licence link has changed is not relivant.
28691 * <script type="text/javascript">
28695 * @class Roo.form.Layout
28696 * @extends Roo.Component
28697 * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
28699 * @param {Object} config Configuration options
28701 Roo.form.Layout = function(config){
28703 if (config.items) {
28704 xitems = config.items;
28705 delete config.items;
28707 Roo.form.Layout.superclass.constructor.call(this, config);
28709 Roo.each(xitems, this.addxtype, this);
28713 Roo.extend(Roo.form.Layout, Roo.Component, {
28715 * @cfg {String/Object} autoCreate
28716 * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
28719 * @cfg {String/Object/Function} style
28720 * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
28721 * a function which returns such a specification.
28724 * @cfg {String} labelAlign
28725 * Valid values are "left," "top" and "right" (defaults to "left")
28728 * @cfg {Number} labelWidth
28729 * Fixed width in pixels of all field labels (defaults to undefined)
28732 * @cfg {Boolean} clear
28733 * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
28737 * @cfg {String} labelSeparator
28738 * The separator to use after field labels (defaults to ':')
28740 labelSeparator : ':',
28742 * @cfg {Boolean} hideLabels
28743 * True to suppress the display of field labels in this layout (defaults to false)
28745 hideLabels : false,
28748 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
28753 onRender : function(ct, position){
28754 if(this.el){ // from markup
28755 this.el = Roo.get(this.el);
28756 }else { // generate
28757 var cfg = this.getAutoCreate();
28758 this.el = ct.createChild(cfg, position);
28761 this.el.applyStyles(this.style);
28763 if(this.labelAlign){
28764 this.el.addClass('x-form-label-'+this.labelAlign);
28766 if(this.hideLabels){
28767 this.labelStyle = "display:none";
28768 this.elementStyle = "padding-left:0;";
28770 if(typeof this.labelWidth == 'number'){
28771 this.labelStyle = "width:"+this.labelWidth+"px;";
28772 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
28774 if(this.labelAlign == 'top'){
28775 this.labelStyle = "width:auto;";
28776 this.elementStyle = "padding-left:0;";
28779 var stack = this.stack;
28780 var slen = stack.length;
28782 if(!this.fieldTpl){
28783 var t = new Roo.Template(
28784 '<div class="x-form-item {5}">',
28785 '<label for="{0}" style="{2}">{1}{4}</label>',
28786 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
28788 '</div><div class="x-form-clear-left"></div>'
28790 t.disableFormats = true;
28792 Roo.form.Layout.prototype.fieldTpl = t;
28794 for(var i = 0; i < slen; i++) {
28795 if(stack[i].isFormField){
28796 this.renderField(stack[i]);
28798 this.renderComponent(stack[i]);
28803 this.el.createChild({cls:'x-form-clear'});
28808 renderField : function(f){
28809 f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
28812 f.labelStyle||this.labelStyle||'', //2
28813 this.elementStyle||'', //3
28814 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
28815 f.itemCls||this.itemCls||'' //5
28816 ], true).getPrevSibling());
28820 renderComponent : function(c){
28821 c.render(c.isLayout ? this.el : this.el.createChild());
28824 * Adds a object form elements (using the xtype property as the factory method.)
28825 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column
28826 * @param {Object} config
28828 addxtype : function(o)
28830 // create the lement.
28831 o.form = this.form;
28832 var fe = Roo.factory(o, Roo.form);
28833 this.form.allItems.push(fe);
28834 this.stack.push(fe);
28836 if (fe.isFormField) {
28837 this.form.items.add(fe);
28845 * @class Roo.form.Column
28846 * @extends Roo.form.Layout
28847 * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
28849 * @param {Object} config Configuration options
28851 Roo.form.Column = function(config){
28852 Roo.form.Column.superclass.constructor.call(this, config);
28855 Roo.extend(Roo.form.Column, Roo.form.Layout, {
28857 * @cfg {Number/String} width
28858 * The fixed width of the column in pixels or CSS value (defaults to "auto")
28861 * @cfg {String/Object} autoCreate
28862 * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
28866 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
28869 onRender : function(ct, position){
28870 Roo.form.Column.superclass.onRender.call(this, ct, position);
28872 this.el.setWidth(this.width);
28879 * @class Roo.form.Row
28880 * @extends Roo.form.Layout
28881 * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
28883 * @param {Object} config Configuration options
28887 Roo.form.Row = function(config){
28888 Roo.form.Row.superclass.constructor.call(this, config);
28891 Roo.extend(Roo.form.Row, Roo.form.Layout, {
28893 * @cfg {Number/String} width
28894 * The fixed width of the column in pixels or CSS value (defaults to "auto")
28897 * @cfg {Number/String} height
28898 * The fixed height of the column in pixels or CSS value (defaults to "auto")
28900 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
28904 onRender : function(ct, position){
28905 //console.log('row render');
28907 var t = new Roo.Template(
28908 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
28909 '<label for="{0}" style="{2}">{1}{4}</label>',
28910 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
28914 t.disableFormats = true;
28916 Roo.form.Layout.prototype.rowTpl = t;
28918 this.fieldTpl = this.rowTpl;
28920 //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
28921 var labelWidth = 100;
28923 if ((this.labelAlign != 'top')) {
28924 if (typeof this.labelWidth == 'number') {
28925 labelWidth = this.labelWidth
28927 this.padWidth = 20 + labelWidth;
28931 Roo.form.Column.superclass.onRender.call(this, ct, position);
28933 this.el.setWidth(this.width);
28936 this.el.setHeight(this.height);
28941 renderField : function(f){
28942 f.fieldEl = this.fieldTpl.append(this.el, [
28943 f.id, f.fieldLabel,
28944 f.labelStyle||this.labelStyle||'',
28945 this.elementStyle||'',
28946 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
28947 f.itemCls||this.itemCls||'',
28948 f.width ? f.width + this.padWidth : 160 + this.padWidth
28955 * @class Roo.form.FieldSet
28956 * @extends Roo.form.Layout
28957 * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
28959 * @param {Object} config Configuration options
28961 Roo.form.FieldSet = function(config){
28962 Roo.form.FieldSet.superclass.constructor.call(this, config);
28965 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
28967 * @cfg {String} legend
28968 * The text to display as the legend for the FieldSet (defaults to '')
28971 * @cfg {String/Object} autoCreate
28972 * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
28976 defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
28979 onRender : function(ct, position){
28980 Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
28982 this.setLegend(this.legend);
28987 setLegend : function(text){
28989 this.el.child('legend').update(text);
28994 * Ext JS Library 1.1.1
28995 * Copyright(c) 2006-2007, Ext JS, LLC.
28997 * Originally Released Under LGPL - original licence link has changed is not relivant.
29000 * <script type="text/javascript">
29003 * @class Roo.form.VTypes
29004 * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
29007 Roo.form.VTypes = function(){
29008 // closure these in so they are only created once.
29009 var alpha = /^[a-zA-Z_]+$/;
29010 var alphanum = /^[a-zA-Z0-9_]+$/;
29011 var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/;
29012 var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
29014 // All these messages and functions are configurable
29017 * The function used to validate email addresses
29018 * @param {String} value The email address
29020 'email' : function(v){
29021 return email.test(v);
29024 * The error text to display when the email validation function returns false
29027 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
29029 * The keystroke filter mask to be applied on email input
29032 'emailMask' : /[a-z0-9_\.\-@]/i,
29035 * The function used to validate URLs
29036 * @param {String} value The URL
29038 'url' : function(v){
29039 return url.test(v);
29042 * The error text to display when the url validation function returns false
29045 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
29048 * The function used to validate alpha values
29049 * @param {String} value The value
29051 'alpha' : function(v){
29052 return alpha.test(v);
29055 * The error text to display when the alpha validation function returns false
29058 'alphaText' : 'This field should only contain letters and _',
29060 * The keystroke filter mask to be applied on alpha input
29063 'alphaMask' : /[a-z_]/i,
29066 * The function used to validate alphanumeric values
29067 * @param {String} value The value
29069 'alphanum' : function(v){
29070 return alphanum.test(v);
29073 * The error text to display when the alphanumeric validation function returns false
29076 'alphanumText' : 'This field should only contain letters, numbers and _',
29078 * The keystroke filter mask to be applied on alphanumeric input
29081 'alphanumMask' : /[a-z0-9_]/i
29083 }();//<script type="text/javascript">
29086 * @class Roo.form.FCKeditor
29087 * @extends Roo.form.TextArea
29088 * Wrapper around the FCKEditor http://www.fckeditor.net
29090 * Creates a new FCKeditor
29091 * @param {Object} config Configuration options
29093 Roo.form.FCKeditor = function(config){
29094 Roo.form.FCKeditor.superclass.constructor.call(this, config);
29097 * @event editorinit
29098 * Fired when the editor is initialized - you can add extra handlers here..
29099 * @param {FCKeditor} this
29100 * @param {Object} the FCK object.
29107 Roo.form.FCKeditor.editors = { };
29108 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
29110 //defaultAutoCreate : {
29111 // tag : "textarea",style : "width:100px;height:60px;" ,autocomplete : "off"
29115 * @cfg {Object} fck options - see fck manual for details.
29120 * @cfg {Object} fck toolbar set (Basic or Default)
29122 toolbarSet : 'Basic',
29124 * @cfg {Object} fck BasePath
29126 basePath : '/fckeditor/',
29134 onRender : function(ct, position)
29137 this.defaultAutoCreate = {
29139 style:"width:300px;height:60px;",
29140 autocomplete: "off"
29143 Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
29146 this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
29147 if(this.preventScrollbars){
29148 this.el.setStyle("overflow", "hidden");
29150 this.el.setHeight(this.growMin);
29153 //console.log('onrender' + this.getId() );
29154 Roo.form.FCKeditor.editors[this.getId()] = this;
29157 this.replaceTextarea() ;
29161 getEditor : function() {
29162 return this.fckEditor;
29165 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
29166 * @param {Mixed} value The value to set
29170 setValue : function(value)
29172 //console.log('setValue: ' + value);
29174 if(typeof(value) == 'undefined') { // not sure why this is happending...
29177 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
29179 //if(!this.el || !this.getEditor()) {
29180 // this.value = value;
29181 //this.setValue.defer(100,this,[value]);
29185 if(!this.getEditor()) {
29189 this.getEditor().SetData(value);
29196 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
29197 * @return {Mixed} value The field value
29199 getValue : function()
29202 if (this.frame && this.frame.dom.style.display == 'none') {
29203 return Roo.form.FCKeditor.superclass.getValue.call(this);
29206 if(!this.el || !this.getEditor()) {
29208 // this.getValue.defer(100,this);
29213 var value=this.getEditor().GetData();
29214 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
29215 return Roo.form.FCKeditor.superclass.getValue.call(this);
29221 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
29222 * @return {Mixed} value The field value
29224 getRawValue : function()
29226 if (this.frame && this.frame.dom.style.display == 'none') {
29227 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
29230 if(!this.el || !this.getEditor()) {
29231 //this.getRawValue.defer(100,this);
29238 var value=this.getEditor().GetData();
29239 Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
29240 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
29244 setSize : function(w,h) {
29248 //if (this.frame && this.frame.dom.style.display == 'none') {
29249 // Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
29252 //if(!this.el || !this.getEditor()) {
29253 // this.setSize.defer(100,this, [w,h]);
29259 Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
29261 this.frame.dom.setAttribute('width', w);
29262 this.frame.dom.setAttribute('height', h);
29263 this.frame.setSize(w,h);
29267 toggleSourceEdit : function(value) {
29271 this.el.dom.style.display = value ? '' : 'none';
29272 this.frame.dom.style.display = value ? 'none' : '';
29277 focus: function(tag)
29279 if (this.frame.dom.style.display == 'none') {
29280 return Roo.form.FCKeditor.superclass.focus.call(this);
29282 if(!this.el || !this.getEditor()) {
29283 this.focus.defer(100,this, [tag]);
29290 var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
29291 this.getEditor().Focus();
29293 if (!this.getEditor().Selection.GetSelection()) {
29294 this.focus.defer(100,this, [tag]);
29299 var r = this.getEditor().EditorDocument.createRange();
29300 r.setStart(tgs[0],0);
29301 r.setEnd(tgs[0],0);
29302 this.getEditor().Selection.GetSelection().removeAllRanges();
29303 this.getEditor().Selection.GetSelection().addRange(r);
29304 this.getEditor().Focus();
29311 replaceTextarea : function()
29313 if ( document.getElementById( this.getId() + '___Frame' ) )
29315 //if ( !this.checkBrowser || this._isCompatibleBrowser() )
29317 // We must check the elements firstly using the Id and then the name.
29318 var oTextarea = document.getElementById( this.getId() );
29320 var colElementsByName = document.getElementsByName( this.getId() ) ;
29322 oTextarea.style.display = 'none' ;
29324 if ( oTextarea.tabIndex ) {
29325 this.TabIndex = oTextarea.tabIndex ;
29328 this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
29329 this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
29330 this.frame = Roo.get(this.getId() + '___Frame')
29333 _getConfigHtml : function()
29337 for ( var o in this.fckconfig ) {
29338 sConfig += sConfig.length > 0 ? '&' : '';
29339 sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
29342 return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
29346 _getIFrameHtml : function()
29348 var sFile = 'fckeditor.html' ;
29349 /* no idea what this is about..
29352 if ( (/fcksource=true/i).test( window.top.location.search ) )
29353 sFile = 'fckeditor.original.html' ;
29358 var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
29359 sLink += this.toolbarSet ? ( '&Toolbar=' + this.toolbarSet) : '';
29362 var html = '<iframe id="' + this.getId() +
29363 '___Frame" src="' + sLink +
29364 '" width="' + this.width +
29365 '" height="' + this.height + '"' +
29366 (this.tabIndex ? ' tabindex="' + this.tabIndex + '"' :'' ) +
29367 ' frameborder="0" scrolling="no"></iframe>' ;
29372 _insertHtmlBefore : function( html, element )
29374 if ( element.insertAdjacentHTML ) {
29376 element.insertAdjacentHTML( 'beforeBegin', html ) ;
29378 var oRange = document.createRange() ;
29379 oRange.setStartBefore( element ) ;
29380 var oFragment = oRange.createContextualFragment( html );
29381 element.parentNode.insertBefore( oFragment, element ) ;
29394 //Roo.reg('fckeditor', Roo.form.FCKeditor);
29396 function FCKeditor_OnComplete(editorInstance){
29397 var f = Roo.form.FCKeditor.editors[editorInstance.Name];
29398 f.fckEditor = editorInstance;
29399 //console.log("loaded");
29400 f.fireEvent('editorinit', f, editorInstance);
29420 //<script type="text/javascript">
29422 * @class Roo.form.GridField
29423 * @extends Roo.form.Field
29424 * Embed a grid (or editable grid into a form)
29427 * This embeds a grid in a form, the value of the field should be the json encoded array of rows
29429 * xgrid.store = Roo.data.Store
29430 * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
29431 * xgrid.store.reader = Roo.data.JsonReader
29435 * Creates a new GridField
29436 * @param {Object} config Configuration options
29438 Roo.form.GridField = function(config){
29439 Roo.form.GridField.superclass.constructor.call(this, config);
29443 Roo.extend(Roo.form.GridField, Roo.form.Field, {
29445 * @cfg {Number} width - used to restrict width of grid..
29449 * @cfg {Number} height - used to restrict height of grid..
29453 * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
29459 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
29460 * {tag: "input", type: "checkbox", autocomplete: "off"})
29462 // defaultAutoCreate : { tag: 'div' },
29463 defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
29465 * @cfg {String} addTitle Text to include for adding a title.
29469 onResize : function(){
29470 Roo.form.Field.superclass.onResize.apply(this, arguments);
29473 initEvents : function(){
29474 // Roo.form.Checkbox.superclass.initEvents.call(this);
29475 // has no events...
29480 getResizeEl : function(){
29484 getPositionEl : function(){
29489 onRender : function(ct, position){
29491 this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
29492 var style = this.style;
29495 Roo.form.GridField.superclass.onRender.call(this, ct, position);
29496 this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
29497 this.viewEl = this.wrap.createChild({ tag: 'div' });
29499 this.viewEl.applyStyles(style);
29502 this.viewEl.setWidth(this.width);
29505 this.viewEl.setHeight(this.height);
29507 //if(this.inputValue !== undefined){
29508 //this.setValue(this.value);
29511 this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
29514 this.grid.render();
29515 this.grid.getDataSource().on('remove', this.refreshValue, this);
29516 this.grid.getDataSource().on('update', this.refreshValue, this);
29517 this.grid.on('afteredit', this.refreshValue, this);
29523 * Sets the value of the item.
29524 * @param {String} either an object or a string..
29526 setValue : function(v){
29528 v = v || []; // empty set..
29529 // this does not seem smart - it really only affects memoryproxy grids..
29530 if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
29531 var ds = this.grid.getDataSource();
29532 // assumes a json reader..
29534 data[ds.reader.meta.root ] = typeof(v) == 'string' ? Roo.decode(v) : v;
29535 ds.loadData( data);
29537 // clear selection so it does not get stale.
29538 if (this.grid.sm) {
29539 this.grid.sm.clearSelections();
29542 Roo.form.GridField.superclass.setValue.call(this, v);
29543 this.refreshValue();
29544 // should load data in the grid really....
29548 refreshValue: function() {
29550 this.grid.getDataSource().each(function(r) {
29553 this.el.dom.value = Roo.encode(val);
29561 * Ext JS Library 1.1.1
29562 * Copyright(c) 2006-2007, Ext JS, LLC.
29564 * Originally Released Under LGPL - original licence link has changed is not relivant.
29567 * <script type="text/javascript">
29570 * @class Roo.form.DisplayField
29571 * @extends Roo.form.Field
29572 * A generic Field to display non-editable data.
29574 * Creates a new Display Field item.
29575 * @param {Object} config Configuration options
29577 Roo.form.DisplayField = function(config){
29578 Roo.form.DisplayField.superclass.constructor.call(this, config);
29582 Roo.extend(Roo.form.DisplayField, Roo.form.TextField, {
29583 inputType: 'hidden',
29589 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
29591 focusClass : undefined,
29593 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
29595 fieldClass: 'x-form-field',
29598 * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
29600 valueRenderer: undefined,
29604 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
29605 * {tag: "input", type: "checkbox", autocomplete: "off"})
29608 // defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
29610 onResize : function(){
29611 Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
29615 initEvents : function(){
29616 // Roo.form.Checkbox.superclass.initEvents.call(this);
29617 // has no events...
29622 getResizeEl : function(){
29626 getPositionEl : function(){
29631 onRender : function(ct, position){
29633 Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
29634 //if(this.inputValue !== undefined){
29635 this.wrap = this.el.wrap();
29637 this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
29639 if (this.bodyStyle) {
29640 this.viewEl.applyStyles(this.bodyStyle);
29642 //this.viewEl.setStyle('padding', '2px');
29644 this.setValue(this.value);
29649 initValue : Roo.emptyFn,
29654 onClick : function(){
29659 * Sets the checked state of the checkbox.
29660 * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
29662 setValue : function(v){
29664 var html = this.valueRenderer ? this.valueRenderer(v) : String.format('{0}', v);
29665 // this might be called before we have a dom element..
29666 if (!this.viewEl) {
29669 this.viewEl.dom.innerHTML = html;
29670 Roo.form.DisplayField.superclass.setValue.call(this, v);
29680 * @class Roo.form.DayPicker
29681 * @extends Roo.form.Field
29682 * A Day picker show [M] [T] [W] ....
29684 * Creates a new Day Picker
29685 * @param {Object} config Configuration options
29687 Roo.form.DayPicker= function(config){
29688 Roo.form.DayPicker.superclass.constructor.call(this, config);
29692 Roo.extend(Roo.form.DayPicker, Roo.form.Field, {
29694 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
29696 focusClass : undefined,
29698 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
29700 fieldClass: "x-form-field",
29703 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
29704 * {tag: "input", type: "checkbox", autocomplete: "off"})
29706 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
29709 actionMode : 'viewEl',
29713 inputType : 'hidden',
29716 inputElement: false, // real input element?
29717 basedOn: false, // ????
29719 isFormField: true, // not sure where this is needed!!!!
29721 onResize : function(){
29722 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
29723 if(!this.boxLabel){
29724 this.el.alignTo(this.wrap, 'c-c');
29728 initEvents : function(){
29729 Roo.form.Checkbox.superclass.initEvents.call(this);
29730 this.el.on("click", this.onClick, this);
29731 this.el.on("change", this.onClick, this);
29735 getResizeEl : function(){
29739 getPositionEl : function(){
29745 onRender : function(ct, position){
29746 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
29748 this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
29750 var r1 = '<table><tr>';
29751 var r2 = '<tr class="x-form-daypick-icons">';
29752 for (var i=0; i < 7; i++) {
29753 r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
29754 r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL +'"></td>';
29757 var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
29758 viewEl.select('img').on('click', this.onClick, this);
29759 this.viewEl = viewEl;
29762 // this will not work on Chrome!!!
29763 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
29764 this.el.on('propertychange', this.setFromHidden, this); //ie
29772 initValue : Roo.emptyFn,
29775 * Returns the checked state of the checkbox.
29776 * @return {Boolean} True if checked, else false
29778 getValue : function(){
29779 return this.el.dom.value;
29784 onClick : function(e){
29785 //this.setChecked(!this.checked);
29786 Roo.get(e.target).toggleClass('x-menu-item-checked');
29787 this.refreshValue();
29788 //if(this.el.dom.checked != this.checked){
29789 // this.setValue(this.el.dom.checked);
29794 refreshValue : function()
29797 this.viewEl.select('img',true).each(function(e,i,n) {
29798 val += e.is(".x-menu-item-checked") ? String(n) : '';
29800 this.setValue(val, true);
29804 * Sets the checked state of the checkbox.
29805 * On is always based on a string comparison between inputValue and the param.
29806 * @param {Boolean/String} value - the value to set
29807 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
29809 setValue : function(v,suppressEvent){
29810 if (!this.el.dom) {
29813 var old = this.el.dom.value ;
29814 this.el.dom.value = v;
29815 if (suppressEvent) {
29819 // update display..
29820 this.viewEl.select('img',true).each(function(e,i,n) {
29822 var on = e.is(".x-menu-item-checked");
29823 var newv = v.indexOf(String(n)) > -1;
29825 e.toggleClass('x-menu-item-checked');
29831 this.fireEvent('change', this, v, old);
29836 // handle setting of hidden value by some other method!!?!?
29837 setFromHidden: function()
29842 //console.log("SET FROM HIDDEN");
29843 //alert('setFrom hidden');
29844 this.setValue(this.el.dom.value);
29847 onDestroy : function()
29850 Roo.get(this.viewEl).remove();
29853 Roo.form.DayPicker.superclass.onDestroy.call(this);
29857 * RooJS Library 1.1.1
29858 * Copyright(c) 2008-2011 Alan Knowles
29865 * @class Roo.form.ComboCheck
29866 * @extends Roo.form.ComboBox
29867 * A combobox for multiple select items.
29869 * FIXME - could do with a reset button..
29872 * Create a new ComboCheck
29873 * @param {Object} config Configuration options
29875 Roo.form.ComboCheck = function(config){
29876 Roo.form.ComboCheck.superclass.constructor.call(this, config);
29877 // should verify some data...
29879 // hiddenName = required..
29880 // displayField = required
29881 // valudField == required
29882 var req= [ 'hiddenName', 'displayField', 'valueField' ];
29884 Roo.each(req, function(e) {
29885 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
29886 throw "Roo.form.ComboCheck : missing value for: " + e;
29893 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
29898 selectedClass: 'x-menu-item-checked',
29901 onRender : function(ct, position){
29907 var cls = 'x-combo-list';
29910 this.tpl = new Roo.Template({
29911 html : '<div class="'+cls+'-item x-menu-check-item">' +
29912 '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' +
29913 '<span>{' + this.displayField + '}</span>' +
29920 Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
29921 this.view.singleSelect = false;
29922 this.view.multiSelect = true;
29923 this.view.toggleSelect = true;
29924 this.pageTb.add(new Roo.Toolbar.Fill(), {
29927 handler: function()
29934 onViewOver : function(e, t){
29940 onViewClick : function(doFocus,index){
29944 select: function () {
29945 //Roo.log("SELECT CALLED");
29948 selectByValue : function(xv, scrollIntoView){
29949 var ar = this.getValueArray();
29952 Roo.each(ar, function(v) {
29953 if(v === undefined || v === null){
29956 var r = this.findRecord(this.valueField, v);
29958 sels.push(this.store.indexOf(r))
29962 this.view.select(sels);
29968 onSelect : function(record, index){
29969 // Roo.log("onselect Called");
29970 // this is only called by the clear button now..
29971 this.view.clearSelections();
29972 this.setValue('[]');
29973 if (this.value != this.valueBefore) {
29974 this.fireEvent('change', this, this.value, this.valueBefore);
29977 getValueArray : function()
29982 //Roo.log(this.value);
29983 if (typeof(this.value) == 'undefined') {
29986 var ar = Roo.decode(this.value);
29987 return ar instanceof Array ? ar : []; //?? valid?
29990 Roo.log(e + "\nRoo.form.ComboCheck:getValueArray invalid data:" + this.getValue());
29995 expand : function ()
29997 Roo.form.ComboCheck.superclass.expand.call(this);
29998 this.valueBefore = this.value;
30003 collapse : function(){
30004 Roo.form.ComboCheck.superclass.collapse.call(this);
30005 var sl = this.view.getSelectedIndexes();
30006 var st = this.store;
30010 Roo.each(sl, function(i) {
30012 nv.push(r.get(this.valueField));
30014 this.setValue(Roo.encode(nv));
30015 if (this.value != this.valueBefore) {
30017 this.fireEvent('change', this, this.value, this.valueBefore);
30022 setValue : function(v){
30026 var vals = this.getValueArray();
30028 Roo.each(vals, function(k) {
30029 var r = this.findRecord(this.valueField, k);
30031 tv.push(r.data[this.displayField]);
30032 }else if(this.valueNotFoundText !== undefined){
30033 tv.push( this.valueNotFoundText );
30038 Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
30039 this.hiddenField.value = v;
30043 });//<script type="text/javasscript">
30047 * @class Roo.DDView
30048 * A DnD enabled version of Roo.View.
30049 * @param {Element/String} container The Element in which to create the View.
30050 * @param {String} tpl The template string used to create the markup for each element of the View
30051 * @param {Object} config The configuration properties. These include all the config options of
30052 * {@link Roo.View} plus some specific to this class.<br>
30054 * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
30055 * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
30057 * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
30058 .x-view-drag-insert-above {
30059 border-top:1px dotted #3366cc;
30061 .x-view-drag-insert-below {
30062 border-bottom:1px dotted #3366cc;
30068 Roo.DDView = function(container, tpl, config) {
30069 Roo.DDView.superclass.constructor.apply(this, arguments);
30070 this.getEl().setStyle("outline", "0px none");
30071 this.getEl().unselectable();
30072 if (this.dragGroup) {
30073 this.setDraggable(this.dragGroup.split(","));
30075 if (this.dropGroup) {
30076 this.setDroppable(this.dropGroup.split(","));
30078 if (this.deletable) {
30079 this.setDeletable();
30081 this.isDirtyFlag = false;
30087 Roo.extend(Roo.DDView, Roo.View, {
30088 /** @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
30089 /** @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
30090 /** @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
30091 /** @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
30095 reset: Roo.emptyFn,
30097 clearInvalid: Roo.form.Field.prototype.clearInvalid,
30099 validate: function() {
30103 destroy: function() {
30104 this.purgeListeners();
30105 this.getEl.removeAllListeners();
30106 this.getEl().remove();
30107 if (this.dragZone) {
30108 if (this.dragZone.destroy) {
30109 this.dragZone.destroy();
30112 if (this.dropZone) {
30113 if (this.dropZone.destroy) {
30114 this.dropZone.destroy();
30119 /** Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
30120 getName: function() {
30124 /** Loads the View from a JSON string representing the Records to put into the Store. */
30125 setValue: function(v) {
30127 throw "DDView.setValue(). DDView must be constructed with a valid Store";
30130 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
30131 this.store.proxy = new Roo.data.MemoryProxy(data);
30135 /** @return {String} a parenthesised list of the ids of the Records in the View. */
30136 getValue: function() {
30138 this.store.each(function(rec) {
30139 result += rec.id + ',';
30141 return result.substr(0, result.length - 1) + ')';
30144 getIds: function() {
30145 var i = 0, result = new Array(this.store.getCount());
30146 this.store.each(function(rec) {
30147 result[i++] = rec.id;
30152 isDirty: function() {
30153 return this.isDirtyFlag;
30157 * Part of the Roo.dd.DropZone interface. If no target node is found, the
30158 * whole Element becomes the target, and this causes the drop gesture to append.
30160 getTargetFromEvent : function(e) {
30161 var target = e.getTarget();
30162 while ((target !== null) && (target.parentNode != this.el.dom)) {
30163 target = target.parentNode;
30166 target = this.el.dom.lastChild || this.el.dom;
30172 * Create the drag data which consists of an object which has the property "ddel" as
30173 * the drag proxy element.
30175 getDragData : function(e) {
30176 var target = this.findItemFromChild(e.getTarget());
30178 this.handleSelection(e);
30179 var selNodes = this.getSelectedNodes();
30182 copy: this.copy || (this.allowCopy && e.ctrlKey),
30186 var selectedIndices = this.getSelectedIndexes();
30187 for (var i = 0; i < selectedIndices.length; i++) {
30188 dragData.records.push(this.store.getAt(selectedIndices[i]));
30190 if (selNodes.length == 1) {
30191 dragData.ddel = target.cloneNode(true); // the div element
30193 var div = document.createElement('div'); // create the multi element drag "ghost"
30194 div.className = 'multi-proxy';
30195 for (var i = 0, len = selNodes.length; i < len; i++) {
30196 div.appendChild(selNodes[i].cloneNode(true));
30198 dragData.ddel = div;
30200 //console.log(dragData)
30201 //console.log(dragData.ddel.innerHTML)
30204 //console.log('nodragData')
30208 /** Specify to which ddGroup items in this DDView may be dragged. */
30209 setDraggable: function(ddGroup) {
30210 if (ddGroup instanceof Array) {
30211 Roo.each(ddGroup, this.setDraggable, this);
30214 if (this.dragZone) {
30215 this.dragZone.addToGroup(ddGroup);
30217 this.dragZone = new Roo.dd.DragZone(this.getEl(), {
30218 containerScroll: true,
30222 // Draggability implies selection. DragZone's mousedown selects the element.
30223 if (!this.multiSelect) { this.singleSelect = true; }
30225 // Wire the DragZone's handlers up to methods in *this*
30226 this.dragZone.getDragData = this.getDragData.createDelegate(this);
30230 /** Specify from which ddGroup this DDView accepts drops. */
30231 setDroppable: function(ddGroup) {
30232 if (ddGroup instanceof Array) {
30233 Roo.each(ddGroup, this.setDroppable, this);
30236 if (this.dropZone) {
30237 this.dropZone.addToGroup(ddGroup);
30239 this.dropZone = new Roo.dd.DropZone(this.getEl(), {
30240 containerScroll: true,
30244 // Wire the DropZone's handlers up to methods in *this*
30245 this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
30246 this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
30247 this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
30248 this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
30249 this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
30253 /** Decide whether to drop above or below a View node. */
30254 getDropPoint : function(e, n, dd){
30255 if (n == this.el.dom) { return "above"; }
30256 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
30257 var c = t + (b - t) / 2;
30258 var y = Roo.lib.Event.getPageY(e);
30266 onNodeEnter : function(n, dd, e, data){
30270 onNodeOver : function(n, dd, e, data){
30271 var pt = this.getDropPoint(e, n, dd);
30272 // set the insert point style on the target node
30273 var dragElClass = this.dropNotAllowed;
30276 if (pt == "above"){
30277 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
30278 targetElClass = "x-view-drag-insert-above";
30280 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
30281 targetElClass = "x-view-drag-insert-below";
30283 if (this.lastInsertClass != targetElClass){
30284 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
30285 this.lastInsertClass = targetElClass;
30288 return dragElClass;
30291 onNodeOut : function(n, dd, e, data){
30292 this.removeDropIndicators(n);
30295 onNodeDrop : function(n, dd, e, data){
30296 if (this.fireEvent("drop", this, n, dd, e, data) === false) {
30299 var pt = this.getDropPoint(e, n, dd);
30300 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
30301 if (pt == "below") { insertAt++; }
30302 for (var i = 0; i < data.records.length; i++) {
30303 var r = data.records[i];
30304 var dup = this.store.getById(r.id);
30305 if (dup && (dd != this.dragZone)) {
30306 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
30309 this.store.insert(insertAt++, r.copy());
30311 data.source.isDirtyFlag = true;
30313 this.store.insert(insertAt++, r);
30315 this.isDirtyFlag = true;
30318 this.dragZone.cachedTarget = null;
30322 removeDropIndicators : function(n){
30324 Roo.fly(n).removeClass([
30325 "x-view-drag-insert-above",
30326 "x-view-drag-insert-below"]);
30327 this.lastInsertClass = "_noclass";
30332 * Utility method. Add a delete option to the DDView's context menu.
30333 * @param {String} imageUrl The URL of the "delete" icon image.
30335 setDeletable: function(imageUrl) {
30336 if (!this.singleSelect && !this.multiSelect) {
30337 this.singleSelect = true;
30339 var c = this.getContextMenu();
30340 this.contextMenu.on("itemclick", function(item) {
30343 this.remove(this.getSelectedIndexes());
30347 this.contextMenu.add({
30354 /** Return the context menu for this DDView. */
30355 getContextMenu: function() {
30356 if (!this.contextMenu) {
30357 // Create the View's context menu
30358 this.contextMenu = new Roo.menu.Menu({
30359 id: this.id + "-contextmenu"
30361 this.el.on("contextmenu", this.showContextMenu, this);
30363 return this.contextMenu;
30366 disableContextMenu: function() {
30367 if (this.contextMenu) {
30368 this.el.un("contextmenu", this.showContextMenu, this);
30372 showContextMenu: function(e, item) {
30373 item = this.findItemFromChild(e.getTarget());
30376 this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
30377 this.contextMenu.showAt(e.getXY());
30382 * Remove {@link Roo.data.Record}s at the specified indices.
30383 * @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
30385 remove: function(selectedIndices) {
30386 selectedIndices = [].concat(selectedIndices);
30387 for (var i = 0; i < selectedIndices.length; i++) {
30388 var rec = this.store.getAt(selectedIndices[i]);
30389 this.store.remove(rec);
30394 * Double click fires the event, but also, if this is draggable, and there is only one other
30395 * related DropZone, it transfers the selected node.
30397 onDblClick : function(e){
30398 var item = this.findItemFromChild(e.getTarget());
30400 if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
30403 if (this.dragGroup) {
30404 var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
30405 while (targets.indexOf(this.dropZone) > -1) {
30406 targets.remove(this.dropZone);
30408 if (targets.length == 1) {
30409 this.dragZone.cachedTarget = null;
30410 var el = Roo.get(targets[0].getEl());
30411 var box = el.getBox(true);
30412 targets[0].onNodeDrop(el.dom, {
30414 xy: [box.x, box.y + box.height - 1]
30415 }, null, this.getDragData(e));
30421 handleSelection: function(e) {
30422 this.dragZone.cachedTarget = null;
30423 var item = this.findItemFromChild(e.getTarget());
30425 this.clearSelections(true);
30428 if (item && (this.multiSelect || this.singleSelect)){
30429 if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
30430 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
30431 }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
30432 this.unselect(item);
30434 this.select(item, this.multiSelect && e.ctrlKey);
30435 this.lastSelection = item;
30440 onItemClick : function(item, index, e){
30441 if(this.fireEvent("beforeclick", this, index, item, e) === false){
30447 unselect : function(nodeInfo, suppressEvent){
30448 var node = this.getNode(nodeInfo);
30449 if(node && this.isSelected(node)){
30450 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
30451 Roo.fly(node).removeClass(this.selectedClass);
30452 this.selections.remove(node);
30453 if(!suppressEvent){
30454 this.fireEvent("selectionchange", this, this.selections);
30462 * Ext JS Library 1.1.1
30463 * Copyright(c) 2006-2007, Ext JS, LLC.
30465 * Originally Released Under LGPL - original licence link has changed is not relivant.
30468 * <script type="text/javascript">
30472 * @class Roo.LayoutManager
30473 * @extends Roo.util.Observable
30474 * Base class for layout managers.
30476 Roo.LayoutManager = function(container, config){
30477 Roo.LayoutManager.superclass.constructor.call(this);
30478 this.el = Roo.get(container);
30479 // ie scrollbar fix
30480 if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
30481 document.body.scroll = "no";
30482 }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
30483 this.el.position('relative');
30485 this.id = this.el.id;
30486 this.el.addClass("x-layout-container");
30487 /** false to disable window resize monitoring @type Boolean */
30488 this.monitorWindowResize = true;
30493 * Fires when a layout is performed.
30494 * @param {Roo.LayoutManager} this
30498 * @event regionresized
30499 * Fires when the user resizes a region.
30500 * @param {Roo.LayoutRegion} region The resized region
30501 * @param {Number} newSize The new size (width for east/west, height for north/south)
30503 "regionresized" : true,
30505 * @event regioncollapsed
30506 * Fires when a region is collapsed.
30507 * @param {Roo.LayoutRegion} region The collapsed region
30509 "regioncollapsed" : true,
30511 * @event regionexpanded
30512 * Fires when a region is expanded.
30513 * @param {Roo.LayoutRegion} region The expanded region
30515 "regionexpanded" : true
30517 this.updating = false;
30518 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
30521 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
30523 * Returns true if this layout is currently being updated
30524 * @return {Boolean}
30526 isUpdating : function(){
30527 return this.updating;
30531 * Suspend the LayoutManager from doing auto-layouts while
30532 * making multiple add or remove calls
30534 beginUpdate : function(){
30535 this.updating = true;
30539 * Restore auto-layouts and optionally disable the manager from performing a layout
30540 * @param {Boolean} noLayout true to disable a layout update
30542 endUpdate : function(noLayout){
30543 this.updating = false;
30549 layout: function(){
30553 onRegionResized : function(region, newSize){
30554 this.fireEvent("regionresized", region, newSize);
30558 onRegionCollapsed : function(region){
30559 this.fireEvent("regioncollapsed", region);
30562 onRegionExpanded : function(region){
30563 this.fireEvent("regionexpanded", region);
30567 * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
30568 * performs box-model adjustments.
30569 * @return {Object} The size as an object {width: (the width), height: (the height)}
30571 getViewSize : function(){
30573 if(this.el.dom != document.body){
30574 size = this.el.getSize();
30576 size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
30578 size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
30579 size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
30584 * Returns the Element this layout is bound to.
30585 * @return {Roo.Element}
30587 getEl : function(){
30592 * Returns the specified region.
30593 * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
30594 * @return {Roo.LayoutRegion}
30596 getRegion : function(target){
30597 return this.regions[target.toLowerCase()];
30600 onWindowResize : function(){
30601 if(this.monitorWindowResize){
30607 * Ext JS Library 1.1.1
30608 * Copyright(c) 2006-2007, Ext JS, LLC.
30610 * Originally Released Under LGPL - original licence link has changed is not relivant.
30613 * <script type="text/javascript">
30616 * @class Roo.BorderLayout
30617 * @extends Roo.LayoutManager
30618 * This class represents a common layout manager used in desktop applications. For screenshots and more details,
30619 * please see: <br><br>
30620 * <a href="http://www.jackslocum.com/yui/2006/10/19/cross-browser-web-20-layouts-with-yahoo-ui/">Cross Browser Layouts - Part 1</a><br>
30621 * <a href="http://www.jackslocum.com/yui/2006/10/28/cross-browser-web-20-layouts-part-2-ajax-feed-viewer-20/">Cross Browser Layouts - Part 2</a><br><br>
30624 var layout = new Roo.BorderLayout(document.body, {
30658 preferredTabWidth: 150
30663 var CP = Roo.ContentPanel;
30665 layout.beginUpdate();
30666 layout.add("north", new CP("north", "North"));
30667 layout.add("south", new CP("south", {title: "South", closable: true}));
30668 layout.add("west", new CP("west", {title: "West"}));
30669 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
30670 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
30671 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
30672 layout.getRegion("center").showPanel("center1");
30673 layout.endUpdate();
30676 <b>The container the layout is rendered into can be either the body element or any other element.
30677 If it is not the body element, the container needs to either be an absolute positioned element,
30678 or you will need to add "position:relative" to the css of the container. You will also need to specify
30679 the container size if it is not the body element.</b>
30682 * Create a new BorderLayout
30683 * @param {String/HTMLElement/Element} container The container this layout is bound to
30684 * @param {Object} config Configuration options
30686 Roo.BorderLayout = function(container, config){
30687 config = config || {};
30688 Roo.BorderLayout.superclass.constructor.call(this, container, config);
30689 this.factory = config.factory || Roo.BorderLayout.RegionFactory;
30690 for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
30691 var target = this.factory.validRegions[i];
30692 if(config[target]){
30693 this.addRegion(target, config[target]);
30698 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
30700 * Creates and adds a new region if it doesn't already exist.
30701 * @param {String} target The target region key (north, south, east, west or center).
30702 * @param {Object} config The regions config object
30703 * @return {BorderLayoutRegion} The new region
30705 addRegion : function(target, config){
30706 if(!this.regions[target]){
30707 var r = this.factory.create(target, this, config);
30708 this.bindRegion(target, r);
30710 return this.regions[target];
30714 bindRegion : function(name, r){
30715 this.regions[name] = r;
30716 r.on("visibilitychange", this.layout, this);
30717 r.on("paneladded", this.layout, this);
30718 r.on("panelremoved", this.layout, this);
30719 r.on("invalidated", this.layout, this);
30720 r.on("resized", this.onRegionResized, this);
30721 r.on("collapsed", this.onRegionCollapsed, this);
30722 r.on("expanded", this.onRegionExpanded, this);
30726 * Performs a layout update.
30728 layout : function(){
30729 if(this.updating) return;
30730 var size = this.getViewSize();
30731 var w = size.width;
30732 var h = size.height;
30737 //var x = 0, y = 0;
30739 var rs = this.regions;
30740 var north = rs["north"];
30741 var south = rs["south"];
30742 var west = rs["west"];
30743 var east = rs["east"];
30744 var center = rs["center"];
30745 //if(this.hideOnLayout){ // not supported anymore
30746 //c.el.setStyle("display", "none");
30748 if(north && north.isVisible()){
30749 var b = north.getBox();
30750 var m = north.getMargins();
30751 b.width = w - (m.left+m.right);
30754 centerY = b.height + b.y + m.bottom;
30755 centerH -= centerY;
30756 north.updateBox(this.safeBox(b));
30758 if(south && south.isVisible()){
30759 var b = south.getBox();
30760 var m = south.getMargins();
30761 b.width = w - (m.left+m.right);
30763 var totalHeight = (b.height + m.top + m.bottom);
30764 b.y = h - totalHeight + m.top;
30765 centerH -= totalHeight;
30766 south.updateBox(this.safeBox(b));
30768 if(west && west.isVisible()){
30769 var b = west.getBox();
30770 var m = west.getMargins();
30771 b.height = centerH - (m.top+m.bottom);
30773 b.y = centerY + m.top;
30774 var totalWidth = (b.width + m.left + m.right);
30775 centerX += totalWidth;
30776 centerW -= totalWidth;
30777 west.updateBox(this.safeBox(b));
30779 if(east && east.isVisible()){
30780 var b = east.getBox();
30781 var m = east.getMargins();
30782 b.height = centerH - (m.top+m.bottom);
30783 var totalWidth = (b.width + m.left + m.right);
30784 b.x = w - totalWidth + m.left;
30785 b.y = centerY + m.top;
30786 centerW -= totalWidth;
30787 east.updateBox(this.safeBox(b));
30790 var m = center.getMargins();
30792 x: centerX + m.left,
30793 y: centerY + m.top,
30794 width: centerW - (m.left+m.right),
30795 height: centerH - (m.top+m.bottom)
30797 //if(this.hideOnLayout){
30798 //center.el.setStyle("display", "block");
30800 center.updateBox(this.safeBox(centerBox));
30803 this.fireEvent("layout", this);
30807 safeBox : function(box){
30808 box.width = Math.max(0, box.width);
30809 box.height = Math.max(0, box.height);
30814 * Adds a ContentPanel (or subclass) to this layout.
30815 * @param {String} target The target region key (north, south, east, west or center).
30816 * @param {Roo.ContentPanel} panel The panel to add
30817 * @return {Roo.ContentPanel} The added panel
30819 add : function(target, panel){
30821 target = target.toLowerCase();
30822 return this.regions[target].add(panel);
30826 * Remove a ContentPanel (or subclass) to this layout.
30827 * @param {String} target The target region key (north, south, east, west or center).
30828 * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
30829 * @return {Roo.ContentPanel} The removed panel
30831 remove : function(target, panel){
30832 target = target.toLowerCase();
30833 return this.regions[target].remove(panel);
30837 * Searches all regions for a panel with the specified id
30838 * @param {String} panelId
30839 * @return {Roo.ContentPanel} The panel or null if it wasn't found
30841 findPanel : function(panelId){
30842 var rs = this.regions;
30843 for(var target in rs){
30844 if(typeof rs[target] != "function"){
30845 var p = rs[target].getPanel(panelId);
30855 * Searches all regions for a panel with the specified id and activates (shows) it.
30856 * @param {String/ContentPanel} panelId The panels id or the panel itself
30857 * @return {Roo.ContentPanel} The shown panel or null
30859 showPanel : function(panelId) {
30860 var rs = this.regions;
30861 for(var target in rs){
30862 var r = rs[target];
30863 if(typeof r != "function"){
30864 if(r.hasPanel(panelId)){
30865 return r.showPanel(panelId);
30873 * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
30874 * @param {Roo.state.Provider} provider (optional) An alternate state provider
30876 restoreState : function(provider){
30878 provider = Roo.state.Manager;
30880 var sm = new Roo.LayoutStateManager();
30881 sm.init(this, provider);
30885 * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object. This config
30886 * object should contain properties for each region to add ContentPanels to, and each property's value should be
30887 * a valid ContentPanel config object. Example:
30889 // Create the main layout
30890 var layout = new Roo.BorderLayout('main-ct', {
30901 // Create and add multiple ContentPanels at once via configs
30904 id: 'source-files',
30906 title:'Ext Source Files',
30919 * @param {Object} regions An object containing ContentPanel configs by region name
30921 batchAdd : function(regions){
30922 this.beginUpdate();
30923 for(var rname in regions){
30924 var lr = this.regions[rname];
30926 this.addTypedPanels(lr, regions[rname]);
30933 addTypedPanels : function(lr, ps){
30934 if(typeof ps == 'string'){
30935 lr.add(new Roo.ContentPanel(ps));
30937 else if(ps instanceof Array){
30938 for(var i =0, len = ps.length; i < len; i++){
30939 this.addTypedPanels(lr, ps[i]);
30942 else if(!ps.events){ // raw config?
30944 delete ps.el; // prevent conflict
30945 lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
30947 else { // panel object assumed!
30952 * Adds a xtype elements to the layout.
30956 xtype : 'ContentPanel',
30963 xtype : 'NestedLayoutPanel',
30969 items : [ ... list of content panels or nested layout panels.. ]
30973 * @param {Object} cfg Xtype definition of item to add.
30975 addxtype : function(cfg)
30977 // basically accepts a pannel...
30978 // can accept a layout region..!?!?
30979 //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
30981 if (!cfg.xtype.match(/Panel$/)) {
30986 if (typeof(cfg.region) == 'undefined') {
30987 Roo.log("Failed to add Panel, region was not set");
30991 var region = cfg.region;
30997 xitems = cfg.items;
31004 case 'ContentPanel': // ContentPanel (el, cfg)
31005 case 'ScrollPanel': // ContentPanel (el, cfg)
31006 if(cfg.autoCreate) {
31007 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
31009 var el = this.el.createChild();
31010 ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
31013 this.add(region, ret);
31017 case 'TreePanel': // our new panel!
31018 cfg.el = this.el.createChild();
31019 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
31020 this.add(region, ret);
31023 case 'NestedLayoutPanel':
31024 // create a new Layout (which is a Border Layout...
31025 var el = this.el.createChild();
31026 var clayout = cfg.layout;
31028 clayout.items = clayout.items || [];
31029 // replace this exitems with the clayout ones..
31030 xitems = clayout.items;
31033 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
31034 cfg.background = false;
31036 var layout = new Roo.BorderLayout(el, clayout);
31038 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
31039 //console.log('adding nested layout panel ' + cfg.toSource());
31040 this.add(region, ret);
31041 nb = {}; /// find first...
31046 // needs grid and region
31048 //var el = this.getRegion(region).el.createChild();
31049 var el = this.el.createChild();
31050 // create the grid first...
31052 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
31054 if (region == 'center' && this.active ) {
31055 cfg.background = false;
31057 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
31059 this.add(region, ret);
31060 if (cfg.background) {
31061 ret.on('activate', function(gp) {
31062 if (!gp.grid.rendered) {
31075 alert("Can not add '" + cfg.xtype + "' to BorderLayout");
31077 // GridPanel (grid, cfg)
31080 this.beginUpdate();
31084 Roo.each(xitems, function(i) {
31085 region = nb && i.region ? i.region : false;
31087 var add = ret.addxtype(i);
31090 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
31091 if (!i.background) {
31092 abn[region] = nb[region] ;
31099 // make the last non-background panel active..
31100 //if (nb) { Roo.log(abn); }
31103 for(var r in abn) {
31104 region = this.getRegion(r);
31106 // tried using nb[r], but it does not work..
31108 region.showPanel(abn[r]);
31119 * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
31120 * the beginUpdate and endUpdate calls internally. The key to this method is the <b>panels</b> property that can be
31121 * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
31122 * during creation. The following code is equivalent to the constructor-based example at the beginning of this class:
31125 var CP = Roo.ContentPanel;
31127 var layout = Roo.BorderLayout.create({
31131 panels: [new CP("north", "North")]
31140 panels: [new CP("west", {title: "West"})]
31149 panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
31158 panels: [new CP("south", {title: "South", closable: true})]
31165 preferredTabWidth: 150,
31167 new CP("center1", {title: "Close Me", closable: true}),
31168 new CP("center2", {title: "Center Panel", closable: false})
31173 layout.getRegion("center").showPanel("center1");
31178 Roo.BorderLayout.create = function(config, targetEl){
31179 var layout = new Roo.BorderLayout(targetEl || document.body, config);
31180 layout.beginUpdate();
31181 var regions = Roo.BorderLayout.RegionFactory.validRegions;
31182 for(var j = 0, jlen = regions.length; j < jlen; j++){
31183 var lr = regions[j];
31184 if(layout.regions[lr] && config[lr].panels){
31185 var r = layout.regions[lr];
31186 var ps = config[lr].panels;
31187 layout.addTypedPanels(r, ps);
31190 layout.endUpdate();
31195 Roo.BorderLayout.RegionFactory = {
31197 validRegions : ["north","south","east","west","center"],
31200 create : function(target, mgr, config){
31201 target = target.toLowerCase();
31202 if(config.lightweight || config.basic){
31203 return new Roo.BasicLayoutRegion(mgr, config, target);
31207 return new Roo.NorthLayoutRegion(mgr, config);
31209 return new Roo.SouthLayoutRegion(mgr, config);
31211 return new Roo.EastLayoutRegion(mgr, config);
31213 return new Roo.WestLayoutRegion(mgr, config);
31215 return new Roo.CenterLayoutRegion(mgr, config);
31217 throw 'Layout region "'+target+'" not supported.';
31221 * Ext JS Library 1.1.1
31222 * Copyright(c) 2006-2007, Ext JS, LLC.
31224 * Originally Released Under LGPL - original licence link has changed is not relivant.
31227 * <script type="text/javascript">
31231 * @class Roo.BasicLayoutRegion
31232 * @extends Roo.util.Observable
31233 * This class represents a lightweight region in a layout manager. This region does not move dom nodes
31234 * and does not have a titlebar, tabs or any other features. All it does is size and position
31235 * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
31237 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
31239 this.position = pos;
31242 * @scope Roo.BasicLayoutRegion
31246 * @event beforeremove
31247 * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
31248 * @param {Roo.LayoutRegion} this
31249 * @param {Roo.ContentPanel} panel The panel
31250 * @param {Object} e The cancel event object
31252 "beforeremove" : true,
31254 * @event invalidated
31255 * Fires when the layout for this region is changed.
31256 * @param {Roo.LayoutRegion} this
31258 "invalidated" : true,
31260 * @event visibilitychange
31261 * Fires when this region is shown or hidden
31262 * @param {Roo.LayoutRegion} this
31263 * @param {Boolean} visibility true or false
31265 "visibilitychange" : true,
31267 * @event paneladded
31268 * Fires when a panel is added.
31269 * @param {Roo.LayoutRegion} this
31270 * @param {Roo.ContentPanel} panel The panel
31272 "paneladded" : true,
31274 * @event panelremoved
31275 * Fires when a panel is removed.
31276 * @param {Roo.LayoutRegion} this
31277 * @param {Roo.ContentPanel} panel The panel
31279 "panelremoved" : true,
31282 * Fires when this region is collapsed.
31283 * @param {Roo.LayoutRegion} this
31285 "collapsed" : true,
31288 * Fires when this region is expanded.
31289 * @param {Roo.LayoutRegion} this
31294 * Fires when this region is slid into view.
31295 * @param {Roo.LayoutRegion} this
31297 "slideshow" : true,
31300 * Fires when this region slides out of view.
31301 * @param {Roo.LayoutRegion} this
31303 "slidehide" : true,
31305 * @event panelactivated
31306 * Fires when a panel is activated.
31307 * @param {Roo.LayoutRegion} this
31308 * @param {Roo.ContentPanel} panel The activated panel
31310 "panelactivated" : true,
31313 * Fires when the user resizes this region.
31314 * @param {Roo.LayoutRegion} this
31315 * @param {Number} newSize The new size (width for east/west, height for north/south)
31319 /** A collection of panels in this region. @type Roo.util.MixedCollection */
31320 this.panels = new Roo.util.MixedCollection();
31321 this.panels.getKey = this.getPanelId.createDelegate(this);
31323 this.activePanel = null;
31324 // ensure listeners are added...
31326 if (config.listeners || config.events) {
31327 Roo.BasicLayoutRegion.superclass.constructor.call(this, {
31328 listeners : config.listeners || {},
31329 events : config.events || {}
31333 if(skipConfig !== true){
31334 this.applyConfig(config);
31338 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
31339 getPanelId : function(p){
31343 applyConfig : function(config){
31344 this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
31345 this.config = config;
31350 * Resizes the region to the specified size. For vertical regions (west, east) this adjusts
31351 * the width, for horizontal (north, south) the height.
31352 * @param {Number} newSize The new width or height
31354 resizeTo : function(newSize){
31355 var el = this.el ? this.el :
31356 (this.activePanel ? this.activePanel.getEl() : null);
31358 switch(this.position){
31361 el.setWidth(newSize);
31362 this.fireEvent("resized", this, newSize);
31366 el.setHeight(newSize);
31367 this.fireEvent("resized", this, newSize);
31373 getBox : function(){
31374 return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
31377 getMargins : function(){
31378 return this.margins;
31381 updateBox : function(box){
31383 var el = this.activePanel.getEl();
31384 el.dom.style.left = box.x + "px";
31385 el.dom.style.top = box.y + "px";
31386 this.activePanel.setSize(box.width, box.height);
31390 * Returns the container element for this region.
31391 * @return {Roo.Element}
31393 getEl : function(){
31394 return this.activePanel;
31398 * Returns true if this region is currently visible.
31399 * @return {Boolean}
31401 isVisible : function(){
31402 return this.activePanel ? true : false;
31405 setActivePanel : function(panel){
31406 panel = this.getPanel(panel);
31407 if(this.activePanel && this.activePanel != panel){
31408 this.activePanel.setActiveState(false);
31409 this.activePanel.getEl().setLeftTop(-10000,-10000);
31411 this.activePanel = panel;
31412 panel.setActiveState(true);
31414 panel.setSize(this.box.width, this.box.height);
31416 this.fireEvent("panelactivated", this, panel);
31417 this.fireEvent("invalidated");
31421 * Show the specified panel.
31422 * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
31423 * @return {Roo.ContentPanel} The shown panel or null
31425 showPanel : function(panel){
31426 if(panel = this.getPanel(panel)){
31427 this.setActivePanel(panel);
31433 * Get the active panel for this region.
31434 * @return {Roo.ContentPanel} The active panel or null
31436 getActivePanel : function(){
31437 return this.activePanel;
31441 * Add the passed ContentPanel(s)
31442 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
31443 * @return {Roo.ContentPanel} The panel added (if only one was added)
31445 add : function(panel){
31446 if(arguments.length > 1){
31447 for(var i = 0, len = arguments.length; i < len; i++) {
31448 this.add(arguments[i]);
31452 if(this.hasPanel(panel)){
31453 this.showPanel(panel);
31456 var el = panel.getEl();
31457 if(el.dom.parentNode != this.mgr.el.dom){
31458 this.mgr.el.dom.appendChild(el.dom);
31460 if(panel.setRegion){
31461 panel.setRegion(this);
31463 this.panels.add(panel);
31464 el.setStyle("position", "absolute");
31465 if(!panel.background){
31466 this.setActivePanel(panel);
31467 if(this.config.initialSize && this.panels.getCount()==1){
31468 this.resizeTo(this.config.initialSize);
31471 this.fireEvent("paneladded", this, panel);
31476 * Returns true if the panel is in this region.
31477 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
31478 * @return {Boolean}
31480 hasPanel : function(panel){
31481 if(typeof panel == "object"){ // must be panel obj
31482 panel = panel.getId();
31484 return this.getPanel(panel) ? true : false;
31488 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
31489 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
31490 * @param {Boolean} preservePanel Overrides the config preservePanel option
31491 * @return {Roo.ContentPanel} The panel that was removed
31493 remove : function(panel, preservePanel){
31494 panel = this.getPanel(panel);
31499 this.fireEvent("beforeremove", this, panel, e);
31500 if(e.cancel === true){
31503 var panelId = panel.getId();
31504 this.panels.removeKey(panelId);
31509 * Returns the panel specified or null if it's not in this region.
31510 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
31511 * @return {Roo.ContentPanel}
31513 getPanel : function(id){
31514 if(typeof id == "object"){ // must be panel obj
31517 return this.panels.get(id);
31521 * Returns this regions position (north/south/east/west/center).
31524 getPosition: function(){
31525 return this.position;
31529 * Ext JS Library 1.1.1
31530 * Copyright(c) 2006-2007, Ext JS, LLC.
31532 * Originally Released Under LGPL - original licence link has changed is not relivant.
31535 * <script type="text/javascript">
31539 * @class Roo.LayoutRegion
31540 * @extends Roo.BasicLayoutRegion
31541 * This class represents a region in a layout manager.
31542 * @cfg {Boolean} collapsible False to disable collapsing (defaults to true)
31543 * @cfg {Boolean} collapsed True to set the initial display to collapsed (defaults to false)
31544 * @cfg {Boolean} floatable False to disable floating (defaults to true)
31545 * @cfg {Object} margins Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
31546 * @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})
31547 * @cfg {String} tabPosition "top" or "bottom" (defaults to "bottom")
31548 * @cfg {String} collapsedTitle Optional string message to display in the collapsed block of a north or south region
31549 * @cfg {Boolean} alwaysShowTabs True to always display tabs even when there is only 1 panel (defaults to false)
31550 * @cfg {Boolean} autoScroll True to enable overflow scrolling (defaults to false)
31551 * @cfg {Boolean} titlebar True to display a title bar (defaults to true)
31552 * @cfg {String} title The title for the region (overrides panel titles)
31553 * @cfg {Boolean} animate True to animate expand/collapse (defaults to false)
31554 * @cfg {Boolean} autoHide False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
31555 * @cfg {Boolean} preservePanels True to preserve removed panels so they can be readded later (defaults to false)
31556 * @cfg {Boolean} closeOnTab True to place the close icon on the tabs instead of the region titlebar (defaults to false)
31557 * @cfg {Boolean} hideTabs True to hide the tab strip (defaults to false)
31558 * @cfg {Boolean} resizeTabs True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
31559 * the space available, similar to FireFox 1.5 tabs (defaults to false)
31560 * @cfg {Number} minTabWidth The minimum tab width (defaults to 40)
31561 * @cfg {Number} preferredTabWidth The preferred tab width (defaults to 150)
31562 * @cfg {Boolean} showPin True to show a pin button
31563 * @cfg {Boolean} hidden True to start the region hidden (defaults to false)
31564 * @cfg {Boolean} hideWhenEmpty True to hide the region when it has no panels
31565 * @cfg {Boolean} disableTabTips True to disable tab tooltips
31566 * @cfg {Number} width For East/West panels
31567 * @cfg {Number} height For North/South panels
31568 * @cfg {Boolean} split To show the splitter
31569 * @cfg {Boolean} toolbar xtype configuration for a toolbar - shows on right of tabbar
31571 Roo.LayoutRegion = function(mgr, config, pos){
31572 Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
31573 var dh = Roo.DomHelper;
31574 /** This region's container element
31575 * @type Roo.Element */
31576 this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
31577 /** This region's title element
31578 * @type Roo.Element */
31580 this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
31581 {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: " "},
31582 {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
31584 this.titleEl.enableDisplayMode();
31585 /** This region's title text element
31586 * @type HTMLElement */
31587 this.titleTextEl = this.titleEl.dom.firstChild;
31588 this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
31589 this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
31590 this.closeBtn.enableDisplayMode();
31591 this.closeBtn.on("click", this.closeClicked, this);
31592 this.closeBtn.hide();
31594 this.createBody(config);
31595 this.visible = true;
31596 this.collapsed = false;
31598 if(config.hideWhenEmpty){
31600 this.on("paneladded", this.validateVisibility, this);
31601 this.on("panelremoved", this.validateVisibility, this);
31603 this.applyConfig(config);
31606 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
31608 createBody : function(){
31609 /** This region's body element
31610 * @type Roo.Element */
31611 this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
31614 applyConfig : function(c){
31615 if(c.collapsible && this.position != "center" && !this.collapsedEl){
31616 var dh = Roo.DomHelper;
31617 if(c.titlebar !== false){
31618 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
31619 this.collapseBtn.on("click", this.collapse, this);
31620 this.collapseBtn.enableDisplayMode();
31622 if(c.showPin === true || this.showPin){
31623 this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
31624 this.stickBtn.enableDisplayMode();
31625 this.stickBtn.on("click", this.expand, this);
31626 this.stickBtn.hide();
31629 /** This region's collapsed element
31630 * @type Roo.Element */
31631 this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
31632 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
31634 if(c.floatable !== false){
31635 this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
31636 this.collapsedEl.on("click", this.collapseClick, this);
31639 if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
31640 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
31641 id: "message", unselectable: "on", style:{"float":"left"}});
31642 this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
31644 this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
31645 this.expandBtn.on("click", this.expand, this);
31647 if(this.collapseBtn){
31648 this.collapseBtn.setVisible(c.collapsible == true);
31650 this.cmargins = c.cmargins || this.cmargins ||
31651 (this.position == "west" || this.position == "east" ?
31652 {top: 0, left: 2, right:2, bottom: 0} :
31653 {top: 2, left: 0, right:0, bottom: 2});
31654 this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
31655 this.bottomTabs = c.tabPosition != "top";
31656 this.autoScroll = c.autoScroll || false;
31657 if(this.autoScroll){
31658 this.bodyEl.setStyle("overflow", "auto");
31660 this.bodyEl.setStyle("overflow", "hidden");
31662 //if(c.titlebar !== false){
31663 if((!c.titlebar && !c.title) || c.titlebar === false){
31664 this.titleEl.hide();
31666 this.titleEl.show();
31668 this.titleTextEl.innerHTML = c.title;
31672 this.duration = c.duration || .30;
31673 this.slideDuration = c.slideDuration || .45;
31676 this.collapse(true);
31683 * Returns true if this region is currently visible.
31684 * @return {Boolean}
31686 isVisible : function(){
31687 return this.visible;
31691 * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
31692 * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&#160;")
31694 setCollapsedTitle : function(title){
31695 title = title || " ";
31696 if(this.collapsedTitleTextEl){
31697 this.collapsedTitleTextEl.innerHTML = title;
31701 getBox : function(){
31703 if(!this.collapsed){
31704 b = this.el.getBox(false, true);
31706 b = this.collapsedEl.getBox(false, true);
31711 getMargins : function(){
31712 return this.collapsed ? this.cmargins : this.margins;
31715 highlight : function(){
31716 this.el.addClass("x-layout-panel-dragover");
31719 unhighlight : function(){
31720 this.el.removeClass("x-layout-panel-dragover");
31723 updateBox : function(box){
31725 if(!this.collapsed){
31726 this.el.dom.style.left = box.x + "px";
31727 this.el.dom.style.top = box.y + "px";
31728 this.updateBody(box.width, box.height);
31730 this.collapsedEl.dom.style.left = box.x + "px";
31731 this.collapsedEl.dom.style.top = box.y + "px";
31732 this.collapsedEl.setSize(box.width, box.height);
31735 this.tabs.autoSizeTabs();
31739 updateBody : function(w, h){
31741 this.el.setWidth(w);
31742 w -= this.el.getBorderWidth("rl");
31743 if(this.config.adjustments){
31744 w += this.config.adjustments[0];
31748 this.el.setHeight(h);
31749 h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
31750 h -= this.el.getBorderWidth("tb");
31751 if(this.config.adjustments){
31752 h += this.config.adjustments[1];
31754 this.bodyEl.setHeight(h);
31756 h = this.tabs.syncHeight(h);
31759 if(this.panelSize){
31760 w = w !== null ? w : this.panelSize.width;
31761 h = h !== null ? h : this.panelSize.height;
31763 if(this.activePanel){
31764 var el = this.activePanel.getEl();
31765 w = w !== null ? w : el.getWidth();
31766 h = h !== null ? h : el.getHeight();
31767 this.panelSize = {width: w, height: h};
31768 this.activePanel.setSize(w, h);
31770 if(Roo.isIE && this.tabs){
31771 this.tabs.el.repaint();
31776 * Returns the container element for this region.
31777 * @return {Roo.Element}
31779 getEl : function(){
31784 * Hides this region.
31787 if(!this.collapsed){
31788 this.el.dom.style.left = "-2000px";
31791 this.collapsedEl.dom.style.left = "-2000px";
31792 this.collapsedEl.hide();
31794 this.visible = false;
31795 this.fireEvent("visibilitychange", this, false);
31799 * Shows this region if it was previously hidden.
31802 if(!this.collapsed){
31805 this.collapsedEl.show();
31807 this.visible = true;
31808 this.fireEvent("visibilitychange", this, true);
31811 closeClicked : function(){
31812 if(this.activePanel){
31813 this.remove(this.activePanel);
31817 collapseClick : function(e){
31819 e.stopPropagation();
31822 e.stopPropagation();
31828 * Collapses this region.
31829 * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
31831 collapse : function(skipAnim){
31832 if(this.collapsed) return;
31833 this.collapsed = true;
31835 this.split.el.hide();
31837 if(this.config.animate && skipAnim !== true){
31838 this.fireEvent("invalidated", this);
31839 this.animateCollapse();
31841 this.el.setLocation(-20000,-20000);
31843 this.collapsedEl.show();
31844 this.fireEvent("collapsed", this);
31845 this.fireEvent("invalidated", this);
31849 animateCollapse : function(){
31854 * Expands this region if it was previously collapsed.
31855 * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
31856 * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
31858 expand : function(e, skipAnim){
31859 if(e) e.stopPropagation();
31860 if(!this.collapsed || this.el.hasActiveFx()) return;
31862 this.afterSlideIn();
31865 this.collapsed = false;
31866 if(this.config.animate && skipAnim !== true){
31867 this.animateExpand();
31871 this.split.el.show();
31873 this.collapsedEl.setLocation(-2000,-2000);
31874 this.collapsedEl.hide();
31875 this.fireEvent("invalidated", this);
31876 this.fireEvent("expanded", this);
31880 animateExpand : function(){
31884 initTabs : function()
31886 this.bodyEl.setStyle("overflow", "hidden");
31887 var ts = new Roo.TabPanel(
31890 tabPosition: this.bottomTabs ? 'bottom' : 'top',
31891 disableTooltips: this.config.disableTabTips,
31892 toolbar : this.config.toolbar
31895 if(this.config.hideTabs){
31896 ts.stripWrap.setDisplayed(false);
31899 ts.resizeTabs = this.config.resizeTabs === true;
31900 ts.minTabWidth = this.config.minTabWidth || 40;
31901 ts.maxTabWidth = this.config.maxTabWidth || 250;
31902 ts.preferredTabWidth = this.config.preferredTabWidth || 150;
31903 ts.monitorResize = false;
31904 ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
31905 ts.bodyEl.addClass('x-layout-tabs-body');
31906 this.panels.each(this.initPanelAsTab, this);
31909 initPanelAsTab : function(panel){
31910 var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
31911 this.config.closeOnTab && panel.isClosable());
31912 if(panel.tabTip !== undefined){
31913 ti.setTooltip(panel.tabTip);
31915 ti.on("activate", function(){
31916 this.setActivePanel(panel);
31918 if(this.config.closeOnTab){
31919 ti.on("beforeclose", function(t, e){
31921 this.remove(panel);
31927 updatePanelTitle : function(panel, title){
31928 if(this.activePanel == panel){
31929 this.updateTitle(title);
31932 var ti = this.tabs.getTab(panel.getEl().id);
31934 if(panel.tabTip !== undefined){
31935 ti.setTooltip(panel.tabTip);
31940 updateTitle : function(title){
31941 if(this.titleTextEl && !this.config.title){
31942 this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : " ");
31946 setActivePanel : function(panel){
31947 panel = this.getPanel(panel);
31948 if(this.activePanel && this.activePanel != panel){
31949 this.activePanel.setActiveState(false);
31951 this.activePanel = panel;
31952 panel.setActiveState(true);
31953 if(this.panelSize){
31954 panel.setSize(this.panelSize.width, this.panelSize.height);
31957 this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
31959 this.updateTitle(panel.getTitle());
31961 this.fireEvent("invalidated", this);
31963 this.fireEvent("panelactivated", this, panel);
31967 * Shows the specified panel.
31968 * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
31969 * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
31971 showPanel : function(panel){
31972 if(panel = this.getPanel(panel)){
31974 var tab = this.tabs.getTab(panel.getEl().id);
31975 if(tab.isHidden()){
31976 this.tabs.unhideTab(tab.id);
31980 this.setActivePanel(panel);
31987 * Get the active panel for this region.
31988 * @return {Roo.ContentPanel} The active panel or null
31990 getActivePanel : function(){
31991 return this.activePanel;
31994 validateVisibility : function(){
31995 if(this.panels.getCount() < 1){
31996 this.updateTitle(" ");
31997 this.closeBtn.hide();
32000 if(!this.isVisible()){
32007 * Adds the passed ContentPanel(s) to this region.
32008 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
32009 * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
32011 add : function(panel){
32012 if(arguments.length > 1){
32013 for(var i = 0, len = arguments.length; i < len; i++) {
32014 this.add(arguments[i]);
32018 if(this.hasPanel(panel)){
32019 this.showPanel(panel);
32022 panel.setRegion(this);
32023 this.panels.add(panel);
32024 if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
32025 this.bodyEl.dom.appendChild(panel.getEl().dom);
32026 if(panel.background !== true){
32027 this.setActivePanel(panel);
32029 this.fireEvent("paneladded", this, panel);
32035 this.initPanelAsTab(panel);
32037 if(panel.background !== true){
32038 this.tabs.activate(panel.getEl().id);
32040 this.fireEvent("paneladded", this, panel);
32045 * Hides the tab for the specified panel.
32046 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
32048 hidePanel : function(panel){
32049 if(this.tabs && (panel = this.getPanel(panel))){
32050 this.tabs.hideTab(panel.getEl().id);
32055 * Unhides the tab for a previously hidden panel.
32056 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
32058 unhidePanel : function(panel){
32059 if(this.tabs && (panel = this.getPanel(panel))){
32060 this.tabs.unhideTab(panel.getEl().id);
32064 clearPanels : function(){
32065 while(this.panels.getCount() > 0){
32066 this.remove(this.panels.first());
32071 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
32072 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
32073 * @param {Boolean} preservePanel Overrides the config preservePanel option
32074 * @return {Roo.ContentPanel} The panel that was removed
32076 remove : function(panel, preservePanel){
32077 panel = this.getPanel(panel);
32082 this.fireEvent("beforeremove", this, panel, e);
32083 if(e.cancel === true){
32086 preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
32087 var panelId = panel.getId();
32088 this.panels.removeKey(panelId);
32090 document.body.appendChild(panel.getEl().dom);
32093 this.tabs.removeTab(panel.getEl().id);
32094 }else if (!preservePanel){
32095 this.bodyEl.dom.removeChild(panel.getEl().dom);
32097 if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
32098 var p = this.panels.first();
32099 var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
32100 tempEl.appendChild(p.getEl().dom);
32101 this.bodyEl.update("");
32102 this.bodyEl.dom.appendChild(p.getEl().dom);
32104 this.updateTitle(p.getTitle());
32106 this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
32107 this.setActivePanel(p);
32109 panel.setRegion(null);
32110 if(this.activePanel == panel){
32111 this.activePanel = null;
32113 if(this.config.autoDestroy !== false && preservePanel !== true){
32114 try{panel.destroy();}catch(e){}
32116 this.fireEvent("panelremoved", this, panel);
32121 * Returns the TabPanel component used by this region
32122 * @return {Roo.TabPanel}
32124 getTabs : function(){
32128 createTool : function(parentEl, className){
32129 var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
32130 children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: " "}]}, true);
32131 btn.addClassOnOver("x-layout-tools-button-over");
32136 * Ext JS Library 1.1.1
32137 * Copyright(c) 2006-2007, Ext JS, LLC.
32139 * Originally Released Under LGPL - original licence link has changed is not relivant.
32142 * <script type="text/javascript">
32148 * @class Roo.SplitLayoutRegion
32149 * @extends Roo.LayoutRegion
32150 * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
32152 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
32153 this.cursor = cursor;
32154 Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
32157 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
32158 splitTip : "Drag to resize.",
32159 collapsibleSplitTip : "Drag to resize. Double click to hide.",
32160 useSplitTips : false,
32162 applyConfig : function(config){
32163 Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
32166 var splitEl = Roo.DomHelper.append(this.mgr.el.dom,
32167 {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: " "});
32168 /** The SplitBar for this region
32169 * @type Roo.SplitBar */
32170 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
32171 this.split.on("moved", this.onSplitMove, this);
32172 this.split.useShim = config.useShim === true;
32173 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
32174 if(this.useSplitTips){
32175 this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
32177 if(config.collapsible){
32178 this.split.el.on("dblclick", this.collapse, this);
32181 if(typeof config.minSize != "undefined"){
32182 this.split.minSize = config.minSize;
32184 if(typeof config.maxSize != "undefined"){
32185 this.split.maxSize = config.maxSize;
32187 if(config.hideWhenEmpty || config.hidden || config.collapsed){
32188 this.hideSplitter();
32193 getHMaxSize : function(){
32194 var cmax = this.config.maxSize || 10000;
32195 var center = this.mgr.getRegion("center");
32196 return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
32199 getVMaxSize : function(){
32200 var cmax = this.config.maxSize || 10000;
32201 var center = this.mgr.getRegion("center");
32202 return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
32205 onSplitMove : function(split, newSize){
32206 this.fireEvent("resized", this, newSize);
32210 * Returns the {@link Roo.SplitBar} for this region.
32211 * @return {Roo.SplitBar}
32213 getSplitBar : function(){
32218 this.hideSplitter();
32219 Roo.SplitLayoutRegion.superclass.hide.call(this);
32222 hideSplitter : function(){
32224 this.split.el.setLocation(-2000,-2000);
32225 this.split.el.hide();
32231 this.split.el.show();
32233 Roo.SplitLayoutRegion.superclass.show.call(this);
32236 beforeSlide: function(){
32237 if(Roo.isGecko){// firefox overflow auto bug workaround
32238 this.bodyEl.clip();
32239 if(this.tabs) this.tabs.bodyEl.clip();
32240 if(this.activePanel){
32241 this.activePanel.getEl().clip();
32243 if(this.activePanel.beforeSlide){
32244 this.activePanel.beforeSlide();
32250 afterSlide : function(){
32251 if(Roo.isGecko){// firefox overflow auto bug workaround
32252 this.bodyEl.unclip();
32253 if(this.tabs) this.tabs.bodyEl.unclip();
32254 if(this.activePanel){
32255 this.activePanel.getEl().unclip();
32256 if(this.activePanel.afterSlide){
32257 this.activePanel.afterSlide();
32263 initAutoHide : function(){
32264 if(this.autoHide !== false){
32265 if(!this.autoHideHd){
32266 var st = new Roo.util.DelayedTask(this.slideIn, this);
32267 this.autoHideHd = {
32268 "mouseout": function(e){
32269 if(!e.within(this.el, true)){
32273 "mouseover" : function(e){
32279 this.el.on(this.autoHideHd);
32283 clearAutoHide : function(){
32284 if(this.autoHide !== false){
32285 this.el.un("mouseout", this.autoHideHd.mouseout);
32286 this.el.un("mouseover", this.autoHideHd.mouseover);
32290 clearMonitor : function(){
32291 Roo.get(document).un("click", this.slideInIf, this);
32294 // these names are backwards but not changed for compat
32295 slideOut : function(){
32296 if(this.isSlid || this.el.hasActiveFx()){
32299 this.isSlid = true;
32300 if(this.collapseBtn){
32301 this.collapseBtn.hide();
32303 this.closeBtnState = this.closeBtn.getStyle('display');
32304 this.closeBtn.hide();
32306 this.stickBtn.show();
32309 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
32310 this.beforeSlide();
32311 this.el.setStyle("z-index", 10001);
32312 this.el.slideIn(this.getSlideAnchor(), {
32313 callback: function(){
32315 this.initAutoHide();
32316 Roo.get(document).on("click", this.slideInIf, this);
32317 this.fireEvent("slideshow", this);
32324 afterSlideIn : function(){
32325 this.clearAutoHide();
32326 this.isSlid = false;
32327 this.clearMonitor();
32328 this.el.setStyle("z-index", "");
32329 if(this.collapseBtn){
32330 this.collapseBtn.show();
32332 this.closeBtn.setStyle('display', this.closeBtnState);
32334 this.stickBtn.hide();
32336 this.fireEvent("slidehide", this);
32339 slideIn : function(cb){
32340 if(!this.isSlid || this.el.hasActiveFx()){
32344 this.isSlid = false;
32345 this.beforeSlide();
32346 this.el.slideOut(this.getSlideAnchor(), {
32347 callback: function(){
32348 this.el.setLeftTop(-10000, -10000);
32350 this.afterSlideIn();
32358 slideInIf : function(e){
32359 if(!e.within(this.el)){
32364 animateCollapse : function(){
32365 this.beforeSlide();
32366 this.el.setStyle("z-index", 20000);
32367 var anchor = this.getSlideAnchor();
32368 this.el.slideOut(anchor, {
32369 callback : function(){
32370 this.el.setStyle("z-index", "");
32371 this.collapsedEl.slideIn(anchor, {duration:.3});
32373 this.el.setLocation(-10000,-10000);
32375 this.fireEvent("collapsed", this);
32382 animateExpand : function(){
32383 this.beforeSlide();
32384 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
32385 this.el.setStyle("z-index", 20000);
32386 this.collapsedEl.hide({
32389 this.el.slideIn(this.getSlideAnchor(), {
32390 callback : function(){
32391 this.el.setStyle("z-index", "");
32394 this.split.el.show();
32396 this.fireEvent("invalidated", this);
32397 this.fireEvent("expanded", this);
32425 getAnchor : function(){
32426 return this.anchors[this.position];
32429 getCollapseAnchor : function(){
32430 return this.canchors[this.position];
32433 getSlideAnchor : function(){
32434 return this.sanchors[this.position];
32437 getAlignAdj : function(){
32438 var cm = this.cmargins;
32439 switch(this.position){
32455 getExpandAdj : function(){
32456 var c = this.collapsedEl, cm = this.cmargins;
32457 switch(this.position){
32459 return [-(cm.right+c.getWidth()+cm.left), 0];
32462 return [cm.right+c.getWidth()+cm.left, 0];
32465 return [0, -(cm.top+cm.bottom+c.getHeight())];
32468 return [0, cm.top+cm.bottom+c.getHeight()];
32474 * Ext JS Library 1.1.1
32475 * Copyright(c) 2006-2007, Ext JS, LLC.
32477 * Originally Released Under LGPL - original licence link has changed is not relivant.
32480 * <script type="text/javascript">
32483 * These classes are private internal classes
32485 Roo.CenterLayoutRegion = function(mgr, config){
32486 Roo.LayoutRegion.call(this, mgr, config, "center");
32487 this.visible = true;
32488 this.minWidth = config.minWidth || 20;
32489 this.minHeight = config.minHeight || 20;
32492 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
32494 // center panel can't be hidden
32498 // center panel can't be hidden
32501 getMinWidth: function(){
32502 return this.minWidth;
32505 getMinHeight: function(){
32506 return this.minHeight;
32511 Roo.NorthLayoutRegion = function(mgr, config){
32512 Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
32514 this.split.placement = Roo.SplitBar.TOP;
32515 this.split.orientation = Roo.SplitBar.VERTICAL;
32516 this.split.el.addClass("x-layout-split-v");
32518 var size = config.initialSize || config.height;
32519 if(typeof size != "undefined"){
32520 this.el.setHeight(size);
32523 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
32524 orientation: Roo.SplitBar.VERTICAL,
32525 getBox : function(){
32526 if(this.collapsed){
32527 return this.collapsedEl.getBox();
32529 var box = this.el.getBox();
32531 box.height += this.split.el.getHeight();
32536 updateBox : function(box){
32537 if(this.split && !this.collapsed){
32538 box.height -= this.split.el.getHeight();
32539 this.split.el.setLeft(box.x);
32540 this.split.el.setTop(box.y+box.height);
32541 this.split.el.setWidth(box.width);
32543 if(this.collapsed){
32544 this.updateBody(box.width, null);
32546 Roo.LayoutRegion.prototype.updateBox.call(this, box);
32550 Roo.SouthLayoutRegion = function(mgr, config){
32551 Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
32553 this.split.placement = Roo.SplitBar.BOTTOM;
32554 this.split.orientation = Roo.SplitBar.VERTICAL;
32555 this.split.el.addClass("x-layout-split-v");
32557 var size = config.initialSize || config.height;
32558 if(typeof size != "undefined"){
32559 this.el.setHeight(size);
32562 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
32563 orientation: Roo.SplitBar.VERTICAL,
32564 getBox : function(){
32565 if(this.collapsed){
32566 return this.collapsedEl.getBox();
32568 var box = this.el.getBox();
32570 var sh = this.split.el.getHeight();
32577 updateBox : function(box){
32578 if(this.split && !this.collapsed){
32579 var sh = this.split.el.getHeight();
32582 this.split.el.setLeft(box.x);
32583 this.split.el.setTop(box.y-sh);
32584 this.split.el.setWidth(box.width);
32586 if(this.collapsed){
32587 this.updateBody(box.width, null);
32589 Roo.LayoutRegion.prototype.updateBox.call(this, box);
32593 Roo.EastLayoutRegion = function(mgr, config){
32594 Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
32596 this.split.placement = Roo.SplitBar.RIGHT;
32597 this.split.orientation = Roo.SplitBar.HORIZONTAL;
32598 this.split.el.addClass("x-layout-split-h");
32600 var size = config.initialSize || config.width;
32601 if(typeof size != "undefined"){
32602 this.el.setWidth(size);
32605 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
32606 orientation: Roo.SplitBar.HORIZONTAL,
32607 getBox : function(){
32608 if(this.collapsed){
32609 return this.collapsedEl.getBox();
32611 var box = this.el.getBox();
32613 var sw = this.split.el.getWidth();
32620 updateBox : function(box){
32621 if(this.split && !this.collapsed){
32622 var sw = this.split.el.getWidth();
32624 this.split.el.setLeft(box.x);
32625 this.split.el.setTop(box.y);
32626 this.split.el.setHeight(box.height);
32629 if(this.collapsed){
32630 this.updateBody(null, box.height);
32632 Roo.LayoutRegion.prototype.updateBox.call(this, box);
32636 Roo.WestLayoutRegion = function(mgr, config){
32637 Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
32639 this.split.placement = Roo.SplitBar.LEFT;
32640 this.split.orientation = Roo.SplitBar.HORIZONTAL;
32641 this.split.el.addClass("x-layout-split-h");
32643 var size = config.initialSize || config.width;
32644 if(typeof size != "undefined"){
32645 this.el.setWidth(size);
32648 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
32649 orientation: Roo.SplitBar.HORIZONTAL,
32650 getBox : function(){
32651 if(this.collapsed){
32652 return this.collapsedEl.getBox();
32654 var box = this.el.getBox();
32656 box.width += this.split.el.getWidth();
32661 updateBox : function(box){
32662 if(this.split && !this.collapsed){
32663 var sw = this.split.el.getWidth();
32665 this.split.el.setLeft(box.x+box.width);
32666 this.split.el.setTop(box.y);
32667 this.split.el.setHeight(box.height);
32669 if(this.collapsed){
32670 this.updateBody(null, box.height);
32672 Roo.LayoutRegion.prototype.updateBox.call(this, box);
32677 * Ext JS Library 1.1.1
32678 * Copyright(c) 2006-2007, Ext JS, LLC.
32680 * Originally Released Under LGPL - original licence link has changed is not relivant.
32683 * <script type="text/javascript">
32688 * Private internal class for reading and applying state
32690 Roo.LayoutStateManager = function(layout){
32691 // default empty state
32700 Roo.LayoutStateManager.prototype = {
32701 init : function(layout, provider){
32702 this.provider = provider;
32703 var state = provider.get(layout.id+"-layout-state");
32705 var wasUpdating = layout.isUpdating();
32707 layout.beginUpdate();
32709 for(var key in state){
32710 if(typeof state[key] != "function"){
32711 var rstate = state[key];
32712 var r = layout.getRegion(key);
32715 r.resizeTo(rstate.size);
32717 if(rstate.collapsed == true){
32720 r.expand(null, true);
32726 layout.endUpdate();
32728 this.state = state;
32730 this.layout = layout;
32731 layout.on("regionresized", this.onRegionResized, this);
32732 layout.on("regioncollapsed", this.onRegionCollapsed, this);
32733 layout.on("regionexpanded", this.onRegionExpanded, this);
32736 storeState : function(){
32737 this.provider.set(this.layout.id+"-layout-state", this.state);
32740 onRegionResized : function(region, newSize){
32741 this.state[region.getPosition()].size = newSize;
32745 onRegionCollapsed : function(region){
32746 this.state[region.getPosition()].collapsed = true;
32750 onRegionExpanded : function(region){
32751 this.state[region.getPosition()].collapsed = false;
32756 * Ext JS Library 1.1.1
32757 * Copyright(c) 2006-2007, Ext JS, LLC.
32759 * Originally Released Under LGPL - original licence link has changed is not relivant.
32762 * <script type="text/javascript">
32765 * @class Roo.ContentPanel
32766 * @extends Roo.util.Observable
32767 * A basic ContentPanel element.
32768 * @cfg {Boolean} fitToFrame True for this panel to adjust its size to fit when the region resizes (defaults to false)
32769 * @cfg {Boolean} fitContainer When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container (defaults to false)
32770 * @cfg {Boolean/Object} autoCreate True to auto generate the DOM element for this panel, or a {@link Roo.DomHelper} config of the element to create
32771 * @cfg {Boolean} closable True if the panel can be closed/removed
32772 * @cfg {Boolean} background True if the panel should not be activated when it is added (defaults to false)
32773 * @cfg {String/HTMLElement/Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
32774 * @cfg {Toolbar} toolbar A toolbar for this panel
32775 * @cfg {Boolean} autoScroll True to scroll overflow in this panel (use with {@link #fitToFrame})
32776 * @cfg {String} title The title for this panel
32777 * @cfg {Array} adjustments Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
32778 * @cfg {String} url Calls {@link #setUrl} with this value
32779 * @cfg {String} region (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
32780 * @cfg {String/Object} params When used with {@link #url}, calls {@link #setUrl} with this value
32781 * @cfg {Boolean} loadOnce When used with {@link #url}, calls {@link #setUrl} with this value
32782 * @cfg {String} content Raw content to fill content panel with (uses setContent on construction.)
32785 * Create a new ContentPanel.
32786 * @param {String/HTMLElement/Roo.Element} el The container element for this panel
32787 * @param {String/Object} config A string to set only the title or a config object
32788 * @param {String} content (optional) Set the HTML content for this panel
32789 * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
32791 Roo.ContentPanel = function(el, config, content){
32795 if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
32799 if (config && config.parentLayout) {
32800 el = config.parentLayout.el.createChild();
32803 if(el.autoCreate){ // xtype is available if this is called from factory
32807 this.el = Roo.get(el);
32808 if(!this.el && config && config.autoCreate){
32809 if(typeof config.autoCreate == "object"){
32810 if(!config.autoCreate.id){
32811 config.autoCreate.id = config.id||el;
32813 this.el = Roo.DomHelper.append(document.body,
32814 config.autoCreate, true);
32816 this.el = Roo.DomHelper.append(document.body,
32817 {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
32820 this.closable = false;
32821 this.loaded = false;
32822 this.active = false;
32823 if(typeof config == "string"){
32824 this.title = config;
32826 Roo.apply(this, config);
32829 if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
32830 this.wrapEl = this.el.wrap();
32831 this.toolbar.container = this.el.insertSibling(false, 'before');
32832 this.toolbar = new Roo.Toolbar(this.toolbar);
32838 this.resizeEl = Roo.get(this.resizeEl, true);
32840 this.resizeEl = this.el;
32845 * Fires when this panel is activated.
32846 * @param {Roo.ContentPanel} this
32850 * @event deactivate
32851 * Fires when this panel is activated.
32852 * @param {Roo.ContentPanel} this
32854 "deactivate" : true,
32858 * Fires when this panel is resized if fitToFrame is true.
32859 * @param {Roo.ContentPanel} this
32860 * @param {Number} width The width after any component adjustments
32861 * @param {Number} height The height after any component adjustments
32867 * Fires when this tab is created
32868 * @param {Roo.ContentPanel} this
32875 if(this.autoScroll){
32876 this.resizeEl.setStyle("overflow", "auto");
32878 // fix randome scrolling
32879 this.el.on('scroll', function() {
32880 Roo.log('fix random scolling');
32881 this.scrollTo('top',0);
32884 content = content || this.content;
32886 this.setContent(content);
32888 if(config && config.url){
32889 this.setUrl(this.url, this.params, this.loadOnce);
32894 Roo.ContentPanel.superclass.constructor.call(this);
32896 this.fireEvent('render', this);
32899 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
32901 setRegion : function(region){
32902 this.region = region;
32904 this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
32906 this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
32911 * Returns the toolbar for this Panel if one was configured.
32912 * @return {Roo.Toolbar}
32914 getToolbar : function(){
32915 return this.toolbar;
32918 setActiveState : function(active){
32919 this.active = active;
32921 this.fireEvent("deactivate", this);
32923 this.fireEvent("activate", this);
32927 * Updates this panel's element
32928 * @param {String} content The new content
32929 * @param {Boolean} loadScripts (optional) true to look for and process scripts
32931 setContent : function(content, loadScripts){
32932 this.el.update(content, loadScripts);
32935 ignoreResize : function(w, h){
32936 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
32939 this.lastSize = {width: w, height: h};
32944 * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
32945 * @return {Roo.UpdateManager} The UpdateManager
32947 getUpdateManager : function(){
32948 return this.el.getUpdateManager();
32951 * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
32952 * @param {Object/String/Function} url The url for this request or a function to call to get the url or a config object containing any of the following options:
32955 url: "your-url.php",
32956 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
32957 callback: yourFunction,
32958 scope: yourObject, //(optional scope)
32961 text: "Loading...",
32966 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
32967 * are shorthand for <i>disableCaching</i>, <i>indicatorText</i> and <i>loadScripts</i> and are used to set their associated property on this panel UpdateManager instance.
32968 * @param {String/Object} params (optional) The parameters to pass as either a URL encoded string "param1=1&param2=2" or an object {param1: 1, param2: 2}
32969 * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
32970 * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used URL. If true, it will not store the URL.
32971 * @return {Roo.ContentPanel} this
32974 var um = this.el.getUpdateManager();
32975 um.update.apply(um, arguments);
32981 * Set a URL to be used to load the content for this panel. When this panel is activated, the content will be loaded from that URL.
32982 * @param {String/Function} url The URL to load the content from or a function to call to get the URL
32983 * @param {String/Object} params (optional) The string params for the update call or an object of the params. See {@link Roo.UpdateManager#update} for more details. (Defaults to null)
32984 * @param {Boolean} loadOnce (optional) Whether to only load the content once. If this is false it makes the Ajax call every time this panel is activated. (Defaults to false)
32985 * @return {Roo.UpdateManager} The UpdateManager
32987 setUrl : function(url, params, loadOnce){
32988 if(this.refreshDelegate){
32989 this.removeListener("activate", this.refreshDelegate);
32991 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
32992 this.on("activate", this.refreshDelegate);
32993 return this.el.getUpdateManager();
32996 _handleRefresh : function(url, params, loadOnce){
32997 if(!loadOnce || !this.loaded){
32998 var updater = this.el.getUpdateManager();
32999 updater.update(url, params, this._setLoaded.createDelegate(this));
33003 _setLoaded : function(){
33004 this.loaded = true;
33008 * Returns this panel's id
33011 getId : function(){
33016 * Returns this panel's element - used by regiosn to add.
33017 * @return {Roo.Element}
33019 getEl : function(){
33020 return this.wrapEl || this.el;
33023 adjustForComponents : function(width, height){
33024 if(this.resizeEl != this.el){
33025 width -= this.el.getFrameWidth('lr');
33026 height -= this.el.getFrameWidth('tb');
33029 var te = this.toolbar.getEl();
33030 height -= te.getHeight();
33031 te.setWidth(width);
33033 if(this.adjustments){
33034 width += this.adjustments[0];
33035 height += this.adjustments[1];
33037 return {"width": width, "height": height};
33040 setSize : function(width, height){
33041 if(this.fitToFrame && !this.ignoreResize(width, height)){
33042 if(this.fitContainer && this.resizeEl != this.el){
33043 this.el.setSize(width, height);
33045 var size = this.adjustForComponents(width, height);
33046 this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
33047 this.fireEvent('resize', this, size.width, size.height);
33052 * Returns this panel's title
33055 getTitle : function(){
33060 * Set this panel's title
33061 * @param {String} title
33063 setTitle : function(title){
33064 this.title = title;
33066 this.region.updatePanelTitle(this, title);
33071 * Returns true is this panel was configured to be closable
33072 * @return {Boolean}
33074 isClosable : function(){
33075 return this.closable;
33078 beforeSlide : function(){
33080 this.resizeEl.clip();
33083 afterSlide : function(){
33085 this.resizeEl.unclip();
33089 * Force a content refresh from the URL specified in the {@link #setUrl} method.
33090 * Will fail silently if the {@link #setUrl} method has not been called.
33091 * This does not activate the panel, just updates its content.
33093 refresh : function(){
33094 if(this.refreshDelegate){
33095 this.loaded = false;
33096 this.refreshDelegate();
33101 * Destroys this panel
33103 destroy : function(){
33104 this.el.removeAllListeners();
33105 var tempEl = document.createElement("span");
33106 tempEl.appendChild(this.el.dom);
33107 tempEl.innerHTML = "";
33113 * form - if the content panel contains a form - this is a reference to it.
33114 * @type {Roo.form.Form}
33118 * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
33119 * This contains a reference to it.
33125 * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
33135 * @param {Object} cfg Xtype definition of item to add.
33138 addxtype : function(cfg) {
33140 if (cfg.xtype.match(/^Form$/)) {
33141 var el = this.el.createChild();
33143 this.form = new Roo.form.Form(cfg);
33146 if ( this.form.allItems.length) this.form.render(el.dom);
33149 // should only have one of theses..
33150 if (['View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
33152 cfg.el = this.el.appendChild(document.createElement("div"));
33155 var ret = new Roo.factory(cfg);
33156 ret.render && ret.render(false, ''); // render blank..
33165 * @class Roo.GridPanel
33166 * @extends Roo.ContentPanel
33168 * Create a new GridPanel.
33169 * @param {Roo.grid.Grid} grid The grid for this panel
33170 * @param {String/Object} config A string to set only the panel's title, or a config object
33172 Roo.GridPanel = function(grid, config){
33175 this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
33176 {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
33178 this.wrapper.dom.appendChild(grid.getGridEl().dom);
33180 Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
33183 this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
33185 // xtype created footer. - not sure if will work as we normally have to render first..
33186 if (this.footer && !this.footer.el && this.footer.xtype) {
33188 this.footer.container = this.grid.getView().getFooterPanel(true);
33189 this.footer.dataSource = this.grid.dataSource;
33190 this.footer = Roo.factory(this.footer, Roo);
33194 grid.monitorWindowResize = false; // turn off autosizing
33195 grid.autoHeight = false;
33196 grid.autoWidth = false;
33198 this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
33201 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
33202 getId : function(){
33203 return this.grid.id;
33207 * Returns the grid for this panel
33208 * @return {Roo.grid.Grid}
33210 getGrid : function(){
33214 setSize : function(width, height){
33215 if(!this.ignoreResize(width, height)){
33216 var grid = this.grid;
33217 var size = this.adjustForComponents(width, height);
33218 grid.getGridEl().setSize(size.width, size.height);
33223 beforeSlide : function(){
33224 this.grid.getView().scroller.clip();
33227 afterSlide : function(){
33228 this.grid.getView().scroller.unclip();
33231 destroy : function(){
33232 this.grid.destroy();
33234 Roo.GridPanel.superclass.destroy.call(this);
33240 * @class Roo.NestedLayoutPanel
33241 * @extends Roo.ContentPanel
33243 * Create a new NestedLayoutPanel.
33246 * @param {Roo.BorderLayout} layout The layout for this panel
33247 * @param {String/Object} config A string to set only the title or a config object
33249 Roo.NestedLayoutPanel = function(layout, config)
33251 // construct with only one argument..
33252 /* FIXME - implement nicer consturctors
33253 if (layout.layout) {
33255 layout = config.layout;
33256 delete config.layout;
33258 if (layout.xtype && !layout.getEl) {
33259 // then layout needs constructing..
33260 layout = Roo.factory(layout, Roo);
33265 Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
33267 layout.monitorWindowResize = false; // turn off autosizing
33268 this.layout = layout;
33269 this.layout.getEl().addClass("x-layout-nested-layout");
33276 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
33278 setSize : function(width, height){
33279 if(!this.ignoreResize(width, height)){
33280 var size = this.adjustForComponents(width, height);
33281 var el = this.layout.getEl();
33282 el.setSize(size.width, size.height);
33283 var touch = el.dom.offsetWidth;
33284 this.layout.layout();
33285 // ie requires a double layout on the first pass
33286 if(Roo.isIE && !this.initialized){
33287 this.initialized = true;
33288 this.layout.layout();
33293 // activate all subpanels if not currently active..
33295 setActiveState : function(active){
33296 this.active = active;
33298 this.fireEvent("deactivate", this);
33302 this.fireEvent("activate", this);
33303 // not sure if this should happen before or after..
33304 if (!this.layout) {
33305 return; // should not happen..
33308 for (var r in this.layout.regions) {
33309 reg = this.layout.getRegion(r);
33310 if (reg.getActivePanel()) {
33311 //reg.showPanel(reg.getActivePanel()); // force it to activate..
33312 reg.setActivePanel(reg.getActivePanel());
33315 if (!reg.panels.length) {
33318 reg.showPanel(reg.getPanel(0));
33327 * Returns the nested BorderLayout for this panel
33328 * @return {Roo.BorderLayout}
33330 getLayout : function(){
33331 return this.layout;
33335 * Adds a xtype elements to the layout of the nested panel
33339 xtype : 'ContentPanel',
33346 xtype : 'NestedLayoutPanel',
33352 items : [ ... list of content panels or nested layout panels.. ]
33356 * @param {Object} cfg Xtype definition of item to add.
33358 addxtype : function(cfg) {
33359 return this.layout.addxtype(cfg);
33364 Roo.ScrollPanel = function(el, config, content){
33365 config = config || {};
33366 config.fitToFrame = true;
33367 Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
33369 this.el.dom.style.overflow = "hidden";
33370 var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
33371 this.el.removeClass("x-layout-inactive-content");
33372 this.el.on("mousewheel", this.onWheel, this);
33374 var up = wrap.createChild({cls: "x-scroller-up", html: " "}, this.el.dom);
33375 var down = wrap.createChild({cls: "x-scroller-down", html: " "});
33376 up.unselectable(); down.unselectable();
33377 up.on("click", this.scrollUp, this);
33378 down.on("click", this.scrollDown, this);
33379 up.addClassOnOver("x-scroller-btn-over");
33380 down.addClassOnOver("x-scroller-btn-over");
33381 up.addClassOnClick("x-scroller-btn-click");
33382 down.addClassOnClick("x-scroller-btn-click");
33383 this.adjustments = [0, -(up.getHeight() + down.getHeight())];
33385 this.resizeEl = this.el;
33386 this.el = wrap; this.up = up; this.down = down;
33389 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
33391 wheelIncrement : 5,
33392 scrollUp : function(){
33393 this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
33396 scrollDown : function(){
33397 this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
33400 afterScroll : function(){
33401 var el = this.resizeEl;
33402 var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
33403 this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
33404 this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
33407 setSize : function(){
33408 Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
33409 this.afterScroll();
33412 onWheel : function(e){
33413 var d = e.getWheelDelta();
33414 this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
33415 this.afterScroll();
33419 setContent : function(content, loadScripts){
33420 this.resizeEl.update(content, loadScripts);
33434 * @class Roo.TreePanel
33435 * @extends Roo.ContentPanel
33437 * Create a new TreePanel. - defaults to fit/scoll contents.
33438 * @param {String/Object} config A string to set only the panel's title, or a config object
33439 * @cfg {Roo.tree.TreePanel} tree The tree TreePanel, with config etc.
33441 Roo.TreePanel = function(config){
33442 var el = config.el;
33443 var tree = config.tree;
33444 delete config.tree;
33445 delete config.el; // hopefull!
33447 // wrapper for IE7 strict & safari scroll issue
33449 var treeEl = el.createChild();
33450 config.resizeEl = treeEl;
33454 Roo.TreePanel.superclass.constructor.call(this, el, config);
33457 this.tree = new Roo.tree.TreePanel(treeEl , tree);
33458 //console.log(tree);
33459 this.on('activate', function()
33461 if (this.tree.rendered) {
33464 //console.log('render tree');
33465 this.tree.render();
33468 this.on('resize', function (cp, w, h) {
33469 this.tree.innerCt.setWidth(w);
33470 this.tree.innerCt.setHeight(h);
33471 this.tree.innerCt.setStyle('overflow-y', 'auto');
33478 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {
33495 * Ext JS Library 1.1.1
33496 * Copyright(c) 2006-2007, Ext JS, LLC.
33498 * Originally Released Under LGPL - original licence link has changed is not relivant.
33501 * <script type="text/javascript">
33506 * @class Roo.ReaderLayout
33507 * @extends Roo.BorderLayout
33508 * This is a pre-built layout that represents a classic, 5-pane application. It consists of a header, a primary
33509 * center region containing two nested regions (a top one for a list view and one for item preview below),
33510 * and regions on either side that can be used for navigation, application commands, informational displays, etc.
33511 * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
33512 * expedites the setup of the overall layout and regions for this common application style.
33515 var reader = new Roo.ReaderLayout();
33516 var CP = Roo.ContentPanel; // shortcut for adding
33518 reader.beginUpdate();
33519 reader.add("north", new CP("north", "North"));
33520 reader.add("west", new CP("west", {title: "West"}));
33521 reader.add("east", new CP("east", {title: "East"}));
33523 reader.regions.listView.add(new CP("listView", "List"));
33524 reader.regions.preview.add(new CP("preview", "Preview"));
33525 reader.endUpdate();
33528 * Create a new ReaderLayout
33529 * @param {Object} config Configuration options
33530 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
33531 * document.body if omitted)
33533 Roo.ReaderLayout = function(config, renderTo){
33534 var c = config || {size:{}};
33535 Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
33536 north: c.north !== false ? Roo.apply({
33540 }, c.north) : false,
33541 west: c.west !== false ? Roo.apply({
33549 margins:{left:5,right:0,bottom:5,top:5},
33550 cmargins:{left:5,right:5,bottom:5,top:5}
33551 }, c.west) : false,
33552 east: c.east !== false ? Roo.apply({
33560 margins:{left:0,right:5,bottom:5,top:5},
33561 cmargins:{left:5,right:5,bottom:5,top:5}
33562 }, c.east) : false,
33563 center: Roo.apply({
33564 tabPosition: 'top',
33568 margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
33572 this.el.addClass('x-reader');
33574 this.beginUpdate();
33576 var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
33577 south: c.preview !== false ? Roo.apply({
33584 cmargins:{top:5,left:0, right:0, bottom:0}
33585 }, c.preview) : false,
33586 center: Roo.apply({
33592 this.add('center', new Roo.NestedLayoutPanel(inner,
33593 Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
33597 this.regions.preview = inner.getRegion('south');
33598 this.regions.listView = inner.getRegion('center');
33601 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
33603 * Ext JS Library 1.1.1
33604 * Copyright(c) 2006-2007, Ext JS, LLC.
33606 * Originally Released Under LGPL - original licence link has changed is not relivant.
33609 * <script type="text/javascript">
33613 * @class Roo.grid.Grid
33614 * @extends Roo.util.Observable
33615 * This class represents the primary interface of a component based grid control.
33616 * <br><br>Usage:<pre><code>
33617 var grid = new Roo.grid.Grid("my-container-id", {
33620 selModel: mySelectionModel,
33621 autoSizeColumns: true,
33622 monitorWindowResize: false,
33623 trackMouseOver: true
33628 * <b>Common Problems:</b><br/>
33629 * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
33630 * element will correct this<br/>
33631 * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
33632 * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
33633 * are unpredictable.<br/>
33634 * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
33635 * grid to calculate dimensions/offsets.<br/>
33637 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
33638 * The container MUST have some type of size defined for the grid to fill. The container will be
33639 * automatically set to position relative if it isn't already.
33640 * @param {Object} config A config object that sets properties on this grid.
33642 Roo.grid.Grid = function(container, config){
33643 // initialize the container
33644 this.container = Roo.get(container);
33645 this.container.update("");
33646 this.container.setStyle("overflow", "hidden");
33647 this.container.addClass('x-grid-container');
33649 this.id = this.container.id;
33651 Roo.apply(this, config);
33652 // check and correct shorthanded configs
33654 this.dataSource = this.ds;
33658 this.colModel = this.cm;
33662 this.selModel = this.sm;
33666 if (this.selModel) {
33667 this.selModel = Roo.factory(this.selModel, Roo.grid);
33668 this.sm = this.selModel;
33669 this.sm.xmodule = this.xmodule || false;
33671 if (typeof(this.colModel.config) == 'undefined') {
33672 this.colModel = new Roo.grid.ColumnModel(this.colModel);
33673 this.cm = this.colModel;
33674 this.cm.xmodule = this.xmodule || false;
33676 if (this.dataSource) {
33677 this.dataSource= Roo.factory(this.dataSource, Roo.data);
33678 this.ds = this.dataSource;
33679 this.ds.xmodule = this.xmodule || false;
33686 this.container.setWidth(this.width);
33690 this.container.setHeight(this.height);
33697 * The raw click event for the entire grid.
33698 * @param {Roo.EventObject} e
33703 * The raw dblclick event for the entire grid.
33704 * @param {Roo.EventObject} e
33708 * @event contextmenu
33709 * The raw contextmenu event for the entire grid.
33710 * @param {Roo.EventObject} e
33712 "contextmenu" : true,
33715 * The raw mousedown event for the entire grid.
33716 * @param {Roo.EventObject} e
33718 "mousedown" : true,
33721 * The raw mouseup event for the entire grid.
33722 * @param {Roo.EventObject} e
33727 * The raw mouseover event for the entire grid.
33728 * @param {Roo.EventObject} e
33730 "mouseover" : true,
33733 * The raw mouseout event for the entire grid.
33734 * @param {Roo.EventObject} e
33739 * The raw keypress event for the entire grid.
33740 * @param {Roo.EventObject} e
33745 * The raw keydown event for the entire grid.
33746 * @param {Roo.EventObject} e
33754 * Fires when a cell is clicked
33755 * @param {Grid} this
33756 * @param {Number} rowIndex
33757 * @param {Number} columnIndex
33758 * @param {Roo.EventObject} e
33760 "cellclick" : true,
33762 * @event celldblclick
33763 * Fires when a cell is double clicked
33764 * @param {Grid} this
33765 * @param {Number} rowIndex
33766 * @param {Number} columnIndex
33767 * @param {Roo.EventObject} e
33769 "celldblclick" : true,
33772 * Fires when a row is clicked
33773 * @param {Grid} this
33774 * @param {Number} rowIndex
33775 * @param {Roo.EventObject} e
33779 * @event rowdblclick
33780 * Fires when a row is double clicked
33781 * @param {Grid} this
33782 * @param {Number} rowIndex
33783 * @param {Roo.EventObject} e
33785 "rowdblclick" : true,
33787 * @event headerclick
33788 * Fires when a header is clicked
33789 * @param {Grid} this
33790 * @param {Number} columnIndex
33791 * @param {Roo.EventObject} e
33793 "headerclick" : true,
33795 * @event headerdblclick
33796 * Fires when a header cell is double clicked
33797 * @param {Grid} this
33798 * @param {Number} columnIndex
33799 * @param {Roo.EventObject} e
33801 "headerdblclick" : true,
33803 * @event rowcontextmenu
33804 * Fires when a row is right clicked
33805 * @param {Grid} this
33806 * @param {Number} rowIndex
33807 * @param {Roo.EventObject} e
33809 "rowcontextmenu" : true,
33811 * @event cellcontextmenu
33812 * Fires when a cell is right clicked
33813 * @param {Grid} this
33814 * @param {Number} rowIndex
33815 * @param {Number} cellIndex
33816 * @param {Roo.EventObject} e
33818 "cellcontextmenu" : true,
33820 * @event headercontextmenu
33821 * Fires when a header is right clicked
33822 * @param {Grid} this
33823 * @param {Number} columnIndex
33824 * @param {Roo.EventObject} e
33826 "headercontextmenu" : true,
33828 * @event bodyscroll
33829 * Fires when the body element is scrolled
33830 * @param {Number} scrollLeft
33831 * @param {Number} scrollTop
33833 "bodyscroll" : true,
33835 * @event columnresize
33836 * Fires when the user resizes a column
33837 * @param {Number} columnIndex
33838 * @param {Number} newSize
33840 "columnresize" : true,
33842 * @event columnmove
33843 * Fires when the user moves a column
33844 * @param {Number} oldIndex
33845 * @param {Number} newIndex
33847 "columnmove" : true,
33850 * Fires when row(s) start being dragged
33851 * @param {Grid} this
33852 * @param {Roo.GridDD} dd The drag drop object
33853 * @param {event} e The raw browser event
33855 "startdrag" : true,
33858 * Fires when a drag operation is complete
33859 * @param {Grid} this
33860 * @param {Roo.GridDD} dd The drag drop object
33861 * @param {event} e The raw browser event
33866 * Fires when dragged row(s) are dropped on a valid DD target
33867 * @param {Grid} this
33868 * @param {Roo.GridDD} dd The drag drop object
33869 * @param {String} targetId The target drag drop object
33870 * @param {event} e The raw browser event
33875 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
33876 * @param {Grid} this
33877 * @param {Roo.GridDD} dd The drag drop object
33878 * @param {String} targetId The target drag drop object
33879 * @param {event} e The raw browser event
33884 * Fires when the dragged row(s) first cross another DD target while being dragged
33885 * @param {Grid} this
33886 * @param {Roo.GridDD} dd The drag drop object
33887 * @param {String} targetId The target drag drop object
33888 * @param {event} e The raw browser event
33890 "dragenter" : true,
33893 * Fires when the dragged row(s) leave another DD target while being dragged
33894 * @param {Grid} this
33895 * @param {Roo.GridDD} dd The drag drop object
33896 * @param {String} targetId The target drag drop object
33897 * @param {event} e The raw browser event
33902 * Fires when a row is rendered, so you can change add a style to it.
33903 * @param {GridView} gridview The grid view
33904 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
33910 * Fires when the grid is rendered
33911 * @param {Grid} grid
33916 Roo.grid.Grid.superclass.constructor.call(this);
33918 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
33921 * @cfg {String} ddGroup - drag drop group.
33925 * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
33927 minColumnWidth : 25,
33930 * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
33931 * <b>on initial render.</b> It is more efficient to explicitly size the columns
33932 * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option. Default is false.
33934 autoSizeColumns : false,
33937 * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
33939 autoSizeHeaders : true,
33942 * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
33944 monitorWindowResize : true,
33947 * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
33948 * rows measured to get a columns size. Default is 0 (all rows).
33950 maxRowsToMeasure : 0,
33953 * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
33955 trackMouseOver : true,
33958 * @cfg {Boolean} enableDrag True to enable drag of rows. Default is false. (double check if this is needed?)
33962 * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
33964 enableDragDrop : false,
33967 * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
33969 enableColumnMove : true,
33972 * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
33974 enableColumnHide : true,
33977 * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
33979 enableRowHeightSync : false,
33982 * @cfg {Boolean} stripeRows True to stripe the rows. Default is true.
33987 * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
33989 autoHeight : false,
33992 * @cfg {String} autoExpandColumn The id (or dataIndex) of a column in this grid that should expand to fill unused space. This id can not be 0. Default is false.
33994 autoExpandColumn : false,
33997 * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
34000 autoExpandMin : 50,
34003 * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
34005 autoExpandMax : 1000,
34008 * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
34013 * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
34017 * @cfg {Roo.dd.DropTarget} dragTarget An {@link Roo.dd.DragTarget} config
34027 * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
34028 * of a fixed width. Default is false.
34031 * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
34034 * Called once after all setup has been completed and the grid is ready to be rendered.
34035 * @return {Roo.grid.Grid} this
34037 render : function()
34039 var c = this.container;
34040 // try to detect autoHeight/width mode
34041 if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
34042 this.autoHeight = true;
34044 var view = this.getView();
34047 c.on("click", this.onClick, this);
34048 c.on("dblclick", this.onDblClick, this);
34049 c.on("contextmenu", this.onContextMenu, this);
34050 c.on("keydown", this.onKeyDown, this);
34052 this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
34054 this.getSelectionModel().init(this);
34059 this.loadMask = new Roo.LoadMask(this.container,
34060 Roo.apply({store:this.dataSource}, this.loadMask));
34064 if (this.toolbar && this.toolbar.xtype) {
34065 this.toolbar.container = this.getView().getHeaderPanel(true);
34066 this.toolbar = new Roo.Toolbar(this.toolbar);
34068 if (this.footer && this.footer.xtype) {
34069 this.footer.dataSource = this.getDataSource();
34070 this.footer.container = this.getView().getFooterPanel(true);
34071 this.footer = Roo.factory(this.footer, Roo);
34073 if (this.dropTarget && this.dropTarget.xtype) {
34074 delete this.dropTarget.xtype;
34075 this.dropTarget = new Ext.dd.DropTarget(this.getView().mainBody, this.dropTarget);
34079 this.rendered = true;
34080 this.fireEvent('render', this);
34085 * Reconfigures the grid to use a different Store and Column Model.
34086 * The View will be bound to the new objects and refreshed.
34087 * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
34088 * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
34090 reconfigure : function(dataSource, colModel){
34092 this.loadMask.destroy();
34093 this.loadMask = new Roo.LoadMask(this.container,
34094 Roo.apply({store:dataSource}, this.loadMask));
34096 this.view.bind(dataSource, colModel);
34097 this.dataSource = dataSource;
34098 this.colModel = colModel;
34099 this.view.refresh(true);
34103 onKeyDown : function(e){
34104 this.fireEvent("keydown", e);
34108 * Destroy this grid.
34109 * @param {Boolean} removeEl True to remove the element
34111 destroy : function(removeEl, keepListeners){
34113 this.loadMask.destroy();
34115 var c = this.container;
34116 c.removeAllListeners();
34117 this.view.destroy();
34118 this.colModel.purgeListeners();
34119 if(!keepListeners){
34120 this.purgeListeners();
34123 if(removeEl === true){
34129 processEvent : function(name, e){
34130 this.fireEvent(name, e);
34131 var t = e.getTarget();
34133 var header = v.findHeaderIndex(t);
34134 if(header !== false){
34135 this.fireEvent("header" + name, this, header, e);
34137 var row = v.findRowIndex(t);
34138 var cell = v.findCellIndex(t);
34140 this.fireEvent("row" + name, this, row, e);
34141 if(cell !== false){
34142 this.fireEvent("cell" + name, this, row, cell, e);
34149 onClick : function(e){
34150 this.processEvent("click", e);
34154 onContextMenu : function(e, t){
34155 this.processEvent("contextmenu", e);
34159 onDblClick : function(e){
34160 this.processEvent("dblclick", e);
34164 walkCells : function(row, col, step, fn, scope){
34165 var cm = this.colModel, clen = cm.getColumnCount();
34166 var ds = this.dataSource, rlen = ds.getCount(), first = true;
34178 if(fn.call(scope || this, row, col, cm) === true){
34196 if(fn.call(scope || this, row, col, cm) === true){
34208 getSelections : function(){
34209 return this.selModel.getSelections();
34213 * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
34214 * but if manual update is required this method will initiate it.
34216 autoSize : function(){
34218 this.view.layout();
34219 if(this.view.adjustForScroll){
34220 this.view.adjustForScroll();
34226 * Returns the grid's underlying element.
34227 * @return {Element} The element
34229 getGridEl : function(){
34230 return this.container;
34233 // private for compatibility, overridden by editor grid
34234 stopEditing : function(){},
34237 * Returns the grid's SelectionModel.
34238 * @return {SelectionModel}
34240 getSelectionModel : function(){
34241 if(!this.selModel){
34242 this.selModel = new Roo.grid.RowSelectionModel();
34244 return this.selModel;
34248 * Returns the grid's DataSource.
34249 * @return {DataSource}
34251 getDataSource : function(){
34252 return this.dataSource;
34256 * Returns the grid's ColumnModel.
34257 * @return {ColumnModel}
34259 getColumnModel : function(){
34260 return this.colModel;
34264 * Returns the grid's GridView object.
34265 * @return {GridView}
34267 getView : function(){
34269 this.view = new Roo.grid.GridView(this.viewConfig);
34274 * Called to get grid's drag proxy text, by default returns this.ddText.
34277 getDragDropText : function(){
34278 var count = this.selModel.getCount();
34279 return String.format(this.ddText, count, count == 1 ? '' : 's');
34283 * Configures the text is the drag proxy (defaults to "%0 selected row(s)").
34284 * %0 is replaced with the number of selected rows.
34287 Roo.grid.Grid.prototype.ddText = "{0} selected row{1}";/*
34289 * Ext JS Library 1.1.1
34290 * Copyright(c) 2006-2007, Ext JS, LLC.
34292 * Originally Released Under LGPL - original licence link has changed is not relivant.
34295 * <script type="text/javascript">
34298 Roo.grid.AbstractGridView = function(){
34302 "beforerowremoved" : true,
34303 "beforerowsinserted" : true,
34304 "beforerefresh" : true,
34305 "rowremoved" : true,
34306 "rowsinserted" : true,
34307 "rowupdated" : true,
34310 Roo.grid.AbstractGridView.superclass.constructor.call(this);
34313 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
34314 rowClass : "x-grid-row",
34315 cellClass : "x-grid-cell",
34316 tdClass : "x-grid-td",
34317 hdClass : "x-grid-hd",
34318 splitClass : "x-grid-hd-split",
34320 init: function(grid){
34322 var cid = this.grid.getGridEl().id;
34323 this.colSelector = "#" + cid + " ." + this.cellClass + "-";
34324 this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
34325 this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
34326 this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
34329 getColumnRenderers : function(){
34330 var renderers = [];
34331 var cm = this.grid.colModel;
34332 var colCount = cm.getColumnCount();
34333 for(var i = 0; i < colCount; i++){
34334 renderers[i] = cm.getRenderer(i);
34339 getColumnIds : function(){
34341 var cm = this.grid.colModel;
34342 var colCount = cm.getColumnCount();
34343 for(var i = 0; i < colCount; i++){
34344 ids[i] = cm.getColumnId(i);
34349 getDataIndexes : function(){
34350 if(!this.indexMap){
34351 this.indexMap = this.buildIndexMap();
34353 return this.indexMap.colToData;
34356 getColumnIndexByDataIndex : function(dataIndex){
34357 if(!this.indexMap){
34358 this.indexMap = this.buildIndexMap();
34360 return this.indexMap.dataToCol[dataIndex];
34364 * Set a css style for a column dynamically.
34365 * @param {Number} colIndex The index of the column
34366 * @param {String} name The css property name
34367 * @param {String} value The css value
34369 setCSSStyle : function(colIndex, name, value){
34370 var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
34371 Roo.util.CSS.updateRule(selector, name, value);
34374 generateRules : function(cm){
34375 var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
34376 Roo.util.CSS.removeStyleSheet(rulesId);
34377 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
34378 var cid = cm.getColumnId(i);
34379 ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
34380 this.tdSelector, cid, " {\n}\n",
34381 this.hdSelector, cid, " {\n}\n",
34382 this.splitSelector, cid, " {\n}\n");
34384 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
34388 * Ext JS Library 1.1.1
34389 * Copyright(c) 2006-2007, Ext JS, LLC.
34391 * Originally Released Under LGPL - original licence link has changed is not relivant.
34394 * <script type="text/javascript">
34398 // This is a support class used internally by the Grid components
34399 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
34401 this.view = grid.getView();
34402 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
34403 Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
34405 this.setHandleElId(Roo.id(hd));
34406 this.setOuterHandleElId(Roo.id(hd2));
34408 this.scroll = false;
34410 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
34412 getDragData : function(e){
34413 var t = Roo.lib.Event.getTarget(e);
34414 var h = this.view.findHeaderCell(t);
34416 return {ddel: h.firstChild, header:h};
34421 onInitDrag : function(e){
34422 this.view.headersDisabled = true;
34423 var clone = this.dragData.ddel.cloneNode(true);
34424 clone.id = Roo.id();
34425 clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
34426 this.proxy.update(clone);
34430 afterValidDrop : function(){
34432 setTimeout(function(){
34433 v.headersDisabled = false;
34437 afterInvalidDrop : function(){
34439 setTimeout(function(){
34440 v.headersDisabled = false;
34446 * Ext JS Library 1.1.1
34447 * Copyright(c) 2006-2007, Ext JS, LLC.
34449 * Originally Released Under LGPL - original licence link has changed is not relivant.
34452 * <script type="text/javascript">
34455 // This is a support class used internally by the Grid components
34456 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
34458 this.view = grid.getView();
34459 // split the proxies so they don't interfere with mouse events
34460 this.proxyTop = Roo.DomHelper.append(document.body, {
34461 cls:"col-move-top", html:" "
34463 this.proxyBottom = Roo.DomHelper.append(document.body, {
34464 cls:"col-move-bottom", html:" "
34466 this.proxyTop.hide = this.proxyBottom.hide = function(){
34467 this.setLeftTop(-100,-100);
34468 this.setStyle("visibility", "hidden");
34470 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
34471 // temporarily disabled
34472 //Roo.dd.ScrollManager.register(this.view.scroller.dom);
34473 Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
34475 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
34476 proxyOffsets : [-4, -9],
34477 fly: Roo.Element.fly,
34479 getTargetFromEvent : function(e){
34480 var t = Roo.lib.Event.getTarget(e);
34481 var cindex = this.view.findCellIndex(t);
34482 if(cindex !== false){
34483 return this.view.getHeaderCell(cindex);
34488 nextVisible : function(h){
34489 var v = this.view, cm = this.grid.colModel;
34492 if(!cm.isHidden(v.getCellIndex(h))){
34500 prevVisible : function(h){
34501 var v = this.view, cm = this.grid.colModel;
34504 if(!cm.isHidden(v.getCellIndex(h))){
34512 positionIndicator : function(h, n, e){
34513 var x = Roo.lib.Event.getPageX(e);
34514 var r = Roo.lib.Dom.getRegion(n.firstChild);
34515 var px, pt, py = r.top + this.proxyOffsets[1];
34516 if((r.right - x) <= (r.right-r.left)/2){
34517 px = r.right+this.view.borderWidth;
34523 var oldIndex = this.view.getCellIndex(h);
34524 var newIndex = this.view.getCellIndex(n);
34526 if(this.grid.colModel.isFixed(newIndex)){
34530 var locked = this.grid.colModel.isLocked(newIndex);
34535 if(oldIndex < newIndex){
34538 if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
34541 px += this.proxyOffsets[0];
34542 this.proxyTop.setLeftTop(px, py);
34543 this.proxyTop.show();
34544 if(!this.bottomOffset){
34545 this.bottomOffset = this.view.mainHd.getHeight();
34547 this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
34548 this.proxyBottom.show();
34552 onNodeEnter : function(n, dd, e, data){
34553 if(data.header != n){
34554 this.positionIndicator(data.header, n, e);
34558 onNodeOver : function(n, dd, e, data){
34559 var result = false;
34560 if(data.header != n){
34561 result = this.positionIndicator(data.header, n, e);
34564 this.proxyTop.hide();
34565 this.proxyBottom.hide();
34567 return result ? this.dropAllowed : this.dropNotAllowed;
34570 onNodeOut : function(n, dd, e, data){
34571 this.proxyTop.hide();
34572 this.proxyBottom.hide();
34575 onNodeDrop : function(n, dd, e, data){
34576 var h = data.header;
34578 var cm = this.grid.colModel;
34579 var x = Roo.lib.Event.getPageX(e);
34580 var r = Roo.lib.Dom.getRegion(n.firstChild);
34581 var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
34582 var oldIndex = this.view.getCellIndex(h);
34583 var newIndex = this.view.getCellIndex(n);
34584 var locked = cm.isLocked(newIndex);
34588 if(oldIndex < newIndex){
34591 if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
34594 cm.setLocked(oldIndex, locked, true);
34595 cm.moveColumn(oldIndex, newIndex);
34596 this.grid.fireEvent("columnmove", oldIndex, newIndex);
34604 * Ext JS Library 1.1.1
34605 * Copyright(c) 2006-2007, Ext JS, LLC.
34607 * Originally Released Under LGPL - original licence link has changed is not relivant.
34610 * <script type="text/javascript">
34614 * @class Roo.grid.GridView
34615 * @extends Roo.util.Observable
34618 * @param {Object} config
34620 Roo.grid.GridView = function(config){
34621 Roo.grid.GridView.superclass.constructor.call(this);
34624 Roo.apply(this, config);
34627 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
34630 rowClass : "x-grid-row",
34632 cellClass : "x-grid-col",
34634 tdClass : "x-grid-td",
34636 hdClass : "x-grid-hd",
34638 splitClass : "x-grid-split",
34640 sortClasses : ["sort-asc", "sort-desc"],
34642 enableMoveAnim : false,
34646 dh : Roo.DomHelper,
34648 fly : Roo.Element.fly,
34650 css : Roo.util.CSS,
34656 scrollIncrement : 22,
34658 cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
34660 findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
34662 bind : function(ds, cm){
34664 this.ds.un("load", this.onLoad, this);
34665 this.ds.un("datachanged", this.onDataChange, this);
34666 this.ds.un("add", this.onAdd, this);
34667 this.ds.un("remove", this.onRemove, this);
34668 this.ds.un("update", this.onUpdate, this);
34669 this.ds.un("clear", this.onClear, this);
34672 ds.on("load", this.onLoad, this);
34673 ds.on("datachanged", this.onDataChange, this);
34674 ds.on("add", this.onAdd, this);
34675 ds.on("remove", this.onRemove, this);
34676 ds.on("update", this.onUpdate, this);
34677 ds.on("clear", this.onClear, this);
34682 this.cm.un("widthchange", this.onColWidthChange, this);
34683 this.cm.un("headerchange", this.onHeaderChange, this);
34684 this.cm.un("hiddenchange", this.onHiddenChange, this);
34685 this.cm.un("columnmoved", this.onColumnMove, this);
34686 this.cm.un("columnlockchange", this.onColumnLock, this);
34689 this.generateRules(cm);
34690 cm.on("widthchange", this.onColWidthChange, this);
34691 cm.on("headerchange", this.onHeaderChange, this);
34692 cm.on("hiddenchange", this.onHiddenChange, this);
34693 cm.on("columnmoved", this.onColumnMove, this);
34694 cm.on("columnlockchange", this.onColumnLock, this);
34699 init: function(grid){
34700 Roo.grid.GridView.superclass.init.call(this, grid);
34702 this.bind(grid.dataSource, grid.colModel);
34704 grid.on("headerclick", this.handleHeaderClick, this);
34706 if(grid.trackMouseOver){
34707 grid.on("mouseover", this.onRowOver, this);
34708 grid.on("mouseout", this.onRowOut, this);
34710 grid.cancelTextSelection = function(){};
34711 this.gridId = grid.id;
34713 var tpls = this.templates || {};
34716 tpls.master = new Roo.Template(
34717 '<div class="x-grid" hidefocus="true">',
34718 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
34719 '<div class="x-grid-topbar"></div>',
34720 '<div class="x-grid-scroller"><div></div></div>',
34721 '<div class="x-grid-locked">',
34722 '<div class="x-grid-header">{lockedHeader}</div>',
34723 '<div class="x-grid-body">{lockedBody}</div>',
34725 '<div class="x-grid-viewport">',
34726 '<div class="x-grid-header">{header}</div>',
34727 '<div class="x-grid-body">{body}</div>',
34729 '<div class="x-grid-bottombar"></div>',
34731 '<div class="x-grid-resize-proxy"> </div>',
34734 tpls.master.disableformats = true;
34738 tpls.header = new Roo.Template(
34739 '<table border="0" cellspacing="0" cellpadding="0">',
34740 '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
34743 tpls.header.disableformats = true;
34745 tpls.header.compile();
34748 tpls.hcell = new Roo.Template(
34749 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
34750 '<div class="x-grid-hd-text" unselectable="on">{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
34753 tpls.hcell.disableFormats = true;
34755 tpls.hcell.compile();
34758 tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style}" unselectable="on"> </div>');
34759 tpls.hsplit.disableFormats = true;
34761 tpls.hsplit.compile();
34764 tpls.body = new Roo.Template(
34765 '<table border="0" cellspacing="0" cellpadding="0">',
34766 "<tbody>{rows}</tbody>",
34769 tpls.body.disableFormats = true;
34771 tpls.body.compile();
34774 tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
34775 tpls.row.disableFormats = true;
34777 tpls.row.compile();
34780 tpls.cell = new Roo.Template(
34781 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
34782 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text" unselectable="on" {attr}>{value}</div></div>',
34785 tpls.cell.disableFormats = true;
34787 tpls.cell.compile();
34789 this.templates = tpls;
34792 // remap these for backwards compat
34793 onColWidthChange : function(){
34794 this.updateColumns.apply(this, arguments);
34796 onHeaderChange : function(){
34797 this.updateHeaders.apply(this, arguments);
34799 onHiddenChange : function(){
34800 this.handleHiddenChange.apply(this, arguments);
34802 onColumnMove : function(){
34803 this.handleColumnMove.apply(this, arguments);
34805 onColumnLock : function(){
34806 this.handleLockChange.apply(this, arguments);
34809 onDataChange : function(){
34811 this.updateHeaderSortState();
34814 onClear : function(){
34818 onUpdate : function(ds, record){
34819 this.refreshRow(record);
34822 refreshRow : function(record){
34823 var ds = this.ds, index;
34824 if(typeof record == 'number'){
34826 record = ds.getAt(index);
34828 index = ds.indexOf(record);
34830 this.insertRows(ds, index, index, true);
34831 this.onRemove(ds, record, index+1, true);
34832 this.syncRowHeights(index, index);
34834 this.fireEvent("rowupdated", this, index, record);
34837 onAdd : function(ds, records, index){
34838 this.insertRows(ds, index, index + (records.length-1));
34841 onRemove : function(ds, record, index, isUpdate){
34842 if(isUpdate !== true){
34843 this.fireEvent("beforerowremoved", this, index, record);
34845 var bt = this.getBodyTable(), lt = this.getLockedTable();
34846 if(bt.rows[index]){
34847 bt.firstChild.removeChild(bt.rows[index]);
34849 if(lt.rows[index]){
34850 lt.firstChild.removeChild(lt.rows[index]);
34852 if(isUpdate !== true){
34853 this.stripeRows(index);
34854 this.syncRowHeights(index, index);
34856 this.fireEvent("rowremoved", this, index, record);
34860 onLoad : function(){
34861 this.scrollToTop();
34865 * Scrolls the grid to the top
34867 scrollToTop : function(){
34869 this.scroller.dom.scrollTop = 0;
34875 * Gets a panel in the header of the grid that can be used for toolbars etc.
34876 * After modifying the contents of this panel a call to grid.autoSize() may be
34877 * required to register any changes in size.
34878 * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
34879 * @return Roo.Element
34881 getHeaderPanel : function(doShow){
34883 this.headerPanel.show();
34885 return this.headerPanel;
34889 * Gets a panel in the footer of the grid that can be used for toolbars etc.
34890 * After modifying the contents of this panel a call to grid.autoSize() may be
34891 * required to register any changes in size.
34892 * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
34893 * @return Roo.Element
34895 getFooterPanel : function(doShow){
34897 this.footerPanel.show();
34899 return this.footerPanel;
34902 initElements : function(){
34903 var E = Roo.Element;
34904 var el = this.grid.getGridEl().dom.firstChild;
34905 var cs = el.childNodes;
34907 this.el = new E(el);
34909 this.focusEl = new E(el.firstChild);
34910 this.focusEl.swallowEvent("click", true);
34912 this.headerPanel = new E(cs[1]);
34913 this.headerPanel.enableDisplayMode("block");
34915 this.scroller = new E(cs[2]);
34916 this.scrollSizer = new E(this.scroller.dom.firstChild);
34918 this.lockedWrap = new E(cs[3]);
34919 this.lockedHd = new E(this.lockedWrap.dom.firstChild);
34920 this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
34922 this.mainWrap = new E(cs[4]);
34923 this.mainHd = new E(this.mainWrap.dom.firstChild);
34924 this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
34926 this.footerPanel = new E(cs[5]);
34927 this.footerPanel.enableDisplayMode("block");
34929 this.resizeProxy = new E(cs[6]);
34931 this.headerSelector = String.format(
34932 '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
34933 this.lockedHd.id, this.mainHd.id
34936 this.splitterSelector = String.format(
34937 '#{0} div.x-grid-split, #{1} div.x-grid-split',
34938 this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
34941 idToCssName : function(s)
34943 return s.replace(/[^a-z0-9]+/ig, '-');
34946 getHeaderCell : function(index){
34947 return Roo.DomQuery.select(this.headerSelector)[index];
34950 getHeaderCellMeasure : function(index){
34951 return this.getHeaderCell(index).firstChild;
34954 getHeaderCellText : function(index){
34955 return this.getHeaderCell(index).firstChild.firstChild;
34958 getLockedTable : function(){
34959 return this.lockedBody.dom.firstChild;
34962 getBodyTable : function(){
34963 return this.mainBody.dom.firstChild;
34966 getLockedRow : function(index){
34967 return this.getLockedTable().rows[index];
34970 getRow : function(index){
34971 return this.getBodyTable().rows[index];
34974 getRowComposite : function(index){
34976 this.rowEl = new Roo.CompositeElementLite();
34978 var els = [], lrow, mrow;
34979 if(lrow = this.getLockedRow(index)){
34982 if(mrow = this.getRow(index)){
34985 this.rowEl.elements = els;
34989 * Gets the 'td' of the cell
34991 * @param {Integer} rowIndex row to select
34992 * @param {Integer} colIndex column to select
34996 getCell : function(rowIndex, colIndex){
34997 var locked = this.cm.getLockedCount();
34999 if(colIndex < locked){
35000 source = this.lockedBody.dom.firstChild;
35002 source = this.mainBody.dom.firstChild;
35003 colIndex -= locked;
35005 return source.rows[rowIndex].childNodes[colIndex];
35008 getCellText : function(rowIndex, colIndex){
35009 return this.getCell(rowIndex, colIndex).firstChild.firstChild;
35012 getCellBox : function(cell){
35013 var b = this.fly(cell).getBox();
35014 if(Roo.isOpera){ // opera fails to report the Y
35015 b.y = cell.offsetTop + this.mainBody.getY();
35020 getCellIndex : function(cell){
35021 var id = String(cell.className).match(this.cellRE);
35023 return parseInt(id[1], 10);
35028 findHeaderIndex : function(n){
35029 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
35030 return r ? this.getCellIndex(r) : false;
35033 findHeaderCell : function(n){
35034 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
35035 return r ? r : false;
35038 findRowIndex : function(n){
35042 var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
35043 return r ? r.rowIndex : false;
35046 findCellIndex : function(node){
35047 var stop = this.el.dom;
35048 while(node && node != stop){
35049 if(this.findRE.test(node.className)){
35050 return this.getCellIndex(node);
35052 node = node.parentNode;
35057 getColumnId : function(index){
35058 return this.cm.getColumnId(index);
35061 getSplitters : function()
35063 if(this.splitterSelector){
35064 return Roo.DomQuery.select(this.splitterSelector);
35070 getSplitter : function(index){
35071 return this.getSplitters()[index];
35074 onRowOver : function(e, t){
35076 if((row = this.findRowIndex(t)) !== false){
35077 this.getRowComposite(row).addClass("x-grid-row-over");
35081 onRowOut : function(e, t){
35083 if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
35084 this.getRowComposite(row).removeClass("x-grid-row-over");
35088 renderHeaders : function(){
35090 var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
35091 var cb = [], lb = [], sb = [], lsb = [], p = {};
35092 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
35093 p.cellId = "x-grid-hd-0-" + i;
35094 p.splitId = "x-grid-csplit-0-" + i;
35095 p.id = cm.getColumnId(i);
35096 p.title = cm.getColumnTooltip(i) || "";
35097 p.value = cm.getColumnHeader(i) || "";
35098 p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
35099 if(!cm.isLocked(i)){
35100 cb[cb.length] = ct.apply(p);
35101 sb[sb.length] = st.apply(p);
35103 lb[lb.length] = ct.apply(p);
35104 lsb[lsb.length] = st.apply(p);
35107 return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
35108 ht.apply({cells: cb.join(""), splits:sb.join("")})];
35111 updateHeaders : function(){
35112 var html = this.renderHeaders();
35113 this.lockedHd.update(html[0]);
35114 this.mainHd.update(html[1]);
35118 * Focuses the specified row.
35119 * @param {Number} row The row index
35121 focusRow : function(row)
35123 //Roo.log('GridView.focusRow');
35124 var x = this.scroller.dom.scrollLeft;
35125 this.focusCell(row, 0, false);
35126 this.scroller.dom.scrollLeft = x;
35130 * Focuses the specified cell.
35131 * @param {Number} row The row index
35132 * @param {Number} col The column index
35133 * @param {Boolean} hscroll false to disable horizontal scrolling
35135 focusCell : function(row, col, hscroll)
35137 //Roo.log('GridView.focusCell');
35138 var el = this.ensureVisible(row, col, hscroll);
35139 this.focusEl.alignTo(el, "tl-tl");
35141 this.focusEl.focus();
35143 this.focusEl.focus.defer(1, this.focusEl);
35148 * Scrolls the specified cell into view
35149 * @param {Number} row The row index
35150 * @param {Number} col The column index
35151 * @param {Boolean} hscroll false to disable horizontal scrolling
35153 ensureVisible : function(row, col, hscroll)
35155 //Roo.log('GridView.ensureVisible,' + row + ',' + col);
35156 //return null; //disable for testing.
35157 if(typeof row != "number"){
35158 row = row.rowIndex;
35160 if(row < 0 && row >= this.ds.getCount()){
35163 col = (col !== undefined ? col : 0);
35164 var cm = this.grid.colModel;
35165 while(cm.isHidden(col)){
35169 var el = this.getCell(row, col);
35173 var c = this.scroller.dom;
35175 var ctop = parseInt(el.offsetTop, 10);
35176 var cleft = parseInt(el.offsetLeft, 10);
35177 var cbot = ctop + el.offsetHeight;
35178 var cright = cleft + el.offsetWidth;
35180 var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
35181 var stop = parseInt(c.scrollTop, 10);
35182 var sleft = parseInt(c.scrollLeft, 10);
35183 var sbot = stop + ch;
35184 var sright = sleft + c.clientWidth;
35186 Roo.log('GridView.ensureVisible:' +
35188 ' c.clientHeight:' + c.clientHeight +
35189 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
35197 c.scrollTop = ctop;
35198 //Roo.log("set scrolltop to ctop DISABLE?");
35199 }else if(cbot > sbot){
35200 //Roo.log("set scrolltop to cbot-ch");
35201 c.scrollTop = cbot-ch;
35204 if(hscroll !== false){
35206 c.scrollLeft = cleft;
35207 }else if(cright > sright){
35208 c.scrollLeft = cright-c.clientWidth;
35215 updateColumns : function(){
35216 this.grid.stopEditing();
35217 var cm = this.grid.colModel, colIds = this.getColumnIds();
35218 //var totalWidth = cm.getTotalWidth();
35220 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
35221 //if(cm.isHidden(i)) continue;
35222 var w = cm.getColumnWidth(i);
35223 this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
35224 this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
35226 this.updateSplitters();
35229 generateRules : function(cm){
35230 var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
35231 Roo.util.CSS.removeStyleSheet(rulesId);
35232 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
35233 var cid = cm.getColumnId(i);
35235 if(cm.config[i].align){
35236 align = 'text-align:'+cm.config[i].align+';';
35239 if(cm.isHidden(i)){
35240 hidden = 'display:none;';
35242 var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
35244 this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
35245 this.hdSelector, cid, " {\n", align, width, "}\n",
35246 this.tdSelector, cid, " {\n",hidden,"\n}\n",
35247 this.splitSelector, cid, " {\n", hidden , "\n}\n");
35249 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
35252 updateSplitters : function(){
35253 var cm = this.cm, s = this.getSplitters();
35254 if(s){ // splitters not created yet
35255 var pos = 0, locked = true;
35256 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
35257 if(cm.isHidden(i)) continue;
35258 var w = cm.getColumnWidth(i); // make sure it's a number
35259 if(!cm.isLocked(i) && locked){
35264 s[i].style.left = (pos-this.splitOffset) + "px";
35269 handleHiddenChange : function(colModel, colIndex, hidden){
35271 this.hideColumn(colIndex);
35273 this.unhideColumn(colIndex);
35277 hideColumn : function(colIndex){
35278 var cid = this.getColumnId(colIndex);
35279 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
35280 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
35282 this.updateHeaders();
35284 this.updateSplitters();
35288 unhideColumn : function(colIndex){
35289 var cid = this.getColumnId(colIndex);
35290 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
35291 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
35294 this.updateHeaders();
35296 this.updateSplitters();
35300 insertRows : function(dm, firstRow, lastRow, isUpdate){
35301 if(firstRow == 0 && lastRow == dm.getCount()-1){
35305 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
35307 var s = this.getScrollState();
35308 var markup = this.renderRows(firstRow, lastRow);
35309 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
35310 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
35311 this.restoreScroll(s);
35313 this.fireEvent("rowsinserted", this, firstRow, lastRow);
35314 this.syncRowHeights(firstRow, lastRow);
35315 this.stripeRows(firstRow);
35321 bufferRows : function(markup, target, index){
35322 var before = null, trows = target.rows, tbody = target.tBodies[0];
35323 if(index < trows.length){
35324 before = trows[index];
35326 var b = document.createElement("div");
35327 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
35328 var rows = b.firstChild.rows;
35329 for(var i = 0, len = rows.length; i < len; i++){
35331 tbody.insertBefore(rows[0], before);
35333 tbody.appendChild(rows[0]);
35340 deleteRows : function(dm, firstRow, lastRow){
35341 if(dm.getRowCount()<1){
35342 this.fireEvent("beforerefresh", this);
35343 this.mainBody.update("");
35344 this.lockedBody.update("");
35345 this.fireEvent("refresh", this);
35347 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
35348 var bt = this.getBodyTable();
35349 var tbody = bt.firstChild;
35350 var rows = bt.rows;
35351 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
35352 tbody.removeChild(rows[firstRow]);
35354 this.stripeRows(firstRow);
35355 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
35359 updateRows : function(dataSource, firstRow, lastRow){
35360 var s = this.getScrollState();
35362 this.restoreScroll(s);
35365 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
35369 this.updateHeaderSortState();
35372 getScrollState : function(){
35374 var sb = this.scroller.dom;
35375 return {left: sb.scrollLeft, top: sb.scrollTop};
35378 stripeRows : function(startRow){
35379 if(!this.grid.stripeRows || this.ds.getCount() < 1){
35382 startRow = startRow || 0;
35383 var rows = this.getBodyTable().rows;
35384 var lrows = this.getLockedTable().rows;
35385 var cls = ' x-grid-row-alt ';
35386 for(var i = startRow, len = rows.length; i < len; i++){
35387 var row = rows[i], lrow = lrows[i];
35388 var isAlt = ((i+1) % 2 == 0);
35389 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
35390 if(isAlt == hasAlt){
35394 row.className += " x-grid-row-alt";
35396 row.className = row.className.replace("x-grid-row-alt", "");
35399 lrow.className = row.className;
35404 restoreScroll : function(state){
35405 //Roo.log('GridView.restoreScroll');
35406 var sb = this.scroller.dom;
35407 sb.scrollLeft = state.left;
35408 sb.scrollTop = state.top;
35412 syncScroll : function(){
35413 //Roo.log('GridView.syncScroll');
35414 var sb = this.scroller.dom;
35415 var sh = this.mainHd.dom;
35416 var bs = this.mainBody.dom;
35417 var lv = this.lockedBody.dom;
35418 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
35419 lv.scrollTop = bs.scrollTop = sb.scrollTop;
35422 handleScroll : function(e){
35424 var sb = this.scroller.dom;
35425 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
35429 handleWheel : function(e){
35430 var d = e.getWheelDelta();
35431 this.scroller.dom.scrollTop -= d*22;
35432 // set this here to prevent jumpy scrolling on large tables
35433 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
35437 renderRows : function(startRow, endRow){
35438 // pull in all the crap needed to render rows
35439 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
35440 var colCount = cm.getColumnCount();
35442 if(ds.getCount() < 1){
35446 // build a map for all the columns
35448 for(var i = 0; i < colCount; i++){
35449 var name = cm.getDataIndex(i);
35451 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
35452 renderer : cm.getRenderer(i),
35453 id : cm.getColumnId(i),
35454 locked : cm.isLocked(i)
35458 startRow = startRow || 0;
35459 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
35461 // records to render
35462 var rs = ds.getRange(startRow, endRow);
35464 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
35467 // As much as I hate to duplicate code, this was branched because FireFox really hates
35468 // [].join("") on strings. The performance difference was substantial enough to
35469 // branch this function
35470 doRender : Roo.isGecko ?
35471 function(cs, rs, ds, startRow, colCount, stripe){
35472 var ts = this.templates, ct = ts.cell, rt = ts.row;
35474 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
35476 var hasListener = this.grid.hasListener('rowclass');
35478 for(var j = 0, len = rs.length; j < len; j++){
35479 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
35480 for(var i = 0; i < colCount; i++){
35482 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
35484 p.css = p.attr = "";
35485 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
35486 if(p.value == undefined || p.value === "") p.value = " ";
35487 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
35488 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
35490 var markup = ct.apply(p);
35498 if(stripe && ((rowIndex+1) % 2 == 0)){
35499 alt.push("x-grid-row-alt")
35502 alt.push( " x-grid-dirty-row");
35505 if(this.getRowClass){
35506 alt.push(this.getRowClass(r, rowIndex));
35512 rowIndex : rowIndex,
35515 this.grid.fireEvent('rowclass', this, rowcfg);
35516 alt.push(rowcfg.rowClass);
35518 rp.alt = alt.join(" ");
35519 lbuf+= rt.apply(rp);
35521 buf+= rt.apply(rp);
35523 return [lbuf, buf];
35525 function(cs, rs, ds, startRow, colCount, stripe){
35526 var ts = this.templates, ct = ts.cell, rt = ts.row;
35528 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
35529 var hasListener = this.grid.hasListener('rowclass');
35532 for(var j = 0, len = rs.length; j < len; j++){
35533 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
35534 for(var i = 0; i < colCount; i++){
35536 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
35538 p.css = p.attr = "";
35539 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
35540 if(p.value == undefined || p.value === "") p.value = " ";
35541 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
35542 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
35545 var markup = ct.apply(p);
35547 cb[cb.length] = markup;
35549 lcb[lcb.length] = markup;
35553 if(stripe && ((rowIndex+1) % 2 == 0)){
35554 alt.push( "x-grid-row-alt");
35557 alt.push(" x-grid-dirty-row");
35560 if(this.getRowClass){
35561 alt.push( this.getRowClass(r, rowIndex));
35567 rowIndex : rowIndex,
35570 this.grid.fireEvent('rowclass', this, rowcfg);
35571 alt.push(rowcfg.rowClass);
35573 rp.alt = alt.join(" ");
35574 rp.cells = lcb.join("");
35575 lbuf[lbuf.length] = rt.apply(rp);
35576 rp.cells = cb.join("");
35577 buf[buf.length] = rt.apply(rp);
35579 return [lbuf.join(""), buf.join("")];
35582 renderBody : function(){
35583 var markup = this.renderRows();
35584 var bt = this.templates.body;
35585 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
35589 * Refreshes the grid
35590 * @param {Boolean} headersToo
35592 refresh : function(headersToo){
35593 this.fireEvent("beforerefresh", this);
35594 this.grid.stopEditing();
35595 var result = this.renderBody();
35596 this.lockedBody.update(result[0]);
35597 this.mainBody.update(result[1]);
35598 if(headersToo === true){
35599 this.updateHeaders();
35600 this.updateColumns();
35601 this.updateSplitters();
35602 this.updateHeaderSortState();
35604 this.syncRowHeights();
35606 this.fireEvent("refresh", this);
35609 handleColumnMove : function(cm, oldIndex, newIndex){
35610 this.indexMap = null;
35611 var s = this.getScrollState();
35612 this.refresh(true);
35613 this.restoreScroll(s);
35614 this.afterMove(newIndex);
35617 afterMove : function(colIndex){
35618 if(this.enableMoveAnim && Roo.enableFx){
35619 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
35621 // if multisort - fix sortOrder, and reload..
35622 if (this.grid.dataSource.multiSort) {
35623 // the we can call sort again..
35624 var dm = this.grid.dataSource;
35625 var cm = this.grid.colModel;
35627 for(var i = 0; i < cm.config.length; i++ ) {
35629 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
35630 continue; // dont' bother, it's not in sort list or being set.
35633 so.push(cm.config[i].dataIndex);
35636 dm.load(dm.lastOptions);
35643 updateCell : function(dm, rowIndex, dataIndex){
35644 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
35645 if(typeof colIndex == "undefined"){ // not present in grid
35648 var cm = this.grid.colModel;
35649 var cell = this.getCell(rowIndex, colIndex);
35650 var cellText = this.getCellText(rowIndex, colIndex);
35653 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
35654 id : cm.getColumnId(colIndex),
35655 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
35657 var renderer = cm.getRenderer(colIndex);
35658 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
35659 if(typeof val == "undefined" || val === "") val = " ";
35660 cellText.innerHTML = val;
35661 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
35662 this.syncRowHeights(rowIndex, rowIndex);
35665 calcColumnWidth : function(colIndex, maxRowsToMeasure){
35667 if(this.grid.autoSizeHeaders){
35668 var h = this.getHeaderCellMeasure(colIndex);
35669 maxWidth = Math.max(maxWidth, h.scrollWidth);
35672 if(this.cm.isLocked(colIndex)){
35673 tb = this.getLockedTable();
35676 tb = this.getBodyTable();
35677 index = colIndex - this.cm.getLockedCount();
35680 var rows = tb.rows;
35681 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
35682 for(var i = 0; i < stopIndex; i++){
35683 var cell = rows[i].childNodes[index].firstChild;
35684 maxWidth = Math.max(maxWidth, cell.scrollWidth);
35687 return maxWidth + /*margin for error in IE*/ 5;
35690 * Autofit a column to its content.
35691 * @param {Number} colIndex
35692 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
35694 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
35695 if(this.cm.isHidden(colIndex)){
35696 return; // can't calc a hidden column
35699 var cid = this.cm.getColumnId(colIndex);
35700 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
35701 if(this.grid.autoSizeHeaders){
35702 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
35705 var newWidth = this.calcColumnWidth(colIndex);
35706 this.cm.setColumnWidth(colIndex,
35707 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
35708 if(!suppressEvent){
35709 this.grid.fireEvent("columnresize", colIndex, newWidth);
35714 * Autofits all columns to their content and then expands to fit any extra space in the grid
35716 autoSizeColumns : function(){
35717 var cm = this.grid.colModel;
35718 var colCount = cm.getColumnCount();
35719 for(var i = 0; i < colCount; i++){
35720 this.autoSizeColumn(i, true, true);
35722 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
35725 this.updateColumns();
35731 * Autofits all columns to the grid's width proportionate with their current size
35732 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
35734 fitColumns : function(reserveScrollSpace){
35735 var cm = this.grid.colModel;
35736 var colCount = cm.getColumnCount();
35740 for (i = 0; i < colCount; i++){
35741 if(!cm.isHidden(i) && !cm.isFixed(i)){
35742 w = cm.getColumnWidth(i);
35748 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
35749 if(reserveScrollSpace){
35752 var frac = (avail - cm.getTotalWidth())/width;
35753 while (cols.length){
35756 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
35758 this.updateColumns();
35762 onRowSelect : function(rowIndex){
35763 var row = this.getRowComposite(rowIndex);
35764 row.addClass("x-grid-row-selected");
35767 onRowDeselect : function(rowIndex){
35768 var row = this.getRowComposite(rowIndex);
35769 row.removeClass("x-grid-row-selected");
35772 onCellSelect : function(row, col){
35773 var cell = this.getCell(row, col);
35775 Roo.fly(cell).addClass("x-grid-cell-selected");
35779 onCellDeselect : function(row, col){
35780 var cell = this.getCell(row, col);
35782 Roo.fly(cell).removeClass("x-grid-cell-selected");
35786 updateHeaderSortState : function(){
35788 // sort state can be single { field: xxx, direction : yyy}
35789 // or { xxx=>ASC , yyy : DESC ..... }
35792 if (!this.ds.multiSort) {
35793 var state = this.ds.getSortState();
35797 mstate[state.field] = state.direction;
35798 // FIXME... - this is not used here.. but might be elsewhere..
35799 this.sortState = state;
35802 mstate = this.ds.sortToggle;
35804 //remove existing sort classes..
35806 var sc = this.sortClasses;
35807 var hds = this.el.select(this.headerSelector).removeClass(sc);
35809 for(var f in mstate) {
35811 var sortColumn = this.cm.findColumnIndex(f);
35813 if(sortColumn != -1){
35814 var sortDir = mstate[f];
35815 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
35824 handleHeaderClick : function(g, index){
35825 if(this.headersDisabled){
35828 var dm = g.dataSource, cm = g.colModel;
35829 if(!cm.isSortable(index)){
35834 if (dm.multiSort) {
35835 // update the sortOrder
35837 for(var i = 0; i < cm.config.length; i++ ) {
35839 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
35840 continue; // dont' bother, it's not in sort list or being set.
35843 so.push(cm.config[i].dataIndex);
35849 dm.sort(cm.getDataIndex(index));
35853 destroy : function(){
35855 this.colMenu.removeAll();
35856 Roo.menu.MenuMgr.unregister(this.colMenu);
35857 this.colMenu.getEl().remove();
35858 delete this.colMenu;
35861 this.hmenu.removeAll();
35862 Roo.menu.MenuMgr.unregister(this.hmenu);
35863 this.hmenu.getEl().remove();
35866 if(this.grid.enableColumnMove){
35867 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
35869 for(var dd in dds){
35870 if(!dds[dd].config.isTarget && dds[dd].dragElId){
35871 var elid = dds[dd].dragElId;
35873 Roo.get(elid).remove();
35874 } else if(dds[dd].config.isTarget){
35875 dds[dd].proxyTop.remove();
35876 dds[dd].proxyBottom.remove();
35879 if(Roo.dd.DDM.locationCache[dd]){
35880 delete Roo.dd.DDM.locationCache[dd];
35883 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
35886 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
35887 this.bind(null, null);
35888 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
35891 handleLockChange : function(){
35892 this.refresh(true);
35895 onDenyColumnLock : function(){
35899 onDenyColumnHide : function(){
35903 handleHdMenuClick : function(item){
35904 var index = this.hdCtxIndex;
35905 var cm = this.cm, ds = this.ds;
35908 ds.sort(cm.getDataIndex(index), "ASC");
35911 ds.sort(cm.getDataIndex(index), "DESC");
35914 var lc = cm.getLockedCount();
35915 if(cm.getColumnCount(true) <= lc+1){
35916 this.onDenyColumnLock();
35920 cm.setLocked(index, true, true);
35921 cm.moveColumn(index, lc);
35922 this.grid.fireEvent("columnmove", index, lc);
35924 cm.setLocked(index, true);
35928 var lc = cm.getLockedCount();
35929 if((lc-1) != index){
35930 cm.setLocked(index, false, true);
35931 cm.moveColumn(index, lc-1);
35932 this.grid.fireEvent("columnmove", index, lc-1);
35934 cm.setLocked(index, false);
35938 index = cm.getIndexById(item.id.substr(4));
35940 if(item.checked && cm.getColumnCount(true) <= 1){
35941 this.onDenyColumnHide();
35944 cm.setHidden(index, item.checked);
35950 beforeColMenuShow : function(){
35951 var cm = this.cm, colCount = cm.getColumnCount();
35952 this.colMenu.removeAll();
35953 for(var i = 0; i < colCount; i++){
35954 this.colMenu.add(new Roo.menu.CheckItem({
35955 id: "col-"+cm.getColumnId(i),
35956 text: cm.getColumnHeader(i),
35957 checked: !cm.isHidden(i),
35963 handleHdCtx : function(g, index, e){
35965 var hd = this.getHeaderCell(index);
35966 this.hdCtxIndex = index;
35967 var ms = this.hmenu.items, cm = this.cm;
35968 ms.get("asc").setDisabled(!cm.isSortable(index));
35969 ms.get("desc").setDisabled(!cm.isSortable(index));
35970 if(this.grid.enableColLock !== false){
35971 ms.get("lock").setDisabled(cm.isLocked(index));
35972 ms.get("unlock").setDisabled(!cm.isLocked(index));
35974 this.hmenu.show(hd, "tl-bl");
35977 handleHdOver : function(e){
35978 var hd = this.findHeaderCell(e.getTarget());
35979 if(hd && !this.headersDisabled){
35980 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
35981 this.fly(hd).addClass("x-grid-hd-over");
35986 handleHdOut : function(e){
35987 var hd = this.findHeaderCell(e.getTarget());
35989 this.fly(hd).removeClass("x-grid-hd-over");
35993 handleSplitDblClick : function(e, t){
35994 var i = this.getCellIndex(t);
35995 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
35996 this.autoSizeColumn(i, true);
36001 render : function(){
36004 var colCount = cm.getColumnCount();
36006 if(this.grid.monitorWindowResize === true){
36007 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
36009 var header = this.renderHeaders();
36010 var body = this.templates.body.apply({rows:""});
36011 var html = this.templates.master.apply({
36014 lockedHeader: header[0],
36018 //this.updateColumns();
36020 this.grid.getGridEl().dom.innerHTML = html;
36022 this.initElements();
36024 // a kludge to fix the random scolling effect in webkit
36025 this.el.on("scroll", function() {
36026 this.el.dom.scrollTop=0; // hopefully not recursive..
36029 this.scroller.on("scroll", this.handleScroll, this);
36030 this.lockedBody.on("mousewheel", this.handleWheel, this);
36031 this.mainBody.on("mousewheel", this.handleWheel, this);
36033 this.mainHd.on("mouseover", this.handleHdOver, this);
36034 this.mainHd.on("mouseout", this.handleHdOut, this);
36035 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
36036 {delegate: "."+this.splitClass});
36038 this.lockedHd.on("mouseover", this.handleHdOver, this);
36039 this.lockedHd.on("mouseout", this.handleHdOut, this);
36040 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
36041 {delegate: "."+this.splitClass});
36043 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
36044 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
36047 this.updateSplitters();
36049 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
36050 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
36051 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
36054 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
36055 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
36057 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
36058 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
36060 if(this.grid.enableColLock !== false){
36061 this.hmenu.add('-',
36062 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
36063 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
36066 if(this.grid.enableColumnHide !== false){
36068 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
36069 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
36070 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
36072 this.hmenu.add('-',
36073 {id:"columns", text: this.columnsText, menu: this.colMenu}
36076 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
36078 this.grid.on("headercontextmenu", this.handleHdCtx, this);
36081 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
36082 this.dd = new Roo.grid.GridDragZone(this.grid, {
36083 ddGroup : this.grid.ddGroup || 'GridDD'
36088 for(var i = 0; i < colCount; i++){
36089 if(cm.isHidden(i)){
36090 this.hideColumn(i);
36092 if(cm.config[i].align){
36093 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
36094 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
36098 this.updateHeaderSortState();
36100 this.beforeInitialResize();
36103 // two part rendering gives faster view to the user
36104 this.renderPhase2.defer(1, this);
36107 renderPhase2 : function(){
36108 // render the rows now
36110 if(this.grid.autoSizeColumns){
36111 this.autoSizeColumns();
36115 beforeInitialResize : function(){
36119 onColumnSplitterMoved : function(i, w){
36120 this.userResized = true;
36121 var cm = this.grid.colModel;
36122 cm.setColumnWidth(i, w, true);
36123 var cid = cm.getColumnId(i);
36124 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
36125 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
36126 this.updateSplitters();
36128 this.grid.fireEvent("columnresize", i, w);
36131 syncRowHeights : function(startIndex, endIndex){
36132 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
36133 startIndex = startIndex || 0;
36134 var mrows = this.getBodyTable().rows;
36135 var lrows = this.getLockedTable().rows;
36136 var len = mrows.length-1;
36137 endIndex = Math.min(endIndex || len, len);
36138 for(var i = startIndex; i <= endIndex; i++){
36139 var m = mrows[i], l = lrows[i];
36140 var h = Math.max(m.offsetHeight, l.offsetHeight);
36141 m.style.height = l.style.height = h + "px";
36146 layout : function(initialRender, is2ndPass){
36148 var auto = g.autoHeight;
36149 var scrollOffset = 16;
36150 var c = g.getGridEl(), cm = this.cm,
36151 expandCol = g.autoExpandColumn,
36153 //c.beginMeasure();
36155 if(!c.dom.offsetWidth){ // display:none?
36157 this.lockedWrap.show();
36158 this.mainWrap.show();
36163 var hasLock = this.cm.isLocked(0);
36165 var tbh = this.headerPanel.getHeight();
36166 var bbh = this.footerPanel.getHeight();
36169 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
36170 var newHeight = ch + c.getBorderWidth("tb");
36172 newHeight = Math.min(g.maxHeight, newHeight);
36174 c.setHeight(newHeight);
36178 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
36181 var s = this.scroller;
36183 var csize = c.getSize(true);
36185 this.el.setSize(csize.width, csize.height);
36187 this.headerPanel.setWidth(csize.width);
36188 this.footerPanel.setWidth(csize.width);
36190 var hdHeight = this.mainHd.getHeight();
36191 var vw = csize.width;
36192 var vh = csize.height - (tbh + bbh);
36196 var bt = this.getBodyTable();
36197 var ltWidth = hasLock ?
36198 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
36200 var scrollHeight = bt.offsetHeight;
36201 var scrollWidth = ltWidth + bt.offsetWidth;
36202 var vscroll = false, hscroll = false;
36204 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
36206 var lw = this.lockedWrap, mw = this.mainWrap;
36207 var lb = this.lockedBody, mb = this.mainBody;
36209 setTimeout(function(){
36210 var t = s.dom.offsetTop;
36211 var w = s.dom.clientWidth,
36212 h = s.dom.clientHeight;
36215 lw.setSize(ltWidth, h);
36217 mw.setLeftTop(ltWidth, t);
36218 mw.setSize(w-ltWidth, h);
36220 lb.setHeight(h-hdHeight);
36221 mb.setHeight(h-hdHeight);
36223 if(is2ndPass !== true && !gv.userResized && expandCol){
36224 // high speed resize without full column calculation
36226 var ci = cm.getIndexById(expandCol);
36228 ci = cm.findColumnIndex(expandCol);
36230 ci = Math.max(0, ci); // make sure it's got at least the first col.
36231 var expandId = cm.getColumnId(ci);
36232 var tw = cm.getTotalWidth(false);
36233 var currentWidth = cm.getColumnWidth(ci);
36234 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
36235 if(currentWidth != cw){
36236 cm.setColumnWidth(ci, cw, true);
36237 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
36238 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
36239 gv.updateSplitters();
36240 gv.layout(false, true);
36252 onWindowResize : function(){
36253 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
36259 appendFooter : function(parentEl){
36263 sortAscText : "Sort Ascending",
36264 sortDescText : "Sort Descending",
36265 lockText : "Lock Column",
36266 unlockText : "Unlock Column",
36267 columnsText : "Columns"
36271 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
36272 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
36273 this.proxy.el.addClass('x-grid3-col-dd');
36276 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
36277 handleMouseDown : function(e){
36281 callHandleMouseDown : function(e){
36282 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
36287 * Ext JS Library 1.1.1
36288 * Copyright(c) 2006-2007, Ext JS, LLC.
36290 * Originally Released Under LGPL - original licence link has changed is not relivant.
36293 * <script type="text/javascript">
36297 // This is a support class used internally by the Grid components
36298 Roo.grid.SplitDragZone = function(grid, hd, hd2){
36300 this.view = grid.getView();
36301 this.proxy = this.view.resizeProxy;
36302 Roo.grid.SplitDragZone.superclass.constructor.call(this, hd,
36303 "gridSplitters" + this.grid.getGridEl().id, {
36304 dragElId : Roo.id(this.proxy.dom), resizeFrame:false
36306 this.setHandleElId(Roo.id(hd));
36307 this.setOuterHandleElId(Roo.id(hd2));
36308 this.scroll = false;
36310 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
36311 fly: Roo.Element.fly,
36313 b4StartDrag : function(x, y){
36314 this.view.headersDisabled = true;
36315 this.proxy.setHeight(this.view.mainWrap.getHeight());
36316 var w = this.cm.getColumnWidth(this.cellIndex);
36317 var minw = Math.max(w-this.grid.minColumnWidth, 0);
36318 this.resetConstraints();
36319 this.setXConstraint(minw, 1000);
36320 this.setYConstraint(0, 0);
36321 this.minX = x - minw;
36322 this.maxX = x + 1000;
36324 Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
36328 handleMouseDown : function(e){
36329 ev = Roo.EventObject.setEvent(e);
36330 var t = this.fly(ev.getTarget());
36331 if(t.hasClass("x-grid-split")){
36332 this.cellIndex = this.view.getCellIndex(t.dom);
36333 this.split = t.dom;
36334 this.cm = this.grid.colModel;
36335 if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
36336 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
36341 endDrag : function(e){
36342 this.view.headersDisabled = false;
36343 var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
36344 var diff = endX - this.startPos;
36345 this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff);
36348 autoOffset : function(){
36349 this.setDelta(0,0);
36353 * Ext JS Library 1.1.1
36354 * Copyright(c) 2006-2007, Ext JS, LLC.
36356 * Originally Released Under LGPL - original licence link has changed is not relivant.
36359 * <script type="text/javascript">
36363 // This is a support class used internally by the Grid components
36364 Roo.grid.GridDragZone = function(grid, config){
36365 this.view = grid.getView();
36366 Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
36367 if(this.view.lockedBody){
36368 this.setHandleElId(Roo.id(this.view.mainBody.dom));
36369 this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
36371 this.scroll = false;
36373 this.ddel = document.createElement('div');
36374 this.ddel.className = 'x-grid-dd-wrap';
36377 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
36378 ddGroup : "GridDD",
36380 getDragData : function(e){
36381 var t = Roo.lib.Event.getTarget(e);
36382 var rowIndex = this.view.findRowIndex(t);
36383 if(rowIndex !== false){
36384 var sm = this.grid.selModel;
36385 //if(!sm.isSelected(rowIndex) || e.hasModifier()){
36386 // sm.mouseDown(e, t);
36388 if (e.hasModifier()){
36389 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
36391 return {grid: this.grid, ddel: this.ddel, rowIndex: rowIndex, selections:sm.getSelections()};
36396 onInitDrag : function(e){
36397 var data = this.dragData;
36398 this.ddel.innerHTML = this.grid.getDragDropText();
36399 this.proxy.update(this.ddel);
36400 // fire start drag?
36403 afterRepair : function(){
36404 this.dragging = false;
36407 getRepairXY : function(e, data){
36411 onEndDrag : function(data, e){
36415 onValidDrop : function(dd, e, id){
36420 beforeInvalidDrop : function(e, id){
36425 * Ext JS Library 1.1.1
36426 * Copyright(c) 2006-2007, Ext JS, LLC.
36428 * Originally Released Under LGPL - original licence link has changed is not relivant.
36431 * <script type="text/javascript">
36436 * @class Roo.grid.ColumnModel
36437 * @extends Roo.util.Observable
36438 * This is the default implementation of a ColumnModel used by the Grid. It defines
36439 * the columns in the grid.
36442 var colModel = new Roo.grid.ColumnModel([
36443 {header: "Ticker", width: 60, sortable: true, locked: true},
36444 {header: "Company Name", width: 150, sortable: true},
36445 {header: "Market Cap.", width: 100, sortable: true},
36446 {header: "$ Sales", width: 100, sortable: true, renderer: money},
36447 {header: "Employees", width: 100, sortable: true, resizable: false}
36452 * The config options listed for this class are options which may appear in each
36453 * individual column definition.
36454 * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
36456 * @param {Object} config An Array of column config objects. See this class's
36457 * config objects for details.
36459 Roo.grid.ColumnModel = function(config){
36461 * The config passed into the constructor
36463 this.config = config;
36466 // if no id, create one
36467 // if the column does not have a dataIndex mapping,
36468 // map it to the order it is in the config
36469 for(var i = 0, len = config.length; i < len; i++){
36471 if(typeof c.dataIndex == "undefined"){
36474 if(typeof c.renderer == "string"){
36475 c.renderer = Roo.util.Format[c.renderer];
36477 if(typeof c.id == "undefined"){
36480 if(c.editor && c.editor.xtype){
36481 c.editor = Roo.factory(c.editor, Roo.grid);
36483 if(c.editor && c.editor.isFormField){
36484 c.editor = new Roo.grid.GridEditor(c.editor);
36486 this.lookup[c.id] = c;
36490 * The width of columns which have no width specified (defaults to 100)
36493 this.defaultWidth = 100;
36496 * Default sortable of columns which have no sortable specified (defaults to false)
36499 this.defaultSortable = false;
36503 * @event widthchange
36504 * Fires when the width of a column changes.
36505 * @param {ColumnModel} this
36506 * @param {Number} columnIndex The column index
36507 * @param {Number} newWidth The new width
36509 "widthchange": true,
36511 * @event headerchange
36512 * Fires when the text of a header changes.
36513 * @param {ColumnModel} this
36514 * @param {Number} columnIndex The column index
36515 * @param {Number} newText The new header text
36517 "headerchange": true,
36519 * @event hiddenchange
36520 * Fires when a column is hidden or "unhidden".
36521 * @param {ColumnModel} this
36522 * @param {Number} columnIndex The column index
36523 * @param {Boolean} hidden true if hidden, false otherwise
36525 "hiddenchange": true,
36527 * @event columnmoved
36528 * Fires when a column is moved.
36529 * @param {ColumnModel} this
36530 * @param {Number} oldIndex
36531 * @param {Number} newIndex
36533 "columnmoved" : true,
36535 * @event columlockchange
36536 * Fires when a column's locked state is changed
36537 * @param {ColumnModel} this
36538 * @param {Number} colIndex
36539 * @param {Boolean} locked true if locked
36541 "columnlockchange" : true
36543 Roo.grid.ColumnModel.superclass.constructor.call(this);
36545 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
36547 * @cfg {String} header The header text to display in the Grid view.
36550 * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
36551 * {@link Roo.data.Record} definition from which to draw the column's value. If not
36552 * specified, the column's index is used as an index into the Record's data Array.
36555 * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
36556 * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
36559 * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
36560 * Defaults to the value of the {@link #defaultSortable} property.
36561 * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
36564 * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid. Defaults to false.
36567 * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed. Defaults to false.
36570 * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
36573 * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
36576 * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
36577 * given the cell's data value. See {@link #setRenderer}. If not specified, the
36578 * default renderer uses the raw data value.
36581 * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor
36584 * @cfg {String} align (Optional) Set the CSS text-align property of the column. Defaults to undefined.
36588 * Returns the id of the column at the specified index.
36589 * @param {Number} index The column index
36590 * @return {String} the id
36592 getColumnId : function(index){
36593 return this.config[index].id;
36597 * Returns the column for a specified id.
36598 * @param {String} id The column id
36599 * @return {Object} the column
36601 getColumnById : function(id){
36602 return this.lookup[id];
36607 * Returns the column for a specified dataIndex.
36608 * @param {String} dataIndex The column dataIndex
36609 * @return {Object|Boolean} the column or false if not found
36611 getColumnByDataIndex: function(dataIndex){
36612 var index = this.findColumnIndex(dataIndex);
36613 return index > -1 ? this.config[index] : false;
36617 * Returns the index for a specified column id.
36618 * @param {String} id The column id
36619 * @return {Number} the index, or -1 if not found
36621 getIndexById : function(id){
36622 for(var i = 0, len = this.config.length; i < len; i++){
36623 if(this.config[i].id == id){
36631 * Returns the index for a specified column dataIndex.
36632 * @param {String} dataIndex The column dataIndex
36633 * @return {Number} the index, or -1 if not found
36636 findColumnIndex : function(dataIndex){
36637 for(var i = 0, len = this.config.length; i < len; i++){
36638 if(this.config[i].dataIndex == dataIndex){
36646 moveColumn : function(oldIndex, newIndex){
36647 var c = this.config[oldIndex];
36648 this.config.splice(oldIndex, 1);
36649 this.config.splice(newIndex, 0, c);
36650 this.dataMap = null;
36651 this.fireEvent("columnmoved", this, oldIndex, newIndex);
36654 isLocked : function(colIndex){
36655 return this.config[colIndex].locked === true;
36658 setLocked : function(colIndex, value, suppressEvent){
36659 if(this.isLocked(colIndex) == value){
36662 this.config[colIndex].locked = value;
36663 if(!suppressEvent){
36664 this.fireEvent("columnlockchange", this, colIndex, value);
36668 getTotalLockedWidth : function(){
36669 var totalWidth = 0;
36670 for(var i = 0; i < this.config.length; i++){
36671 if(this.isLocked(i) && !this.isHidden(i)){
36672 this.totalWidth += this.getColumnWidth(i);
36678 getLockedCount : function(){
36679 for(var i = 0, len = this.config.length; i < len; i++){
36680 if(!this.isLocked(i)){
36687 * Returns the number of columns.
36690 getColumnCount : function(visibleOnly){
36691 if(visibleOnly === true){
36693 for(var i = 0, len = this.config.length; i < len; i++){
36694 if(!this.isHidden(i)){
36700 return this.config.length;
36704 * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
36705 * @param {Function} fn
36706 * @param {Object} scope (optional)
36707 * @return {Array} result
36709 getColumnsBy : function(fn, scope){
36711 for(var i = 0, len = this.config.length; i < len; i++){
36712 var c = this.config[i];
36713 if(fn.call(scope||this, c, i) === true){
36721 * Returns true if the specified column is sortable.
36722 * @param {Number} col The column index
36723 * @return {Boolean}
36725 isSortable : function(col){
36726 if(typeof this.config[col].sortable == "undefined"){
36727 return this.defaultSortable;
36729 return this.config[col].sortable;
36733 * Returns the rendering (formatting) function defined for the column.
36734 * @param {Number} col The column index.
36735 * @return {Function} The function used to render the cell. See {@link #setRenderer}.
36737 getRenderer : function(col){
36738 if(!this.config[col].renderer){
36739 return Roo.grid.ColumnModel.defaultRenderer;
36741 return this.config[col].renderer;
36745 * Sets the rendering (formatting) function for a column.
36746 * @param {Number} col The column index
36747 * @param {Function} fn The function to use to process the cell's raw data
36748 * to return HTML markup for the grid view. The render function is called with
36749 * the following parameters:<ul>
36750 * <li>Data value.</li>
36751 * <li>Cell metadata. An object in which you may set the following attributes:<ul>
36752 * <li>css A CSS style string to apply to the table cell.</li>
36753 * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
36754 * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
36755 * <li>Row index</li>
36756 * <li>Column index</li>
36757 * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
36759 setRenderer : function(col, fn){
36760 this.config[col].renderer = fn;
36764 * Returns the width for the specified column.
36765 * @param {Number} col The column index
36768 getColumnWidth : function(col){
36769 return this.config[col].width * 1 || this.defaultWidth;
36773 * Sets the width for a column.
36774 * @param {Number} col The column index
36775 * @param {Number} width The new width
36777 setColumnWidth : function(col, width, suppressEvent){
36778 this.config[col].width = width;
36779 this.totalWidth = null;
36780 if(!suppressEvent){
36781 this.fireEvent("widthchange", this, col, width);
36786 * Returns the total width of all columns.
36787 * @param {Boolean} includeHidden True to include hidden column widths
36790 getTotalWidth : function(includeHidden){
36791 if(!this.totalWidth){
36792 this.totalWidth = 0;
36793 for(var i = 0, len = this.config.length; i < len; i++){
36794 if(includeHidden || !this.isHidden(i)){
36795 this.totalWidth += this.getColumnWidth(i);
36799 return this.totalWidth;
36803 * Returns the header for the specified column.
36804 * @param {Number} col The column index
36807 getColumnHeader : function(col){
36808 return this.config[col].header;
36812 * Sets the header for a column.
36813 * @param {Number} col The column index
36814 * @param {String} header The new header
36816 setColumnHeader : function(col, header){
36817 this.config[col].header = header;
36818 this.fireEvent("headerchange", this, col, header);
36822 * Returns the tooltip for the specified column.
36823 * @param {Number} col The column index
36826 getColumnTooltip : function(col){
36827 return this.config[col].tooltip;
36830 * Sets the tooltip for a column.
36831 * @param {Number} col The column index
36832 * @param {String} tooltip The new tooltip
36834 setColumnTooltip : function(col, tooltip){
36835 this.config[col].tooltip = tooltip;
36839 * Returns the dataIndex for the specified column.
36840 * @param {Number} col The column index
36843 getDataIndex : function(col){
36844 return this.config[col].dataIndex;
36848 * Sets the dataIndex for a column.
36849 * @param {Number} col The column index
36850 * @param {Number} dataIndex The new dataIndex
36852 setDataIndex : function(col, dataIndex){
36853 this.config[col].dataIndex = dataIndex;
36859 * Returns true if the cell is editable.
36860 * @param {Number} colIndex The column index
36861 * @param {Number} rowIndex The row index
36862 * @return {Boolean}
36864 isCellEditable : function(colIndex, rowIndex){
36865 return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
36869 * Returns the editor defined for the cell/column.
36870 * return false or null to disable editing.
36871 * @param {Number} colIndex The column index
36872 * @param {Number} rowIndex The row index
36875 getCellEditor : function(colIndex, rowIndex){
36876 return this.config[colIndex].editor;
36880 * Sets if a column is editable.
36881 * @param {Number} col The column index
36882 * @param {Boolean} editable True if the column is editable
36884 setEditable : function(col, editable){
36885 this.config[col].editable = editable;
36890 * Returns true if the column is hidden.
36891 * @param {Number} colIndex The column index
36892 * @return {Boolean}
36894 isHidden : function(colIndex){
36895 return this.config[colIndex].hidden;
36900 * Returns true if the column width cannot be changed
36902 isFixed : function(colIndex){
36903 return this.config[colIndex].fixed;
36907 * Returns true if the column can be resized
36908 * @return {Boolean}
36910 isResizable : function(colIndex){
36911 return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
36914 * Sets if a column is hidden.
36915 * @param {Number} colIndex The column index
36916 * @param {Boolean} hidden True if the column is hidden
36918 setHidden : function(colIndex, hidden){
36919 this.config[colIndex].hidden = hidden;
36920 this.totalWidth = null;
36921 this.fireEvent("hiddenchange", this, colIndex, hidden);
36925 * Sets the editor for a column.
36926 * @param {Number} col The column index
36927 * @param {Object} editor The editor object
36929 setEditor : function(col, editor){
36930 this.config[col].editor = editor;
36934 Roo.grid.ColumnModel.defaultRenderer = function(value){
36935 if(typeof value == "string" && value.length < 1){
36941 // Alias for backwards compatibility
36942 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
36945 * Ext JS Library 1.1.1
36946 * Copyright(c) 2006-2007, Ext JS, LLC.
36948 * Originally Released Under LGPL - original licence link has changed is not relivant.
36951 * <script type="text/javascript">
36955 * @class Roo.grid.AbstractSelectionModel
36956 * @extends Roo.util.Observable
36957 * Abstract base class for grid SelectionModels. It provides the interface that should be
36958 * implemented by descendant classes. This class should not be directly instantiated.
36961 Roo.grid.AbstractSelectionModel = function(){
36962 this.locked = false;
36963 Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
36966 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable, {
36967 /** @ignore Called by the grid automatically. Do not call directly. */
36968 init : function(grid){
36974 * Locks the selections.
36977 this.locked = true;
36981 * Unlocks the selections.
36983 unlock : function(){
36984 this.locked = false;
36988 * Returns true if the selections are locked.
36989 * @return {Boolean}
36991 isLocked : function(){
36992 return this.locked;
36996 * Ext JS Library 1.1.1
36997 * Copyright(c) 2006-2007, Ext JS, LLC.
36999 * Originally Released Under LGPL - original licence link has changed is not relivant.
37002 * <script type="text/javascript">
37005 * @extends Roo.grid.AbstractSelectionModel
37006 * @class Roo.grid.RowSelectionModel
37007 * The default SelectionModel used by {@link Roo.grid.Grid}.
37008 * It supports multiple selections and keyboard selection/navigation.
37010 * @param {Object} config
37012 Roo.grid.RowSelectionModel = function(config){
37013 Roo.apply(this, config);
37014 this.selections = new Roo.util.MixedCollection(false, function(o){
37019 this.lastActive = false;
37023 * @event selectionchange
37024 * Fires when the selection changes
37025 * @param {SelectionModel} this
37027 "selectionchange" : true,
37029 * @event afterselectionchange
37030 * Fires after the selection changes (eg. by key press or clicking)
37031 * @param {SelectionModel} this
37033 "afterselectionchange" : true,
37035 * @event beforerowselect
37036 * Fires when a row is selected being selected, return false to cancel.
37037 * @param {SelectionModel} this
37038 * @param {Number} rowIndex The selected index
37039 * @param {Boolean} keepExisting False if other selections will be cleared
37041 "beforerowselect" : true,
37044 * Fires when a row is selected.
37045 * @param {SelectionModel} this
37046 * @param {Number} rowIndex The selected index
37047 * @param {Roo.data.Record} r The record
37049 "rowselect" : true,
37051 * @event rowdeselect
37052 * Fires when a row is deselected.
37053 * @param {SelectionModel} this
37054 * @param {Number} rowIndex The selected index
37056 "rowdeselect" : true
37058 Roo.grid.RowSelectionModel.superclass.constructor.call(this);
37059 this.locked = false;
37062 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel, {
37064 * @cfg {Boolean} singleSelect
37065 * True to allow selection of only one row at a time (defaults to false)
37067 singleSelect : false,
37070 initEvents : function(){
37072 if(!this.grid.enableDragDrop && !this.grid.enableDrag){
37073 this.grid.on("mousedown", this.handleMouseDown, this);
37074 }else{ // allow click to work like normal
37075 this.grid.on("rowclick", this.handleDragableRowClick, this);
37078 this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
37079 "up" : function(e){
37081 this.selectPrevious(e.shiftKey);
37082 }else if(this.last !== false && this.lastActive !== false){
37083 var last = this.last;
37084 this.selectRange(this.last, this.lastActive-1);
37085 this.grid.getView().focusRow(this.lastActive);
37086 if(last !== false){
37090 this.selectFirstRow();
37092 this.fireEvent("afterselectionchange", this);
37094 "down" : function(e){
37096 this.selectNext(e.shiftKey);
37097 }else if(this.last !== false && this.lastActive !== false){
37098 var last = this.last;
37099 this.selectRange(this.last, this.lastActive+1);
37100 this.grid.getView().focusRow(this.lastActive);
37101 if(last !== false){
37105 this.selectFirstRow();
37107 this.fireEvent("afterselectionchange", this);
37112 var view = this.grid.view;
37113 view.on("refresh", this.onRefresh, this);
37114 view.on("rowupdated", this.onRowUpdated, this);
37115 view.on("rowremoved", this.onRemove, this);
37119 onRefresh : function(){
37120 var ds = this.grid.dataSource, i, v = this.grid.view;
37121 var s = this.selections;
37122 s.each(function(r){
37123 if((i = ds.indexOfId(r.id)) != -1){
37132 onRemove : function(v, index, r){
37133 this.selections.remove(r);
37137 onRowUpdated : function(v, index, r){
37138 if(this.isSelected(r)){
37139 v.onRowSelect(index);
37145 * @param {Array} records The records to select
37146 * @param {Boolean} keepExisting (optional) True to keep existing selections
37148 selectRecords : function(records, keepExisting){
37150 this.clearSelections();
37152 var ds = this.grid.dataSource;
37153 for(var i = 0, len = records.length; i < len; i++){
37154 this.selectRow(ds.indexOf(records[i]), true);
37159 * Gets the number of selected rows.
37162 getCount : function(){
37163 return this.selections.length;
37167 * Selects the first row in the grid.
37169 selectFirstRow : function(){
37174 * Select the last row.
37175 * @param {Boolean} keepExisting (optional) True to keep existing selections
37177 selectLastRow : function(keepExisting){
37178 this.selectRow(this.grid.dataSource.getCount() - 1, keepExisting);
37182 * Selects the row immediately following the last selected row.
37183 * @param {Boolean} keepExisting (optional) True to keep existing selections
37185 selectNext : function(keepExisting){
37186 if(this.last !== false && (this.last+1) < this.grid.dataSource.getCount()){
37187 this.selectRow(this.last+1, keepExisting);
37188 this.grid.getView().focusRow(this.last);
37193 * Selects the row that precedes the last selected row.
37194 * @param {Boolean} keepExisting (optional) True to keep existing selections
37196 selectPrevious : function(keepExisting){
37198 this.selectRow(this.last-1, keepExisting);
37199 this.grid.getView().focusRow(this.last);
37204 * Returns the selected records
37205 * @return {Array} Array of selected records
37207 getSelections : function(){
37208 return [].concat(this.selections.items);
37212 * Returns the first selected record.
37215 getSelected : function(){
37216 return this.selections.itemAt(0);
37221 * Clears all selections.
37223 clearSelections : function(fast){
37224 if(this.locked) return;
37226 var ds = this.grid.dataSource;
37227 var s = this.selections;
37228 s.each(function(r){
37229 this.deselectRow(ds.indexOfId(r.id));
37233 this.selections.clear();
37240 * Selects all rows.
37242 selectAll : function(){
37243 if(this.locked) return;
37244 this.selections.clear();
37245 for(var i = 0, len = this.grid.dataSource.getCount(); i < len; i++){
37246 this.selectRow(i, true);
37251 * Returns True if there is a selection.
37252 * @return {Boolean}
37254 hasSelection : function(){
37255 return this.selections.length > 0;
37259 * Returns True if the specified row is selected.
37260 * @param {Number/Record} record The record or index of the record to check
37261 * @return {Boolean}
37263 isSelected : function(index){
37264 var r = typeof index == "number" ? this.grid.dataSource.getAt(index) : index;
37265 return (r && this.selections.key(r.id) ? true : false);
37269 * Returns True if the specified record id is selected.
37270 * @param {String} id The id of record to check
37271 * @return {Boolean}
37273 isIdSelected : function(id){
37274 return (this.selections.key(id) ? true : false);
37278 handleMouseDown : function(e, t){
37279 var view = this.grid.getView(), rowIndex;
37280 if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
37283 if(e.shiftKey && this.last !== false){
37284 var last = this.last;
37285 this.selectRange(last, rowIndex, e.ctrlKey);
37286 this.last = last; // reset the last
37287 view.focusRow(rowIndex);
37289 var isSelected = this.isSelected(rowIndex);
37290 if(e.button !== 0 && isSelected){
37291 view.focusRow(rowIndex);
37292 }else if(e.ctrlKey && isSelected){
37293 this.deselectRow(rowIndex);
37294 }else if(!isSelected){
37295 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
37296 view.focusRow(rowIndex);
37299 this.fireEvent("afterselectionchange", this);
37302 handleDragableRowClick : function(grid, rowIndex, e)
37304 if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
37305 this.selectRow(rowIndex, false);
37306 grid.view.focusRow(rowIndex);
37307 this.fireEvent("afterselectionchange", this);
37312 * Selects multiple rows.
37313 * @param {Array} rows Array of the indexes of the row to select
37314 * @param {Boolean} keepExisting (optional) True to keep existing selections
37316 selectRows : function(rows, keepExisting){
37318 this.clearSelections();
37320 for(var i = 0, len = rows.length; i < len; i++){
37321 this.selectRow(rows[i], true);
37326 * Selects a range of rows. All rows in between startRow and endRow are also selected.
37327 * @param {Number} startRow The index of the first row in the range
37328 * @param {Number} endRow The index of the last row in the range
37329 * @param {Boolean} keepExisting (optional) True to retain existing selections
37331 selectRange : function(startRow, endRow, keepExisting){
37332 if(this.locked) return;
37334 this.clearSelections();
37336 if(startRow <= endRow){
37337 for(var i = startRow; i <= endRow; i++){
37338 this.selectRow(i, true);
37341 for(var i = startRow; i >= endRow; i--){
37342 this.selectRow(i, true);
37348 * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
37349 * @param {Number} startRow The index of the first row in the range
37350 * @param {Number} endRow The index of the last row in the range
37352 deselectRange : function(startRow, endRow, preventViewNotify){
37353 if(this.locked) return;
37354 for(var i = startRow; i <= endRow; i++){
37355 this.deselectRow(i, preventViewNotify);
37361 * @param {Number} row The index of the row to select
37362 * @param {Boolean} keepExisting (optional) True to keep existing selections
37364 selectRow : function(index, keepExisting, preventViewNotify){
37365 if(this.locked || (index < 0 || index >= this.grid.dataSource.getCount())) return;
37366 if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
37367 if(!keepExisting || this.singleSelect){
37368 this.clearSelections();
37370 var r = this.grid.dataSource.getAt(index);
37371 this.selections.add(r);
37372 this.last = this.lastActive = index;
37373 if(!preventViewNotify){
37374 this.grid.getView().onRowSelect(index);
37376 this.fireEvent("rowselect", this, index, r);
37377 this.fireEvent("selectionchange", this);
37383 * @param {Number} row The index of the row to deselect
37385 deselectRow : function(index, preventViewNotify){
37386 if(this.locked) return;
37387 if(this.last == index){
37390 if(this.lastActive == index){
37391 this.lastActive = false;
37393 var r = this.grid.dataSource.getAt(index);
37394 this.selections.remove(r);
37395 if(!preventViewNotify){
37396 this.grid.getView().onRowDeselect(index);
37398 this.fireEvent("rowdeselect", this, index);
37399 this.fireEvent("selectionchange", this);
37403 restoreLast : function(){
37405 this.last = this._last;
37410 acceptsNav : function(row, col, cm){
37411 return !cm.isHidden(col) && cm.isCellEditable(col, row);
37415 onEditorKey : function(field, e){
37416 var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
37421 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
37423 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
37425 }else if(k == e.ENTER && !e.ctrlKey){
37429 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
37431 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
37433 }else if(k == e.ESC){
37437 g.startEditing(newCell[0], newCell[1]);
37442 * Ext JS Library 1.1.1
37443 * Copyright(c) 2006-2007, Ext JS, LLC.
37445 * Originally Released Under LGPL - original licence link has changed is not relivant.
37448 * <script type="text/javascript">
37451 * @class Roo.grid.CellSelectionModel
37452 * @extends Roo.grid.AbstractSelectionModel
37453 * This class provides the basic implementation for cell selection in a grid.
37455 * @param {Object} config The object containing the configuration of this model.
37456 * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
37458 Roo.grid.CellSelectionModel = function(config){
37459 Roo.apply(this, config);
37461 this.selection = null;
37465 * @event beforerowselect
37466 * Fires before a cell is selected.
37467 * @param {SelectionModel} this
37468 * @param {Number} rowIndex The selected row index
37469 * @param {Number} colIndex The selected cell index
37471 "beforecellselect" : true,
37473 * @event cellselect
37474 * Fires when a cell is selected.
37475 * @param {SelectionModel} this
37476 * @param {Number} rowIndex The selected row index
37477 * @param {Number} colIndex The selected cell index
37479 "cellselect" : true,
37481 * @event selectionchange
37482 * Fires when the active selection changes.
37483 * @param {SelectionModel} this
37484 * @param {Object} selection null for no selection or an object (o) with two properties
37486 <li>o.record: the record object for the row the selection is in</li>
37487 <li>o.cell: An array of [rowIndex, columnIndex]</li>
37490 "selectionchange" : true,
37493 * Fires when the tab (or enter) was pressed on the last editable cell
37494 * You can use this to trigger add new row.
37495 * @param {SelectionModel} this
37499 * @event beforeeditnext
37500 * Fires before the next editable sell is made active
37501 * You can use this to skip to another cell or fire the tabend
37502 * if you set cell to false
37503 * @param {Object} eventdata object : { cell : [ row, col ] }
37505 "beforeeditnext" : true
37507 Roo.grid.CellSelectionModel.superclass.constructor.call(this);
37510 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel, {
37512 enter_is_tab: false,
37515 initEvents : function(){
37516 this.grid.on("mousedown", this.handleMouseDown, this);
37517 this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
37518 var view = this.grid.view;
37519 view.on("refresh", this.onViewChange, this);
37520 view.on("rowupdated", this.onRowUpdated, this);
37521 view.on("beforerowremoved", this.clearSelections, this);
37522 view.on("beforerowsinserted", this.clearSelections, this);
37523 if(this.grid.isEditor){
37524 this.grid.on("beforeedit", this.beforeEdit, this);
37529 beforeEdit : function(e){
37530 this.select(e.row, e.column, false, true, e.record);
37534 onRowUpdated : function(v, index, r){
37535 if(this.selection && this.selection.record == r){
37536 v.onCellSelect(index, this.selection.cell[1]);
37541 onViewChange : function(){
37542 this.clearSelections(true);
37546 * Returns the currently selected cell,.
37547 * @return {Array} The selected cell (row, column) or null if none selected.
37549 getSelectedCell : function(){
37550 return this.selection ? this.selection.cell : null;
37554 * Clears all selections.
37555 * @param {Boolean} true to prevent the gridview from being notified about the change.
37557 clearSelections : function(preventNotify){
37558 var s = this.selection;
37560 if(preventNotify !== true){
37561 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
37563 this.selection = null;
37564 this.fireEvent("selectionchange", this, null);
37569 * Returns true if there is a selection.
37570 * @return {Boolean}
37572 hasSelection : function(){
37573 return this.selection ? true : false;
37577 handleMouseDown : function(e, t){
37578 var v = this.grid.getView();
37579 if(this.isLocked()){
37582 var row = v.findRowIndex(t);
37583 var cell = v.findCellIndex(t);
37584 if(row !== false && cell !== false){
37585 this.select(row, cell);
37591 * @param {Number} rowIndex
37592 * @param {Number} collIndex
37594 select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
37595 if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
37596 this.clearSelections();
37597 r = r || this.grid.dataSource.getAt(rowIndex);
37600 cell : [rowIndex, colIndex]
37602 if(!preventViewNotify){
37603 var v = this.grid.getView();
37604 v.onCellSelect(rowIndex, colIndex);
37605 if(preventFocus !== true){
37606 v.focusCell(rowIndex, colIndex);
37609 this.fireEvent("cellselect", this, rowIndex, colIndex);
37610 this.fireEvent("selectionchange", this, this.selection);
37615 isSelectable : function(rowIndex, colIndex, cm){
37616 return !cm.isHidden(colIndex);
37620 handleKeyDown : function(e){
37621 //Roo.log('Cell Sel Model handleKeyDown');
37622 if(!e.isNavKeyPress()){
37625 var g = this.grid, s = this.selection;
37628 var cell = g.walkCells(0, 0, 1, this.isSelectable, this);
37630 this.select(cell[0], cell[1]);
37635 var walk = function(row, col, step){
37636 return g.walkCells(row, col, step, sm.isSelectable, sm);
37638 var k = e.getKey(), r = s.cell[0], c = s.cell[1];
37645 // handled by onEditorKey
37646 if (g.isEditor && g.editing) {
37650 newCell = walk(r, c-1, -1);
37652 newCell = walk(r, c+1, 1);
37657 newCell = walk(r+1, c, 1);
37661 newCell = walk(r-1, c, -1);
37665 newCell = walk(r, c+1, 1);
37669 newCell = walk(r, c-1, -1);
37674 if(g.isEditor && !g.editing){
37675 g.startEditing(r, c);
37684 this.select(newCell[0], newCell[1]);
37690 acceptsNav : function(row, col, cm){
37691 return !cm.isHidden(col) && cm.isCellEditable(col, row);
37695 * @param {Number} field (not used) - as it's normally used as a listener
37696 * @param {Number} e - event - fake it by using
37698 * var e = Roo.EventObjectImpl.prototype;
37699 * e.keyCode = e.TAB
37703 onEditorKey : function(field, e){
37705 var k = e.getKey(),
37708 ed = g.activeEditor,
37710 ///Roo.log('onEditorKey' + k);
37713 if (this.enter_is_tab && k == e.ENTER) {
37719 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
37721 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
37727 } else if(k == e.ENTER && !e.ctrlKey){
37730 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
37732 } else if(k == e.ESC){
37737 var ecall = { cell : newCell, forward : forward };
37738 this.fireEvent('beforeeditnext', ecall );
37739 newCell = ecall.cell;
37740 forward = ecall.forward;
37744 //Roo.log('next cell after edit');
37745 g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
37746 } else if (forward) {
37747 // tabbed past last
37748 this.fireEvent.defer(100, this, ['tabend',this]);
37753 * Ext JS Library 1.1.1
37754 * Copyright(c) 2006-2007, Ext JS, LLC.
37756 * Originally Released Under LGPL - original licence link has changed is not relivant.
37759 * <script type="text/javascript">
37763 * @class Roo.grid.EditorGrid
37764 * @extends Roo.grid.Grid
37765 * Class for creating and editable grid.
37766 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
37767 * The container MUST have some type of size defined for the grid to fill. The container will be
37768 * automatically set to position relative if it isn't already.
37769 * @param {Object} dataSource The data model to bind to
37770 * @param {Object} colModel The column model with info about this grid's columns
37772 Roo.grid.EditorGrid = function(container, config){
37773 Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
37774 this.getGridEl().addClass("xedit-grid");
37776 if(!this.selModel){
37777 this.selModel = new Roo.grid.CellSelectionModel();
37780 this.activeEditor = null;
37784 * @event beforeedit
37785 * Fires before cell editing is triggered. The edit event object has the following properties <br />
37786 * <ul style="padding:5px;padding-left:16px;">
37787 * <li>grid - This grid</li>
37788 * <li>record - The record being edited</li>
37789 * <li>field - The field name being edited</li>
37790 * <li>value - The value for the field being edited.</li>
37791 * <li>row - The grid row index</li>
37792 * <li>column - The grid column index</li>
37793 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
37795 * @param {Object} e An edit event (see above for description)
37797 "beforeedit" : true,
37800 * Fires after a cell is edited. <br />
37801 * <ul style="padding:5px;padding-left:16px;">
37802 * <li>grid - This grid</li>
37803 * <li>record - The record being edited</li>
37804 * <li>field - The field name being edited</li>
37805 * <li>value - The value being set</li>
37806 * <li>originalValue - The original value for the field, before the edit.</li>
37807 * <li>row - The grid row index</li>
37808 * <li>column - The grid column index</li>
37810 * @param {Object} e An edit event (see above for description)
37812 "afteredit" : true,
37814 * @event validateedit
37815 * Fires after a cell is edited, but before the value is set in the record.
37816 * You can use this to modify the value being set in the field, Return false
37817 * to cancel the change. The edit event object has the following properties <br />
37818 * <ul style="padding:5px;padding-left:16px;">
37819 * <li>editor - This editor</li>
37820 * <li>grid - This grid</li>
37821 * <li>record - The record being edited</li>
37822 * <li>field - The field name being edited</li>
37823 * <li>value - The value being set</li>
37824 * <li>originalValue - The original value for the field, before the edit.</li>
37825 * <li>row - The grid row index</li>
37826 * <li>column - The grid column index</li>
37827 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
37829 * @param {Object} e An edit event (see above for description)
37831 "validateedit" : true
37833 this.on("bodyscroll", this.stopEditing, this);
37834 this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick, this);
37837 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
37839 * @cfg {Number} clicksToEdit
37840 * The number of clicks on a cell required to display the cell's editor (defaults to 2)
37847 trackMouseOver: false, // causes very odd FF errors
37849 onCellDblClick : function(g, row, col){
37850 this.startEditing(row, col);
37853 onEditComplete : function(ed, value, startValue){
37854 this.editing = false;
37855 this.activeEditor = null;
37856 ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
37858 var field = this.colModel.getDataIndex(ed.col);
37863 originalValue: startValue,
37870 var cell = Roo.get(this.view.getCell(ed.row,ed.col))
37873 if(String(value) !== String(startValue)){
37875 if(this.fireEvent("validateedit", e) !== false && !e.cancel){
37876 r.set(field, e.value);
37877 // if we are dealing with a combo box..
37878 // then we also set the 'name' colum to be the displayField
37879 if (ed.field.displayField && ed.field.name) {
37880 r.set(ed.field.name, ed.field.el.dom.value);
37883 delete e.cancel; //?? why!!!
37884 this.fireEvent("afteredit", e);
37887 this.fireEvent("afteredit", e); // always fire it!
37889 this.view.focusCell(ed.row, ed.col);
37893 * Starts editing the specified for the specified row/column
37894 * @param {Number} rowIndex
37895 * @param {Number} colIndex
37897 startEditing : function(row, col){
37898 this.stopEditing();
37899 if(this.colModel.isCellEditable(col, row)){
37900 this.view.ensureVisible(row, col, true);
37902 var r = this.dataSource.getAt(row);
37903 var field = this.colModel.getDataIndex(col);
37904 var cell = Roo.get(this.view.getCell(row,col));
37909 value: r.data[field],
37914 if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
37915 this.editing = true;
37916 var ed = this.colModel.getCellEditor(col, row);
37922 ed.render(ed.parentEl || document.body);
37928 (function(){ // complex but required for focus issues in safari, ie and opera
37932 ed.on("complete", this.onEditComplete, this, {single: true});
37933 ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
37934 this.activeEditor = ed;
37935 var v = r.data[field];
37936 ed.startEdit(this.view.getCell(row, col), v);
37937 // combo's with 'displayField and name set
37938 if (ed.field.displayField && ed.field.name) {
37939 ed.field.el.dom.value = r.data[ed.field.name];
37943 }).defer(50, this);
37949 * Stops any active editing
37951 stopEditing : function(){
37952 if(this.activeEditor){
37953 this.activeEditor.completeEdit();
37955 this.activeEditor = null;
37959 * Ext JS Library 1.1.1
37960 * Copyright(c) 2006-2007, Ext JS, LLC.
37962 * Originally Released Under LGPL - original licence link has changed is not relivant.
37965 * <script type="text/javascript">
37968 // private - not really -- you end up using it !
37969 // This is a support class used internally by the Grid components
37972 * @class Roo.grid.GridEditor
37973 * @extends Roo.Editor
37974 * Class for creating and editable grid elements.
37975 * @param {Object} config any settings (must include field)
37977 Roo.grid.GridEditor = function(field, config){
37978 if (!config && field.field) {
37980 field = Roo.factory(config.field, Roo.form);
37982 Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
37983 field.monitorTab = false;
37986 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
37989 * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
37992 alignment: "tl-tl",
37995 cls: "x-small-editor x-grid-editor",
38000 * Ext JS Library 1.1.1
38001 * Copyright(c) 2006-2007, Ext JS, LLC.
38003 * Originally Released Under LGPL - original licence link has changed is not relivant.
38006 * <script type="text/javascript">
38011 Roo.grid.PropertyRecord = Roo.data.Record.create([
38012 {name:'name',type:'string'}, 'value'
38016 Roo.grid.PropertyStore = function(grid, source){
38018 this.store = new Roo.data.Store({
38019 recordType : Roo.grid.PropertyRecord
38021 this.store.on('update', this.onUpdate, this);
38023 this.setSource(source);
38025 Roo.grid.PropertyStore.superclass.constructor.call(this);
38030 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
38031 setSource : function(o){
38033 this.store.removeAll();
38036 if(this.isEditableValue(o[k])){
38037 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
38040 this.store.loadRecords({records: data}, {}, true);
38043 onUpdate : function(ds, record, type){
38044 if(type == Roo.data.Record.EDIT){
38045 var v = record.data['value'];
38046 var oldValue = record.modified['value'];
38047 if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
38048 this.source[record.id] = v;
38050 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
38057 getProperty : function(row){
38058 return this.store.getAt(row);
38061 isEditableValue: function(val){
38062 if(val && val instanceof Date){
38064 }else if(typeof val == 'object' || typeof val == 'function'){
38070 setValue : function(prop, value){
38071 this.source[prop] = value;
38072 this.store.getById(prop).set('value', value);
38075 getSource : function(){
38076 return this.source;
38080 Roo.grid.PropertyColumnModel = function(grid, store){
38083 g.PropertyColumnModel.superclass.constructor.call(this, [
38084 {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
38085 {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
38087 this.store = store;
38088 this.bselect = Roo.DomHelper.append(document.body, {
38089 tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
38090 {tag: 'option', value: 'true', html: 'true'},
38091 {tag: 'option', value: 'false', html: 'false'}
38094 Roo.id(this.bselect);
38097 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
38098 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
38099 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
38100 'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
38101 'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
38103 this.renderCellDelegate = this.renderCell.createDelegate(this);
38104 this.renderPropDelegate = this.renderProp.createDelegate(this);
38107 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
38111 valueText : 'Value',
38113 dateFormat : 'm/j/Y',
38116 renderDate : function(dateVal){
38117 return dateVal.dateFormat(this.dateFormat);
38120 renderBool : function(bVal){
38121 return bVal ? 'true' : 'false';
38124 isCellEditable : function(colIndex, rowIndex){
38125 return colIndex == 1;
38128 getRenderer : function(col){
38130 this.renderCellDelegate : this.renderPropDelegate;
38133 renderProp : function(v){
38134 return this.getPropertyName(v);
38137 renderCell : function(val){
38139 if(val instanceof Date){
38140 rv = this.renderDate(val);
38141 }else if(typeof val == 'boolean'){
38142 rv = this.renderBool(val);
38144 return Roo.util.Format.htmlEncode(rv);
38147 getPropertyName : function(name){
38148 var pn = this.grid.propertyNames;
38149 return pn && pn[name] ? pn[name] : name;
38152 getCellEditor : function(colIndex, rowIndex){
38153 var p = this.store.getProperty(rowIndex);
38154 var n = p.data['name'], val = p.data['value'];
38156 if(typeof(this.grid.customEditors[n]) == 'string'){
38157 return this.editors[this.grid.customEditors[n]];
38159 if(typeof(this.grid.customEditors[n]) != 'undefined'){
38160 return this.grid.customEditors[n];
38162 if(val instanceof Date){
38163 return this.editors['date'];
38164 }else if(typeof val == 'number'){
38165 return this.editors['number'];
38166 }else if(typeof val == 'boolean'){
38167 return this.editors['boolean'];
38169 return this.editors['string'];
38175 * @class Roo.grid.PropertyGrid
38176 * @extends Roo.grid.EditorGrid
38177 * This class represents the interface of a component based property grid control.
38178 * <br><br>Usage:<pre><code>
38179 var grid = new Roo.grid.PropertyGrid("my-container-id", {
38187 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
38188 * The container MUST have some type of size defined for the grid to fill. The container will be
38189 * automatically set to position relative if it isn't already.
38190 * @param {Object} config A config object that sets properties on this grid.
38192 Roo.grid.PropertyGrid = function(container, config){
38193 config = config || {};
38194 var store = new Roo.grid.PropertyStore(this);
38195 this.store = store;
38196 var cm = new Roo.grid.PropertyColumnModel(this, store);
38197 store.store.sort('name', 'ASC');
38198 Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
38201 enableColLock:false,
38202 enableColumnMove:false,
38204 trackMouseOver: false,
38207 this.getGridEl().addClass('x-props-grid');
38208 this.lastEditRow = null;
38209 this.on('columnresize', this.onColumnResize, this);
38212 * @event beforepropertychange
38213 * Fires before a property changes (return false to stop?)
38214 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
38215 * @param {String} id Record Id
38216 * @param {String} newval New Value
38217 * @param {String} oldval Old Value
38219 "beforepropertychange": true,
38221 * @event propertychange
38222 * Fires after a property changes
38223 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
38224 * @param {String} id Record Id
38225 * @param {String} newval New Value
38226 * @param {String} oldval Old Value
38228 "propertychange": true
38230 this.customEditors = this.customEditors || {};
38232 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
38235 * @cfg {Object} customEditors map of colnames=> custom editors.
38236 * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
38237 * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
38238 * false disables editing of the field.
38242 * @cfg {Object} propertyNames map of property Names to their displayed value
38245 render : function(){
38246 Roo.grid.PropertyGrid.superclass.render.call(this);
38247 this.autoSize.defer(100, this);
38250 autoSize : function(){
38251 Roo.grid.PropertyGrid.superclass.autoSize.call(this);
38253 this.view.fitColumns();
38257 onColumnResize : function(){
38258 this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
38262 * Sets the data for the Grid
38263 * accepts a Key => Value object of all the elements avaiable.
38264 * @param {Object} data to appear in grid.
38266 setSource : function(source){
38267 this.store.setSource(source);
38271 * Gets all the data from the grid.
38272 * @return {Object} data data stored in grid
38274 getSource : function(){
38275 return this.store.getSource();
38279 * Ext JS Library 1.1.1
38280 * Copyright(c) 2006-2007, Ext JS, LLC.
38282 * Originally Released Under LGPL - original licence link has changed is not relivant.
38285 * <script type="text/javascript">
38289 * @class Roo.LoadMask
38290 * A simple utility class for generically masking elements while loading data. If the element being masked has
38291 * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
38292 * process and the mask element will be cached for reuse. For all other elements, this mask will replace the
38293 * element's UpdateManager load indicator and will be destroyed after the initial load.
38295 * Create a new LoadMask
38296 * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
38297 * @param {Object} config The config object
38299 Roo.LoadMask = function(el, config){
38300 this.el = Roo.get(el);
38301 Roo.apply(this, config);
38303 this.store.on('beforeload', this.onBeforeLoad, this);
38304 this.store.on('load', this.onLoad, this);
38305 this.store.on('loadexception', this.onLoadException, this);
38306 this.removeMask = false;
38308 var um = this.el.getUpdateManager();
38309 um.showLoadIndicator = false; // disable the default indicator
38310 um.on('beforeupdate', this.onBeforeLoad, this);
38311 um.on('update', this.onLoad, this);
38312 um.on('failure', this.onLoad, this);
38313 this.removeMask = true;
38317 Roo.LoadMask.prototype = {
38319 * @cfg {Boolean} removeMask
38320 * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
38321 * False to persist the mask element reference for multiple uses (e.g., for paged data widgets). Defaults to false.
38324 * @cfg {String} msg
38325 * The text to display in a centered loading message box (defaults to 'Loading...')
38327 msg : 'Loading...',
38329 * @cfg {String} msgCls
38330 * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
38332 msgCls : 'x-mask-loading',
38335 * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
38341 * Disables the mask to prevent it from being displayed
38343 disable : function(){
38344 this.disabled = true;
38348 * Enables the mask so that it can be displayed
38350 enable : function(){
38351 this.disabled = false;
38354 onLoadException : function()
38356 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
38357 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
38359 this.el.unmask(this.removeMask);
38362 onLoad : function()
38364 this.el.unmask(this.removeMask);
38368 onBeforeLoad : function(){
38369 if(!this.disabled){
38370 this.el.mask(this.msg, this.msgCls);
38375 destroy : function(){
38377 this.store.un('beforeload', this.onBeforeLoad, this);
38378 this.store.un('load', this.onLoad, this);
38379 this.store.un('loadexception', this.onLoadException, this);
38381 var um = this.el.getUpdateManager();
38382 um.un('beforeupdate', this.onBeforeLoad, this);
38383 um.un('update', this.onLoad, this);
38384 um.un('failure', this.onLoad, this);
38389 * Ext JS Library 1.1.1
38390 * Copyright(c) 2006-2007, Ext JS, LLC.
38392 * Originally Released Under LGPL - original licence link has changed is not relivant.
38395 * <script type="text/javascript">
38400 * @class Roo.XTemplate
38401 * @extends Roo.Template
38402 * Provides a template that can have nested templates for loops or conditionals. The syntax is:
38404 var t = new Roo.XTemplate(
38405 '<select name="{name}">',
38406 '<tpl for="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
38410 // then append, applying the master template values
38413 * Supported features:
38418 {a_variable} - output encoded.
38419 {a_variable.format:("Y-m-d")} - call a method on the variable
38420 {a_variable:raw} - unencoded output
38421 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
38422 {a_variable:this.method_on_template(...)} - call a method on the template object.
38427 <tpl for="a_variable or condition.."></tpl>
38428 <tpl if="a_variable or condition"></tpl>
38429 <tpl exec="some javascript"></tpl>
38430 <tpl name="named_template"></tpl> (experimental)
38432 <tpl for="."></tpl> - just iterate the property..
38433 <tpl for=".."></tpl> - iterates with the parent (probably the template)
38437 Roo.XTemplate = function()
38439 Roo.XTemplate.superclass.constructor.apply(this, arguments);
38446 Roo.extend(Roo.XTemplate, Roo.Template, {
38449 * The various sub templates
38454 * basic tag replacing syntax
38457 * // you can fake an object call by doing this
38461 re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
38464 * compile the template
38466 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
38469 compile: function()
38473 s = ['<tpl>', s, '</tpl>'].join('');
38475 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
38476 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
38477 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
38478 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
38479 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
38484 while(true == !!(m = s.match(re))){
38485 var forMatch = m[0].match(nameRe),
38486 ifMatch = m[0].match(ifRe),
38487 execMatch = m[0].match(execRe),
38488 namedMatch = m[0].match(namedRe),
38493 name = forMatch && forMatch[1] ? forMatch[1] : '';
38496 // if - puts fn into test..
38497 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
38499 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
38504 // exec - calls a function... returns empty if true is returned.
38505 exp = execMatch && execMatch[1] ? execMatch[1] : null;
38507 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
38515 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
38516 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
38517 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
38520 var uid = namedMatch ? namedMatch[1] : id;
38524 id: namedMatch ? namedMatch[1] : id,
38531 s = s.replace(m[0], '');
38533 s = s.replace(m[0], '{xtpl'+ id + '}');
38538 for(var i = tpls.length-1; i >= 0; --i){
38539 this.compileTpl(tpls[i]);
38540 this.tpls[tpls[i].id] = tpls[i];
38542 this.master = tpls[tpls.length-1];
38546 * same as applyTemplate, except it's done to one of the subTemplates
38547 * when using named templates, you can do:
38549 * var str = pl.applySubTemplate('your-name', values);
38552 * @param {Number} id of the template
38553 * @param {Object} values to apply to template
38554 * @param {Object} parent (normaly the instance of this object)
38556 applySubTemplate : function(id, values, parent)
38560 var t = this.tpls[id];
38564 if(t.test && !t.test.call(this, values, parent)){
38568 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
38569 Roo.log(e.toString());
38575 if(t.exec && t.exec.call(this, values, parent)){
38579 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
38580 Roo.log(e.toString());
38585 var vs = t.target ? t.target.call(this, values, parent) : values;
38586 parent = t.target ? values : parent;
38587 if(t.target && vs instanceof Array){
38589 for(var i = 0, len = vs.length; i < len; i++){
38590 buf[buf.length] = t.compiled.call(this, vs[i], parent);
38592 return buf.join('');
38594 return t.compiled.call(this, vs, parent);
38596 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
38597 Roo.log(e.toString());
38598 Roo.log(t.compiled);
38603 compileTpl : function(tpl)
38605 var fm = Roo.util.Format;
38606 var useF = this.disableFormats !== true;
38607 var sep = Roo.isGecko ? "+" : ",";
38608 var undef = function(str) {
38609 Roo.log("Property not found :" + str);
38613 var fn = function(m, name, format, args)
38615 //Roo.log(arguments);
38616 args = args ? args.replace(/\\'/g,"'") : args;
38617 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
38618 if (typeof(format) == 'undefined') {
38619 format= 'htmlEncode';
38621 if (format == 'raw' ) {
38625 if(name.substr(0, 4) == 'xtpl'){
38626 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
38629 // build an array of options to determine if value is undefined..
38631 // basically get 'xxxx.yyyy' then do
38632 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
38633 // (function () { Roo.log("Property not found"); return ''; })() :
38638 Roo.each(name.split('.'), function(st) {
38639 lookfor += (lookfor.length ? '.': '') + st;
38640 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
38643 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
38646 if(format && useF){
38648 args = args ? ',' + args : "";
38650 if(format.substr(0, 5) != "this."){
38651 format = "fm." + format + '(';
38653 format = 'this.call("'+ format.substr(5) + '", ';
38657 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
38661 // called with xxyx.yuu:(test,test)
38663 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
38665 // raw.. - :raw modifier..
38666 return "'"+ sep + udef_st + name + ")"+sep+"'";
38670 // branched to use + in gecko and [].join() in others
38672 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
38673 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
38676 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
38677 body.push(tpl.body.replace(/(\r\n|\n)/g,
38678 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
38679 body.push("'].join('');};};");
38680 body = body.join('');
38683 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
38685 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
38691 applyTemplate : function(values){
38692 return this.master.compiled.call(this, values, {});
38693 //var s = this.subs;
38696 apply : function(){
38697 return this.applyTemplate.apply(this, arguments);
38702 Roo.XTemplate.from = function(el){
38703 el = Roo.getDom(el);
38704 return new Roo.XTemplate(el.value || el.innerHTML);
38706 * Original code for Roojs - LGPL
38707 * <script type="text/javascript">
38711 * @class Roo.XComponent
38712 * A delayed Element creator...
38713 * Or a way to group chunks of interface together.
38715 * Mypart.xyx = new Roo.XComponent({
38717 parent : 'Mypart.xyz', // empty == document.element.!!
38721 disabled : function() {}
38723 tree : function() { // return an tree of xtype declared components
38727 xtype : 'NestedLayoutPanel',
38734 * It can be used to build a big heiracy, with parent etc.
38735 * or you can just use this to render a single compoent to a dom element
38736 * MYPART.render(Roo.Element | String(id) | dom_element )
38738 * @extends Roo.util.Observable
38740 * @param cfg {Object} configuration of component
38743 Roo.XComponent = function(cfg) {
38744 Roo.apply(this, cfg);
38748 * Fires when this the componnt is built
38749 * @param {Roo.XComponent} c the component
38754 this.region = this.region || 'center'; // default..
38755 Roo.XComponent.register(this);
38756 this.modules = false;
38757 this.el = false; // where the layout goes..
38761 Roo.extend(Roo.XComponent, Roo.util.Observable, {
38764 * The created element (with Roo.factory())
38765 * @type {Roo.Layout}
38771 * for BC - use el in new code
38772 * @type {Roo.Layout}
38778 * for BC - use el in new code
38779 * @type {Roo.Layout}
38784 * @cfg {Function|boolean} disabled
38785 * If this module is disabled by some rule, return true from the funtion
38790 * @cfg {String} parent
38791 * Name of parent element which it get xtype added to..
38796 * @cfg {String} order
38797 * Used to set the order in which elements are created (usefull for multiple tabs)
38802 * @cfg {String} name
38803 * String to display while loading.
38807 * @cfg {String} region
38808 * Region to render component to (defaults to center)
38813 * @cfg {Array} items
38814 * A single item array - the first element is the root of the tree..
38815 * It's done this way to stay compatible with the Xtype system...
38821 * The method that retuns the tree of parts that make up this compoennt
38828 * render element to dom or tree
38829 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
38832 render : function(el)
38836 var hp = this.parent ? 1 : 0;
38838 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
38839 // if parent is a '#.....' string, then let's use that..
38840 var ename = this.parent.substr(1)
38841 this.parent = false;
38842 el = Roo.get(ename);
38844 Roo.log("Warning - element can not be found :#" + ename );
38850 if (!this.parent) {
38852 el = el ? Roo.get(el) : false;
38854 // it's a top level one..
38856 el : new Roo.BorderLayout(el || document.body, {
38862 tabPosition: 'top',
38863 //resizeTabs: true,
38864 alwaysShowTabs: el && hp? false : true,
38865 hideTabs: el || !hp ? true : false,
38872 if (!this.parent.el) {
38873 // probably an old style ctor, which has been disabled.
38877 // The 'tree' method is '_tree now'
38879 var tree = this._tree ? this._tree() : this.tree();
38880 tree.region = tree.region || this.region;
38881 this.el = this.parent.el.addxtype(tree);
38882 this.fireEvent('built', this);
38884 this.panel = this.el;
38885 this.layout = this.panel.layout;
38886 this.parentLayout = this.parent.layout || false;
38892 Roo.apply(Roo.XComponent, {
38894 * @property hideProgress
38895 * true to disable the building progress bar.. usefull on single page renders.
38898 hideProgress : false,
38900 * @property buildCompleted
38901 * True when the builder has completed building the interface.
38904 buildCompleted : false,
38907 * @property topModule
38908 * the upper most module - uses document.element as it's constructor.
38915 * @property modules
38916 * array of modules to be created by registration system.
38917 * @type {Array} of Roo.XComponent
38922 * @property elmodules
38923 * array of modules to be created by which use #ID
38924 * @type {Array} of Roo.XComponent
38931 * Register components to be built later.
38933 * This solves the following issues
38934 * - Building is not done on page load, but after an authentication process has occured.
38935 * - Interface elements are registered on page load
38936 * - Parent Interface elements may not be loaded before child, so this handles that..
38943 module : 'Pman.Tab.projectMgr',
38945 parent : 'Pman.layout',
38946 disabled : false, // or use a function..
38949 * * @param {Object} details about module
38951 register : function(obj) {
38953 Roo.XComponent.event.fireEvent('register', obj);
38954 switch(typeof(obj.disabled) ) {
38960 if ( obj.disabled() ) {
38966 if (obj.disabled) {
38972 this.modules.push(obj);
38976 * convert a string to an object..
38977 * eg. 'AAA.BBB' -> finds AAA.BBB
38981 toObject : function(str)
38983 if (!str || typeof(str) == 'object') {
38986 if (str.substring(0,1) == '#') {
38990 var ar = str.split('.');
38995 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
38997 throw "Module not found : " + str;
39001 throw "Module not found : " + str;
39003 Roo.each(ar, function(e) {
39004 if (typeof(o[e]) == 'undefined') {
39005 throw "Module not found : " + str;
39016 * move modules into their correct place in the tree..
39019 preBuild : function ()
39022 Roo.each(this.modules , function (obj)
39024 Roo.XComponent.event.fireEvent('beforebuild', obj);
39026 var opar = obj.parent;
39028 obj.parent = this.toObject(opar);
39030 Roo.log("parent:toObject failed: " + e.toString());
39035 Roo.debug && Roo.log("GOT top level module");
39036 Roo.debug && Roo.log(obj);
39037 obj.modules = new Roo.util.MixedCollection(false,
39038 function(o) { return o.order + '' }
39040 this.topModule = obj;
39043 // parent is a string (usually a dom element name..)
39044 if (typeof(obj.parent) == 'string') {
39045 this.elmodules.push(obj);
39048 if (obj.parent.constructor != Roo.XComponent) {
39049 Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
39051 if (!obj.parent.modules) {
39052 obj.parent.modules = new Roo.util.MixedCollection(false,
39053 function(o) { return o.order + '' }
39056 if (obj.parent.disabled) {
39057 obj.disabled = true;
39059 obj.parent.modules.add(obj);
39064 * make a list of modules to build.
39065 * @return {Array} list of modules.
39068 buildOrder : function()
39071 var cmp = function(a,b) {
39072 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
39074 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
39075 throw "No top level modules to build";
39078 // make a flat list in order of modules to build.
39079 var mods = this.topModule ? [ this.topModule ] : [];
39081 // elmodules (is a list of DOM based modules )
39082 Roo.each(this.elmodules, function(e) {
39087 // add modules to their parents..
39088 var addMod = function(m) {
39089 Roo.debug && Roo.log("build Order: add: " + m.name);
39092 if (m.modules && !m.disabled) {
39093 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
39094 m.modules.keySort('ASC', cmp );
39095 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
39097 m.modules.each(addMod);
39099 Roo.debug && Roo.log("build Order: no child modules");
39101 // not sure if this is used any more..
39103 m.finalize.name = m.name + " (clean up) ";
39104 mods.push(m.finalize);
39108 if (this.topModule) {
39109 this.topModule.modules.keySort('ASC', cmp );
39110 this.topModule.modules.each(addMod);
39116 * Build the registered modules.
39117 * @param {Object} parent element.
39118 * @param {Function} optional method to call after module has been added.
39126 var mods = this.buildOrder();
39128 //this.allmods = mods;
39129 //Roo.debug && Roo.log(mods);
39131 if (!mods.length) { // should not happen
39132 throw "NO modules!!!";
39136 var msg = "Building Interface...";
39137 // flash it up as modal - so we store the mask!?
39138 if (!this.hideProgress) {
39139 Roo.MessageBox.show({ title: 'loading' });
39140 Roo.MessageBox.show({
39141 title: "Please wait...",
39150 var total = mods.length;
39153 var progressRun = function() {
39154 if (!mods.length) {
39155 Roo.debug && Roo.log('hide?');
39156 if (!this.hideProgress) {
39157 Roo.MessageBox.hide();
39159 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
39165 var m = mods.shift();
39168 Roo.debug && Roo.log(m);
39169 // not sure if this is supported any more.. - modules that are are just function
39170 if (typeof(m) == 'function') {
39172 return progressRun.defer(10, _this);
39176 msg = "Building Interface " + (total - mods.length) +
39178 (m.name ? (' - ' + m.name) : '');
39179 Roo.debug && Roo.log(msg);
39180 if (!this.hideProgress) {
39181 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
39185 // is the module disabled?
39186 var disabled = (typeof(m.disabled) == 'function') ?
39187 m.disabled.call(m.module.disabled) : m.disabled;
39191 return progressRun(); // we do not update the display!
39199 // it's 10 on top level, and 1 on others??? why...
39200 return progressRun.defer(10, _this);
39203 progressRun.defer(1, _this);
39217 * wrapper for event.on - aliased later..
39218 * Typically use to register a event handler for register:
39220 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
39229 Roo.XComponent.event = new Roo.util.Observable({
39233 * Fires when an Component is registered,
39234 * set the disable property on the Component to stop registration.
39235 * @param {Roo.XComponent} c the component being registerd.
39240 * @event beforebuild
39241 * Fires before each Component is built
39242 * can be used to apply permissions.
39243 * @param {Roo.XComponent} c the component being registerd.
39246 'beforebuild' : true,
39248 * @event buildcomplete
39249 * Fires on the top level element when all elements have been built
39250 * @param {Roo.XComponent} the top level component.
39252 'buildcomplete' : true
39257 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);
39258 //<script type="text/javascript">
39263 * @extends Roo.LayoutDialog
39264 * A generic Login Dialog..... - only one needed in theory!?!?
39266 * Fires XComponent builder on success...
39269 * username,password, lang = for login actions.
39270 * check = 1 for periodic checking that sesion is valid.
39271 * passwordRequest = email request password
39272 * logout = 1 = to logout
39274 * Affects: (this id="????" elements)
39275 * loading (removed) (used to indicate application is loading)
39276 * loading-mask (hides) (used to hide application when it's building loading)
39282 * Myapp.login = Roo.Login({
39298 Roo.Login = function(cfg)
39304 Roo.apply(this,cfg);
39306 Roo.onReady(function() {
39312 Roo.Login.superclass.constructor.call(this, this);
39313 //this.addxtype(this.items[0]);
39319 Roo.extend(Roo.Login, Roo.LayoutDialog, {
39322 * @cfg {String} method
39323 * Method used to query for login details.
39328 * @cfg {String} url
39329 * URL to query login data. - eg. baseURL + '/Login.php'
39335 * The user data - if user.id < 0 then login will be bypassed. (used for inital setup situation.
39340 * @property checkFails
39341 * Number of times we have attempted to get authentication check, and failed.
39346 * @property intervalID
39347 * The window interval that does the constant login checking.
39353 onLoad : function() // called on page load...
39357 if (Roo.get('loading')) { // clear any loading indicator..
39358 Roo.get('loading').remove();
39361 //this.switchLang('en'); // set the language to english..
39364 success: function(response, opts) { // check successfull...
39366 var res = this.processResponse(response);
39367 this.checkFails =0;
39368 if (!res.success) { // error!
39369 this.checkFails = 5;
39370 //console.log('call failure');
39371 return this.failure(response,opts);
39374 if (!res.data.id) { // id=0 == login failure.
39375 return this.show();
39379 //console.log(success);
39380 this.fillAuth(res.data);
39381 this.checkFails =0;
39382 Roo.XComponent.build();
39384 failure : this.show
39390 check: function(cfg) // called every so often to refresh cookie etc..
39392 if (cfg.again) { // could be undefined..
39395 this.checkFails = 0;
39398 if (this.sending) {
39399 if ( this.checkFails > 4) {
39400 Roo.MessageBox.alert("Error",
39401 "Error getting authentication status. - try reloading, or wait a while", function() {
39402 _this.sending = false;
39407 _this.check.defer(10000, _this, [ cfg ]); // check in 10 secs.
39410 this.sending = true;
39417 method: this.method,
39418 success: cfg.success || this.success,
39419 failure : cfg.failure || this.failure,
39429 window.onbeforeunload = function() { }; // false does not work for IE..
39439 failure : function() {
39440 Roo.MessageBox.alert("Error", "Error logging out. - continuing anyway.", function() {
39441 document.location = document.location.toString() + '?ts=' + Math.random();
39445 success : function() {
39446 _this.user = false;
39447 this.checkFails =0;
39449 document.location = document.location.toString() + '?ts=' + Math.random();
39456 processResponse : function (response)
39460 res = Roo.decode(response.responseText);
39462 if (typeof(res) != 'object') {
39463 res = { success : false, errorMsg : res, errors : true };
39465 if (typeof(res.success) == 'undefined') {
39466 res.success = false;
39470 res = { success : false, errorMsg : response.responseText, errors : true };
39475 success : function(response, opts) // check successfull...
39477 this.sending = false;
39478 var res = this.processResponse(response);
39479 if (!res.success) {
39480 return this.failure(response, opts);
39482 if (!res.data || !res.data.id) {
39483 return this.failure(response,opts);
39485 //console.log(res);
39486 this.fillAuth(res.data);
39488 this.checkFails =0;
39493 failure : function (response, opts) // called if login 'check' fails.. (causes re-check)
39495 this.authUser = -1;
39496 this.sending = false;
39497 var res = this.processResponse(response);
39498 //console.log(res);
39499 if ( this.checkFails > 2) {
39501 Roo.MessageBox.alert("Error", res.errorMsg ? res.errorMsg :
39502 "Error getting authentication status. - try reloading");
39505 opts.callCfg.again = true;
39506 this.check.defer(1000, this, [ opts.callCfg ]);
39512 fillAuth: function(au) {
39513 this.startAuthCheck();
39514 this.authUserId = au.id;
39515 this.authUser = au;
39516 this.lastChecked = new Date();
39517 this.fireEvent('refreshed', au);
39518 //Pman.Tab.FaxQueue.newMaxId(au.faxMax);
39519 //Pman.Tab.FaxTab.setTitle(au.faxNumPending);
39520 au.lang = au.lang || 'en';
39521 //this.switchLang(Roo.state.Manager.get('Pman.Login.lang', 'en'));
39522 Roo.state.Manager.set( this.realm + 'lang' , au.lang);
39523 this.switchLang(au.lang );
39526 // open system... - -on setyp..
39527 if (this.authUserId < 0) {
39528 Roo.MessageBox.alert("Warning",
39529 "This is an open system - please set up a admin user with a password.");
39532 //Pman.onload(); // which should do nothing if it's a re-auth result...
39537 startAuthCheck : function() // starter for timeout checking..
39539 if (this.intervalID) { // timer already in place...
39543 this.intervalID = window.setInterval(function() {
39544 _this.check(false);
39545 }, 120000); // every 120 secs = 2mins..
39551 switchLang : function (lang)
39553 _T = typeof(_T) == 'undefined' ? false : _T;
39554 if (!_T || !lang.length) {
39558 if (!_T && lang != 'en') {
39559 Roo.MessageBox.alert("Sorry", "Language not available yet (" + lang +')');
39563 if (typeof(_T.en) == 'undefined') {
39565 Roo.apply(_T.en, _T);
39568 if (typeof(_T[lang]) == 'undefined') {
39569 Roo.MessageBox.alert("Sorry", "Language not available yet (" + lang +')');
39574 Roo.apply(_T, _T[lang]);
39575 // just need to set the text values for everything...
39577 /* this will not work ...
39581 function formLabel(name, val) {
39582 _this.form.findField(name).fieldEl.child('label').dom.innerHTML = val;
39585 formLabel('password', "Password"+':');
39586 formLabel('username', "Email Address"+':');
39587 formLabel('lang', "Language"+':');
39588 this.dialog.setTitle("Login");
39589 this.dialog.buttons[0].setText("Forgot Password");
39590 this.dialog.buttons[1].setText("Login");
39609 collapsible: false,
39611 center: { // needed??
39614 // tabPosition: 'top',
39617 alwaysShowTabs: false
39621 show : function(dlg)
39623 //console.log(this);
39624 this.form = this.layout.getRegion('center').activePanel.form;
39625 this.form.dialog = dlg;
39626 this.buttons[0].form = this.form;
39627 this.buttons[0].dialog = dlg;
39628 this.buttons[1].form = this.form;
39629 this.buttons[1].dialog = dlg;
39631 //this.resizeToLogo.defer(1000,this);
39632 // this is all related to resizing for logos..
39633 //var sz = Roo.get(Pman.Login.form.el.query('img')[0]).getSize();
39635 // this.resizeToLogo.defer(1000,this);
39638 //var w = Ext.lib.Dom.getViewWidth() - 100;
39639 //var h = Ext.lib.Dom.getViewHeight() - 100;
39640 //this.resizeTo(Math.max(350, Math.min(sz.width + 30, w)),Math.min(sz.height+200, h));
39642 if (this.disabled) {
39647 if (this.user.id < 0) { // used for inital setup situations.
39651 if (this.intervalID) {
39652 // remove the timer
39653 window.clearInterval(this.intervalID);
39654 this.intervalID = false;
39658 if (Roo.get('loading')) {
39659 Roo.get('loading').remove();
39661 if (Roo.get('loading-mask')) {
39662 Roo.get('loading-mask').hide();
39665 //incomming._node = tnode;
39667 //this.dialog.modal = !modal;
39668 //this.dialog.show();
39672 this.form.setValues({
39673 'username' : Roo.state.Manager.get(this.realm + '.username', ''),
39674 'lang' : Roo.state.Manager.get(this.realm + '.lang', 'en')
39677 this.switchLang(Roo.state.Manager.get(this.realm + '.lang', 'en'));
39678 if (this.form.findField('username').getValue().length > 0 ){
39679 this.form.findField('password').focus();
39681 this.form.findField('username').focus();
39689 xtype : 'ContentPanel',
39701 style : 'margin: 10px;',
39704 actionfailed : function(f, act) {
39705 // form can return { errors: .... }
39707 //act.result.errors // invalid form element list...
39708 //act.result.errorMsg// invalid form element list...
39710 this.dialog.el.unmask();
39711 Roo.MessageBox.alert("Error", act.result.errorMsg ? act.result.errorMsg :
39712 "Login failed - communication error - try again.");
39715 actioncomplete: function(re, act) {
39717 Roo.state.Manager.set(
39718 this.dialog.realm + '.username',
39719 this.findField('username').getValue()
39721 Roo.state.Manager.set(
39722 this.dialog.realm + '.lang',
39723 this.findField('lang').getValue()
39726 this.dialog.fillAuth(act.result.data);
39728 this.dialog.hide();
39730 if (Roo.get('loading-mask')) {
39731 Roo.get('loading-mask').show();
39733 Roo.XComponent.build();
39741 xtype : 'TextField',
39743 fieldLabel: "Email Address",
39746 autoCreate : {tag: "input", type: "text", size: "20"}
39749 xtype : 'TextField',
39751 fieldLabel: "Password",
39752 inputType: 'password',
39755 autoCreate : {tag: "input", type: "text", size: "20"},
39757 specialkey : function(e,ev) {
39758 if (ev.keyCode == 13) {
39759 this.form.dialog.el.mask("Logging in");
39760 this.form.doAction('submit', {
39761 url: this.form.dialog.url,
39762 method: this.form.dialog.method
39769 xtype : 'ComboBox',
39771 fieldLabel: "Language",
39774 xtype : 'SimpleStore',
39775 fields: ['lang', 'ldisp'],
39777 [ 'en', 'English' ],
39778 [ 'zh_HK' , '\u7E41\u4E2D' ],
39779 [ 'zh_CN', '\u7C21\u4E2D' ]
39783 valueField : 'lang',
39784 hiddenName: 'lang',
39786 displayField:'ldisp',
39790 triggerAction: 'all',
39791 emptyText:'Select a Language...',
39792 selectOnFocus:true,
39794 select : function(cb, rec, ix) {
39795 this.form.switchLang(rec.data.lang);
39811 text : "Forgot Password",
39813 click : function() {
39814 //console.log(this);
39815 var n = this.form.findField('username').getValue();
39817 Roo.MessageBox.alert("Error", "Fill in your email address");
39821 url: this.dialog.url,
39825 method: this.dialog.method,
39826 success: function(response, opts) { // check successfull...
39828 var res = this.dialog.processResponse(response);
39829 if (!res.success) { // error!
39830 Roo.MessageBox.alert("Error" ,
39831 res.errorMsg ? res.errorMsg : "Problem Requesting Password Reset");
39834 Roo.MessageBox.alert("Notice" ,
39835 "Please check you email for the Password Reset message");
39837 failure : function() {
39838 Roo.MessageBox.alert("Error" , "Problem Requesting Password Reset");
39851 click : function () {
39853 this.dialog.el.mask("Logging in");
39854 this.form.doAction('submit', {
39855 url: this.dialog.url,
39856 method: this.dialog.method