PageRenderTime 125ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/ext-4.0.7/pkgs/classes.js

https://bitbucket.org/srogerf/javascript
JavaScript | 14596 lines | 6692 code | 1488 blank | 6416 comment | 1428 complexity | a081e388c7e0f979768b033e444b0e49 MD5 | raw file
  1. /*
  2. This file is part of Ext JS 4
  3. Copyright (c) 2011 Sencha Inc
  4. Contact: http://www.sencha.com/contact
  5. GNU General Public License Usage
  6. This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
  7. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
  8. */
  9. /**
  10. * Base class that provides a common interface for publishing events. Subclasses are expected to to have a property
  11. * "events" with all the events defined, and, optionally, a property "listeners" with configured listeners defined.
  12. *
  13. * For example:
  14. *
  15. * Ext.define('Employee', {
  16. * extend: 'Ext.util.Observable',
  17. * constructor: function(config){
  18. * this.name = config.name;
  19. * this.addEvents({
  20. * "fired" : true,
  21. * "quit" : true
  22. * });
  23. *
  24. * // Copy configured listeners into *this* object so that the base class's
  25. * // constructor will add them.
  26. * this.listeners = config.listeners;
  27. *
  28. * // Call our superclass constructor to complete construction process.
  29. * this.callParent(arguments)
  30. * }
  31. * });
  32. *
  33. * This could then be used like this:
  34. *
  35. * var newEmployee = new Employee({
  36. * name: employeeName,
  37. * listeners: {
  38. * quit: function() {
  39. * // By default, "this" will be the object that fired the event.
  40. * alert(this.name + " has quit!");
  41. * }
  42. * }
  43. * });
  44. */
  45. Ext.define('Ext.util.Observable', {
  46. /* Begin Definitions */
  47. requires: ['Ext.util.Event'],
  48. statics: {
  49. /**
  50. * Removes **all** added captures from the Observable.
  51. *
  52. * @param {Ext.util.Observable} o The Observable to release
  53. * @static
  54. */
  55. releaseCapture: function(o) {
  56. o.fireEvent = this.prototype.fireEvent;
  57. },
  58. /**
  59. * Starts capture on the specified Observable. All events will be passed to the supplied function with the event
  60. * name + standard signature of the event **before** the event is fired. If the supplied function returns false,
  61. * the event will not fire.
  62. *
  63. * @param {Ext.util.Observable} o The Observable to capture events from.
  64. * @param {Function} fn The function to call when an event is fired.
  65. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. Defaults to
  66. * the Observable firing the event.
  67. * @static
  68. */
  69. capture: function(o, fn, scope) {
  70. o.fireEvent = Ext.Function.createInterceptor(o.fireEvent, fn, scope);
  71. },
  72. /**
  73. * Sets observability on the passed class constructor.
  74. *
  75. * This makes any event fired on any instance of the passed class also fire a single event through
  76. * the **class** allowing for central handling of events on many instances at once.
  77. *
  78. * Usage:
  79. *
  80. * Ext.util.Observable.observe(Ext.data.Connection);
  81. * Ext.data.Connection.on('beforerequest', function(con, options) {
  82. * console.log('Ajax request made to ' + options.url);
  83. * });
  84. *
  85. * @param {Function} c The class constructor to make observable.
  86. * @param {Object} listeners An object containing a series of listeners to add. See {@link #addListener}.
  87. * @static
  88. */
  89. observe: function(cls, listeners) {
  90. if (cls) {
  91. if (!cls.isObservable) {
  92. Ext.applyIf(cls, new this());
  93. this.capture(cls.prototype, cls.fireEvent, cls);
  94. }
  95. if (Ext.isObject(listeners)) {
  96. cls.on(listeners);
  97. }
  98. return cls;
  99. }
  100. }
  101. },
  102. /* End Definitions */
  103. /**
  104. * @cfg {Object} listeners
  105. *
  106. * A config object containing one or more event handlers to be added to this object during initialization. This
  107. * should be a valid listeners config object as specified in the {@link #addListener} example for attaching multiple
  108. * handlers at once.
  109. *
  110. * **DOM events from Ext JS {@link Ext.Component Components}**
  111. *
  112. * While _some_ Ext JS Component classes export selected DOM events (e.g. "click", "mouseover" etc), this is usually
  113. * only done when extra value can be added. For example the {@link Ext.view.View DataView}'s **`{@link
  114. * Ext.view.View#itemclick itemclick}`** event passing the node clicked on. To access DOM events directly from a
  115. * child element of a Component, we need to specify the `element` option to identify the Component property to add a
  116. * DOM listener to:
  117. *
  118. * new Ext.panel.Panel({
  119. * width: 400,
  120. * height: 200,
  121. * dockedItems: [{
  122. * xtype: 'toolbar'
  123. * }],
  124. * listeners: {
  125. * click: {
  126. * element: 'el', //bind to the underlying el property on the panel
  127. * fn: function(){ console.log('click el'); }
  128. * },
  129. * dblclick: {
  130. * element: 'body', //bind to the underlying body property on the panel
  131. * fn: function(){ console.log('dblclick body'); }
  132. * }
  133. * }
  134. * });
  135. */
  136. // @private
  137. isObservable: true,
  138. constructor: function(config) {
  139. var me = this;
  140. Ext.apply(me, config);
  141. if (me.listeners) {
  142. me.on(me.listeners);
  143. delete me.listeners;
  144. }
  145. me.events = me.events || {};
  146. if (me.bubbleEvents) {
  147. me.enableBubble(me.bubbleEvents);
  148. }
  149. },
  150. // @private
  151. eventOptionsRe : /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|element|vertical|horizontal|freezeEvent)$/,
  152. /**
  153. * Adds listeners to any Observable object (or Ext.Element) which are automatically removed when this Component is
  154. * destroyed.
  155. *
  156. * @param {Ext.util.Observable/Ext.Element} item The item to which to add a listener/listeners.
  157. * @param {Object/String} ename The event name, or an object containing event name properties.
  158. * @param {Function} fn (optional) If the `ename` parameter was an event name, this is the handler function.
  159. * @param {Object} scope (optional) If the `ename` parameter was an event name, this is the scope (`this` reference)
  160. * in which the handler function is executed.
  161. * @param {Object} opt (optional) If the `ename` parameter was an event name, this is the
  162. * {@link Ext.util.Observable#addListener addListener} options.
  163. */
  164. addManagedListener : function(item, ename, fn, scope, options) {
  165. var me = this,
  166. managedListeners = me.managedListeners = me.managedListeners || [],
  167. config;
  168. if (typeof ename !== 'string') {
  169. options = ename;
  170. for (ename in options) {
  171. if (options.hasOwnProperty(ename)) {
  172. config = options[ename];
  173. if (!me.eventOptionsRe.test(ename)) {
  174. me.addManagedListener(item, ename, config.fn || config, config.scope || options.scope, config.fn ? config : options);
  175. }
  176. }
  177. }
  178. }
  179. else {
  180. managedListeners.push({
  181. item: item,
  182. ename: ename,
  183. fn: fn,
  184. scope: scope,
  185. options: options
  186. });
  187. item.on(ename, fn, scope, options);
  188. }
  189. },
  190. /**
  191. * Removes listeners that were added by the {@link #mon} method.
  192. *
  193. * @param {Ext.util.Observable/Ext.Element} item The item from which to remove a listener/listeners.
  194. * @param {Object/String} ename The event name, or an object containing event name properties.
  195. * @param {Function} fn (optional) If the `ename` parameter was an event name, this is the handler function.
  196. * @param {Object} scope (optional) If the `ename` parameter was an event name, this is the scope (`this` reference)
  197. * in which the handler function is executed.
  198. */
  199. removeManagedListener : function(item, ename, fn, scope) {
  200. var me = this,
  201. options,
  202. config,
  203. managedListeners,
  204. length,
  205. i;
  206. if (typeof ename !== 'string') {
  207. options = ename;
  208. for (ename in options) {
  209. if (options.hasOwnProperty(ename)) {
  210. config = options[ename];
  211. if (!me.eventOptionsRe.test(ename)) {
  212. me.removeManagedListener(item, ename, config.fn || config, config.scope || options.scope);
  213. }
  214. }
  215. }
  216. }
  217. managedListeners = me.managedListeners ? me.managedListeners.slice() : [];
  218. for (i = 0, length = managedListeners.length; i < length; i++) {
  219. me.removeManagedListenerItem(false, managedListeners[i], item, ename, fn, scope);
  220. }
  221. },
  222. /**
  223. * Fires the specified event with the passed parameters (minus the event name, plus the `options` object passed
  224. * to {@link #addListener}).
  225. *
  226. * An event may be set to bubble up an Observable parent hierarchy (See {@link Ext.Component#getBubbleTarget}) by
  227. * calling {@link #enableBubble}.
  228. *
  229. * @param {String} eventName The name of the event to fire.
  230. * @param {Object...} args Variable number of parameters are passed to handlers.
  231. * @return {Boolean} returns false if any of the handlers return false otherwise it returns true.
  232. */
  233. fireEvent: function(eventName) {
  234. var name = eventName.toLowerCase(),
  235. events = this.events,
  236. event = events && events[name],
  237. bubbles = event && event.bubble;
  238. return this.continueFireEvent(name, Ext.Array.slice(arguments, 1), bubbles);
  239. },
  240. /**
  241. * Continue to fire event.
  242. * @private
  243. *
  244. * @param {String} eventName
  245. * @param {Array} args
  246. * @param {Boolean} bubbles
  247. */
  248. continueFireEvent: function(eventName, args, bubbles) {
  249. var target = this,
  250. queue, event,
  251. ret = true;
  252. do {
  253. if (target.eventsSuspended === true) {
  254. if ((queue = target.eventQueue)) {
  255. queue.push([eventName, args, bubbles]);
  256. }
  257. return ret;
  258. } else {
  259. event = target.events[eventName];
  260. // Continue bubbling if event exists and it is `true` or the handler didn't returns false and it
  261. // configure to bubble.
  262. if (event && event != true) {
  263. if ((ret = event.fire.apply(event, args)) === false) {
  264. break;
  265. }
  266. }
  267. }
  268. } while (bubbles && (target = target.getBubbleParent()));
  269. return ret;
  270. },
  271. /**
  272. * Gets the bubbling parent for an Observable
  273. * @private
  274. * @return {Ext.util.Observable} The bubble parent. null is returned if no bubble target exists
  275. */
  276. getBubbleParent: function(){
  277. var me = this, parent = me.getBubbleTarget && me.getBubbleTarget();
  278. if (parent && parent.isObservable) {
  279. return parent;
  280. }
  281. return null;
  282. },
  283. /**
  284. * Appends an event handler to this object.
  285. *
  286. * @param {String} eventName The name of the event to listen for. May also be an object who's property names are
  287. * event names.
  288. * @param {Function} fn The method the event invokes. Will be called with arguments given to
  289. * {@link #fireEvent} plus the `options` parameter described below.
  290. * @param {Object} [scope] The scope (`this` reference) in which the handler function is executed. **If
  291. * omitted, defaults to the object which fired the event.**
  292. * @param {Object} [options] An object containing handler configuration.
  293. *
  294. * **Note:** Unlike in ExtJS 3.x, the options object will also be passed as the last argument to every event handler.
  295. *
  296. * This object may contain any of the following properties:
  297. *
  298. * - **scope** : Object
  299. *
  300. * The scope (`this` reference) in which the handler function is executed. **If omitted, defaults to the object
  301. * which fired the event.**
  302. *
  303. * - **delay** : Number
  304. *
  305. * The number of milliseconds to delay the invocation of the handler after the event fires.
  306. *
  307. * - **single** : Boolean
  308. *
  309. * True to add a handler to handle just the next firing of the event, and then remove itself.
  310. *
  311. * - **buffer** : Number
  312. *
  313. * Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed by the specified number of
  314. * milliseconds. If the event fires again within that time, the original handler is _not_ invoked, but the new
  315. * handler is scheduled in its place.
  316. *
  317. * - **target** : Observable
  318. *
  319. * Only call the handler if the event was fired on the target Observable, _not_ if the event was bubbled up from a
  320. * child Observable.
  321. *
  322. * - **element** : String
  323. *
  324. * **This option is only valid for listeners bound to {@link Ext.Component Components}.** The name of a Component
  325. * property which references an element to add a listener to.
  326. *
  327. * This option is useful during Component construction to add DOM event listeners to elements of
  328. * {@link Ext.Component Components} which will exist only after the Component is rendered.
  329. * For example, to add a click listener to a Panel's body:
  330. *
  331. * new Ext.panel.Panel({
  332. * title: 'The title',
  333. * listeners: {
  334. * click: this.handlePanelClick,
  335. * element: 'body'
  336. * }
  337. * });
  338. *
  339. * **Combining Options**
  340. *
  341. * Using the options argument, it is possible to combine different types of listeners:
  342. *
  343. * A delayed, one-time listener.
  344. *
  345. * myPanel.on('hide', this.handleClick, this, {
  346. * single: true,
  347. * delay: 100
  348. * });
  349. *
  350. * **Attaching multiple handlers in 1 call**
  351. *
  352. * The method also allows for a single argument to be passed which is a config object containing properties which
  353. * specify multiple events. For example:
  354. *
  355. * myGridPanel.on({
  356. * cellClick: this.onCellClick,
  357. * mouseover: this.onMouseOver,
  358. * mouseout: this.onMouseOut,
  359. * scope: this // Important. Ensure "this" is correct during handler execution
  360. * });
  361. *
  362. * One can also specify options for each event handler separately:
  363. *
  364. * myGridPanel.on({
  365. * cellClick: {fn: this.onCellClick, scope: this, single: true},
  366. * mouseover: {fn: panel.onMouseOver, scope: panel}
  367. * });
  368. *
  369. */
  370. addListener: function(ename, fn, scope, options) {
  371. var me = this,
  372. config,
  373. event;
  374. if (typeof ename !== 'string') {
  375. options = ename;
  376. for (ename in options) {
  377. if (options.hasOwnProperty(ename)) {
  378. config = options[ename];
  379. if (!me.eventOptionsRe.test(ename)) {
  380. me.addListener(ename, config.fn || config, config.scope || options.scope, config.fn ? config : options);
  381. }
  382. }
  383. }
  384. }
  385. else {
  386. ename = ename.toLowerCase();
  387. me.events[ename] = me.events[ename] || true;
  388. event = me.events[ename] || true;
  389. if (Ext.isBoolean(event)) {
  390. me.events[ename] = event = new Ext.util.Event(me, ename);
  391. }
  392. event.addListener(fn, scope, Ext.isObject(options) ? options : {});
  393. }
  394. },
  395. /**
  396. * Removes an event handler.
  397. *
  398. * @param {String} eventName The type of event the handler was associated with.
  399. * @param {Function} fn The handler to remove. **This must be a reference to the function passed into the
  400. * {@link #addListener} call.**
  401. * @param {Object} scope (optional) The scope originally specified for the handler. It must be the same as the
  402. * scope argument specified in the original call to {@link #addListener} or the listener will not be removed.
  403. */
  404. removeListener: function(ename, fn, scope) {
  405. var me = this,
  406. config,
  407. event,
  408. options;
  409. if (typeof ename !== 'string') {
  410. options = ename;
  411. for (ename in options) {
  412. if (options.hasOwnProperty(ename)) {
  413. config = options[ename];
  414. if (!me.eventOptionsRe.test(ename)) {
  415. me.removeListener(ename, config.fn || config, config.scope || options.scope);
  416. }
  417. }
  418. }
  419. } else {
  420. ename = ename.toLowerCase();
  421. event = me.events[ename];
  422. if (event && event.isEvent) {
  423. event.removeListener(fn, scope);
  424. }
  425. }
  426. },
  427. /**
  428. * Removes all listeners for this object including the managed listeners
  429. */
  430. clearListeners: function() {
  431. var events = this.events,
  432. event,
  433. key;
  434. for (key in events) {
  435. if (events.hasOwnProperty(key)) {
  436. event = events[key];
  437. if (event.isEvent) {
  438. event.clearListeners();
  439. }
  440. }
  441. }
  442. this.clearManagedListeners();
  443. },
  444. //<debug>
  445. purgeListeners : function() {
  446. if (Ext.global.console) {
  447. Ext.global.console.warn('Observable: purgeListeners has been deprecated. Please use clearListeners.');
  448. }
  449. return this.clearListeners.apply(this, arguments);
  450. },
  451. //</debug>
  452. /**
  453. * Removes all managed listeners for this object.
  454. */
  455. clearManagedListeners : function() {
  456. var managedListeners = this.managedListeners || [],
  457. i = 0,
  458. len = managedListeners.length;
  459. for (; i < len; i++) {
  460. this.removeManagedListenerItem(true, managedListeners[i]);
  461. }
  462. this.managedListeners = [];
  463. },
  464. /**
  465. * Remove a single managed listener item
  466. * @private
  467. * @param {Boolean} isClear True if this is being called during a clear
  468. * @param {Object} managedListener The managed listener item
  469. * See removeManagedListener for other args
  470. */
  471. removeManagedListenerItem: function(isClear, managedListener, item, ename, fn, scope){
  472. if (isClear || (managedListener.item === item && managedListener.ename === ename && (!fn || managedListener.fn === fn) && (!scope || managedListener.scope === scope))) {
  473. managedListener.item.un(managedListener.ename, managedListener.fn, managedListener.scope);
  474. if (!isClear) {
  475. Ext.Array.remove(this.managedListeners, managedListener);
  476. }
  477. }
  478. },
  479. //<debug>
  480. purgeManagedListeners : function() {
  481. if (Ext.global.console) {
  482. Ext.global.console.warn('Observable: purgeManagedListeners has been deprecated. Please use clearManagedListeners.');
  483. }
  484. return this.clearManagedListeners.apply(this, arguments);
  485. },
  486. //</debug>
  487. /**
  488. * Adds the specified events to the list of events which this Observable may fire.
  489. *
  490. * @param {Object/String} o Either an object with event names as properties with a value of `true` or the first
  491. * event name string if multiple event names are being passed as separate parameters. Usage:
  492. *
  493. * this.addEvents({
  494. * storeloaded: true,
  495. * storecleared: true
  496. * });
  497. *
  498. * @param {String...} more (optional) Additional event names if multiple event names are being passed as separate
  499. * parameters. Usage:
  500. *
  501. * this.addEvents('storeloaded', 'storecleared');
  502. *
  503. */
  504. addEvents: function(o) {
  505. var me = this,
  506. args,
  507. len,
  508. i;
  509. me.events = me.events || {};
  510. if (Ext.isString(o)) {
  511. args = arguments;
  512. i = args.length;
  513. while (i--) {
  514. me.events[args[i]] = me.events[args[i]] || true;
  515. }
  516. } else {
  517. Ext.applyIf(me.events, o);
  518. }
  519. },
  520. /**
  521. * Checks to see if this object has any listeners for a specified event
  522. *
  523. * @param {String} eventName The name of the event to check for
  524. * @return {Boolean} True if the event is being listened for, else false
  525. */
  526. hasListener: function(ename) {
  527. var event = this.events[ename.toLowerCase()];
  528. return event && event.isEvent === true && event.listeners.length > 0;
  529. },
  530. /**
  531. * Suspends the firing of all events. (see {@link #resumeEvents})
  532. *
  533. * @param {Boolean} queueSuspended Pass as true to queue up suspended events to be fired
  534. * after the {@link #resumeEvents} call instead of discarding all suspended events.
  535. */
  536. suspendEvents: function(queueSuspended) {
  537. this.eventsSuspended = true;
  538. if (queueSuspended && !this.eventQueue) {
  539. this.eventQueue = [];
  540. }
  541. },
  542. /**
  543. * Resumes firing events (see {@link #suspendEvents}).
  544. *
  545. * If events were suspended using the `queueSuspended` parameter, then all events fired
  546. * during event suspension will be sent to any listeners now.
  547. */
  548. resumeEvents: function() {
  549. var me = this,
  550. queued = me.eventQueue;
  551. me.eventsSuspended = false;
  552. delete me.eventQueue;
  553. if (queued) {
  554. Ext.each(queued, function(e) {
  555. me.continueFireEvent.apply(me, e);
  556. });
  557. }
  558. },
  559. /**
  560. * Relays selected events from the specified Observable as if the events were fired by `this`.
  561. *
  562. * @param {Object} origin The Observable whose events this object is to relay.
  563. * @param {String[]} events Array of event names to relay.
  564. * @param {String} prefix
  565. */
  566. relayEvents : function(origin, events, prefix) {
  567. prefix = prefix || '';
  568. var me = this,
  569. len = events.length,
  570. i = 0,
  571. oldName,
  572. newName;
  573. for (; i < len; i++) {
  574. oldName = events[i].substr(prefix.length);
  575. newName = prefix + oldName;
  576. me.events[newName] = me.events[newName] || true;
  577. origin.on(oldName, me.createRelayer(newName));
  578. }
  579. },
  580. /**
  581. * @private
  582. * Creates an event handling function which refires the event from this object as the passed event name.
  583. * @param newName
  584. * @returns {Function}
  585. */
  586. createRelayer: function(newName){
  587. var me = this;
  588. return function(){
  589. return me.fireEvent.apply(me, [newName].concat(Array.prototype.slice.call(arguments, 0, -1)));
  590. };
  591. },
  592. /**
  593. * Enables events fired by this Observable to bubble up an owner hierarchy by calling `this.getBubbleTarget()` if
  594. * present. There is no implementation in the Observable base class.
  595. *
  596. * This is commonly used by Ext.Components to bubble events to owner Containers.
  597. * See {@link Ext.Component#getBubbleTarget}. The default implementation in Ext.Component returns the
  598. * Component's immediate owner. But if a known target is required, this can be overridden to access the
  599. * required target more quickly.
  600. *
  601. * Example:
  602. *
  603. * Ext.override(Ext.form.field.Base, {
  604. * // Add functionality to Field's initComponent to enable the change event to bubble
  605. * initComponent : Ext.Function.createSequence(Ext.form.field.Base.prototype.initComponent, function() {
  606. * this.enableBubble('change');
  607. * }),
  608. *
  609. * // We know that we want Field's events to bubble directly to the FormPanel.
  610. * getBubbleTarget : function() {
  611. * if (!this.formPanel) {
  612. * this.formPanel = this.findParentByType('form');
  613. * }
  614. * return this.formPanel;
  615. * }
  616. * });
  617. *
  618. * var myForm = new Ext.formPanel({
  619. * title: 'User Details',
  620. * items: [{
  621. * ...
  622. * }],
  623. * listeners: {
  624. * change: function() {
  625. * // Title goes red if form has been modified.
  626. * myForm.header.setStyle('color', 'red');
  627. * }
  628. * }
  629. * });
  630. *
  631. * @param {String/String[]} events The event name to bubble, or an Array of event names.
  632. */
  633. enableBubble: function(events) {
  634. var me = this;
  635. if (!Ext.isEmpty(events)) {
  636. events = Ext.isArray(events) ? events: Ext.Array.toArray(arguments);
  637. Ext.each(events,
  638. function(ename) {
  639. ename = ename.toLowerCase();
  640. var ce = me.events[ename] || true;
  641. if (Ext.isBoolean(ce)) {
  642. ce = new Ext.util.Event(me, ename);
  643. me.events[ename] = ce;
  644. }
  645. ce.bubble = true;
  646. });
  647. }
  648. }
  649. }, function() {
  650. this.createAlias({
  651. /**
  652. * @method
  653. * Shorthand for {@link #addListener}.
  654. * @alias Ext.util.Observable#addListener
  655. */
  656. on: 'addListener',
  657. /**
  658. * @method
  659. * Shorthand for {@link #removeListener}.
  660. * @alias Ext.util.Observable#removeListener
  661. */
  662. un: 'removeListener',
  663. /**
  664. * @method
  665. * Shorthand for {@link #addManagedListener}.
  666. * @alias Ext.util.Observable#addManagedListener
  667. */
  668. mon: 'addManagedListener',
  669. /**
  670. * @method
  671. * Shorthand for {@link #removeManagedListener}.
  672. * @alias Ext.util.Observable#removeManagedListener
  673. */
  674. mun: 'removeManagedListener'
  675. });
  676. //deprecated, will be removed in 5.0
  677. this.observeClass = this.observe;
  678. Ext.apply(Ext.util.Observable.prototype, function(){
  679. // this is considered experimental (along with beforeMethod, afterMethod, removeMethodListener?)
  680. // allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call
  681. // private
  682. function getMethodEvent(method){
  683. var e = (this.methodEvents = this.methodEvents || {})[method],
  684. returnValue,
  685. v,
  686. cancel,
  687. obj = this;
  688. if (!e) {
  689. this.methodEvents[method] = e = {};
  690. e.originalFn = this[method];
  691. e.methodName = method;
  692. e.before = [];
  693. e.after = [];
  694. var makeCall = function(fn, scope, args){
  695. if((v = fn.apply(scope || obj, args)) !== undefined){
  696. if (typeof v == 'object') {
  697. if(v.returnValue !== undefined){
  698. returnValue = v.returnValue;
  699. }else{
  700. returnValue = v;
  701. }
  702. cancel = !!v.cancel;
  703. }
  704. else
  705. if (v === false) {
  706. cancel = true;
  707. }
  708. else {
  709. returnValue = v;
  710. }
  711. }
  712. };
  713. this[method] = function(){
  714. var args = Array.prototype.slice.call(arguments, 0),
  715. b, i, len;
  716. returnValue = v = undefined;
  717. cancel = false;
  718. for(i = 0, len = e.before.length; i < len; i++){
  719. b = e.before[i];
  720. makeCall(b.fn, b.scope, args);
  721. if (cancel) {
  722. return returnValue;
  723. }
  724. }
  725. if((v = e.originalFn.apply(obj, args)) !== undefined){
  726. returnValue = v;
  727. }
  728. for(i = 0, len = e.after.length; i < len; i++){
  729. b = e.after[i];
  730. makeCall(b.fn, b.scope, args);
  731. if (cancel) {
  732. return returnValue;
  733. }
  734. }
  735. return returnValue;
  736. };
  737. }
  738. return e;
  739. }
  740. return {
  741. // these are considered experimental
  742. // allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call
  743. // adds an 'interceptor' called before the original method
  744. beforeMethod : function(method, fn, scope){
  745. getMethodEvent.call(this, method).before.push({
  746. fn: fn,
  747. scope: scope
  748. });
  749. },
  750. // adds a 'sequence' called after the original method
  751. afterMethod : function(method, fn, scope){
  752. getMethodEvent.call(this, method).after.push({
  753. fn: fn,
  754. scope: scope
  755. });
  756. },
  757. removeMethodListener: function(method, fn, scope){
  758. var e = this.getMethodEvent(method),
  759. i, len;
  760. for(i = 0, len = e.before.length; i < len; i++){
  761. if(e.before[i].fn == fn && e.before[i].scope == scope){
  762. Ext.Array.erase(e.before, i, 1);
  763. return;
  764. }
  765. }
  766. for(i = 0, len = e.after.length; i < len; i++){
  767. if(e.after[i].fn == fn && e.after[i].scope == scope){
  768. Ext.Array.erase(e.after, i, 1);
  769. return;
  770. }
  771. }
  772. },
  773. toggleEventLogging: function(toggle) {
  774. Ext.util.Observable[toggle ? 'capture' : 'releaseCapture'](this, function(en) {
  775. if (Ext.isDefined(Ext.global.console)) {
  776. Ext.global.console.log(en, arguments);
  777. }
  778. });
  779. }
  780. };
  781. }());
  782. });
  783. /**
  784. * @class Ext.util.Animate
  785. * This animation class is a mixin.
  786. *
  787. * Ext.util.Animate provides an API for the creation of animated transitions of properties and styles.
  788. * This class is used as a mixin and currently applied to {@link Ext.Element}, {@link Ext.CompositeElement},
  789. * {@link Ext.draw.Sprite}, {@link Ext.draw.CompositeSprite}, and {@link Ext.Component}. Note that Components
  790. * have a limited subset of what attributes can be animated such as top, left, x, y, height, width, and
  791. * opacity (color, paddings, and margins can not be animated).
  792. *
  793. * ## Animation Basics
  794. *
  795. * All animations require three things - `easing`, `duration`, and `to` (the final end value for each property)
  796. * you wish to animate. Easing and duration are defaulted values specified below.
  797. * Easing describes how the intermediate values used during a transition will be calculated.
  798. * {@link Ext.fx.Anim#easing Easing} allows for a transition to change speed over its duration.
  799. * You may use the defaults for easing and duration, but you must always set a
  800. * {@link Ext.fx.Anim#to to} property which is the end value for all animations.
  801. *
  802. * Popular element 'to' configurations are:
  803. *
  804. * - opacity
  805. * - x
  806. * - y
  807. * - color
  808. * - height
  809. * - width
  810. *
  811. * Popular sprite 'to' configurations are:
  812. *
  813. * - translation
  814. * - path
  815. * - scale
  816. * - stroke
  817. * - rotation
  818. *
  819. * The default duration for animations is 250 (which is a 1/4 of a second). Duration is denoted in
  820. * milliseconds. Therefore 1 second is 1000, 1 minute would be 60000, and so on. The default easing curve
  821. * used for all animations is 'ease'. Popular easing functions are included and can be found in {@link Ext.fx.Anim#easing Easing}.
  822. *
  823. * For example, a simple animation to fade out an element with a default easing and duration:
  824. *
  825. * var p1 = Ext.get('myElementId');
  826. *
  827. * p1.animate({
  828. * to: {
  829. * opacity: 0
  830. * }
  831. * });
  832. *
  833. * To make this animation fade out in a tenth of a second:
  834. *
  835. * var p1 = Ext.get('myElementId');
  836. *
  837. * p1.animate({
  838. * duration: 100,
  839. * to: {
  840. * opacity: 0
  841. * }
  842. * });
  843. *
  844. * ## Animation Queues
  845. *
  846. * By default all animations are added to a queue which allows for animation via a chain-style API.
  847. * For example, the following code will queue 4 animations which occur sequentially (one right after the other):
  848. *
  849. * p1.animate({
  850. * to: {
  851. * x: 500
  852. * }
  853. * }).animate({
  854. * to: {
  855. * y: 150
  856. * }
  857. * }).animate({
  858. * to: {
  859. * backgroundColor: '#f00' //red
  860. * }
  861. * }).animate({
  862. * to: {
  863. * opacity: 0
  864. * }
  865. * });
  866. *
  867. * You can change this behavior by calling the {@link Ext.util.Animate#syncFx syncFx} method and all
  868. * subsequent animations for the specified target will be run concurrently (at the same time).
  869. *
  870. * p1.syncFx(); //this will make all animations run at the same time
  871. *
  872. * p1.animate({
  873. * to: {
  874. * x: 500
  875. * }
  876. * }).animate({
  877. * to: {
  878. * y: 150
  879. * }
  880. * }).animate({
  881. * to: {
  882. * backgroundColor: '#f00' //red
  883. * }
  884. * }).animate({
  885. * to: {
  886. * opacity: 0
  887. * }
  888. * });
  889. *
  890. * This works the same as:
  891. *
  892. * p1.animate({
  893. * to: {
  894. * x: 500,
  895. * y: 150,
  896. * backgroundColor: '#f00' //red
  897. * opacity: 0
  898. * }
  899. * });
  900. *
  901. * The {@link Ext.util.Animate#stopAnimation stopAnimation} method can be used to stop any
  902. * currently running animations and clear any queued animations.
  903. *
  904. * ## Animation Keyframes
  905. *
  906. * You can also set up complex animations with {@link Ext.fx.Anim#keyframes keyframes} which follow the
  907. * CSS3 Animation configuration pattern. Note rotation, translation, and scaling can only be done for sprites.
  908. * The previous example can be written with the following syntax:
  909. *
  910. * p1.animate({
  911. * duration: 1000, //one second total
  912. * keyframes: {
  913. * 25: { //from 0 to 250ms (25%)
  914. * x: 0
  915. * },
  916. * 50: { //from 250ms to 500ms (50%)
  917. * y: 0
  918. * },
  919. * 75: { //from 500ms to 750ms (75%)
  920. * backgroundColor: '#f00' //red
  921. * },
  922. * 100: { //from 750ms to 1sec
  923. * opacity: 0
  924. * }
  925. * }
  926. * });
  927. *
  928. * ## Animation Events
  929. *
  930. * Each animation you create has events for {@link Ext.fx.Anim#beforeanimate beforeanimate},
  931. * {@link Ext.fx.Anim#afteranimate afteranimate}, and {@link Ext.fx.Anim#lastframe lastframe}.
  932. * Keyframed animations adds an additional {@link Ext.fx.Animator#keyframe keyframe} event which
  933. * fires for each keyframe in your animation.
  934. *
  935. * All animations support the {@link Ext.util.Observable#listeners listeners} configuration to attact functions to these events.
  936. *
  937. * startAnimate: function() {
  938. * var p1 = Ext.get('myElementId');
  939. * p1.animate({
  940. * duration: 100,
  941. * to: {
  942. * opacity: 0
  943. * },
  944. * listeners: {
  945. * beforeanimate: function() {
  946. * // Execute my custom method before the animation
  947. * this.myBeforeAnimateFn();
  948. * },
  949. * afteranimate: function() {
  950. * // Execute my custom method after the animation
  951. * this.myAfterAnimateFn();
  952. * },
  953. * scope: this
  954. * });
  955. * },
  956. * myBeforeAnimateFn: function() {
  957. * // My custom logic
  958. * },
  959. * myAfterAnimateFn: function() {
  960. * // My custom logic
  961. * }
  962. *
  963. * Due to the fact that animations run asynchronously, you can determine if an animation is currently
  964. * running on any target by using the {@link Ext.util.Animate#getActiveAnimation getActiveAnimation}
  965. * method. This method will return false if there are no active animations or return the currently
  966. * running {@link Ext.fx.Anim} instance.
  967. *
  968. * In this example, we're going to wait for the current animation to finish, then stop any other
  969. * queued animations before we fade our element's opacity to 0:
  970. *
  971. * var curAnim = p1.getActiveAnimation();
  972. * if (curAnim) {
  973. * curAnim.on('afteranimate', function() {
  974. * p1.stopAnimation();
  975. * p1.animate({
  976. * to: {
  977. * opacity: 0
  978. * }
  979. * });
  980. * });
  981. * }
  982. *
  983. * @docauthor Jamie Avins <jamie@sencha.com>
  984. */
  985. Ext.define('Ext.util.Animate', {
  986. uses: ['Ext.fx.Manager', 'Ext.fx.Anim'],
  987. /**
  988. * <p>Perform custom animation on this object.<p>
  989. * <p>This method is applicable to both the {@link Ext.Component Component} class and the {@link Ext.Element Element} class.
  990. * It performs animated transitions of certain properties of this object over a specified timeline.</p>
  991. * <p>The sole parameter is an object which specifies start property values, end property values, and properties which
  992. * describe the timeline. Of the properties listed below, only <b><code>to</code></b> is mandatory.</p>
  993. * <p>Properties include<ul>
  994. * <li><code>from</code> <div class="sub-desc">An object which specifies start values for the properties being animated.
  995. * If not supplied, properties are animated from current settings. The actual properties which may be animated depend upon
  996. * ths object being animated. See the sections below on Element and Component animation.<div></li>
  997. * <li><code>to</code> <div class="sub-desc">An object which specifies end values for the properties being animated.</div></li>
  998. * <li><code>duration</code><div class="sub-desc">The duration <b>in milliseconds</b> for which the animation will run.</div></li>
  999. * <li><code>easing</code> <div class="sub-desc">A string value describing an easing type to modify the rate of change from the default linear to non-linear. Values may be one of:<code><ul>
  1000. * <li>ease</li>
  1001. * <li>easeIn</li>
  1002. * <li>easeOut</li>
  1003. * <li>easeInOut</li>
  1004. * <li>backIn</li>
  1005. * <li>backOut</li>
  1006. * <li>elasticIn</li>
  1007. * <li>elasticOut</li>
  1008. * <li>bounceIn</li>
  1009. * <li>bounceOut</li>
  1010. * </ul></code></div></li>
  1011. * <li><code>keyframes</code> <div class="sub-desc">This is an object which describes the state of animated properties at certain points along the timeline.
  1012. * it is an object containing properties who's names are the percentage along the timeline being described and who's values specify the animation state at that point.</div></li>
  1013. * <li><code>listeners</code> <div class="sub-desc">This is a standard {@link Ext.util.Observable#listeners listeners} configuration object which may be used
  1014. * to inject behaviour at either the <code>beforeanimate</code> event or the <code>afteranimate</code> event.</div></li>
  1015. * </ul></p>
  1016. * <h3>Animating an {@link Ext.Element Element}</h3>
  1017. * When animating an Element, the following properties may be specified in <code>from</code>, <code>to</code>, and <code>keyframe</code> objects:<ul>
  1018. * <li><code>x</code> <div class="sub-desc">The page X position in pixels.</div></li>
  1019. * <li><code>y</code> <div class="sub-desc">The page Y position in pixels</div></li>
  1020. * <li><code>left</code> <div class="sub-desc">The element's CSS <code>left</code> value. Units must be supplied.</div></li>
  1021. * <li><code>top</code> <div class="sub-desc">The element's CSS <code>top</code> value. Units must be supplied.</div></li>
  1022. * <li><code>width</code> <div class="sub-desc">The element's CSS <code>width</code> value. Units must be supplied.</div></li>
  1023. * <li><code>height</code> <div class="sub-desc">The element's CSS <code>height</code> value. Units must be supplied.</div></li>
  1024. * <li><code>scrollLeft</code> <div class="sub-desc">The element's <code>scrollLeft</code> value.</div></li>
  1025. * <li><code>scrollTop</code> <div class="sub-desc">The element's <code>scrollLeft</code> value.</div></li>
  1026. * <li><code>opacity</code> <div class="sub-desc">The element's <code>opacity</code> value. This must be a value between <code>0</code> and <code>1</code>.</div></li>
  1027. * </ul>
  1028. * <p><b>Be aware than animating an Element which is being used by an Ext Component without in some way informing the Component about the changed element state
  1029. * will result in incorrect Component behaviour. This is because the Component will be using the old state of the element. To avoid this problem, it is now possible to
  1030. * directly animate certain properties of Components.</b></p>
  1031. * <h3>Animating a {@link Ext.Component Component}</h3>
  1032. * When animating an Element, the following properties may be specified in <code>from</code>, <code>to</code>, and <code>keyframe</code> objects:<ul>
  1033. * <li><code>x</code> <div class="sub-desc">The Component's page X position in pixels.</div></li>
  1034. * <li><code>y</code> <div class="sub-desc">The Component's page Y position in pixels</div></li>
  1035. * <li><code>left</code> <div class="sub-desc">The Component's <code>left</code> value in pixels.</div></li>
  1036. * <li><code>top</code> <div class="sub-desc">The Component's <code>top</code> value in pixels.</div></li>
  1037. * <li><code>width</code> <div class="sub-desc">The Component's <code>width</code> value in pixels.</div></li>
  1038. * <li><code>width</code> <div class="sub-desc">The Component's <code>width</code> value in pixels.</div></li>
  1039. * <li><code>dynamic</code> <div class="sub-desc">Specify as true to update the Component's layout (if it is a Container) at every frame
  1040. * of the animation. <i>Use sparingly as laying out on every intermediate size change is an expensive operation</i>.</div></li>
  1041. * </ul>
  1042. * <p>For example, to animate a Window to a new size, ensuring that its internal layout, and any shadow is correct:</p>
  1043. * <pre><code>
  1044. myWindow = Ext.create('Ext.window.Window', {
  1045. title: 'Test Component animation',
  1046. width: 500,
  1047. height: 300,
  1048. layout: {
  1049. type: 'hbox',
  1050. align: 'stretch'
  1051. },
  1052. items: [{
  1053. title: 'Left: 33%',
  1054. margins: '5 0 5 5',
  1055. flex: 1
  1056. }, {
  1057. title: 'Left: 66%',
  1058. margins: '5 5 5 5',
  1059. flex: 2
  1060. }]
  1061. });
  1062. myWindow.show();
  1063. myWindow.header.el.on('click', function() {
  1064. myWindow.animate({
  1065. to: {
  1066. width: (myWindow.getWidth() == 500) ? 700 : 500,
  1067. height: (myWindow.getHeight() == 300) ? 400 : 300,
  1068. }
  1069. });
  1070. });
  1071. </code></pre>
  1072. * <p>For performance reasons, by default, the internal layout is only updated when the Window reaches its final <code>"to"</code> size. If dynamic updating of the Window's child
  1073. * Components is required, then configure the animation with <code>dynamic: true</code> and the two child items will maintain their proportions during the animation.</p>
  1074. * @param {Object} config An object containing properties which describe the animation's start and end states, and the timeline of the animation.
  1075. * @return {Object} this
  1076. */
  1077. animate: function(animObj) {
  1078. var me = this;
  1079. if (Ext.fx.Manager.hasFxBlock(me.id)) {
  1080. return me;
  1081. }
  1082. Ext.fx.Manager.queueFx(Ext.create('Ext.fx.Anim', me.anim(animObj)));
  1083. return this;
  1084. },
  1085. // @private - process the passed fx configuration.
  1086. anim: function(config) {
  1087. if (!Ext.isObject(config)) {
  1088. return (config) ? {} : false;
  1089. }
  1090. var me = this;
  1091. if (config.stopAnimation) {
  1092. me.stopAnimation();
  1093. }
  1094. Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id));
  1095. return Ext.apply({
  1096. target: me,
  1097. paused: true
  1098. }, config);
  1099. },
  1100. /**
  1101. * @deprecated 4.0 Replaced by {@link #stopAnimation}
  1102. * Stops any running effects and clears this object's internal effects queue if it contains
  1103. * any additional effects that haven't started yet.
  1104. * @return {Ext.Element} The Element
  1105. * @method
  1106. */
  1107. stopFx: Ext.Function.alias(Ext.util.Animate, 'stopAnimation'),
  1108. /**
  1109. * Stops any running effects and clears this object's internal effects queue if it contains
  1110. * any additional effects that haven't started yet.
  1111. * @return {Ext.Element} The Element
  1112. */
  1113. stopAnimation: function() {
  1114. Ext.fx.Manager.stopAnimation(this.id);
  1115. return this;
  1116. },
  1117. /**
  1118. * Ensures that all effects queued after syncFx is called on this object are
  1119. * run concurrently. This is the opposite of {@link #sequenceFx}.
  1120. * @return {Object} this
  1121. */
  1122. syncFx: function() {
  1123. Ext.fx.Manager.setFxDefaults(this.id, {
  1124. concurrent: true
  1125. });
  1126. return this;
  1127. },
  1128. /**
  1129. * Ensures that all effects queued after sequenceFx is called on this object are
  1130. * run in sequence. This is the opposite of {@link #syncFx}.
  1131. * @return {Object} this
  1132. */
  1133. sequenceFx: function() {
  1134. Ext.fx.Manager.setFxDefaults(this.id, {
  1135. concurrent: false
  1136. });
  1137. return this;
  1138. },
  1139. /**
  1140. * @deprecated 4.0 Replaced by {@link #getActiveAnimation}
  1141. * @alias Ext.util.Animate#getActiveAnimation
  1142. * @method
  1143. */
  1144. hasActiveFx: Ext.Function.alias(Ext.util.Animate, 'getActiveAnimation'),
  1145. /**
  1146. * Returns the current animation if this object has any effects actively running or queued, else returns false.
  1147. * @return {Ext.fx.Anim/Boolean} Anim if element has active effects, else false
  1148. */
  1149. getActiveAnimation: function() {
  1150. return Ext.fx.Manager.getActiveAnimation(this.id);
  1151. }
  1152. }, function(){
  1153. // Apply Animate mixin manually until Element is defined in the proper 4.x way
  1154. Ext.applyIf(Ext.Element.prototype, this.prototype);
  1155. // We need to call this again so the animation methods get copied over to CE
  1156. Ext.CompositeElementLite.importElementMethods();
  1157. });
  1158. /**
  1159. * @class Ext.state.Provider
  1160. * <p>Abstract base class for state provider implementations. The provider is responsible
  1161. * for setting values and extracting values to/from the underlying storage source. The
  1162. * storage source can vary and the details should be implemented in a subclass. For example
  1163. * a provider could use a server side database or the browser localstorage where supported.</p>
  1164. *
  1165. * <p>This class provides methods for encoding and decoding <b>typed</b> variables including
  1166. * dates and defines the Provider interface. By default these methods put the value and the
  1167. * type information into a delimited string that can be stored. These should be overridden in
  1168. * a subclass if you want to change the format of the encoded value and subsequent decoding.</p>
  1169. */
  1170. Ext.define('Ext.state.Provider', {
  1171. mixins: {
  1172. observable: 'Ext.util.Observable'
  1173. },
  1174. /**
  1175. * @cfg {String} prefix A string to prefix to items stored in the underlying state store.
  1176. * Defaults to <tt>'ext-'</tt>
  1177. */
  1178. prefix: 'ext-',
  1179. constructor : function(config){
  1180. config = config || {};
  1181. var me = this;
  1182. Ext.apply(me, config);
  1183. /**
  1184. * @event statechange
  1185. * Fires when a state change occurs.
  1186. * @param {Ext.state.Provider} this This state provider
  1187. * @param {String} key The state key which was changed
  1188. * @param {String} value The encoded value for the state
  1189. */
  1190. me.addEvents("statechange");
  1191. me.state = {};
  1192. me.mixins.observable.constructor.call(me);
  1193. },
  1194. /**
  1195. * Returns the current value for a key
  1196. * @param {String} name The key name
  1197. * @param {Object} defaultValue A default value to return if the key's value is not found
  1198. * @return {Object} The state data
  1199. */
  1200. get : function(name, defaultValue){
  1201. return typeof this.state[name] == "undefined" ?
  1202. defaultValue : this.state[name];
  1203. },
  1204. /**
  1205. * Clears a value from the state
  1206. * @param {String} name The key name
  1207. */
  1208. clear : function(name){
  1209. var me = this;
  1210. delete me.state[name];
  1211. me.fireEvent("statechange", me, name, null);
  1212. },
  1213. /**
  1214. * Sets the value for a key
  1215. * @param {String} name The key name
  1216. * @param {Object} value The value to set
  1217. */
  1218. set : function(name, value){
  1219. var me = this;
  1220. me.state[name] = value;
  1221. me.fireEvent("statechange", me, name, value);
  1222. },
  1223. /**
  1224. * Decodes a string previously encoded with {@link #encodeValue}.
  1225. * @param {String} value The value to decode
  1226. * @return {Object} The decoded value
  1227. */
  1228. decodeValue : function(value){
  1229. // a -> Array
  1230. // n -> Number
  1231. // d -> Date
  1232. // b -> Boolean
  1233. // s -> String
  1234. // o -> Object
  1235. // -> Empty (null)
  1236. var me = this,
  1237. re = /^(a|n|d|b|s|o|e)\:(.*)$/,
  1238. matches = re.exec(unescape(value)),
  1239. all,
  1240. type,
  1241. value,
  1242. keyValue;
  1243. if(!matches || !matches[1]){
  1244. return; // non state
  1245. }
  1246. type = matches[1];
  1247. value = matches[2];
  1248. switch (type) {
  1249. case 'e':
  1250. return null;
  1251. case 'n':
  1252. return parseFloat(value);
  1253. case 'd':
  1254. return new Date(Date.parse(value));
  1255. case 'b':
  1256. return (value == '1');
  1257. case 'a':
  1258. all = [];
  1259. if(value != ''){
  1260. Ext.each(value.split('^'), function(val){
  1261. all.push(me.decodeValue(val));
  1262. }, me);
  1263. }
  1264. return all;
  1265. case 'o':
  1266. all = {};
  1267. if(value != ''){
  1268. Ext.each(value.split('^'), function(val){
  1269. keyValue = val.split('=');
  1270. all[keyValue[0]] = me.decodeValue(keyValue[1]);
  1271. }, me);
  1272. }
  1273. return all;
  1274. default:
  1275. return value;
  1276. }
  1277. },
  1278. /**
  1279. * Encodes a value including type information. Decode with {@link #decodeValue}.
  1280. * @param {Object} value The value to encode
  1281. * @return {String} The encoded value
  1282. */
  1283. encodeValue : function(value){
  1284. var flat = '',
  1285. i = 0,
  1286. enc,
  1287. len,
  1288. key;
  1289. if (value == null) {
  1290. return 'e:1';
  1291. } else if(typeof value == 'number') {
  1292. enc = 'n:' + value;
  1293. } else if(typeof value == 'boolean') {
  1294. enc = 'b:' + (value ? '1' : '0');
  1295. } else if(Ext.isDate(value)) {
  1296. enc = 'd:' + value.toGMTString();
  1297. } else if(Ext.isArray(value)) {
  1298. for (len = value.length; i < len; i++) {
  1299. flat += this.encodeValue(value[i]);
  1300. if (i != len - 1) {
  1301. flat += '^';
  1302. }
  1303. }
  1304. enc = 'a:' + flat;
  1305. } else if (typeof value == 'object') {
  1306. for (key in value) {
  1307. if (typeof value[key] != 'function' && value[key] !== undefined) {
  1308. flat += key + '=' + this.encodeValue(value[key]) + '^';
  1309. }
  1310. }
  1311. enc = 'o:' + flat.substring(0, flat.length-1);
  1312. } else {
  1313. enc = 's:' + value;
  1314. }
  1315. return escape(enc);
  1316. }
  1317. });
  1318. /**
  1319. * Provides searching of Components within Ext.ComponentManager (globally) or a specific
  1320. * Ext.container.Container on the document with a similar syntax to a CSS selector.
  1321. *
  1322. * Components can be retrieved by using their {@link Ext.Component xtype} with an optional . prefix
  1323. *
  1324. * - `component` or `.component`
  1325. * - `gridpanel` or `.gridpanel`
  1326. *
  1327. * An itemId or id must be prefixed with a #
  1328. *
  1329. * - `#myContainer`
  1330. *
  1331. * Attributes must be wrapped in brackets
  1332. *
  1333. * - `component[autoScroll]`
  1334. * - `panel[title="Test"]`
  1335. *
  1336. * Member expressions from candidate Components may be tested. If the expression returns a *truthy* value,
  1337. * the candidate Component will be included in the query:
  1338. *
  1339. * var disabledFields = myFormPanel.query("{isDisabled()}");
  1340. *
  1341. * Pseudo classes may be used to filter results in the same way as in {@link Ext.DomQuery DomQuery}:
  1342. *
  1343. * // Function receives array and returns a filtered array.
  1344. * Ext.ComponentQuery.pseudos.invalid = function(items) {
  1345. * var i = 0, l = items.length, c, result = [];
  1346. * for (; i < l; i++) {
  1347. * if (!(c = items[i]).isValid()) {
  1348. * result.push(c);
  1349. * }
  1350. * }
  1351. * return result;
  1352. * };
  1353. *
  1354. * var invalidFields = myFormPanel.query('field:invalid');
  1355. * if (invalidFields.length) {
  1356. * invalidFields[0].getEl().scrollIntoView(myFormPanel.body);
  1357. * for (var i = 0, l = invalidFields.length; i < l; i++) {
  1358. * invalidFields[i].getEl().frame("red");
  1359. * }
  1360. * }
  1361. *
  1362. * Default pseudos include:
  1363. *
  1364. * - not
  1365. * - last
  1366. *
  1367. * Queries return an array of components.
  1368. * Here are some example queries.
  1369. *
  1370. * // retrieve all Ext.Panels in the document by xtype
  1371. * var panelsArray = Ext.ComponentQuery.query('panel');
  1372. *
  1373. * // retrieve all Ext.Panels within the container with an id myCt
  1374. * var panelsWithinmyCt = Ext.ComponentQuery.query('#myCt panel');
  1375. *
  1376. * // retrieve all direct children which are Ext.Panels within myCt
  1377. * var directChildPanel = Ext.ComponentQuery.query('#myCt > panel');
  1378. *
  1379. * // retrieve all grids and trees
  1380. * var gridsAndTrees = Ext.ComponentQuery.query('gridpanel, treepanel');
  1381. *
  1382. * For easy access to queries based from a particular Container see the {@link Ext.container.Container#query},
  1383. * {@link Ext.container.Container#down} and {@link Ext.container.Container#child} methods. Also see
  1384. * {@link Ext.Component#up}.
  1385. */
  1386. Ext.define('Ext.ComponentQuery', {
  1387. singleton: true,
  1388. uses: ['Ext.ComponentManager']
  1389. }, function() {
  1390. var cq = this,
  1391. // A function source code pattern with a placeholder which accepts an expression which yields a truth value when applied
  1392. // as a member on each item in the passed array.
  1393. filterFnPattern = [
  1394. 'var r = [],',
  1395. 'i = 0,',
  1396. 'it = items,',
  1397. 'l = it.length,',
  1398. 'c;',
  1399. 'for (; i < l; i++) {',
  1400. 'c = it[i];',
  1401. 'if (c.{0}) {',
  1402. 'r.push(c);',
  1403. '}',
  1404. '}',
  1405. 'return r;'
  1406. ].join(''),
  1407. filterItems = function(items, operation) {
  1408. // Argument list for the operation is [ itemsArray, operationArg1, operationArg2...]
  1409. // The operation's method loops over each item in the candidate array and
  1410. // returns an array of items which match its criteria
  1411. return operation.method.apply(this, [ items ].concat(operation.args));
  1412. },
  1413. getItems = function(items, mode) {
  1414. var result = [],
  1415. i = 0,
  1416. length = items.length,
  1417. candidate,
  1418. deep = mode !== '>';
  1419. for (; i < length; i++) {
  1420. candidate = items[i];
  1421. if (candidate.getRefItems) {
  1422. result = result.concat(candidate.getRefItems(deep));
  1423. }
  1424. }
  1425. return result;
  1426. },
  1427. getAncestors = function(items) {
  1428. var result = [],
  1429. i = 0,
  1430. length = items.length,
  1431. candidate;
  1432. for (; i < length; i++) {
  1433. candidate = items[i];
  1434. while (!!(candidate = (candidate.ownerCt || candidate.floatParent))) {
  1435. result.push(candidate);
  1436. }
  1437. }
  1438. return result;
  1439. },
  1440. // Filters the passed candidate array and returns only items which match the passed xtype
  1441. filterByXType = function(items, xtype, shallow) {
  1442. if (xtype === '*') {
  1443. return items.slice();
  1444. }
  1445. else {
  1446. var result = [],
  1447. i = 0,
  1448. length = items.length,
  1449. candidate;
  1450. for (; i < length; i++) {
  1451. candidate = items[i];
  1452. if (candidate.isXType(xtype, shallow)) {
  1453. result.push(candidate);
  1454. }
  1455. }
  1456. return result;
  1457. }
  1458. },
  1459. // Filters the passed candidate array and returns only items which have the passed className
  1460. filterByClassName = function(items, className) {
  1461. var EA = Ext.Array,
  1462. result = [],
  1463. i = 0,
  1464. length = items.length,
  1465. candidate;
  1466. for (; i < length; i++) {
  1467. candidate = items[i];
  1468. if (candidate.el ? candidate.el.hasCls(className) : EA.contains(candidate.initCls(), className)) {
  1469. result.push(candidate);
  1470. }
  1471. }
  1472. return result;
  1473. },
  1474. // Filters the passed candidate array and returns only items which have the specified property match
  1475. filterByAttribute = function(items, property, operator, value) {
  1476. var result = [],
  1477. i = 0,
  1478. length = items.length,
  1479. candidate;
  1480. for (; i < length; i++) {
  1481. candidate = items[i];
  1482. if (!value ? !!candidate[property] : (String(candidate[property]) === value)) {
  1483. result.push(candidate);
  1484. }
  1485. }
  1486. return result;
  1487. },
  1488. // Filters the passed candidate array and returns only items which have the specified itemId or id
  1489. filterById = function(items, id) {
  1490. var result = [],
  1491. i = 0,
  1492. length = items.length,
  1493. candidate;
  1494. for (; i < length; i++) {
  1495. candidate = items[i];
  1496. if (candidate.getItemId() === id) {
  1497. result.push(candidate);
  1498. }
  1499. }
  1500. return result;
  1501. },
  1502. // Filters the passed candidate array and returns only items which the named pseudo class matcher filters in
  1503. filterByPseudo = function(items, name, value) {
  1504. return cq.pseudos[name](items, value);
  1505. },
  1506. // Determines leading mode
  1507. // > for direct child, and ^ to switch to ownerCt axis
  1508. modeRe = /^(\s?([>\^])\s?|\s|$)/,
  1509. // Matches a token with possibly (true|false) appended for the "shallow" parameter
  1510. tokenRe = /^(#)?([\w\-]+|\*)(?:\((true|false)\))?/,
  1511. matchers = [{
  1512. // Checks for .xtype with possibly (true|false) appended for the "shallow" parameter
  1513. re: /^\.([\w\-]+)(?:\((true|false)\))?/,
  1514. method: filterByXType
  1515. },{
  1516. // checks for [attribute=value]
  1517. re: /^(?:[\[](?:@)?([\w\-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]])/,
  1518. method: filterByAttribute
  1519. }, {
  1520. // checks for #cmpItemId
  1521. re: /^#([\w\-]+)/,
  1522. method: filterById
  1523. }, {
  1524. // checks for :<pseudo_class>(<selector>)
  1525. re: /^\:([\w\-]+)(?:\(((?:\{[^\}]+\})|(?:(?!\{)[^\s>\/]*?(?!\})))\))?/,
  1526. method: filterByPseudo
  1527. }, {
  1528. // checks for {<member_expression>}
  1529. re: /^(?:\{([^\}]+)\})/,
  1530. method: filterFnPattern
  1531. }];
  1532. // @class Ext.ComponentQuery.Query
  1533. // This internal class is completely hidden in documentation.
  1534. cq.Query = Ext.extend(Object, {
  1535. constructor: function(cfg) {
  1536. cfg = cfg || {};
  1537. Ext.apply(this, cfg);
  1538. },
  1539. // Executes this Query upon the selected root.
  1540. // The root provides the initial source of candidate Component matches which are progressively
  1541. // filtered by iterating through this Query's operations cache.
  1542. // If no root is provided, all registered Components are searched via the ComponentManager.
  1543. // root may be a Container who's descendant Components are filtered
  1544. // root may be a Component with an implementation of getRefItems which provides some nested Components such as the
  1545. // docked items within a Panel.
  1546. // root may be an array of candidate Components to filter using this Query.
  1547. execute : function(root) {
  1548. var operations = this.operations,
  1549. i = 0,
  1550. length = operations.length,
  1551. operation,
  1552. workingItems;
  1553. // no root, use all Components in the document
  1554. if (!root) {
  1555. workingItems = Ext.ComponentManager.all.getArray();
  1556. }
  1557. // Root is a candidate Array
  1558. else if (Ext.isArray(root)) {
  1559. workingItems = root;
  1560. }
  1561. // We are going to loop over our operations and take care of them
  1562. // one by one.
  1563. for (; i < length; i++) {
  1564. operation = operations[i];
  1565. // The mode operation requires some custom handling.
  1566. // All other operations essentially filter down our current
  1567. // working items, while mode replaces our current working
  1568. // items by getting children from each one of our current
  1569. // working items. The type of mode determines the type of
  1570. // children we get. (e.g. > only gets direct children)
  1571. if (operation.mode === '^') {
  1572. workingItems = getAncestors(workingItems || [root]);
  1573. }
  1574. else if (operation.mode) {
  1575. workingItems = getItems(workingItems || [root], operation.mode);
  1576. }
  1577. else {
  1578. workingItems = filterItems(workingItems || getItems([root]), operation);
  1579. }
  1580. // If this is the last operation, it means our current working
  1581. // items are the final matched items. Thus return them!
  1582. if (i === length -1) {
  1583. return workingItems;
  1584. }
  1585. }
  1586. return [];
  1587. },
  1588. is: function(component) {
  1589. var operations = this.operations,
  1590. components = Ext.isArray(component) ? component : [component],
  1591. originalLength = components.length,
  1592. lastOperation = operations[operations.length-1],
  1593. ln, i;
  1594. components = filterItems(components, lastOperation);
  1595. if (components.length === originalLength) {
  1596. if (operations.length > 1) {
  1597. for (i = 0, ln = components.length; i < ln; i++) {
  1598. if (Ext.Array.indexOf(this.execute(), components[i]) === -1) {
  1599. return false;
  1600. }
  1601. }
  1602. }
  1603. return true;
  1604. }
  1605. return false;
  1606. }
  1607. });
  1608. Ext.apply(this, {
  1609. // private cache of selectors and matching ComponentQuery.Query objects
  1610. cache: {},
  1611. // private cache of pseudo class filter functions
  1612. pseudos: {
  1613. not: function(components, selector){
  1614. var CQ = Ext.ComponentQuery,
  1615. i = 0,
  1616. length = components.length,
  1617. results = [],
  1618. index = -1,
  1619. component;
  1620. for(; i < length; ++i) {
  1621. component = components[i];
  1622. if (!CQ.is(component, selector)) {
  1623. results[++index] = component;
  1624. }
  1625. }
  1626. return results;
  1627. },
  1628. last: function(components) {
  1629. return components[components.length - 1];
  1630. }
  1631. },
  1632. /**
  1633. * Returns an array of matched Components from within the passed root object.
  1634. *
  1635. * This method filters returned Components in a similar way to how CSS selector based DOM
  1636. * queries work using a textual selector string.
  1637. *
  1638. * See class summary for details.
  1639. *
  1640. * @param {String} selector The selector string to filter returned Components
  1641. * @param {Ext.container.Container} root The Container within which to perform the query.
  1642. * If omitted, all Components within the document are included in the search.
  1643. *
  1644. * This parameter may also be an array of Components to filter according to the selector.</p>
  1645. * @returns {Ext.Component[]} The matched Components.
  1646. *
  1647. * @member Ext.ComponentQuery
  1648. */
  1649. query: function(selector, root) {
  1650. var selectors = selector.split(','),
  1651. length = selectors.length,
  1652. i = 0,
  1653. results = [],
  1654. noDupResults = [],
  1655. dupMatcher = {},
  1656. query, resultsLn, cmp;
  1657. for (; i < length; i++) {
  1658. selector = Ext.String.trim(selectors[i]);
  1659. query = this.cache[selector];
  1660. if (!query) {
  1661. this.cache[selector] = query = this.parse(selector);
  1662. }
  1663. results = results.concat(query.execute(root));
  1664. }
  1665. // multiple selectors, potential to find duplicates
  1666. // lets filter them out.
  1667. if (length > 1) {
  1668. resultsLn = results.length;
  1669. for (i = 0; i < resultsLn; i++) {
  1670. cmp = results[i];
  1671. if (!dupMatcher[cmp.id]) {
  1672. noDupResults.push(cmp);
  1673. dupMatcher[cmp.id] = true;
  1674. }
  1675. }
  1676. results = noDupResults;
  1677. }
  1678. return results;
  1679. },
  1680. /**
  1681. * Tests whether the passed Component matches the selector string.
  1682. * @param {Ext.Component} component The Component to test
  1683. * @param {String} selector The selector string to test against.
  1684. * @return {Boolean} True if the Component matches the selector.
  1685. * @member Ext.ComponentQuery
  1686. */
  1687. is: function(component, selector) {
  1688. if (!selector) {
  1689. return true;
  1690. }
  1691. var query = this.cache[selector];
  1692. if (!query) {
  1693. this.cache[selector] = query = this.parse(selector);
  1694. }
  1695. return query.is(component);
  1696. },
  1697. parse: function(selector) {
  1698. var operations = [],
  1699. length = matchers.length,
  1700. lastSelector,
  1701. tokenMatch,
  1702. matchedChar,
  1703. modeMatch,
  1704. selectorMatch,
  1705. i, matcher, method;
  1706. // We are going to parse the beginning of the selector over and
  1707. // over again, slicing off the selector any portions we converted into an
  1708. // operation, until it is an empty string.
  1709. while (selector && lastSelector !== selector) {
  1710. lastSelector = selector;
  1711. // First we check if we are dealing with a token like #, * or an xtype
  1712. tokenMatch = selector.match(tokenRe);
  1713. if (tokenMatch) {
  1714. matchedChar = tokenMatch[1];
  1715. // If the token is prefixed with a # we push a filterById operation to our stack
  1716. if (matchedChar === '#') {
  1717. operations.push({
  1718. method: filterById,
  1719. args: [Ext.String.trim(tokenMatch[2])]
  1720. });
  1721. }
  1722. // If the token is prefixed with a . we push a filterByClassName operation to our stack
  1723. // FIXME: Not enabled yet. just needs \. adding to the tokenRe prefix
  1724. else if (matchedChar === '.') {
  1725. operations.push({
  1726. method: filterByClassName,
  1727. args: [Ext.String.trim(tokenMatch[2])]
  1728. });
  1729. }
  1730. // If the token is a * or an xtype string, we push a filterByXType
  1731. // operation to the stack.
  1732. else {
  1733. operations.push({
  1734. method: filterByXType,
  1735. args: [Ext.String.trim(tokenMatch[2]), Boolean(tokenMatch[3])]
  1736. });
  1737. }
  1738. // Now we slice of the part we just converted into an operation
  1739. selector = selector.replace(tokenMatch[0], '');
  1740. }
  1741. // If the next part of the query is not a space or > or ^, it means we
  1742. // are going to check for more things that our current selection
  1743. // has to comply to.
  1744. while (!(modeMatch = selector.match(modeRe))) {
  1745. // Lets loop over each type of matcher and execute it
  1746. // on our current selector.
  1747. for (i = 0; selector && i < length; i++) {
  1748. matcher = matchers[i];
  1749. selectorMatch = selector.match(matcher.re);
  1750. method = matcher.method;
  1751. // If we have a match, add an operation with the method
  1752. // associated with this matcher, and pass the regular
  1753. // expression matches are arguments to the operation.
  1754. if (selectorMatch) {
  1755. operations.push({
  1756. method: Ext.isString(matcher.method)
  1757. // Turn a string method into a function by formatting the string with our selector matche expression
  1758. // A new method is created for different match expressions, eg {id=='textfield-1024'}
  1759. // Every expression may be different in different selectors.
  1760. ? Ext.functionFactory('items', Ext.String.format.apply(Ext.String, [method].concat(selectorMatch.slice(1))))
  1761. : matcher.method,
  1762. args: selectorMatch.slice(1)
  1763. });
  1764. selector = selector.replace(selectorMatch[0], '');
  1765. break; // Break on match
  1766. }
  1767. //<debug>
  1768. // Exhausted all matches: It's an error
  1769. if (i === (length - 1)) {
  1770. Ext.Error.raise('Invalid ComponentQuery selector: "' + arguments[0] + '"');
  1771. }
  1772. //</debug>
  1773. }
  1774. }
  1775. // Now we are going to check for a mode change. This means a space
  1776. // or a > to determine if we are going to select all the children
  1777. // of the currently matched items, or a ^ if we are going to use the
  1778. // ownerCt axis as the candidate source.
  1779. if (modeMatch[1]) { // Assignment, and test for truthiness!
  1780. operations.push({
  1781. mode: modeMatch[2]||modeMatch[1]
  1782. });
  1783. selector = selector.replace(modeMatch[0], '');
  1784. }
  1785. }
  1786. // Now that we have all our operations in an array, we are going
  1787. // to create a new Query using these operations.
  1788. return new cq.Query({
  1789. operations: operations
  1790. });
  1791. }
  1792. });
  1793. });
  1794. /**
  1795. * @class Ext.util.HashMap
  1796. * <p>
  1797. * Represents a collection of a set of key and value pairs. Each key in the HashMap
  1798. * must be unique, the same key cannot exist twice. Access to items is provided via
  1799. * the key only. Sample usage:
  1800. * <pre><code>
  1801. var map = new Ext.util.HashMap();
  1802. map.add('key1', 1);
  1803. map.add('key2', 2);
  1804. map.add('key3', 3);
  1805. map.each(function(key, value, length){
  1806. console.log(key, value, length);
  1807. });
  1808. * </code></pre>
  1809. * </p>
  1810. *
  1811. * <p>The HashMap is an unordered class,
  1812. * there is no guarantee when iterating over the items that they will be in any particular
  1813. * order. If this is required, then use a {@link Ext.util.MixedCollection}.
  1814. * </p>
  1815. */
  1816. Ext.define('Ext.util.HashMap', {
  1817. mixins: {
  1818. observable: 'Ext.util.Observable'
  1819. },
  1820. /**
  1821. * @cfg {Function} keyFn A function that is used to retrieve a default key for a passed object.
  1822. * A default is provided that returns the <b>id</b> property on the object. This function is only used
  1823. * if the add method is called with a single argument.
  1824. */
  1825. /**
  1826. * Creates new HashMap.
  1827. * @param {Object} config (optional) Config object.
  1828. */
  1829. constructor: function(config) {
  1830. config = config || {};
  1831. var me = this,
  1832. keyFn = config.keyFn;
  1833. me.addEvents(
  1834. /**
  1835. * @event add
  1836. * Fires when a new item is added to the hash
  1837. * @param {Ext.util.HashMap} this.
  1838. * @param {String} key The key of the added item.
  1839. * @param {Object} value The value of the added item.
  1840. */
  1841. 'add',
  1842. /**
  1843. * @event clear
  1844. * Fires when the hash is cleared.
  1845. * @param {Ext.util.HashMap} this.
  1846. */
  1847. 'clear',
  1848. /**
  1849. * @event remove
  1850. * Fires when an item is removed from the hash.
  1851. * @param {Ext.util.HashMap} this.
  1852. * @param {String} key The key of the removed item.
  1853. * @param {Object} value The value of the removed item.
  1854. */
  1855. 'remove',
  1856. /**
  1857. * @event replace
  1858. * Fires when an item is replaced in the hash.
  1859. * @param {Ext.util.HashMap} this.
  1860. * @param {String} key The key of the replaced item.
  1861. * @param {Object} value The new value for the item.
  1862. * @param {Object} old The old value for the item.
  1863. */
  1864. 'replace'
  1865. );
  1866. me.mixins.observable.constructor.call(me, config);
  1867. me.clear(true);
  1868. if (keyFn) {
  1869. me.getKey = keyFn;
  1870. }
  1871. },
  1872. /**
  1873. * Gets the number of items in the hash.
  1874. * @return {Number} The number of items in the hash.
  1875. */
  1876. getCount: function() {
  1877. return this.length;
  1878. },
  1879. /**
  1880. * Implementation for being able to extract the key from an object if only
  1881. * a single argument is passed.
  1882. * @private
  1883. * @param {String} key The key
  1884. * @param {Object} value The value
  1885. * @return {Array} [key, value]
  1886. */
  1887. getData: function(key, value) {
  1888. // if we have no value, it means we need to get the key from the object
  1889. if (value === undefined) {
  1890. value = key;
  1891. key = this.getKey(value);
  1892. }
  1893. return [key, value];
  1894. },
  1895. /**
  1896. * Extracts the key from an object. This is a default implementation, it may be overridden
  1897. * @param {Object} o The object to get the key from
  1898. * @return {String} The key to use.
  1899. */
  1900. getKey: function(o) {
  1901. return o.id;
  1902. },
  1903. /**
  1904. * Adds an item to the collection. Fires the {@link #add} event when complete.
  1905. * @param {String} key <p>The key to associate with the item, or the new item.</p>
  1906. * <p>If a {@link #getKey} implementation was specified for this HashMap,
  1907. * or if the key of the stored items is in a property called <tt><b>id</b></tt>,
  1908. * the HashMap will be able to <i>derive</i> the key for the new item.
  1909. * In this case just pass the new item in this parameter.</p>
  1910. * @param {Object} o The item to add.
  1911. * @return {Object} The item added.
  1912. */
  1913. add: function(key, value) {
  1914. var me = this,
  1915. data;
  1916. if (arguments.length === 1) {
  1917. value = key;
  1918. key = me.getKey(value);
  1919. }
  1920. if (me.containsKey(key)) {
  1921. return me.replace(key, value);
  1922. }
  1923. data = me.getData(key, value);
  1924. key = data[0];
  1925. value = data[1];
  1926. me.map[key] = value;
  1927. ++me.length;
  1928. me.fireEvent('add', me, key, value);
  1929. return value;
  1930. },
  1931. /**
  1932. * Replaces an item in the hash. If the key doesn't exist, the
  1933. * {@link #add} method will be used.
  1934. * @param {String} key The key of the item.
  1935. * @param {Object} value The new value for the item.
  1936. * @return {Object} The new value of the item.
  1937. */
  1938. replace: function(key, value) {
  1939. var me = this,
  1940. map = me.map,
  1941. old;
  1942. if (!me.containsKey(key)) {
  1943. me.add(key, value);
  1944. }
  1945. old = map[key];
  1946. map[key] = value;
  1947. me.fireEvent('replace', me, key, value, old);
  1948. return value;
  1949. },
  1950. /**
  1951. * Remove an item from the hash.
  1952. * @param {Object} o The value of the item to remove.
  1953. * @return {Boolean} True if the item was successfully removed.
  1954. */
  1955. remove: function(o) {
  1956. var key = this.findKey(o);
  1957. if (key !== undefined) {
  1958. return this.removeAtKey(key);
  1959. }
  1960. return false;
  1961. },
  1962. /**
  1963. * Remove an item from the hash.
  1964. * @param {String} key The key to remove.
  1965. * @return {Boolean} True if the item was successfully removed.
  1966. */
  1967. removeAtKey: function(key) {
  1968. var me = this,
  1969. value;
  1970. if (me.containsKey(key)) {
  1971. value = me.map[key];
  1972. delete me.map[key];
  1973. --me.length;
  1974. me.fireEvent('remove', me, key, value);
  1975. return true;
  1976. }
  1977. return false;
  1978. },
  1979. /**
  1980. * Retrieves an item with a particular key.
  1981. * @param {String} key The key to lookup.
  1982. * @return {Object} The value at that key. If it doesn't exist, <tt>undefined</tt> is returned.
  1983. */
  1984. get: function(key) {
  1985. return this.map[key];
  1986. },
  1987. /**
  1988. * Removes all items from the hash.
  1989. * @return {Ext.util.HashMap} this
  1990. */
  1991. clear: function(/* private */ initial) {
  1992. var me = this;
  1993. me.map = {};
  1994. me.length = 0;
  1995. if (initial !== true) {
  1996. me.fireEvent('clear', me);
  1997. }
  1998. return me;
  1999. },
  2000. /**
  2001. * Checks whether a key exists in the hash.
  2002. * @param {String} key The key to check for.
  2003. * @return {Boolean} True if they key exists in the hash.
  2004. */
  2005. containsKey: function(key) {
  2006. return this.map[key] !== undefined;
  2007. },
  2008. /**
  2009. * Checks whether a value exists in the hash.
  2010. * @param {Object} value The value to check for.
  2011. * @return {Boolean} True if the value exists in the dictionary.
  2012. */
  2013. contains: function(value) {
  2014. return this.containsKey(this.findKey(value));
  2015. },
  2016. /**
  2017. * Return all of the keys in the hash.
  2018. * @return {Array} An array of keys.
  2019. */
  2020. getKeys: function() {
  2021. return this.getArray(true);
  2022. },
  2023. /**
  2024. * Return all of the values in the hash.
  2025. * @return {Array} An array of values.
  2026. */
  2027. getValues: function() {
  2028. return this.getArray(false);
  2029. },
  2030. /**
  2031. * Gets either the keys/values in an array from the hash.
  2032. * @private
  2033. * @param {Boolean} isKey True to extract the keys, otherwise, the value
  2034. * @return {Array} An array of either keys/values from the hash.
  2035. */
  2036. getArray: function(isKey) {
  2037. var arr = [],
  2038. key,
  2039. map = this.map;
  2040. for (key in map) {
  2041. if (map.hasOwnProperty(key)) {
  2042. arr.push(isKey ? key: map[key]);
  2043. }
  2044. }
  2045. return arr;
  2046. },
  2047. /**
  2048. * Executes the specified function once for each item in the hash.
  2049. * Returning false from the function will cease iteration.
  2050. *
  2051. * The paramaters passed to the function are:
  2052. * <div class="mdetail-params"><ul>
  2053. * <li><b>key</b> : String<p class="sub-desc">The key of the item</p></li>
  2054. * <li><b>value</b> : Number<p class="sub-desc">The value of the item</p></li>
  2055. * <li><b>length</b> : Number<p class="sub-desc">The total number of items in the hash</p></li>
  2056. * </ul></div>
  2057. * @param {Function} fn The function to execute.
  2058. * @param {Object} scope The scope to execute in. Defaults to <tt>this</tt>.
  2059. * @return {Ext.util.HashMap} this
  2060. */
  2061. each: function(fn, scope) {
  2062. // copy items so they may be removed during iteration.
  2063. var items = Ext.apply({}, this.map),
  2064. key,
  2065. length = this.length;
  2066. scope = scope || this;
  2067. for (key in items) {
  2068. if (items.hasOwnProperty(key)) {
  2069. if (fn.call(scope, key, items[key], length) === false) {
  2070. break;
  2071. }
  2072. }
  2073. }
  2074. return this;
  2075. },
  2076. /**
  2077. * Performs a shallow copy on this hash.
  2078. * @return {Ext.util.HashMap} The new hash object.
  2079. */
  2080. clone: function() {
  2081. var hash = new this.self(),
  2082. map = this.map,
  2083. key;
  2084. hash.suspendEvents();
  2085. for (key in map) {
  2086. if (map.hasOwnProperty(key)) {
  2087. hash.add(key, map[key]);
  2088. }
  2089. }
  2090. hash.resumeEvents();
  2091. return hash;
  2092. },
  2093. /**
  2094. * @private
  2095. * Find the key for a value.
  2096. * @param {Object} value The value to find.
  2097. * @return {Object} The value of the item. Returns <tt>undefined</tt> if not found.
  2098. */
  2099. findKey: function(value) {
  2100. var key,
  2101. map = this.map;
  2102. for (key in map) {
  2103. if (map.hasOwnProperty(key) && map[key] === value) {
  2104. return key;
  2105. }
  2106. }
  2107. return undefined;
  2108. }
  2109. });
  2110. /**
  2111. * @class Ext.state.Manager
  2112. * This is the global state manager. By default all components that are "state aware" check this class
  2113. * for state information if you don't pass them a custom state provider. In order for this class
  2114. * to be useful, it must be initialized with a provider when your application initializes. Example usage:
  2115. <pre><code>
  2116. // in your initialization function
  2117. init : function(){
  2118. Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
  2119. var win = new Window(...);
  2120. win.restoreState();
  2121. }
  2122. </code></pre>
  2123. * This class passes on calls from components to the underlying {@link Ext.state.Provider} so that
  2124. * there is a common interface that can be used without needing to refer to a specific provider instance
  2125. * in every component.
  2126. * @singleton
  2127. * @docauthor Evan Trimboli <evan@sencha.com>
  2128. */
  2129. Ext.define('Ext.state.Manager', {
  2130. singleton: true,
  2131. requires: ['Ext.state.Provider'],
  2132. constructor: function() {
  2133. this.provider = Ext.create('Ext.state.Provider');
  2134. },
  2135. /**
  2136. * Configures the default state provider for your application
  2137. * @param {Ext.state.Provider} stateProvider The state provider to set
  2138. */
  2139. setProvider : function(stateProvider){
  2140. this.provider = stateProvider;
  2141. },
  2142. /**
  2143. * Returns the current value for a key
  2144. * @param {String} name The key name
  2145. * @param {Object} defaultValue The default value to return if the key lookup does not match
  2146. * @return {Object} The state data
  2147. */
  2148. get : function(key, defaultValue){
  2149. return this.provider.get(key, defaultValue);
  2150. },
  2151. /**
  2152. * Sets the value for a key
  2153. * @param {String} name The key name
  2154. * @param {Object} value The state data
  2155. */
  2156. set : function(key, value){
  2157. this.provider.set(key, value);
  2158. },
  2159. /**
  2160. * Clears a value from the state
  2161. * @param {String} name The key name
  2162. */
  2163. clear : function(key){
  2164. this.provider.clear(key);
  2165. },
  2166. /**
  2167. * Gets the currently configured state provider
  2168. * @return {Ext.state.Provider} The state provider
  2169. */
  2170. getProvider : function(){
  2171. return this.provider;
  2172. }
  2173. });
  2174. /**
  2175. * @class Ext.state.Stateful
  2176. * A mixin for being able to save the state of an object to an underlying
  2177. * {@link Ext.state.Provider}.
  2178. */
  2179. Ext.define('Ext.state.Stateful', {
  2180. /* Begin Definitions */
  2181. mixins: {
  2182. observable: 'Ext.util.Observable'
  2183. },
  2184. requires: ['Ext.state.Manager'],
  2185. /* End Definitions */
  2186. /**
  2187. * @cfg {Boolean} stateful
  2188. * <p>A flag which causes the object to attempt to restore the state of
  2189. * internal properties from a saved state on startup. The object must have
  2190. * a <code>{@link #stateId}</code> for state to be managed.
  2191. * Auto-generated ids are not guaranteed to be stable across page loads and
  2192. * cannot be relied upon to save and restore the same state for a object.<p>
  2193. * <p>For state saving to work, the state manager's provider must have been
  2194. * set to an implementation of {@link Ext.state.Provider} which overrides the
  2195. * {@link Ext.state.Provider#set set} and {@link Ext.state.Provider#get get}
  2196. * methods to save and recall name/value pairs. A built-in implementation,
  2197. * {@link Ext.state.CookieProvider} is available.</p>
  2198. * <p>To set the state provider for the current page:</p>
  2199. * <pre><code>
  2200. Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
  2201. expires: new Date(new Date().getTime()+(1000*60*60*24*7)), //7 days from now
  2202. }));
  2203. * </code></pre>
  2204. * <p>A stateful object attempts to save state when one of the events
  2205. * listed in the <code>{@link #stateEvents}</code> configuration fires.</p>
  2206. * <p>To save state, a stateful object first serializes its state by
  2207. * calling <b><code>{@link #getState}</code></b>. By default, this function does
  2208. * nothing. The developer must provide an implementation which returns an
  2209. * object hash which represents the restorable state of the object.</p>
  2210. * <p>The value yielded by getState is passed to {@link Ext.state.Manager#set}
  2211. * which uses the configured {@link Ext.state.Provider} to save the object
  2212. * keyed by the <code>{@link #stateId}</code>.</p>
  2213. * <p>During construction, a stateful object attempts to <i>restore</i>
  2214. * its state by calling {@link Ext.state.Manager#get} passing the
  2215. * <code>{@link #stateId}</code></p>
  2216. * <p>The resulting object is passed to <b><code>{@link #applyState}</code></b>.
  2217. * The default implementation of <code>{@link #applyState}</code> simply copies
  2218. * properties into the object, but a developer may override this to support
  2219. * more behaviour.</p>
  2220. * <p>You can perform extra processing on state save and restore by attaching
  2221. * handlers to the {@link #beforestaterestore}, {@link #staterestore},
  2222. * {@link #beforestatesave} and {@link #statesave} events.</p>
  2223. */
  2224. stateful: true,
  2225. /**
  2226. * @cfg {String} stateId
  2227. * The unique id for this object to use for state management purposes.
  2228. * <p>See {@link #stateful} for an explanation of saving and restoring state.</p>
  2229. */
  2230. /**
  2231. * @cfg {String[]} stateEvents
  2232. * <p>An array of events that, when fired, should trigger this object to
  2233. * save its state. Defaults to none. <code>stateEvents</code> may be any type
  2234. * of event supported by this object, including browser or custom events
  2235. * (e.g., <tt>['click', 'customerchange']</tt>).</p>
  2236. * <p>See <code>{@link #stateful}</code> for an explanation of saving and
  2237. * restoring object state.</p>
  2238. */
  2239. /**
  2240. * @cfg {Number} saveDelay
  2241. * A buffer to be applied if many state events are fired within a short period.
  2242. */
  2243. saveDelay: 100,
  2244. autoGenIdRe: /^((\w+-)|(ext-comp-))\d{4,}$/i,
  2245. constructor: function(config) {
  2246. var me = this;
  2247. config = config || {};
  2248. if (Ext.isDefined(config.stateful)) {
  2249. me.stateful = config.stateful;
  2250. }
  2251. if (Ext.isDefined(config.saveDelay)) {
  2252. me.saveDelay = config.saveDelay;
  2253. }
  2254. me.stateId = me.stateId || config.stateId;
  2255. if (!me.stateEvents) {
  2256. me.stateEvents = [];
  2257. }
  2258. if (config.stateEvents) {
  2259. me.stateEvents.concat(config.stateEvents);
  2260. }
  2261. this.addEvents(
  2262. /**
  2263. * @event beforestaterestore
  2264. * Fires before the state of the object is restored. Return false from an event handler to stop the restore.
  2265. * @param {Ext.state.Stateful} this
  2266. * @param {Object} state The hash of state values returned from the StateProvider. If this
  2267. * event is not vetoed, then the state object is passed to <b><tt>applyState</tt></b>. By default,
  2268. * that simply copies property values into this object. The method maybe overriden to
  2269. * provide custom state restoration.
  2270. */
  2271. 'beforestaterestore',
  2272. /**
  2273. * @event staterestore
  2274. * Fires after the state of the object is restored.
  2275. * @param {Ext.state.Stateful} this
  2276. * @param {Object} state The hash of state values returned from the StateProvider. This is passed
  2277. * to <b><tt>applyState</tt></b>. By default, that simply copies property values into this
  2278. * object. The method maybe overriden to provide custom state restoration.
  2279. */
  2280. 'staterestore',
  2281. /**
  2282. * @event beforestatesave
  2283. * Fires before the state of the object is saved to the configured state provider. Return false to stop the save.
  2284. * @param {Ext.state.Stateful} this
  2285. * @param {Object} state The hash of state values. This is determined by calling
  2286. * <b><tt>getState()</tt></b> on the object. This method must be provided by the
  2287. * developer to return whetever representation of state is required, by default, Ext.state.Stateful
  2288. * has a null implementation.
  2289. */
  2290. 'beforestatesave',
  2291. /**
  2292. * @event statesave
  2293. * Fires after the state of the object is saved to the configured state provider.
  2294. * @param {Ext.state.Stateful} this
  2295. * @param {Object} state The hash of state values. This is determined by calling
  2296. * <b><tt>getState()</tt></b> on the object. This method must be provided by the
  2297. * developer to return whetever representation of state is required, by default, Ext.state.Stateful
  2298. * has a null implementation.
  2299. */
  2300. 'statesave'
  2301. );
  2302. me.mixins.observable.constructor.call(me);
  2303. if (me.stateful !== false) {
  2304. me.initStateEvents();
  2305. me.initState();
  2306. }
  2307. },
  2308. /**
  2309. * Initializes any state events for this object.
  2310. * @private
  2311. */
  2312. initStateEvents: function() {
  2313. this.addStateEvents(this.stateEvents);
  2314. },
  2315. /**
  2316. * Add events that will trigger the state to be saved.
  2317. * @param {String/String[]} events The event name or an array of event names.
  2318. */
  2319. addStateEvents: function(events){
  2320. if (!Ext.isArray(events)) {
  2321. events = [events];
  2322. }
  2323. var me = this,
  2324. i = 0,
  2325. len = events.length;
  2326. for (; i < len; ++i) {
  2327. me.on(events[i], me.onStateChange, me);
  2328. }
  2329. },
  2330. /**
  2331. * This method is called when any of the {@link #stateEvents} are fired.
  2332. * @private
  2333. */
  2334. onStateChange: function(){
  2335. var me = this,
  2336. delay = me.saveDelay;
  2337. if (delay > 0) {
  2338. if (!me.stateTask) {
  2339. me.stateTask = Ext.create('Ext.util.DelayedTask', me.saveState, me);
  2340. }
  2341. me.stateTask.delay(me.saveDelay);
  2342. } else {
  2343. me.saveState();
  2344. }
  2345. },
  2346. /**
  2347. * Saves the state of the object to the persistence store.
  2348. * @private
  2349. */
  2350. saveState: function() {
  2351. var me = this,
  2352. id,
  2353. state;
  2354. if (me.stateful !== false) {
  2355. id = me.getStateId();
  2356. if (id) {
  2357. state = me.getState();
  2358. if (me.fireEvent('beforestatesave', me, state) !== false) {
  2359. Ext.state.Manager.set(id, state);
  2360. me.fireEvent('statesave', me, state);
  2361. }
  2362. }
  2363. }
  2364. },
  2365. /**
  2366. * Gets the current state of the object. By default this function returns null,
  2367. * it should be overridden in subclasses to implement methods for getting the state.
  2368. * @return {Object} The current state
  2369. */
  2370. getState: function(){
  2371. return null;
  2372. },
  2373. /**
  2374. * Applies the state to the object. This should be overridden in subclasses to do
  2375. * more complex state operations. By default it applies the state properties onto
  2376. * the current object.
  2377. * @param {Object} state The state
  2378. */
  2379. applyState: function(state) {
  2380. if (state) {
  2381. Ext.apply(this, state);
  2382. }
  2383. },
  2384. /**
  2385. * Gets the state id for this object.
  2386. * @return {String} The state id, null if not found.
  2387. */
  2388. getStateId: function() {
  2389. var me = this,
  2390. id = me.stateId;
  2391. if (!id) {
  2392. id = me.autoGenIdRe.test(String(me.id)) ? null : me.id;
  2393. }
  2394. return id;
  2395. },
  2396. /**
  2397. * Initializes the state of the object upon construction.
  2398. * @private
  2399. */
  2400. initState: function(){
  2401. var me = this,
  2402. id = me.getStateId(),
  2403. state;
  2404. if (me.stateful !== false) {
  2405. if (id) {
  2406. state = Ext.state.Manager.get(id);
  2407. if (state) {
  2408. state = Ext.apply({}, state);
  2409. if (me.fireEvent('beforestaterestore', me, state) !== false) {
  2410. me.applyState(state);
  2411. me.fireEvent('staterestore', me, state);
  2412. }
  2413. }
  2414. }
  2415. }
  2416. },
  2417. /**
  2418. * Conditionally saves a single property from this object to the given state object.
  2419. * The idea is to only save state which has changed from the initial state so that
  2420. * current software settings do not override future software settings. Only those
  2421. * values that are user-changed state should be saved.
  2422. *
  2423. * @param {String} propName The name of the property to save.
  2424. * @param {Object} state The state object in to which to save the property.
  2425. * @param {String} stateName (optional) The name to use for the property in state.
  2426. * @return {Boolean} True if the property was saved, false if not.
  2427. */
  2428. savePropToState: function (propName, state, stateName) {
  2429. var me = this,
  2430. value = me[propName],
  2431. config = me.initialConfig;
  2432. if (me.hasOwnProperty(propName)) {
  2433. if (!config || config[propName] !== value) {
  2434. if (state) {
  2435. state[stateName || propName] = value;
  2436. }
  2437. return true;
  2438. }
  2439. }
  2440. return false;
  2441. },
  2442. savePropsToState: function (propNames, state) {
  2443. var me = this;
  2444. Ext.each(propNames, function (propName) {
  2445. me.savePropToState(propName, state);
  2446. });
  2447. return state;
  2448. },
  2449. /**
  2450. * Destroys this stateful object.
  2451. */
  2452. destroy: function(){
  2453. var task = this.stateTask;
  2454. if (task) {
  2455. task.cancel();
  2456. }
  2457. this.clearListeners();
  2458. }
  2459. });
  2460. /**
  2461. * Base Manager class
  2462. */
  2463. Ext.define('Ext.AbstractManager', {
  2464. /* Begin Definitions */
  2465. requires: ['Ext.util.HashMap'],
  2466. /* End Definitions */
  2467. typeName: 'type',
  2468. constructor: function(config) {
  2469. Ext.apply(this, config || {});
  2470. /**
  2471. * @property {Ext.util.HashMap} all
  2472. * Contains all of the items currently managed
  2473. */
  2474. this.all = Ext.create('Ext.util.HashMap');
  2475. this.types = {};
  2476. },
  2477. /**
  2478. * Returns an item by id.
  2479. * For additional details see {@link Ext.util.HashMap#get}.
  2480. * @param {String} id The id of the item
  2481. * @return {Object} The item, undefined if not found.
  2482. */
  2483. get : function(id) {
  2484. return this.all.get(id);
  2485. },
  2486. /**
  2487. * Registers an item to be managed
  2488. * @param {Object} item The item to register
  2489. */
  2490. register: function(item) {
  2491. //<debug>
  2492. var all = this.all,
  2493. key = all.getKey(item);
  2494. if (all.containsKey(key)) {
  2495. Ext.Error.raise('Registering duplicate id "' + key + '" with this manager');
  2496. }
  2497. //</debug>
  2498. this.all.add(item);
  2499. },
  2500. /**
  2501. * Unregisters an item by removing it from this manager
  2502. * @param {Object} item The item to unregister
  2503. */
  2504. unregister: function(item) {
  2505. this.all.remove(item);
  2506. },
  2507. /**
  2508. * Registers a new item constructor, keyed by a type key.
  2509. * @param {String} type The mnemonic string by which the class may be looked up.
  2510. * @param {Function} cls The new instance class.
  2511. */
  2512. registerType : function(type, cls) {
  2513. this.types[type] = cls;
  2514. cls[this.typeName] = type;
  2515. },
  2516. /**
  2517. * Checks if an item type is registered.
  2518. * @param {String} type The mnemonic string by which the class may be looked up
  2519. * @return {Boolean} Whether the type is registered.
  2520. */
  2521. isRegistered : function(type){
  2522. return this.types[type] !== undefined;
  2523. },
  2524. /**
  2525. * Creates and returns an instance of whatever this manager manages, based on the supplied type and
  2526. * config object.
  2527. * @param {Object} config The config object
  2528. * @param {String} defaultType If no type is discovered in the config object, we fall back to this type
  2529. * @return {Object} The instance of whatever this manager is managing
  2530. */
  2531. create: function(config, defaultType) {
  2532. var type = config[this.typeName] || config.type || defaultType,
  2533. Constructor = this.types[type];
  2534. //<debug>
  2535. if (Constructor === undefined) {
  2536. Ext.Error.raise("The '" + type + "' type has not been registered with this manager");
  2537. }
  2538. //</debug>
  2539. return new Constructor(config);
  2540. },
  2541. /**
  2542. * Registers a function that will be called when an item with the specified id is added to the manager.
  2543. * This will happen on instantiation.
  2544. * @param {String} id The item id
  2545. * @param {Function} fn The callback function. Called with a single parameter, the item.
  2546. * @param {Object} scope The scope (this reference) in which the callback is executed.
  2547. * Defaults to the item.
  2548. */
  2549. onAvailable : function(id, fn, scope){
  2550. var all = this.all,
  2551. item;
  2552. if (all.containsKey(id)) {
  2553. item = all.get(id);
  2554. fn.call(scope || item, item);
  2555. } else {
  2556. all.on('add', function(map, key, item){
  2557. if (key == id) {
  2558. fn.call(scope || item, item);
  2559. all.un('add', fn, scope);
  2560. }
  2561. });
  2562. }
  2563. },
  2564. /**
  2565. * Executes the specified function once for each item in the collection.
  2566. * @param {Function} fn The function to execute.
  2567. * @param {String} fn.key The key of the item
  2568. * @param {Number} fn.value The value of the item
  2569. * @param {Number} fn.length The total number of items in the collection
  2570. * @param {Boolean} fn.return False to cease iteration.
  2571. * @param {Object} scope The scope to execute in. Defaults to `this`.
  2572. */
  2573. each: function(fn, scope){
  2574. this.all.each(fn, scope || this);
  2575. },
  2576. /**
  2577. * Gets the number of items in the collection.
  2578. * @return {Number} The number of items in the collection.
  2579. */
  2580. getCount: function(){
  2581. return this.all.getCount();
  2582. }
  2583. });
  2584. /**
  2585. * @class Ext.ComponentManager
  2586. * @extends Ext.AbstractManager
  2587. * <p>Provides a registry of all Components (instances of {@link Ext.Component} or any subclass
  2588. * thereof) on a page so that they can be easily accessed by {@link Ext.Component component}
  2589. * {@link Ext.Component#id id} (see {@link #get}, or the convenience method {@link Ext#getCmp Ext.getCmp}).</p>
  2590. * <p>This object also provides a registry of available Component <i>classes</i>
  2591. * indexed by a mnemonic code known as the Component's {@link Ext.Component#xtype xtype}.
  2592. * The <code>xtype</code> provides a way to avoid instantiating child Components
  2593. * when creating a full, nested config object for a complete Ext page.</p>
  2594. * <p>A child Component may be specified simply as a <i>config object</i>
  2595. * as long as the correct <code>{@link Ext.Component#xtype xtype}</code> is specified so that if and when the Component
  2596. * needs rendering, the correct type can be looked up for lazy instantiation.</p>
  2597. * <p>For a list of all available <code>{@link Ext.Component#xtype xtypes}</code>, see {@link Ext.Component}.</p>
  2598. * @singleton
  2599. */
  2600. Ext.define('Ext.ComponentManager', {
  2601. extend: 'Ext.AbstractManager',
  2602. alternateClassName: 'Ext.ComponentMgr',
  2603. singleton: true,
  2604. typeName: 'xtype',
  2605. /**
  2606. * Creates a new Component from the specified config object using the
  2607. * config object's xtype to determine the class to instantiate.
  2608. * @param {Object} config A configuration object for the Component you wish to create.
  2609. * @param {Function} defaultType (optional) The constructor to provide the default Component type if
  2610. * the config object does not contain a <code>xtype</code>. (Optional if the config contains a <code>xtype</code>).
  2611. * @return {Ext.Component} The newly instantiated Component.
  2612. */
  2613. create: function(component, defaultType){
  2614. if (component instanceof Ext.AbstractComponent) {
  2615. return component;
  2616. }
  2617. else if (Ext.isString(component)) {
  2618. return Ext.createByAlias('widget.' + component);
  2619. }
  2620. else {
  2621. var type = component.xtype || defaultType,
  2622. config = component;
  2623. return Ext.createByAlias('widget.' + type, config);
  2624. }
  2625. },
  2626. registerType: function(type, cls) {
  2627. this.types[type] = cls;
  2628. cls[this.typeName] = type;
  2629. cls.prototype[this.typeName] = type;
  2630. }
  2631. });
  2632. /**
  2633. * An abstract base class which provides shared methods for Components across the Sencha product line.
  2634. *
  2635. * Please refer to sub class's documentation
  2636. * @private
  2637. */
  2638. Ext.define('Ext.AbstractComponent', {
  2639. /* Begin Definitions */
  2640. requires: [
  2641. 'Ext.ComponentQuery',
  2642. 'Ext.ComponentManager'
  2643. ],
  2644. mixins: {
  2645. observable: 'Ext.util.Observable',
  2646. animate: 'Ext.util.Animate',
  2647. state: 'Ext.state.Stateful'
  2648. },
  2649. // The "uses" property specifies class which are used in an instantiated AbstractComponent.
  2650. // They do *not* have to be loaded before this class may be defined - that is what "requires" is for.
  2651. uses: [
  2652. 'Ext.PluginManager',
  2653. 'Ext.ComponentManager',
  2654. 'Ext.Element',
  2655. 'Ext.DomHelper',
  2656. 'Ext.XTemplate',
  2657. 'Ext.ComponentQuery',
  2658. 'Ext.ComponentLoader',
  2659. 'Ext.EventManager',
  2660. 'Ext.layout.Layout',
  2661. 'Ext.layout.component.Auto',
  2662. 'Ext.LoadMask',
  2663. 'Ext.ZIndexManager'
  2664. ],
  2665. statics: {
  2666. AUTO_ID: 1000
  2667. },
  2668. /* End Definitions */
  2669. isComponent: true,
  2670. getAutoId: function() {
  2671. return ++Ext.AbstractComponent.AUTO_ID;
  2672. },
  2673. /**
  2674. * @cfg {String} id
  2675. * The **unique id of this component instance.**
  2676. *
  2677. * It should not be necessary to use this configuration except for singleton objects in your application. Components
  2678. * created with an id may be accessed globally using {@link Ext#getCmp Ext.getCmp}.
  2679. *
  2680. * Instead of using assigned ids, use the {@link #itemId} config, and {@link Ext.ComponentQuery ComponentQuery}
  2681. * which provides selector-based searching for Sencha Components analogous to DOM querying. The {@link
  2682. * Ext.container.Container Container} class contains {@link Ext.container.Container#down shortcut methods} to query
  2683. * its descendant Components by selector.
  2684. *
  2685. * Note that this id will also be used as the element id for the containing HTML element that is rendered to the
  2686. * page for this component. This allows you to write id-based CSS rules to style the specific instance of this
  2687. * component uniquely, and also to select sub-elements using this component's id as the parent.
  2688. *
  2689. * **Note**: to avoid complications imposed by a unique id also see `{@link #itemId}`.
  2690. *
  2691. * **Note**: to access the container of a Component see `{@link #ownerCt}`.
  2692. *
  2693. * Defaults to an {@link #getId auto-assigned id}.
  2694. */
  2695. /**
  2696. * @cfg {String} itemId
  2697. * An itemId can be used as an alternative way to get a reference to a component when no object reference is
  2698. * available. Instead of using an `{@link #id}` with {@link Ext}.{@link Ext#getCmp getCmp}, use `itemId` with
  2699. * {@link Ext.container.Container}.{@link Ext.container.Container#getComponent getComponent} which will retrieve
  2700. * `itemId`'s or {@link #id}'s. Since `itemId`'s are an index to the container's internal MixedCollection, the
  2701. * `itemId` is scoped locally to the container -- avoiding potential conflicts with {@link Ext.ComponentManager}
  2702. * which requires a **unique** `{@link #id}`.
  2703. *
  2704. * var c = new Ext.panel.Panel({ //
  2705. * {@link Ext.Component#height height}: 300,
  2706. * {@link #renderTo}: document.body,
  2707. * {@link Ext.container.Container#layout layout}: 'auto',
  2708. * {@link Ext.container.Container#items items}: [
  2709. * {
  2710. * itemId: 'p1',
  2711. * {@link Ext.panel.Panel#title title}: 'Panel 1',
  2712. * {@link Ext.Component#height height}: 150
  2713. * },
  2714. * {
  2715. * itemId: 'p2',
  2716. * {@link Ext.panel.Panel#title title}: 'Panel 2',
  2717. * {@link Ext.Component#height height}: 150
  2718. * }
  2719. * ]
  2720. * })
  2721. * p1 = c.{@link Ext.container.Container#getComponent getComponent}('p1'); // not the same as {@link Ext#getCmp Ext.getCmp()}
  2722. * p2 = p1.{@link #ownerCt}.{@link Ext.container.Container#getComponent getComponent}('p2'); // reference via a sibling
  2723. *
  2724. * Also see {@link #id}, `{@link Ext.container.Container#query}`, `{@link Ext.container.Container#down}` and
  2725. * `{@link Ext.container.Container#child}`.
  2726. *
  2727. * **Note**: to access the container of an item see {@link #ownerCt}.
  2728. */
  2729. /**
  2730. * @property {Ext.Container} ownerCt
  2731. * This Component's owner {@link Ext.container.Container Container} (is set automatically
  2732. * when this Component is added to a Container). Read-only.
  2733. *
  2734. * **Note**: to access items within the Container see {@link #itemId}.
  2735. */
  2736. /**
  2737. * @property {Boolean} layoutManagedWidth
  2738. * @private
  2739. * Flag set by the container layout to which this Component is added.
  2740. * If the layout manages this Component's width, it sets the value to 1.
  2741. * If it does NOT manage the width, it sets it to 2.
  2742. * If the layout MAY affect the width, but only if the owning Container has a fixed width, this is set to 0.
  2743. */
  2744. /**
  2745. * @property {Boolean} layoutManagedHeight
  2746. * @private
  2747. * Flag set by the container layout to which this Component is added.
  2748. * If the layout manages this Component's height, it sets the value to 1.
  2749. * If it does NOT manage the height, it sets it to 2.
  2750. * If the layout MAY affect the height, but only if the owning Container has a fixed height, this is set to 0.
  2751. */
  2752. /**
  2753. * @cfg {String/Object} autoEl
  2754. * A tag name or {@link Ext.DomHelper DomHelper} spec used to create the {@link #getEl Element} which will
  2755. * encapsulate this Component.
  2756. *
  2757. * You do not normally need to specify this. For the base classes {@link Ext.Component} and
  2758. * {@link Ext.container.Container}, this defaults to **'div'**. The more complex Sencha classes use a more
  2759. * complex DOM structure specified by their own {@link #renderTpl}s.
  2760. *
  2761. * This is intended to allow the developer to create application-specific utility Components encapsulated by
  2762. * different DOM elements. Example usage:
  2763. *
  2764. * {
  2765. * xtype: 'component',
  2766. * autoEl: {
  2767. * tag: 'img',
  2768. * src: 'http://www.example.com/example.jpg'
  2769. * }
  2770. * }, {
  2771. * xtype: 'component',
  2772. * autoEl: {
  2773. * tag: 'blockquote',
  2774. * html: 'autoEl is cool!'
  2775. * }
  2776. * }, {
  2777. * xtype: 'container',
  2778. * autoEl: 'ul',
  2779. * cls: 'ux-unordered-list',
  2780. * items: {
  2781. * xtype: 'component',
  2782. * autoEl: 'li',
  2783. * html: 'First list item'
  2784. * }
  2785. * }
  2786. */
  2787. /**
  2788. * @cfg {Ext.XTemplate/String/String[]} renderTpl
  2789. * An {@link Ext.XTemplate XTemplate} used to create the internal structure inside this Component's encapsulating
  2790. * {@link #getEl Element}.
  2791. *
  2792. * You do not normally need to specify this. For the base classes {@link Ext.Component} and
  2793. * {@link Ext.container.Container}, this defaults to **`null`** which means that they will be initially rendered
  2794. * with no internal structure; they render their {@link #getEl Element} empty. The more specialized ExtJS and Touch
  2795. * classes which use a more complex DOM structure, provide their own template definitions.
  2796. *
  2797. * This is intended to allow the developer to create application-specific utility Components with customized
  2798. * internal structure.
  2799. *
  2800. * Upon rendering, any created child elements may be automatically imported into object properties using the
  2801. * {@link #renderSelectors} and {@link #childEls} options.
  2802. */
  2803. renderTpl: null,
  2804. /**
  2805. * @cfg {Object} renderData
  2806. *
  2807. * The data used by {@link #renderTpl} in addition to the following property values of the component:
  2808. *
  2809. * - id
  2810. * - ui
  2811. * - uiCls
  2812. * - baseCls
  2813. * - componentCls
  2814. * - frame
  2815. *
  2816. * See {@link #renderSelectors} and {@link #childEls} for usage examples.
  2817. */
  2818. /**
  2819. * @cfg {Object} renderSelectors
  2820. * An object containing properties specifying {@link Ext.DomQuery DomQuery} selectors which identify child elements
  2821. * created by the render process.
  2822. *
  2823. * After the Component's internal structure is rendered according to the {@link #renderTpl}, this object is iterated through,
  2824. * and the found Elements are added as properties to the Component using the `renderSelector` property name.
  2825. *
  2826. * For example, a Component which renderes a title and description into its element:
  2827. *
  2828. * Ext.create('Ext.Component', {
  2829. * renderTo: Ext.getBody(),
  2830. * renderTpl: [
  2831. * '<h1 class="title">{title}</h1>',
  2832. * '<p>{desc}</p>'
  2833. * ],
  2834. * renderData: {
  2835. * title: "Error",
  2836. * desc: "Something went wrong"
  2837. * },
  2838. * renderSelectors: {
  2839. * titleEl: 'h1.title',
  2840. * descEl: 'p'
  2841. * },
  2842. * listeners: {
  2843. * afterrender: function(cmp){
  2844. * // After rendering the component will have a titleEl and descEl properties
  2845. * cmp.titleEl.setStyle({color: "red"});
  2846. * }
  2847. * }
  2848. * });
  2849. *
  2850. * For a faster, but less flexible, alternative that achieves the same end result (properties for child elements on the
  2851. * Component after render), see {@link #childEls} and {@link #addChildEls}.
  2852. */
  2853. /**
  2854. * @cfg {Object[]} childEls
  2855. * An array describing the child elements of the Component. Each member of the array
  2856. * is an object with these properties:
  2857. *
  2858. * - `name` - The property name on the Component for the child element.
  2859. * - `itemId` - The id to combine with the Component's id that is the id of the child element.
  2860. * - `id` - The id of the child element.
  2861. *
  2862. * If the array member is a string, it is equivalent to `{ name: m, itemId: m }`.
  2863. *
  2864. * For example, a Component which renders a title and body text:
  2865. *
  2866. * Ext.create('Ext.Component', {
  2867. * renderTo: Ext.getBody(),
  2868. * renderTpl: [
  2869. * '<h1 id="{id}-title">{title}</h1>',
  2870. * '<p>{msg}</p>',
  2871. * ],
  2872. * renderData: {
  2873. * title: "Error",
  2874. * msg: "Something went wrong"
  2875. * },
  2876. * childEls: ["title"],
  2877. * listeners: {
  2878. * afterrender: function(cmp){
  2879. * // After rendering the component will have a title property
  2880. * cmp.title.setStyle({color: "red"});
  2881. * }
  2882. * }
  2883. * });
  2884. *
  2885. * A more flexible, but somewhat slower, approach is {@link #renderSelectors}.
  2886. */
  2887. /**
  2888. * @cfg {String/HTMLElement/Ext.Element} renderTo
  2889. * Specify the id of the element, a DOM element or an existing Element that this component will be rendered into.
  2890. *
  2891. * **Notes:**
  2892. *
  2893. * Do *not* use this option if the Component is to be a child item of a {@link Ext.container.Container Container}.
  2894. * It is the responsibility of the {@link Ext.container.Container Container}'s
  2895. * {@link Ext.container.Container#layout layout manager} to render and manage its child items.
  2896. *
  2897. * When using this config, a call to render() is not required.
  2898. *
  2899. * See `{@link #render}` also.
  2900. */
  2901. /**
  2902. * @cfg {Boolean} frame
  2903. * Specify as `true` to have the Component inject framing elements within the Component at render time to provide a
  2904. * graphical rounded frame around the Component content.
  2905. *
  2906. * This is only necessary when running on outdated, or non standard-compliant browsers such as Microsoft's Internet
  2907. * Explorer prior to version 9 which do not support rounded corners natively.
  2908. *
  2909. * The extra space taken up by this framing is available from the read only property {@link #frameSize}.
  2910. */
  2911. /**
  2912. * @property {Object} frameSize
  2913. * Read-only property indicating the width of any framing elements which were added within the encapsulating element
  2914. * to provide graphical, rounded borders. See the {@link #frame} config.
  2915. *
  2916. * This is an object containing the frame width in pixels for all four sides of the Component containing the
  2917. * following properties:
  2918. *
  2919. * @property {Number} frameSize.top The width of the top framing element in pixels.
  2920. * @property {Number} frameSize.right The width of the right framing element in pixels.
  2921. * @property {Number} frameSize.bottom The width of the bottom framing element in pixels.
  2922. * @property {Number} frameSize.left The width of the left framing element in pixels.
  2923. */
  2924. /**
  2925. * @cfg {String/Object} componentLayout
  2926. * The sizing and positioning of a Component's internal Elements is the responsibility of the Component's layout
  2927. * manager which sizes a Component's internal structure in response to the Component being sized.
  2928. *
  2929. * Generally, developers will not use this configuration as all provided Components which need their internal
  2930. * elements sizing (Such as {@link Ext.form.field.Base input fields}) come with their own componentLayout managers.
  2931. *
  2932. * The {@link Ext.layout.container.Auto default layout manager} will be used on instances of the base Ext.Component
  2933. * class which simply sizes the Component's encapsulating element to the height and width specified in the
  2934. * {@link #setSize} method.
  2935. */
  2936. /**
  2937. * @cfg {Ext.XTemplate/Ext.Template/String/String[]} tpl
  2938. * An {@link Ext.Template}, {@link Ext.XTemplate} or an array of strings to form an Ext.XTemplate. Used in
  2939. * conjunction with the `{@link #data}` and `{@link #tplWriteMode}` configurations.
  2940. */
  2941. /**
  2942. * @cfg {Object} data
  2943. * The initial set of data to apply to the `{@link #tpl}` to update the content area of the Component.
  2944. */
  2945. /**
  2946. * @cfg {String} xtype
  2947. * The `xtype` configuration option can be used to optimize Component creation and rendering. It serves as a
  2948. * shortcut to the full componet name. For example, the component `Ext.button.Button` has an xtype of `button`.
  2949. *
  2950. * You can define your own xtype on a custom {@link Ext.Component component} by specifying the
  2951. * {@link Ext.Class#alias alias} config option with a prefix of `widget`. For example:
  2952. *
  2953. * Ext.define('PressMeButton', {
  2954. * extend: 'Ext.button.Button',
  2955. * alias: 'widget.pressmebutton',
  2956. * text: 'Press Me'
  2957. * })
  2958. *
  2959. * Any Component can be created implicitly as an object config with an xtype specified, allowing it to be
  2960. * declared and passed into the rendering pipeline without actually being instantiated as an object. Not only is
  2961. * rendering deferred, but the actual creation of the object itself is also deferred, saving memory and resources
  2962. * until they are actually needed. In complex, nested layouts containing many Components, this can make a
  2963. * noticeable improvement in performance.
  2964. *
  2965. * // Explicit creation of contained Components:
  2966. * var panel = new Ext.Panel({
  2967. * ...
  2968. * items: [
  2969. * Ext.create('Ext.button.Button', {
  2970. * text: 'OK'
  2971. * })
  2972. * ]
  2973. * };
  2974. *
  2975. * // Implicit creation using xtype:
  2976. * var panel = new Ext.Panel({
  2977. * ...
  2978. * items: [{
  2979. * xtype: 'button',
  2980. * text: 'OK'
  2981. * }]
  2982. * };
  2983. *
  2984. * In the first example, the button will always be created immediately during the panel's initialization. With
  2985. * many added Components, this approach could potentially slow the rendering of the page. In the second example,
  2986. * the button will not be created or rendered until the panel is actually displayed in the browser. If the panel
  2987. * is never displayed (for example, if it is a tab that remains hidden) then the button will never be created and
  2988. * will never consume any resources whatsoever.
  2989. */
  2990. /**
  2991. * @cfg {String} tplWriteMode
  2992. * The Ext.(X)Template method to use when updating the content area of the Component.
  2993. * See `{@link Ext.XTemplate#overwrite}` for information on default mode.
  2994. */
  2995. tplWriteMode: 'overwrite',
  2996. /**
  2997. * @cfg {String} [baseCls='x-component']
  2998. * The base CSS class to apply to this components's element. This will also be prepended to elements within this
  2999. * component like Panel's body will get a class x-panel-body. This means that if you create a subclass of Panel, and
  3000. * you want it to get all the Panels styling for the element and the body, you leave the baseCls x-panel and use
  3001. * componentCls to add specific styling for this component.
  3002. */
  3003. baseCls: Ext.baseCSSPrefix + 'component',
  3004. /**
  3005. * @cfg {String} componentCls
  3006. * CSS Class to be added to a components root level element to give distinction to it via styling.
  3007. */
  3008. /**
  3009. * @cfg {String} [cls='']
  3010. * An optional extra CSS class that will be added to this component's Element. This can be useful
  3011. * for adding customized styles to the component or any of its children using standard CSS rules.
  3012. */
  3013. /**
  3014. * @cfg {String} [overCls='']
  3015. * An optional extra CSS class that will be added to this component's Element when the mouse moves over the Element,
  3016. * and removed when the mouse moves out. This can be useful for adding customized 'active' or 'hover' styles to the
  3017. * component or any of its children using standard CSS rules.
  3018. */
  3019. /**
  3020. * @cfg {String} [disabledCls='x-item-disabled']
  3021. * CSS class to add when the Component is disabled. Defaults to 'x-item-disabled'.
  3022. */
  3023. disabledCls: Ext.baseCSSPrefix + 'item-disabled',
  3024. /**
  3025. * @cfg {String/String[]} ui
  3026. * A set style for a component. Can be a string or an Array of multiple strings (UIs)
  3027. */
  3028. ui: 'default',
  3029. /**
  3030. * @cfg {String[]} uiCls
  3031. * An array of of classNames which are currently applied to this component
  3032. * @private
  3033. */
  3034. uiCls: [],
  3035. /**
  3036. * @cfg {String} style
  3037. * A custom style specification to be applied to this component's Element. Should be a valid argument to
  3038. * {@link Ext.Element#applyStyles}.
  3039. *
  3040. * new Ext.panel.Panel({
  3041. * title: 'Some Title',
  3042. * renderTo: Ext.getBody(),
  3043. * width: 400, height: 300,
  3044. * layout: 'form',
  3045. * items: [{
  3046. * xtype: 'textarea',
  3047. * style: {
  3048. * width: '95%',
  3049. * marginBottom: '10px'
  3050. * }
  3051. * },
  3052. * new Ext.button.Button({
  3053. * text: 'Send',
  3054. * minWidth: '100',
  3055. * style: {
  3056. * marginBottom: '10px'
  3057. * }
  3058. * })
  3059. * ]
  3060. * });
  3061. */
  3062. /**
  3063. * @cfg {Number} width
  3064. * The width of this component in pixels.
  3065. */
  3066. /**
  3067. * @cfg {Number} height
  3068. * The height of this component in pixels.
  3069. */
  3070. /**
  3071. * @cfg {Number/String} border
  3072. * Specifies the border for this component. The border can be a single numeric value to apply to all sides or it can
  3073. * be a CSS style specification for each style, for example: '10 5 3 10'.
  3074. */
  3075. /**
  3076. * @cfg {Number/String} padding
  3077. * Specifies the padding for this component. The padding can be a single numeric value to apply to all sides or it
  3078. * can be a CSS style specification for each style, for example: '10 5 3 10'.
  3079. */
  3080. /**
  3081. * @cfg {Number/String} margin
  3082. * Specifies the margin for this component. The margin can be a single numeric value to apply to all sides or it can
  3083. * be a CSS style specification for each style, for example: '10 5 3 10'.
  3084. */
  3085. /**
  3086. * @cfg {Boolean} hidden
  3087. * True to hide the component.
  3088. */
  3089. hidden: false,
  3090. /**
  3091. * @cfg {Boolean} disabled
  3092. * True to disable the component.
  3093. */
  3094. disabled: false,
  3095. /**
  3096. * @cfg {Boolean} [draggable=false]
  3097. * Allows the component to be dragged.
  3098. */
  3099. /**
  3100. * @property {Boolean} draggable
  3101. * Read-only property indicating whether or not the component can be dragged
  3102. */
  3103. draggable: false,
  3104. /**
  3105. * @cfg {Boolean} floating
  3106. * Create the Component as a floating and use absolute positioning.
  3107. *
  3108. * The z-index of floating Components is handled by a ZIndexManager. If you simply render a floating Component into the DOM, it will be managed
  3109. * by the global {@link Ext.WindowManager WindowManager}.
  3110. *
  3111. * If you include a floating Component as a child item of a Container, then upon render, ExtJS will seek an ancestor floating Component to house a new
  3112. * ZIndexManager instance to manage its descendant floaters. If no floating ancestor can be found, the global WindowManager will be used.
  3113. *
  3114. * When a floating Component which has a ZindexManager managing descendant floaters is destroyed, those descendant floaters will also be destroyed.
  3115. */
  3116. floating: false,
  3117. /**
  3118. * @cfg {String} hideMode
  3119. * A String which specifies how this Component's encapsulating DOM element will be hidden. Values may be:
  3120. *
  3121. * - `'display'` : The Component will be hidden using the `display: none` style.
  3122. * - `'visibility'` : The Component will be hidden using the `visibility: hidden` style.
  3123. * - `'offsets'` : The Component will be hidden by absolutely positioning it out of the visible area of the document.
  3124. * This is useful when a hidden Component must maintain measurable dimensions. Hiding using `display` results in a
  3125. * Component having zero dimensions.
  3126. */
  3127. hideMode: 'display',
  3128. /**
  3129. * @cfg {String} contentEl
  3130. * Specify an existing HTML element, or the `id` of an existing HTML element to use as the content for this component.
  3131. *
  3132. * This config option is used to take an existing HTML element and place it in the layout element of a new component
  3133. * (it simply moves the specified DOM element _after the Component is rendered_ to use as the content.
  3134. *
  3135. * **Notes:**
  3136. *
  3137. * The specified HTML element is appended to the layout element of the component _after any configured
  3138. * {@link #html HTML} has been inserted_, and so the document will not contain this element at the time
  3139. * the {@link #render} event is fired.
  3140. *
  3141. * The specified HTML element used will not participate in any **`{@link Ext.container.Container#layout layout}`**
  3142. * scheme that the Component may use. It is just HTML. Layouts operate on child
  3143. * **`{@link Ext.container.Container#items items}`**.
  3144. *
  3145. * Add either the `x-hidden` or the `x-hide-display` CSS class to prevent a brief flicker of the content before it
  3146. * is rendered to the panel.
  3147. */
  3148. /**
  3149. * @cfg {String/Object} [html='']
  3150. * An HTML fragment, or a {@link Ext.DomHelper DomHelper} specification to use as the layout element content.
  3151. * The HTML content is added after the component is rendered, so the document will not contain this HTML at the time
  3152. * the {@link #render} event is fired. This content is inserted into the body _before_ any configured {@link #contentEl}
  3153. * is appended.
  3154. */
  3155. /**
  3156. * @cfg {Boolean} styleHtmlContent
  3157. * True to automatically style the html inside the content target of this component (body for panels).
  3158. */
  3159. styleHtmlContent: false,
  3160. /**
  3161. * @cfg {String} [styleHtmlCls='x-html']
  3162. * The class that is added to the content target when you set styleHtmlContent to true.
  3163. */
  3164. styleHtmlCls: Ext.baseCSSPrefix + 'html',
  3165. /**
  3166. * @cfg {Number} minHeight
  3167. * The minimum value in pixels which this Component will set its height to.
  3168. *
  3169. * **Warning:** This will override any size management applied by layout managers.
  3170. */
  3171. /**
  3172. * @cfg {Number} minWidth
  3173. * The minimum value in pixels which this Component will set its width to.
  3174. *
  3175. * **Warning:** This will override any size management applied by layout managers.
  3176. */
  3177. /**
  3178. * @cfg {Number} maxHeight
  3179. * The maximum value in pixels which this Component will set its height to.
  3180. *
  3181. * **Warning:** This will override any size management applied by layout managers.
  3182. */
  3183. /**
  3184. * @cfg {Number} maxWidth
  3185. * The maximum value in pixels which this Component will set its width to.
  3186. *
  3187. * **Warning:** This will override any size management applied by layout managers.
  3188. */
  3189. /**
  3190. * @cfg {Ext.ComponentLoader/Object} loader
  3191. * A configuration object or an instance of a {@link Ext.ComponentLoader} to load remote content for this Component.
  3192. */
  3193. /**
  3194. * @cfg {Boolean} autoShow
  3195. * True to automatically show the component upon creation. This config option may only be used for
  3196. * {@link #floating} components or components that use {@link #autoRender}. Defaults to false.
  3197. */
  3198. autoShow: false,
  3199. /**
  3200. * @cfg {Boolean/String/HTMLElement/Ext.Element} autoRender
  3201. * This config is intended mainly for non-{@link #floating} Components which may or may not be shown. Instead of using
  3202. * {@link #renderTo} in the configuration, and rendering upon construction, this allows a Component to render itself
  3203. * upon first _{@link #show}_. If {@link #floating} is true, the value of this config is omited as if it is `true`.
  3204. *
  3205. * Specify as `true` to have this Component render to the document body upon first show.
  3206. *
  3207. * Specify as an element, or the ID of an element to have this Component render to a specific element upon first
  3208. * show.
  3209. *
  3210. * **This defaults to `true` for the {@link Ext.window.Window Window} class.**
  3211. */
  3212. autoRender: false,
  3213. needsLayout: false,
  3214. // @private
  3215. allowDomMove: true,
  3216. /**
  3217. * @cfg {Object/Object[]} plugins
  3218. * An object or array of objects that will provide custom functionality for this component. The only requirement for
  3219. * a valid plugin is that it contain an init method that accepts a reference of type Ext.Component. When a component
  3220. * is created, if any plugins are available, the component will call the init method on each plugin, passing a
  3221. * reference to itself. Each plugin can then call methods or respond to events on the component as needed to provide
  3222. * its functionality.
  3223. */
  3224. /**
  3225. * @property {Boolean} rendered
  3226. * Read-only property indicating whether or not the component has been rendered.
  3227. */
  3228. rendered: false,
  3229. /**
  3230. * @property {Number} componentLayoutCounter
  3231. * @private
  3232. * The number of component layout calls made on this object.
  3233. */
  3234. componentLayoutCounter: 0,
  3235. weight: 0,
  3236. trimRe: /^\s+|\s+$/g,
  3237. spacesRe: /\s+/,
  3238. /**
  3239. * @property {Boolean} maskOnDisable
  3240. * This is an internal flag that you use when creating custom components. By default this is set to true which means
  3241. * that every component gets a mask when its disabled. Components like FieldContainer, FieldSet, Field, Button, Tab
  3242. * override this property to false since they want to implement custom disable logic.
  3243. */
  3244. maskOnDisable: true,
  3245. /**
  3246. * Creates new Component.
  3247. * @param {Object} config (optional) Config object.
  3248. */
  3249. constructor : function(config) {
  3250. var me = this,
  3251. i, len;
  3252. config = config || {};
  3253. me.initialConfig = config;
  3254. Ext.apply(me, config);
  3255. me.addEvents(
  3256. /**
  3257. * @event beforeactivate
  3258. * Fires before a Component has been visually activated. Returning false from an event listener can prevent
  3259. * the activate from occurring.
  3260. * @param {Ext.Component} this
  3261. */
  3262. 'beforeactivate',
  3263. /**
  3264. * @event activate
  3265. * Fires after a Component has been visually activated.
  3266. * @param {Ext.Component} this
  3267. */
  3268. 'activate',
  3269. /**
  3270. * @event beforedeactivate
  3271. * Fires before a Component has been visually deactivated. Returning false from an event listener can
  3272. * prevent the deactivate from occurring.
  3273. * @param {Ext.Component} this
  3274. */
  3275. 'beforedeactivate',
  3276. /**
  3277. * @event deactivate
  3278. * Fires after a Component has been visually deactivated.
  3279. * @param {Ext.Component} this
  3280. */
  3281. 'deactivate',
  3282. /**
  3283. * @event added
  3284. * Fires after a Component had been added to a Container.
  3285. * @param {Ext.Component} this
  3286. * @param {Ext.container.Container} container Parent Container
  3287. * @param {Number} pos position of Component
  3288. */
  3289. 'added',
  3290. /**
  3291. * @event disable
  3292. * Fires after the component is disabled.
  3293. * @param {Ext.Component} this
  3294. */
  3295. 'disable',
  3296. /**
  3297. * @event enable
  3298. * Fires after the component is enabled.
  3299. * @param {Ext.Component} this
  3300. */
  3301. 'enable',
  3302. /**
  3303. * @event beforeshow
  3304. * Fires before the component is shown when calling the {@link #show} method. Return false from an event
  3305. * handler to stop the show.
  3306. * @param {Ext.Component} this
  3307. */
  3308. 'beforeshow',
  3309. /**
  3310. * @event show
  3311. * Fires after the component is shown when calling the {@link #show} method.
  3312. * @param {Ext.Component} this
  3313. */
  3314. 'show',
  3315. /**
  3316. * @event beforehide
  3317. * Fires before the component is hidden when calling the {@link #hide} method. Return false from an event
  3318. * handler to stop the hide.
  3319. * @param {Ext.Component} this
  3320. */
  3321. 'beforehide',
  3322. /**
  3323. * @event hide
  3324. * Fires after the component is hidden. Fires after the component is hidden when calling the {@link #hide}
  3325. * method.
  3326. * @param {Ext.Component} this
  3327. */
  3328. 'hide',
  3329. /**
  3330. * @event removed
  3331. * Fires when a component is removed from an Ext.container.Container
  3332. * @param {Ext.Component} this
  3333. * @param {Ext.container.Container} ownerCt Container which holds the component
  3334. */
  3335. 'removed',
  3336. /**
  3337. * @event beforerender
  3338. * Fires before the component is {@link #rendered}. Return false from an event handler to stop the
  3339. * {@link #render}.
  3340. * @param {Ext.Component} this
  3341. */
  3342. 'beforerender',
  3343. /**
  3344. * @event render
  3345. * Fires after the component markup is {@link #rendered}.
  3346. * @param {Ext.Component} this
  3347. */
  3348. 'render',
  3349. /**
  3350. * @event afterrender
  3351. * Fires after the component rendering is finished.
  3352. *
  3353. * The afterrender event is fired after this Component has been {@link #rendered}, been postprocesed by any
  3354. * afterRender method defined for the Component.
  3355. * @param {Ext.Component} this
  3356. */
  3357. 'afterrender',
  3358. /**
  3359. * @event beforedestroy
  3360. * Fires before the component is {@link #destroy}ed. Return false from an event handler to stop the
  3361. * {@link #destroy}.
  3362. * @param {Ext.Component} this
  3363. */
  3364. 'beforedestroy',
  3365. /**
  3366. * @event destroy
  3367. * Fires after the component is {@link #destroy}ed.
  3368. * @param {Ext.Component} this
  3369. */
  3370. 'destroy',
  3371. /**
  3372. * @event resize
  3373. * Fires after the component is resized.
  3374. * @param {Ext.Component} this
  3375. * @param {Number} adjWidth The box-adjusted width that was set
  3376. * @param {Number} adjHeight The box-adjusted height that was set
  3377. */
  3378. 'resize',
  3379. /**
  3380. * @event move
  3381. * Fires after the component is moved.
  3382. * @param {Ext.Component} this
  3383. * @param {Number} x The new x position
  3384. * @param {Number} y The new y position
  3385. */
  3386. 'move'
  3387. );
  3388. me.getId();
  3389. me.mons = [];
  3390. me.additionalCls = [];
  3391. me.renderData = me.renderData || {};
  3392. me.renderSelectors = me.renderSelectors || {};
  3393. if (me.plugins) {
  3394. me.plugins = [].concat(me.plugins);
  3395. me.constructPlugins();
  3396. }
  3397. me.initComponent();
  3398. // ititComponent gets a chance to change the id property before registering
  3399. Ext.ComponentManager.register(me);
  3400. // Dont pass the config so that it is not applied to 'this' again
  3401. me.mixins.observable.constructor.call(me);
  3402. me.mixins.state.constructor.call(me, config);
  3403. // Save state on resize.
  3404. this.addStateEvents('resize');
  3405. // Move this into Observable?
  3406. if (me.plugins) {
  3407. me.plugins = [].concat(me.plugins);
  3408. for (i = 0, len = me.plugins.length; i < len; i++) {
  3409. me.plugins[i] = me.initPlugin(me.plugins[i]);
  3410. }
  3411. }
  3412. me.loader = me.getLoader();
  3413. if (me.renderTo) {
  3414. me.render(me.renderTo);
  3415. // EXTJSIV-1935 - should be a way to do afterShow or something, but that
  3416. // won't work. Likewise, rendering hidden and then showing (w/autoShow) has
  3417. // implications to afterRender so we cannot do that.
  3418. }
  3419. if (me.autoShow) {
  3420. me.show();
  3421. }
  3422. //<debug>
  3423. if (Ext.isDefined(me.disabledClass)) {
  3424. if (Ext.isDefined(Ext.global.console)) {
  3425. Ext.global.console.warn('Ext.Component: disabledClass has been deprecated. Please use disabledCls.');
  3426. }
  3427. me.disabledCls = me.disabledClass;
  3428. delete me.disabledClass;
  3429. }
  3430. //</debug>
  3431. },
  3432. initComponent: function () {
  3433. // This is called again here to allow derived classes to add plugin configs to the
  3434. // plugins array before calling down to this, the base initComponent.
  3435. this.constructPlugins();
  3436. },
  3437. /**
  3438. * The supplied default state gathering method for the AbstractComponent class.
  3439. *
  3440. * This method returns dimension settings such as `flex`, `anchor`, `width` and `height` along with `collapsed`
  3441. * state.
  3442. *
  3443. * Subclasses which implement more complex state should call the superclass's implementation, and apply their state
  3444. * to the result if this basic state is to be saved.
  3445. *
  3446. * Note that Component state will only be saved if the Component has a {@link #stateId} and there as a StateProvider
  3447. * configured for the document.
  3448. *
  3449. * @return {Object}
  3450. */
  3451. getState: function() {
  3452. var me = this,
  3453. layout = me.ownerCt ? (me.shadowOwnerCt || me.ownerCt).getLayout() : null,
  3454. state = {
  3455. collapsed: me.collapsed
  3456. },
  3457. width = me.width,
  3458. height = me.height,
  3459. cm = me.collapseMemento,
  3460. anchors;
  3461. // If a Panel-local collapse has taken place, use remembered values as the dimensions.
  3462. // TODO: remove this coupling with Panel's privates! All collapse/expand logic should be refactored into one place.
  3463. if (me.collapsed && cm) {
  3464. if (Ext.isDefined(cm.data.width)) {
  3465. width = cm.width;
  3466. }
  3467. if (Ext.isDefined(cm.data.height)) {
  3468. height = cm.height;
  3469. }
  3470. }
  3471. // If we have flex, only store the perpendicular dimension.
  3472. if (layout && me.flex) {
  3473. state.flex = me.flex;
  3474. if (layout.perpendicularPrefix) {
  3475. state[layout.perpendicularPrefix] = me['get' + layout.perpendicularPrefixCap]();
  3476. } else {
  3477. //<debug>
  3478. if (Ext.isDefined(Ext.global.console)) {
  3479. Ext.global.console.warn('Ext.Component: Specified a flex value on a component not inside a Box layout');
  3480. }
  3481. //</debug>
  3482. }
  3483. }
  3484. // If we have anchor, only store dimensions which are *not* being anchored
  3485. else if (layout && me.anchor) {
  3486. state.anchor = me.anchor;
  3487. anchors = me.anchor.split(' ').concat(null);
  3488. if (!anchors[0]) {
  3489. if (me.width) {
  3490. state.width = width;
  3491. }
  3492. }
  3493. if (!anchors[1]) {
  3494. if (me.height) {
  3495. state.height = height;
  3496. }
  3497. }
  3498. }
  3499. // Store dimensions.
  3500. else {
  3501. if (me.width) {
  3502. state.width = width;
  3503. }
  3504. if (me.height) {
  3505. state.height = height;
  3506. }
  3507. }
  3508. // Don't save dimensions if they are unchanged from the original configuration.
  3509. if (state.width == me.initialConfig.width) {
  3510. delete state.width;
  3511. }
  3512. if (state.height == me.initialConfig.height) {
  3513. delete state.height;
  3514. }
  3515. // If a Box layout was managing the perpendicular dimension, don't save that dimension
  3516. if (layout && layout.align && (layout.align.indexOf('stretch') !== -1)) {
  3517. delete state[layout.perpendicularPrefix];
  3518. }
  3519. return state;
  3520. },
  3521. show: Ext.emptyFn,
  3522. animate: function(animObj) {
  3523. var me = this,
  3524. to;
  3525. animObj = animObj || {};
  3526. to = animObj.to || {};
  3527. if (Ext.fx.Manager.hasFxBlock(me.id)) {
  3528. return me;
  3529. }
  3530. // Special processing for animating Component dimensions.
  3531. if (!animObj.dynamic && (to.height || to.width)) {
  3532. var curWidth = me.getWidth(),
  3533. w = curWidth,
  3534. curHeight = me.getHeight(),
  3535. h = curHeight,
  3536. needsResize = false;
  3537. if (to.height && to.height > curHeight) {
  3538. h = to.height;
  3539. needsResize = true;
  3540. }
  3541. if (to.width && to.width > curWidth) {
  3542. w = to.width;
  3543. needsResize = true;
  3544. }
  3545. // If any dimensions are being increased, we must resize the internal structure
  3546. // of the Component, but then clip it by sizing its encapsulating element back to original dimensions.
  3547. // The animation will then progressively reveal the larger content.
  3548. if (needsResize) {
  3549. var clearWidth = !Ext.isNumber(me.width),
  3550. clearHeight = !Ext.isNumber(me.height);
  3551. me.componentLayout.childrenChanged = true;
  3552. me.setSize(w, h, me.ownerCt);
  3553. me.el.setSize(curWidth, curHeight);
  3554. if (clearWidth) {
  3555. delete me.width;
  3556. }
  3557. if (clearHeight) {
  3558. delete me.height;
  3559. }
  3560. }
  3561. }
  3562. return me.mixins.animate.animate.apply(me, arguments);
  3563. },
  3564. /**
  3565. * This method finds the topmost active layout who's processing will eventually determine the size and position of
  3566. * this Component.
  3567. *
  3568. * This method is useful when dynamically adding Components into Containers, and some processing must take place
  3569. * after the final sizing and positioning of the Component has been performed.
  3570. *
  3571. * @return {Ext.Component}
  3572. */
  3573. findLayoutController: function() {
  3574. return this.findParentBy(function(c) {
  3575. // Return true if we are at the root of the Container tree
  3576. // or this Container's layout is busy but the next one up is not.
  3577. return !c.ownerCt || (c.layout.layoutBusy && !c.ownerCt.layout.layoutBusy);
  3578. });
  3579. },
  3580. onShow : function() {
  3581. // Layout if needed
  3582. var needsLayout = this.needsLayout;
  3583. if (Ext.isObject(needsLayout)) {
  3584. this.doComponentLayout(needsLayout.width, needsLayout.height, needsLayout.isSetSize, needsLayout.ownerCt);
  3585. }
  3586. },
  3587. constructPlugin: function(plugin) {
  3588. if (plugin.ptype && typeof plugin.init != 'function') {
  3589. plugin.cmp = this;
  3590. plugin = Ext.PluginManager.create(plugin);
  3591. }
  3592. else if (typeof plugin == 'string') {
  3593. plugin = Ext.PluginManager.create({
  3594. ptype: plugin,
  3595. cmp: this
  3596. });
  3597. }
  3598. return plugin;
  3599. },
  3600. /**
  3601. * Ensures that the plugins array contains fully constructed plugin instances. This converts any configs into their
  3602. * appropriate instances.
  3603. */
  3604. constructPlugins: function() {
  3605. var me = this,
  3606. plugins = me.plugins,
  3607. i, len;
  3608. if (plugins) {
  3609. for (i = 0, len = plugins.length; i < len; i++) {
  3610. // this just returns already-constructed plugin instances...
  3611. plugins[i] = me.constructPlugin(plugins[i]);
  3612. }
  3613. }
  3614. },
  3615. // @private
  3616. initPlugin : function(plugin) {
  3617. plugin.init(this);
  3618. return plugin;
  3619. },
  3620. /**
  3621. * Handles autoRender. Floating Components may have an ownerCt. If they are asking to be constrained, constrain them
  3622. * within that ownerCt, and have their z-index managed locally. Floating Components are always rendered to
  3623. * document.body
  3624. */
  3625. doAutoRender: function() {
  3626. var me = this;
  3627. if (me.floating) {
  3628. me.render(document.body);
  3629. } else {
  3630. me.render(Ext.isBoolean(me.autoRender) ? Ext.getBody() : me.autoRender);
  3631. }
  3632. },
  3633. // @private
  3634. render : function(container, position) {
  3635. var me = this;
  3636. if (!me.rendered && me.fireEvent('beforerender', me) !== false) {
  3637. // Flag set during the render process.
  3638. // It can be used to inhibit event-driven layout calls during the render phase
  3639. me.rendering = true;
  3640. // If this.el is defined, we want to make sure we are dealing with
  3641. // an Ext Element.
  3642. if (me.el) {
  3643. me.el = Ext.get(me.el);
  3644. }
  3645. // Perform render-time processing for floating Components
  3646. if (me.floating) {
  3647. me.onFloatRender();
  3648. }
  3649. container = me.initContainer(container);
  3650. me.onRender(container, position);
  3651. // Tell the encapsulating element to hide itself in the way the Component is configured to hide
  3652. // This means DISPLAY, VISIBILITY or OFFSETS.
  3653. me.el.setVisibilityMode(Ext.Element[me.hideMode.toUpperCase()]);
  3654. if (me.overCls) {
  3655. me.el.hover(me.addOverCls, me.removeOverCls, me);
  3656. }
  3657. me.fireEvent('render', me);
  3658. me.initContent();
  3659. me.afterRender(container);
  3660. me.fireEvent('afterrender', me);
  3661. me.initEvents();
  3662. if (me.hidden) {
  3663. // Hiding during the render process should not perform any ancillary
  3664. // actions that the full hide process does; It is not hiding, it begins in a hidden state.'
  3665. // So just make the element hidden according to the configured hideMode
  3666. me.el.hide();
  3667. }
  3668. if (me.disabled) {
  3669. // pass silent so the event doesn't fire the first time.
  3670. me.disable(true);
  3671. }
  3672. // Delete the flag once the rendering is done.
  3673. delete me.rendering;
  3674. }
  3675. return me;
  3676. },
  3677. // @private
  3678. onRender : function(container, position) {
  3679. var me = this,
  3680. el = me.el,
  3681. styles = me.initStyles(),
  3682. renderTpl, renderData, i;
  3683. position = me.getInsertPosition(position);
  3684. if (!el) {
  3685. if (position) {
  3686. el = Ext.DomHelper.insertBefore(position, me.getElConfig(), true);
  3687. }
  3688. else {
  3689. el = Ext.DomHelper.append(container, me.getElConfig(), true);
  3690. }
  3691. }
  3692. else if (me.allowDomMove !== false) {
  3693. if (position) {
  3694. container.dom.insertBefore(el.dom, position);
  3695. } else {
  3696. container.dom.appendChild(el.dom);
  3697. }
  3698. }
  3699. if (Ext.scopeResetCSS && !me.ownerCt) {
  3700. // If this component's el is the body element, we add the reset class to the html tag
  3701. if (el.dom == Ext.getBody().dom) {
  3702. el.parent().addCls(Ext.baseCSSPrefix + 'reset');
  3703. }
  3704. else {
  3705. // Else we wrap this element in an element that adds the reset class.
  3706. me.resetEl = el.wrap({
  3707. cls: Ext.baseCSSPrefix + 'reset'
  3708. });
  3709. }
  3710. }
  3711. me.setUI(me.ui);
  3712. el.addCls(me.initCls());
  3713. el.setStyle(styles);
  3714. // Here we check if the component has a height set through style or css.
  3715. // If it does then we set the this.height to that value and it won't be
  3716. // considered an auto height component
  3717. // if (this.height === undefined) {
  3718. // var height = el.getHeight();
  3719. // // This hopefully means that the panel has an explicit height set in style or css
  3720. // if (height - el.getPadding('tb') - el.getBorderWidth('tb') > 0) {
  3721. // this.height = height;
  3722. // }
  3723. // }
  3724. me.el = el;
  3725. me.initFrame();
  3726. renderTpl = me.initRenderTpl();
  3727. if (renderTpl) {
  3728. renderData = me.initRenderData();
  3729. renderTpl.append(me.getTargetEl(), renderData);
  3730. }
  3731. me.applyRenderSelectors();
  3732. me.rendered = true;
  3733. },
  3734. // @private
  3735. afterRender : function() {
  3736. var me = this,
  3737. pos,
  3738. xy;
  3739. me.getComponentLayout();
  3740. // Set the size if a size is configured, or if this is the outermost Container.
  3741. // Also, if this is a collapsed Panel, it needs an initial component layout
  3742. // to lay out its header so that it can have a height determined.
  3743. if (me.collapsed || (!me.ownerCt || (me.height || me.width))) {
  3744. me.setSize(me.width, me.height);
  3745. } else {
  3746. // It is expected that child items be rendered before this method returns and
  3747. // the afterrender event fires. Since we aren't going to do the layout now, we
  3748. // must render the child items. This is handled implicitly above in the layout
  3749. // caused by setSize.
  3750. me.renderChildren();
  3751. }
  3752. // For floaters, calculate x and y if they aren't defined by aligning
  3753. // the sized element to the center of either the container or the ownerCt
  3754. if (me.floating && (me.x === undefined || me.y === undefined)) {
  3755. if (me.floatParent) {
  3756. xy = me.el.getAlignToXY(me.floatParent.getTargetEl(), 'c-c');
  3757. pos = me.floatParent.getTargetEl().translatePoints(xy[0], xy[1]);
  3758. } else {
  3759. xy = me.el.getAlignToXY(me.container, 'c-c');
  3760. pos = me.container.translatePoints(xy[0], xy[1]);
  3761. }
  3762. me.x = me.x === undefined ? pos.left: me.x;
  3763. me.y = me.y === undefined ? pos.top: me.y;
  3764. }
  3765. if (Ext.isDefined(me.x) || Ext.isDefined(me.y)) {
  3766. me.setPosition(me.x, me.y);
  3767. }
  3768. if (me.styleHtmlContent) {
  3769. me.getTargetEl().addCls(me.styleHtmlCls);
  3770. }
  3771. },
  3772. /**
  3773. * @private
  3774. * Called by Component#doAutoRender
  3775. *
  3776. * Register a Container configured `floating: true` with this Component's {@link Ext.ZIndexManager ZIndexManager}.
  3777. *
  3778. * Components added in ths way will not participate in any layout, but will be rendered
  3779. * upon first show in the way that {@link Ext.window.Window Window}s are.
  3780. */
  3781. registerFloatingItem: function(cmp) {
  3782. var me = this;
  3783. if (!me.floatingItems) {
  3784. me.floatingItems = Ext.create('Ext.ZIndexManager', me);
  3785. }
  3786. me.floatingItems.register(cmp);
  3787. },
  3788. renderChildren: function () {
  3789. var me = this,
  3790. layout = me.getComponentLayout();
  3791. me.suspendLayout = true;
  3792. layout.renderChildren();
  3793. delete me.suspendLayout;
  3794. },
  3795. frameCls: Ext.baseCSSPrefix + 'frame',
  3796. frameIdRegex: /[-]frame\d+[TMB][LCR]$/,
  3797. frameElementCls: {
  3798. tl: [],
  3799. tc: [],
  3800. tr: [],
  3801. ml: [],
  3802. mc: [],
  3803. mr: [],
  3804. bl: [],
  3805. bc: [],
  3806. br: []
  3807. },
  3808. frameTpl: [
  3809. '<tpl if="top">',
  3810. '<tpl if="left"><div id="{fgid}TL" class="{frameCls}-tl {baseCls}-tl {baseCls}-{ui}-tl<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-tl</tpl></tpl>" style="background-position: {tl}; padding-left: {frameWidth}px" role="presentation"></tpl>',
  3811. '<tpl if="right"><div id="{fgid}TR" class="{frameCls}-tr {baseCls}-tr {baseCls}-{ui}-tr<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-tr</tpl></tpl>" style="background-position: {tr}; padding-right: {frameWidth}px" role="presentation"></tpl>',
  3812. '<div id="{fgid}TC" class="{frameCls}-tc {baseCls}-tc {baseCls}-{ui}-tc<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-tc</tpl></tpl>" style="background-position: {tc}; height: {frameWidth}px" role="presentation"></div>',
  3813. '<tpl if="right"></div></tpl>',
  3814. '<tpl if="left"></div></tpl>',
  3815. '</tpl>',
  3816. '<tpl if="left"><div id="{fgid}ML" class="{frameCls}-ml {baseCls}-ml {baseCls}-{ui}-ml<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-ml</tpl></tpl>" style="background-position: {ml}; padding-left: {frameWidth}px" role="presentation"></tpl>',
  3817. '<tpl if="right"><div id="{fgid}MR" class="{frameCls}-mr {baseCls}-mr {baseCls}-{ui}-mr<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-mr</tpl></tpl>" style="background-position: {mr}; padding-right: {frameWidth}px" role="presentation"></tpl>',
  3818. '<div id="{fgid}MC" class="{frameCls}-mc {baseCls}-mc {baseCls}-{ui}-mc<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-mc</tpl></tpl>" role="presentation"></div>',
  3819. '<tpl if="right"></div></tpl>',
  3820. '<tpl if="left"></div></tpl>',
  3821. '<tpl if="bottom">',
  3822. '<tpl if="left"><div id="{fgid}BL" class="{frameCls}-bl {baseCls}-bl {baseCls}-{ui}-bl<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-bl</tpl></tpl>" style="background-position: {bl}; padding-left: {frameWidth}px" role="presentation"></tpl>',
  3823. '<tpl if="right"><div id="{fgid}BR" class="{frameCls}-br {baseCls}-br {baseCls}-{ui}-br<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-br</tpl></tpl>" style="background-position: {br}; padding-right: {frameWidth}px" role="presentation"></tpl>',
  3824. '<div id="{fgid}BC" class="{frameCls}-bc {baseCls}-bc {baseCls}-{ui}-bc<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-bc</tpl></tpl>" style="background-position: {bc}; height: {frameWidth}px" role="presentation"></div>',
  3825. '<tpl if="right"></div></tpl>',
  3826. '<tpl if="left"></div></tpl>',
  3827. '</tpl>'
  3828. ],
  3829. frameTableTpl: [
  3830. '<table><tbody>',
  3831. '<tpl if="top">',
  3832. '<tr>',
  3833. '<tpl if="left"><td id="{fgid}TL" class="{frameCls}-tl {baseCls}-tl {baseCls}-{ui}-tl<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-tl</tpl></tpl>" style="background-position: {tl}; padding-left:{frameWidth}px" role="presentation"></td></tpl>',
  3834. '<td id="{fgid}TC" class="{frameCls}-tc {baseCls}-tc {baseCls}-{ui}-tc<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-tc</tpl></tpl>" style="background-position: {tc}; height: {frameWidth}px" role="presentation"></td>',
  3835. '<tpl if="right"><td id="{fgid}TR" class="{frameCls}-tr {baseCls}-tr {baseCls}-{ui}-tr<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-tr</tpl></tpl>" style="background-position: {tr}; padding-left: {frameWidth}px" role="presentation"></td></tpl>',
  3836. '</tr>',
  3837. '</tpl>',
  3838. '<tr>',
  3839. '<tpl if="left"><td id="{fgid}ML" class="{frameCls}-ml {baseCls}-ml {baseCls}-{ui}-ml<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-ml</tpl></tpl>" style="background-position: {ml}; padding-left: {frameWidth}px" role="presentation"></td></tpl>',
  3840. '<td id="{fgid}MC" class="{frameCls}-mc {baseCls}-mc {baseCls}-{ui}-mc<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-mc</tpl></tpl>" style="background-position: 0 0;" role="presentation"></td>',
  3841. '<tpl if="right"><td id="{fgid}MR" class="{frameCls}-mr {baseCls}-mr {baseCls}-{ui}-mr<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-mr</tpl></tpl>" style="background-position: {mr}; padding-left: {frameWidth}px" role="presentation"></td></tpl>',
  3842. '</tr>',
  3843. '<tpl if="bottom">',
  3844. '<tr>',
  3845. '<tpl if="left"><td id="{fgid}BL" class="{frameCls}-bl {baseCls}-bl {baseCls}-{ui}-bl<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-bl</tpl></tpl>" style="background-position: {bl}; padding-left: {frameWidth}px" role="presentation"></td></tpl>',
  3846. '<td id="{fgid}BC" class="{frameCls}-bc {baseCls}-bc {baseCls}-{ui}-bc<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-bc</tpl></tpl>" style="background-position: {bc}; height: {frameWidth}px" role="presentation"></td>',
  3847. '<tpl if="right"><td id="{fgid}BR" class="{frameCls}-br {baseCls}-br {baseCls}-{ui}-br<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-br</tpl></tpl>" style="background-position: {br}; padding-left: {frameWidth}px" role="presentation"></td></tpl>',
  3848. '</tr>',
  3849. '</tpl>',
  3850. '</tbody></table>'
  3851. ],
  3852. /**
  3853. * @private
  3854. */
  3855. initFrame : function() {
  3856. if (Ext.supports.CSS3BorderRadius) {
  3857. return false;
  3858. }
  3859. var me = this,
  3860. frameInfo = me.getFrameInfo(),
  3861. frameWidth = frameInfo.width,
  3862. frameTpl = me.getFrameTpl(frameInfo.table),
  3863. frameGenId;
  3864. if (me.frame) {
  3865. // since we render id's into the markup and id's NEED to be unique, we have a
  3866. // simple strategy for numbering their generations.
  3867. me.frameGenId = frameGenId = (me.frameGenId || 0) + 1;
  3868. frameGenId = me.id + '-frame' + frameGenId;
  3869. // Here we render the frameTpl to this component. This inserts the 9point div or the table framing.
  3870. frameTpl.insertFirst(me.el, Ext.apply({}, {
  3871. fgid: frameGenId,
  3872. ui: me.ui,
  3873. uiCls: me.uiCls,
  3874. frameCls: me.frameCls,
  3875. baseCls: me.baseCls,
  3876. frameWidth: frameWidth,
  3877. top: !!frameInfo.top,
  3878. left: !!frameInfo.left,
  3879. right: !!frameInfo.right,
  3880. bottom: !!frameInfo.bottom
  3881. }, me.getFramePositions(frameInfo)));
  3882. // The frameBody is returned in getTargetEl, so that layouts render items to the correct target.=
  3883. me.frameBody = me.el.down('.' + me.frameCls + '-mc');
  3884. // Clean out the childEls for the old frame elements (the majority of the els)
  3885. me.removeChildEls(function (c) {
  3886. return c.id && me.frameIdRegex.test(c.id);
  3887. });
  3888. // Add the childEls for each of the new frame elements
  3889. Ext.each(['TL','TC','TR','ML','MC','MR','BL','BC','BR'], function (suffix) {
  3890. me.childEls.push({ name: 'frame' + suffix, id: frameGenId + suffix });
  3891. });
  3892. }
  3893. },
  3894. updateFrame: function() {
  3895. if (Ext.supports.CSS3BorderRadius) {
  3896. return false;
  3897. }
  3898. var me = this,
  3899. wasTable = this.frameSize && this.frameSize.table,
  3900. oldFrameTL = this.frameTL,
  3901. oldFrameBL = this.frameBL,
  3902. oldFrameML = this.frameML,
  3903. oldFrameMC = this.frameMC,
  3904. newMCClassName;
  3905. this.initFrame();
  3906. if (oldFrameMC) {
  3907. if (me.frame) {
  3908. // Reapply render selectors
  3909. delete me.frameTL;
  3910. delete me.frameTC;
  3911. delete me.frameTR;
  3912. delete me.frameML;
  3913. delete me.frameMC;
  3914. delete me.frameMR;
  3915. delete me.frameBL;
  3916. delete me.frameBC;
  3917. delete me.frameBR;
  3918. this.applyRenderSelectors();
  3919. // Store the class names set on the new mc
  3920. newMCClassName = this.frameMC.dom.className;
  3921. // Replace the new mc with the old mc
  3922. oldFrameMC.insertAfter(this.frameMC);
  3923. this.frameMC.remove();
  3924. // Restore the reference to the old frame mc as the framebody
  3925. this.frameBody = this.frameMC = oldFrameMC;
  3926. // Apply the new mc classes to the old mc element
  3927. oldFrameMC.dom.className = newMCClassName;
  3928. // Remove the old framing
  3929. if (wasTable) {
  3930. me.el.query('> table')[1].remove();
  3931. }
  3932. else {
  3933. if (oldFrameTL) {
  3934. oldFrameTL.remove();
  3935. }
  3936. if (oldFrameBL) {
  3937. oldFrameBL.remove();
  3938. }
  3939. oldFrameML.remove();
  3940. }
  3941. }
  3942. else {
  3943. // We were framed but not anymore. Move all content from the old frame to the body
  3944. }
  3945. }
  3946. else if (me.frame) {
  3947. this.applyRenderSelectors();
  3948. }
  3949. },
  3950. getFrameInfo: function() {
  3951. if (Ext.supports.CSS3BorderRadius) {
  3952. return false;
  3953. }
  3954. var me = this,
  3955. left = me.el.getStyle('background-position-x'),
  3956. top = me.el.getStyle('background-position-y'),
  3957. info, frameInfo = false, max;
  3958. // Some browsers dont support background-position-x and y, so for those
  3959. // browsers let's split background-position into two parts.
  3960. if (!left && !top) {
  3961. info = me.el.getStyle('background-position').split(' ');
  3962. left = info[0];
  3963. top = info[1];
  3964. }
  3965. // We actually pass a string in the form of '[type][tl][tr]px [type][br][bl]px' as
  3966. // the background position of this.el from the css to indicate to IE that this component needs
  3967. // framing. We parse it here and change the markup accordingly.
  3968. if (parseInt(left, 10) >= 1000000 && parseInt(top, 10) >= 1000000) {
  3969. max = Math.max;
  3970. frameInfo = {
  3971. // Table markup starts with 110, div markup with 100.
  3972. table: left.substr(0, 3) == '110',
  3973. // Determine if we are dealing with a horizontal or vertical component
  3974. vertical: top.substr(0, 3) == '110',
  3975. // Get and parse the different border radius sizes
  3976. top: max(left.substr(3, 2), left.substr(5, 2)),
  3977. right: max(left.substr(5, 2), top.substr(3, 2)),
  3978. bottom: max(top.substr(3, 2), top.substr(5, 2)),
  3979. left: max(top.substr(5, 2), left.substr(3, 2))
  3980. };
  3981. frameInfo.width = max(frameInfo.top, frameInfo.right, frameInfo.bottom, frameInfo.left);
  3982. // Just to be sure we set the background image of the el to none.
  3983. me.el.setStyle('background-image', 'none');
  3984. }
  3985. // This happens when you set frame: true explicitly without using the x-frame mixin in sass.
  3986. // This way IE can't figure out what sizes to use and thus framing can't work.
  3987. if (me.frame === true && !frameInfo) {
  3988. //<debug error>
  3989. Ext.Error.raise("You have set frame: true explicity on this component while it doesn't have any " +
  3990. "framing defined in the CSS template. In this case IE can't figure out what sizes " +
  3991. "to use and thus framing on this component will be disabled.");
  3992. //</debug>
  3993. }
  3994. me.frame = me.frame || !!frameInfo;
  3995. me.frameSize = frameInfo || false;
  3996. return frameInfo;
  3997. },
  3998. getFramePositions: function(frameInfo) {
  3999. var me = this,
  4000. frameWidth = frameInfo.width,
  4001. dock = me.dock,
  4002. positions, tc, bc, ml, mr;
  4003. if (frameInfo.vertical) {
  4004. tc = '0 -' + (frameWidth * 0) + 'px';
  4005. bc = '0 -' + (frameWidth * 1) + 'px';
  4006. if (dock && dock == "right") {
  4007. tc = 'right -' + (frameWidth * 0) + 'px';
  4008. bc = 'right -' + (frameWidth * 1) + 'px';
  4009. }
  4010. positions = {
  4011. tl: '0 -' + (frameWidth * 0) + 'px',
  4012. tr: '0 -' + (frameWidth * 1) + 'px',
  4013. bl: '0 -' + (frameWidth * 2) + 'px',
  4014. br: '0 -' + (frameWidth * 3) + 'px',
  4015. ml: '-' + (frameWidth * 1) + 'px 0',
  4016. mr: 'right 0',
  4017. tc: tc,
  4018. bc: bc
  4019. };
  4020. } else {
  4021. ml = '-' + (frameWidth * 0) + 'px 0';
  4022. mr = 'right 0';
  4023. if (dock && dock == "bottom") {
  4024. ml = 'left bottom';
  4025. mr = 'right bottom';
  4026. }
  4027. positions = {
  4028. tl: '0 -' + (frameWidth * 2) + 'px',
  4029. tr: 'right -' + (frameWidth * 3) + 'px',
  4030. bl: '0 -' + (frameWidth * 4) + 'px',
  4031. br: 'right -' + (frameWidth * 5) + 'px',
  4032. ml: ml,
  4033. mr: mr,
  4034. tc: '0 -' + (frameWidth * 0) + 'px',
  4035. bc: '0 -' + (frameWidth * 1) + 'px'
  4036. };
  4037. }
  4038. return positions;
  4039. },
  4040. /**
  4041. * @private
  4042. */
  4043. getFrameTpl : function(table) {
  4044. return table ? this.getTpl('frameTableTpl') : this.getTpl('frameTpl');
  4045. },
  4046. /**
  4047. * Creates an array of class names from the configurations to add to this Component's `el` on render.
  4048. *
  4049. * Private, but (possibly) used by ComponentQuery for selection by class name if Component is not rendered.
  4050. *
  4051. * @return {String[]} An array of class names with which the Component's element will be rendered.
  4052. * @private
  4053. */
  4054. initCls: function() {
  4055. var me = this,
  4056. cls = [];
  4057. cls.push(me.baseCls);
  4058. //<deprecated since=0.99>
  4059. if (Ext.isDefined(me.cmpCls)) {
  4060. if (Ext.isDefined(Ext.global.console)) {
  4061. Ext.global.console.warn('Ext.Component: cmpCls has been deprecated. Please use componentCls.');
  4062. }
  4063. me.componentCls = me.cmpCls;
  4064. delete me.cmpCls;
  4065. }
  4066. //</deprecated>
  4067. if (me.componentCls) {
  4068. cls.push(me.componentCls);
  4069. } else {
  4070. me.componentCls = me.baseCls;
  4071. }
  4072. if (me.cls) {
  4073. cls.push(me.cls);
  4074. delete me.cls;
  4075. }
  4076. return cls.concat(me.additionalCls);
  4077. },
  4078. /**
  4079. * Sets the UI for the component. This will remove any existing UIs on the component. It will also loop through any
  4080. * uiCls set on the component and rename them so they include the new UI
  4081. * @param {String} ui The new UI for the component
  4082. */
  4083. setUI: function(ui) {
  4084. var me = this,
  4085. oldUICls = Ext.Array.clone(me.uiCls),
  4086. newUICls = [],
  4087. classes = [],
  4088. cls,
  4089. i;
  4090. //loop through all exisiting uiCls and update the ui in them
  4091. for (i = 0; i < oldUICls.length; i++) {
  4092. cls = oldUICls[i];
  4093. classes = classes.concat(me.removeClsWithUI(cls, true));
  4094. newUICls.push(cls);
  4095. }
  4096. if (classes.length) {
  4097. me.removeCls(classes);
  4098. }
  4099. //remove the UI from the element
  4100. me.removeUIFromElement();
  4101. //set the UI
  4102. me.ui = ui;
  4103. //add the new UI to the elemend
  4104. me.addUIToElement();
  4105. //loop through all exisiting uiCls and update the ui in them
  4106. classes = [];
  4107. for (i = 0; i < newUICls.length; i++) {
  4108. cls = newUICls[i];
  4109. classes = classes.concat(me.addClsWithUI(cls, true));
  4110. }
  4111. if (classes.length) {
  4112. me.addCls(classes);
  4113. }
  4114. },
  4115. /**
  4116. * Adds a cls to the uiCls array, which will also call {@link #addUIClsToElement} and adds to all elements of this
  4117. * component.
  4118. * @param {String/String[]} cls A string or an array of strings to add to the uiCls
  4119. * @param {Object} skip (Boolean) skip True to skip adding it to the class and do it later (via the return)
  4120. */
  4121. addClsWithUI: function(cls, skip) {
  4122. var me = this,
  4123. classes = [],
  4124. i;
  4125. if (!Ext.isArray(cls)) {
  4126. cls = [cls];
  4127. }
  4128. for (i = 0; i < cls.length; i++) {
  4129. if (cls[i] && !me.hasUICls(cls[i])) {
  4130. me.uiCls = Ext.Array.clone(me.uiCls);
  4131. me.uiCls.push(cls[i]);
  4132. classes = classes.concat(me.addUIClsToElement(cls[i]));
  4133. }
  4134. }
  4135. if (skip !== true) {
  4136. me.addCls(classes);
  4137. }
  4138. return classes;
  4139. },
  4140. /**
  4141. * Removes a cls to the uiCls array, which will also call {@link #removeUIClsFromElement} and removes it from all
  4142. * elements of this component.
  4143. * @param {String/String[]} cls A string or an array of strings to remove to the uiCls
  4144. */
  4145. removeClsWithUI: function(cls, skip) {
  4146. var me = this,
  4147. classes = [],
  4148. i;
  4149. if (!Ext.isArray(cls)) {
  4150. cls = [cls];
  4151. }
  4152. for (i = 0; i < cls.length; i++) {
  4153. if (cls[i] && me.hasUICls(cls[i])) {
  4154. me.uiCls = Ext.Array.remove(me.uiCls, cls[i]);
  4155. classes = classes.concat(me.removeUIClsFromElement(cls[i]));
  4156. }
  4157. }
  4158. if (skip !== true) {
  4159. me.removeCls(classes);
  4160. }
  4161. return classes;
  4162. },
  4163. /**
  4164. * Checks if there is currently a specified uiCls
  4165. * @param {String} cls The cls to check
  4166. */
  4167. hasUICls: function(cls) {
  4168. var me = this,
  4169. uiCls = me.uiCls || [];
  4170. return Ext.Array.contains(uiCls, cls);
  4171. },
  4172. /**
  4173. * Method which adds a specified UI + uiCls to the components element. Can be overridden to remove the UI from more
  4174. * than just the components element.
  4175. * @param {String} ui The UI to remove from the element
  4176. */
  4177. addUIClsToElement: function(cls, force) {
  4178. var me = this,
  4179. result = [],
  4180. frameElementCls = me.frameElementCls;
  4181. result.push(Ext.baseCSSPrefix + cls);
  4182. result.push(me.baseCls + '-' + cls);
  4183. result.push(me.baseCls + '-' + me.ui + '-' + cls);
  4184. if (!force && me.frame && !Ext.supports.CSS3BorderRadius) {
  4185. // define each element of the frame
  4186. var els = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'],
  4187. classes, i, j, el;
  4188. // loop through each of them, and if they are defined add the ui
  4189. for (i = 0; i < els.length; i++) {
  4190. el = me['frame' + els[i].toUpperCase()];
  4191. classes = [me.baseCls + '-' + me.ui + '-' + els[i], me.baseCls + '-' + me.ui + '-' + cls + '-' + els[i]];
  4192. if (el && el.dom) {
  4193. el.addCls(classes);
  4194. } else {
  4195. for (j = 0; j < classes.length; j++) {
  4196. if (Ext.Array.indexOf(frameElementCls[els[i]], classes[j]) == -1) {
  4197. frameElementCls[els[i]].push(classes[j]);
  4198. }
  4199. }
  4200. }
  4201. }
  4202. }
  4203. me.frameElementCls = frameElementCls;
  4204. return result;
  4205. },
  4206. /**
  4207. * Method which removes a specified UI + uiCls from the components element. The cls which is added to the element
  4208. * will be: `this.baseCls + '-' + ui`
  4209. * @param {String} ui The UI to add to the element
  4210. */
  4211. removeUIClsFromElement: function(cls, force) {
  4212. var me = this,
  4213. result = [],
  4214. frameElementCls = me.frameElementCls;
  4215. result.push(Ext.baseCSSPrefix + cls);
  4216. result.push(me.baseCls + '-' + cls);
  4217. result.push(me.baseCls + '-' + me.ui + '-' + cls);
  4218. if (!force && me.frame && !Ext.supports.CSS3BorderRadius) {
  4219. // define each element of the frame
  4220. var els = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'],
  4221. i, el;
  4222. cls = me.baseCls + '-' + me.ui + '-' + cls + '-' + els[i];
  4223. // loop through each of them, and if they are defined add the ui
  4224. for (i = 0; i < els.length; i++) {
  4225. el = me['frame' + els[i].toUpperCase()];
  4226. if (el && el.dom) {
  4227. el.removeCls(cls);
  4228. } else {
  4229. Ext.Array.remove(frameElementCls[els[i]], cls);
  4230. }
  4231. }
  4232. }
  4233. me.frameElementCls = frameElementCls;
  4234. return result;
  4235. },
  4236. /**
  4237. * Method which adds a specified UI to the components element.
  4238. * @private
  4239. */
  4240. addUIToElement: function(force) {
  4241. var me = this,
  4242. frameElementCls = me.frameElementCls;
  4243. me.addCls(me.baseCls + '-' + me.ui);
  4244. if (me.frame && !Ext.supports.CSS3BorderRadius) {
  4245. // define each element of the frame
  4246. var els = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'],
  4247. i, el, cls;
  4248. // loop through each of them, and if they are defined add the ui
  4249. for (i = 0; i < els.length; i++) {
  4250. el = me['frame' + els[i].toUpperCase()];
  4251. cls = me.baseCls + '-' + me.ui + '-' + els[i];
  4252. if (el) {
  4253. el.addCls(cls);
  4254. } else {
  4255. if (!Ext.Array.contains(frameElementCls[els[i]], cls)) {
  4256. frameElementCls[els[i]].push(cls);
  4257. }
  4258. }
  4259. }
  4260. }
  4261. },
  4262. /**
  4263. * Method which removes a specified UI from the components element.
  4264. * @private
  4265. */
  4266. removeUIFromElement: function() {
  4267. var me = this,
  4268. frameElementCls = me.frameElementCls;
  4269. me.removeCls(me.baseCls + '-' + me.ui);
  4270. if (me.frame && !Ext.supports.CSS3BorderRadius) {
  4271. // define each element of the frame
  4272. var els = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'],
  4273. i, j, el, cls;
  4274. // loop through each of them, and if they are defined add the ui
  4275. for (i = 0; i < els.length; i++) {
  4276. el = me['frame' + els[i].toUpperCase()];
  4277. cls = me.baseCls + '-' + me.ui + '-' + els[i];
  4278. if (el) {
  4279. el.removeCls(cls);
  4280. } else {
  4281. Ext.Array.remove(frameElementCls[els[i]], cls);
  4282. }
  4283. }
  4284. }
  4285. },
  4286. getElConfig : function() {
  4287. if (Ext.isString(this.autoEl)) {
  4288. this.autoEl = {
  4289. tag: this.autoEl
  4290. };
  4291. }
  4292. var result = this.autoEl || {tag: 'div'};
  4293. result.id = this.id;
  4294. return result;
  4295. },
  4296. /**
  4297. * This function takes the position argument passed to onRender and returns a DOM element that you can use in the
  4298. * insertBefore.
  4299. * @param {String/Number/Ext.Element/HTMLElement} position Index, element id or element you want to put this
  4300. * component before.
  4301. * @return {HTMLElement} DOM element that you can use in the insertBefore
  4302. */
  4303. getInsertPosition: function(position) {
  4304. // Convert the position to an element to insert before
  4305. if (position !== undefined) {
  4306. if (Ext.isNumber(position)) {
  4307. position = this.container.dom.childNodes[position];
  4308. }
  4309. else {
  4310. position = Ext.getDom(position);
  4311. }
  4312. }
  4313. return position;
  4314. },
  4315. /**
  4316. * Adds ctCls to container.
  4317. * @return {Ext.Element} The initialized container
  4318. * @private
  4319. */
  4320. initContainer: function(container) {
  4321. var me = this;
  4322. // If you render a component specifying the el, we get the container
  4323. // of the el, and make sure we dont move the el around in the dom
  4324. // during the render
  4325. if (!container && me.el) {
  4326. container = me.el.dom.parentNode;
  4327. me.allowDomMove = false;
  4328. }
  4329. me.container = Ext.get(container);
  4330. if (me.ctCls) {
  4331. me.container.addCls(me.ctCls);
  4332. }
  4333. return me.container;
  4334. },
  4335. /**
  4336. * Initialized the renderData to be used when rendering the renderTpl.
  4337. * @return {Object} Object with keys and values that are going to be applied to the renderTpl
  4338. * @private
  4339. */
  4340. initRenderData: function() {
  4341. var me = this;
  4342. return Ext.applyIf(me.renderData, {
  4343. id: me.id,
  4344. ui: me.ui,
  4345. uiCls: me.uiCls,
  4346. baseCls: me.baseCls,
  4347. componentCls: me.componentCls,
  4348. frame: me.frame
  4349. });
  4350. },
  4351. /**
  4352. * @private
  4353. */
  4354. getTpl: function(name) {
  4355. var me = this,
  4356. prototype = me.self.prototype,
  4357. ownerPrototype,
  4358. tpl;
  4359. if (me.hasOwnProperty(name)) {
  4360. tpl = me[name];
  4361. if (tpl && !(tpl instanceof Ext.XTemplate)) {
  4362. me[name] = Ext.ClassManager.dynInstantiate('Ext.XTemplate', tpl);
  4363. }
  4364. return me[name];
  4365. }
  4366. if (!(prototype[name] instanceof Ext.XTemplate)) {
  4367. ownerPrototype = prototype;
  4368. do {
  4369. if (ownerPrototype.hasOwnProperty(name)) {
  4370. tpl = ownerPrototype[name];
  4371. if (tpl && !(tpl instanceof Ext.XTemplate)) {
  4372. ownerPrototype[name] = Ext.ClassManager.dynInstantiate('Ext.XTemplate', tpl);
  4373. break;
  4374. }
  4375. }
  4376. ownerPrototype = ownerPrototype.superclass;
  4377. } while (ownerPrototype);
  4378. }
  4379. return prototype[name];
  4380. },
  4381. /**
  4382. * Initializes the renderTpl.
  4383. * @return {Ext.XTemplate} The renderTpl XTemplate instance.
  4384. * @private
  4385. */
  4386. initRenderTpl: function() {
  4387. return this.getTpl('renderTpl');
  4388. },
  4389. /**
  4390. * Converts style definitions to String.
  4391. * @return {String} A CSS style string with style, padding, margin and border.
  4392. * @private
  4393. */
  4394. initStyles: function() {
  4395. var style = {},
  4396. me = this,
  4397. Element = Ext.Element;
  4398. if (Ext.isString(me.style)) {
  4399. style = Element.parseStyles(me.style);
  4400. } else {
  4401. style = Ext.apply({}, me.style);
  4402. }
  4403. // Convert the padding, margin and border properties from a space seperated string
  4404. // into a proper style string
  4405. if (me.padding !== undefined) {
  4406. style.padding = Element.unitizeBox((me.padding === true) ? 5 : me.padding);
  4407. }
  4408. if (me.margin !== undefined) {
  4409. style.margin = Element.unitizeBox((me.margin === true) ? 5 : me.margin);
  4410. }
  4411. delete me.style;
  4412. return style;
  4413. },
  4414. /**
  4415. * Initializes this components contents. It checks for the properties html, contentEl and tpl/data.
  4416. * @private
  4417. */
  4418. initContent: function() {
  4419. var me = this,
  4420. target = me.getTargetEl(),
  4421. contentEl,
  4422. pre;
  4423. if (me.html) {
  4424. target.update(Ext.DomHelper.markup(me.html));
  4425. delete me.html;
  4426. }
  4427. if (me.contentEl) {
  4428. contentEl = Ext.get(me.contentEl);
  4429. pre = Ext.baseCSSPrefix;
  4430. contentEl.removeCls([pre + 'hidden', pre + 'hide-display', pre + 'hide-offsets', pre + 'hide-nosize']);
  4431. target.appendChild(contentEl.dom);
  4432. }
  4433. if (me.tpl) {
  4434. // Make sure this.tpl is an instantiated XTemplate
  4435. if (!me.tpl.isTemplate) {
  4436. me.tpl = Ext.create('Ext.XTemplate', me.tpl);
  4437. }
  4438. if (me.data) {
  4439. me.tpl[me.tplWriteMode](target, me.data);
  4440. delete me.data;
  4441. }
  4442. }
  4443. },
  4444. // @private
  4445. initEvents : function() {
  4446. var me = this,
  4447. afterRenderEvents = me.afterRenderEvents,
  4448. el,
  4449. property,
  4450. fn = function(listeners){
  4451. me.mon(el, listeners);
  4452. };
  4453. if (afterRenderEvents) {
  4454. for (property in afterRenderEvents) {
  4455. if (afterRenderEvents.hasOwnProperty(property)) {
  4456. el = me[property];
  4457. if (el && el.on) {
  4458. Ext.each(afterRenderEvents[property], fn);
  4459. }
  4460. }
  4461. }
  4462. }
  4463. },
  4464. /**
  4465. * Adds each argument passed to this method to the {@link #childEls} array.
  4466. */
  4467. addChildEls: function () {
  4468. var me = this,
  4469. childEls = me.childEls || (me.childEls = []);
  4470. childEls.push.apply(childEls, arguments);
  4471. },
  4472. /**
  4473. * Removes items in the childEls array based on the return value of a supplied test function. The function is called
  4474. * with a entry in childEls and if the test function return true, that entry is removed. If false, that entry is
  4475. * kept.
  4476. * @param {Function} testFn The test function.
  4477. */
  4478. removeChildEls: function (testFn) {
  4479. var me = this,
  4480. old = me.childEls,
  4481. keepers = (me.childEls = []),
  4482. n, i, cel;
  4483. for (i = 0, n = old.length; i < n; ++i) {
  4484. cel = old[i];
  4485. if (!testFn(cel)) {
  4486. keepers.push(cel);
  4487. }
  4488. }
  4489. },
  4490. /**
  4491. * Sets references to elements inside the component. This applies {@link #renderSelectors}
  4492. * as well as {@link #childEls}.
  4493. * @private
  4494. */
  4495. applyRenderSelectors: function() {
  4496. var me = this,
  4497. childEls = me.childEls,
  4498. selectors = me.renderSelectors,
  4499. el = me.el,
  4500. dom = el.dom,
  4501. baseId, childName, childId, i, selector;
  4502. if (childEls) {
  4503. baseId = me.id + '-';
  4504. for (i = childEls.length; i--; ) {
  4505. childName = childId = childEls[i];
  4506. if (typeof(childName) != 'string') {
  4507. childId = childName.id || (baseId + childName.itemId);
  4508. childName = childName.name;
  4509. } else {
  4510. childId = baseId + childId;
  4511. }
  4512. // We don't use Ext.get because that is 3x (or more) slower on IE6-8. Since
  4513. // we know the el's are children of our el we use getById instead:
  4514. me[childName] = el.getById(childId);
  4515. }
  4516. }
  4517. // We still support renderSelectors. There are a few places in the framework that
  4518. // need them and they are a documented part of the API. In fact, we support mixing
  4519. // childEls and renderSelectors (no reason not to).
  4520. if (selectors) {
  4521. for (selector in selectors) {
  4522. if (selectors.hasOwnProperty(selector) && selectors[selector]) {
  4523. me[selector] = Ext.get(Ext.DomQuery.selectNode(selectors[selector], dom));
  4524. }
  4525. }
  4526. }
  4527. },
  4528. /**
  4529. * Tests whether this Component matches the selector string.
  4530. * @param {String} selector The selector string to test against.
  4531. * @return {Boolean} True if this Component matches the selector.
  4532. */
  4533. is: function(selector) {
  4534. return Ext.ComponentQuery.is(this, selector);
  4535. },
  4536. /**
  4537. * Walks up the `ownerCt` axis looking for an ancestor Container which matches the passed simple selector.
  4538. *
  4539. * Example:
  4540. *
  4541. * var owningTabPanel = grid.up('tabpanel');
  4542. *
  4543. * @param {String} [selector] The simple selector to test.
  4544. * @return {Ext.container.Container} The matching ancestor Container (or `undefined` if no match was found).
  4545. */
  4546. up: function(selector) {
  4547. var result = this.ownerCt;
  4548. if (selector) {
  4549. for (; result; result = result.ownerCt) {
  4550. if (Ext.ComponentQuery.is(result, selector)) {
  4551. return result;
  4552. }
  4553. }
  4554. }
  4555. return result;
  4556. },
  4557. /**
  4558. * Returns the next sibling of this Component.
  4559. *
  4560. * Optionally selects the next sibling which matches the passed {@link Ext.ComponentQuery ComponentQuery} selector.
  4561. *
  4562. * May also be refered to as **`next()`**
  4563. *
  4564. * Note that this is limited to siblings, and if no siblings of the item match, `null` is returned. Contrast with
  4565. * {@link #nextNode}
  4566. * @param {String} [selector] A {@link Ext.ComponentQuery ComponentQuery} selector to filter the following items.
  4567. * @return {Ext.Component} The next sibling (or the next sibling which matches the selector).
  4568. * Returns null if there is no matching sibling.
  4569. */
  4570. nextSibling: function(selector) {
  4571. var o = this.ownerCt, it, last, idx, c;
  4572. if (o) {
  4573. it = o.items;
  4574. idx = it.indexOf(this) + 1;
  4575. if (idx) {
  4576. if (selector) {
  4577. for (last = it.getCount(); idx < last; idx++) {
  4578. if ((c = it.getAt(idx)).is(selector)) {
  4579. return c;
  4580. }
  4581. }
  4582. } else {
  4583. if (idx < it.getCount()) {
  4584. return it.getAt(idx);
  4585. }
  4586. }
  4587. }
  4588. }
  4589. return null;
  4590. },
  4591. /**
  4592. * Returns the previous sibling of this Component.
  4593. *
  4594. * Optionally selects the previous sibling which matches the passed {@link Ext.ComponentQuery ComponentQuery}
  4595. * selector.
  4596. *
  4597. * May also be refered to as **`prev()`**
  4598. *
  4599. * Note that this is limited to siblings, and if no siblings of the item match, `null` is returned. Contrast with
  4600. * {@link #previousNode}
  4601. * @param {String} [selector] A {@link Ext.ComponentQuery ComponentQuery} selector to filter the preceding items.
  4602. * @return {Ext.Component} The previous sibling (or the previous sibling which matches the selector).
  4603. * Returns null if there is no matching sibling.
  4604. */
  4605. previousSibling: function(selector) {
  4606. var o = this.ownerCt, it, idx, c;
  4607. if (o) {
  4608. it = o.items;
  4609. idx = it.indexOf(this);
  4610. if (idx != -1) {
  4611. if (selector) {
  4612. for (--idx; idx >= 0; idx--) {
  4613. if ((c = it.getAt(idx)).is(selector)) {
  4614. return c;
  4615. }
  4616. }
  4617. } else {
  4618. if (idx) {
  4619. return it.getAt(--idx);
  4620. }
  4621. }
  4622. }
  4623. }
  4624. return null;
  4625. },
  4626. /**
  4627. * Returns the previous node in the Component tree in tree traversal order.
  4628. *
  4629. * Note that this is not limited to siblings, and if invoked upon a node with no matching siblings, will walk the
  4630. * tree in reverse order to attempt to find a match. Contrast with {@link #previousSibling}.
  4631. * @param {String} [selector] A {@link Ext.ComponentQuery ComponentQuery} selector to filter the preceding nodes.
  4632. * @return {Ext.Component} The previous node (or the previous node which matches the selector).
  4633. * Returns null if there is no matching node.
  4634. */
  4635. previousNode: function(selector, includeSelf) {
  4636. var node = this,
  4637. result,
  4638. it, len, i;
  4639. // If asked to include self, test me
  4640. if (includeSelf && node.is(selector)) {
  4641. return node;
  4642. }
  4643. result = this.prev(selector);
  4644. if (result) {
  4645. return result;
  4646. }
  4647. if (node.ownerCt) {
  4648. for (it = node.ownerCt.items.items, i = Ext.Array.indexOf(it, node) - 1; i > -1; i--) {
  4649. if (it[i].query) {
  4650. result = it[i].query(selector);
  4651. result = result[result.length - 1];
  4652. if (result) {
  4653. return result;
  4654. }
  4655. }
  4656. }
  4657. return node.ownerCt.previousNode(selector, true);
  4658. }
  4659. },
  4660. /**
  4661. * Returns the next node in the Component tree in tree traversal order.
  4662. *
  4663. * Note that this is not limited to siblings, and if invoked upon a node with no matching siblings, will walk the
  4664. * tree to attempt to find a match. Contrast with {@link #nextSibling}.
  4665. * @param {String} [selector] A {@link Ext.ComponentQuery ComponentQuery} selector to filter the following nodes.
  4666. * @return {Ext.Component} The next node (or the next node which matches the selector).
  4667. * Returns null if there is no matching node.
  4668. */
  4669. nextNode: function(selector, includeSelf) {
  4670. var node = this,
  4671. result,
  4672. it, len, i;
  4673. // If asked to include self, test me
  4674. if (includeSelf && node.is(selector)) {
  4675. return node;
  4676. }
  4677. result = this.next(selector);
  4678. if (result) {
  4679. return result;
  4680. }
  4681. if (node.ownerCt) {
  4682. for (it = node.ownerCt.items, i = it.indexOf(node) + 1, it = it.items, len = it.length; i < len; i++) {
  4683. if (it[i].down) {
  4684. result = it[i].down(selector);
  4685. if (result) {
  4686. return result;
  4687. }
  4688. }
  4689. }
  4690. return node.ownerCt.nextNode(selector);
  4691. }
  4692. },
  4693. /**
  4694. * Retrieves the id of this component. Will autogenerate an id if one has not already been set.
  4695. * @return {String}
  4696. */
  4697. getId : function() {
  4698. return this.id || (this.id = 'ext-comp-' + (this.getAutoId()));
  4699. },
  4700. getItemId : function() {
  4701. return this.itemId || this.id;
  4702. },
  4703. /**
  4704. * Retrieves the top level element representing this component.
  4705. * @return {Ext.core.Element}
  4706. */
  4707. getEl : function() {
  4708. return this.el;
  4709. },
  4710. /**
  4711. * This is used to determine where to insert the 'html', 'contentEl' and 'items' in this component.
  4712. * @private
  4713. */
  4714. getTargetEl: function() {
  4715. return this.frameBody || this.el;
  4716. },
  4717. /**
  4718. * Tests whether or not this Component is of a specific xtype. This can test whether this Component is descended
  4719. * from the xtype (default) or whether it is directly of the xtype specified (shallow = true).
  4720. *
  4721. * **If using your own subclasses, be aware that a Component must register its own xtype to participate in
  4722. * determination of inherited xtypes.**
  4723. *
  4724. * For a list of all available xtypes, see the {@link Ext.Component} header.
  4725. *
  4726. * Example usage:
  4727. *
  4728. * var t = new Ext.form.field.Text();
  4729. * var isText = t.isXType('textfield'); // true
  4730. * var isBoxSubclass = t.isXType('field'); // true, descended from Ext.form.field.Base
  4731. * var isBoxInstance = t.isXType('field', true); // false, not a direct Ext.form.field.Base instance
  4732. *
  4733. * @param {String} xtype The xtype to check for this Component
  4734. * @param {Boolean} [shallow=false] True to check whether this Component is directly of the specified xtype, false to
  4735. * check whether this Component is descended from the xtype.
  4736. * @return {Boolean} True if this component descends from the specified xtype, false otherwise.
  4737. */
  4738. isXType: function(xtype, shallow) {
  4739. //assume a string by default
  4740. if (Ext.isFunction(xtype)) {
  4741. xtype = xtype.xtype;
  4742. //handle being passed the class, e.g. Ext.Component
  4743. } else if (Ext.isObject(xtype)) {
  4744. xtype = xtype.statics().xtype;
  4745. //handle being passed an instance
  4746. }
  4747. return !shallow ? ('/' + this.getXTypes() + '/').indexOf('/' + xtype + '/') != -1: this.self.xtype == xtype;
  4748. },
  4749. /**
  4750. * Returns this Component's xtype hierarchy as a slash-delimited string. For a list of all available xtypes, see the
  4751. * {@link Ext.Component} header.
  4752. *
  4753. * **If using your own subclasses, be aware that a Component must register its own xtype to participate in
  4754. * determination of inherited xtypes.**
  4755. *
  4756. * Example usage:
  4757. *
  4758. * var t = new Ext.form.field.Text();
  4759. * alert(t.getXTypes()); // alerts 'component/field/textfield'
  4760. *
  4761. * @return {String} The xtype hierarchy string
  4762. */
  4763. getXTypes: function() {
  4764. var self = this.self,
  4765. xtypes, parentPrototype, parentXtypes;
  4766. if (!self.xtypes) {
  4767. xtypes = [];
  4768. parentPrototype = this;
  4769. while (parentPrototype) {
  4770. parentXtypes = parentPrototype.xtypes;
  4771. if (parentXtypes !== undefined) {
  4772. xtypes.unshift.apply(xtypes, parentXtypes);
  4773. }
  4774. parentPrototype = parentPrototype.superclass;
  4775. }
  4776. self.xtypeChain = xtypes;
  4777. self.xtypes = xtypes.join('/');
  4778. }
  4779. return self.xtypes;
  4780. },
  4781. /**
  4782. * Update the content area of a component.
  4783. * @param {String/Object} htmlOrData If this component has been configured with a template via the tpl config then
  4784. * it will use this argument as data to populate the template. If this component was not configured with a template,
  4785. * the components content area will be updated via Ext.Element update
  4786. * @param {Boolean} [loadScripts=false] Only legitimate when using the html configuration.
  4787. * @param {Function} [callback] Only legitimate when using the html configuration. Callback to execute when
  4788. * scripts have finished loading
  4789. */
  4790. update : function(htmlOrData, loadScripts, cb) {
  4791. var me = this;
  4792. if (me.tpl && !Ext.isString(htmlOrData)) {
  4793. me.data = htmlOrData;
  4794. if (me.rendered) {
  4795. me.tpl[me.tplWriteMode](me.getTargetEl(), htmlOrData || {});
  4796. }
  4797. } else {
  4798. me.html = Ext.isObject(htmlOrData) ? Ext.DomHelper.markup(htmlOrData) : htmlOrData;
  4799. if (me.rendered) {
  4800. me.getTargetEl().update(me.html, loadScripts, cb);
  4801. }
  4802. }
  4803. if (me.rendered) {
  4804. me.doComponentLayout();
  4805. }
  4806. },
  4807. /**
  4808. * Convenience function to hide or show this component by boolean.
  4809. * @param {Boolean} visible True to show, false to hide
  4810. * @return {Ext.Component} this
  4811. */
  4812. setVisible : function(visible) {
  4813. return this[visible ? 'show': 'hide']();
  4814. },
  4815. /**
  4816. * Returns true if this component is visible.
  4817. *
  4818. * @param {Boolean} [deep=false] Pass `true` to interrogate the visibility status of all parent Containers to
  4819. * determine whether this Component is truly visible to the user.
  4820. *
  4821. * Generally, to determine whether a Component is hidden, the no argument form is needed. For example when creating
  4822. * dynamically laid out UIs in a hidden Container before showing them.
  4823. *
  4824. * @return {Boolean} True if this component is visible, false otherwise.
  4825. */
  4826. isVisible: function(deep) {
  4827. var me = this,
  4828. child = me,
  4829. visible = !me.hidden,
  4830. ancestor = me.ownerCt;
  4831. // Clear hiddenOwnerCt property
  4832. me.hiddenAncestor = false;
  4833. if (me.destroyed) {
  4834. return false;
  4835. }
  4836. if (deep && visible && me.rendered && ancestor) {
  4837. while (ancestor) {
  4838. // If any ancestor is hidden, then this is hidden.
  4839. // If an ancestor Panel (only Panels have a collapse method) is collapsed,
  4840. // then its layoutTarget (body) is hidden, so this is hidden unless its within a
  4841. // docked item; they are still visible when collapsed (Unless they themseves are hidden)
  4842. if (ancestor.hidden || (ancestor.collapsed &&
  4843. !(ancestor.getDockedItems && Ext.Array.contains(ancestor.getDockedItems(), child)))) {
  4844. // Store hiddenOwnerCt property if needed
  4845. me.hiddenAncestor = ancestor;
  4846. visible = false;
  4847. break;
  4848. }
  4849. child = ancestor;
  4850. ancestor = ancestor.ownerCt;
  4851. }
  4852. }
  4853. return visible;
  4854. },
  4855. /**
  4856. * Enable the component
  4857. * @param {Boolean} [silent=false] Passing true will supress the 'enable' event from being fired.
  4858. */
  4859. enable: function(silent) {
  4860. var me = this;
  4861. if (me.rendered) {
  4862. me.el.removeCls(me.disabledCls);
  4863. me.el.dom.disabled = false;
  4864. me.onEnable();
  4865. }
  4866. me.disabled = false;
  4867. if (silent !== true) {
  4868. me.fireEvent('enable', me);
  4869. }
  4870. return me;
  4871. },
  4872. /**
  4873. * Disable the component.
  4874. * @param {Boolean} [silent=false] Passing true will supress the 'disable' event from being fired.
  4875. */
  4876. disable: function(silent) {
  4877. var me = this;
  4878. if (me.rendered) {
  4879. me.el.addCls(me.disabledCls);
  4880. me.el.dom.disabled = true;
  4881. me.onDisable();
  4882. }
  4883. me.disabled = true;
  4884. if (silent !== true) {
  4885. me.fireEvent('disable', me);
  4886. }
  4887. return me;
  4888. },
  4889. // @private
  4890. onEnable: function() {
  4891. if (this.maskOnDisable) {
  4892. this.el.unmask();
  4893. }
  4894. },
  4895. // @private
  4896. onDisable : function() {
  4897. if (this.maskOnDisable) {
  4898. this.el.mask();
  4899. }
  4900. },
  4901. /**
  4902. * Method to determine whether this Component is currently disabled.
  4903. * @return {Boolean} the disabled state of this Component.
  4904. */
  4905. isDisabled : function() {
  4906. return this.disabled;
  4907. },
  4908. /**
  4909. * Enable or disable the component.
  4910. * @param {Boolean} disabled True to disable.
  4911. */
  4912. setDisabled : function(disabled) {
  4913. return this[disabled ? 'disable': 'enable']();
  4914. },
  4915. /**
  4916. * Method to determine whether this Component is currently set to hidden.
  4917. * @return {Boolean} the hidden state of this Component.
  4918. */
  4919. isHidden : function() {
  4920. return this.hidden;
  4921. },
  4922. /**
  4923. * Adds a CSS class to the top level element representing this component.
  4924. * @param {String} cls The CSS class name to add
  4925. * @return {Ext.Component} Returns the Component to allow method chaining.
  4926. */
  4927. addCls : function(className) {
  4928. var me = this;
  4929. if (!className) {
  4930. return me;
  4931. }
  4932. if (!Ext.isArray(className)){
  4933. className = className.replace(me.trimRe, '').split(me.spacesRe);
  4934. }
  4935. if (me.rendered) {
  4936. me.el.addCls(className);
  4937. }
  4938. else {
  4939. me.additionalCls = Ext.Array.unique(me.additionalCls.concat(className));
  4940. }
  4941. return me;
  4942. },
  4943. /**
  4944. * Adds a CSS class to the top level element representing this component.
  4945. * @param {String} cls The CSS class name to add
  4946. * @return {Ext.Component} Returns the Component to allow method chaining.
  4947. */
  4948. addClass : function() {
  4949. return this.addCls.apply(this, arguments);
  4950. },
  4951. /**
  4952. * Removes a CSS class from the top level element representing this component.
  4953. * @param {Object} className
  4954. * @return {Ext.Component} Returns the Component to allow method chaining.
  4955. */
  4956. removeCls : function(className) {
  4957. var me = this;
  4958. if (!className) {
  4959. return me;
  4960. }
  4961. if (!Ext.isArray(className)){
  4962. className = className.replace(me.trimRe, '').split(me.spacesRe);
  4963. }
  4964. if (me.rendered) {
  4965. me.el.removeCls(className);
  4966. }
  4967. else if (me.additionalCls.length) {
  4968. Ext.each(className, function(cls) {
  4969. Ext.Array.remove(me.additionalCls, cls);
  4970. });
  4971. }
  4972. return me;
  4973. },
  4974. //<debug>
  4975. removeClass : function() {
  4976. if (Ext.isDefined(Ext.global.console)) {
  4977. Ext.global.console.warn('Ext.Component: removeClass has been deprecated. Please use removeCls.');
  4978. }
  4979. return this.removeCls.apply(this, arguments);
  4980. },
  4981. //</debug>
  4982. addOverCls: function() {
  4983. var me = this;
  4984. if (!me.disabled) {
  4985. me.el.addCls(me.overCls);
  4986. }
  4987. },
  4988. removeOverCls: function() {
  4989. this.el.removeCls(this.overCls);
  4990. },
  4991. addListener : function(element, listeners, scope, options) {
  4992. var me = this,
  4993. fn,
  4994. option;
  4995. if (Ext.isString(element) && (Ext.isObject(listeners) || options && options.element)) {
  4996. if (options.element) {
  4997. fn = listeners;
  4998. listeners = {};
  4999. listeners[element] = fn;
  5000. element = options.element;
  5001. if (scope) {
  5002. listeners.scope = scope;
  5003. }
  5004. for (option in options) {
  5005. if (options.hasOwnProperty(option)) {
  5006. if (me.eventOptionsRe.test(option)) {
  5007. listeners[option] = options[option];
  5008. }
  5009. }
  5010. }
  5011. }
  5012. // At this point we have a variable called element,
  5013. // and a listeners object that can be passed to on
  5014. if (me[element] && me[element].on) {
  5015. me.mon(me[element], listeners);
  5016. } else {
  5017. me.afterRenderEvents = me.afterRenderEvents || {};
  5018. if (!me.afterRenderEvents[element]) {
  5019. me.afterRenderEvents[element] = [];
  5020. }
  5021. me.afterRenderEvents[element].push(listeners);
  5022. }
  5023. }
  5024. return me.mixins.observable.addListener.apply(me, arguments);
  5025. },
  5026. // inherit docs
  5027. removeManagedListenerItem: function(isClear, managedListener, item, ename, fn, scope){
  5028. var me = this,
  5029. element = managedListener.options ? managedListener.options.element : null;
  5030. if (element) {
  5031. element = me[element];
  5032. if (element && element.un) {
  5033. if (isClear || (managedListener.item === item && managedListener.ename === ename && (!fn || managedListener.fn === fn) && (!scope || managedListener.scope === scope))) {
  5034. element.un(managedListener.ename, managedListener.fn, managedListener.scope);
  5035. if (!isClear) {
  5036. Ext.Array.remove(me.managedListeners, managedListener);
  5037. }
  5038. }
  5039. }
  5040. } else {
  5041. return me.mixins.observable.removeManagedListenerItem.apply(me, arguments);
  5042. }
  5043. },
  5044. /**
  5045. * Provides the link for Observable's fireEvent method to bubble up the ownership hierarchy.
  5046. * @return {Ext.container.Container} the Container which owns this Component.
  5047. */
  5048. getBubbleTarget : function() {
  5049. return this.ownerCt;
  5050. },
  5051. /**
  5052. * Method to determine whether this Component is floating.
  5053. * @return {Boolean} the floating state of this component.
  5054. */
  5055. isFloating : function() {
  5056. return this.floating;
  5057. },
  5058. /**
  5059. * Method to determine whether this Component is draggable.
  5060. * @return {Boolean} the draggable state of this component.
  5061. */
  5062. isDraggable : function() {
  5063. return !!this.draggable;
  5064. },
  5065. /**
  5066. * Method to determine whether this Component is droppable.
  5067. * @return {Boolean} the droppable state of this component.
  5068. */
  5069. isDroppable : function() {
  5070. return !!this.droppable;
  5071. },
  5072. /**
  5073. * @private
  5074. * Method to manage awareness of when components are added to their
  5075. * respective Container, firing an added event.
  5076. * References are established at add time rather than at render time.
  5077. * @param {Ext.container.Container} container Container which holds the component
  5078. * @param {Number} pos Position at which the component was added
  5079. */
  5080. onAdded : function(container, pos) {
  5081. this.ownerCt = container;
  5082. this.fireEvent('added', this, container, pos);
  5083. },
  5084. /**
  5085. * @private
  5086. * Method to manage awareness of when components are removed from their
  5087. * respective Container, firing an removed event. References are properly
  5088. * cleaned up after removing a component from its owning container.
  5089. */
  5090. onRemoved : function() {
  5091. var me = this;
  5092. me.fireEvent('removed', me, me.ownerCt);
  5093. delete me.ownerCt;
  5094. },
  5095. // @private
  5096. beforeDestroy : Ext.emptyFn,
  5097. // @private
  5098. // @private
  5099. onResize : Ext.emptyFn,
  5100. /**
  5101. * Sets the width and height of this Component. This method fires the {@link #resize} event. This method can accept
  5102. * either width and height as separate arguments, or you can pass a size object like `{width:10, height:20}`.
  5103. *
  5104. * @param {Number/String/Object} width The new width to set. This may be one of:
  5105. *
  5106. * - A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).
  5107. * - A String used to set the CSS width style.
  5108. * - A size object in the format `{width: widthValue, height: heightValue}`.
  5109. * - `undefined` to leave the width unchanged.
  5110. *
  5111. * @param {Number/String} height The new height to set (not required if a size object is passed as the first arg).
  5112. * This may be one of:
  5113. *
  5114. * - A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).
  5115. * - A String used to set the CSS height style. Animation may **not** be used.
  5116. * - `undefined` to leave the height unchanged.
  5117. *
  5118. * @return {Ext.Component} this
  5119. */
  5120. setSize : function(width, height) {
  5121. var me = this,
  5122. layoutCollection;
  5123. // support for standard size objects
  5124. if (Ext.isObject(width)) {
  5125. height = width.height;
  5126. width = width.width;
  5127. }
  5128. // Constrain within configured maxima
  5129. if (Ext.isNumber(width)) {
  5130. width = Ext.Number.constrain(width, me.minWidth, me.maxWidth);
  5131. }
  5132. if (Ext.isNumber(height)) {
  5133. height = Ext.Number.constrain(height, me.minHeight, me.maxHeight);
  5134. }
  5135. if (!me.rendered || !me.isVisible()) {
  5136. // If an ownerCt is hidden, add my reference onto the layoutOnShow stack. Set the needsLayout flag.
  5137. if (me.hiddenAncestor) {
  5138. layoutCollection = me.hiddenAncestor.layoutOnShow;
  5139. layoutCollection.remove(me);
  5140. layoutCollection.add(me);
  5141. }
  5142. me.needsLayout = {
  5143. width: width,
  5144. height: height,
  5145. isSetSize: true
  5146. };
  5147. if (!me.rendered) {
  5148. me.width = (width !== undefined) ? width : me.width;
  5149. me.height = (height !== undefined) ? height : me.height;
  5150. }
  5151. return me;
  5152. }
  5153. me.doComponentLayout(width, height, true);
  5154. return me;
  5155. },
  5156. isFixedWidth: function() {
  5157. var me = this,
  5158. layoutManagedWidth = me.layoutManagedWidth;
  5159. if (Ext.isDefined(me.width) || layoutManagedWidth == 1) {
  5160. return true;
  5161. }
  5162. if (layoutManagedWidth == 2) {
  5163. return false;
  5164. }
  5165. return (me.ownerCt && me.ownerCt.isFixedWidth());
  5166. },
  5167. isFixedHeight: function() {
  5168. var me = this,
  5169. layoutManagedHeight = me.layoutManagedHeight;
  5170. if (Ext.isDefined(me.height) || layoutManagedHeight == 1) {
  5171. return true;
  5172. }
  5173. if (layoutManagedHeight == 2) {
  5174. return false;
  5175. }
  5176. return (me.ownerCt && me.ownerCt.isFixedHeight());
  5177. },
  5178. setCalculatedSize : function(width, height, callingContainer) {
  5179. var me = this,
  5180. layoutCollection;
  5181. // support for standard size objects
  5182. if (Ext.isObject(width)) {
  5183. callingContainer = width.ownerCt;
  5184. height = width.height;
  5185. width = width.width;
  5186. }
  5187. // Constrain within configured maxima
  5188. if (Ext.isNumber(width)) {
  5189. width = Ext.Number.constrain(width, me.minWidth, me.maxWidth);
  5190. }
  5191. if (Ext.isNumber(height)) {
  5192. height = Ext.Number.constrain(height, me.minHeight, me.maxHeight);
  5193. }
  5194. if (!me.rendered || !me.isVisible()) {
  5195. // If an ownerCt is hidden, add my reference onto the layoutOnShow stack. Set the needsLayout flag.
  5196. if (me.hiddenAncestor) {
  5197. layoutCollection = me.hiddenAncestor.layoutOnShow;
  5198. layoutCollection.remove(me);
  5199. layoutCollection.add(me);
  5200. }
  5201. me.needsLayout = {
  5202. width: width,
  5203. height: height,
  5204. isSetSize: false,
  5205. ownerCt: callingContainer
  5206. };
  5207. return me;
  5208. }
  5209. me.doComponentLayout(width, height, false, callingContainer);
  5210. return me;
  5211. },
  5212. /**
  5213. * This method needs to be called whenever you change something on this component that requires the Component's
  5214. * layout to be recalculated.
  5215. * @param {Object} width
  5216. * @param {Object} height
  5217. * @param {Object} isSetSize
  5218. * @param {Object} callingContainer
  5219. * @return {Ext.container.Container} this
  5220. */
  5221. doComponentLayout : function(width, height, isSetSize, callingContainer) {
  5222. var me = this,
  5223. componentLayout = me.getComponentLayout(),
  5224. lastComponentSize = componentLayout.lastComponentSize || {
  5225. width: undefined,
  5226. height: undefined
  5227. };
  5228. // collapsed state is not relevant here, so no testing done.
  5229. // Only Panels have a collapse method, and that just sets the width/height such that only
  5230. // a single docked Header parallel to the collapseTo side are visible, and the Panel body is hidden.
  5231. if (me.rendered && componentLayout) {
  5232. // If no width passed, then only insert a value if the Component is NOT ALLOWED to autowidth itself.
  5233. if (!Ext.isDefined(width)) {
  5234. if (me.isFixedWidth()) {
  5235. width = Ext.isDefined(me.width) ? me.width : lastComponentSize.width;
  5236. }
  5237. }
  5238. // If no height passed, then only insert a value if the Component is NOT ALLOWED to autoheight itself.
  5239. if (!Ext.isDefined(height)) {
  5240. if (me.isFixedHeight()) {
  5241. height = Ext.isDefined(me.height) ? me.height : lastComponentSize.height;
  5242. }
  5243. }
  5244. if (isSetSize) {
  5245. me.width = width;
  5246. me.height = height;
  5247. }
  5248. componentLayout.layout(width, height, isSetSize, callingContainer);
  5249. }
  5250. return me;
  5251. },
  5252. /**
  5253. * Forces this component to redo its componentLayout.
  5254. */
  5255. forceComponentLayout: function () {
  5256. this.doComponentLayout();
  5257. },
  5258. // @private
  5259. setComponentLayout : function(layout) {
  5260. var currentLayout = this.componentLayout;
  5261. if (currentLayout && currentLayout.isLayout && currentLayout != layout) {
  5262. currentLayout.setOwner(null);
  5263. }
  5264. this.componentLayout = layout;
  5265. layout.setOwner(this);
  5266. },
  5267. getComponentLayout : function() {
  5268. var me = this;
  5269. if (!me.componentLayout || !me.componentLayout.isLayout) {
  5270. me.setComponentLayout(Ext.layout.Layout.create(me.componentLayout, 'autocomponent'));
  5271. }
  5272. return me.componentLayout;
  5273. },
  5274. /**
  5275. * Occurs after componentLayout is run.
  5276. * @param {Number} adjWidth The box-adjusted width that was set
  5277. * @param {Number} adjHeight The box-adjusted height that was set
  5278. * @param {Boolean} isSetSize Whether or not the height/width are stored on the component permanently
  5279. * @param {Ext.Component} callingContainer Container requesting the layout. Only used when isSetSize is false.
  5280. */
  5281. afterComponentLayout: function(width, height, isSetSize, callingContainer) {
  5282. var me = this,
  5283. layout = me.componentLayout,
  5284. oldSize = me.preLayoutSize;
  5285. ++me.componentLayoutCounter;
  5286. if (!oldSize || ((width !== oldSize.width) || (height !== oldSize.height))) {
  5287. me.fireEvent('resize', me, width, height);
  5288. }
  5289. },
  5290. /**
  5291. * Occurs before componentLayout is run. Returning false from this method will prevent the componentLayout from
  5292. * being executed.
  5293. * @param {Number} adjWidth The box-adjusted width that was set
  5294. * @param {Number} adjHeight The box-adjusted height that was set
  5295. * @param {Boolean} isSetSize Whether or not the height/width are stored on the component permanently
  5296. * @param {Ext.Component} callingContainer Container requesting sent the layout. Only used when isSetSize is false.
  5297. */
  5298. beforeComponentLayout: function(width, height, isSetSize, callingContainer) {
  5299. this.preLayoutSize = this.componentLayout.lastComponentSize;
  5300. return true;
  5301. },
  5302. /**
  5303. * Sets the left and top of the component. To set the page XY position instead, use
  5304. * {@link Ext.Component#setPagePosition setPagePosition}. This method fires the {@link #move} event.
  5305. * @param {Number} left The new left
  5306. * @param {Number} top The new top
  5307. * @return {Ext.Component} this
  5308. */
  5309. setPosition : function(x, y) {
  5310. var me = this;
  5311. if (Ext.isObject(x)) {
  5312. y = x.y;
  5313. x = x.x;
  5314. }
  5315. if (!me.rendered) {
  5316. return me;
  5317. }
  5318. if (x !== undefined || y !== undefined) {
  5319. me.el.setBox(x, y);
  5320. me.onPosition(x, y);
  5321. me.fireEvent('move', me, x, y);
  5322. }
  5323. return me;
  5324. },
  5325. /**
  5326. * @private
  5327. * Called after the component is moved, this method is empty by default but can be implemented by any
  5328. * subclass that needs to perform custom logic after a move occurs.
  5329. * @param {Number} x The new x position
  5330. * @param {Number} y The new y position
  5331. */
  5332. onPosition: Ext.emptyFn,
  5333. /**
  5334. * Sets the width of the component. This method fires the {@link #resize} event.
  5335. *
  5336. * @param {Number} width The new width to setThis may be one of:
  5337. *
  5338. * - A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).
  5339. * - A String used to set the CSS width style.
  5340. *
  5341. * @return {Ext.Component} this
  5342. */
  5343. setWidth : function(width) {
  5344. return this.setSize(width);
  5345. },
  5346. /**
  5347. * Sets the height of the component. This method fires the {@link #resize} event.
  5348. *
  5349. * @param {Number} height The new height to set. This may be one of:
  5350. *
  5351. * - A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).
  5352. * - A String used to set the CSS height style.
  5353. * - _undefined_ to leave the height unchanged.
  5354. *
  5355. * @return {Ext.Component} this
  5356. */
  5357. setHeight : function(height) {
  5358. return this.setSize(undefined, height);
  5359. },
  5360. /**
  5361. * Gets the current size of the component's underlying element.
  5362. * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
  5363. */
  5364. getSize : function() {
  5365. return this.el.getSize();
  5366. },
  5367. /**
  5368. * Gets the current width of the component's underlying element.
  5369. * @return {Number}
  5370. */
  5371. getWidth : function() {
  5372. return this.el.getWidth();
  5373. },
  5374. /**
  5375. * Gets the current height of the component's underlying element.
  5376. * @return {Number}
  5377. */
  5378. getHeight : function() {
  5379. return this.el.getHeight();
  5380. },
  5381. /**
  5382. * Gets the {@link Ext.ComponentLoader} for this Component.
  5383. * @return {Ext.ComponentLoader} The loader instance, null if it doesn't exist.
  5384. */
  5385. getLoader: function(){
  5386. var me = this,
  5387. autoLoad = me.autoLoad ? (Ext.isObject(me.autoLoad) ? me.autoLoad : {url: me.autoLoad}) : null,
  5388. loader = me.loader || autoLoad;
  5389. if (loader) {
  5390. if (!loader.isLoader) {
  5391. me.loader = Ext.create('Ext.ComponentLoader', Ext.apply({
  5392. target: me,
  5393. autoLoad: autoLoad
  5394. }, loader));
  5395. } else {
  5396. loader.setTarget(me);
  5397. }
  5398. return me.loader;
  5399. }
  5400. return null;
  5401. },
  5402. /**
  5403. * This method allows you to show or hide a LoadMask on top of this component.
  5404. *
  5405. * @param {Boolean/Object/String} load True to show the default LoadMask, a config object that will be passed to the
  5406. * LoadMask constructor, or a message String to show. False to hide the current LoadMask.
  5407. * @param {Boolean} [targetEl=false] True to mask the targetEl of this Component instead of the `this.el`. For example,
  5408. * setting this to true on a Panel will cause only the body to be masked.
  5409. * @return {Ext.LoadMask} The LoadMask instance that has just been shown.
  5410. */
  5411. setLoading : function(load, targetEl) {
  5412. var me = this,
  5413. config;
  5414. if (me.rendered) {
  5415. if (load !== false && !me.collapsed) {
  5416. if (Ext.isObject(load)) {
  5417. config = load;
  5418. }
  5419. else if (Ext.isString(load)) {
  5420. config = {msg: load};
  5421. }
  5422. else {
  5423. config = {};
  5424. }
  5425. me.loadMask = me.loadMask || Ext.create('Ext.LoadMask', targetEl ? me.getTargetEl() : me.el, config);
  5426. me.loadMask.show();
  5427. } else if (me.loadMask) {
  5428. Ext.destroy(me.loadMask);
  5429. me.loadMask = null;
  5430. }
  5431. }
  5432. return me.loadMask;
  5433. },
  5434. /**
  5435. * Sets the dock position of this component in its parent panel. Note that this only has effect if this item is part
  5436. * of the dockedItems collection of a parent that has a DockLayout (note that any Panel has a DockLayout by default)
  5437. * @param {Object} dock The dock position.
  5438. * @param {Boolean} [layoutParent=false] True to re-layout parent.
  5439. * @return {Ext.Component} this
  5440. */
  5441. setDocked : function(dock, layoutParent) {
  5442. var me = this;
  5443. me.dock = dock;
  5444. if (layoutParent && me.ownerCt && me.rendered) {
  5445. me.ownerCt.doComponentLayout();
  5446. }
  5447. return me;
  5448. },
  5449. onDestroy : function() {
  5450. var me = this;
  5451. if (me.monitorResize && Ext.EventManager.resizeEvent) {
  5452. Ext.EventManager.resizeEvent.removeListener(me.setSize, me);
  5453. }
  5454. // Destroying the floatingItems ZIndexManager will also destroy descendant floating Components
  5455. Ext.destroy(
  5456. me.componentLayout,
  5457. me.loadMask,
  5458. me.floatingItems
  5459. );
  5460. },
  5461. /**
  5462. * Remove any references to elements added via renderSelectors/childEls
  5463. * @private
  5464. */
  5465. cleanElementRefs: function(){
  5466. var me = this,
  5467. i = 0,
  5468. childEls = me.childEls,
  5469. selectors = me.renderSelectors,
  5470. selector,
  5471. name,
  5472. len;
  5473. if (me.rendered) {
  5474. if (childEls) {
  5475. for (len = childEls.length; i < len; ++i) {
  5476. name = childEls[i];
  5477. if (typeof(name) != 'string') {
  5478. name = name.name;
  5479. }
  5480. delete me[name];
  5481. }
  5482. }
  5483. if (selectors) {
  5484. for (selector in selectors) {
  5485. if (selectors.hasOwnProperty(selector)) {
  5486. delete me[selector];
  5487. }
  5488. }
  5489. }
  5490. }
  5491. delete me.rendered;
  5492. delete me.el;
  5493. delete me.frameBody;
  5494. },
  5495. /**
  5496. * Destroys the Component.
  5497. */
  5498. destroy : function() {
  5499. var me = this;
  5500. if (!me.isDestroyed) {
  5501. if (me.fireEvent('beforedestroy', me) !== false) {
  5502. me.destroying = true;
  5503. me.beforeDestroy();
  5504. if (me.floating) {
  5505. delete me.floatParent;
  5506. // A zIndexManager is stamped into a *floating* Component when it is added to a Container.
  5507. // If it has no zIndexManager at render time, it is assigned to the global Ext.WindowManager instance.
  5508. if (me.zIndexManager) {
  5509. me.zIndexManager.unregister(me);
  5510. }
  5511. } else if (me.ownerCt && me.ownerCt.remove) {
  5512. me.ownerCt.remove(me, false);
  5513. }
  5514. me.onDestroy();
  5515. // Attempt to destroy all plugins
  5516. Ext.destroy(me.plugins);
  5517. if (me.rendered) {
  5518. me.el.remove();
  5519. }
  5520. me.fireEvent('destroy', me);
  5521. Ext.ComponentManager.unregister(me);
  5522. me.mixins.state.destroy.call(me);
  5523. me.clearListeners();
  5524. // make sure we clean up the element references after removing all events
  5525. me.cleanElementRefs();
  5526. me.destroying = false;
  5527. me.isDestroyed = true;
  5528. }
  5529. }
  5530. },
  5531. /**
  5532. * Retrieves a plugin by its pluginId which has been bound to this component.
  5533. * @param {Object} pluginId
  5534. * @return {Ext.AbstractPlugin} plugin instance.
  5535. */
  5536. getPlugin: function(pluginId) {
  5537. var i = 0,
  5538. plugins = this.plugins,
  5539. ln = plugins.length;
  5540. for (; i < ln; i++) {
  5541. if (plugins[i].pluginId === pluginId) {
  5542. return plugins[i];
  5543. }
  5544. }
  5545. },
  5546. /**
  5547. * Determines whether this component is the descendant of a particular container.
  5548. * @param {Ext.Container} container
  5549. * @return {Boolean} True if it is.
  5550. */
  5551. isDescendantOf: function(container) {
  5552. return !!this.findParentBy(function(p){
  5553. return p === container;
  5554. });
  5555. }
  5556. }, function() {
  5557. this.createAlias({
  5558. on: 'addListener',
  5559. prev: 'previousSibling',
  5560. next: 'nextSibling'
  5561. });
  5562. });
  5563. /**
  5564. * The AbstractPlugin class is the base class from which user-implemented plugins should inherit.
  5565. *
  5566. * This class defines the essential API of plugins as used by Components by defining the following methods:
  5567. *
  5568. * - `init` : The plugin initialization method which the owning Component calls at Component initialization time.
  5569. *
  5570. * The Component passes itself as the sole parameter.
  5571. *
  5572. * Subclasses should set up bidirectional links between the plugin and its client Component here.
  5573. *
  5574. * - `destroy` : The plugin cleanup method which the owning Component calls at Component destruction time.
  5575. *
  5576. * Use this method to break links between the plugin and the Component and to free any allocated resources.
  5577. *
  5578. * - `enable` : The base implementation just sets the plugin's `disabled` flag to `false`
  5579. *
  5580. * - `disable` : The base implementation just sets the plugin's `disabled` flag to `true`
  5581. */
  5582. Ext.define('Ext.AbstractPlugin', {
  5583. disabled: false,
  5584. constructor: function(config) {
  5585. //<debug>
  5586. if (!config.cmp && Ext.global.console) {
  5587. Ext.global.console.warn("Attempted to attach a plugin ");
  5588. }
  5589. //</debug>
  5590. Ext.apply(this, config);
  5591. },
  5592. getCmp: function() {
  5593. return this.cmp;
  5594. },
  5595. /**
  5596. * @method
  5597. * The init method is invoked after initComponent method has been run for the client Component.
  5598. *
  5599. * The supplied implementation is empty. Subclasses should perform plugin initialization, and set up bidirectional
  5600. * links between the plugin and its client Component in their own implementation of this method.
  5601. * @param {Ext.Component} client The client Component which owns this plugin.
  5602. */
  5603. init: Ext.emptyFn,
  5604. /**
  5605. * @method
  5606. * The destroy method is invoked by the owning Component at the time the Component is being destroyed.
  5607. *
  5608. * The supplied implementation is empty. Subclasses should perform plugin cleanup in their own implementation of
  5609. * this method.
  5610. */
  5611. destroy: Ext.emptyFn,
  5612. /**
  5613. * The base implementation just sets the plugin's `disabled` flag to `false`
  5614. *
  5615. * Plugin subclasses which need more complex processing may implement an overriding implementation.
  5616. */
  5617. enable: function() {
  5618. this.disabled = false;
  5619. },
  5620. /**
  5621. * The base implementation just sets the plugin's `disabled` flag to `true`
  5622. *
  5623. * Plugin subclasses which need more complex processing may implement an overriding implementation.
  5624. */
  5625. disable: function() {
  5626. this.disabled = true;
  5627. }
  5628. });
  5629. /**
  5630. * The Connection class encapsulates a connection to the page's originating domain, allowing requests to be made either
  5631. * to a configured URL, or to a URL specified at request time.
  5632. *
  5633. * Requests made by this class are asynchronous, and will return immediately. No data from the server will be available
  5634. * to the statement immediately following the {@link #request} call. To process returned data, use a success callback
  5635. * in the request options object, or an {@link #requestcomplete event listener}.
  5636. *
  5637. * # File Uploads
  5638. *
  5639. * File uploads are not performed using normal "Ajax" techniques, that is they are not performed using XMLHttpRequests.
  5640. * Instead the form is submitted in the standard manner with the DOM &lt;form&gt; element temporarily modified to have its
  5641. * target set to refer to a dynamically generated, hidden &lt;iframe&gt; which is inserted into the document but removed
  5642. * after the return data has been gathered.
  5643. *
  5644. * The server response is parsed by the browser to create the document for the IFRAME. If the server is using JSON to
  5645. * send the return object, then the Content-Type header must be set to "text/html" in order to tell the browser to
  5646. * insert the text unchanged into the document body.
  5647. *
  5648. * Characters which are significant to an HTML parser must be sent as HTML entities, so encode `<` as `&lt;`, `&` as
  5649. * `&amp;` etc.
  5650. *
  5651. * The response text is retrieved from the document, and a fake XMLHttpRequest object is created containing a
  5652. * responseText property in order to conform to the requirements of event handlers and callbacks.
  5653. *
  5654. * Be aware that file upload packets are sent with the content type multipart/form and some server technologies
  5655. * (notably JEE) may require some custom processing in order to retrieve parameter names and parameter values from the
  5656. * packet content.
  5657. *
  5658. * Also note that it's not possible to check the response code of the hidden iframe, so the success handler will ALWAYS fire.
  5659. */
  5660. Ext.define('Ext.data.Connection', {
  5661. mixins: {
  5662. observable: 'Ext.util.Observable'
  5663. },
  5664. statics: {
  5665. requestId: 0
  5666. },
  5667. url: null,
  5668. async: true,
  5669. method: null,
  5670. username: '',
  5671. password: '',
  5672. /**
  5673. * @cfg {Boolean} disableCaching
  5674. * True to add a unique cache-buster param to GET requests.
  5675. */
  5676. disableCaching: true,
  5677. /**
  5678. * @cfg {Boolean} withCredentials
  5679. * True to set `withCredentials = true` on the XHR object
  5680. */
  5681. withCredentials: false,
  5682. /**
  5683. * @cfg {Boolean} cors
  5684. * True to enable CORS support on the XHR object. Currently the only effect of this option
  5685. * is to use the XDomainRequest object instead of XMLHttpRequest if the browser is IE8 or above.
  5686. */
  5687. cors: false,
  5688. /**
  5689. * @cfg {String} disableCachingParam
  5690. * Change the parameter which is sent went disabling caching through a cache buster.
  5691. */
  5692. disableCachingParam: '_dc',
  5693. /**
  5694. * @cfg {Number} timeout
  5695. * The timeout in milliseconds to be used for requests.
  5696. */
  5697. timeout : 30000,
  5698. /**
  5699. * @cfg {Object} extraParams
  5700. * Any parameters to be appended to the request.
  5701. */
  5702. useDefaultHeader : true,
  5703. defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8',
  5704. useDefaultXhrHeader : true,
  5705. defaultXhrHeader : 'XMLHttpRequest',
  5706. constructor : function(config) {
  5707. config = config || {};
  5708. Ext.apply(this, config);
  5709. this.addEvents(
  5710. /**
  5711. * @event beforerequest
  5712. * Fires before a network request is made to retrieve a data object.
  5713. * @param {Ext.data.Connection} conn This Connection object.
  5714. * @param {Object} options The options config object passed to the {@link #request} method.
  5715. */
  5716. 'beforerequest',
  5717. /**
  5718. * @event requestcomplete
  5719. * Fires if the request was successfully completed.
  5720. * @param {Ext.data.Connection} conn This Connection object.
  5721. * @param {Object} response The XHR object containing the response data.
  5722. * See [The XMLHttpRequest Object](http://www.w3.org/TR/XMLHttpRequest/) for details.
  5723. * @param {Object} options The options config object passed to the {@link #request} method.
  5724. */
  5725. 'requestcomplete',
  5726. /**
  5727. * @event requestexception
  5728. * Fires if an error HTTP status was returned from the server.
  5729. * See [HTTP Status Code Definitions](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
  5730. * for details of HTTP status codes.
  5731. * @param {Ext.data.Connection} conn This Connection object.
  5732. * @param {Object} response The XHR object containing the response data.
  5733. * See [The XMLHttpRequest Object](http://www.w3.org/TR/XMLHttpRequest/) for details.
  5734. * @param {Object} options The options config object passed to the {@link #request} method.
  5735. */
  5736. 'requestexception'
  5737. );
  5738. this.requests = {};
  5739. this.mixins.observable.constructor.call(this);
  5740. },
  5741. /**
  5742. * Sends an HTTP request to a remote server.
  5743. *
  5744. * **Important:** Ajax server requests are asynchronous, and this call will
  5745. * return before the response has been received. Process any returned data
  5746. * in a callback function.
  5747. *
  5748. * Ext.Ajax.request({
  5749. * url: 'ajax_demo/sample.json',
  5750. * success: function(response, opts) {
  5751. * var obj = Ext.decode(response.responseText);
  5752. * console.dir(obj);
  5753. * },
  5754. * failure: function(response, opts) {
  5755. * console.log('server-side failure with status code ' + response.status);
  5756. * }
  5757. * });
  5758. *
  5759. * To execute a callback function in the correct scope, use the `scope` option.
  5760. *
  5761. * @param {Object} options An object which may contain the following properties:
  5762. *
  5763. * (The options object may also contain any other property which might be needed to perform
  5764. * postprocessing in a callback because it is passed to callback functions.)
  5765. *
  5766. * @param {String/Function} options.url The URL to which to send the request, or a function
  5767. * to call which returns a URL string. The scope of the function is specified by the `scope` option.
  5768. * Defaults to the configured `url`.
  5769. *
  5770. * @param {Object/String/Function} options.params An object containing properties which are
  5771. * used as parameters to the request, a url encoded string or a function to call to get either. The scope
  5772. * of the function is specified by the `scope` option.
  5773. *
  5774. * @param {String} options.method The HTTP method to use
  5775. * for the request. Defaults to the configured method, or if no method was configured,
  5776. * "GET" if no parameters are being sent, and "POST" if parameters are being sent. Note that
  5777. * the method name is case-sensitive and should be all caps.
  5778. *
  5779. * @param {Function} options.callback The function to be called upon receipt of the HTTP response.
  5780. * The callback is called regardless of success or failure and is passed the following parameters:
  5781. * @param {Object} options.callback.options The parameter to the request call.
  5782. * @param {Boolean} options.callback.success True if the request succeeded.
  5783. * @param {Object} options.callback.response The XMLHttpRequest object containing the response data.
  5784. * See [www.w3.org/TR/XMLHttpRequest/](http://www.w3.org/TR/XMLHttpRequest/) for details about
  5785. * accessing elements of the response.
  5786. *
  5787. * @param {Function} options.success The function to be called upon success of the request.
  5788. * The callback is passed the following parameters:
  5789. * @param {Object} options.success.response The XMLHttpRequest object containing the response data.
  5790. * @param {Object} options.success.options The parameter to the request call.
  5791. *
  5792. * @param {Function} options.failure The function to be called upon success of the request.
  5793. * The callback is passed the following parameters:
  5794. * @param {Object} options.failure.response The XMLHttpRequest object containing the response data.
  5795. * @param {Object} options.failure.options The parameter to the request call.
  5796. *
  5797. * @param {Object} options.scope The scope in which to execute the callbacks: The "this" object for
  5798. * the callback function. If the `url`, or `params` options were specified as functions from which to
  5799. * draw values, then this also serves as the scope for those function calls. Defaults to the browser
  5800. * window.
  5801. *
  5802. * @param {Number} options.timeout The timeout in milliseconds to be used for this request.
  5803. * Defaults to 30 seconds.
  5804. *
  5805. * @param {Ext.Element/HTMLElement/String} options.form The `<form>` Element or the id of the `<form>`
  5806. * to pull parameters from.
  5807. *
  5808. * @param {Boolean} options.isUpload **Only meaningful when used with the `form` option.**
  5809. *
  5810. * True if the form object is a file upload (will be set automatically if the form was configured
  5811. * with **`enctype`** `"multipart/form-data"`).
  5812. *
  5813. * File uploads are not performed using normal "Ajax" techniques, that is they are **not**
  5814. * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
  5815. * DOM `<form>` element temporarily modified to have its [target][] set to refer to a dynamically
  5816. * generated, hidden `<iframe>` which is inserted into the document but removed after the return data
  5817. * has been gathered.
  5818. *
  5819. * The server response is parsed by the browser to create the document for the IFRAME. If the
  5820. * server is using JSON to send the return object, then the [Content-Type][] header must be set to
  5821. * "text/html" in order to tell the browser to insert the text unchanged into the document body.
  5822. *
  5823. * The response text is retrieved from the document, and a fake XMLHttpRequest object is created
  5824. * containing a `responseText` property in order to conform to the requirements of event handlers
  5825. * and callbacks.
  5826. *
  5827. * Be aware that file upload packets are sent with the content type [multipart/form][] and some server
  5828. * technologies (notably JEE) may require some custom processing in order to retrieve parameter names
  5829. * and parameter values from the packet content.
  5830. *
  5831. * [target]: http://www.w3.org/TR/REC-html40/present/frames.html#adef-target
  5832. * [Content-Type]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
  5833. * [multipart/form]: http://www.faqs.org/rfcs/rfc2388.html
  5834. *
  5835. * @param {Object} options.headers Request headers to set for the request.
  5836. *
  5837. * @param {Object} options.xmlData XML document to use for the post. Note: This will be used instead
  5838. * of params for the post data. Any params will be appended to the URL.
  5839. *
  5840. * @param {Object/String} options.jsonData JSON data to use as the post. Note: This will be used
  5841. * instead of params for the post data. Any params will be appended to the URL.
  5842. *
  5843. * @param {Boolean} options.disableCaching True to add a unique cache-buster param to GET requests.
  5844. *
  5845. * @param {Boolean} options.withCredentials True to add the withCredentials property to the XHR object
  5846. *
  5847. * @return {Object} The request object. This may be used to cancel the request.
  5848. */
  5849. request : function(options) {
  5850. options = options || {};
  5851. var me = this,
  5852. scope = options.scope || window,
  5853. username = options.username || me.username,
  5854. password = options.password || me.password || '',
  5855. async,
  5856. requestOptions,
  5857. request,
  5858. headers,
  5859. xhr;
  5860. if (me.fireEvent('beforerequest', me, options) !== false) {
  5861. requestOptions = me.setOptions(options, scope);
  5862. if (this.isFormUpload(options) === true) {
  5863. this.upload(options.form, requestOptions.url, requestOptions.data, options);
  5864. return null;
  5865. }
  5866. // if autoabort is set, cancel the current transactions
  5867. if (options.autoAbort === true || me.autoAbort) {
  5868. me.abort();
  5869. }
  5870. // create a connection object
  5871. if ((options.cors === true || me.cors === true) && Ext.isIe && Ext.ieVersion >= 8) {
  5872. xhr = new XDomainRequest();
  5873. } else {
  5874. xhr = this.getXhrInstance();
  5875. }
  5876. async = options.async !== false ? (options.async || me.async) : false;
  5877. // open the request
  5878. if (username) {
  5879. xhr.open(requestOptions.method, requestOptions.url, async, username, password);
  5880. } else {
  5881. xhr.open(requestOptions.method, requestOptions.url, async);
  5882. }
  5883. if (options.withCredentials === true || me.withCredentials === true) {
  5884. xhr.withCredentials = true;
  5885. }
  5886. headers = me.setupHeaders(xhr, options, requestOptions.data, requestOptions.params);
  5887. // create the transaction object
  5888. request = {
  5889. id: ++Ext.data.Connection.requestId,
  5890. xhr: xhr,
  5891. headers: headers,
  5892. options: options,
  5893. async: async,
  5894. timeout: setTimeout(function() {
  5895. request.timedout = true;
  5896. me.abort(request);
  5897. }, options.timeout || me.timeout)
  5898. };
  5899. me.requests[request.id] = request;
  5900. me.latestId = request.id;
  5901. // bind our statechange listener
  5902. if (async) {
  5903. xhr.onreadystatechange = Ext.Function.bind(me.onStateChange, me, [request]);
  5904. }
  5905. // start the request!
  5906. xhr.send(requestOptions.data);
  5907. if (!async) {
  5908. return this.onComplete(request);
  5909. }
  5910. return request;
  5911. } else {
  5912. Ext.callback(options.callback, options.scope, [options, undefined, undefined]);
  5913. return null;
  5914. }
  5915. },
  5916. /**
  5917. * Uploads a form using a hidden iframe.
  5918. * @param {String/HTMLElement/Ext.Element} form The form to upload
  5919. * @param {String} url The url to post to
  5920. * @param {String} params Any extra parameters to pass
  5921. * @param {Object} options The initial options
  5922. */
  5923. upload: function(form, url, params, options) {
  5924. form = Ext.getDom(form);
  5925. options = options || {};
  5926. var id = Ext.id(),
  5927. frame = document.createElement('iframe'),
  5928. hiddens = [],
  5929. encoding = 'multipart/form-data',
  5930. buf = {
  5931. target: form.target,
  5932. method: form.method,
  5933. encoding: form.encoding,
  5934. enctype: form.enctype,
  5935. action: form.action
  5936. }, hiddenItem;
  5937. /*
  5938. * Originally this behaviour was modified for Opera 10 to apply the secure URL after
  5939. * the frame had been added to the document. It seems this has since been corrected in
  5940. * Opera so the behaviour has been reverted, the URL will be set before being added.
  5941. */
  5942. Ext.fly(frame).set({
  5943. id: id,
  5944. name: id,
  5945. cls: Ext.baseCSSPrefix + 'hide-display',
  5946. src: Ext.SSL_SECURE_URL
  5947. });
  5948. document.body.appendChild(frame);
  5949. // This is required so that IE doesn't pop the response up in a new window.
  5950. if (document.frames) {
  5951. document.frames[id].name = id;
  5952. }
  5953. Ext.fly(form).set({
  5954. target: id,
  5955. method: 'POST',
  5956. enctype: encoding,
  5957. encoding: encoding,
  5958. action: url || buf.action
  5959. });
  5960. // add dynamic params
  5961. if (params) {
  5962. Ext.iterate(Ext.Object.fromQueryString(params), function(name, value){
  5963. hiddenItem = document.createElement('input');
  5964. Ext.fly(hiddenItem).set({
  5965. type: 'hidden',
  5966. value: value,
  5967. name: name
  5968. });
  5969. form.appendChild(hiddenItem);
  5970. hiddens.push(hiddenItem);
  5971. });
  5972. }
  5973. Ext.fly(frame).on('load', Ext.Function.bind(this.onUploadComplete, this, [frame, options]), null, {single: true});
  5974. form.submit();
  5975. Ext.fly(form).set(buf);
  5976. Ext.each(hiddens, function(h) {
  5977. Ext.removeNode(h);
  5978. });
  5979. },
  5980. /**
  5981. * @private
  5982. * Callback handler for the upload function. After we've submitted the form via the iframe this creates a bogus
  5983. * response object to simulate an XHR and populates its responseText from the now-loaded iframe's document body
  5984. * (or a textarea inside the body). We then clean up by removing the iframe
  5985. */
  5986. onUploadComplete: function(frame, options) {
  5987. var me = this,
  5988. // bogus response object
  5989. response = {
  5990. responseText: '',
  5991. responseXML: null
  5992. }, doc, firstChild;
  5993. try {
  5994. doc = frame.contentWindow.document || frame.contentDocument || window.frames[frame.id].document;
  5995. if (doc) {
  5996. if (doc.body) {
  5997. if (/textarea/i.test((firstChild = doc.body.firstChild || {}).tagName)) { // json response wrapped in textarea
  5998. response.responseText = firstChild.value;
  5999. } else {
  6000. response.responseText = doc.body.innerHTML;
  6001. }
  6002. }
  6003. //in IE the document may still have a body even if returns XML.
  6004. response.responseXML = doc.XMLDocument || doc;
  6005. }
  6006. } catch (e) {
  6007. }
  6008. me.fireEvent('requestcomplete', me, response, options);
  6009. Ext.callback(options.success, options.scope, [response, options]);
  6010. Ext.callback(options.callback, options.scope, [options, true, response]);
  6011. setTimeout(function(){
  6012. Ext.removeNode(frame);
  6013. }, 100);
  6014. },
  6015. /**
  6016. * Detects whether the form is intended to be used for an upload.
  6017. * @private
  6018. */
  6019. isFormUpload: function(options){
  6020. var form = this.getForm(options);
  6021. if (form) {
  6022. return (options.isUpload || (/multipart\/form-data/i).test(form.getAttribute('enctype')));
  6023. }
  6024. return false;
  6025. },
  6026. /**
  6027. * Gets the form object from options.
  6028. * @private
  6029. * @param {Object} options The request options
  6030. * @return {HTMLElement} The form, null if not passed
  6031. */
  6032. getForm: function(options){
  6033. return Ext.getDom(options.form) || null;
  6034. },
  6035. /**
  6036. * Sets various options such as the url, params for the request
  6037. * @param {Object} options The initial options
  6038. * @param {Object} scope The scope to execute in
  6039. * @return {Object} The params for the request
  6040. */
  6041. setOptions: function(options, scope){
  6042. var me = this,
  6043. params = options.params || {},
  6044. extraParams = me.extraParams,
  6045. urlParams = options.urlParams,
  6046. url = options.url || me.url,
  6047. jsonData = options.jsonData,
  6048. method,
  6049. disableCache,
  6050. data;
  6051. // allow params to be a method that returns the params object
  6052. if (Ext.isFunction(params)) {
  6053. params = params.call(scope, options);
  6054. }
  6055. // allow url to be a method that returns the actual url
  6056. if (Ext.isFunction(url)) {
  6057. url = url.call(scope, options);
  6058. }
  6059. url = this.setupUrl(options, url);
  6060. //<debug>
  6061. if (!url) {
  6062. Ext.Error.raise({
  6063. options: options,
  6064. msg: 'No URL specified'
  6065. });
  6066. }
  6067. //</debug>
  6068. // check for xml or json data, and make sure json data is encoded
  6069. data = options.rawData || options.xmlData || jsonData || null;
  6070. if (jsonData && !Ext.isPrimitive(jsonData)) {
  6071. data = Ext.encode(data);
  6072. }
  6073. // make sure params are a url encoded string and include any extraParams if specified
  6074. if (Ext.isObject(params)) {
  6075. params = Ext.Object.toQueryString(params);
  6076. }
  6077. if (Ext.isObject(extraParams)) {
  6078. extraParams = Ext.Object.toQueryString(extraParams);
  6079. }
  6080. params = params + ((extraParams) ? ((params) ? '&' : '') + extraParams : '');
  6081. urlParams = Ext.isObject(urlParams) ? Ext.Object.toQueryString(urlParams) : urlParams;
  6082. params = this.setupParams(options, params);
  6083. // decide the proper method for this request
  6084. method = (options.method || me.method || ((params || data) ? 'POST' : 'GET')).toUpperCase();
  6085. this.setupMethod(options, method);
  6086. disableCache = options.disableCaching !== false ? (options.disableCaching || me.disableCaching) : false;
  6087. // if the method is get append date to prevent caching
  6088. if (method === 'GET' && disableCache) {
  6089. url = Ext.urlAppend(url, (options.disableCachingParam || me.disableCachingParam) + '=' + (new Date().getTime()));
  6090. }
  6091. // if the method is get or there is json/xml data append the params to the url
  6092. if ((method == 'GET' || data) && params) {
  6093. url = Ext.urlAppend(url, params);
  6094. params = null;
  6095. }
  6096. // allow params to be forced into the url
  6097. if (urlParams) {
  6098. url = Ext.urlAppend(url, urlParams);
  6099. }
  6100. return {
  6101. url: url,
  6102. method: method,
  6103. data: data || params || null
  6104. };
  6105. },
  6106. /**
  6107. * Template method for overriding url
  6108. * @template
  6109. * @private
  6110. * @param {Object} options
  6111. * @param {String} url
  6112. * @return {String} The modified url
  6113. */
  6114. setupUrl: function(options, url){
  6115. var form = this.getForm(options);
  6116. if (form) {
  6117. url = url || form.action;
  6118. }
  6119. return url;
  6120. },
  6121. /**
  6122. * Template method for overriding params
  6123. * @template
  6124. * @private
  6125. * @param {Object} options
  6126. * @param {String} params
  6127. * @return {String} The modified params
  6128. */
  6129. setupParams: function(options, params) {
  6130. var form = this.getForm(options),
  6131. serializedForm;
  6132. if (form && !this.isFormUpload(options)) {
  6133. serializedForm = Ext.Element.serializeForm(form);
  6134. params = params ? (params + '&' + serializedForm) : serializedForm;
  6135. }
  6136. return params;
  6137. },
  6138. /**
  6139. * Template method for overriding method
  6140. * @template
  6141. * @private
  6142. * @param {Object} options
  6143. * @param {String} method
  6144. * @return {String} The modified method
  6145. */
  6146. setupMethod: function(options, method){
  6147. if (this.isFormUpload(options)) {
  6148. return 'POST';
  6149. }
  6150. return method;
  6151. },
  6152. /**
  6153. * Setup all the headers for the request
  6154. * @private
  6155. * @param {Object} xhr The xhr object
  6156. * @param {Object} options The options for the request
  6157. * @param {Object} data The data for the request
  6158. * @param {Object} params The params for the request
  6159. */
  6160. setupHeaders: function(xhr, options, data, params){
  6161. var me = this,
  6162. headers = Ext.apply({}, options.headers || {}, me.defaultHeaders || {}),
  6163. contentType = me.defaultPostHeader,
  6164. jsonData = options.jsonData,
  6165. xmlData = options.xmlData,
  6166. key,
  6167. header;
  6168. if (!headers['Content-Type'] && (data || params)) {
  6169. if (data) {
  6170. if (options.rawData) {
  6171. contentType = 'text/plain';
  6172. } else {
  6173. if (xmlData && Ext.isDefined(xmlData)) {
  6174. contentType = 'text/xml';
  6175. } else if (jsonData && Ext.isDefined(jsonData)) {
  6176. contentType = 'application/json';
  6177. }
  6178. }
  6179. }
  6180. headers['Content-Type'] = contentType;
  6181. }
  6182. if (me.useDefaultXhrHeader && !headers['X-Requested-With']) {
  6183. headers['X-Requested-With'] = me.defaultXhrHeader;
  6184. }
  6185. // set up all the request headers on the xhr object
  6186. try{
  6187. for (key in headers) {
  6188. if (headers.hasOwnProperty(key)) {
  6189. header = headers[key];
  6190. xhr.setRequestHeader(key, header);
  6191. }
  6192. }
  6193. } catch(e) {
  6194. me.fireEvent('exception', key, header);
  6195. }
  6196. return headers;
  6197. },
  6198. /**
  6199. * Creates the appropriate XHR transport for the browser.
  6200. * @private
  6201. */
  6202. getXhrInstance: (function(){
  6203. var options = [function(){
  6204. return new XMLHttpRequest();
  6205. }, function(){
  6206. return new ActiveXObject('MSXML2.XMLHTTP.3.0');
  6207. }, function(){
  6208. return new ActiveXObject('MSXML2.XMLHTTP');
  6209. }, function(){
  6210. return new ActiveXObject('Microsoft.XMLHTTP');
  6211. }], i = 0,
  6212. len = options.length,
  6213. xhr;
  6214. for(; i < len; ++i) {
  6215. try{
  6216. xhr = options[i];
  6217. xhr();
  6218. break;
  6219. }catch(e){}
  6220. }
  6221. return xhr;
  6222. })(),
  6223. /**
  6224. * Determines whether this object has a request outstanding.
  6225. * @param {Object} [request] Defaults to the last transaction
  6226. * @return {Boolean} True if there is an outstanding request.
  6227. */
  6228. isLoading : function(request) {
  6229. if (!request) {
  6230. request = this.getLatest();
  6231. }
  6232. if (!(request && request.xhr)) {
  6233. return false;
  6234. }
  6235. // if there is a connection and readyState is not 0 or 4
  6236. var state = request.xhr.readyState;
  6237. return !(state === 0 || state == 4);
  6238. },
  6239. /**
  6240. * Aborts an active request.
  6241. * @param {Object} [request] Defaults to the last request
  6242. */
  6243. abort : function(request) {
  6244. var me = this;
  6245. if (!request) {
  6246. request = me.getLatest();
  6247. }
  6248. if (request && me.isLoading(request)) {
  6249. /*
  6250. * Clear out the onreadystatechange here, this allows us
  6251. * greater control, the browser may/may not fire the function
  6252. * depending on a series of conditions.
  6253. */
  6254. request.xhr.onreadystatechange = null;
  6255. request.xhr.abort();
  6256. me.clearTimeout(request);
  6257. if (!request.timedout) {
  6258. request.aborted = true;
  6259. }
  6260. me.onComplete(request);
  6261. me.cleanup(request);
  6262. }
  6263. },
  6264. /**
  6265. * Aborts all active requests
  6266. */
  6267. abortAll: function(){
  6268. var requests = this.requests,
  6269. id;
  6270. for (id in requests) {
  6271. if (requests.hasOwnProperty(id)) {
  6272. this.abort(requests[id]);
  6273. }
  6274. }
  6275. },
  6276. /**
  6277. * Gets the most recent request
  6278. * @private
  6279. * @return {Object} The request. Null if there is no recent request
  6280. */
  6281. getLatest: function(){
  6282. var id = this.latestId,
  6283. request;
  6284. if (id) {
  6285. request = this.requests[id];
  6286. }
  6287. return request || null;
  6288. },
  6289. /**
  6290. * Fires when the state of the xhr changes
  6291. * @private
  6292. * @param {Object} request The request
  6293. */
  6294. onStateChange : function(request) {
  6295. if (request.xhr.readyState == 4) {
  6296. this.clearTimeout(request);
  6297. this.onComplete(request);
  6298. this.cleanup(request);
  6299. }
  6300. },
  6301. /**
  6302. * Clears the timeout on the request
  6303. * @private
  6304. * @param {Object} The request
  6305. */
  6306. clearTimeout: function(request){
  6307. clearTimeout(request.timeout);
  6308. delete request.timeout;
  6309. },
  6310. /**
  6311. * Cleans up any left over information from the request
  6312. * @private
  6313. * @param {Object} The request
  6314. */
  6315. cleanup: function(request){
  6316. request.xhr = null;
  6317. delete request.xhr;
  6318. },
  6319. /**
  6320. * To be called when the request has come back from the server
  6321. * @private
  6322. * @param {Object} request
  6323. * @return {Object} The response
  6324. */
  6325. onComplete : function(request) {
  6326. var me = this,
  6327. options = request.options,
  6328. result,
  6329. success,
  6330. response;
  6331. try {
  6332. result = me.parseStatus(request.xhr.status);
  6333. } catch (e) {
  6334. // in some browsers we can't access the status if the readyState is not 4, so the request has failed
  6335. result = {
  6336. success : false,
  6337. isException : false
  6338. };
  6339. }
  6340. success = result.success;
  6341. if (success) {
  6342. response = me.createResponse(request);
  6343. me.fireEvent('requestcomplete', me, response, options);
  6344. Ext.callback(options.success, options.scope, [response, options]);
  6345. } else {
  6346. if (result.isException || request.aborted || request.timedout) {
  6347. response = me.createException(request);
  6348. } else {
  6349. response = me.createResponse(request);
  6350. }
  6351. me.fireEvent('requestexception', me, response, options);
  6352. Ext.callback(options.failure, options.scope, [response, options]);
  6353. }
  6354. Ext.callback(options.callback, options.scope, [options, success, response]);
  6355. delete me.requests[request.id];
  6356. return response;
  6357. },
  6358. /**
  6359. * Checks if the response status was successful
  6360. * @param {Number} status The status code
  6361. * @return {Object} An object containing success/status state
  6362. */
  6363. parseStatus: function(status) {
  6364. // see: https://prototype.lighthouseapp.com/projects/8886/tickets/129-ie-mangles-http-response-status-code-204-to-1223
  6365. status = status == 1223 ? 204 : status;
  6366. var success = (status >= 200 && status < 300) || status == 304,
  6367. isException = false;
  6368. if (!success) {
  6369. switch (status) {
  6370. case 12002:
  6371. case 12029:
  6372. case 12030:
  6373. case 12031:
  6374. case 12152:
  6375. case 13030:
  6376. isException = true;
  6377. break;
  6378. }
  6379. }
  6380. return {
  6381. success: success,
  6382. isException: isException
  6383. };
  6384. },
  6385. /**
  6386. * Creates the response object
  6387. * @private
  6388. * @param {Object} request
  6389. */
  6390. createResponse : function(request) {
  6391. var xhr = request.xhr,
  6392. headers = {},
  6393. lines = xhr.getAllResponseHeaders().replace(/\r\n/g, '\n').split('\n'),
  6394. count = lines.length,
  6395. line, index, key, value, response;
  6396. while (count--) {
  6397. line = lines[count];
  6398. index = line.indexOf(':');
  6399. if(index >= 0) {
  6400. key = line.substr(0, index).toLowerCase();
  6401. if (line.charAt(index + 1) == ' ') {
  6402. ++index;
  6403. }
  6404. headers[key] = line.substr(index + 1);
  6405. }
  6406. }
  6407. request.xhr = null;
  6408. delete request.xhr;
  6409. response = {
  6410. request: request,
  6411. requestId : request.id,
  6412. status : xhr.status,
  6413. statusText : xhr.statusText,
  6414. getResponseHeader : function(header){ return headers[header.toLowerCase()]; },
  6415. getAllResponseHeaders : function(){ return headers; },
  6416. responseText : xhr.responseText,
  6417. responseXML : xhr.responseXML
  6418. };
  6419. // If we don't explicitly tear down the xhr reference, IE6/IE7 will hold this in the closure of the
  6420. // functions created with getResponseHeader/getAllResponseHeaders
  6421. xhr = null;
  6422. return response;
  6423. },
  6424. /**
  6425. * Creates the exception object
  6426. * @private
  6427. * @param {Object} request
  6428. */
  6429. createException : function(request) {
  6430. return {
  6431. request : request,
  6432. requestId : request.id,
  6433. status : request.aborted ? -1 : 0,
  6434. statusText : request.aborted ? 'transaction aborted' : 'communication failure',
  6435. aborted: request.aborted,
  6436. timedout: request.timedout
  6437. };
  6438. }
  6439. });
  6440. /**
  6441. * @class Ext.Ajax
  6442. * @singleton
  6443. * @markdown
  6444. * @extends Ext.data.Connection
  6445. A singleton instance of an {@link Ext.data.Connection}. This class
  6446. is used to communicate with your server side code. It can be used as follows:
  6447. Ext.Ajax.request({
  6448. url: 'page.php',
  6449. params: {
  6450. id: 1
  6451. },
  6452. success: function(response){
  6453. var text = response.responseText;
  6454. // process server response here
  6455. }
  6456. });
  6457. Default options for all requests can be set by changing a property on the Ext.Ajax class:
  6458. Ext.Ajax.timeout = 60000; // 60 seconds
  6459. Any options specified in the request method for the Ajax request will override any
  6460. defaults set on the Ext.Ajax class. In the code sample below, the timeout for the
  6461. request will be 60 seconds.
  6462. Ext.Ajax.timeout = 120000; // 120 seconds
  6463. Ext.Ajax.request({
  6464. url: 'page.aspx',
  6465. timeout: 60000
  6466. });
  6467. In general, this class will be used for all Ajax requests in your application.
  6468. The main reason for creating a separate {@link Ext.data.Connection} is for a
  6469. series of requests that share common settings that are different to all other
  6470. requests in the application.
  6471. */
  6472. Ext.define('Ext.Ajax', {
  6473. extend: 'Ext.data.Connection',
  6474. singleton: true,
  6475. /**
  6476. * @cfg {String} url @hide
  6477. */
  6478. /**
  6479. * @cfg {Object} extraParams @hide
  6480. */
  6481. /**
  6482. * @cfg {Object} defaultHeaders @hide
  6483. */
  6484. /**
  6485. * @cfg {String} method (Optional) @hide
  6486. */
  6487. /**
  6488. * @cfg {Number} timeout (Optional) @hide
  6489. */
  6490. /**
  6491. * @cfg {Boolean} autoAbort (Optional) @hide
  6492. */
  6493. /**
  6494. * @cfg {Boolean} disableCaching (Optional) @hide
  6495. */
  6496. /**
  6497. * @property {Boolean} disableCaching
  6498. * True to add a unique cache-buster param to GET requests. Defaults to true.
  6499. */
  6500. /**
  6501. * @property {String} url
  6502. * The default URL to be used for requests to the server.
  6503. * If the server receives all requests through one URL, setting this once is easier than
  6504. * entering it on every request.
  6505. */
  6506. /**
  6507. * @property {Object} extraParams
  6508. * An object containing properties which are used as extra parameters to each request made
  6509. * by this object. Session information and other data that you need
  6510. * to pass with each request are commonly put here.
  6511. */
  6512. /**
  6513. * @property {Object} defaultHeaders
  6514. * An object containing request headers which are added to each request made by this object.
  6515. */
  6516. /**
  6517. * @property {String} method
  6518. * The default HTTP method to be used for requests. Note that this is case-sensitive and
  6519. * should be all caps (if not set but params are present will use
  6520. * <tt>"POST"</tt>, otherwise will use <tt>"GET"</tt>.)
  6521. */
  6522. /**
  6523. * @property {Number} timeout
  6524. * The timeout in milliseconds to be used for requests. Defaults to 30000.
  6525. */
  6526. /**
  6527. * @property {Boolean} autoAbort
  6528. * Whether a new request should abort any pending requests.
  6529. */
  6530. autoAbort : false
  6531. });
  6532. /**
  6533. * A class used to load remote content to an Element. Sample usage:
  6534. *
  6535. * Ext.get('el').load({
  6536. * url: 'myPage.php',
  6537. * scripts: true,
  6538. * params: {
  6539. * id: 1
  6540. * }
  6541. * });
  6542. *
  6543. * In general this class will not be instanced directly, rather the {@link Ext.Element#load} method
  6544. * will be used.
  6545. */
  6546. Ext.define('Ext.ElementLoader', {
  6547. /* Begin Definitions */
  6548. mixins: {
  6549. observable: 'Ext.util.Observable'
  6550. },
  6551. uses: [
  6552. 'Ext.data.Connection',
  6553. 'Ext.Ajax'
  6554. ],
  6555. statics: {
  6556. Renderer: {
  6557. Html: function(loader, response, active){
  6558. loader.getTarget().update(response.responseText, active.scripts === true);
  6559. return true;
  6560. }
  6561. }
  6562. },
  6563. /* End Definitions */
  6564. /**
  6565. * @cfg {String} url
  6566. * The url to retrieve the content from.
  6567. */
  6568. url: null,
  6569. /**
  6570. * @cfg {Object} params
  6571. * Any params to be attached to the Ajax request. These parameters will
  6572. * be overridden by any params in the load options.
  6573. */
  6574. params: null,
  6575. /**
  6576. * @cfg {Object} baseParams Params that will be attached to every request. These parameters
  6577. * will not be overridden by any params in the load options.
  6578. */
  6579. baseParams: null,
  6580. /**
  6581. * @cfg {Boolean/Object} autoLoad
  6582. * True to have the loader make a request as soon as it is created.
  6583. * This argument can also be a set of options that will be passed to {@link #load} is called.
  6584. */
  6585. autoLoad: false,
  6586. /**
  6587. * @cfg {HTMLElement/Ext.Element/String} target
  6588. * The target element for the loader. It can be the DOM element, the id or an {@link Ext.Element}.
  6589. */
  6590. target: null,
  6591. /**
  6592. * @cfg {Boolean/String} loadMask
  6593. * True or a string to show when the element is loading.
  6594. */
  6595. loadMask: false,
  6596. /**
  6597. * @cfg {Object} ajaxOptions
  6598. * Any additional options to be passed to the request, for example timeout or headers.
  6599. */
  6600. ajaxOptions: null,
  6601. /**
  6602. * @cfg {Boolean} scripts
  6603. * True to parse any inline script tags in the response.
  6604. */
  6605. scripts: false,
  6606. /**
  6607. * @cfg {Function} success
  6608. * A function to be called when a load request is successful.
  6609. * Will be called with the following config parameters:
  6610. *
  6611. * - this - The ElementLoader instance.
  6612. * - response - The response object.
  6613. * - options - Ajax options.
  6614. */
  6615. /**
  6616. * @cfg {Function} failure A function to be called when a load request fails.
  6617. * Will be called with the following config parameters:
  6618. *
  6619. * - this - The ElementLoader instance.
  6620. * - response - The response object.
  6621. * - options - Ajax options.
  6622. */
  6623. /**
  6624. * @cfg {Function} callback A function to be called when a load request finishes.
  6625. * Will be called with the following config parameters:
  6626. *
  6627. * - this - The ElementLoader instance.
  6628. * - success - True if successful request.
  6629. * - response - The response object.
  6630. * - options - Ajax options.
  6631. */
  6632. /**
  6633. * @cfg {Object} scope
  6634. * The scope to execute the {@link #success} and {@link #failure} functions in.
  6635. */
  6636. /**
  6637. * @cfg {Function} renderer
  6638. * A custom function to render the content to the element. The passed parameters are:
  6639. *
  6640. * - The loader
  6641. * - The response
  6642. * - The active request
  6643. */
  6644. isLoader: true,
  6645. constructor: function(config) {
  6646. var me = this,
  6647. autoLoad;
  6648. config = config || {};
  6649. Ext.apply(me, config);
  6650. me.setTarget(me.target);
  6651. me.addEvents(
  6652. /**
  6653. * @event beforeload
  6654. * Fires before a load request is made to the server.
  6655. * Returning false from an event listener can prevent the load
  6656. * from occurring.
  6657. * @param {Ext.ElementLoader} this
  6658. * @param {Object} options The options passed to the request
  6659. */
  6660. 'beforeload',
  6661. /**
  6662. * @event exception
  6663. * Fires after an unsuccessful load.
  6664. * @param {Ext.ElementLoader} this
  6665. * @param {Object} response The response from the server
  6666. * @param {Object} options The options passed to the request
  6667. */
  6668. 'exception',
  6669. /**
  6670. * @event load
  6671. * Fires after a successful load.
  6672. * @param {Ext.ElementLoader} this
  6673. * @param {Object} response The response from the server
  6674. * @param {Object} options The options passed to the request
  6675. */
  6676. 'load'
  6677. );
  6678. // don't pass config because we have already applied it.
  6679. me.mixins.observable.constructor.call(me);
  6680. if (me.autoLoad) {
  6681. autoLoad = me.autoLoad;
  6682. if (autoLoad === true) {
  6683. autoLoad = {};
  6684. }
  6685. me.load(autoLoad);
  6686. }
  6687. },
  6688. /**
  6689. * Sets an {@link Ext.Element} as the target of this loader.
  6690. * Note that if the target is changed, any active requests will be aborted.
  6691. * @param {String/HTMLElement/Ext.Element} target The element or its ID.
  6692. */
  6693. setTarget: function(target){
  6694. var me = this;
  6695. target = Ext.get(target);
  6696. if (me.target && me.target != target) {
  6697. me.abort();
  6698. }
  6699. me.target = target;
  6700. },
  6701. /**
  6702. * Returns the target of this loader.
  6703. * @return {Ext.Component} The target or null if none exists.
  6704. */
  6705. getTarget: function(){
  6706. return this.target || null;
  6707. },
  6708. /**
  6709. * Aborts the active load request
  6710. */
  6711. abort: function(){
  6712. var active = this.active;
  6713. if (active !== undefined) {
  6714. Ext.Ajax.abort(active.request);
  6715. if (active.mask) {
  6716. this.removeMask();
  6717. }
  6718. delete this.active;
  6719. }
  6720. },
  6721. /**
  6722. * Removes the mask on the target
  6723. * @private
  6724. */
  6725. removeMask: function(){
  6726. this.target.unmask();
  6727. },
  6728. /**
  6729. * Adds the mask on the target
  6730. * @private
  6731. * @param {Boolean/Object} mask The mask configuration
  6732. */
  6733. addMask: function(mask){
  6734. this.target.mask(mask === true ? null : mask);
  6735. },
  6736. /**
  6737. * Loads new data from the server.
  6738. * @param {Object} options The options for the request. They can be any configuration option that can be specified for
  6739. * the class, with the exception of the target option. Note that any options passed to the method will override any
  6740. * class defaults.
  6741. */
  6742. load: function(options) {
  6743. //<debug>
  6744. if (!this.target) {
  6745. Ext.Error.raise('A valid target is required when loading content');
  6746. }
  6747. //</debug>
  6748. options = Ext.apply({}, options);
  6749. var me = this,
  6750. target = me.target,
  6751. mask = Ext.isDefined(options.loadMask) ? options.loadMask : me.loadMask,
  6752. params = Ext.apply({}, options.params),
  6753. ajaxOptions = Ext.apply({}, options.ajaxOptions),
  6754. callback = options.callback || me.callback,
  6755. scope = options.scope || me.scope || me,
  6756. request;
  6757. Ext.applyIf(ajaxOptions, me.ajaxOptions);
  6758. Ext.applyIf(options, ajaxOptions);
  6759. Ext.applyIf(params, me.params);
  6760. Ext.apply(params, me.baseParams);
  6761. Ext.applyIf(options, {
  6762. url: me.url
  6763. });
  6764. //<debug>
  6765. if (!options.url) {
  6766. Ext.Error.raise('You must specify the URL from which content should be loaded');
  6767. }
  6768. //</debug>
  6769. Ext.apply(options, {
  6770. scope: me,
  6771. params: params,
  6772. callback: me.onComplete
  6773. });
  6774. if (me.fireEvent('beforeload', me, options) === false) {
  6775. return;
  6776. }
  6777. if (mask) {
  6778. me.addMask(mask);
  6779. }
  6780. request = Ext.Ajax.request(options);
  6781. me.active = {
  6782. request: request,
  6783. options: options,
  6784. mask: mask,
  6785. scope: scope,
  6786. callback: callback,
  6787. success: options.success || me.success,
  6788. failure: options.failure || me.failure,
  6789. renderer: options.renderer || me.renderer,
  6790. scripts: Ext.isDefined(options.scripts) ? options.scripts : me.scripts
  6791. };
  6792. me.setOptions(me.active, options);
  6793. },
  6794. /**
  6795. * Sets any additional options on the active request
  6796. * @private
  6797. * @param {Object} active The active request
  6798. * @param {Object} options The initial options
  6799. */
  6800. setOptions: Ext.emptyFn,
  6801. /**
  6802. * Parses the response after the request completes
  6803. * @private
  6804. * @param {Object} options Ajax options
  6805. * @param {Boolean} success Success status of the request
  6806. * @param {Object} response The response object
  6807. */
  6808. onComplete: function(options, success, response) {
  6809. var me = this,
  6810. active = me.active,
  6811. scope = active.scope,
  6812. renderer = me.getRenderer(active.renderer);
  6813. if (success) {
  6814. success = renderer.call(me, me, response, active);
  6815. }
  6816. if (success) {
  6817. Ext.callback(active.success, scope, [me, response, options]);
  6818. me.fireEvent('load', me, response, options);
  6819. } else {
  6820. Ext.callback(active.failure, scope, [me, response, options]);
  6821. me.fireEvent('exception', me, response, options);
  6822. }
  6823. Ext.callback(active.callback, scope, [me, success, response, options]);
  6824. if (active.mask) {
  6825. me.removeMask();
  6826. }
  6827. delete me.active;
  6828. },
  6829. /**
  6830. * Gets the renderer to use
  6831. * @private
  6832. * @param {String/Function} renderer The renderer to use
  6833. * @return {Function} A rendering function to use.
  6834. */
  6835. getRenderer: function(renderer){
  6836. if (Ext.isFunction(renderer)) {
  6837. return renderer;
  6838. }
  6839. return this.statics().Renderer.Html;
  6840. },
  6841. /**
  6842. * Automatically refreshes the content over a specified period.
  6843. * @param {Number} interval The interval to refresh in ms.
  6844. * @param {Object} options (optional) The options to pass to the load method. See {@link #load}
  6845. */
  6846. startAutoRefresh: function(interval, options){
  6847. var me = this;
  6848. me.stopAutoRefresh();
  6849. me.autoRefresh = setInterval(function(){
  6850. me.load(options);
  6851. }, interval);
  6852. },
  6853. /**
  6854. * Clears any auto refresh. See {@link #startAutoRefresh}.
  6855. */
  6856. stopAutoRefresh: function(){
  6857. clearInterval(this.autoRefresh);
  6858. delete this.autoRefresh;
  6859. },
  6860. /**
  6861. * Checks whether the loader is automatically refreshing. See {@link #startAutoRefresh}.
  6862. * @return {Boolean} True if the loader is automatically refreshing
  6863. */
  6864. isAutoRefreshing: function(){
  6865. return Ext.isDefined(this.autoRefresh);
  6866. },
  6867. /**
  6868. * Destroys the loader. Any active requests will be aborted.
  6869. */
  6870. destroy: function(){
  6871. var me = this;
  6872. me.stopAutoRefresh();
  6873. delete me.target;
  6874. me.abort();
  6875. me.clearListeners();
  6876. }
  6877. });
  6878. /**
  6879. * @class Ext.ComponentLoader
  6880. * @extends Ext.ElementLoader
  6881. *
  6882. * This class is used to load content via Ajax into a {@link Ext.Component}. In general
  6883. * this class will not be instanced directly, rather a loader configuration will be passed to the
  6884. * constructor of the {@link Ext.Component}.
  6885. *
  6886. * ## HTML Renderer
  6887. * By default, the content loaded will be processed as raw html. The response text
  6888. * from the request is taken and added to the component. This can be used in
  6889. * conjunction with the {@link #scripts} option to execute any inline scripts in
  6890. * the resulting content. Using this renderer has the same effect as passing the
  6891. * {@link Ext.Component#html} configuration option.
  6892. *
  6893. * ## Data Renderer
  6894. * This renderer allows content to be added by using JSON data and a {@link Ext.XTemplate}.
  6895. * The content received from the response is passed to the {@link Ext.Component#update} method.
  6896. * This content is run through the attached {@link Ext.Component#tpl} and the data is added to
  6897. * the Component. Using this renderer has the same effect as using the {@link Ext.Component#data}
  6898. * configuration in conjunction with a {@link Ext.Component#tpl}.
  6899. *
  6900. * ## Component Renderer
  6901. * This renderer can only be used with a {@link Ext.container.Container} and subclasses. It allows for
  6902. * Components to be loaded remotely into a Container. The response is expected to be a single/series of
  6903. * {@link Ext.Component} configuration objects. When the response is received, the data is decoded
  6904. * and then passed to {@link Ext.container.Container#add}. Using this renderer has the same effect as specifying
  6905. * the {@link Ext.container.Container#items} configuration on a Container.
  6906. *
  6907. * ## Custom Renderer
  6908. * A custom function can be passed to handle any other special case, see the {@link #renderer} option.
  6909. *
  6910. * ## Example Usage
  6911. * new Ext.Component({
  6912. * tpl: '{firstName} - {lastName}',
  6913. * loader: {
  6914. * url: 'myPage.php',
  6915. * renderer: 'data',
  6916. * params: {
  6917. * userId: 1
  6918. * }
  6919. * }
  6920. * });
  6921. */
  6922. Ext.define('Ext.ComponentLoader', {
  6923. /* Begin Definitions */
  6924. extend: 'Ext.ElementLoader',
  6925. statics: {
  6926. Renderer: {
  6927. Data: function(loader, response, active){
  6928. var success = true;
  6929. try {
  6930. loader.getTarget().update(Ext.decode(response.responseText));
  6931. } catch (e) {
  6932. success = false;
  6933. }
  6934. return success;
  6935. },
  6936. Component: function(loader, response, active){
  6937. var success = true,
  6938. target = loader.getTarget(),
  6939. items = [];
  6940. //<debug>
  6941. if (!target.isContainer) {
  6942. Ext.Error.raise({
  6943. target: target,
  6944. msg: 'Components can only be loaded into a container'
  6945. });
  6946. }
  6947. //</debug>
  6948. try {
  6949. items = Ext.decode(response.responseText);
  6950. } catch (e) {
  6951. success = false;
  6952. }
  6953. if (success) {
  6954. if (active.removeAll) {
  6955. target.removeAll();
  6956. }
  6957. target.add(items);
  6958. }
  6959. return success;
  6960. }
  6961. }
  6962. },
  6963. /* End Definitions */
  6964. /**
  6965. * @cfg {Ext.Component/String} target The target {@link Ext.Component} for the loader.
  6966. * If a string is passed it will be looked up via the id.
  6967. */
  6968. target: null,
  6969. /**
  6970. * @cfg {Boolean/Object} loadMask True or a {@link Ext.LoadMask} configuration to enable masking during loading.
  6971. */
  6972. loadMask: false,
  6973. /**
  6974. * @cfg {Boolean} scripts True to parse any inline script tags in the response. This only used when using the html
  6975. * {@link #renderer}.
  6976. */
  6977. /**
  6978. * @cfg {String/Function} renderer
  6979. The type of content that is to be loaded into, which can be one of 3 types:
  6980. + **html** : Loads raw html content, see {@link Ext.Component#html}
  6981. + **data** : Loads raw html content, see {@link Ext.Component#data}
  6982. + **component** : Loads child {Ext.Component} instances. This option is only valid when used with a Container.
  6983. Alternatively, you can pass a function which is called with the following parameters.
  6984. + loader - Loader instance
  6985. + response - The server response
  6986. + active - The active request
  6987. The function must return false is loading is not successful. Below is a sample of using a custom renderer:
  6988. new Ext.Component({
  6989. loader: {
  6990. url: 'myPage.php',
  6991. renderer: function(loader, response, active) {
  6992. var text = response.responseText;
  6993. loader.getTarget().update('The response is ' + text);
  6994. return true;
  6995. }
  6996. }
  6997. });
  6998. */
  6999. renderer: 'html',
  7000. /**
  7001. * Set a {Ext.Component} as the target of this loader. Note that if the target is changed,
  7002. * any active requests will be aborted.
  7003. * @param {String/Ext.Component} target The component to be the target of this loader. If a string is passed
  7004. * it will be looked up via its id.
  7005. */
  7006. setTarget: function(target){
  7007. var me = this;
  7008. if (Ext.isString(target)) {
  7009. target = Ext.getCmp(target);
  7010. }
  7011. if (me.target && me.target != target) {
  7012. me.abort();
  7013. }
  7014. me.target = target;
  7015. },
  7016. // inherit docs
  7017. removeMask: function(){
  7018. this.target.setLoading(false);
  7019. },
  7020. /**
  7021. * Add the mask on the target
  7022. * @private
  7023. * @param {Boolean/Object} mask The mask configuration
  7024. */
  7025. addMask: function(mask){
  7026. this.target.setLoading(mask);
  7027. },
  7028. /**
  7029. * Get the target of this loader.
  7030. * @return {Ext.Component} target The target, null if none exists.
  7031. */
  7032. setOptions: function(active, options){
  7033. active.removeAll = Ext.isDefined(options.removeAll) ? options.removeAll : this.removeAll;
  7034. },
  7035. /**
  7036. * Gets the renderer to use
  7037. * @private
  7038. * @param {String/Function} renderer The renderer to use
  7039. * @return {Function} A rendering function to use.
  7040. */
  7041. getRenderer: function(renderer){
  7042. if (Ext.isFunction(renderer)) {
  7043. return renderer;
  7044. }
  7045. var renderers = this.statics().Renderer;
  7046. switch (renderer) {
  7047. case 'component':
  7048. return renderers.Component;
  7049. case 'data':
  7050. return renderers.Data;
  7051. default:
  7052. return Ext.ElementLoader.Renderer.Html;
  7053. }
  7054. }
  7055. });
  7056. /**
  7057. * @author Ed Spencer
  7058. *
  7059. * Associations enable you to express relationships between different {@link Ext.data.Model Models}. Let's say we're
  7060. * writing an ecommerce system where Users can make Orders - there's a relationship between these Models that we can
  7061. * express like this:
  7062. *
  7063. * Ext.define('User', {
  7064. * extend: 'Ext.data.Model',
  7065. * fields: ['id', 'name', 'email'],
  7066. *
  7067. * hasMany: {model: 'Order', name: 'orders'}
  7068. * });
  7069. *
  7070. * Ext.define('Order', {
  7071. * extend: 'Ext.data.Model',
  7072. * fields: ['id', 'user_id', 'status', 'price'],
  7073. *
  7074. * belongsTo: 'User'
  7075. * });
  7076. *
  7077. * We've set up two models - User and Order - and told them about each other. You can set up as many associations on
  7078. * each Model as you need using the two default types - {@link Ext.data.HasManyAssociation hasMany} and {@link
  7079. * Ext.data.BelongsToAssociation belongsTo}. There's much more detail on the usage of each of those inside their
  7080. * documentation pages. If you're not familiar with Models already, {@link Ext.data.Model there is plenty on those too}.
  7081. *
  7082. * **Further Reading**
  7083. *
  7084. * - {@link Ext.data.HasManyAssociation hasMany associations}
  7085. * - {@link Ext.data.BelongsToAssociation belongsTo associations}
  7086. * - {@link Ext.data.Model using Models}
  7087. *
  7088. * # Self association models
  7089. *
  7090. * We can also have models that create parent/child associations between the same type. Below is an example, where
  7091. * groups can be nested inside other groups:
  7092. *
  7093. * // Server Data
  7094. * {
  7095. * "groups": {
  7096. * "id": 10,
  7097. * "parent_id": 100,
  7098. * "name": "Main Group",
  7099. * "parent_group": {
  7100. * "id": 100,
  7101. * "parent_id": null,
  7102. * "name": "Parent Group"
  7103. * },
  7104. * "child_groups": [{
  7105. * "id": 2,
  7106. * "parent_id": 10,
  7107. * "name": "Child Group 1"
  7108. * },{
  7109. * "id": 3,
  7110. * "parent_id": 10,
  7111. * "name": "Child Group 2"
  7112. * },{
  7113. * "id": 4,
  7114. * "parent_id": 10,
  7115. * "name": "Child Group 3"
  7116. * }]
  7117. * }
  7118. * }
  7119. *
  7120. * // Client code
  7121. * Ext.define('Group', {
  7122. * extend: 'Ext.data.Model',
  7123. * fields: ['id', 'parent_id', 'name'],
  7124. * proxy: {
  7125. * type: 'ajax',
  7126. * url: 'data.json',
  7127. * reader: {
  7128. * type: 'json',
  7129. * root: 'groups'
  7130. * }
  7131. * },
  7132. * associations: [{
  7133. * type: 'hasMany',
  7134. * model: 'Group',
  7135. * primaryKey: 'id',
  7136. * foreignKey: 'parent_id',
  7137. * autoLoad: true,
  7138. * associationKey: 'child_groups' // read child data from child_groups
  7139. * }, {
  7140. * type: 'belongsTo',
  7141. * model: 'Group',
  7142. * primaryKey: 'id',
  7143. * foreignKey: 'parent_id',
  7144. * associationKey: 'parent_group' // read parent data from parent_group
  7145. * }]
  7146. * });
  7147. *
  7148. * Ext.onReady(function(){
  7149. *
  7150. * Group.load(10, {
  7151. * success: function(group){
  7152. * console.log(group.getGroup().get('name'));
  7153. *
  7154. * group.groups().each(function(rec){
  7155. * console.log(rec.get('name'));
  7156. * });
  7157. * }
  7158. * });
  7159. *
  7160. * });
  7161. *
  7162. */
  7163. Ext.define('Ext.data.Association', {
  7164. /**
  7165. * @cfg {String} ownerModel (required)
  7166. * The string name of the model that owns the association.
  7167. */
  7168. /**
  7169. * @cfg {String} associatedModel (required)
  7170. * The string name of the model that is being associated with.
  7171. */
  7172. /**
  7173. * @cfg {String} primaryKey
  7174. * The name of the primary key on the associated model. In general this will be the
  7175. * {@link Ext.data.Model#idProperty} of the Model.
  7176. */
  7177. primaryKey: 'id',
  7178. /**
  7179. * @cfg {Ext.data.reader.Reader} reader
  7180. * A special reader to read associated data
  7181. */
  7182. /**
  7183. * @cfg {String} associationKey
  7184. * The name of the property in the data to read the association from. Defaults to the name of the associated model.
  7185. */
  7186. defaultReaderType: 'json',
  7187. statics: {
  7188. create: function(association){
  7189. if (!association.isAssociation) {
  7190. if (Ext.isString(association)) {
  7191. association = {
  7192. type: association
  7193. };
  7194. }
  7195. switch (association.type) {
  7196. case 'belongsTo':
  7197. return Ext.create('Ext.data.BelongsToAssociation', association);
  7198. case 'hasMany':
  7199. return Ext.create('Ext.data.HasManyAssociation', association);
  7200. //TODO Add this back when it's fixed
  7201. // case 'polymorphic':
  7202. // return Ext.create('Ext.data.PolymorphicAssociation', association);
  7203. default:
  7204. //<debug>
  7205. Ext.Error.raise('Unknown Association type: "' + association.type + '"');
  7206. //</debug>
  7207. }
  7208. }
  7209. return association;
  7210. }
  7211. },
  7212. /**
  7213. * Creates the Association object.
  7214. * @param {Object} [config] Config object.
  7215. */
  7216. constructor: function(config) {
  7217. Ext.apply(this, config);
  7218. var types = Ext.ModelManager.types,
  7219. ownerName = config.ownerModel,
  7220. associatedName = config.associatedModel,
  7221. ownerModel = types[ownerName],
  7222. associatedModel = types[associatedName],
  7223. ownerProto;
  7224. //<debug>
  7225. if (ownerModel === undefined) {
  7226. Ext.Error.raise("The configured ownerModel was not valid (you tried " + ownerName + ")");
  7227. }
  7228. if (associatedModel === undefined) {
  7229. Ext.Error.raise("The configured associatedModel was not valid (you tried " + associatedName + ")");
  7230. }
  7231. //</debug>
  7232. this.ownerModel = ownerModel;
  7233. this.associatedModel = associatedModel;
  7234. /**
  7235. * @property {String} ownerName
  7236. * The name of the model that 'owns' the association
  7237. */
  7238. /**
  7239. * @property {String} associatedName
  7240. * The name of the model is on the other end of the association (e.g. if a User model hasMany Orders, this is
  7241. * 'Order')
  7242. */
  7243. Ext.applyIf(this, {
  7244. ownerName : ownerName,
  7245. associatedName: associatedName
  7246. });
  7247. },
  7248. /**
  7249. * Get a specialized reader for reading associated data
  7250. * @return {Ext.data.reader.Reader} The reader, null if not supplied
  7251. */
  7252. getReader: function(){
  7253. var me = this,
  7254. reader = me.reader,
  7255. model = me.associatedModel;
  7256. if (reader) {
  7257. if (Ext.isString(reader)) {
  7258. reader = {
  7259. type: reader
  7260. };
  7261. }
  7262. if (reader.isReader) {
  7263. reader.setModel(model);
  7264. } else {
  7265. Ext.applyIf(reader, {
  7266. model: model,
  7267. type : me.defaultReaderType
  7268. });
  7269. }
  7270. me.reader = Ext.createByAlias('reader.' + reader.type, reader);
  7271. }
  7272. return me.reader || null;
  7273. }
  7274. });
  7275. /**
  7276. * @author Ed Spencer
  7277. * @class Ext.ModelManager
  7278. * @extends Ext.AbstractManager
  7279. The ModelManager keeps track of all {@link Ext.data.Model} types defined in your application.
  7280. __Creating Model Instances__
  7281. Model instances can be created by using the {@link Ext#create Ext.create} method. Ext.create replaces
  7282. the deprecated {@link #create Ext.ModelManager.create} method. It is also possible to create a model instance
  7283. this by using the Model type directly. The following 3 snippets are equivalent:
  7284. Ext.define('User', {
  7285. extend: 'Ext.data.Model',
  7286. fields: ['first', 'last']
  7287. });
  7288. // method 1, create using Ext.create (recommended)
  7289. Ext.create('User', {
  7290. first: 'Ed',
  7291. last: 'Spencer'
  7292. });
  7293. // method 2, create through the manager (deprecated)
  7294. Ext.ModelManager.create({
  7295. first: 'Ed',
  7296. last: 'Spencer'
  7297. }, 'User');
  7298. // method 3, create on the type directly
  7299. new User({
  7300. first: 'Ed',
  7301. last: 'Spencer'
  7302. });
  7303. __Accessing Model Types__
  7304. A reference to a Model type can be obtained by using the {@link #getModel} function. Since models types
  7305. are normal classes, you can access the type directly. The following snippets are equivalent:
  7306. Ext.define('User', {
  7307. extend: 'Ext.data.Model',
  7308. fields: ['first', 'last']
  7309. });
  7310. // method 1, access model type through the manager
  7311. var UserType = Ext.ModelManager.getModel('User');
  7312. // method 2, reference the type directly
  7313. var UserType = User;
  7314. * @markdown
  7315. * @singleton
  7316. */
  7317. Ext.define('Ext.ModelManager', {
  7318. extend: 'Ext.AbstractManager',
  7319. alternateClassName: 'Ext.ModelMgr',
  7320. requires: ['Ext.data.Association'],
  7321. singleton: true,
  7322. typeName: 'mtype',
  7323. /**
  7324. * Private stack of associations that must be created once their associated model has been defined
  7325. * @property {Ext.data.Association[]} associationStack
  7326. */
  7327. associationStack: [],
  7328. /**
  7329. * Registers a model definition. All model plugins marked with isDefault: true are bootstrapped
  7330. * immediately, as are any addition plugins defined in the model config.
  7331. * @private
  7332. */
  7333. registerType: function(name, config) {
  7334. var proto = config.prototype,
  7335. model;
  7336. if (proto && proto.isModel) {
  7337. // registering an already defined model
  7338. model = config;
  7339. } else {
  7340. // passing in a configuration
  7341. if (!config.extend) {
  7342. config.extend = 'Ext.data.Model';
  7343. }
  7344. model = Ext.define(name, config);
  7345. }
  7346. this.types[name] = model;
  7347. return model;
  7348. },
  7349. /**
  7350. * @private
  7351. * Private callback called whenever a model has just been defined. This sets up any associations
  7352. * that were waiting for the given model to be defined
  7353. * @param {Function} model The model that was just created
  7354. */
  7355. onModelDefined: function(model) {
  7356. var stack = this.associationStack,
  7357. length = stack.length,
  7358. create = [],
  7359. association, i, created;
  7360. for (i = 0; i < length; i++) {
  7361. association = stack[i];
  7362. if (association.associatedModel == model.modelName) {
  7363. create.push(association);
  7364. }
  7365. }
  7366. for (i = 0, length = create.length; i < length; i++) {
  7367. created = create[i];
  7368. this.types[created.ownerModel].prototype.associations.add(Ext.data.Association.create(created));
  7369. Ext.Array.remove(stack, created);
  7370. }
  7371. },
  7372. /**
  7373. * Registers an association where one of the models defined doesn't exist yet.
  7374. * The ModelManager will check when new models are registered if it can link them
  7375. * together
  7376. * @private
  7377. * @param {Ext.data.Association} association The association
  7378. */
  7379. registerDeferredAssociation: function(association){
  7380. this.associationStack.push(association);
  7381. },
  7382. /**
  7383. * Returns the {@link Ext.data.Model} for a given model name
  7384. * @param {String/Object} id The id of the model or the model instance.
  7385. * @return {Ext.data.Model} a model class.
  7386. */
  7387. getModel: function(id) {
  7388. var model = id;
  7389. if (typeof model == 'string') {
  7390. model = this.types[model];
  7391. }
  7392. return model;
  7393. },
  7394. /**
  7395. * Creates a new instance of a Model using the given data.
  7396. *
  7397. * This method is deprecated. Use {@link Ext#create Ext.create} instead. For example:
  7398. *
  7399. * Ext.create('User', {
  7400. * first: 'Ed',
  7401. * last: 'Spencer'
  7402. * });
  7403. *
  7404. * @param {Object} data Data to initialize the Model's fields with
  7405. * @param {String} name The name of the model to create
  7406. * @param {Number} id (Optional) unique id of the Model instance (see {@link Ext.data.Model})
  7407. */
  7408. create: function(config, name, id) {
  7409. var con = typeof name == 'function' ? name : this.types[name || config.name];
  7410. return new con(config, id);
  7411. }
  7412. }, function() {
  7413. /**
  7414. * Old way for creating Model classes. Instead use:
  7415. *
  7416. * Ext.define("MyModel", {
  7417. * extend: "Ext.data.Model",
  7418. * fields: []
  7419. * });
  7420. *
  7421. * @param {String} name Name of the Model class.
  7422. * @param {Object} config A configuration object for the Model you wish to create.
  7423. * @return {Ext.data.Model} The newly registered Model
  7424. * @member Ext
  7425. * @deprecated 4.0.0 Use {@link Ext#define} instead.
  7426. */
  7427. Ext.regModel = function() {
  7428. //<debug>
  7429. if (Ext.isDefined(Ext.global.console)) {
  7430. Ext.global.console.warn('Ext.regModel has been deprecated. Models can now be created by extending Ext.data.Model: Ext.define("MyModel", {extend: "Ext.data.Model", fields: []});.');
  7431. }
  7432. //</debug>
  7433. return this.ModelManager.registerType.apply(this.ModelManager, arguments);
  7434. };
  7435. });
  7436. /**
  7437. * @singleton
  7438. *
  7439. * Provides a registry of available Plugin classes indexed by a mnemonic code known as the Plugin's ptype.
  7440. *
  7441. * A plugin may be specified simply as a *config object* as long as the correct `ptype` is specified:
  7442. *
  7443. * {
  7444. * ptype: 'gridviewdragdrop',
  7445. * dragText: 'Drag and drop to reorganize'
  7446. * }
  7447. *
  7448. * Or just use the ptype on its own:
  7449. *
  7450. * 'gridviewdragdrop'
  7451. *
  7452. * Alternatively you can instantiate the plugin with Ext.create:
  7453. *
  7454. * Ext.create('Ext.view.plugin.AutoComplete', {
  7455. * ptype: 'gridviewdragdrop',
  7456. * dragText: 'Drag and drop to reorganize'
  7457. * })
  7458. */
  7459. Ext.define('Ext.PluginManager', {
  7460. extend: 'Ext.AbstractManager',
  7461. alternateClassName: 'Ext.PluginMgr',
  7462. singleton: true,
  7463. typeName: 'ptype',
  7464. /**
  7465. * Creates a new Plugin from the specified config object using the config object's ptype to determine the class to
  7466. * instantiate.
  7467. * @param {Object} config A configuration object for the Plugin you wish to create.
  7468. * @param {Function} defaultType (optional) The constructor to provide the default Plugin type if the config object does not
  7469. * contain a `ptype`. (Optional if the config contains a `ptype`).
  7470. * @return {Ext.Component} The newly instantiated Plugin.
  7471. */
  7472. //create: function(plugin, defaultType) {
  7473. // if (plugin instanceof this) {
  7474. // return plugin;
  7475. // } else {
  7476. // var type, config = {};
  7477. //
  7478. // if (Ext.isString(plugin)) {
  7479. // type = plugin;
  7480. // }
  7481. // else {
  7482. // type = plugin[this.typeName] || defaultType;
  7483. // config = plugin;
  7484. // }
  7485. //
  7486. // return Ext.createByAlias('plugin.' + type, config);
  7487. // }
  7488. //},
  7489. create : function(config, defaultType){
  7490. if (config.init) {
  7491. return config;
  7492. } else {
  7493. return Ext.createByAlias('plugin.' + (config.ptype || defaultType), config);
  7494. }
  7495. // Prior system supported Singleton plugins.
  7496. //var PluginCls = this.types[config.ptype || defaultType];
  7497. //if (PluginCls.init) {
  7498. // return PluginCls;
  7499. //} else {
  7500. // return new PluginCls(config);
  7501. //}
  7502. },
  7503. /**
  7504. * Returns all plugins registered with the given type. Here, 'type' refers to the type of plugin, not its ptype.
  7505. * @param {String} type The type to search for
  7506. * @param {Boolean} defaultsOnly True to only return plugins of this type where the plugin's isDefault property is
  7507. * truthy
  7508. * @return {Ext.AbstractPlugin[]} All matching plugins
  7509. */
  7510. findByType: function(type, defaultsOnly) {
  7511. var matches = [],
  7512. types = this.types;
  7513. for (var name in types) {
  7514. if (!types.hasOwnProperty(name)) {
  7515. continue;
  7516. }
  7517. var item = types[name];
  7518. if (item.type == type && (!defaultsOnly || (defaultsOnly === true && item.isDefault))) {
  7519. matches.push(item);
  7520. }
  7521. }
  7522. return matches;
  7523. }
  7524. }, function() {
  7525. /**
  7526. * Shorthand for {@link Ext.PluginManager#registerType}
  7527. * @param {String} ptype The ptype mnemonic string by which the Plugin class
  7528. * may be looked up.
  7529. * @param {Function} cls The new Plugin class.
  7530. * @member Ext
  7531. * @method preg
  7532. */
  7533. Ext.preg = function() {
  7534. return Ext.PluginManager.registerType.apply(Ext.PluginManager, arguments);
  7535. };
  7536. });
  7537. /**
  7538. * Represents an HTML fragment template. Templates may be {@link #compile precompiled} for greater performance.
  7539. *
  7540. * An instance of this class may be created by passing to the constructor either a single argument, or multiple
  7541. * arguments:
  7542. *
  7543. * # Single argument: String/Array
  7544. *
  7545. * The single argument may be either a String or an Array:
  7546. *
  7547. * - String:
  7548. *
  7549. * var t = new Ext.Template("<div>Hello {0}.</div>");
  7550. * t.{@link #append}('some-element', ['foo']);
  7551. *
  7552. * - Array:
  7553. *
  7554. * An Array will be combined with `join('')`.
  7555. *
  7556. * var t = new Ext.Template([
  7557. * '<div name="{id}">',
  7558. * '<span class="{cls}">{name:trim} {value:ellipsis(10)}</span>',
  7559. * '</div>',
  7560. * ]);
  7561. * t.{@link #compile}();
  7562. * t.{@link #append}('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
  7563. *
  7564. * # Multiple arguments: String, Object, Array, ...
  7565. *
  7566. * Multiple arguments will be combined with `join('')`.
  7567. *
  7568. * var t = new Ext.Template(
  7569. * '<div name="{id}">',
  7570. * '<span class="{cls}">{name} {value}</span>',
  7571. * '</div>',
  7572. * // a configuration object:
  7573. * {
  7574. * compiled: true, // {@link #compile} immediately
  7575. * }
  7576. * );
  7577. *
  7578. * # Notes
  7579. *
  7580. * - For a list of available format functions, see {@link Ext.util.Format}.
  7581. * - `disableFormats` reduces `{@link #apply}` time when no formatting is required.
  7582. */
  7583. Ext.define('Ext.Template', {
  7584. /* Begin Definitions */
  7585. requires: ['Ext.DomHelper', 'Ext.util.Format'],
  7586. inheritableStatics: {
  7587. /**
  7588. * Creates a template from the passed element's value (_display:none_ textarea, preferred) or innerHTML.
  7589. * @param {String/HTMLElement} el A DOM element or its id
  7590. * @param {Object} config (optional) Config object
  7591. * @return {Ext.Template} The created template
  7592. * @static
  7593. * @inheritable
  7594. */
  7595. from: function(el, config) {
  7596. el = Ext.getDom(el);
  7597. return new this(el.value || el.innerHTML, config || '');
  7598. }
  7599. },
  7600. /* End Definitions */
  7601. /**
  7602. * Creates new template.
  7603. *
  7604. * @param {String...} html List of strings to be concatenated into template.
  7605. * Alternatively an array of strings can be given, but then no config object may be passed.
  7606. * @param {Object} config (optional) Config object
  7607. */
  7608. constructor: function(html) {
  7609. var me = this,
  7610. args = arguments,
  7611. buffer = [],
  7612. i = 0,
  7613. length = args.length,
  7614. value;
  7615. me.initialConfig = {};
  7616. if (length > 1) {
  7617. for (; i < length; i++) {
  7618. value = args[i];
  7619. if (typeof value == 'object') {
  7620. Ext.apply(me.initialConfig, value);
  7621. Ext.apply(me, value);
  7622. } else {
  7623. buffer.push(value);
  7624. }
  7625. }
  7626. html = buffer.join('');
  7627. } else {
  7628. if (Ext.isArray(html)) {
  7629. buffer.push(html.join(''));
  7630. } else {
  7631. buffer.push(html);
  7632. }
  7633. }
  7634. // @private
  7635. me.html = buffer.join('');
  7636. if (me.compiled) {
  7637. me.compile();
  7638. }
  7639. },
  7640. isTemplate: true,
  7641. /**
  7642. * @cfg {Boolean} compiled
  7643. * True to immediately compile the template. Defaults to false.
  7644. */
  7645. /**
  7646. * @cfg {Boolean} disableFormats
  7647. * True to disable format functions in the template. If the template doesn't contain
  7648. * format functions, setting disableFormats to true will reduce apply time. Defaults to false.
  7649. */
  7650. disableFormats: false,
  7651. re: /\{([\w\-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
  7652. /**
  7653. * Returns an HTML fragment of this template with the specified values applied.
  7654. *
  7655. * @param {Object/Array} values The template values. Can be an array if your params are numeric:
  7656. *
  7657. * var tpl = new Ext.Template('Name: {0}, Age: {1}');
  7658. * tpl.applyTemplate(['John', 25]);
  7659. *
  7660. * or an object:
  7661. *
  7662. * var tpl = new Ext.Template('Name: {name}, Age: {age}');
  7663. * tpl.applyTemplate({name: 'John', age: 25});
  7664. *
  7665. * @return {String} The HTML fragment
  7666. */
  7667. applyTemplate: function(values) {
  7668. var me = this,
  7669. useFormat = me.disableFormats !== true,
  7670. fm = Ext.util.Format,
  7671. tpl = me;
  7672. if (me.compiled) {
  7673. return me.compiled(values);
  7674. }
  7675. function fn(m, name, format, args) {
  7676. if (format && useFormat) {
  7677. if (args) {
  7678. args = [values[name]].concat(Ext.functionFactory('return ['+ args +'];')());
  7679. } else {
  7680. args = [values[name]];
  7681. }
  7682. if (format.substr(0, 5) == "this.") {
  7683. return tpl[format.substr(5)].apply(tpl, args);
  7684. }
  7685. else {
  7686. return fm[format].apply(fm, args);
  7687. }
  7688. }
  7689. else {
  7690. return values[name] !== undefined ? values[name] : "";
  7691. }
  7692. }
  7693. return me.html.replace(me.re, fn);
  7694. },
  7695. /**
  7696. * Sets the HTML used as the template and optionally compiles it.
  7697. * @param {String} html
  7698. * @param {Boolean} compile (optional) True to compile the template.
  7699. * @return {Ext.Template} this
  7700. */
  7701. set: function(html, compile) {
  7702. var me = this;
  7703. me.html = html;
  7704. me.compiled = null;
  7705. return compile ? me.compile() : me;
  7706. },
  7707. compileARe: /\\/g,
  7708. compileBRe: /(\r\n|\n)/g,
  7709. compileCRe: /'/g,
  7710. /**
  7711. * Compiles the template into an internal function, eliminating the RegEx overhead.
  7712. * @return {Ext.Template} this
  7713. */
  7714. compile: function() {
  7715. var me = this,
  7716. fm = Ext.util.Format,
  7717. useFormat = me.disableFormats !== true,
  7718. body, bodyReturn;
  7719. function fn(m, name, format, args) {
  7720. if (format && useFormat) {
  7721. args = args ? ',' + args: "";
  7722. if (format.substr(0, 5) != "this.") {
  7723. format = "fm." + format + '(';
  7724. }
  7725. else {
  7726. format = 'this.' + format.substr(5) + '(';
  7727. }
  7728. }
  7729. else {
  7730. args = '';
  7731. format = "(values['" + name + "'] == undefined ? '' : ";
  7732. }
  7733. return "'," + format + "values['" + name + "']" + args + ") ,'";
  7734. }
  7735. bodyReturn = me.html.replace(me.compileARe, '\\\\').replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn);
  7736. body = "this.compiled = function(values){ return ['" + bodyReturn + "'].join('');};";
  7737. eval(body);
  7738. return me;
  7739. },
  7740. /**
  7741. * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
  7742. *
  7743. * @param {String/HTMLElement/Ext.Element} el The context element
  7744. * @param {Object/Array} values The template values. See {@link #applyTemplate} for details.
  7745. * @param {Boolean} returnElement (optional) true to return a Ext.Element.
  7746. * @return {HTMLElement/Ext.Element} The new node or Element
  7747. */
  7748. insertFirst: function(el, values, returnElement) {
  7749. return this.doInsert('afterBegin', el, values, returnElement);
  7750. },
  7751. /**
  7752. * Applies the supplied values to the template and inserts the new node(s) before el.
  7753. *
  7754. * @param {String/HTMLElement/Ext.Element} el The context element
  7755. * @param {Object/Array} values The template values. See {@link #applyTemplate} for details.
  7756. * @param {Boolean} returnElement (optional) true to return a Ext.Element.
  7757. * @return {HTMLElement/Ext.Element} The new node or Element
  7758. */
  7759. insertBefore: function(el, values, returnElement) {
  7760. return this.doInsert('beforeBegin', el, values, returnElement);
  7761. },
  7762. /**
  7763. * Applies the supplied values to the template and inserts the new node(s) after el.
  7764. *
  7765. * @param {String/HTMLElement/Ext.Element} el The context element
  7766. * @param {Object/Array} values The template values. See {@link #applyTemplate} for details.
  7767. * @param {Boolean} returnElement (optional) true to return a Ext.Element.
  7768. * @return {HTMLElement/Ext.Element} The new node or Element
  7769. */
  7770. insertAfter: function(el, values, returnElement) {
  7771. return this.doInsert('afterEnd', el, values, returnElement);
  7772. },
  7773. /**
  7774. * Applies the supplied `values` to the template and appends the new node(s) to the specified `el`.
  7775. *
  7776. * For example usage see {@link Ext.Template Ext.Template class docs}.
  7777. *
  7778. * @param {String/HTMLElement/Ext.Element} el The context element
  7779. * @param {Object/Array} values The template values. See {@link #applyTemplate} for details.
  7780. * @param {Boolean} returnElement (optional) true to return an Ext.Element.
  7781. * @return {HTMLElement/Ext.Element} The new node or Element
  7782. */
  7783. append: function(el, values, returnElement) {
  7784. return this.doInsert('beforeEnd', el, values, returnElement);
  7785. },
  7786. doInsert: function(where, el, values, returnEl) {
  7787. el = Ext.getDom(el);
  7788. var newNode = Ext.DomHelper.insertHtml(where, el, this.applyTemplate(values));
  7789. return returnEl ? Ext.get(newNode, true) : newNode;
  7790. },
  7791. /**
  7792. * Applies the supplied values to the template and overwrites the content of el with the new node(s).
  7793. *
  7794. * @param {String/HTMLElement/Ext.Element} el The context element
  7795. * @param {Object/Array} values The template values. See {@link #applyTemplate} for details.
  7796. * @param {Boolean} returnElement (optional) true to return a Ext.Element.
  7797. * @return {HTMLElement/Ext.Element} The new node or Element
  7798. */
  7799. overwrite: function(el, values, returnElement) {
  7800. el = Ext.getDom(el);
  7801. el.innerHTML = this.applyTemplate(values);
  7802. return returnElement ? Ext.get(el.firstChild, true) : el.firstChild;
  7803. }
  7804. }, function() {
  7805. /**
  7806. * @method apply
  7807. * @member Ext.Template
  7808. * Alias for {@link #applyTemplate}.
  7809. * @alias Ext.Template#applyTemplate
  7810. */
  7811. this.createAlias('apply', 'applyTemplate');
  7812. });
  7813. /**
  7814. * A template class that supports advanced functionality like:
  7815. *
  7816. * - Autofilling arrays using templates and sub-templates
  7817. * - Conditional processing with basic comparison operators
  7818. * - Basic math function support
  7819. * - Execute arbitrary inline code with special built-in template variables
  7820. * - Custom member functions
  7821. * - Many special tags and built-in operators that aren't defined as part of the API, but are supported in the templates that can be created
  7822. *
  7823. * XTemplate provides the templating mechanism built into:
  7824. *
  7825. * - {@link Ext.view.View}
  7826. *
  7827. * The {@link Ext.Template} describes the acceptable parameters to pass to the constructor. The following examples
  7828. * demonstrate all of the supported features.
  7829. *
  7830. * # Sample Data
  7831. *
  7832. * This is the data object used for reference in each code example:
  7833. *
  7834. * var data = {
  7835. * name: 'Tommy Maintz',
  7836. * title: 'Lead Developer',
  7837. * company: 'Sencha Inc.',
  7838. * email: 'tommy@sencha.com',
  7839. * address: '5 Cups Drive',
  7840. * city: 'Palo Alto',
  7841. * state: 'CA',
  7842. * zip: '44102',
  7843. * drinks: ['Coffee', 'Soda', 'Water'],
  7844. * kids: [
  7845. * {
  7846. * name: 'Joshua',
  7847. * age:3
  7848. * },
  7849. * {
  7850. * name: 'Matthew',
  7851. * age:2
  7852. * },
  7853. * {
  7854. * name: 'Solomon',
  7855. * age:0
  7856. * }
  7857. * ]
  7858. * };
  7859. *
  7860. * # Auto filling of arrays
  7861. *
  7862. * The **tpl** tag and the **for** operator are used to process the provided data object:
  7863. *
  7864. * - If the value specified in for is an array, it will auto-fill, repeating the template block inside the tpl
  7865. * tag for each item in the array.
  7866. * - If for="." is specified, the data object provided is examined.
  7867. * - While processing an array, the special variable {#} will provide the current array index + 1 (starts at 1, not 0).
  7868. *
  7869. * Examples:
  7870. *
  7871. * <tpl for=".">...</tpl> // loop through array at root node
  7872. * <tpl for="foo">...</tpl> // loop through array at foo node
  7873. * <tpl for="foo.bar">...</tpl> // loop through array at foo.bar node
  7874. *
  7875. * Using the sample data above:
  7876. *
  7877. * var tpl = new Ext.XTemplate(
  7878. * '<p>Kids: ',
  7879. * '<tpl for=".">', // process the data.kids node
  7880. * '<p>{#}. {name}</p>', // use current array index to autonumber
  7881. * '</tpl></p>'
  7882. * );
  7883. * tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
  7884. *
  7885. * An example illustrating how the **for** property can be leveraged to access specified members of the provided data
  7886. * object to populate the template:
  7887. *
  7888. * var tpl = new Ext.XTemplate(
  7889. * '<p>Name: {name}</p>',
  7890. * '<p>Title: {title}</p>',
  7891. * '<p>Company: {company}</p>',
  7892. * '<p>Kids: ',
  7893. * '<tpl for="kids">', // interrogate the kids property within the data
  7894. * '<p>{name}</p>',
  7895. * '</tpl></p>'
  7896. * );
  7897. * tpl.overwrite(panel.body, data); // pass the root node of the data object
  7898. *
  7899. * Flat arrays that contain values (and not objects) can be auto-rendered using the special **`{.}`** variable inside a
  7900. * loop. This variable will represent the value of the array at the current index:
  7901. *
  7902. * var tpl = new Ext.XTemplate(
  7903. * '<p>{name}\'s favorite beverages:</p>',
  7904. * '<tpl for="drinks">',
  7905. * '<div> - {.}</div>',
  7906. * '</tpl>'
  7907. * );
  7908. * tpl.overwrite(panel.body, data);
  7909. *
  7910. * When processing a sub-template, for example while looping through a child array, you can access the parent object's
  7911. * members via the **parent** object:
  7912. *
  7913. * var tpl = new Ext.XTemplate(
  7914. * '<p>Name: {name}</p>',
  7915. * '<p>Kids: ',
  7916. * '<tpl for="kids">',
  7917. * '<tpl if="age &gt; 1">',
  7918. * '<p>{name}</p>',
  7919. * '<p>Dad: {parent.name}</p>',
  7920. * '</tpl>',
  7921. * '</tpl></p>'
  7922. * );
  7923. * tpl.overwrite(panel.body, data);
  7924. *
  7925. * # Conditional processing with basic comparison operators
  7926. *
  7927. * The **tpl** tag and the **if** operator are used to provide conditional checks for deciding whether or not to render
  7928. * specific parts of the template. Notes:
  7929. *
  7930. * - Double quotes must be encoded if used within the conditional
  7931. * - There is no else operator -- if needed, two opposite if statements should be used.
  7932. *
  7933. * Examples:
  7934. *
  7935. * <tpl if="age > 1 && age < 10">Child</tpl>
  7936. * <tpl if="age >= 10 && age < 18">Teenager</tpl>
  7937. * <tpl if="this.isGirl(name)">...</tpl>
  7938. * <tpl if="id==\'download\'">...</tpl>
  7939. * <tpl if="needsIcon"><img src="{icon}" class="{iconCls}"/></tpl>
  7940. * // no good:
  7941. * <tpl if="name == "Tommy"">Hello</tpl>
  7942. * // encode " if it is part of the condition, e.g.
  7943. * <tpl if="name == &quot;Tommy&quot;">Hello</tpl>
  7944. *
  7945. * Using the sample data above:
  7946. *
  7947. * var tpl = new Ext.XTemplate(
  7948. * '<p>Name: {name}</p>',
  7949. * '<p>Kids: ',
  7950. * '<tpl for="kids">',
  7951. * '<tpl if="age &gt; 1">',
  7952. * '<p>{name}</p>',
  7953. * '</tpl>',
  7954. * '</tpl></p>'
  7955. * );
  7956. * tpl.overwrite(panel.body, data);
  7957. *
  7958. * # Basic math support
  7959. *
  7960. * The following basic math operators may be applied directly on numeric data values:
  7961. *
  7962. * + - * /
  7963. *
  7964. * For example:
  7965. *
  7966. * var tpl = new Ext.XTemplate(
  7967. * '<p>Name: {name}</p>',
  7968. * '<p>Kids: ',
  7969. * '<tpl for="kids">',
  7970. * '<tpl if="age &gt; 1">', // <-- Note that the > is encoded
  7971. * '<p>{#}: {name}</p>', // <-- Auto-number each item
  7972. * '<p>In 5 Years: {age+5}</p>', // <-- Basic math
  7973. * '<p>Dad: {parent.name}</p>',
  7974. * '</tpl>',
  7975. * '</tpl></p>'
  7976. * );
  7977. * tpl.overwrite(panel.body, data);
  7978. *
  7979. * # Execute arbitrary inline code with special built-in template variables
  7980. *
  7981. * Anything between `{[ ... ]}` is considered code to be executed in the scope of the template. There are some special
  7982. * variables available in that code:
  7983. *
  7984. * - **values**: The values in the current scope. If you are using scope changing sub-templates,
  7985. * you can change what values is.
  7986. * - **parent**: The scope (values) of the ancestor template.
  7987. * - **xindex**: If you are in a looping template, the index of the loop you are in (1-based).
  7988. * - **xcount**: If you are in a looping template, the total length of the array you are looping.
  7989. *
  7990. * This example demonstrates basic row striping using an inline code block and the xindex variable:
  7991. *
  7992. * var tpl = new Ext.XTemplate(
  7993. * '<p>Name: {name}</p>',
  7994. * '<p>Company: {[values.company.toUpperCase() + ", " + values.title]}</p>',
  7995. * '<p>Kids: ',
  7996. * '<tpl for="kids">',
  7997. * '<div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
  7998. * '{name}',
  7999. * '</div>',
  8000. * '</tpl></p>'
  8001. * );
  8002. * tpl.overwrite(panel.body, data);
  8003. *
  8004. * # Template member functions
  8005. *
  8006. * One or more member functions can be specified in a configuration object passed into the XTemplate constructor for
  8007. * more complex processing:
  8008. *
  8009. * var tpl = new Ext.XTemplate(
  8010. * '<p>Name: {name}</p>',
  8011. * '<p>Kids: ',
  8012. * '<tpl for="kids">',
  8013. * '<tpl if="this.isGirl(name)">',
  8014. * '<p>Girl: {name} - {age}</p>',
  8015. * '</tpl>',
  8016. * // use opposite if statement to simulate 'else' processing:
  8017. * '<tpl if="this.isGirl(name) == false">',
  8018. * '<p>Boy: {name} - {age}</p>',
  8019. * '</tpl>',
  8020. * '<tpl if="this.isBaby(age)">',
  8021. * '<p>{name} is a baby!</p>',
  8022. * '</tpl>',
  8023. * '</tpl></p>',
  8024. * {
  8025. * // XTemplate configuration:
  8026. * disableFormats: true,
  8027. * // member functions:
  8028. * isGirl: function(name){
  8029. * return name == 'Sara Grace';
  8030. * },
  8031. * isBaby: function(age){
  8032. * return age < 1;
  8033. * }
  8034. * }
  8035. * );
  8036. * tpl.overwrite(panel.body, data);
  8037. */
  8038. Ext.define('Ext.XTemplate', {
  8039. /* Begin Definitions */
  8040. extend: 'Ext.Template',
  8041. /* End Definitions */
  8042. argsRe: /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
  8043. nameRe: /^<tpl\b[^>]*?for="(.*?)"/,
  8044. ifRe: /^<tpl\b[^>]*?if="(.*?)"/,
  8045. execRe: /^<tpl\b[^>]*?exec="(.*?)"/,
  8046. constructor: function() {
  8047. this.callParent(arguments);
  8048. var me = this,
  8049. html = me.html,
  8050. argsRe = me.argsRe,
  8051. nameRe = me.nameRe,
  8052. ifRe = me.ifRe,
  8053. execRe = me.execRe,
  8054. id = 0,
  8055. tpls = [],
  8056. VALUES = 'values',
  8057. PARENT = 'parent',
  8058. XINDEX = 'xindex',
  8059. XCOUNT = 'xcount',
  8060. RETURN = 'return ',
  8061. WITHVALUES = 'with(values){ ',
  8062. m, matchName, matchIf, matchExec, exp, fn, exec, name, i;
  8063. html = ['<tpl>', html, '</tpl>'].join('');
  8064. while ((m = html.match(argsRe))) {
  8065. exp = null;
  8066. fn = null;
  8067. exec = null;
  8068. matchName = m[0].match(nameRe);
  8069. matchIf = m[0].match(ifRe);
  8070. matchExec = m[0].match(execRe);
  8071. exp = matchIf ? matchIf[1] : null;
  8072. if (exp) {
  8073. fn = Ext.functionFactory(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + 'try{' + RETURN + Ext.String.htmlDecode(exp) + ';}catch(e){return;}}');
  8074. }
  8075. exp = matchExec ? matchExec[1] : null;
  8076. if (exp) {
  8077. exec = Ext.functionFactory(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + Ext.String.htmlDecode(exp) + ';}');
  8078. }
  8079. name = matchName ? matchName[1] : null;
  8080. if (name) {
  8081. if (name === '.') {
  8082. name = VALUES;
  8083. } else if (name === '..') {
  8084. name = PARENT;
  8085. }
  8086. name = Ext.functionFactory(VALUES, PARENT, 'try{' + WITHVALUES + RETURN + name + ';}}catch(e){return;}');
  8087. }
  8088. tpls.push({
  8089. id: id,
  8090. target: name,
  8091. exec: exec,
  8092. test: fn,
  8093. body: m[1] || ''
  8094. });
  8095. html = html.replace(m[0], '{xtpl' + id + '}');
  8096. id = id + 1;
  8097. }
  8098. for (i = tpls.length - 1; i >= 0; --i) {
  8099. me.compileTpl(tpls[i]);
  8100. }
  8101. me.master = tpls[tpls.length - 1];
  8102. me.tpls = tpls;
  8103. },
  8104. // @private
  8105. applySubTemplate: function(id, values, parent, xindex, xcount) {
  8106. var me = this, t = me.tpls[id];
  8107. return t.compiled.call(me, values, parent, xindex, xcount);
  8108. },
  8109. /**
  8110. * @cfg {RegExp} codeRe
  8111. * The regular expression used to match code variables. Default: matches {[expression]}.
  8112. */
  8113. codeRe: /\{\[((?:\\\]|.|\n)*?)\]\}/g,
  8114. /**
  8115. * @cfg {Boolean} compiled
  8116. * Only applies to {@link Ext.Template}, XTemplates are compiled automatically.
  8117. */
  8118. re: /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\/]\s?[\d\.\+\-\*\/\(\)]+)?\}/g,
  8119. // @private
  8120. compileTpl: function(tpl) {
  8121. var fm = Ext.util.Format,
  8122. me = this,
  8123. useFormat = me.disableFormats !== true,
  8124. body, bodyReturn, evaluatedFn;
  8125. function fn(m, name, format, args, math) {
  8126. var v;
  8127. // name is what is inside the {}
  8128. // Name begins with xtpl, use a Sub Template
  8129. if (name.substr(0, 4) == 'xtpl') {
  8130. return "',this.applySubTemplate(" + name.substr(4) + ", values, parent, xindex, xcount),'";
  8131. }
  8132. // name = "." - Just use the values object.
  8133. if (name == '.') {
  8134. // filter to not include arrays/objects/nulls
  8135. v = 'Ext.Array.indexOf(["string", "number", "boolean"], typeof values) > -1 || Ext.isDate(values) ? values : ""';
  8136. }
  8137. // name = "#" - Use the xindex
  8138. else if (name == '#') {
  8139. v = 'xindex';
  8140. }
  8141. else if (name.substr(0, 7) == "parent.") {
  8142. v = name;
  8143. }
  8144. // name has a . in it - Use object literal notation, starting from values
  8145. else if (name.indexOf('.') != -1) {
  8146. v = "values." + name;
  8147. }
  8148. // name is a property of values
  8149. else {
  8150. v = "values['" + name + "']";
  8151. }
  8152. if (math) {
  8153. v = '(' + v + math + ')';
  8154. }
  8155. if (format && useFormat) {
  8156. args = args ? ',' + args : "";
  8157. if (format.substr(0, 5) != "this.") {
  8158. format = "fm." + format + '(';
  8159. }
  8160. else {
  8161. format = 'this.' + format.substr(5) + '(';
  8162. }
  8163. }
  8164. else {
  8165. args = '';
  8166. format = "(" + v + " === undefined ? '' : ";
  8167. }
  8168. return "'," + format + v + args + "),'";
  8169. }
  8170. function codeFn(m, code) {
  8171. // Single quotes get escaped when the template is compiled, however we want to undo this when running code.
  8172. return "',(" + code.replace(me.compileARe, "'") + "),'";
  8173. }
  8174. bodyReturn = tpl.body.replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn).replace(me.codeRe, codeFn);
  8175. body = "evaluatedFn = function(values, parent, xindex, xcount){return ['" + bodyReturn + "'].join('');};";
  8176. eval(body);
  8177. tpl.compiled = function(values, parent, xindex, xcount) {
  8178. var vs,
  8179. length,
  8180. buffer,
  8181. i;
  8182. if (tpl.test && !tpl.test.call(me, values, parent, xindex, xcount)) {
  8183. return '';
  8184. }
  8185. vs = tpl.target ? tpl.target.call(me, values, parent) : values;
  8186. if (!vs) {
  8187. return '';
  8188. }
  8189. parent = tpl.target ? values : parent;
  8190. if (tpl.target && Ext.isArray(vs)) {
  8191. buffer = [];
  8192. length = vs.length;
  8193. if (tpl.exec) {
  8194. for (i = 0; i < length; i++) {
  8195. buffer[buffer.length] = evaluatedFn.call(me, vs[i], parent, i + 1, length);
  8196. tpl.exec.call(me, vs[i], parent, i + 1, length);
  8197. }
  8198. } else {
  8199. for (i = 0; i < length; i++) {
  8200. buffer[buffer.length] = evaluatedFn.call(me, vs[i], parent, i + 1, length);
  8201. }
  8202. }
  8203. return buffer.join('');
  8204. }
  8205. if (tpl.exec) {
  8206. tpl.exec.call(me, vs, parent, xindex, xcount);
  8207. }
  8208. return evaluatedFn.call(me, vs, parent, xindex, xcount);
  8209. };
  8210. return this;
  8211. },
  8212. // inherit docs from Ext.Template
  8213. applyTemplate: function(values) {
  8214. return this.master.compiled.call(this, values, {}, 1, 1);
  8215. },
  8216. /**
  8217. * Does nothing. XTemplates are compiled automatically, so this function simply returns this.
  8218. * @return {Ext.XTemplate} this
  8219. */
  8220. compile: function() {
  8221. return this;
  8222. }
  8223. }, function() {
  8224. // re-create the alias, inheriting it from Ext.Template doesn't work as intended.
  8225. this.createAlias('apply', 'applyTemplate');
  8226. });
  8227. /**
  8228. * @class Ext.app.Controller
  8229. *
  8230. * Controllers are the glue that binds an application together. All they really do is listen for events (usually from
  8231. * views) and take some action. Here's how we might create a Controller to manage Users:
  8232. *
  8233. * Ext.define('MyApp.controller.Users', {
  8234. * extend: 'Ext.app.Controller',
  8235. *
  8236. * init: function() {
  8237. * console.log('Initialized Users! This happens before the Application launch function is called');
  8238. * }
  8239. * });
  8240. *
  8241. * The init function is a special method that is called when your application boots. It is called before the
  8242. * {@link Ext.app.Application Application}'s launch function is executed so gives a hook point to run any code before
  8243. * your Viewport is created.
  8244. *
  8245. * The init function is a great place to set up how your controller interacts with the view, and is usually used in
  8246. * conjunction with another Controller function - {@link Ext.app.Controller#control control}. The control function
  8247. * makes it easy to listen to events on your view classes and take some action with a handler function. Let's update
  8248. * our Users controller to tell us when the panel is rendered:
  8249. *
  8250. * Ext.define('MyApp.controller.Users', {
  8251. * extend: 'Ext.app.Controller',
  8252. *
  8253. * init: function() {
  8254. * this.control({
  8255. * 'viewport > panel': {
  8256. * render: this.onPanelRendered
  8257. * }
  8258. * });
  8259. * },
  8260. *
  8261. * onPanelRendered: function() {
  8262. * console.log('The panel was rendered');
  8263. * }
  8264. * });
  8265. *
  8266. * We've updated the init function to use this.control to set up listeners on views in our application. The control
  8267. * function uses the new ComponentQuery engine to quickly and easily get references to components on the page. If you
  8268. * are not familiar with ComponentQuery yet, be sure to check out the {@link Ext.ComponentQuery documentation}. In brief though,
  8269. * it allows us to pass a CSS-like selector that will find every matching component on the page.
  8270. *
  8271. * In our init function above we supplied 'viewport > panel', which translates to "find me every Panel that is a direct
  8272. * child of a Viewport". We then supplied an object that maps event names (just 'render' in this case) to handler
  8273. * functions. The overall effect is that whenever any component that matches our selector fires a 'render' event, our
  8274. * onPanelRendered function is called.
  8275. *
  8276. * <u>Using refs</u>
  8277. *
  8278. * One of the most useful parts of Controllers is the new ref system. These use the new {@link Ext.ComponentQuery} to
  8279. * make it really easy to get references to Views on your page. Let's look at an example of this now:
  8280. *
  8281. * Ext.define('MyApp.controller.Users', {
  8282. * extend: 'Ext.app.Controller',
  8283. *
  8284. * refs: [
  8285. * {
  8286. * ref: 'list',
  8287. * selector: 'grid'
  8288. * }
  8289. * ],
  8290. *
  8291. * init: function() {
  8292. * this.control({
  8293. * 'button': {
  8294. * click: this.refreshGrid
  8295. * }
  8296. * });
  8297. * },
  8298. *
  8299. * refreshGrid: function() {
  8300. * this.getList().store.load();
  8301. * }
  8302. * });
  8303. *
  8304. * This example assumes the existence of a {@link Ext.grid.Panel Grid} on the page, which contains a single button to
  8305. * refresh the Grid when clicked. In our refs array, we set up a reference to the grid. There are two parts to this -
  8306. * the 'selector', which is a {@link Ext.ComponentQuery ComponentQuery} selector which finds any grid on the page and
  8307. * assigns it to the reference 'list'.
  8308. *
  8309. * By giving the reference a name, we get a number of things for free. The first is the getList function that we use in
  8310. * the refreshGrid method above. This is generated automatically by the Controller based on the name of our ref, which
  8311. * was capitalized and prepended with get to go from 'list' to 'getList'.
  8312. *
  8313. * The way this works is that the first time getList is called by your code, the ComponentQuery selector is run and the
  8314. * first component that matches the selector ('grid' in this case) will be returned. All future calls to getList will
  8315. * use a cached reference to that grid. Usually it is advised to use a specific ComponentQuery selector that will only
  8316. * match a single View in your application (in the case above our selector will match any grid on the page).
  8317. *
  8318. * Bringing it all together, our init function is called when the application boots, at which time we call this.control
  8319. * to listen to any click on a {@link Ext.button.Button button} and call our refreshGrid function (again, this will
  8320. * match any button on the page so we advise a more specific selector than just 'button', but have left it this way for
  8321. * simplicity). When the button is clicked we use out getList function to refresh the grid.
  8322. *
  8323. * You can create any number of refs and control any number of components this way, simply adding more functions to
  8324. * your Controller as you go. For an example of real-world usage of Controllers see the Feed Viewer example in the
  8325. * examples/app/feed-viewer folder in the SDK download.
  8326. *
  8327. * <u>Generated getter methods</u>
  8328. *
  8329. * Refs aren't the only thing that generate convenient getter methods. Controllers often have to deal with Models and
  8330. * Stores so the framework offers a couple of easy ways to get access to those too. Let's look at another example:
  8331. *
  8332. * Ext.define('MyApp.controller.Users', {
  8333. * extend: 'Ext.app.Controller',
  8334. *
  8335. * models: ['User'],
  8336. * stores: ['AllUsers', 'AdminUsers'],
  8337. *
  8338. * init: function() {
  8339. * var User = this.getUserModel(),
  8340. * allUsers = this.getAllUsersStore();
  8341. *
  8342. * var ed = new User({name: 'Ed'});
  8343. * allUsers.add(ed);
  8344. * }
  8345. * });
  8346. *
  8347. * By specifying Models and Stores that the Controller cares about, it again dynamically loads them from the appropriate
  8348. * locations (app/model/User.js, app/store/AllUsers.js and app/store/AdminUsers.js in this case) and creates getter
  8349. * functions for them all. The example above will create a new User model instance and add it to the AllUsers Store.
  8350. * Of course, you could do anything in this function but in this case we just did something simple to demonstrate the
  8351. * functionality.
  8352. *
  8353. * <u>Further Reading</u>
  8354. *
  8355. * For more information about writing Ext JS 4 applications, please see the
  8356. * [application architecture guide](#/guide/application_architecture). Also see the {@link Ext.app.Application} documentation.
  8357. *
  8358. * @docauthor Ed Spencer
  8359. */
  8360. Ext.define('Ext.app.Controller', {
  8361. mixins: {
  8362. observable: 'Ext.util.Observable'
  8363. },
  8364. /**
  8365. * @cfg {String} id The id of this controller. You can use this id when dispatching.
  8366. */
  8367. /**
  8368. * @cfg {String[]} models
  8369. * Array of models to require from AppName.model namespace. For example:
  8370. *
  8371. * Ext.define("MyApp.controller.Foo", {
  8372. * extend: "Ext.app.Controller",
  8373. * models: ['User', 'Vehicle']
  8374. * });
  8375. *
  8376. * This is equivalent of:
  8377. *
  8378. * Ext.define("MyApp.controller.Foo", {
  8379. * extend: "Ext.app.Controller",
  8380. * requires: ['MyApp.model.User', 'MyApp.model.Vehicle']
  8381. * });
  8382. *
  8383. */
  8384. /**
  8385. * @cfg {String[]} views
  8386. * Array of views to require from AppName.view namespace. For example:
  8387. *
  8388. * Ext.define("MyApp.controller.Foo", {
  8389. * extend: "Ext.app.Controller",
  8390. * views: ['List', 'Detail']
  8391. * });
  8392. *
  8393. * This is equivalent of:
  8394. *
  8395. * Ext.define("MyApp.controller.Foo", {
  8396. * extend: "Ext.app.Controller",
  8397. * requires: ['MyApp.view.List', 'MyApp.view.Detail']
  8398. * });
  8399. *
  8400. */
  8401. /**
  8402. * @cfg {String[]} stores
  8403. * Array of stores to require from AppName.store namespace. For example:
  8404. *
  8405. * Ext.define("MyApp.controller.Foo", {
  8406. * extend: "Ext.app.Controller",
  8407. * stores: ['Users', 'Vehicles']
  8408. * });
  8409. *
  8410. * This is equivalent of:
  8411. *
  8412. * Ext.define("MyApp.controller.Foo", {
  8413. * extend: "Ext.app.Controller",
  8414. * requires: ['MyApp.store.Users', 'MyApp.store.Vehicles']
  8415. * });
  8416. *
  8417. */
  8418. onClassExtended: function(cls, data) {
  8419. var className = Ext.getClassName(cls),
  8420. match = className.match(/^(.*)\.controller\./);
  8421. if (match !== null) {
  8422. var namespace = Ext.Loader.getPrefix(className) || match[1],
  8423. onBeforeClassCreated = data.onBeforeClassCreated,
  8424. requires = [],
  8425. modules = ['model', 'view', 'store'],
  8426. prefix;
  8427. data.onBeforeClassCreated = function(cls, data) {
  8428. var i, ln, module,
  8429. items, j, subLn, item;
  8430. for (i = 0,ln = modules.length; i < ln; i++) {
  8431. module = modules[i];
  8432. items = Ext.Array.from(data[module + 's']);
  8433. for (j = 0,subLn = items.length; j < subLn; j++) {
  8434. item = items[j];
  8435. prefix = Ext.Loader.getPrefix(item);
  8436. if (prefix === '' || prefix === item) {
  8437. requires.push(namespace + '.' + module + '.' + item);
  8438. }
  8439. else {
  8440. requires.push(item);
  8441. }
  8442. }
  8443. }
  8444. Ext.require(requires, Ext.Function.pass(onBeforeClassCreated, arguments, this));
  8445. };
  8446. }
  8447. },
  8448. /**
  8449. * Creates new Controller.
  8450. * @param {Object} config (optional) Config object.
  8451. */
  8452. constructor: function(config) {
  8453. this.mixins.observable.constructor.call(this, config);
  8454. Ext.apply(this, config || {});
  8455. this.createGetters('model', this.models);
  8456. this.createGetters('store', this.stores);
  8457. this.createGetters('view', this.views);
  8458. if (this.refs) {
  8459. this.ref(this.refs);
  8460. }
  8461. },
  8462. /**
  8463. * A template method that is called when your application boots. It is called before the
  8464. * {@link Ext.app.Application Application}'s launch function is executed so gives a hook point to run any code before
  8465. * your Viewport is created.
  8466. *
  8467. * @param {Ext.app.Application} application
  8468. * @template
  8469. */
  8470. init: function(application) {},
  8471. /**
  8472. * A template method like {@link #init}, but called after the viewport is created.
  8473. * This is called after the {@link Ext.app.Application#launch launch} method of Application is executed.
  8474. *
  8475. * @param {Ext.app.Application} application
  8476. * @template
  8477. */
  8478. onLaunch: function(application) {},
  8479. createGetters: function(type, refs) {
  8480. type = Ext.String.capitalize(type);
  8481. Ext.Array.each(refs, function(ref) {
  8482. var fn = 'get',
  8483. parts = ref.split('.');
  8484. // Handle namespaced class names. E.g. feed.Add becomes getFeedAddView etc.
  8485. Ext.Array.each(parts, function(part) {
  8486. fn += Ext.String.capitalize(part);
  8487. });
  8488. fn += type;
  8489. if (!this[fn]) {
  8490. this[fn] = Ext.Function.pass(this['get' + type], [ref], this);
  8491. }
  8492. // Execute it right away
  8493. this[fn](ref);
  8494. },
  8495. this);
  8496. },
  8497. ref: function(refs) {
  8498. var me = this;
  8499. refs = Ext.Array.from(refs);
  8500. Ext.Array.each(refs, function(info) {
  8501. var ref = info.ref,
  8502. fn = 'get' + Ext.String.capitalize(ref);
  8503. if (!me[fn]) {
  8504. me[fn] = Ext.Function.pass(me.getRef, [ref, info], me);
  8505. }
  8506. });
  8507. },
  8508. getRef: function(ref, info, config) {
  8509. this.refCache = this.refCache || {};
  8510. info = info || {};
  8511. config = config || {};
  8512. Ext.apply(info, config);
  8513. if (info.forceCreate) {
  8514. return Ext.ComponentManager.create(info, 'component');
  8515. }
  8516. var me = this,
  8517. selector = info.selector,
  8518. cached = me.refCache[ref];
  8519. if (!cached) {
  8520. me.refCache[ref] = cached = Ext.ComponentQuery.query(info.selector)[0];
  8521. if (!cached && info.autoCreate) {
  8522. me.refCache[ref] = cached = Ext.ComponentManager.create(info, 'component');
  8523. }
  8524. if (cached) {
  8525. cached.on('beforedestroy', function() {
  8526. me.refCache[ref] = null;
  8527. });
  8528. }
  8529. }
  8530. return cached;
  8531. },
  8532. /**
  8533. * Adds listeners to components selected via {@link Ext.ComponentQuery}. Accepts an
  8534. * object containing component paths mapped to a hash of listener functions.
  8535. *
  8536. * In the following example the `updateUser` function is mapped to to the `click`
  8537. * event on a button component, which is a child of the `useredit` component.
  8538. *
  8539. * Ext.define('AM.controller.Users', {
  8540. * init: function() {
  8541. * this.control({
  8542. * 'useredit button[action=save]': {
  8543. * click: this.updateUser
  8544. * }
  8545. * });
  8546. * },
  8547. *
  8548. * updateUser: function(button) {
  8549. * console.log('clicked the Save button');
  8550. * }
  8551. * });
  8552. *
  8553. * See {@link Ext.ComponentQuery} for more information on component selectors.
  8554. *
  8555. * @param {String/Object} selectors If a String, the second argument is used as the
  8556. * listeners, otherwise an object of selectors -> listeners is assumed
  8557. * @param {Object} listeners
  8558. */
  8559. control: function(selectors, listeners) {
  8560. this.application.control(selectors, listeners, this);
  8561. },
  8562. /**
  8563. * Returns instance of a {@link Ext.app.Controller controller} with the given name.
  8564. * When controller doesn't exist yet, it's created.
  8565. * @param {String} name
  8566. * @return {Ext.app.Controller} a controller instance.
  8567. */
  8568. getController: function(name) {
  8569. return this.application.getController(name);
  8570. },
  8571. /**
  8572. * Returns instance of a {@link Ext.data.Store Store} with the given name.
  8573. * When store doesn't exist yet, it's created.
  8574. * @param {String} name
  8575. * @return {Ext.data.Store} a store instance.
  8576. */
  8577. getStore: function(name) {
  8578. return this.application.getStore(name);
  8579. },
  8580. /**
  8581. * Returns a {@link Ext.data.Model Model} class with the given name.
  8582. * A shorthand for using {@link Ext.ModelManager#getModel}.
  8583. * @param {String} name
  8584. * @return {Ext.data.Model} a model class.
  8585. */
  8586. getModel: function(model) {
  8587. return this.application.getModel(model);
  8588. },
  8589. /**
  8590. * Returns a View class with the given name. To create an instance of the view,
  8591. * you can use it like it's used by Application to create the Viewport:
  8592. *
  8593. * this.getView('Viewport').create();
  8594. *
  8595. * @param {String} name
  8596. * @return {Ext.Base} a view class.
  8597. */
  8598. getView: function(view) {
  8599. return this.application.getView(view);
  8600. }
  8601. });
  8602. /**
  8603. * @author Don Griffin
  8604. *
  8605. * This class is a base for all id generators. It also provides lookup of id generators by
  8606. * their id.
  8607. *
  8608. * Generally, id generators are used to generate a primary key for new model instances. There
  8609. * are different approaches to solving this problem, so this mechanism has both simple use
  8610. * cases and is open to custom implementations. A {@link Ext.data.Model} requests id generation
  8611. * using the {@link Ext.data.Model#idgen} property.
  8612. *
  8613. * # Identity, Type and Shared IdGenerators
  8614. *
  8615. * It is often desirable to share IdGenerators to ensure uniqueness or common configuration.
  8616. * This is done by giving IdGenerator instances an id property by which they can be looked
  8617. * up using the {@link #get} method. To configure two {@link Ext.data.Model Model} classes
  8618. * to share one {@link Ext.data.SequentialIdGenerator sequential} id generator, you simply
  8619. * assign them the same id:
  8620. *
  8621. * Ext.define('MyApp.data.MyModelA', {
  8622. * extend: 'Ext.data.Model',
  8623. * idgen: {
  8624. * type: 'sequential',
  8625. * id: 'foo'
  8626. * }
  8627. * });
  8628. *
  8629. * Ext.define('MyApp.data.MyModelB', {
  8630. * extend: 'Ext.data.Model',
  8631. * idgen: {
  8632. * type: 'sequential',
  8633. * id: 'foo'
  8634. * }
  8635. * });
  8636. *
  8637. * To make this as simple as possible for generator types that are shared by many (or all)
  8638. * Models, the IdGenerator types (such as 'sequential' or 'uuid') are also reserved as
  8639. * generator id's. This is used by the {@link Ext.data.UuidGenerator} which has an id equal
  8640. * to its type ('uuid'). In other words, the following Models share the same generator:
  8641. *
  8642. * Ext.define('MyApp.data.MyModelX', {
  8643. * extend: 'Ext.data.Model',
  8644. * idgen: 'uuid'
  8645. * });
  8646. *
  8647. * Ext.define('MyApp.data.MyModelY', {
  8648. * extend: 'Ext.data.Model',
  8649. * idgen: 'uuid'
  8650. * });
  8651. *
  8652. * This can be overridden (by specifying the id explicitly), but there is no particularly
  8653. * good reason to do so for this generator type.
  8654. *
  8655. * # Creating Custom Generators
  8656. *
  8657. * An id generator should derive from this class and implement the {@link #generate} method.
  8658. * The constructor will apply config properties on new instances, so a constructor is often
  8659. * not necessary.
  8660. *
  8661. * To register an id generator type, a derived class should provide an `alias` like so:
  8662. *
  8663. * Ext.define('MyApp.data.CustomIdGenerator', {
  8664. * extend: 'Ext.data.IdGenerator',
  8665. * alias: 'idgen.custom',
  8666. *
  8667. * configProp: 42, // some config property w/default value
  8668. *
  8669. * generate: function () {
  8670. * return ... // a new id
  8671. * }
  8672. * });
  8673. *
  8674. * Using the custom id generator is then straightforward:
  8675. *
  8676. * Ext.define('MyApp.data.MyModel', {
  8677. * extend: 'Ext.data.Model',
  8678. * idgen: 'custom'
  8679. * });
  8680. * // or...
  8681. *
  8682. * Ext.define('MyApp.data.MyModel', {
  8683. * extend: 'Ext.data.Model',
  8684. * idgen: {
  8685. * type: 'custom',
  8686. * configProp: value
  8687. * }
  8688. * });
  8689. *
  8690. * It is not recommended to mix shared generators with generator configuration. This leads
  8691. * to unpredictable results unless all configurations match (which is also redundant). In
  8692. * such cases, a custom generator with a default id is the best approach.
  8693. *
  8694. * Ext.define('MyApp.data.CustomIdGenerator', {
  8695. * extend: 'Ext.data.SequentialIdGenerator',
  8696. * alias: 'idgen.custom',
  8697. *
  8698. * id: 'custom', // shared by default
  8699. *
  8700. * prefix: 'ID_',
  8701. * seed: 1000
  8702. * });
  8703. *
  8704. * Ext.define('MyApp.data.MyModelX', {
  8705. * extend: 'Ext.data.Model',
  8706. * idgen: 'custom'
  8707. * });
  8708. *
  8709. * Ext.define('MyApp.data.MyModelY', {
  8710. * extend: 'Ext.data.Model',
  8711. * idgen: 'custom'
  8712. * });
  8713. *
  8714. * // the above models share a generator that produces ID_1000, ID_1001, etc..
  8715. *
  8716. */
  8717. Ext.define('Ext.data.IdGenerator', {
  8718. isGenerator: true,
  8719. /**
  8720. * Initializes a new instance.
  8721. * @param {Object} config (optional) Configuration object to be applied to the new instance.
  8722. */
  8723. constructor: function(config) {
  8724. var me = this;
  8725. Ext.apply(me, config);
  8726. if (me.id) {
  8727. Ext.data.IdGenerator.all[me.id] = me;
  8728. }
  8729. },
  8730. /**
  8731. * @cfg {String} id
  8732. * The id by which to register a new instance. This instance can be found using the
  8733. * {@link Ext.data.IdGenerator#get} static method.
  8734. */
  8735. getRecId: function (rec) {
  8736. return rec.modelName + '-' + rec.internalId;
  8737. },
  8738. /**
  8739. * Generates and returns the next id. This method must be implemented by the derived
  8740. * class.
  8741. *
  8742. * @return {String} The next id.
  8743. * @method generate
  8744. * @abstract
  8745. */
  8746. statics: {
  8747. /**
  8748. * @property {Object} all
  8749. * This object is keyed by id to lookup instances.
  8750. * @private
  8751. * @static
  8752. */
  8753. all: {},
  8754. /**
  8755. * Returns the IdGenerator given its config description.
  8756. * @param {String/Object} config If this parameter is an IdGenerator instance, it is
  8757. * simply returned. If this is a string, it is first used as an id for lookup and
  8758. * then, if there is no match, as a type to create a new instance. This parameter
  8759. * can also be a config object that contains a `type` property (among others) that
  8760. * are used to create and configure the instance.
  8761. * @static
  8762. */
  8763. get: function (config) {
  8764. var generator,
  8765. id,
  8766. type;
  8767. if (typeof config == 'string') {
  8768. id = type = config;
  8769. config = null;
  8770. } else if (config.isGenerator) {
  8771. return config;
  8772. } else {
  8773. id = config.id || config.type;
  8774. type = config.type;
  8775. }
  8776. generator = this.all[id];
  8777. if (!generator) {
  8778. generator = Ext.create('idgen.' + type, config);
  8779. }
  8780. return generator;
  8781. }
  8782. }
  8783. });
  8784. /**
  8785. * @class Ext.data.SortTypes
  8786. * This class defines a series of static methods that are used on a
  8787. * {@link Ext.data.Field} for performing sorting. The methods cast the
  8788. * underlying values into a data type that is appropriate for sorting on
  8789. * that particular field. If a {@link Ext.data.Field#type} is specified,
  8790. * the sortType will be set to a sane default if the sortType is not
  8791. * explicitly defined on the field. The sortType will make any necessary
  8792. * modifications to the value and return it.
  8793. * <ul>
  8794. * <li><b>asText</b> - Removes any tags and converts the value to a string</li>
  8795. * <li><b>asUCText</b> - Removes any tags and converts the value to an uppercase string</li>
  8796. * <li><b>asUCText</b> - Converts the value to an uppercase string</li>
  8797. * <li><b>asDate</b> - Converts the value into Unix epoch time</li>
  8798. * <li><b>asFloat</b> - Converts the value to a floating point number</li>
  8799. * <li><b>asInt</b> - Converts the value to an integer number</li>
  8800. * </ul>
  8801. * <p>
  8802. * It is also possible to create a custom sortType that can be used throughout
  8803. * an application.
  8804. * <pre><code>
  8805. Ext.apply(Ext.data.SortTypes, {
  8806. asPerson: function(person){
  8807. // expects an object with a first and last name property
  8808. return person.lastName.toUpperCase() + person.firstName.toLowerCase();
  8809. }
  8810. });
  8811. Ext.define('Employee', {
  8812. extend: 'Ext.data.Model',
  8813. fields: [{
  8814. name: 'person',
  8815. sortType: 'asPerson'
  8816. }, {
  8817. name: 'salary',
  8818. type: 'float' // sortType set to asFloat
  8819. }]
  8820. });
  8821. * </code></pre>
  8822. * </p>
  8823. * @singleton
  8824. * @docauthor Evan Trimboli <evan@sencha.com>
  8825. */
  8826. Ext.define('Ext.data.SortTypes', {
  8827. singleton: true,
  8828. /**
  8829. * Default sort that does nothing
  8830. * @param {Object} s The value being converted
  8831. * @return {Object} The comparison value
  8832. */
  8833. none : function(s) {
  8834. return s;
  8835. },
  8836. /**
  8837. * The regular expression used to strip tags
  8838. * @type {RegExp}
  8839. * @property
  8840. */
  8841. stripTagsRE : /<\/?[^>]+>/gi,
  8842. /**
  8843. * Strips all HTML tags to sort on text only
  8844. * @param {Object} s The value being converted
  8845. * @return {String} The comparison value
  8846. */
  8847. asText : function(s) {
  8848. return String(s).replace(this.stripTagsRE, "");
  8849. },
  8850. /**
  8851. * Strips all HTML tags to sort on text only - Case insensitive
  8852. * @param {Object} s The value being converted
  8853. * @return {String} The comparison value
  8854. */
  8855. asUCText : function(s) {
  8856. return String(s).toUpperCase().replace(this.stripTagsRE, "");
  8857. },
  8858. /**
  8859. * Case insensitive string
  8860. * @param {Object} s The value being converted
  8861. * @return {String} The comparison value
  8862. */
  8863. asUCString : function(s) {
  8864. return String(s).toUpperCase();
  8865. },
  8866. /**
  8867. * Date sorting
  8868. * @param {Object} s The value being converted
  8869. * @return {Number} The comparison value
  8870. */
  8871. asDate : function(s) {
  8872. if(!s){
  8873. return 0;
  8874. }
  8875. if(Ext.isDate(s)){
  8876. return s.getTime();
  8877. }
  8878. return Date.parse(String(s));
  8879. },
  8880. /**
  8881. * Float sorting
  8882. * @param {Object} s The value being converted
  8883. * @return {Number} The comparison value
  8884. */
  8885. asFloat : function(s) {
  8886. var val = parseFloat(String(s).replace(/,/g, ""));
  8887. return isNaN(val) ? 0 : val;
  8888. },
  8889. /**
  8890. * Integer sorting
  8891. * @param {Object} s The value being converted
  8892. * @return {Number} The comparison value
  8893. */
  8894. asInt : function(s) {
  8895. var val = parseInt(String(s).replace(/,/g, ""), 10);
  8896. return isNaN(val) ? 0 : val;
  8897. }
  8898. });
  8899. /**
  8900. * Represents a filter that can be applied to a {@link Ext.util.MixedCollection MixedCollection}. Can either simply
  8901. * filter on a property/value pair or pass in a filter function with custom logic. Filters are always used in the
  8902. * context of MixedCollections, though {@link Ext.data.Store Store}s frequently create them when filtering and searching
  8903. * on their records. Example usage:
  8904. *
  8905. * //set up a fictional MixedCollection containing a few people to filter on
  8906. * var allNames = new Ext.util.MixedCollection();
  8907. * allNames.addAll([
  8908. * {id: 1, name: 'Ed', age: 25},
  8909. * {id: 2, name: 'Jamie', age: 37},
  8910. * {id: 3, name: 'Abe', age: 32},
  8911. * {id: 4, name: 'Aaron', age: 26},
  8912. * {id: 5, name: 'David', age: 32}
  8913. * ]);
  8914. *
  8915. * var ageFilter = new Ext.util.Filter({
  8916. * property: 'age',
  8917. * value : 32
  8918. * });
  8919. *
  8920. * var longNameFilter = new Ext.util.Filter({
  8921. * filterFn: function(item) {
  8922. * return item.name.length > 4;
  8923. * }
  8924. * });
  8925. *
  8926. * //a new MixedCollection with the 3 names longer than 4 characters
  8927. * var longNames = allNames.filter(longNameFilter);
  8928. *
  8929. * //a new MixedCollection with the 2 people of age 24:
  8930. * var youngFolk = allNames.filter(ageFilter);
  8931. *
  8932. */
  8933. Ext.define('Ext.util.Filter', {
  8934. /* Begin Definitions */
  8935. /* End Definitions */
  8936. /**
  8937. * @cfg {String} property
  8938. * The property to filter on. Required unless a {@link #filterFn} is passed
  8939. */
  8940. /**
  8941. * @cfg {Function} filterFn
  8942. * A custom filter function which is passed each item in the {@link Ext.util.MixedCollection} in turn. Should return
  8943. * true to accept each item or false to reject it
  8944. */
  8945. /**
  8946. * @cfg {Boolean} anyMatch
  8947. * True to allow any match - no regex start/end line anchors will be added.
  8948. */
  8949. anyMatch: false,
  8950. /**
  8951. * @cfg {Boolean} exactMatch
  8952. * True to force exact match (^ and $ characters added to the regex). Ignored if anyMatch is true.
  8953. */
  8954. exactMatch: false,
  8955. /**
  8956. * @cfg {Boolean} caseSensitive
  8957. * True to make the regex case sensitive (adds 'i' switch to regex).
  8958. */
  8959. caseSensitive: false,
  8960. /**
  8961. * @cfg {String} root
  8962. * Optional root property. This is mostly useful when filtering a Store, in which case we set the root to 'data' to
  8963. * make the filter pull the {@link #property} out of the data object of each item
  8964. */
  8965. /**
  8966. * Creates new Filter.
  8967. * @param {Object} [config] Config object
  8968. */
  8969. constructor: function(config) {
  8970. var me = this;
  8971. Ext.apply(me, config);
  8972. //we're aliasing filter to filterFn mostly for API cleanliness reasons, despite the fact it dirties the code here.
  8973. //Ext.util.Sorter takes a sorterFn property but allows .sort to be called - we do the same here
  8974. me.filter = me.filter || me.filterFn;
  8975. if (me.filter === undefined) {
  8976. if (me.property === undefined || me.value === undefined) {
  8977. // Commented this out temporarily because it stops us using string ids in models. TODO: Remove this once
  8978. // Model has been updated to allow string ids
  8979. // Ext.Error.raise("A Filter requires either a property or a filterFn to be set");
  8980. } else {
  8981. me.filter = me.createFilterFn();
  8982. }
  8983. me.filterFn = me.filter;
  8984. }
  8985. },
  8986. /**
  8987. * @private
  8988. * Creates a filter function for the configured property/value/anyMatch/caseSensitive options for this Filter
  8989. */
  8990. createFilterFn: function() {
  8991. var me = this,
  8992. matcher = me.createValueMatcher(),
  8993. property = me.property;
  8994. return function(item) {
  8995. var value = me.getRoot.call(me, item)[property];
  8996. return matcher === null ? value === null : matcher.test(value);
  8997. };
  8998. },
  8999. /**
  9000. * @private
  9001. * Returns the root property of the given item, based on the configured {@link #root} property
  9002. * @param {Object} item The item
  9003. * @return {Object} The root property of the object
  9004. */
  9005. getRoot: function(item) {
  9006. var root = this.root;
  9007. return root === undefined ? item : item[root];
  9008. },
  9009. /**
  9010. * @private
  9011. * Returns a regular expression based on the given value and matching options
  9012. */
  9013. createValueMatcher : function() {
  9014. var me = this,
  9015. value = me.value,
  9016. anyMatch = me.anyMatch,
  9017. exactMatch = me.exactMatch,
  9018. caseSensitive = me.caseSensitive,
  9019. escapeRe = Ext.String.escapeRegex;
  9020. if (value === null) {
  9021. return value;
  9022. }
  9023. if (!value.exec) { // not a regex
  9024. value = String(value);
  9025. if (anyMatch === true) {
  9026. value = escapeRe(value);
  9027. } else {
  9028. value = '^' + escapeRe(value);
  9029. if (exactMatch === true) {
  9030. value += '$';
  9031. }
  9032. }
  9033. value = new RegExp(value, caseSensitive ? '' : 'i');
  9034. }
  9035. return value;
  9036. }
  9037. });
  9038. /**
  9039. * Represents a single sorter that can be applied to a Store. The sorter is used
  9040. * to compare two values against each other for the purpose of ordering them. Ordering
  9041. * is achieved by specifying either:
  9042. *
  9043. * - {@link #property A sorting property}
  9044. * - {@link #sorterFn A sorting function}
  9045. *
  9046. * As a contrived example, we can specify a custom sorter that sorts by rank:
  9047. *
  9048. * Ext.define('Person', {
  9049. * extend: 'Ext.data.Model',
  9050. * fields: ['name', 'rank']
  9051. * });
  9052. *
  9053. * Ext.create('Ext.data.Store', {
  9054. * model: 'Person',
  9055. * proxy: 'memory',
  9056. * sorters: [{
  9057. * sorterFn: function(o1, o2){
  9058. * var getRank = function(o){
  9059. * var name = o.get('rank');
  9060. * if (name === 'first') {
  9061. * return 1;
  9062. * } else if (name === 'second') {
  9063. * return 2;
  9064. * } else {
  9065. * return 3;
  9066. * }
  9067. * },
  9068. * rank1 = getRank(o1),
  9069. * rank2 = getRank(o2);
  9070. *
  9071. * if (rank1 === rank2) {
  9072. * return 0;
  9073. * }
  9074. *
  9075. * return rank1 < rank2 ? -1 : 1;
  9076. * }
  9077. * }],
  9078. * data: [{
  9079. * name: 'Person1',
  9080. * rank: 'second'
  9081. * }, {
  9082. * name: 'Person2',
  9083. * rank: 'third'
  9084. * }, {
  9085. * name: 'Person3',
  9086. * rank: 'first'
  9087. * }]
  9088. * });
  9089. */
  9090. Ext.define('Ext.util.Sorter', {
  9091. /**
  9092. * @cfg {String} property
  9093. * The property to sort by. Required unless {@link #sorterFn} is provided. The property is extracted from the object
  9094. * directly and compared for sorting using the built in comparison operators.
  9095. */
  9096. /**
  9097. * @cfg {Function} sorterFn
  9098. * A specific sorter function to execute. Can be passed instead of {@link #property}. This sorter function allows
  9099. * for any kind of custom/complex comparisons. The sorterFn receives two arguments, the objects being compared. The
  9100. * function should return:
  9101. *
  9102. * - -1 if o1 is "less than" o2
  9103. * - 0 if o1 is "equal" to o2
  9104. * - 1 if o1 is "greater than" o2
  9105. */
  9106. /**
  9107. * @cfg {String} root
  9108. * Optional root property. This is mostly useful when sorting a Store, in which case we set the root to 'data' to
  9109. * make the filter pull the {@link #property} out of the data object of each item
  9110. */
  9111. /**
  9112. * @cfg {Function} transform
  9113. * A function that will be run on each value before it is compared in the sorter. The function will receive a single
  9114. * argument, the value.
  9115. */
  9116. /**
  9117. * @cfg {String} direction
  9118. * The direction to sort by.
  9119. */
  9120. direction: "ASC",
  9121. constructor: function(config) {
  9122. var me = this;
  9123. Ext.apply(me, config);
  9124. //<debug>
  9125. if (me.property === undefined && me.sorterFn === undefined) {
  9126. Ext.Error.raise("A Sorter requires either a property or a sorter function");
  9127. }
  9128. //</debug>
  9129. me.updateSortFunction();
  9130. },
  9131. /**
  9132. * @private
  9133. * Creates and returns a function which sorts an array by the given property and direction
  9134. * @return {Function} A function which sorts by the property/direction combination provided
  9135. */
  9136. createSortFunction: function(sorterFn) {
  9137. var me = this,
  9138. property = me.property,
  9139. direction = me.direction || "ASC",
  9140. modifier = direction.toUpperCase() == "DESC" ? -1 : 1;
  9141. //create a comparison function. Takes 2 objects, returns 1 if object 1 is greater,
  9142. //-1 if object 2 is greater or 0 if they are equal
  9143. return function(o1, o2) {
  9144. return modifier * sorterFn.call(me, o1, o2);
  9145. };
  9146. },
  9147. /**
  9148. * @private
  9149. * Basic default sorter function that just compares the defined property of each object
  9150. */
  9151. defaultSorterFn: function(o1, o2) {
  9152. var me = this,
  9153. transform = me.transform,
  9154. v1 = me.getRoot(o1)[me.property],
  9155. v2 = me.getRoot(o2)[me.property];
  9156. if (transform) {
  9157. v1 = transform(v1);
  9158. v2 = transform(v2);
  9159. }
  9160. return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
  9161. },
  9162. /**
  9163. * @private
  9164. * Returns the root property of the given item, based on the configured {@link #root} property
  9165. * @param {Object} item The item
  9166. * @return {Object} The root property of the object
  9167. */
  9168. getRoot: function(item) {
  9169. return this.root === undefined ? item : item[this.root];
  9170. },
  9171. /**
  9172. * Set the sorting direction for this sorter.
  9173. * @param {String} direction The direction to sort in. Should be either 'ASC' or 'DESC'.
  9174. */
  9175. setDirection: function(direction) {
  9176. var me = this;
  9177. me.direction = direction;
  9178. me.updateSortFunction();
  9179. },
  9180. /**
  9181. * Toggles the sorting direction for this sorter.
  9182. */
  9183. toggle: function() {
  9184. var me = this;
  9185. me.direction = Ext.String.toggle(me.direction, "ASC", "DESC");
  9186. me.updateSortFunction();
  9187. },
  9188. /**
  9189. * Update the sort function for this sorter.
  9190. * @param {Function} [fn] A new sorter function for this sorter. If not specified it will use the default
  9191. * sorting function.
  9192. */
  9193. updateSortFunction: function(fn) {
  9194. var me = this;
  9195. fn = fn || me.sorterFn || me.defaultSorterFn;
  9196. me.sort = me.createSortFunction(fn);
  9197. }
  9198. });
  9199. /**
  9200. * @author Ed Spencer
  9201. *
  9202. * Represents a single read or write operation performed by a {@link Ext.data.proxy.Proxy Proxy}. Operation objects are
  9203. * used to enable communication between Stores and Proxies. Application developers should rarely need to interact with
  9204. * Operation objects directly.
  9205. *
  9206. * Several Operations can be batched together in a {@link Ext.data.Batch batch}.
  9207. */
  9208. Ext.define('Ext.data.Operation', {
  9209. /**
  9210. * @cfg {Boolean} synchronous
  9211. * True if this Operation is to be executed synchronously. This property is inspected by a
  9212. * {@link Ext.data.Batch Batch} to see if a series of Operations can be executed in parallel or not.
  9213. */
  9214. synchronous: true,
  9215. /**
  9216. * @cfg {String} action
  9217. * The action being performed by this Operation. Should be one of 'create', 'read', 'update' or 'destroy'.
  9218. */
  9219. action: undefined,
  9220. /**
  9221. * @cfg {Ext.util.Filter[]} filters
  9222. * Optional array of filter objects. Only applies to 'read' actions.
  9223. */
  9224. filters: undefined,
  9225. /**
  9226. * @cfg {Ext.util.Sorter[]} sorters
  9227. * Optional array of sorter objects. Only applies to 'read' actions.
  9228. */
  9229. sorters: undefined,
  9230. /**
  9231. * @cfg {Ext.util.Grouper} group
  9232. * Optional grouping configuration. Only applies to 'read' actions where grouping is desired.
  9233. */
  9234. group: undefined,
  9235. /**
  9236. * @cfg {Number} start
  9237. * The start index (offset), used in paging when running a 'read' action.
  9238. */
  9239. start: undefined,
  9240. /**
  9241. * @cfg {Number} limit
  9242. * The number of records to load. Used on 'read' actions when paging is being used.
  9243. */
  9244. limit: undefined,
  9245. /**
  9246. * @cfg {Ext.data.Batch} batch
  9247. * The batch that this Operation is a part of.
  9248. */
  9249. batch: undefined,
  9250. /**
  9251. * @cfg {Function} callback
  9252. * Function to execute when operation completed. Will be called with the following parameters:
  9253. *
  9254. * - records : Array of Ext.data.Model objects.
  9255. * - operation : The Ext.data.Operation itself.
  9256. * - success : True when operation completed successfully.
  9257. */
  9258. callback: undefined,
  9259. /**
  9260. * @cfg {Object} scope
  9261. * Scope for the {@link #callback} function.
  9262. */
  9263. scope: undefined,
  9264. /**
  9265. * @property {Boolean} started
  9266. * Read-only property tracking the start status of this Operation. Use {@link #isStarted}.
  9267. * @private
  9268. */
  9269. started: false,
  9270. /**
  9271. * @property {Boolean} running
  9272. * Read-only property tracking the run status of this Operation. Use {@link #isRunning}.
  9273. * @private
  9274. */
  9275. running: false,
  9276. /**
  9277. * @property {Boolean} complete
  9278. * Read-only property tracking the completion status of this Operation. Use {@link #isComplete}.
  9279. * @private
  9280. */
  9281. complete: false,
  9282. /**
  9283. * @property {Boolean} success
  9284. * Read-only property tracking whether the Operation was successful or not. This starts as undefined and is set to true
  9285. * or false by the Proxy that is executing the Operation. It is also set to false by {@link #setException}. Use
  9286. * {@link #wasSuccessful} to query success status.
  9287. * @private
  9288. */
  9289. success: undefined,
  9290. /**
  9291. * @property {Boolean} exception
  9292. * Read-only property tracking the exception status of this Operation. Use {@link #hasException} and see {@link #getError}.
  9293. * @private
  9294. */
  9295. exception: false,
  9296. /**
  9297. * @property {String/Object} error
  9298. * The error object passed when {@link #setException} was called. This could be any object or primitive.
  9299. * @private
  9300. */
  9301. error: undefined,
  9302. /**
  9303. * @property {RegExp} actionCommitRecordsRe
  9304. * The RegExp used to categorize actions that require record commits.
  9305. */
  9306. actionCommitRecordsRe: /^(?:create|update)$/i,
  9307. /**
  9308. * @property {RegExp} actionSkipSyncRe
  9309. * The RegExp used to categorize actions that skip local record synchronization. This defaults
  9310. * to match 'destroy'.
  9311. */
  9312. actionSkipSyncRe: /^destroy$/i,
  9313. /**
  9314. * Creates new Operation object.
  9315. * @param {Object} config (optional) Config object.
  9316. */
  9317. constructor: function(config) {
  9318. Ext.apply(this, config || {});
  9319. },
  9320. /**
  9321. * This method is called to commit data to this instance's records given the records in
  9322. * the server response. This is followed by calling {@link Ext.data.Model#commit} on all
  9323. * those records (for 'create' and 'update' actions).
  9324. *
  9325. * If this {@link #action} is 'destroy', any server records are ignored and the
  9326. * {@link Ext.data.Model#commit} method is not called.
  9327. *
  9328. * @param {Ext.data.Model[]} serverRecords An array of {@link Ext.data.Model} objects returned by
  9329. * the server.
  9330. * @markdown
  9331. */
  9332. commitRecords: function (serverRecords) {
  9333. var me = this,
  9334. mc, index, clientRecords, serverRec, clientRec;
  9335. if (!me.actionSkipSyncRe.test(me.action)) {
  9336. clientRecords = me.records;
  9337. if (clientRecords && clientRecords.length) {
  9338. mc = Ext.create('Ext.util.MixedCollection', true, function(r) {return r.getId();});
  9339. mc.addAll(clientRecords);
  9340. for (index = serverRecords ? serverRecords.length : 0; index--; ) {
  9341. serverRec = serverRecords[index];
  9342. clientRec = mc.get(serverRec.getId());
  9343. if (clientRec) {
  9344. clientRec.beginEdit();
  9345. clientRec.set(serverRec.data);
  9346. clientRec.endEdit(true);
  9347. }
  9348. }
  9349. if (me.actionCommitRecordsRe.test(me.action)) {
  9350. for (index = clientRecords.length; index--; ) {
  9351. clientRecords[index].commit();
  9352. }
  9353. }
  9354. }
  9355. }
  9356. },
  9357. /**
  9358. * Marks the Operation as started.
  9359. */
  9360. setStarted: function() {
  9361. this.started = true;
  9362. this.running = true;
  9363. },
  9364. /**
  9365. * Marks the Operation as completed.
  9366. */
  9367. setCompleted: function() {
  9368. this.complete = true;
  9369. this.running = false;
  9370. },
  9371. /**
  9372. * Marks the Operation as successful.
  9373. */
  9374. setSuccessful: function() {
  9375. this.success = true;
  9376. },
  9377. /**
  9378. * Marks the Operation as having experienced an exception. Can be supplied with an option error message/object.
  9379. * @param {String/Object} error (optional) error string/object
  9380. */
  9381. setException: function(error) {
  9382. this.exception = true;
  9383. this.success = false;
  9384. this.running = false;
  9385. this.error = error;
  9386. },
  9387. /**
  9388. * Returns true if this Operation encountered an exception (see also {@link #getError})
  9389. * @return {Boolean} True if there was an exception
  9390. */
  9391. hasException: function() {
  9392. return this.exception === true;
  9393. },
  9394. /**
  9395. * Returns the error string or object that was set using {@link #setException}
  9396. * @return {String/Object} The error object
  9397. */
  9398. getError: function() {
  9399. return this.error;
  9400. },
  9401. /**
  9402. * Returns an array of Ext.data.Model instances as set by the Proxy.
  9403. * @return {Ext.data.Model[]} Any loaded Records
  9404. */
  9405. getRecords: function() {
  9406. var resultSet = this.getResultSet();
  9407. return (resultSet === undefined ? this.records : resultSet.records);
  9408. },
  9409. /**
  9410. * Returns the ResultSet object (if set by the Proxy). This object will contain the {@link Ext.data.Model model}
  9411. * instances as well as meta data such as number of instances fetched, number available etc
  9412. * @return {Ext.data.ResultSet} The ResultSet object
  9413. */
  9414. getResultSet: function() {
  9415. return this.resultSet;
  9416. },
  9417. /**
  9418. * Returns true if the Operation has been started. Note that the Operation may have started AND completed, see
  9419. * {@link #isRunning} to test if the Operation is currently running.
  9420. * @return {Boolean} True if the Operation has started
  9421. */
  9422. isStarted: function() {
  9423. return this.started === true;
  9424. },
  9425. /**
  9426. * Returns true if the Operation has been started but has not yet completed.
  9427. * @return {Boolean} True if the Operation is currently running
  9428. */
  9429. isRunning: function() {
  9430. return this.running === true;
  9431. },
  9432. /**
  9433. * Returns true if the Operation has been completed
  9434. * @return {Boolean} True if the Operation is complete
  9435. */
  9436. isComplete: function() {
  9437. return this.complete === true;
  9438. },
  9439. /**
  9440. * Returns true if the Operation has completed and was successful
  9441. * @return {Boolean} True if successful
  9442. */
  9443. wasSuccessful: function() {
  9444. return this.isComplete() && this.success === true;
  9445. },
  9446. /**
  9447. * @private
  9448. * Associates this Operation with a Batch
  9449. * @param {Ext.data.Batch} batch The batch
  9450. */
  9451. setBatch: function(batch) {
  9452. this.batch = batch;
  9453. },
  9454. /**
  9455. * Checks whether this operation should cause writing to occur.
  9456. * @return {Boolean} Whether the operation should cause a write to occur.
  9457. */
  9458. allowWrite: function() {
  9459. return this.action != 'read';
  9460. }
  9461. });
  9462. /**
  9463. * @author Ed Spencer
  9464. *
  9465. * This singleton contains a set of validation functions that can be used to validate any type of data. They are most
  9466. * often used in {@link Ext.data.Model Models}, where they are automatically set up and executed.
  9467. */
  9468. Ext.define('Ext.data.validations', {
  9469. singleton: true,
  9470. /**
  9471. * @property {String} presenceMessage
  9472. * The default error message used when a presence validation fails.
  9473. */
  9474. presenceMessage: 'must be present',
  9475. /**
  9476. * @property {String} lengthMessage
  9477. * The default error message used when a length validation fails.
  9478. */
  9479. lengthMessage: 'is the wrong length',
  9480. /**
  9481. * @property {Boolean} formatMessage
  9482. * The default error message used when a format validation fails.
  9483. */
  9484. formatMessage: 'is the wrong format',
  9485. /**
  9486. * @property {String} inclusionMessage
  9487. * The default error message used when an inclusion validation fails.
  9488. */
  9489. inclusionMessage: 'is not included in the list of acceptable values',
  9490. /**
  9491. * @property {String} exclusionMessage
  9492. * The default error message used when an exclusion validation fails.
  9493. */
  9494. exclusionMessage: 'is not an acceptable value',
  9495. /**
  9496. * @property {String} emailMessage
  9497. * The default error message used when an email validation fails
  9498. */
  9499. emailMessage: 'is not a valid email address',
  9500. /**
  9501. * @property {RegExp} emailRe
  9502. * The regular expression used to validate email addresses
  9503. */
  9504. emailRe: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
  9505. /**
  9506. * Validates that the given value is present.
  9507. * For example:
  9508. *
  9509. * validations: [{type: 'presence', field: 'age'}]
  9510. *
  9511. * @param {Object} config Config object
  9512. * @param {Object} value The value to validate
  9513. * @return {Boolean} True if validation passed
  9514. */
  9515. presence: function(config, value) {
  9516. if (value === undefined) {
  9517. value = config;
  9518. }
  9519. //we need an additional check for zero here because zero is an acceptable form of present data
  9520. return !!value || value === 0;
  9521. },
  9522. /**
  9523. * Returns true if the given value is between the configured min and max values.
  9524. * For example:
  9525. *
  9526. * validations: [{type: 'length', field: 'name', min: 2}]
  9527. *
  9528. * @param {Object} config Config object
  9529. * @param {String} value The value to validate
  9530. * @return {Boolean} True if the value passes validation
  9531. */
  9532. length: function(config, value) {
  9533. if (value === undefined || value === null) {
  9534. return false;
  9535. }
  9536. var length = value.length,
  9537. min = config.min,
  9538. max = config.max;
  9539. if ((min && length < min) || (max && length > max)) {
  9540. return false;
  9541. } else {
  9542. return true;
  9543. }
  9544. },
  9545. /**
  9546. * Validates that an email string is in the correct format
  9547. * @param {Object} config Config object
  9548. * @param {String} email The email address
  9549. * @return {Boolean} True if the value passes validation
  9550. */
  9551. email: function(config, email) {
  9552. return Ext.data.validations.emailRe.test(email);
  9553. },
  9554. /**
  9555. * Returns true if the given value passes validation against the configured `matcher` regex.
  9556. * For example:
  9557. *
  9558. * validations: [{type: 'format', field: 'username', matcher: /([a-z]+)[0-9]{2,3}/}]
  9559. *
  9560. * @param {Object} config Config object
  9561. * @param {String} value The value to validate
  9562. * @return {Boolean} True if the value passes the format validation
  9563. */
  9564. format: function(config, value) {
  9565. return !!(config.matcher && config.matcher.test(value));
  9566. },
  9567. /**
  9568. * Validates that the given value is present in the configured `list`.
  9569. * For example:
  9570. *
  9571. * validations: [{type: 'inclusion', field: 'gender', list: ['Male', 'Female']}]
  9572. *
  9573. * @param {Object} config Config object
  9574. * @param {String} value The value to validate
  9575. * @return {Boolean} True if the value is present in the list
  9576. */
  9577. inclusion: function(config, value) {
  9578. return config.list && Ext.Array.indexOf(config.list,value) != -1;
  9579. },
  9580. /**
  9581. * Validates that the given value is present in the configured `list`.
  9582. * For example:
  9583. *
  9584. * validations: [{type: 'exclusion', field: 'username', list: ['Admin', 'Operator']}]
  9585. *
  9586. * @param {Object} config Config object
  9587. * @param {String} value The value to validate
  9588. * @return {Boolean} True if the value is not present in the list
  9589. */
  9590. exclusion: function(config, value) {
  9591. return config.list && Ext.Array.indexOf(config.list,value) == -1;
  9592. }
  9593. });
  9594. /**
  9595. * @author Ed Spencer
  9596. *
  9597. * Simple wrapper class that represents a set of records returned by a Proxy.
  9598. */
  9599. Ext.define('Ext.data.ResultSet', {
  9600. /**
  9601. * @cfg {Boolean} loaded
  9602. * True if the records have already been loaded. This is only meaningful when dealing with
  9603. * SQL-backed proxies.
  9604. */
  9605. loaded: true,
  9606. /**
  9607. * @cfg {Number} count
  9608. * The number of records in this ResultSet. Note that total may differ from this number.
  9609. */
  9610. count: 0,
  9611. /**
  9612. * @cfg {Number} total
  9613. * The total number of records reported by the data source. This ResultSet may form a subset of
  9614. * those records (see {@link #count}).
  9615. */
  9616. total: 0,
  9617. /**
  9618. * @cfg {Boolean} success
  9619. * True if the ResultSet loaded successfully, false if any errors were encountered.
  9620. */
  9621. success: false,
  9622. /**
  9623. * @cfg {Ext.data.Model[]} records (required)
  9624. * The array of record instances.
  9625. */
  9626. /**
  9627. * Creates the resultSet
  9628. * @param {Object} [config] Config object.
  9629. */
  9630. constructor: function(config) {
  9631. Ext.apply(this, config);
  9632. /**
  9633. * @property {Number} totalRecords
  9634. * Copy of this.total.
  9635. * @deprecated Will be removed in Ext JS 5.0. Use {@link #total} instead.
  9636. */
  9637. this.totalRecords = this.total;
  9638. if (config.count === undefined) {
  9639. this.count = this.records.length;
  9640. }
  9641. }
  9642. });
  9643. /**
  9644. * @author Ed Spencer
  9645. *
  9646. * Base Writer class used by most subclasses of {@link Ext.data.proxy.Server}. This class is responsible for taking a
  9647. * set of {@link Ext.data.Operation} objects and a {@link Ext.data.Request} object and modifying that request based on
  9648. * the Operations.
  9649. *
  9650. * For example a Ext.data.writer.Json would format the Operations and their {@link Ext.data.Model} instances based on
  9651. * the config options passed to the JsonWriter's constructor.
  9652. *
  9653. * Writers are not needed for any kind of local storage - whether via a {@link Ext.data.proxy.WebStorage Web Storage
  9654. * proxy} (see {@link Ext.data.proxy.LocalStorage localStorage} and {@link Ext.data.proxy.SessionStorage
  9655. * sessionStorage}) or just in memory via a {@link Ext.data.proxy.Memory MemoryProxy}.
  9656. */
  9657. Ext.define('Ext.data.writer.Writer', {
  9658. alias: 'writer.base',
  9659. alternateClassName: ['Ext.data.DataWriter', 'Ext.data.Writer'],
  9660. /**
  9661. * @cfg {Boolean} writeAllFields
  9662. * True to write all fields from the record to the server. If set to false it will only send the fields that were
  9663. * modified. Note that any fields that have {@link Ext.data.Field#persist} set to false will still be ignored.
  9664. */
  9665. writeAllFields: true,
  9666. /**
  9667. * @cfg {String} nameProperty
  9668. * This property is used to read the key for each value that will be sent to the server. For example:
  9669. *
  9670. * Ext.define('Person', {
  9671. * extend: 'Ext.data.Model',
  9672. * fields: [{
  9673. * name: 'first',
  9674. * mapping: 'firstName'
  9675. * }, {
  9676. * name: 'last',
  9677. * mapping: 'lastName'
  9678. * }, {
  9679. * name: 'age'
  9680. * }]
  9681. * });
  9682. * new Ext.data.writer.Writer({
  9683. * writeAllFields: true,
  9684. * nameProperty: 'mapping'
  9685. * });
  9686. *
  9687. * // This will be sent to the server
  9688. * {
  9689. * firstName: 'first name value',
  9690. * lastName: 'last name value',
  9691. * age: 1
  9692. * }
  9693. *
  9694. * If the value is not present, the field name will always be used.
  9695. */
  9696. nameProperty: 'name',
  9697. /**
  9698. * Creates new Writer.
  9699. * @param {Object} [config] Config object.
  9700. */
  9701. constructor: function(config) {
  9702. Ext.apply(this, config);
  9703. },
  9704. /**
  9705. * Prepares a Proxy's Ext.data.Request object
  9706. * @param {Ext.data.Request} request The request object
  9707. * @return {Ext.data.Request} The modified request object
  9708. */
  9709. write: function(request) {
  9710. var operation = request.operation,
  9711. records = operation.records || [],
  9712. len = records.length,
  9713. i = 0,
  9714. data = [];
  9715. for (; i < len; i++) {
  9716. data.push(this.getRecordData(records[i]));
  9717. }
  9718. return this.writeRecords(request, data);
  9719. },
  9720. /**
  9721. * Formats the data for each record before sending it to the server. This method should be overridden to format the
  9722. * data in a way that differs from the default.
  9723. * @param {Object} record The record that we are writing to the server.
  9724. * @return {Object} An object literal of name/value keys to be written to the server. By default this method returns
  9725. * the data property on the record.
  9726. */
  9727. getRecordData: function(record) {
  9728. var isPhantom = record.phantom === true,
  9729. writeAll = this.writeAllFields || isPhantom,
  9730. nameProperty = this.nameProperty,
  9731. fields = record.fields,
  9732. data = {},
  9733. changes,
  9734. name,
  9735. field,
  9736. key;
  9737. if (writeAll) {
  9738. fields.each(function(field){
  9739. if (field.persist) {
  9740. name = field[nameProperty] || field.name;
  9741. data[name] = record.get(field.name);
  9742. }
  9743. });
  9744. } else {
  9745. // Only write the changes
  9746. changes = record.getChanges();
  9747. for (key in changes) {
  9748. if (changes.hasOwnProperty(key)) {
  9749. field = fields.get(key);
  9750. name = field[nameProperty] || field.name;
  9751. data[name] = changes[key];
  9752. }
  9753. }
  9754. if (!isPhantom) {
  9755. // always include the id for non phantoms
  9756. data[record.idProperty] = record.getId();
  9757. }
  9758. }
  9759. return data;
  9760. }
  9761. });
  9762. /**
  9763. * A mixin to add floating capability to a Component.
  9764. */
  9765. Ext.define('Ext.util.Floating', {
  9766. uses: ['Ext.Layer', 'Ext.window.Window'],
  9767. /**
  9768. * @cfg {Boolean} focusOnToFront
  9769. * Specifies whether the floated component should be automatically {@link Ext.Component#focus focused} when
  9770. * it is {@link #toFront brought to the front}.
  9771. */
  9772. focusOnToFront: true,
  9773. /**
  9774. * @cfg {String/Boolean} shadow
  9775. * Specifies whether the floating component should be given a shadow. Set to true to automatically create an {@link
  9776. * Ext.Shadow}, or a string indicating the shadow's display {@link Ext.Shadow#mode}. Set to false to disable the
  9777. * shadow.
  9778. */
  9779. shadow: 'sides',
  9780. constructor: function(config) {
  9781. var me = this;
  9782. me.floating = true;
  9783. me.el = Ext.create('Ext.Layer', Ext.apply({}, config, {
  9784. hideMode: me.hideMode,
  9785. hidden: me.hidden,
  9786. shadow: Ext.isDefined(me.shadow) ? me.shadow : 'sides',
  9787. shadowOffset: me.shadowOffset,
  9788. constrain: false,
  9789. shim: me.shim === false ? false : undefined
  9790. }), me.el);
  9791. },
  9792. onFloatRender: function() {
  9793. var me = this;
  9794. me.zIndexParent = me.getZIndexParent();
  9795. me.setFloatParent(me.ownerCt);
  9796. delete me.ownerCt;
  9797. if (me.zIndexParent) {
  9798. me.zIndexParent.registerFloatingItem(me);
  9799. } else {
  9800. Ext.WindowManager.register(me);
  9801. }
  9802. },
  9803. setFloatParent: function(floatParent) {
  9804. var me = this;
  9805. // Remove listeners from previous floatParent
  9806. if (me.floatParent) {
  9807. me.mun(me.floatParent, {
  9808. hide: me.onFloatParentHide,
  9809. show: me.onFloatParentShow,
  9810. scope: me
  9811. });
  9812. }
  9813. me.floatParent = floatParent;
  9814. // Floating Components as children of Containers must hide when their parent hides.
  9815. if (floatParent) {
  9816. me.mon(me.floatParent, {
  9817. hide: me.onFloatParentHide,
  9818. show: me.onFloatParentShow,
  9819. scope: me
  9820. });
  9821. }
  9822. // If a floating Component is configured to be constrained, but has no configured
  9823. // constrainTo setting, set its constrainTo to be it's ownerCt before rendering.
  9824. if ((me.constrain || me.constrainHeader) && !me.constrainTo) {
  9825. me.constrainTo = floatParent ? floatParent.getTargetEl() : me.container;
  9826. }
  9827. },
  9828. onFloatParentHide: function() {
  9829. var me = this;
  9830. if (me.hideOnParentHide !== false) {
  9831. me.showOnParentShow = me.isVisible();
  9832. me.hide();
  9833. }
  9834. },
  9835. onFloatParentShow: function() {
  9836. if (this.showOnParentShow) {
  9837. delete this.showOnParentShow;
  9838. this.show();
  9839. }
  9840. },
  9841. /**
  9842. * @private
  9843. * Finds the ancestor Container responsible for allocating zIndexes for the passed Component.
  9844. *
  9845. * That will be the outermost floating Container (a Container which has no ownerCt and has floating:true).
  9846. *
  9847. * If we have no ancestors, or we walk all the way up to the document body, there's no zIndexParent,
  9848. * and the global Ext.WindowManager will be used.
  9849. */
  9850. getZIndexParent: function() {
  9851. var p = this.ownerCt,
  9852. c;
  9853. if (p) {
  9854. while (p) {
  9855. c = p;
  9856. p = p.ownerCt;
  9857. }
  9858. if (c.floating) {
  9859. return c;
  9860. }
  9861. }
  9862. },
  9863. // private
  9864. // z-index is managed by the zIndexManager and may be overwritten at any time.
  9865. // Returns the next z-index to be used.
  9866. // If this is a Container, then it will have rebased any managed floating Components,
  9867. // and so the next available z-index will be approximately 10000 above that.
  9868. setZIndex: function(index) {
  9869. var me = this;
  9870. me.el.setZIndex(index);
  9871. // Next item goes 10 above;
  9872. index += 10;
  9873. // When a Container with floating items has its z-index set, it rebases any floating items it is managing.
  9874. // The returned value is a round number approximately 10000 above the last z-index used.
  9875. if (me.floatingItems) {
  9876. index = Math.floor(me.floatingItems.setBase(index) / 100) * 100 + 10000;
  9877. }
  9878. return index;
  9879. },
  9880. /**
  9881. * Moves this floating Component into a constrain region.
  9882. *
  9883. * By default, this Component is constrained to be within the container it was added to, or the element it was
  9884. * rendered to.
  9885. *
  9886. * An alternative constraint may be passed.
  9887. * @param {String/HTMLElement/Ext.Element/Ext.util.Region} constrainTo (Optional) The Element or {@link Ext.util.Region Region} into which this Component is
  9888. * to be constrained. Defaults to the element into which this floating Component was rendered.
  9889. */
  9890. doConstrain: function(constrainTo) {
  9891. var me = this,
  9892. vector = me.getConstrainVector(constrainTo || me.el.getScopeParent()),
  9893. xy;
  9894. if (vector) {
  9895. xy = me.getPosition();
  9896. xy[0] += vector[0];
  9897. xy[1] += vector[1];
  9898. me.setPosition(xy);
  9899. }
  9900. },
  9901. /**
  9902. * Gets the x/y offsets to constrain this float
  9903. * @private
  9904. * @param {String/HTMLElement/Ext.Element/Ext.util.Region} constrainTo (Optional) The Element or {@link Ext.util.Region Region} into which this Component is to be constrained.
  9905. * @return {Number[]} The x/y constraints
  9906. */
  9907. getConstrainVector: function(constrainTo){
  9908. var me = this,
  9909. el;
  9910. if (me.constrain || me.constrainHeader) {
  9911. el = me.constrainHeader ? me.header.el : me.el;
  9912. constrainTo = constrainTo || (me.floatParent && me.floatParent.getTargetEl()) || me.container;
  9913. return el.getConstrainVector(constrainTo);
  9914. }
  9915. },
  9916. /**
  9917. * Aligns this floating Component to the specified element
  9918. *
  9919. * @param {Ext.Component/Ext.Element/HTMLElement/String} element
  9920. * The element or {@link Ext.Component} to align to. If passing a component, it must be a
  9921. * omponent instance. If a string id is passed, it will be used as an element id.
  9922. * @param {String} [position="tl-bl?"] The position to align to (see {@link
  9923. * Ext.Element#alignTo} for more details).
  9924. * @param {Number[]} [offsets] Offset the positioning by [x, y]
  9925. * @return {Ext.Component} this
  9926. */
  9927. alignTo: function(element, position, offsets) {
  9928. if (element.isComponent) {
  9929. element = element.getEl();
  9930. }
  9931. var xy = this.el.getAlignToXY(element, position, offsets);
  9932. this.setPagePosition(xy);
  9933. return this;
  9934. },
  9935. /**
  9936. * Brings this floating Component to the front of any other visible, floating Components managed by the same {@link
  9937. * Ext.ZIndexManager ZIndexManager}
  9938. *
  9939. * If this Component is modal, inserts the modal mask just below this Component in the z-index stack.
  9940. *
  9941. * @param {Boolean} [preventFocus=false] Specify `true` to prevent the Component from being focused.
  9942. * @return {Ext.Component} this
  9943. */
  9944. toFront: function(preventFocus) {
  9945. var me = this;
  9946. // Find the floating Component which provides the base for this Component's zIndexing.
  9947. // That must move to front to then be able to rebase its zIndex stack and move this to the front
  9948. if (me.zIndexParent) {
  9949. me.zIndexParent.toFront(true);
  9950. }
  9951. if (me.zIndexManager.bringToFront(me)) {
  9952. if (!Ext.isDefined(preventFocus)) {
  9953. preventFocus = !me.focusOnToFront;
  9954. }
  9955. if (!preventFocus) {
  9956. // Kick off a delayed focus request.
  9957. // If another floating Component is toFronted before the delay expires
  9958. // this will not receive focus.
  9959. me.focus(false, true);
  9960. }
  9961. }
  9962. return me;
  9963. },
  9964. /**
  9965. * This method is called internally by {@link Ext.ZIndexManager} to signal that a floating Component has either been
  9966. * moved to the top of its zIndex stack, or pushed from the top of its zIndex stack.
  9967. *
  9968. * If a _Window_ is superceded by another Window, deactivating it hides its shadow.
  9969. *
  9970. * This method also fires the {@link Ext.Component#activate activate} or
  9971. * {@link Ext.Component#deactivate deactivate} event depending on which action occurred.
  9972. *
  9973. * @param {Boolean} [active=false] True to activate the Component, false to deactivate it.
  9974. * @param {Ext.Component} [newActive] The newly active Component which is taking over topmost zIndex position.
  9975. */
  9976. setActive: function(active, newActive) {
  9977. var me = this;
  9978. if (active) {
  9979. if (me.el.shadow && !me.maximized) {
  9980. me.el.enableShadow(true);
  9981. }
  9982. me.fireEvent('activate', me);
  9983. } else {
  9984. // Only the *Windows* in a zIndex stack share a shadow. All other types of floaters
  9985. // can keep their shadows all the time
  9986. if ((me instanceof Ext.window.Window) && (newActive instanceof Ext.window.Window)) {
  9987. me.el.disableShadow();
  9988. }
  9989. me.fireEvent('deactivate', me);
  9990. }
  9991. },
  9992. /**
  9993. * Sends this Component to the back of (lower z-index than) any other visible windows
  9994. * @return {Ext.Component} this
  9995. */
  9996. toBack: function() {
  9997. this.zIndexManager.sendToBack(this);
  9998. return this;
  9999. },
  10000. /**
  10001. * Center this Component in its container.
  10002. * @return {Ext.Component} this
  10003. */
  10004. center: function() {
  10005. var me = this,
  10006. xy = me.el.getAlignToXY(me.container, 'c-c');
  10007. me.setPagePosition(xy);
  10008. return me;
  10009. },
  10010. // private
  10011. syncShadow : function(){
  10012. if (this.floating) {
  10013. this.el.sync(true);
  10014. }
  10015. },
  10016. // private
  10017. fitContainer: function() {
  10018. var parent = this.floatParent,
  10019. container = parent ? parent.getTargetEl() : this.container,
  10020. size = container.getViewSize(false);
  10021. this.setSize(size);
  10022. }
  10023. });
  10024. /**
  10025. * Base Layout class - extended by ComponentLayout and ContainerLayout
  10026. */
  10027. Ext.define('Ext.layout.Layout', {
  10028. /* Begin Definitions */
  10029. /* End Definitions */
  10030. isLayout: true,
  10031. initialized: false,
  10032. statics: {
  10033. create: function(layout, defaultType) {
  10034. var type;
  10035. if (layout instanceof Ext.layout.Layout) {
  10036. return Ext.createByAlias('layout.' + layout);
  10037. } else {
  10038. if (!layout || typeof layout === 'string') {
  10039. type = layout || defaultType;
  10040. layout = {};
  10041. }
  10042. else {
  10043. type = layout.type || defaultType;
  10044. }
  10045. return Ext.createByAlias('layout.' + type, layout || {});
  10046. }
  10047. }
  10048. },
  10049. constructor : function(config) {
  10050. this.id = Ext.id(null, this.type + '-');
  10051. Ext.apply(this, config);
  10052. },
  10053. /**
  10054. * @private
  10055. */
  10056. layout : function() {
  10057. var me = this;
  10058. me.layoutBusy = true;
  10059. me.initLayout();
  10060. if (me.beforeLayout.apply(me, arguments) !== false) {
  10061. me.layoutCancelled = false;
  10062. me.onLayout.apply(me, arguments);
  10063. me.childrenChanged = false;
  10064. me.owner.needsLayout = false;
  10065. me.layoutBusy = false;
  10066. me.afterLayout.apply(me, arguments);
  10067. }
  10068. else {
  10069. me.layoutCancelled = true;
  10070. }
  10071. me.layoutBusy = false;
  10072. me.doOwnerCtLayouts();
  10073. },
  10074. beforeLayout : function() {
  10075. this.renderChildren();
  10076. return true;
  10077. },
  10078. renderChildren: function () {
  10079. this.renderItems(this.getLayoutItems(), this.getRenderTarget());
  10080. },
  10081. /**
  10082. * @private
  10083. * Iterates over all passed items, ensuring they are rendered. If the items are already rendered,
  10084. * also determines if the items are in the proper place dom.
  10085. */
  10086. renderItems : function(items, target) {
  10087. var me = this,
  10088. ln = items.length,
  10089. i = 0,
  10090. item;
  10091. for (; i < ln; i++) {
  10092. item = items[i];
  10093. if (item && !item.rendered) {
  10094. me.renderItem(item, target, i);
  10095. } else if (!me.isValidParent(item, target, i)) {
  10096. me.moveItem(item, target, i);
  10097. } else {
  10098. // still need to configure the item, it may have moved in the container.
  10099. me.configureItem(item);
  10100. }
  10101. }
  10102. },
  10103. // @private - Validates item is in the proper place in the dom.
  10104. isValidParent : function(item, target, position) {
  10105. var dom = item.el ? item.el.dom : Ext.getDom(item);
  10106. if (dom && target && target.dom) {
  10107. if (Ext.isNumber(position) && dom !== target.dom.childNodes[position]) {
  10108. return false;
  10109. }
  10110. return (dom.parentNode == (target.dom || target));
  10111. }
  10112. return false;
  10113. },
  10114. /**
  10115. * @private
  10116. * Renders the given Component into the target Element.
  10117. * @param {Ext.Component} item The Component to render
  10118. * @param {Ext.Element} target The target Element
  10119. * @param {Number} position The position within the target to render the item to
  10120. */
  10121. renderItem : function(item, target, position) {
  10122. var me = this;
  10123. if (!item.rendered) {
  10124. if (me.itemCls) {
  10125. item.addCls(me.itemCls);
  10126. }
  10127. if (me.owner.itemCls) {
  10128. item.addCls(me.owner.itemCls);
  10129. }
  10130. item.render(target, position);
  10131. me.configureItem(item);
  10132. me.childrenChanged = true;
  10133. }
  10134. },
  10135. /**
  10136. * @private
  10137. * Moved Component to the provided target instead.
  10138. */
  10139. moveItem : function(item, target, position) {
  10140. // Make sure target is a dom element
  10141. target = target.dom || target;
  10142. if (typeof position == 'number') {
  10143. position = target.childNodes[position];
  10144. }
  10145. target.insertBefore(item.el.dom, position || null);
  10146. item.container = Ext.get(target);
  10147. this.configureItem(item);
  10148. this.childrenChanged = true;
  10149. },
  10150. /**
  10151. * @private
  10152. * Adds the layout's targetCls if necessary and sets
  10153. * initialized flag when complete.
  10154. */
  10155. initLayout : function() {
  10156. var me = this,
  10157. targetCls = me.targetCls;
  10158. if (!me.initialized && !Ext.isEmpty(targetCls)) {
  10159. me.getTarget().addCls(targetCls);
  10160. }
  10161. me.initialized = true;
  10162. },
  10163. // @private Sets the layout owner
  10164. setOwner : function(owner) {
  10165. this.owner = owner;
  10166. },
  10167. // @private - Returns empty array
  10168. getLayoutItems : function() {
  10169. return [];
  10170. },
  10171. /**
  10172. * @private
  10173. * Applies itemCls
  10174. * Empty template method
  10175. */
  10176. configureItem: Ext.emptyFn,
  10177. // Placeholder empty functions for subclasses to extend
  10178. onLayout : Ext.emptyFn,
  10179. afterLayout : Ext.emptyFn,
  10180. onRemove : Ext.emptyFn,
  10181. onDestroy : Ext.emptyFn,
  10182. doOwnerCtLayouts : Ext.emptyFn,
  10183. /**
  10184. * @private
  10185. * Removes itemCls
  10186. */
  10187. afterRemove : function(item) {
  10188. var el = item.el,
  10189. owner = this.owner,
  10190. itemCls = this.itemCls,
  10191. ownerCls = owner.itemCls;
  10192. // Clear managed dimensions flag when removed from the layout.
  10193. if (item.rendered && !item.isDestroyed) {
  10194. if (itemCls) {
  10195. el.removeCls(itemCls);
  10196. }
  10197. if (ownerCls) {
  10198. el.removeCls(ownerCls);
  10199. }
  10200. }
  10201. // These flags are set at the time a child item is added to a layout.
  10202. // The layout must decide if it is managing the item's width, or its height, or both.
  10203. // See AbstractComponent for docs on these properties.
  10204. delete item.layoutManagedWidth;
  10205. delete item.layoutManagedHeight;
  10206. },
  10207. /**
  10208. * Destroys this layout. This is a template method that is empty by default, but should be implemented
  10209. * by subclasses that require explicit destruction to purge event handlers or remove DOM nodes.
  10210. * @template
  10211. */
  10212. destroy : function() {
  10213. var targetCls = this.targetCls,
  10214. target;
  10215. if (!Ext.isEmpty(targetCls)) {
  10216. target = this.getTarget();
  10217. if (target) {
  10218. target.removeCls(targetCls);
  10219. }
  10220. }
  10221. this.onDestroy();
  10222. }
  10223. });
  10224. /**
  10225. * @class Ext.ZIndexManager
  10226. * <p>A class that manages a group of {@link Ext.Component#floating} Components and provides z-order management,
  10227. * and Component activation behavior, including masking below the active (topmost) Component.</p>
  10228. * <p>{@link Ext.Component#floating Floating} Components which are rendered directly into the document (such as {@link Ext.window.Window Window}s) which are
  10229. * {@link Ext.Component#show show}n are managed by a {@link Ext.WindowManager global instance}.</p>
  10230. * <p>{@link Ext.Component#floating Floating} Components which are descendants of {@link Ext.Component#floating floating} <i>Containers</i>
  10231. * (for example a {@link Ext.view.BoundList BoundList} within an {@link Ext.window.Window Window}, or a {@link Ext.menu.Menu Menu}),
  10232. * are managed by a ZIndexManager owned by that floating Container. Therefore ComboBox dropdowns within Windows will have managed z-indices
  10233. * guaranteed to be correct, relative to the Window.</p>
  10234. */
  10235. Ext.define('Ext.ZIndexManager', {
  10236. alternateClassName: 'Ext.WindowGroup',
  10237. statics: {
  10238. zBase : 9000
  10239. },
  10240. constructor: function(container) {
  10241. var me = this;
  10242. me.list = {};
  10243. me.zIndexStack = [];
  10244. me.front = null;
  10245. if (container) {
  10246. // This is the ZIndexManager for an Ext.container.Container, base its zseed on the zIndex of the Container's element
  10247. if (container.isContainer) {
  10248. container.on('resize', me._onContainerResize, me);
  10249. me.zseed = Ext.Number.from(container.getEl().getStyle('zIndex'), me.getNextZSeed());
  10250. // The containing element we will be dealing with (eg masking) is the content target
  10251. me.targetEl = container.getTargetEl();
  10252. me.container = container;
  10253. }
  10254. // This is the ZIndexManager for a DOM element
  10255. else {
  10256. Ext.EventManager.onWindowResize(me._onContainerResize, me);
  10257. me.zseed = me.getNextZSeed();
  10258. me.targetEl = Ext.get(container);
  10259. }
  10260. }
  10261. // No container passed means we are the global WindowManager. Our target is the doc body.
  10262. // DOM must be ready to collect that ref.
  10263. else {
  10264. Ext.EventManager.onWindowResize(me._onContainerResize, me);
  10265. me.zseed = me.getNextZSeed();
  10266. Ext.onDocumentReady(function() {
  10267. me.targetEl = Ext.getBody();
  10268. });
  10269. }
  10270. },
  10271. getNextZSeed: function() {
  10272. return (Ext.ZIndexManager.zBase += 10000);
  10273. },
  10274. setBase: function(baseZIndex) {
  10275. this.zseed = baseZIndex;
  10276. return this.assignZIndices();
  10277. },
  10278. // private
  10279. assignZIndices: function() {
  10280. var a = this.zIndexStack,
  10281. len = a.length,
  10282. i = 0,
  10283. zIndex = this.zseed,
  10284. comp;
  10285. for (; i < len; i++) {
  10286. comp = a[i];
  10287. if (comp && !comp.hidden) {
  10288. // Setting the zIndex of a Component returns the topmost zIndex consumed by
  10289. // that Component.
  10290. // If it's just a plain floating Component such as a BoundList, then the
  10291. // return value is the passed value plus 10, ready for the next item.
  10292. // If a floating *Container* has its zIndex set, it re-orders its managed
  10293. // floating children, starting from that new base, and returns a value 10000 above
  10294. // the highest zIndex which it allocates.
  10295. zIndex = comp.setZIndex(zIndex);
  10296. }
  10297. }
  10298. this._activateLast();
  10299. return zIndex;
  10300. },
  10301. // private
  10302. _setActiveChild: function(comp) {
  10303. if (comp !== this.front) {
  10304. if (this.front) {
  10305. this.front.setActive(false, comp);
  10306. }
  10307. this.front = comp;
  10308. if (comp) {
  10309. comp.setActive(true);
  10310. if (comp.modal) {
  10311. this._showModalMask(comp);
  10312. }
  10313. }
  10314. }
  10315. },
  10316. // private
  10317. _activateLast: function(justHidden) {
  10318. var comp,
  10319. lastActivated = false,
  10320. i;
  10321. // Go down through the z-index stack.
  10322. // Activate the next visible one down.
  10323. // Keep going down to find the next visible modal one to shift the modal mask down under
  10324. for (i = this.zIndexStack.length-1; i >= 0; --i) {
  10325. comp = this.zIndexStack[i];
  10326. if (!comp.hidden) {
  10327. if (!lastActivated) {
  10328. this._setActiveChild(comp);
  10329. lastActivated = true;
  10330. }
  10331. // Move any modal mask down to just under the next modal floater down the stack
  10332. if (comp.modal) {
  10333. this._showModalMask(comp);
  10334. return;
  10335. }
  10336. }
  10337. }
  10338. // none to activate, so there must be no modal mask.
  10339. // And clear the currently active property
  10340. this._hideModalMask();
  10341. if (!lastActivated) {
  10342. this._setActiveChild(null);
  10343. }
  10344. },
  10345. _showModalMask: function(comp) {
  10346. var zIndex = comp.el.getStyle('zIndex') - 4,
  10347. maskTarget = comp.floatParent ? comp.floatParent.getTargetEl() : Ext.get(comp.getEl().dom.parentNode),
  10348. parentBox;
  10349. if (!maskTarget) {
  10350. //<debug>
  10351. Ext.global.console && Ext.global.console.warn && Ext.global.console.warn('mask target could not be found. Mask cannot be shown');
  10352. //</debug>
  10353. return;
  10354. }
  10355. parentBox = maskTarget.getBox();
  10356. if (!this.mask) {
  10357. this.mask = Ext.getBody().createChild({
  10358. cls: Ext.baseCSSPrefix + 'mask'
  10359. });
  10360. this.mask.setVisibilityMode(Ext.Element.DISPLAY);
  10361. this.mask.on('click', this._onMaskClick, this);
  10362. }
  10363. if (maskTarget.dom === document.body) {
  10364. parentBox.height = Ext.Element.getViewHeight();
  10365. }
  10366. maskTarget.addCls(Ext.baseCSSPrefix + 'body-masked');
  10367. this.mask.setBox(parentBox);
  10368. this.mask.setStyle('zIndex', zIndex);
  10369. this.mask.show();
  10370. },
  10371. _hideModalMask: function() {
  10372. if (this.mask && this.mask.dom.parentNode) {
  10373. Ext.get(this.mask.dom.parentNode).removeCls(Ext.baseCSSPrefix + 'body-masked');
  10374. this.mask.hide();
  10375. }
  10376. },
  10377. _onMaskClick: function() {
  10378. if (this.front) {
  10379. this.front.focus();
  10380. }
  10381. },
  10382. _onContainerResize: function() {
  10383. if (this.mask && this.mask.isVisible()) {
  10384. this.mask.setSize(Ext.get(this.mask.dom.parentNode).getViewSize(true));
  10385. }
  10386. },
  10387. /**
  10388. * <p>Registers a floating {@link Ext.Component} with this ZIndexManager. This should not
  10389. * need to be called under normal circumstances. Floating Components (such as Windows, BoundLists and Menus) are automatically registered
  10390. * with a {@link Ext.Component#zIndexManager zIndexManager} at render time.</p>
  10391. * <p>Where this may be useful is moving Windows between two ZIndexManagers. For example,
  10392. * to bring the Ext.MessageBox dialog under the same manager as the Desktop's
  10393. * ZIndexManager in the desktop sample app:</p><code><pre>
  10394. MyDesktop.getDesktop().getManager().register(Ext.MessageBox);
  10395. </pre></code>
  10396. * @param {Ext.Component} comp The Component to register.
  10397. */
  10398. register : function(comp) {
  10399. if (comp.zIndexManager) {
  10400. comp.zIndexManager.unregister(comp);
  10401. }
  10402. comp.zIndexManager = this;
  10403. this.list[comp.id] = comp;
  10404. this.zIndexStack.push(comp);
  10405. comp.on('hide', this._activateLast, this);
  10406. },
  10407. /**
  10408. * <p>Unregisters a {@link Ext.Component} from this ZIndexManager. This should not
  10409. * need to be called. Components are automatically unregistered upon destruction.
  10410. * See {@link #register}.</p>
  10411. * @param {Ext.Component} comp The Component to unregister.
  10412. */
  10413. unregister : function(comp) {
  10414. delete comp.zIndexManager;
  10415. if (this.list && this.list[comp.id]) {
  10416. delete this.list[comp.id];
  10417. comp.un('hide', this._activateLast);
  10418. Ext.Array.remove(this.zIndexStack, comp);
  10419. // Destruction requires that the topmost visible floater be activated. Same as hiding.
  10420. this._activateLast(comp);
  10421. }
  10422. },
  10423. /**
  10424. * Gets a registered Component by id.
  10425. * @param {String/Object} id The id of the Component or a {@link Ext.Component} instance
  10426. * @return {Ext.Component}
  10427. */
  10428. get : function(id) {
  10429. return typeof id == "object" ? id : this.list[id];
  10430. },
  10431. /**
  10432. * Brings the specified Component to the front of any other active Components in this ZIndexManager.
  10433. * @param {String/Object} comp The id of the Component or a {@link Ext.Component} instance
  10434. * @return {Boolean} True if the dialog was brought to the front, else false
  10435. * if it was already in front
  10436. */
  10437. bringToFront : function(comp) {
  10438. comp = this.get(comp);
  10439. if (comp !== this.front) {
  10440. Ext.Array.remove(this.zIndexStack, comp);
  10441. this.zIndexStack.push(comp);
  10442. this.assignZIndices();
  10443. return true;
  10444. }
  10445. if (comp.modal) {
  10446. this._showModalMask(comp);
  10447. }
  10448. return false;
  10449. },
  10450. /**
  10451. * Sends the specified Component to the back of other active Components in this ZIndexManager.
  10452. * @param {String/Object} comp The id of the Component or a {@link Ext.Component} instance
  10453. * @return {Ext.Component} The Component
  10454. */
  10455. sendToBack : function(comp) {
  10456. comp = this.get(comp);
  10457. Ext.Array.remove(this.zIndexStack, comp);
  10458. this.zIndexStack.unshift(comp);
  10459. this.assignZIndices();
  10460. return comp;
  10461. },
  10462. /**
  10463. * Hides all Components managed by this ZIndexManager.
  10464. */
  10465. hideAll : function() {
  10466. for (var id in this.list) {
  10467. if (this.list[id].isComponent && this.list[id].isVisible()) {
  10468. this.list[id].hide();
  10469. }
  10470. }
  10471. },
  10472. /**
  10473. * @private
  10474. * Temporarily hides all currently visible managed Components. This is for when
  10475. * dragging a Window which may manage a set of floating descendants in its ZIndexManager;
  10476. * they should all be hidden just for the duration of the drag.
  10477. */
  10478. hide: function() {
  10479. var i = 0,
  10480. ln = this.zIndexStack.length,
  10481. comp;
  10482. this.tempHidden = [];
  10483. for (; i < ln; i++) {
  10484. comp = this.zIndexStack[i];
  10485. if (comp.isVisible()) {
  10486. this.tempHidden.push(comp);
  10487. comp.hide();
  10488. }
  10489. }
  10490. },
  10491. /**
  10492. * @private
  10493. * Restores temporarily hidden managed Components to visibility.
  10494. */
  10495. show: function() {
  10496. var i = 0,
  10497. ln = this.tempHidden.length,
  10498. comp,
  10499. x,
  10500. y;
  10501. for (; i < ln; i++) {
  10502. comp = this.tempHidden[i];
  10503. x = comp.x;
  10504. y = comp.y;
  10505. comp.show();
  10506. comp.setPosition(x, y);
  10507. }
  10508. delete this.tempHidden;
  10509. },
  10510. /**
  10511. * Gets the currently-active Component in this ZIndexManager.
  10512. * @return {Ext.Component} The active Component
  10513. */
  10514. getActive : function() {
  10515. return this.front;
  10516. },
  10517. /**
  10518. * Returns zero or more Components in this ZIndexManager using the custom search function passed to this method.
  10519. * The function should accept a single {@link Ext.Component} reference as its only argument and should
  10520. * return true if the Component matches the search criteria, otherwise it should return false.
  10521. * @param {Function} fn The search function
  10522. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the Component being tested.
  10523. * that gets passed to the function if not specified)
  10524. * @return {Array} An array of zero or more matching windows
  10525. */
  10526. getBy : function(fn, scope) {
  10527. var r = [],
  10528. i = 0,
  10529. len = this.zIndexStack.length,
  10530. comp;
  10531. for (; i < len; i++) {
  10532. comp = this.zIndexStack[i];
  10533. if (fn.call(scope||comp, comp) !== false) {
  10534. r.push(comp);
  10535. }
  10536. }
  10537. return r;
  10538. },
  10539. /**
  10540. * Executes the specified function once for every Component in this ZIndexManager, passing each
  10541. * Component as the only parameter. Returning false from the function will stop the iteration.
  10542. * @param {Function} fn The function to execute for each item
  10543. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the current Component in the iteration.
  10544. */
  10545. each : function(fn, scope) {
  10546. var comp;
  10547. for (var id in this.list) {
  10548. comp = this.list[id];
  10549. if (comp.isComponent && fn.call(scope || comp, comp) === false) {
  10550. return;
  10551. }
  10552. }
  10553. },
  10554. /**
  10555. * Executes the specified function once for every Component in this ZIndexManager, passing each
  10556. * Component as the only parameter. Returning false from the function will stop the iteration.
  10557. * The components are passed to the function starting at the bottom and proceeding to the top.
  10558. * @param {Function} fn The function to execute for each item
  10559. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function
  10560. * is executed. Defaults to the current Component in the iteration.
  10561. */
  10562. eachBottomUp: function (fn, scope) {
  10563. var comp,
  10564. stack = this.zIndexStack,
  10565. i, n;
  10566. for (i = 0, n = stack.length ; i < n; i++) {
  10567. comp = stack[i];
  10568. if (comp.isComponent && fn.call(scope || comp, comp) === false) {
  10569. return;
  10570. }
  10571. }
  10572. },
  10573. /**
  10574. * Executes the specified function once for every Component in this ZIndexManager, passing each
  10575. * Component as the only parameter. Returning false from the function will stop the iteration.
  10576. * The components are passed to the function starting at the top and proceeding to the bottom.
  10577. * @param {Function} fn The function to execute for each item
  10578. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function
  10579. * is executed. Defaults to the current Component in the iteration.
  10580. */
  10581. eachTopDown: function (fn, scope) {
  10582. var comp,
  10583. stack = this.zIndexStack,
  10584. i;
  10585. for (i = stack.length ; i-- > 0; ) {
  10586. comp = stack[i];
  10587. if (comp.isComponent && fn.call(scope || comp, comp) === false) {
  10588. return;
  10589. }
  10590. }
  10591. },
  10592. destroy: function() {
  10593. this.each(function(c) {
  10594. c.destroy();
  10595. });
  10596. delete this.zIndexStack;
  10597. delete this.list;
  10598. delete this.container;
  10599. delete this.targetEl;
  10600. }
  10601. }, function() {
  10602. /**
  10603. * @class Ext.WindowManager
  10604. * @extends Ext.ZIndexManager
  10605. * <p>The default global floating Component group that is available automatically.</p>
  10606. * <p>This manages instances of floating Components which were rendered programatically without
  10607. * being added to a {@link Ext.container.Container Container}, and for floating Components which were added into non-floating Containers.</p>
  10608. * <p><i>Floating</i> Containers create their own instance of ZIndexManager, and floating Components added at any depth below
  10609. * there are managed by that ZIndexManager.</p>
  10610. * @singleton
  10611. */
  10612. Ext.WindowManager = Ext.WindowMgr = new this();
  10613. });
  10614. /**
  10615. * @private
  10616. * Base class for Box Layout overflow handlers. These specialized classes are invoked when a Box Layout
  10617. * (either an HBox or a VBox) has child items that are either too wide (for HBox) or too tall (for VBox)
  10618. * for its container.
  10619. */
  10620. Ext.define('Ext.layout.container.boxOverflow.None', {
  10621. alternateClassName: 'Ext.layout.boxOverflow.None',
  10622. constructor: function(layout, config) {
  10623. this.layout = layout;
  10624. Ext.apply(this, config || {});
  10625. },
  10626. handleOverflow: Ext.emptyFn,
  10627. clearOverflow: Ext.emptyFn,
  10628. onRemove: Ext.emptyFn,
  10629. /**
  10630. * @private
  10631. * Normalizes an item reference, string id or numerical index into a reference to the item
  10632. * @param {Ext.Component/String/Number} item The item reference, id or index
  10633. * @return {Ext.Component} The item
  10634. */
  10635. getItem: function(item) {
  10636. return this.layout.owner.getComponent(item);
  10637. },
  10638. onRemove: Ext.emptyFn
  10639. });
  10640. /**
  10641. * @class Ext.util.KeyMap
  10642. * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
  10643. * The constructor accepts the same config object as defined by {@link #addBinding}.
  10644. * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
  10645. * combination it will call the function with this signature (if the match is a multi-key
  10646. * combination the callback will still be called only once): (String key, Ext.EventObject e)
  10647. * A KeyMap can also handle a string representation of keys. By default KeyMap starts enabled.<br />
  10648. * Usage:
  10649. <pre><code>
  10650. // map one key by key code
  10651. var map = new Ext.util.KeyMap("my-element", {
  10652. key: 13, // or Ext.EventObject.ENTER
  10653. fn: myHandler,
  10654. scope: myObject
  10655. });
  10656. // map multiple keys to one action by string
  10657. var map = new Ext.util.KeyMap("my-element", {
  10658. key: "a\r\n\t",
  10659. fn: myHandler,
  10660. scope: myObject
  10661. });
  10662. // map multiple keys to multiple actions by strings and array of codes
  10663. var map = new Ext.util.KeyMap("my-element", [
  10664. {
  10665. key: [10,13],
  10666. fn: function(){ alert("Return was pressed"); }
  10667. }, {
  10668. key: "abc",
  10669. fn: function(){ alert('a, b or c was pressed'); }
  10670. }, {
  10671. key: "\t",
  10672. ctrl:true,
  10673. shift:true,
  10674. fn: function(){ alert('Control + shift + tab was pressed.'); }
  10675. }
  10676. ]);
  10677. </code></pre>
  10678. */
  10679. Ext.define('Ext.util.KeyMap', {
  10680. alternateClassName: 'Ext.KeyMap',
  10681. /**
  10682. * Creates new KeyMap.
  10683. * @param {String/HTMLElement/Ext.Element} el The element or its ID to bind to
  10684. * @param {Object} binding The binding (see {@link #addBinding})
  10685. * @param {String} [eventName="keydown"] The event to bind to
  10686. */
  10687. constructor: function(el, binding, eventName){
  10688. var me = this;
  10689. Ext.apply(me, {
  10690. el: Ext.get(el),
  10691. eventName: eventName || me.eventName,
  10692. bindings: []
  10693. });
  10694. if (binding) {
  10695. me.addBinding(binding);
  10696. }
  10697. me.enable();
  10698. },
  10699. eventName: 'keydown',
  10700. /**
  10701. * Add a new binding to this KeyMap. The following config object properties are supported:
  10702. * <pre>
  10703. Property Type Description
  10704. ---------- --------------- ----------------------------------------------------------------------
  10705. key String/Array A single keycode or an array of keycodes to handle
  10706. shift Boolean True to handle key only when shift is pressed, False to handle the key only when shift is not pressed (defaults to undefined)
  10707. ctrl Boolean True to handle key only when ctrl is pressed, False to handle the key only when ctrl is not pressed (defaults to undefined)
  10708. alt Boolean True to handle key only when alt is pressed, False to handle the key only when alt is not pressed (defaults to undefined)
  10709. handler Function The function to call when KeyMap finds the expected key combination
  10710. fn Function Alias of handler (for backwards-compatibility)
  10711. scope Object The scope of the callback function
  10712. defaultEventAction String A default action to apply to the event. Possible values are: stopEvent, stopPropagation, preventDefault. If no value is set no action is performed.
  10713. </pre>
  10714. *
  10715. * Usage:
  10716. * <pre><code>
  10717. // Create a KeyMap
  10718. var map = new Ext.util.KeyMap(document, {
  10719. key: Ext.EventObject.ENTER,
  10720. fn: handleKey,
  10721. scope: this
  10722. });
  10723. //Add a new binding to the existing KeyMap later
  10724. map.addBinding({
  10725. key: 'abc',
  10726. shift: true,
  10727. fn: handleKey,
  10728. scope: this
  10729. });
  10730. </code></pre>
  10731. * @param {Object/Object[]} binding A single KeyMap config or an array of configs
  10732. */
  10733. addBinding : function(binding){
  10734. if (Ext.isArray(binding)) {
  10735. Ext.each(binding, this.addBinding, this);
  10736. return;
  10737. }
  10738. var keyCode = binding.key,
  10739. processed = false,
  10740. key,
  10741. keys,
  10742. keyString,
  10743. i,
  10744. len;
  10745. if (Ext.isString(keyCode)) {
  10746. keys = [];
  10747. keyString = keyCode.toUpperCase();
  10748. for (i = 0, len = keyString.length; i < len; ++i){
  10749. keys.push(keyString.charCodeAt(i));
  10750. }
  10751. keyCode = keys;
  10752. processed = true;
  10753. }
  10754. if (!Ext.isArray(keyCode)) {
  10755. keyCode = [keyCode];
  10756. }
  10757. if (!processed) {
  10758. for (i = 0, len = keyCode.length; i < len; ++i) {
  10759. key = keyCode[i];
  10760. if (Ext.isString(key)) {
  10761. keyCode[i] = key.toUpperCase().charCodeAt(0);
  10762. }
  10763. }
  10764. }
  10765. this.bindings.push(Ext.apply({
  10766. keyCode: keyCode
  10767. }, binding));
  10768. },
  10769. /**
  10770. * Process any keydown events on the element
  10771. * @private
  10772. * @param {Ext.EventObject} event
  10773. */
  10774. handleKeyDown: function(event) {
  10775. if (this.enabled) { //just in case
  10776. var bindings = this.bindings,
  10777. i = 0,
  10778. len = bindings.length;
  10779. event = this.processEvent(event);
  10780. for(; i < len; ++i){
  10781. this.processBinding(bindings[i], event);
  10782. }
  10783. }
  10784. },
  10785. /**
  10786. * Ugly hack to allow this class to be tested. Currently WebKit gives
  10787. * no way to raise a key event properly with both
  10788. * a) A keycode
  10789. * b) The alt/ctrl/shift modifiers
  10790. * So we have to simulate them here. Yuk!
  10791. * This is a stub method intended to be overridden by tests.
  10792. * More info: https://bugs.webkit.org/show_bug.cgi?id=16735
  10793. * @private
  10794. */
  10795. processEvent: function(event){
  10796. return event;
  10797. },
  10798. /**
  10799. * Process a particular binding and fire the handler if necessary.
  10800. * @private
  10801. * @param {Object} binding The binding information
  10802. * @param {Ext.EventObject} event
  10803. */
  10804. processBinding: function(binding, event){
  10805. if (this.checkModifiers(binding, event)) {
  10806. var key = event.getKey(),
  10807. handler = binding.fn || binding.handler,
  10808. scope = binding.scope || this,
  10809. keyCode = binding.keyCode,
  10810. defaultEventAction = binding.defaultEventAction,
  10811. i,
  10812. len,
  10813. keydownEvent = new Ext.EventObjectImpl(event);
  10814. for (i = 0, len = keyCode.length; i < len; ++i) {
  10815. if (key === keyCode[i]) {
  10816. if (handler.call(scope, key, event) !== true && defaultEventAction) {
  10817. keydownEvent[defaultEventAction]();
  10818. }
  10819. break;
  10820. }
  10821. }
  10822. }
  10823. },
  10824. /**
  10825. * Check if the modifiers on the event match those on the binding
  10826. * @private
  10827. * @param {Object} binding
  10828. * @param {Ext.EventObject} event
  10829. * @return {Boolean} True if the event matches the binding
  10830. */
  10831. checkModifiers: function(binding, e){
  10832. var keys = ['shift', 'ctrl', 'alt'],
  10833. i = 0,
  10834. len = keys.length,
  10835. val, key;
  10836. for (; i < len; ++i){
  10837. key = keys[i];
  10838. val = binding[key];
  10839. if (!(val === undefined || (val === e[key + 'Key']))) {
  10840. return false;
  10841. }
  10842. }
  10843. return true;
  10844. },
  10845. /**
  10846. * Shorthand for adding a single key listener
  10847. * @param {Number/Number[]/Object} key Either the numeric key code, array of key codes or an object with the
  10848. * following options:
  10849. * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
  10850. * @param {Function} fn The function to call
  10851. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the browser window.
  10852. */
  10853. on: function(key, fn, scope) {
  10854. var keyCode, shift, ctrl, alt;
  10855. if (Ext.isObject(key) && !Ext.isArray(key)) {
  10856. keyCode = key.key;
  10857. shift = key.shift;
  10858. ctrl = key.ctrl;
  10859. alt = key.alt;
  10860. } else {
  10861. keyCode = key;
  10862. }
  10863. this.addBinding({
  10864. key: keyCode,
  10865. shift: shift,
  10866. ctrl: ctrl,
  10867. alt: alt,
  10868. fn: fn,
  10869. scope: scope
  10870. });
  10871. },
  10872. /**
  10873. * Returns true if this KeyMap is enabled
  10874. * @return {Boolean}
  10875. */
  10876. isEnabled : function(){
  10877. return this.enabled;
  10878. },
  10879. /**
  10880. * Enables this KeyMap
  10881. */
  10882. enable: function(){
  10883. var me = this;
  10884. if (!me.enabled) {
  10885. me.el.on(me.eventName, me.handleKeyDown, me);
  10886. me.enabled = true;
  10887. }
  10888. },
  10889. /**
  10890. * Disable this KeyMap
  10891. */
  10892. disable: function(){
  10893. var me = this;
  10894. if (me.enabled) {
  10895. me.el.removeListener(me.eventName, me.handleKeyDown, me);
  10896. me.enabled = false;
  10897. }
  10898. },
  10899. /**
  10900. * Convenience function for setting disabled/enabled by boolean.
  10901. * @param {Boolean} disabled
  10902. */
  10903. setDisabled : function(disabled){
  10904. if (disabled) {
  10905. this.disable();
  10906. } else {
  10907. this.enable();
  10908. }
  10909. },
  10910. /**
  10911. * Destroys the KeyMap instance and removes all handlers.
  10912. * @param {Boolean} removeEl True to also remove the attached element
  10913. */
  10914. destroy: function(removeEl){
  10915. var me = this;
  10916. me.bindings = [];
  10917. me.disable();
  10918. if (removeEl === true) {
  10919. me.el.remove();
  10920. }
  10921. delete me.el;
  10922. }
  10923. });
  10924. /**
  10925. * @class Ext.util.ClickRepeater
  10926. * @extends Ext.util.Observable
  10927. *
  10928. * A wrapper class which can be applied to any element. Fires a "click" event while the
  10929. * mouse is pressed. The interval between firings may be specified in the config but
  10930. * defaults to 20 milliseconds.
  10931. *
  10932. * Optionally, a CSS class may be applied to the element during the time it is pressed.
  10933. *
  10934. */
  10935. Ext.define('Ext.util.ClickRepeater', {
  10936. extend: 'Ext.util.Observable',
  10937. /**
  10938. * Creates new ClickRepeater.
  10939. * @param {String/HTMLElement/Ext.Element} el The element or its ID to listen on
  10940. * @param {Object} config (optional) Config object.
  10941. */
  10942. constructor : function(el, config){
  10943. this.el = Ext.get(el);
  10944. this.el.unselectable();
  10945. Ext.apply(this, config);
  10946. this.addEvents(
  10947. /**
  10948. * @event mousedown
  10949. * Fires when the mouse button is depressed.
  10950. * @param {Ext.util.ClickRepeater} this
  10951. * @param {Ext.EventObject} e
  10952. */
  10953. "mousedown",
  10954. /**
  10955. * @event click
  10956. * Fires on a specified interval during the time the element is pressed.
  10957. * @param {Ext.util.ClickRepeater} this
  10958. * @param {Ext.EventObject} e
  10959. */
  10960. "click",
  10961. /**
  10962. * @event mouseup
  10963. * Fires when the mouse key is released.
  10964. * @param {Ext.util.ClickRepeater} this
  10965. * @param {Ext.EventObject} e
  10966. */
  10967. "mouseup"
  10968. );
  10969. if(!this.disabled){
  10970. this.disabled = true;
  10971. this.enable();
  10972. }
  10973. // allow inline handler
  10974. if(this.handler){
  10975. this.on("click", this.handler, this.scope || this);
  10976. }
  10977. this.callParent();
  10978. },
  10979. /**
  10980. * @cfg {String/HTMLElement/Ext.Element} el The element to act as a button.
  10981. */
  10982. /**
  10983. * @cfg {String} pressedCls A CSS class name to be applied to the element while pressed.
  10984. */
  10985. /**
  10986. * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
  10987. * "interval" and "delay" are ignored.
  10988. */
  10989. /**
  10990. * @cfg {Number} interval The interval between firings of the "click" event. Default 20 ms.
  10991. */
  10992. interval : 20,
  10993. /**
  10994. * @cfg {Number} delay The initial delay before the repeating event begins firing.
  10995. * Similar to an autorepeat key delay.
  10996. */
  10997. delay: 250,
  10998. /**
  10999. * @cfg {Boolean} preventDefault True to prevent the default click event
  11000. */
  11001. preventDefault : true,
  11002. /**
  11003. * @cfg {Boolean} stopDefault True to stop the default click event
  11004. */
  11005. stopDefault : false,
  11006. timer : 0,
  11007. /**
  11008. * Enables the repeater and allows events to fire.
  11009. */
  11010. enable: function(){
  11011. if(this.disabled){
  11012. this.el.on('mousedown', this.handleMouseDown, this);
  11013. if (Ext.isIE){
  11014. this.el.on('dblclick', this.handleDblClick, this);
  11015. }
  11016. if(this.preventDefault || this.stopDefault){
  11017. this.el.on('click', this.eventOptions, this);
  11018. }
  11019. }
  11020. this.disabled = false;
  11021. },
  11022. /**
  11023. * Disables the repeater and stops events from firing.
  11024. */
  11025. disable: function(/* private */ force){
  11026. if(force || !this.disabled){
  11027. clearTimeout(this.timer);
  11028. if(this.pressedCls){
  11029. this.el.removeCls(this.pressedCls);
  11030. }
  11031. Ext.getDoc().un('mouseup', this.handleMouseUp, this);
  11032. this.el.removeAllListeners();
  11033. }
  11034. this.disabled = true;
  11035. },
  11036. /**
  11037. * Convenience function for setting disabled/enabled by boolean.
  11038. * @param {Boolean} disabled
  11039. */
  11040. setDisabled: function(disabled){
  11041. this[disabled ? 'disable' : 'enable']();
  11042. },
  11043. eventOptions: function(e){
  11044. if(this.preventDefault){
  11045. e.preventDefault();
  11046. }
  11047. if(this.stopDefault){
  11048. e.stopEvent();
  11049. }
  11050. },
  11051. // private
  11052. destroy : function() {
  11053. this.disable(true);
  11054. Ext.destroy(this.el);
  11055. this.clearListeners();
  11056. },
  11057. handleDblClick : function(e){
  11058. clearTimeout(this.timer);
  11059. this.el.blur();
  11060. this.fireEvent("mousedown", this, e);
  11061. this.fireEvent("click", this, e);
  11062. },
  11063. // private
  11064. handleMouseDown : function(e){
  11065. clearTimeout(this.timer);
  11066. this.el.blur();
  11067. if(this.pressedCls){
  11068. this.el.addCls(this.pressedCls);
  11069. }
  11070. this.mousedownTime = new Date();
  11071. Ext.getDoc().on("mouseup", this.handleMouseUp, this);
  11072. this.el.on("mouseout", this.handleMouseOut, this);
  11073. this.fireEvent("mousedown", this, e);
  11074. this.fireEvent("click", this, e);
  11075. // Do not honor delay or interval if acceleration wanted.
  11076. if (this.accelerate) {
  11077. this.delay = 400;
  11078. }
  11079. // Re-wrap the event object in a non-shared object, so it doesn't lose its context if
  11080. // the global shared EventObject gets a new Event put into it before the timer fires.
  11081. e = new Ext.EventObjectImpl(e);
  11082. this.timer = Ext.defer(this.click, this.delay || this.interval, this, [e]);
  11083. },
  11084. // private
  11085. click : function(e){
  11086. this.fireEvent("click", this, e);
  11087. this.timer = Ext.defer(this.click, this.accelerate ?
  11088. this.easeOutExpo(Ext.Date.getElapsed(this.mousedownTime),
  11089. 400,
  11090. -390,
  11091. 12000) :
  11092. this.interval, this, [e]);
  11093. },
  11094. easeOutExpo : function (t, b, c, d) {
  11095. return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
  11096. },
  11097. // private
  11098. handleMouseOut : function(){
  11099. clearTimeout(this.timer);
  11100. if(this.pressedCls){
  11101. this.el.removeCls(this.pressedCls);
  11102. }
  11103. this.el.on("mouseover", this.handleMouseReturn, this);
  11104. },
  11105. // private
  11106. handleMouseReturn : function(){
  11107. this.el.un("mouseover", this.handleMouseReturn, this);
  11108. if(this.pressedCls){
  11109. this.el.addCls(this.pressedCls);
  11110. }
  11111. this.click();
  11112. },
  11113. // private
  11114. handleMouseUp : function(e){
  11115. clearTimeout(this.timer);
  11116. this.el.un("mouseover", this.handleMouseReturn, this);
  11117. this.el.un("mouseout", this.handleMouseOut, this);
  11118. Ext.getDoc().un("mouseup", this.handleMouseUp, this);
  11119. if(this.pressedCls){
  11120. this.el.removeCls(this.pressedCls);
  11121. }
  11122. this.fireEvent("mouseup", this, e);
  11123. }
  11124. });
  11125. /**
  11126. * @class Ext.layout.component.Component
  11127. * @extends Ext.layout.Layout
  11128. *
  11129. * This class is intended to be extended or created via the {@link Ext.Component#componentLayout layout}
  11130. * configuration property. See {@link Ext.Component#componentLayout} for additional details.
  11131. *
  11132. * @private
  11133. */
  11134. Ext.define('Ext.layout.component.Component', {
  11135. /* Begin Definitions */
  11136. extend: 'Ext.layout.Layout',
  11137. /* End Definitions */
  11138. type: 'component',
  11139. monitorChildren: true,
  11140. initLayout : function() {
  11141. var me = this,
  11142. owner = me.owner,
  11143. ownerEl = owner.el;
  11144. if (!me.initialized) {
  11145. if (owner.frameSize) {
  11146. me.frameSize = owner.frameSize;
  11147. }
  11148. else {
  11149. owner.frameSize = me.frameSize = {
  11150. top: 0,
  11151. left: 0,
  11152. bottom: 0,
  11153. right: 0
  11154. };
  11155. }
  11156. }
  11157. me.callParent(arguments);
  11158. },
  11159. beforeLayout : function(width, height, isSetSize, callingContainer) {
  11160. this.callParent(arguments);
  11161. var me = this,
  11162. owner = me.owner,
  11163. ownerCt = owner.ownerCt,
  11164. layout = owner.layout,
  11165. isVisible = owner.isVisible(true),
  11166. ownerElChild = owner.el.child,
  11167. layoutCollection;
  11168. // Cache the size we began with so we can see if there has been any effect.
  11169. me.previousComponentSize = me.lastComponentSize;
  11170. // Do not allow autoing of any dimensions which are fixed
  11171. if (!isSetSize
  11172. && ((!Ext.isNumber(width) && owner.isFixedWidth()) ||
  11173. (!Ext.isNumber(height) && owner.isFixedHeight()))
  11174. // unless we are being told to do so by the ownerCt's layout
  11175. && callingContainer && callingContainer !== ownerCt) {
  11176. me.doContainerLayout();
  11177. return false;
  11178. }
  11179. // If an ownerCt is hidden, add my reference onto the layoutOnShow stack. Set the needsLayout flag.
  11180. // If the owner itself is a directly hidden floater, set the needsLayout object on that for when it is shown.
  11181. if (!isVisible && (owner.hiddenAncestor || owner.floating)) {
  11182. if (owner.hiddenAncestor) {
  11183. layoutCollection = owner.hiddenAncestor.layoutOnShow;
  11184. layoutCollection.remove(owner);
  11185. layoutCollection.add(owner);
  11186. }
  11187. owner.needsLayout = {
  11188. width: width,
  11189. height: height,
  11190. isSetSize: false
  11191. };
  11192. }
  11193. if (isVisible && this.needsLayout(width, height)) {
  11194. return owner.beforeComponentLayout(width, height, isSetSize, callingContainer);
  11195. }
  11196. else {
  11197. return false;
  11198. }
  11199. },
  11200. /**
  11201. * Check if the new size is different from the current size and only
  11202. * trigger a layout if it is necessary.
  11203. * @param {Number} width The new width to set.
  11204. * @param {Number} height The new height to set.
  11205. */
  11206. needsLayout : function(width, height) {
  11207. var me = this,
  11208. widthBeingChanged,
  11209. heightBeingChanged;
  11210. me.lastComponentSize = me.lastComponentSize || {
  11211. width: -Infinity,
  11212. height: -Infinity
  11213. };
  11214. // If autoWidthing, or an explicitly different width is passed, then the width is being changed.
  11215. widthBeingChanged = !Ext.isDefined(width) || me.lastComponentSize.width !== width;
  11216. // If autoHeighting, or an explicitly different height is passed, then the height is being changed.
  11217. heightBeingChanged = !Ext.isDefined(height) || me.lastComponentSize.height !== height;
  11218. // isSizing flag added to prevent redundant layouts when going up the layout chain
  11219. return !me.isSizing && (me.childrenChanged || widthBeingChanged || heightBeingChanged);
  11220. },
  11221. /**
  11222. * Set the size of any element supporting undefined, null, and values.
  11223. * @param {Number} width The new width to set.
  11224. * @param {Number} height The new height to set.
  11225. */
  11226. setElementSize: function(el, width, height) {
  11227. if (width !== undefined && height !== undefined) {
  11228. el.setSize(width, height);
  11229. }
  11230. else if (height !== undefined) {
  11231. el.setHeight(height);
  11232. }
  11233. else if (width !== undefined) {
  11234. el.setWidth(width);
  11235. }
  11236. },
  11237. /**
  11238. * Returns the owner component's resize element.
  11239. * @return {Ext.Element}
  11240. */
  11241. getTarget : function() {
  11242. return this.owner.el;
  11243. },
  11244. /**
  11245. * <p>Returns the element into which rendering must take place. Defaults to the owner Component's encapsulating element.</p>
  11246. * May be overridden in Component layout managers which implement an inner element.
  11247. * @return {Ext.Element}
  11248. */
  11249. getRenderTarget : function() {
  11250. return this.owner.el;
  11251. },
  11252. /**
  11253. * Set the size of the target element.
  11254. * @param {Number} width The new width to set.
  11255. * @param {Number} height The new height to set.
  11256. */
  11257. setTargetSize : function(width, height) {
  11258. var me = this;
  11259. me.setElementSize(me.owner.el, width, height);
  11260. if (me.owner.frameBody) {
  11261. var targetInfo = me.getTargetInfo(),
  11262. padding = targetInfo.padding,
  11263. border = targetInfo.border,
  11264. frameSize = me.frameSize;
  11265. me.setElementSize(me.owner.frameBody,
  11266. Ext.isNumber(width) ? (width - frameSize.left - frameSize.right - padding.left - padding.right - border.left - border.right) : width,
  11267. Ext.isNumber(height) ? (height - frameSize.top - frameSize.bottom - padding.top - padding.bottom - border.top - border.bottom) : height
  11268. );
  11269. }
  11270. me.autoSized = {
  11271. width: !Ext.isNumber(width),
  11272. height: !Ext.isNumber(height)
  11273. };
  11274. me.lastComponentSize = {
  11275. width: width,
  11276. height: height
  11277. };
  11278. },
  11279. getTargetInfo : function() {
  11280. if (!this.targetInfo) {
  11281. var target = this.getTarget(),
  11282. body = this.owner.getTargetEl();
  11283. this.targetInfo = {
  11284. padding: {
  11285. top: target.getPadding('t'),
  11286. right: target.getPadding('r'),
  11287. bottom: target.getPadding('b'),
  11288. left: target.getPadding('l')
  11289. },
  11290. border: {
  11291. top: target.getBorderWidth('t'),
  11292. right: target.getBorderWidth('r'),
  11293. bottom: target.getBorderWidth('b'),
  11294. left: target.getBorderWidth('l')
  11295. },
  11296. bodyMargin: {
  11297. top: body.getMargin('t'),
  11298. right: body.getMargin('r'),
  11299. bottom: body.getMargin('b'),
  11300. left: body.getMargin('l')
  11301. }
  11302. };
  11303. }
  11304. return this.targetInfo;
  11305. },
  11306. // Start laying out UP the ownerCt's layout when flagged to do so.
  11307. doOwnerCtLayouts: function() {
  11308. var owner = this.owner,
  11309. ownerCt = owner.ownerCt,
  11310. ownerCtComponentLayout, ownerCtContainerLayout,
  11311. curSize = this.lastComponentSize,
  11312. prevSize = this.previousComponentSize,
  11313. widthChange = (prevSize && curSize && Ext.isNumber(curSize.width )) ? curSize.width !== prevSize.width : true,
  11314. heightChange = (prevSize && curSize && Ext.isNumber(curSize.height)) ? curSize.height !== prevSize.height : true;
  11315. // If size has not changed, do not inform upstream layouts
  11316. if (!ownerCt || (!widthChange && !heightChange)) {
  11317. return;
  11318. }
  11319. ownerCtComponentLayout = ownerCt.componentLayout;
  11320. ownerCtContainerLayout = ownerCt.layout;
  11321. if (!owner.floating && ownerCtComponentLayout && ownerCtComponentLayout.monitorChildren && !ownerCtComponentLayout.layoutBusy) {
  11322. if (!ownerCt.suspendLayout && ownerCtContainerLayout && !ownerCtContainerLayout.layoutBusy) {
  11323. // If the owning Container may be adjusted in any of the the dimension which have changed, perform its Component layout
  11324. if (((widthChange && !ownerCt.isFixedWidth()) || (heightChange && !ownerCt.isFixedHeight()))) {
  11325. // Set the isSizing flag so that the upstream Container layout (called after a Component layout) can omit this component from sizing operations
  11326. this.isSizing = true;
  11327. ownerCt.doComponentLayout();
  11328. this.isSizing = false;
  11329. }
  11330. // Execute upstream Container layout
  11331. else if (ownerCtContainerLayout.bindToOwnerCtContainer === true) {
  11332. ownerCtContainerLayout.layout();
  11333. }
  11334. }
  11335. }
  11336. },
  11337. doContainerLayout: function() {
  11338. var me = this,
  11339. owner = me.owner,
  11340. ownerCt = owner.ownerCt,
  11341. layout = owner.layout,
  11342. ownerCtComponentLayout;
  11343. // Run the container layout if it exists (layout for child items)
  11344. // **Unless automatic laying out is suspended, or the layout is currently running**
  11345. if (!owner.suspendLayout && layout && layout.isLayout && !layout.layoutBusy && !layout.isAutoDock) {
  11346. layout.layout();
  11347. }
  11348. // Tell the ownerCt that it's child has changed and can be re-layed by ignoring the lastComponentSize cache.
  11349. if (ownerCt && ownerCt.componentLayout) {
  11350. ownerCtComponentLayout = ownerCt.componentLayout;
  11351. if (!owner.floating && ownerCtComponentLayout.monitorChildren && !ownerCtComponentLayout.layoutBusy) {
  11352. ownerCtComponentLayout.childrenChanged = true;
  11353. }
  11354. }
  11355. },
  11356. afterLayout : function(width, height, isSetSize, layoutOwner) {
  11357. this.doContainerLayout();
  11358. this.owner.afterComponentLayout(width, height, isSetSize, layoutOwner);
  11359. }
  11360. });
  11361. /**
  11362. * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
  11363. * wide, in pixels, a given block of text will be. Note that when measuring text, it should be plain text and
  11364. * should not contain any HTML, otherwise it may not be measured correctly.
  11365. *
  11366. * The measurement works by copying the relevant CSS styles that can affect the font related display,
  11367. * then checking the size of an element that is auto-sized. Note that if the text is multi-lined, you must
  11368. * provide a **fixed width** when doing the measurement.
  11369. *
  11370. * If multiple measurements are being done on the same element, you create a new instance to initialize
  11371. * to avoid the overhead of copying the styles to the element repeatedly.
  11372. */
  11373. Ext.define('Ext.util.TextMetrics', {
  11374. statics: {
  11375. shared: null,
  11376. /**
  11377. * Measures the size of the specified text
  11378. * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
  11379. * that can affect the size of the rendered text
  11380. * @param {String} text The text to measure
  11381. * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
  11382. * in order to accurately measure the text height
  11383. * @return {Object} An object containing the text's size `{width: (width), height: (height)}`
  11384. */
  11385. measure: function(el, text, fixedWidth){
  11386. var me = this,
  11387. shared = me.shared;
  11388. if(!shared){
  11389. shared = me.shared = new me(el, fixedWidth);
  11390. }
  11391. shared.bind(el);
  11392. shared.setFixedWidth(fixedWidth || 'auto');
  11393. return shared.getSize(text);
  11394. },
  11395. /**
  11396. * Destroy the TextMetrics instance created by {@link #measure}.
  11397. */
  11398. destroy: function(){
  11399. var me = this;
  11400. Ext.destroy(me.shared);
  11401. me.shared = null;
  11402. }
  11403. },
  11404. /**
  11405. * Creates new TextMetrics.
  11406. * @param {String/HTMLElement/Ext.Element} bindTo The element or its ID to bind to.
  11407. * @param {Number} fixedWidth (optional) A fixed width to apply to the measuring element.
  11408. */
  11409. constructor: function(bindTo, fixedWidth){
  11410. var measure = this.measure = Ext.getBody().createChild({
  11411. cls: 'x-textmetrics'
  11412. });
  11413. this.el = Ext.get(bindTo);
  11414. measure.position('absolute');
  11415. measure.setLeftTop(-1000, -1000);
  11416. measure.hide();
  11417. if (fixedWidth) {
  11418. measure.setWidth(fixedWidth);
  11419. }
  11420. },
  11421. /**
  11422. * Returns the size of the specified text based on the internal element's style and width properties
  11423. * @param {String} text The text to measure
  11424. * @return {Object} An object containing the text's size `{width: (width), height: (height)}`
  11425. */
  11426. getSize: function(text){
  11427. var measure = this.measure,
  11428. size;
  11429. measure.update(text);
  11430. size = measure.getSize();
  11431. measure.update('');
  11432. return size;
  11433. },
  11434. /**
  11435. * Binds this TextMetrics instance to a new element
  11436. * @param {String/HTMLElement/Ext.Element} el The element or its ID.
  11437. */
  11438. bind: function(el){
  11439. var me = this;
  11440. me.el = Ext.get(el);
  11441. me.measure.setStyle(
  11442. me.el.getStyles('font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing')
  11443. );
  11444. },
  11445. /**
  11446. * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
  11447. * to set a fixed width in order to accurately measure the text height.
  11448. * @param {Number} width The width to set on the element
  11449. */
  11450. setFixedWidth : function(width){
  11451. this.measure.setWidth(width);
  11452. },
  11453. /**
  11454. * Returns the measured width of the specified text
  11455. * @param {String} text The text to measure
  11456. * @return {Number} width The width in pixels
  11457. */
  11458. getWidth : function(text){
  11459. this.measure.dom.style.width = 'auto';
  11460. return this.getSize(text).width;
  11461. },
  11462. /**
  11463. * Returns the measured height of the specified text
  11464. * @param {String} text The text to measure
  11465. * @return {Number} height The height in pixels
  11466. */
  11467. getHeight : function(text){
  11468. return this.getSize(text).height;
  11469. },
  11470. /**
  11471. * Destroy this instance
  11472. */
  11473. destroy: function(){
  11474. var me = this;
  11475. me.measure.remove();
  11476. delete me.el;
  11477. delete me.measure;
  11478. }
  11479. }, function(){
  11480. Ext.Element.addMethods({
  11481. /**
  11482. * Returns the width in pixels of the passed text, or the width of the text in this Element.
  11483. * @param {String} text The text to measure. Defaults to the innerHTML of the element.
  11484. * @param {Number} min (optional) The minumum value to return.
  11485. * @param {Number} max (optional) The maximum value to return.
  11486. * @return {Number} The text width in pixels.
  11487. * @member Ext.Element
  11488. */
  11489. getTextWidth : function(text, min, max){
  11490. return Ext.Number.constrain(Ext.util.TextMetrics.measure(this.dom, Ext.value(text, this.dom.innerHTML, true)).width, min || 0, max || 1000000);
  11491. }
  11492. });
  11493. });
  11494. /**
  11495. * @class Ext.layout.container.boxOverflow.Scroller
  11496. * @extends Ext.layout.container.boxOverflow.None
  11497. * @private
  11498. */
  11499. Ext.define('Ext.layout.container.boxOverflow.Scroller', {
  11500. /* Begin Definitions */
  11501. extend: 'Ext.layout.container.boxOverflow.None',
  11502. requires: ['Ext.util.ClickRepeater', 'Ext.Element'],
  11503. alternateClassName: 'Ext.layout.boxOverflow.Scroller',
  11504. mixins: {
  11505. observable: 'Ext.util.Observable'
  11506. },
  11507. /* End Definitions */
  11508. /**
  11509. * @cfg {Boolean} animateScroll
  11510. * True to animate the scrolling of items within the layout (ignored if enableScroll is false)
  11511. */
  11512. animateScroll: false,
  11513. /**
  11514. * @cfg {Number} scrollIncrement
  11515. * The number of pixels to scroll by on scroller click
  11516. */
  11517. scrollIncrement: 20,
  11518. /**
  11519. * @cfg {Number} wheelIncrement
  11520. * The number of pixels to increment on mouse wheel scrolling.
  11521. */
  11522. wheelIncrement: 10,
  11523. /**
  11524. * @cfg {Number} scrollRepeatInterval
  11525. * Number of milliseconds between each scroll while a scroller button is held down
  11526. */
  11527. scrollRepeatInterval: 60,
  11528. /**
  11529. * @cfg {Number} scrollDuration
  11530. * Number of milliseconds that each scroll animation lasts
  11531. */
  11532. scrollDuration: 400,
  11533. /**
  11534. * @cfg {String} beforeCtCls
  11535. * CSS class added to the beforeCt element. This is the element that holds any special items such as scrollers,
  11536. * which must always be present at the leftmost edge of the Container
  11537. */
  11538. /**
  11539. * @cfg {String} afterCtCls
  11540. * CSS class added to the afterCt element. This is the element that holds any special items such as scrollers,
  11541. * which must always be present at the rightmost edge of the Container
  11542. */
  11543. /**
  11544. * @cfg {String} [scrollerCls='x-box-scroller']
  11545. * CSS class added to both scroller elements if enableScroll is used
  11546. */
  11547. scrollerCls: Ext.baseCSSPrefix + 'box-scroller',
  11548. /**
  11549. * @cfg {String} beforeScrollerCls
  11550. * CSS class added to the left scroller element if enableScroll is used
  11551. */
  11552. /**
  11553. * @cfg {String} afterScrollerCls
  11554. * CSS class added to the right scroller element if enableScroll is used
  11555. */
  11556. constructor: function(layout, config) {
  11557. this.layout = layout;
  11558. Ext.apply(this, config || {});
  11559. this.addEvents(
  11560. /**
  11561. * @event scroll
  11562. * @param {Ext.layout.container.boxOverflow.Scroller} scroller The layout scroller
  11563. * @param {Number} newPosition The new position of the scroller
  11564. * @param {Boolean/Object} animate If animating or not. If true, it will be a animation configuration, else it will be false
  11565. */
  11566. 'scroll'
  11567. );
  11568. },
  11569. initCSSClasses: function() {
  11570. var me = this,
  11571. layout = me.layout;
  11572. if (!me.CSSinitialized) {
  11573. me.beforeCtCls = me.beforeCtCls || Ext.baseCSSPrefix + 'box-scroller-' + layout.parallelBefore;
  11574. me.afterCtCls = me.afterCtCls || Ext.baseCSSPrefix + 'box-scroller-' + layout.parallelAfter;
  11575. me.beforeScrollerCls = me.beforeScrollerCls || Ext.baseCSSPrefix + layout.owner.getXType() + '-scroll-' + layout.parallelBefore;
  11576. me.afterScrollerCls = me.afterScrollerCls || Ext.baseCSSPrefix + layout.owner.getXType() + '-scroll-' + layout.parallelAfter;
  11577. me.CSSinitializes = true;
  11578. }
  11579. },
  11580. handleOverflow: function(calculations, targetSize) {
  11581. var me = this,
  11582. layout = me.layout,
  11583. methodName = 'get' + layout.parallelPrefixCap,
  11584. newSize = {};
  11585. me.initCSSClasses();
  11586. me.callParent(arguments);
  11587. this.createInnerElements();
  11588. this.showScrollers();
  11589. newSize[layout.perpendicularPrefix] = targetSize[layout.perpendicularPrefix];
  11590. newSize[layout.parallelPrefix] = targetSize[layout.parallelPrefix] - (me.beforeCt[methodName]() + me.afterCt[methodName]());
  11591. return { targetSize: newSize };
  11592. },
  11593. /**
  11594. * @private
  11595. * Creates the beforeCt and afterCt elements if they have not already been created
  11596. */
  11597. createInnerElements: function() {
  11598. var me = this,
  11599. target = me.layout.getRenderTarget();
  11600. //normal items will be rendered to the innerCt. beforeCt and afterCt allow for fixed positioning of
  11601. //special items such as scrollers or dropdown menu triggers
  11602. if (!me.beforeCt) {
  11603. target.addCls(Ext.baseCSSPrefix + me.layout.direction + '-box-overflow-body');
  11604. me.beforeCt = target.insertSibling({cls: Ext.layout.container.Box.prototype.innerCls + ' ' + me.beforeCtCls}, 'before');
  11605. me.afterCt = target.insertSibling({cls: Ext.layout.container.Box.prototype.innerCls + ' ' + me.afterCtCls}, 'after');
  11606. me.createWheelListener();
  11607. }
  11608. },
  11609. /**
  11610. * @private
  11611. * Sets up an listener to scroll on the layout's innerCt mousewheel event
  11612. */
  11613. createWheelListener: function() {
  11614. this.layout.innerCt.on({
  11615. scope : this,
  11616. mousewheel: function(e) {
  11617. e.stopEvent();
  11618. this.scrollBy(e.getWheelDelta() * this.wheelIncrement * -1, false);
  11619. }
  11620. });
  11621. },
  11622. /**
  11623. * @private
  11624. */
  11625. clearOverflow: function() {
  11626. this.hideScrollers();
  11627. },
  11628. /**
  11629. * @private
  11630. * Shows the scroller elements in the beforeCt and afterCt. Creates the scrollers first if they are not already
  11631. * present.
  11632. */
  11633. showScrollers: function() {
  11634. this.createScrollers();
  11635. this.beforeScroller.show();
  11636. this.afterScroller.show();
  11637. this.updateScrollButtons();
  11638. this.layout.owner.addClsWithUI('scroller');
  11639. },
  11640. /**
  11641. * @private
  11642. * Hides the scroller elements in the beforeCt and afterCt
  11643. */
  11644. hideScrollers: function() {
  11645. if (this.beforeScroller != undefined) {
  11646. this.beforeScroller.hide();
  11647. this.afterScroller.hide();
  11648. this.layout.owner.removeClsWithUI('scroller');
  11649. }
  11650. },
  11651. /**
  11652. * @private
  11653. * Creates the clickable scroller elements and places them into the beforeCt and afterCt
  11654. */
  11655. createScrollers: function() {
  11656. if (!this.beforeScroller && !this.afterScroller) {
  11657. var before = this.beforeCt.createChild({
  11658. cls: Ext.String.format("{0} {1} ", this.scrollerCls, this.beforeScrollerCls)
  11659. });
  11660. var after = this.afterCt.createChild({
  11661. cls: Ext.String.format("{0} {1}", this.scrollerCls, this.afterScrollerCls)
  11662. });
  11663. before.addClsOnOver(this.beforeScrollerCls + '-hover');
  11664. after.addClsOnOver(this.afterScrollerCls + '-hover');
  11665. before.setVisibilityMode(Ext.Element.DISPLAY);
  11666. after.setVisibilityMode(Ext.Element.DISPLAY);
  11667. this.beforeRepeater = Ext.create('Ext.util.ClickRepeater', before, {
  11668. interval: this.scrollRepeatInterval,
  11669. handler : this.scrollLeft,
  11670. scope : this
  11671. });
  11672. this.afterRepeater = Ext.create('Ext.util.ClickRepeater', after, {
  11673. interval: this.scrollRepeatInterval,
  11674. handler : this.scrollRight,
  11675. scope : this
  11676. });
  11677. /**
  11678. * @property beforeScroller
  11679. * @type Ext.Element
  11680. * The left scroller element. Only created when needed.
  11681. */
  11682. this.beforeScroller = before;
  11683. /**
  11684. * @property afterScroller
  11685. * @type Ext.Element
  11686. * The left scroller element. Only created when needed.
  11687. */
  11688. this.afterScroller = after;
  11689. }
  11690. },
  11691. /**
  11692. * @private
  11693. */
  11694. destroy: function() {
  11695. Ext.destroy(this.beforeRepeater, this.afterRepeater, this.beforeScroller, this.afterScroller, this.beforeCt, this.afterCt);
  11696. },
  11697. /**
  11698. * @private
  11699. * Scrolls left or right by the number of pixels specified
  11700. * @param {Number} delta Number of pixels to scroll to the right by. Use a negative number to scroll left
  11701. */
  11702. scrollBy: function(delta, animate) {
  11703. this.scrollTo(this.getScrollPosition() + delta, animate);
  11704. },
  11705. /**
  11706. * @private
  11707. * @return {Object} Object passed to scrollTo when scrolling
  11708. */
  11709. getScrollAnim: function() {
  11710. return {
  11711. duration: this.scrollDuration,
  11712. callback: this.updateScrollButtons,
  11713. scope : this
  11714. };
  11715. },
  11716. /**
  11717. * @private
  11718. * Enables or disables each scroller button based on the current scroll position
  11719. */
  11720. updateScrollButtons: function() {
  11721. if (this.beforeScroller == undefined || this.afterScroller == undefined) {
  11722. return;
  11723. }
  11724. var beforeMeth = this.atExtremeBefore() ? 'addCls' : 'removeCls',
  11725. afterMeth = this.atExtremeAfter() ? 'addCls' : 'removeCls',
  11726. beforeCls = this.beforeScrollerCls + '-disabled',
  11727. afterCls = this.afterScrollerCls + '-disabled';
  11728. this.beforeScroller[beforeMeth](beforeCls);
  11729. this.afterScroller[afterMeth](afterCls);
  11730. this.scrolling = false;
  11731. },
  11732. /**
  11733. * @private
  11734. * Returns true if the innerCt scroll is already at its left-most point
  11735. * @return {Boolean} True if already at furthest left point
  11736. */
  11737. atExtremeBefore: function() {
  11738. return this.getScrollPosition() === 0;
  11739. },
  11740. /**
  11741. * @private
  11742. * Scrolls to the left by the configured amount
  11743. */
  11744. scrollLeft: function() {
  11745. this.scrollBy(-this.scrollIncrement, false);
  11746. },
  11747. /**
  11748. * @private
  11749. * Scrolls to the right by the configured amount
  11750. */
  11751. scrollRight: function() {
  11752. this.scrollBy(this.scrollIncrement, false);
  11753. },
  11754. /**
  11755. * Returns the current scroll position of the innerCt element
  11756. * @return {Number} The current scroll position
  11757. */
  11758. getScrollPosition: function(){
  11759. var layout = this.layout;
  11760. return parseInt(layout.innerCt.dom['scroll' + layout.parallelBeforeCap], 10) || 0;
  11761. },
  11762. /**
  11763. * @private
  11764. * Returns the maximum value we can scrollTo
  11765. * @return {Number} The max scroll value
  11766. */
  11767. getMaxScrollPosition: function() {
  11768. var layout = this.layout;
  11769. return layout.innerCt.dom['scroll' + layout.parallelPrefixCap] - this.layout.innerCt['get' + layout.parallelPrefixCap]();
  11770. },
  11771. /**
  11772. * @private
  11773. * Returns true if the innerCt scroll is already at its right-most point
  11774. * @return {Boolean} True if already at furthest right point
  11775. */
  11776. atExtremeAfter: function() {
  11777. return this.getScrollPosition() >= this.getMaxScrollPosition();
  11778. },
  11779. /**
  11780. * @private
  11781. * Scrolls to the given position. Performs bounds checking.
  11782. * @param {Number} position The position to scroll to. This is constrained.
  11783. * @param {Boolean} animate True to animate. If undefined, falls back to value of this.animateScroll
  11784. */
  11785. scrollTo: function(position, animate) {
  11786. var me = this,
  11787. layout = me.layout,
  11788. oldPosition = me.getScrollPosition(),
  11789. newPosition = Ext.Number.constrain(position, 0, me.getMaxScrollPosition());
  11790. if (newPosition != oldPosition && !me.scrolling) {
  11791. if (animate == undefined) {
  11792. animate = me.animateScroll;
  11793. }
  11794. layout.innerCt.scrollTo(layout.parallelBefore, newPosition, animate ? me.getScrollAnim() : false);
  11795. if (animate) {
  11796. me.scrolling = true;
  11797. } else {
  11798. me.scrolling = false;
  11799. me.updateScrollButtons();
  11800. }
  11801. me.fireEvent('scroll', me, newPosition, animate ? me.getScrollAnim() : false);
  11802. }
  11803. },
  11804. /**
  11805. * Scrolls to the given component.
  11806. * @param {String/Number/Ext.Component} item The item to scroll to. Can be a numerical index, component id
  11807. * or a reference to the component itself.
  11808. * @param {Boolean} animate True to animate the scrolling
  11809. */
  11810. scrollToItem: function(item, animate) {
  11811. var me = this,
  11812. layout = me.layout,
  11813. visibility,
  11814. box,
  11815. newPos;
  11816. item = me.getItem(item);
  11817. if (item != undefined) {
  11818. visibility = this.getItemVisibility(item);
  11819. if (!visibility.fullyVisible) {
  11820. box = item.getBox(true, true);
  11821. newPos = box[layout.parallelPosition];
  11822. if (visibility.hiddenEnd) {
  11823. newPos -= (this.layout.innerCt['get' + layout.parallelPrefixCap]() - box[layout.parallelPrefix]);
  11824. }
  11825. this.scrollTo(newPos, animate);
  11826. }
  11827. }
  11828. },
  11829. /**
  11830. * @private
  11831. * For a given item in the container, return an object with information on whether the item is visible
  11832. * with the current innerCt scroll value.
  11833. * @param {Ext.Component} item The item
  11834. * @return {Object} Values for fullyVisible, hiddenStart and hiddenEnd
  11835. */
  11836. getItemVisibility: function(item) {
  11837. var me = this,
  11838. box = me.getItem(item).getBox(true, true),
  11839. layout = me.layout,
  11840. itemStart = box[layout.parallelPosition],
  11841. itemEnd = itemStart + box[layout.parallelPrefix],
  11842. scrollStart = me.getScrollPosition(),
  11843. scrollEnd = scrollStart + layout.innerCt['get' + layout.parallelPrefixCap]();
  11844. return {
  11845. hiddenStart : itemStart < scrollStart,
  11846. hiddenEnd : itemEnd > scrollEnd,
  11847. fullyVisible: itemStart > scrollStart && itemEnd < scrollEnd
  11848. };
  11849. }
  11850. });
  11851. /**
  11852. * @class Ext.util.Offset
  11853. * @ignore
  11854. */
  11855. Ext.define('Ext.util.Offset', {
  11856. /* Begin Definitions */
  11857. statics: {
  11858. fromObject: function(obj) {
  11859. return new this(obj.x, obj.y);
  11860. }
  11861. },
  11862. /* End Definitions */
  11863. constructor: function(x, y) {
  11864. this.x = (x != null && !isNaN(x)) ? x : 0;
  11865. this.y = (y != null && !isNaN(y)) ? y : 0;
  11866. return this;
  11867. },
  11868. copy: function() {
  11869. return new Ext.util.Offset(this.x, this.y);
  11870. },
  11871. copyFrom: function(p) {
  11872. this.x = p.x;
  11873. this.y = p.y;
  11874. },
  11875. toString: function() {
  11876. return "Offset[" + this.x + "," + this.y + "]";
  11877. },
  11878. equals: function(offset) {
  11879. //<debug>
  11880. if(!(offset instanceof this.statics())) {
  11881. Ext.Error.raise('Offset must be an instance of Ext.util.Offset');
  11882. }
  11883. //</debug>
  11884. return (this.x == offset.x && this.y == offset.y);
  11885. },
  11886. round: function(to) {
  11887. if (!isNaN(to)) {
  11888. var factor = Math.pow(10, to);
  11889. this.x = Math.round(this.x * factor) / factor;
  11890. this.y = Math.round(this.y * factor) / factor;
  11891. } else {
  11892. this.x = Math.round(this.x);
  11893. this.y = Math.round(this.y);
  11894. }
  11895. },
  11896. isZero: function() {
  11897. return this.x == 0 && this.y == 0;
  11898. }
  11899. });
  11900. /**
  11901. * @class Ext.util.KeyNav
  11902. * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
  11903. * navigation keys to function calls that will get called when the keys are pressed, providing an easy
  11904. * way to implement custom navigation schemes for any UI component.</p>
  11905. * <p>The following are all of the possible keys that can be implemented: enter, space, left, right, up, down, tab, esc,
  11906. * pageUp, pageDown, del, backspace, home, end. Usage:</p>
  11907. <pre><code>
  11908. var nav = new Ext.util.KeyNav("my-element", {
  11909. "left" : function(e){
  11910. this.moveLeft(e.ctrlKey);
  11911. },
  11912. "right" : function(e){
  11913. this.moveRight(e.ctrlKey);
  11914. },
  11915. "enter" : function(e){
  11916. this.save();
  11917. },
  11918. scope : this
  11919. });
  11920. </code></pre>
  11921. */
  11922. Ext.define('Ext.util.KeyNav', {
  11923. alternateClassName: 'Ext.KeyNav',
  11924. requires: ['Ext.util.KeyMap'],
  11925. statics: {
  11926. keyOptions: {
  11927. left: 37,
  11928. right: 39,
  11929. up: 38,
  11930. down: 40,
  11931. space: 32,
  11932. pageUp: 33,
  11933. pageDown: 34,
  11934. del: 46,
  11935. backspace: 8,
  11936. home: 36,
  11937. end: 35,
  11938. enter: 13,
  11939. esc: 27,
  11940. tab: 9
  11941. }
  11942. },
  11943. /**
  11944. * Creates new KeyNav.
  11945. * @param {String/HTMLElement/Ext.Element} el The element or its ID to bind to
  11946. * @param {Object} config The config
  11947. */
  11948. constructor: function(el, config){
  11949. this.setConfig(el, config || {});
  11950. },
  11951. /**
  11952. * Sets up a configuration for the KeyNav.
  11953. * @private
  11954. * @param {String/HTMLElement/Ext.Element} el The element or its ID to bind to
  11955. * @param {Object} config A configuration object as specified in the constructor.
  11956. */
  11957. setConfig: function(el, config) {
  11958. if (this.map) {
  11959. this.map.destroy();
  11960. }
  11961. var map = Ext.create('Ext.util.KeyMap', el, null, this.getKeyEvent('forceKeyDown' in config ? config.forceKeyDown : this.forceKeyDown)),
  11962. keys = Ext.util.KeyNav.keyOptions,
  11963. scope = config.scope || this,
  11964. key;
  11965. this.map = map;
  11966. for (key in keys) {
  11967. if (keys.hasOwnProperty(key)) {
  11968. if (config[key]) {
  11969. map.addBinding({
  11970. scope: scope,
  11971. key: keys[key],
  11972. handler: Ext.Function.bind(this.handleEvent, scope, [config[key]], true),
  11973. defaultEventAction: config.defaultEventAction || this.defaultEventAction
  11974. });
  11975. }
  11976. }
  11977. }
  11978. map.disable();
  11979. if (!config.disabled) {
  11980. map.enable();
  11981. }
  11982. },
  11983. /**
  11984. * Method for filtering out the map argument
  11985. * @private
  11986. * @param {Ext.util.KeyMap} map
  11987. * @param {Ext.EventObject} event
  11988. * @param {Object} options Contains the handler to call
  11989. */
  11990. handleEvent: function(map, event, handler){
  11991. return handler.call(this, event);
  11992. },
  11993. /**
  11994. * @cfg {Boolean} disabled
  11995. * True to disable this KeyNav instance.
  11996. */
  11997. disabled: false,
  11998. /**
  11999. * @cfg {String} defaultEventAction
  12000. * The method to call on the {@link Ext.EventObject} after this KeyNav intercepts a key. Valid values are
  12001. * {@link Ext.EventObject#stopEvent}, {@link Ext.EventObject#preventDefault} and
  12002. * {@link Ext.EventObject#stopPropagation}.
  12003. */
  12004. defaultEventAction: "stopEvent",
  12005. /**
  12006. * @cfg {Boolean} forceKeyDown
  12007. * Handle the keydown event instead of keypress. KeyNav automatically does this for IE since
  12008. * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
  12009. * handle keydown instead of keypress.
  12010. */
  12011. forceKeyDown: false,
  12012. /**
  12013. * Destroy this KeyNav (this is the same as calling disable).
  12014. * @param {Boolean} removeEl True to remove the element associated with this KeyNav.
  12015. */
  12016. destroy: function(removeEl){
  12017. this.map.destroy(removeEl);
  12018. delete this.map;
  12019. },
  12020. /**
  12021. * Enable this KeyNav
  12022. */
  12023. enable: function() {
  12024. this.map.enable();
  12025. this.disabled = false;
  12026. },
  12027. /**
  12028. * Disable this KeyNav
  12029. */
  12030. disable: function() {
  12031. this.map.disable();
  12032. this.disabled = true;
  12033. },
  12034. /**
  12035. * Convenience function for setting disabled/enabled by boolean.
  12036. * @param {Boolean} disabled
  12037. */
  12038. setDisabled : function(disabled){
  12039. this.map.setDisabled(disabled);
  12040. this.disabled = disabled;
  12041. },
  12042. /**
  12043. * Determines the event to bind to listen for keys. Depends on the {@link #forceKeyDown} setting,
  12044. * as well as the useKeyDown option on the EventManager.
  12045. * @return {String} The type of event to listen for.
  12046. */
  12047. getKeyEvent: function(forceKeyDown){
  12048. return (forceKeyDown || Ext.EventManager.useKeyDown) ? 'keydown' : 'keypress';
  12049. }
  12050. });
  12051. /**
  12052. * @class Ext.fx.Queue
  12053. * Animation Queue mixin to handle chaining and queueing by target.
  12054. * @private
  12055. */
  12056. Ext.define('Ext.fx.Queue', {
  12057. requires: ['Ext.util.HashMap'],
  12058. constructor: function() {
  12059. this.targets = Ext.create('Ext.util.HashMap');
  12060. this.fxQueue = {};
  12061. },
  12062. // @private
  12063. getFxDefaults: function(targetId) {
  12064. var target = this.targets.get(targetId);
  12065. if (target) {
  12066. return target.fxDefaults;
  12067. }
  12068. return {};
  12069. },
  12070. // @private
  12071. setFxDefaults: function(targetId, obj) {
  12072. var target = this.targets.get(targetId);
  12073. if (target) {
  12074. target.fxDefaults = Ext.apply(target.fxDefaults || {}, obj);
  12075. }
  12076. },
  12077. // @private
  12078. stopAnimation: function(targetId) {
  12079. var me = this,
  12080. queue = me.getFxQueue(targetId),
  12081. ln = queue.length;
  12082. while (ln) {
  12083. queue[ln - 1].end();
  12084. ln--;
  12085. }
  12086. },
  12087. /**
  12088. * @private
  12089. * Returns current animation object if the element has any effects actively running or queued, else returns false.
  12090. */
  12091. getActiveAnimation: function(targetId) {
  12092. var queue = this.getFxQueue(targetId);
  12093. return (queue && !!queue.length) ? queue[0] : false;
  12094. },
  12095. // @private
  12096. hasFxBlock: function(targetId) {
  12097. var queue = this.getFxQueue(targetId);
  12098. return queue && queue[0] && queue[0].block;
  12099. },
  12100. // @private get fx queue for passed target, create if needed.
  12101. getFxQueue: function(targetId) {
  12102. if (!targetId) {
  12103. return false;
  12104. }
  12105. var me = this,
  12106. queue = me.fxQueue[targetId],
  12107. target = me.targets.get(targetId);
  12108. if (!target) {
  12109. return false;
  12110. }
  12111. if (!queue) {
  12112. me.fxQueue[targetId] = [];
  12113. // GarbageCollector will need to clean up Elements since they aren't currently observable
  12114. if (target.type != 'element') {
  12115. target.target.on('destroy', function() {
  12116. me.fxQueue[targetId] = [];
  12117. });
  12118. }
  12119. }
  12120. return me.fxQueue[targetId];
  12121. },
  12122. // @private
  12123. queueFx: function(anim) {
  12124. var me = this,
  12125. target = anim.target,
  12126. queue, ln;
  12127. if (!target) {
  12128. return;
  12129. }
  12130. queue = me.getFxQueue(target.getId());
  12131. ln = queue.length;
  12132. if (ln) {
  12133. if (anim.concurrent) {
  12134. anim.paused = false;
  12135. }
  12136. else {
  12137. queue[ln - 1].on('afteranimate', function() {
  12138. anim.paused = false;
  12139. });
  12140. }
  12141. }
  12142. else {
  12143. anim.paused = false;
  12144. }
  12145. anim.on('afteranimate', function() {
  12146. Ext.Array.remove(queue, anim);
  12147. if (anim.remove) {
  12148. if (target.type == 'element') {
  12149. var el = Ext.get(target.id);
  12150. if (el) {
  12151. el.remove();
  12152. }
  12153. }
  12154. }
  12155. }, this);
  12156. queue.push(anim);
  12157. }
  12158. });
  12159. /**
  12160. * @class Ext.fx.target.Target
  12161. This class specifies a generic target for an animation. It provides a wrapper around a
  12162. series of different types of objects to allow for a generic animation API.
  12163. A target can be a single object or a Composite object containing other objects that are
  12164. to be animated. This class and it's subclasses are generally not created directly, the
  12165. underlying animation will create the appropriate Ext.fx.target.Target object by passing
  12166. the instance to be animated.
  12167. The following types of objects can be animated:
  12168. - {@link Ext.fx.target.Component Components}
  12169. - {@link Ext.fx.target.Element Elements}
  12170. - {@link Ext.fx.target.Sprite Sprites}
  12171. * @markdown
  12172. * @abstract
  12173. */
  12174. Ext.define('Ext.fx.target.Target', {
  12175. isAnimTarget: true,
  12176. /**
  12177. * Creates new Target.
  12178. * @param {Ext.Component/Ext.Element/Ext.draw.Sprite} target The object to be animated
  12179. */
  12180. constructor: function(target) {
  12181. this.target = target;
  12182. this.id = this.getId();
  12183. },
  12184. getId: function() {
  12185. return this.target.id;
  12186. }
  12187. });
  12188. /**
  12189. * @class Ext.fx.target.Sprite
  12190. * @extends Ext.fx.target.Target
  12191. This class represents a animation target for a {@link Ext.draw.Sprite}. In general this class will not be
  12192. created directly, the {@link Ext.draw.Sprite} will be passed to the animation and
  12193. and the appropriate target will be created.
  12194. * @markdown
  12195. */
  12196. Ext.define('Ext.fx.target.Sprite', {
  12197. /* Begin Definitions */
  12198. extend: 'Ext.fx.target.Target',
  12199. /* End Definitions */
  12200. type: 'draw',
  12201. getFromPrim: function(sprite, attr) {
  12202. var o;
  12203. if (attr == 'translate') {
  12204. o = {
  12205. x: sprite.attr.translation.x || 0,
  12206. y: sprite.attr.translation.y || 0
  12207. };
  12208. }
  12209. else if (attr == 'rotate') {
  12210. o = {
  12211. degrees: sprite.attr.rotation.degrees || 0,
  12212. x: sprite.attr.rotation.x,
  12213. y: sprite.attr.rotation.y
  12214. };
  12215. }
  12216. else {
  12217. o = sprite.attr[attr];
  12218. }
  12219. return o;
  12220. },
  12221. getAttr: function(attr, val) {
  12222. return [[this.target, val != undefined ? val : this.getFromPrim(this.target, attr)]];
  12223. },
  12224. setAttr: function(targetData) {
  12225. var ln = targetData.length,
  12226. spriteArr = [],
  12227. attrs, attr, attrArr, attPtr, spritePtr, idx, value, i, j, x, y, ln2;
  12228. for (i = 0; i < ln; i++) {
  12229. attrs = targetData[i].attrs;
  12230. for (attr in attrs) {
  12231. attrArr = attrs[attr];
  12232. ln2 = attrArr.length;
  12233. for (j = 0; j < ln2; j++) {
  12234. spritePtr = attrArr[j][0];
  12235. attPtr = attrArr[j][1];
  12236. if (attr === 'translate') {
  12237. value = {
  12238. x: attPtr.x,
  12239. y: attPtr.y
  12240. };
  12241. }
  12242. else if (attr === 'rotate') {
  12243. x = attPtr.x;
  12244. if (isNaN(x)) {
  12245. x = null;
  12246. }
  12247. y = attPtr.y;
  12248. if (isNaN(y)) {
  12249. y = null;
  12250. }
  12251. value = {
  12252. degrees: attPtr.degrees,
  12253. x: x,
  12254. y: y
  12255. };
  12256. }
  12257. else if (attr === 'width' || attr === 'height' || attr === 'x' || attr === 'y') {
  12258. value = parseFloat(attPtr);
  12259. }
  12260. else {
  12261. value = attPtr;
  12262. }
  12263. idx = Ext.Array.indexOf(spriteArr, spritePtr);
  12264. if (idx == -1) {
  12265. spriteArr.push([spritePtr, {}]);
  12266. idx = spriteArr.length - 1;
  12267. }
  12268. spriteArr[idx][1][attr] = value;
  12269. }
  12270. }
  12271. }
  12272. ln = spriteArr.length;
  12273. for (i = 0; i < ln; i++) {
  12274. spritePtr = spriteArr[i];
  12275. spritePtr[0].setAttributes(spritePtr[1]);
  12276. }
  12277. this.target.redraw();
  12278. }
  12279. });
  12280. /**
  12281. * @class Ext.fx.target.CompositeSprite
  12282. * @extends Ext.fx.target.Sprite
  12283. This class represents a animation target for a {@link Ext.draw.CompositeSprite}. It allows
  12284. each {@link Ext.draw.Sprite} in the group to be animated as a whole. In general this class will not be
  12285. created directly, the {@link Ext.draw.CompositeSprite} will be passed to the animation and
  12286. and the appropriate target will be created.
  12287. * @markdown
  12288. */
  12289. Ext.define('Ext.fx.target.CompositeSprite', {
  12290. /* Begin Definitions */
  12291. extend: 'Ext.fx.target.Sprite',
  12292. /* End Definitions */
  12293. getAttr: function(attr, val) {
  12294. var out = [],
  12295. target = this.target;
  12296. target.each(function(sprite) {
  12297. out.push([sprite, val != undefined ? val : this.getFromPrim(sprite, attr)]);
  12298. }, this);
  12299. return out;
  12300. }
  12301. });
  12302. /**
  12303. * @class Ext.fx.target.Component
  12304. * @extends Ext.fx.target.Target
  12305. *
  12306. * This class represents a animation target for a {@link Ext.Component}. In general this class will not be
  12307. * created directly, the {@link Ext.Component} will be passed to the animation and
  12308. * and the appropriate target will be created.
  12309. */
  12310. Ext.define('Ext.fx.target.Component', {
  12311. /* Begin Definitions */
  12312. extend: 'Ext.fx.target.Target',
  12313. /* End Definitions */
  12314. type: 'component',
  12315. // Methods to call to retrieve unspecified "from" values from a target Component
  12316. getPropMethod: {
  12317. top: function() {
  12318. return this.getPosition(true)[1];
  12319. },
  12320. left: function() {
  12321. return this.getPosition(true)[0];
  12322. },
  12323. x: function() {
  12324. return this.getPosition()[0];
  12325. },
  12326. y: function() {
  12327. return this.getPosition()[1];
  12328. },
  12329. height: function() {
  12330. return this.getHeight();
  12331. },
  12332. width: function() {
  12333. return this.getWidth();
  12334. },
  12335. opacity: function() {
  12336. return this.el.getStyle('opacity');
  12337. }
  12338. },
  12339. compMethod: {
  12340. top: 'setPosition',
  12341. left: 'setPosition',
  12342. x: 'setPagePosition',
  12343. y: 'setPagePosition',
  12344. height: 'setSize',
  12345. width: 'setSize',
  12346. opacity: 'setOpacity'
  12347. },
  12348. // Read the named attribute from the target Component. Use the defined getter for the attribute
  12349. getAttr: function(attr, val) {
  12350. return [[this.target, val !== undefined ? val : this.getPropMethod[attr].call(this.target)]];
  12351. },
  12352. setAttr: function(targetData, isFirstFrame, isLastFrame) {
  12353. var me = this,
  12354. target = me.target,
  12355. ln = targetData.length,
  12356. attrs, attr, o, i, j, meth, targets, left, top, w, h;
  12357. for (i = 0; i < ln; i++) {
  12358. attrs = targetData[i].attrs;
  12359. for (attr in attrs) {
  12360. targets = attrs[attr].length;
  12361. meth = {
  12362. setPosition: {},
  12363. setPagePosition: {},
  12364. setSize: {},
  12365. setOpacity: {}
  12366. };
  12367. for (j = 0; j < targets; j++) {
  12368. o = attrs[attr][j];
  12369. // We REALLY want a single function call, so push these down to merge them: eg
  12370. // meth.setPagePosition.target = <targetComponent>
  12371. // meth.setPagePosition['x'] = 100
  12372. // meth.setPagePosition['y'] = 100
  12373. meth[me.compMethod[attr]].target = o[0];
  12374. meth[me.compMethod[attr]][attr] = o[1];
  12375. }
  12376. if (meth.setPosition.target) {
  12377. o = meth.setPosition;
  12378. left = (o.left === undefined) ? undefined : parseInt(o.left, 10);
  12379. top = (o.top === undefined) ? undefined : parseInt(o.top, 10);
  12380. o.target.setPosition(left, top);
  12381. }
  12382. if (meth.setPagePosition.target) {
  12383. o = meth.setPagePosition;
  12384. o.target.setPagePosition(o.x, o.y);
  12385. }
  12386. if (meth.setSize.target && meth.setSize.target.el) {
  12387. o = meth.setSize;
  12388. // Dimensions not being animated MUST NOT be autosized. They must remain at current value.
  12389. w = (o.width === undefined) ? o.target.getWidth() : parseInt(o.width, 10);
  12390. h = (o.height === undefined) ? o.target.getHeight() : parseInt(o.height, 10);
  12391. // Only set the size of the Component on the last frame, or if the animation was
  12392. // configured with dynamic: true.
  12393. // In other cases, we just set the target element size.
  12394. // This will result in either clipping if animating a reduction in size, or the revealing of
  12395. // the inner elements of the Component if animating an increase in size.
  12396. // Component's animate function initially resizes to the larger size before resizing the
  12397. // outer element to clip the contents.
  12398. if (isLastFrame || me.dynamic) {
  12399. o.target.componentLayout.childrenChanged = true;
  12400. // Flag if we are being called by an animating layout: use setCalculatedSize
  12401. if (me.layoutAnimation) {
  12402. o.target.setCalculatedSize(w, h);
  12403. } else {
  12404. o.target.setSize(w, h);
  12405. }
  12406. }
  12407. else {
  12408. o.target.el.setSize(w, h);
  12409. }
  12410. }
  12411. if (meth.setOpacity.target) {
  12412. o = meth.setOpacity;
  12413. o.target.el.setStyle('opacity', o.opacity);
  12414. }
  12415. }
  12416. }
  12417. }
  12418. });
  12419. /**
  12420. * @class Ext.fx.CubicBezier
  12421. * @ignore
  12422. */
  12423. Ext.define('Ext.fx.CubicBezier', {
  12424. /* Begin Definitions */
  12425. singleton: true,
  12426. /* End Definitions */
  12427. cubicBezierAtTime: function(t, p1x, p1y, p2x, p2y, duration) {
  12428. var cx = 3 * p1x,
  12429. bx = 3 * (p2x - p1x) - cx,
  12430. ax = 1 - cx - bx,
  12431. cy = 3 * p1y,
  12432. by = 3 * (p2y - p1y) - cy,
  12433. ay = 1 - cy - by;
  12434. function sampleCurveX(t) {
  12435. return ((ax * t + bx) * t + cx) * t;
  12436. }
  12437. function solve(x, epsilon) {
  12438. var t = solveCurveX(x, epsilon);
  12439. return ((ay * t + by) * t + cy) * t;
  12440. }
  12441. function solveCurveX(x, epsilon) {
  12442. var t0, t1, t2, x2, d2, i;
  12443. for (t2 = x, i = 0; i < 8; i++) {
  12444. x2 = sampleCurveX(t2) - x;
  12445. if (Math.abs(x2) < epsilon) {
  12446. return t2;
  12447. }
  12448. d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
  12449. if (Math.abs(d2) < 1e-6) {
  12450. break;
  12451. }
  12452. t2 = t2 - x2 / d2;
  12453. }
  12454. t0 = 0;
  12455. t1 = 1;
  12456. t2 = x;
  12457. if (t2 < t0) {
  12458. return t0;
  12459. }
  12460. if (t2 > t1) {
  12461. return t1;
  12462. }
  12463. while (t0 < t1) {
  12464. x2 = sampleCurveX(t2);
  12465. if (Math.abs(x2 - x) < epsilon) {
  12466. return t2;
  12467. }
  12468. if (x > x2) {
  12469. t0 = t2;
  12470. } else {
  12471. t1 = t2;
  12472. }
  12473. t2 = (t1 - t0) / 2 + t0;
  12474. }
  12475. return t2;
  12476. }
  12477. return solve(t, 1 / (200 * duration));
  12478. },
  12479. cubicBezier: function(x1, y1, x2, y2) {
  12480. var fn = function(pos) {
  12481. return Ext.fx.CubicBezier.cubicBezierAtTime(pos, x1, y1, x2, y2, 1);
  12482. };
  12483. fn.toCSS3 = function() {
  12484. return 'cubic-bezier(' + [x1, y1, x2, y2].join(',') + ')';
  12485. };
  12486. fn.reverse = function() {
  12487. return Ext.fx.CubicBezier.cubicBezier(1 - x2, 1 - y2, 1 - x1, 1 - y1);
  12488. };
  12489. return fn;
  12490. }
  12491. });
  12492. /**
  12493. * Represents an RGB color and provides helper functions get
  12494. * color components in HSL color space.
  12495. */
  12496. Ext.define('Ext.draw.Color', {
  12497. /* Begin Definitions */
  12498. /* End Definitions */
  12499. colorToHexRe: /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/,
  12500. rgbRe: /\s*rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)\s*/,
  12501. hexRe: /\s*#([0-9a-fA-F][0-9a-fA-F]?)([0-9a-fA-F][0-9a-fA-F]?)([0-9a-fA-F][0-9a-fA-F]?)\s*/,
  12502. /**
  12503. * @cfg {Number} lightnessFactor
  12504. *
  12505. * The default factor to compute the lighter or darker color. Defaults to 0.2.
  12506. */
  12507. lightnessFactor: 0.2,
  12508. /**
  12509. * Creates new Color.
  12510. * @param {Number} red Red component (0..255)
  12511. * @param {Number} green Green component (0..255)
  12512. * @param {Number} blue Blue component (0..255)
  12513. */
  12514. constructor : function(red, green, blue) {
  12515. var me = this,
  12516. clamp = Ext.Number.constrain;
  12517. me.r = clamp(red, 0, 255);
  12518. me.g = clamp(green, 0, 255);
  12519. me.b = clamp(blue, 0, 255);
  12520. },
  12521. /**
  12522. * Get the red component of the color, in the range 0..255.
  12523. * @return {Number}
  12524. */
  12525. getRed: function() {
  12526. return this.r;
  12527. },
  12528. /**
  12529. * Get the green component of the color, in the range 0..255.
  12530. * @return {Number}
  12531. */
  12532. getGreen: function() {
  12533. return this.g;
  12534. },
  12535. /**
  12536. * Get the blue component of the color, in the range 0..255.
  12537. * @return {Number}
  12538. */
  12539. getBlue: function() {
  12540. return this.b;
  12541. },
  12542. /**
  12543. * Get the RGB values.
  12544. * @return {Number[]}
  12545. */
  12546. getRGB: function() {
  12547. var me = this;
  12548. return [me.r, me.g, me.b];
  12549. },
  12550. /**
  12551. * Get the equivalent HSL components of the color.
  12552. * @return {Number[]}
  12553. */
  12554. getHSL: function() {
  12555. var me = this,
  12556. r = me.r / 255,
  12557. g = me.g / 255,
  12558. b = me.b / 255,
  12559. max = Math.max(r, g, b),
  12560. min = Math.min(r, g, b),
  12561. delta = max - min,
  12562. h,
  12563. s = 0,
  12564. l = 0.5 * (max + min);
  12565. // min==max means achromatic (hue is undefined)
  12566. if (min != max) {
  12567. s = (l < 0.5) ? delta / (max + min) : delta / (2 - max - min);
  12568. if (r == max) {
  12569. h = 60 * (g - b) / delta;
  12570. } else if (g == max) {
  12571. h = 120 + 60 * (b - r) / delta;
  12572. } else {
  12573. h = 240 + 60 * (r - g) / delta;
  12574. }
  12575. if (h < 0) {
  12576. h += 360;
  12577. }
  12578. if (h >= 360) {
  12579. h -= 360;
  12580. }
  12581. }
  12582. return [h, s, l];
  12583. },
  12584. /**
  12585. * Return a new color that is lighter than this color.
  12586. * @param {Number} factor Lighter factor (0..1), default to 0.2
  12587. * @return Ext.draw.Color
  12588. */
  12589. getLighter: function(factor) {
  12590. var hsl = this.getHSL();
  12591. factor = factor || this.lightnessFactor;
  12592. hsl[2] = Ext.Number.constrain(hsl[2] + factor, 0, 1);
  12593. return this.fromHSL(hsl[0], hsl[1], hsl[2]);
  12594. },
  12595. /**
  12596. * Return a new color that is darker than this color.
  12597. * @param {Number} factor Darker factor (0..1), default to 0.2
  12598. * @return Ext.draw.Color
  12599. */
  12600. getDarker: function(factor) {
  12601. factor = factor || this.lightnessFactor;
  12602. return this.getLighter(-factor);
  12603. },
  12604. /**
  12605. * Return the color in the hex format, i.e. '#rrggbb'.
  12606. * @return {String}
  12607. */
  12608. toString: function() {
  12609. var me = this,
  12610. round = Math.round,
  12611. r = round(me.r).toString(16),
  12612. g = round(me.g).toString(16),
  12613. b = round(me.b).toString(16);
  12614. r = (r.length == 1) ? '0' + r : r;
  12615. g = (g.length == 1) ? '0' + g : g;
  12616. b = (b.length == 1) ? '0' + b : b;
  12617. return ['#', r, g, b].join('');
  12618. },
  12619. /**
  12620. * Convert a color to hexadecimal format.
  12621. *
  12622. * **Note:** This method is both static and instance.
  12623. *
  12624. * @param {String/String[]} color The color value (i.e 'rgb(255, 255, 255)', 'color: #ffffff').
  12625. * Can also be an Array, in this case the function handles the first member.
  12626. * @returns {String} The color in hexadecimal format.
  12627. * @static
  12628. */
  12629. toHex: function(color) {
  12630. if (Ext.isArray(color)) {
  12631. color = color[0];
  12632. }
  12633. if (!Ext.isString(color)) {
  12634. return '';
  12635. }
  12636. if (color.substr(0, 1) === '#') {
  12637. return color;
  12638. }
  12639. var digits = this.colorToHexRe.exec(color);
  12640. if (Ext.isArray(digits)) {
  12641. var red = parseInt(digits[2], 10),
  12642. green = parseInt(digits[3], 10),
  12643. blue = parseInt(digits[4], 10),
  12644. rgb = blue | (green << 8) | (red << 16);
  12645. return digits[1] + '#' + ("000000" + rgb.toString(16)).slice(-6);
  12646. }
  12647. else {
  12648. return '';
  12649. }
  12650. },
  12651. /**
  12652. * Parse the string and create a new color.
  12653. *
  12654. * Supported formats: '#rrggbb', '#rgb', and 'rgb(r,g,b)'.
  12655. *
  12656. * If the string is not recognized, an undefined will be returned instead.
  12657. *
  12658. * **Note:** This method is both static and instance.
  12659. *
  12660. * @param {String} str Color in string.
  12661. * @returns Ext.draw.Color
  12662. * @static
  12663. */
  12664. fromString: function(str) {
  12665. var values, r, g, b,
  12666. parse = parseInt;
  12667. if ((str.length == 4 || str.length == 7) && str.substr(0, 1) === '#') {
  12668. values = str.match(this.hexRe);
  12669. if (values) {
  12670. r = parse(values[1], 16) >> 0;
  12671. g = parse(values[2], 16) >> 0;
  12672. b = parse(values[3], 16) >> 0;
  12673. if (str.length == 4) {
  12674. r += (r * 16);
  12675. g += (g * 16);
  12676. b += (b * 16);
  12677. }
  12678. }
  12679. }
  12680. else {
  12681. values = str.match(this.rgbRe);
  12682. if (values) {
  12683. r = values[1];
  12684. g = values[2];
  12685. b = values[3];
  12686. }
  12687. }
  12688. return (typeof r == 'undefined') ? undefined : Ext.create('Ext.draw.Color', r, g, b);
  12689. },
  12690. /**
  12691. * Returns the gray value (0 to 255) of the color.
  12692. *
  12693. * The gray value is calculated using the formula r*0.3 + g*0.59 + b*0.11.
  12694. *
  12695. * @returns {Number}
  12696. */
  12697. getGrayscale: function() {
  12698. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  12699. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  12700. },
  12701. /**
  12702. * Create a new color based on the specified HSL values.
  12703. *
  12704. * **Note:** This method is both static and instance.
  12705. *
  12706. * @param {Number} h Hue component (0..359)
  12707. * @param {Number} s Saturation component (0..1)
  12708. * @param {Number} l Lightness component (0..1)
  12709. * @returns Ext.draw.Color
  12710. * @static
  12711. */
  12712. fromHSL: function(h, s, l) {
  12713. var C, X, m, i, rgb = [],
  12714. abs = Math.abs,
  12715. floor = Math.floor;
  12716. if (s == 0 || h == null) {
  12717. // achromatic
  12718. rgb = [l, l, l];
  12719. }
  12720. else {
  12721. // http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL
  12722. // C is the chroma
  12723. // X is the second largest component
  12724. // m is the lightness adjustment
  12725. h /= 60;
  12726. C = s * (1 - abs(2 * l - 1));
  12727. X = C * (1 - abs(h - 2 * floor(h / 2) - 1));
  12728. m = l - C / 2;
  12729. switch (floor(h)) {
  12730. case 0:
  12731. rgb = [C, X, 0];
  12732. break;
  12733. case 1:
  12734. rgb = [X, C, 0];
  12735. break;
  12736. case 2:
  12737. rgb = [0, C, X];
  12738. break;
  12739. case 3:
  12740. rgb = [0, X, C];
  12741. break;
  12742. case 4:
  12743. rgb = [X, 0, C];
  12744. break;
  12745. case 5:
  12746. rgb = [C, 0, X];
  12747. break;
  12748. }
  12749. rgb = [rgb[0] + m, rgb[1] + m, rgb[2] + m];
  12750. }
  12751. return Ext.create('Ext.draw.Color', rgb[0] * 255, rgb[1] * 255, rgb[2] * 255);
  12752. }
  12753. }, function() {
  12754. var prototype = this.prototype;
  12755. //These functions are both static and instance. TODO: find a more elegant way of copying them
  12756. this.addStatics({
  12757. fromHSL: function() {
  12758. return prototype.fromHSL.apply(prototype, arguments);
  12759. },
  12760. fromString: function() {
  12761. return prototype.fromString.apply(prototype, arguments);
  12762. },
  12763. toHex: function() {
  12764. return prototype.toHex.apply(prototype, arguments);
  12765. }
  12766. });
  12767. });
  12768. /**
  12769. * @class Ext.dd.StatusProxy
  12770. * A specialized drag proxy that supports a drop status icon, {@link Ext.Layer} styles and auto-repair. This is the
  12771. * default drag proxy used by all Ext.dd components.
  12772. */
  12773. Ext.define('Ext.dd.StatusProxy', {
  12774. animRepair: false,
  12775. /**
  12776. * Creates new StatusProxy.
  12777. * @param {Object} config (optional) Config object.
  12778. */
  12779. constructor: function(config){
  12780. Ext.apply(this, config);
  12781. this.id = this.id || Ext.id();
  12782. this.proxy = Ext.createWidget('component', {
  12783. floating: true,
  12784. stateful: false,
  12785. id: this.id,
  12786. html: '<div class="' + Ext.baseCSSPrefix + 'dd-drop-icon"></div>' +
  12787. '<div class="' + Ext.baseCSSPrefix + 'dd-drag-ghost"></div>',
  12788. cls: Ext.baseCSSPrefix + 'dd-drag-proxy ' + this.dropNotAllowed,
  12789. shadow: !config || config.shadow !== false,
  12790. renderTo: document.body
  12791. });
  12792. this.el = this.proxy.el;
  12793. this.el.show();
  12794. this.el.setVisibilityMode(Ext.Element.VISIBILITY);
  12795. this.el.hide();
  12796. this.ghost = Ext.get(this.el.dom.childNodes[1]);
  12797. this.dropStatus = this.dropNotAllowed;
  12798. },
  12799. /**
  12800. * @cfg {String} [dropAllowed="x-dd-drop-ok"]
  12801. * The CSS class to apply to the status element when drop is allowed.
  12802. */
  12803. dropAllowed : Ext.baseCSSPrefix + 'dd-drop-ok',
  12804. /**
  12805. * @cfg {String} [dropNotAllowed="x-dd-drop-nodrop"]
  12806. * The CSS class to apply to the status element when drop is not allowed.
  12807. */
  12808. dropNotAllowed : Ext.baseCSSPrefix + 'dd-drop-nodrop',
  12809. /**
  12810. * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
  12811. * over the current target element.
  12812. * @param {String} cssClass The css class for the new drop status indicator image
  12813. */
  12814. setStatus : function(cssClass){
  12815. cssClass = cssClass || this.dropNotAllowed;
  12816. if(this.dropStatus != cssClass){
  12817. this.el.replaceCls(this.dropStatus, cssClass);
  12818. this.dropStatus = cssClass;
  12819. }
  12820. },
  12821. /**
  12822. * Resets the status indicator to the default dropNotAllowed value
  12823. * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
  12824. */
  12825. reset : function(clearGhost){
  12826. this.el.dom.className = Ext.baseCSSPrefix + 'dd-drag-proxy ' + this.dropNotAllowed;
  12827. this.dropStatus = this.dropNotAllowed;
  12828. if(clearGhost){
  12829. this.ghost.update("");
  12830. }
  12831. },
  12832. /**
  12833. * Updates the contents of the ghost element
  12834. * @param {String/HTMLElement} html The html that will replace the current innerHTML of the ghost element, or a
  12835. * DOM node to append as the child of the ghost element (in which case the innerHTML will be cleared first).
  12836. */
  12837. update : function(html){
  12838. if(typeof html == "string"){
  12839. this.ghost.update(html);
  12840. }else{
  12841. this.ghost.update("");
  12842. html.style.margin = "0";
  12843. this.ghost.dom.appendChild(html);
  12844. }
  12845. var el = this.ghost.dom.firstChild;
  12846. if(el){
  12847. Ext.fly(el).setStyle('float', 'none');
  12848. }
  12849. },
  12850. /**
  12851. * Returns the underlying proxy {@link Ext.Layer}
  12852. * @return {Ext.Layer} el
  12853. */
  12854. getEl : function(){
  12855. return this.el;
  12856. },
  12857. /**
  12858. * Returns the ghost element
  12859. * @return {Ext.Element} el
  12860. */
  12861. getGhost : function(){
  12862. return this.ghost;
  12863. },
  12864. /**
  12865. * Hides the proxy
  12866. * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
  12867. */
  12868. hide : function(clear) {
  12869. this.proxy.hide();
  12870. if (clear) {
  12871. this.reset(true);
  12872. }
  12873. },
  12874. /**
  12875. * Stops the repair animation if it's currently running
  12876. */
  12877. stop : function(){
  12878. if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
  12879. this.anim.stop();
  12880. }
  12881. },
  12882. /**
  12883. * Displays this proxy
  12884. */
  12885. show : function() {
  12886. this.proxy.show();
  12887. this.proxy.toFront();
  12888. },
  12889. /**
  12890. * Force the Layer to sync its shadow and shim positions to the element
  12891. */
  12892. sync : function(){
  12893. this.proxy.el.sync();
  12894. },
  12895. /**
  12896. * Causes the proxy to return to its position of origin via an animation. Should be called after an
  12897. * invalid drop operation by the item being dragged.
  12898. * @param {Number[]} xy The XY position of the element ([x, y])
  12899. * @param {Function} callback The function to call after the repair is complete.
  12900. * @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
  12901. */
  12902. repair : function(xy, callback, scope){
  12903. this.callback = callback;
  12904. this.scope = scope;
  12905. if (xy && this.animRepair !== false) {
  12906. this.el.addCls(Ext.baseCSSPrefix + 'dd-drag-repair');
  12907. this.el.hideUnders(true);
  12908. this.anim = this.el.animate({
  12909. duration: this.repairDuration || 500,
  12910. easing: 'ease-out',
  12911. to: {
  12912. x: xy[0],
  12913. y: xy[1]
  12914. },
  12915. stopAnimation: true,
  12916. callback: this.afterRepair,
  12917. scope: this
  12918. });
  12919. } else {
  12920. this.afterRepair();
  12921. }
  12922. },
  12923. // private
  12924. afterRepair : function(){
  12925. this.hide(true);
  12926. if(typeof this.callback == "function"){
  12927. this.callback.call(this.scope || this);
  12928. }
  12929. this.callback = null;
  12930. this.scope = null;
  12931. },
  12932. destroy: function(){
  12933. Ext.destroy(this.ghost, this.proxy, this.el);
  12934. }
  12935. });
  12936. /**
  12937. * A custom drag proxy implementation specific to {@link Ext.panel.Panel}s. This class
  12938. * is primarily used internally for the Panel's drag drop implementation, and
  12939. * should never need to be created directly.
  12940. * @private
  12941. */
  12942. Ext.define('Ext.panel.Proxy', {
  12943. alternateClassName: 'Ext.dd.PanelProxy',
  12944. /**
  12945. * Creates new panel proxy.
  12946. * @param {Ext.panel.Panel} panel The {@link Ext.panel.Panel} to proxy for
  12947. * @param {Object} [config] Config object
  12948. */
  12949. constructor: function(panel, config){
  12950. /**
  12951. * @property panel
  12952. * @type Ext.panel.Panel
  12953. */
  12954. this.panel = panel;
  12955. this.id = this.panel.id +'-ddproxy';
  12956. Ext.apply(this, config);
  12957. },
  12958. /**
  12959. * @cfg {Boolean} insertProxy
  12960. * True to insert a placeholder proxy element while dragging the panel, false to drag with no proxy.
  12961. * Most Panels are not absolute positioned and therefore we need to reserve this space.
  12962. */
  12963. insertProxy: true,
  12964. // private overrides
  12965. setStatus: Ext.emptyFn,
  12966. reset: Ext.emptyFn,
  12967. update: Ext.emptyFn,
  12968. stop: Ext.emptyFn,
  12969. sync: Ext.emptyFn,
  12970. /**
  12971. * Gets the proxy's element
  12972. * @return {Ext.Element} The proxy's element
  12973. */
  12974. getEl: function(){
  12975. return this.ghost.el;
  12976. },
  12977. /**
  12978. * Gets the proxy's ghost Panel
  12979. * @return {Ext.panel.Panel} The proxy's ghost Panel
  12980. */
  12981. getGhost: function(){
  12982. return this.ghost;
  12983. },
  12984. /**
  12985. * Gets the proxy element. This is the element that represents where the
  12986. * Panel was before we started the drag operation.
  12987. * @return {Ext.Element} The proxy's element
  12988. */
  12989. getProxy: function(){
  12990. return this.proxy;
  12991. },
  12992. /**
  12993. * Hides the proxy
  12994. */
  12995. hide : function(){
  12996. if (this.ghost) {
  12997. if (this.proxy) {
  12998. this.proxy.remove();
  12999. delete this.proxy;
  13000. }
  13001. // Unghost the Panel, do not move the Panel to where the ghost was
  13002. this.panel.unghost(null, false);
  13003. delete this.ghost;
  13004. }
  13005. },
  13006. /**
  13007. * Shows the proxy
  13008. */
  13009. show: function(){
  13010. if (!this.ghost) {
  13011. var panelSize = this.panel.getSize();
  13012. this.panel.el.setVisibilityMode(Ext.Element.DISPLAY);
  13013. this.ghost = this.panel.ghost();
  13014. if (this.insertProxy) {
  13015. // bc Panels aren't absolute positioned we need to take up the space
  13016. // of where the panel previously was
  13017. this.proxy = this.panel.el.insertSibling({cls: Ext.baseCSSPrefix + 'panel-dd-spacer'});
  13018. this.proxy.setSize(panelSize);
  13019. }
  13020. }
  13021. },
  13022. // private
  13023. repair: function(xy, callback, scope) {
  13024. this.hide();
  13025. if (typeof callback == "function") {
  13026. callback.call(scope || this);
  13027. }
  13028. },
  13029. /**
  13030. * Moves the proxy to a different position in the DOM. This is typically
  13031. * called while dragging the Panel to keep the proxy sync'd to the Panel's
  13032. * location.
  13033. * @param {HTMLElement} parentNode The proxy's parent DOM node
  13034. * @param {HTMLElement} [before] The sibling node before which the
  13035. * proxy should be inserted (defaults to the parent's last child if not
  13036. * specified)
  13037. */
  13038. moveProxy : function(parentNode, before){
  13039. if (this.proxy) {
  13040. parentNode.insertBefore(this.proxy.dom, before);
  13041. }
  13042. }
  13043. });
  13044. /**
  13045. * @class Ext.layout.component.AbstractDock
  13046. * @extends Ext.layout.component.Component
  13047. * @private
  13048. * This ComponentLayout handles docking for Panels. It takes care of panels that are
  13049. * part of a ContainerLayout that sets this Panel's size and Panels that are part of
  13050. * an AutoContainerLayout in which this panel get his height based of the CSS or
  13051. * or its content.
  13052. */
  13053. Ext.define('Ext.layout.component.AbstractDock', {
  13054. /* Begin Definitions */
  13055. extend: 'Ext.layout.component.Component',
  13056. /* End Definitions */
  13057. type: 'dock',
  13058. /**
  13059. * @private
  13060. * @property autoSizing
  13061. * @type Boolean
  13062. * This flag is set to indicate this layout may have an autoHeigh