/ext-4.0.7/ext-all-debug-w-comments.js

https://bitbucket.org/srogerf/javascript · JavaScript · 27823 lines · 14877 code · 2469 blank · 10477 comment · 3006 complexity · cd31a3bae62ba15b08ea7e8779ed7476 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. * @class Ext
  11. * @singleton
  12. */
  13. (function() {
  14. var global = this,
  15. objectPrototype = Object.prototype,
  16. toString = objectPrototype.toString,
  17. enumerables = true,
  18. enumerablesTest = { toString: 1 },
  19. i;
  20. if (typeof Ext === 'undefined') {
  21. global.Ext = {};
  22. }
  23. Ext.global = global;
  24. for (i in enumerablesTest) {
  25. enumerables = null;
  26. }
  27. if (enumerables) {
  28. enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable',
  29. 'toLocaleString', 'toString', 'constructor'];
  30. }
  31. /**
  32. * An array containing extra enumerables for old browsers
  33. * @property {String[]}
  34. */
  35. Ext.enumerables = enumerables;
  36. /**
  37. * Copies all the properties of config to the specified object.
  38. * Note that if recursive merging and cloning without referencing the original objects / arrays is needed, use
  39. * {@link Ext.Object#merge} instead.
  40. * @param {Object} object The receiver of the properties
  41. * @param {Object} config The source of the properties
  42. * @param {Object} defaults A different object that will also be applied for default values
  43. * @return {Object} returns obj
  44. */
  45. Ext.apply = function(object, config, defaults) {
  46. if (defaults) {
  47. Ext.apply(object, defaults);
  48. }
  49. if (object && config && typeof config === 'object') {
  50. var i, j, k;
  51. for (i in config) {
  52. object[i] = config[i];
  53. }
  54. if (enumerables) {
  55. for (j = enumerables.length; j--;) {
  56. k = enumerables[j];
  57. if (config.hasOwnProperty(k)) {
  58. object[k] = config[k];
  59. }
  60. }
  61. }
  62. }
  63. return object;
  64. };
  65. Ext.buildSettings = Ext.apply({
  66. baseCSSPrefix: 'x-',
  67. scopeResetCSS: false
  68. }, Ext.buildSettings || {});
  69. Ext.apply(Ext, {
  70. /**
  71. * A reusable empty function
  72. */
  73. emptyFn: function() {},
  74. baseCSSPrefix: Ext.buildSettings.baseCSSPrefix,
  75. /**
  76. * Copies all the properties of config to object if they don't already exist.
  77. * @param {Object} object The receiver of the properties
  78. * @param {Object} config The source of the properties
  79. * @return {Object} returns obj
  80. */
  81. applyIf: function(object, config) {
  82. var property;
  83. if (object) {
  84. for (property in config) {
  85. if (object[property] === undefined) {
  86. object[property] = config[property];
  87. }
  88. }
  89. }
  90. return object;
  91. },
  92. /**
  93. * Iterates either an array or an object. This method delegates to
  94. * {@link Ext.Array#each Ext.Array.each} if the given value is iterable, and {@link Ext.Object#each Ext.Object.each} otherwise.
  95. *
  96. * @param {Object/Array} object The object or array to be iterated.
  97. * @param {Function} fn The function to be called for each iteration. See and {@link Ext.Array#each Ext.Array.each} and
  98. * {@link Ext.Object#each Ext.Object.each} for detailed lists of arguments passed to this function depending on the given object
  99. * type that is being iterated.
  100. * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
  101. * Defaults to the object being iterated itself.
  102. * @markdown
  103. */
  104. iterate: function(object, fn, scope) {
  105. if (Ext.isEmpty(object)) {
  106. return;
  107. }
  108. if (scope === undefined) {
  109. scope = object;
  110. }
  111. if (Ext.isIterable(object)) {
  112. Ext.Array.each.call(Ext.Array, object, fn, scope);
  113. }
  114. else {
  115. Ext.Object.each.call(Ext.Object, object, fn, scope);
  116. }
  117. }
  118. });
  119. Ext.apply(Ext, {
  120. /**
  121. * This method deprecated. Use {@link Ext#define Ext.define} instead.
  122. * @method
  123. * @param {Function} superclass
  124. * @param {Object} overrides
  125. * @return {Function} The subclass constructor from the <tt>overrides</tt> parameter, or a generated one if not provided.
  126. * @deprecated 4.0.0 Use {@link Ext#define Ext.define} instead
  127. */
  128. extend: function() {
  129. // inline overrides
  130. var objectConstructor = objectPrototype.constructor,
  131. inlineOverrides = function(o) {
  132. for (var m in o) {
  133. if (!o.hasOwnProperty(m)) {
  134. continue;
  135. }
  136. this[m] = o[m];
  137. }
  138. };
  139. return function(subclass, superclass, overrides) {
  140. // First we check if the user passed in just the superClass with overrides
  141. if (Ext.isObject(superclass)) {
  142. overrides = superclass;
  143. superclass = subclass;
  144. subclass = overrides.constructor !== objectConstructor ? overrides.constructor : function() {
  145. superclass.apply(this, arguments);
  146. };
  147. }
  148. // We create a new temporary class
  149. var F = function() {},
  150. subclassProto, superclassProto = superclass.prototype;
  151. F.prototype = superclassProto;
  152. subclassProto = subclass.prototype = new F();
  153. subclassProto.constructor = subclass;
  154. subclass.superclass = superclassProto;
  155. if (superclassProto.constructor === objectConstructor) {
  156. superclassProto.constructor = superclass;
  157. }
  158. subclass.override = function(overrides) {
  159. Ext.override(subclass, overrides);
  160. };
  161. subclassProto.override = inlineOverrides;
  162. subclassProto.proto = subclassProto;
  163. subclass.override(overrides);
  164. subclass.extend = function(o) {
  165. return Ext.extend(subclass, o);
  166. };
  167. return subclass;
  168. };
  169. }(),
  170. /**
  171. * Proxy to {@link Ext.Base#override}. Please refer {@link Ext.Base#override} for further details.
  172. Ext.define('My.cool.Class', {
  173. sayHi: function() {
  174. alert('Hi!');
  175. }
  176. }
  177. Ext.override(My.cool.Class, {
  178. sayHi: function() {
  179. alert('About to say...');
  180. this.callOverridden();
  181. }
  182. });
  183. var cool = new My.cool.Class();
  184. cool.sayHi(); // alerts 'About to say...'
  185. // alerts 'Hi!'
  186. * Please note that `this.callOverridden()` only works if the class was previously
  187. * created with {@link Ext#define)
  188. *
  189. * @param {Object} cls The class to override
  190. * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
  191. * containing one or more methods.
  192. * @method override
  193. * @markdown
  194. */
  195. override: function(cls, overrides) {
  196. if (cls.prototype.$className) {
  197. return cls.override(overrides);
  198. }
  199. else {
  200. Ext.apply(cls.prototype, overrides);
  201. }
  202. }
  203. });
  204. // A full set of static methods to do type checking
  205. Ext.apply(Ext, {
  206. /**
  207. * Returns the given value itself if it's not empty, as described in {@link Ext#isEmpty}; returns the default
  208. * value (second argument) otherwise.
  209. *
  210. * @param {Object} value The value to test
  211. * @param {Object} defaultValue The value to return if the original value is empty
  212. * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
  213. * @return {Object} value, if non-empty, else defaultValue
  214. */
  215. valueFrom: function(value, defaultValue, allowBlank){
  216. return Ext.isEmpty(value, allowBlank) ? defaultValue : value;
  217. },
  218. /**
  219. * Returns the type of the given variable in string format. List of possible values are:
  220. *
  221. * - `undefined`: If the given value is `undefined`
  222. * - `null`: If the given value is `null`
  223. * - `string`: If the given value is a string
  224. * - `number`: If the given value is a number
  225. * - `boolean`: If the given value is a boolean value
  226. * - `date`: If the given value is a `Date` object
  227. * - `function`: If the given value is a function reference
  228. * - `object`: If the given value is an object
  229. * - `array`: If the given value is an array
  230. * - `regexp`: If the given value is a regular expression
  231. * - `element`: If the given value is a DOM Element
  232. * - `textnode`: If the given value is a DOM text node and contains something other than whitespace
  233. * - `whitespace`: If the given value is a DOM text node and contains only whitespace
  234. *
  235. * @param {Object} value
  236. * @return {String}
  237. * @markdown
  238. */
  239. typeOf: function(value) {
  240. if (value === null) {
  241. return 'null';
  242. }
  243. var type = typeof value;
  244. if (type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean') {
  245. return type;
  246. }
  247. var typeToString = toString.call(value);
  248. switch(typeToString) {
  249. case '[object Array]':
  250. return 'array';
  251. case '[object Date]':
  252. return 'date';
  253. case '[object Boolean]':
  254. return 'boolean';
  255. case '[object Number]':
  256. return 'number';
  257. case '[object RegExp]':
  258. return 'regexp';
  259. }
  260. if (type === 'function') {
  261. return 'function';
  262. }
  263. if (type === 'object') {
  264. if (value.nodeType !== undefined) {
  265. if (value.nodeType === 3) {
  266. return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace';
  267. }
  268. else {
  269. return 'element';
  270. }
  271. }
  272. return 'object';
  273. }
  274. },
  275. /**
  276. * Returns true if the passed value is empty, false otherwise. The value is deemed to be empty if it is either:
  277. *
  278. * - `null`
  279. * - `undefined`
  280. * - a zero-length array
  281. * - a zero-length string (Unless the `allowEmptyString` parameter is set to `true`)
  282. *
  283. * @param {Object} value The value to test
  284. * @param {Boolean} allowEmptyString (optional) true to allow empty strings (defaults to false)
  285. * @return {Boolean}
  286. * @markdown
  287. */
  288. isEmpty: function(value, allowEmptyString) {
  289. return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Ext.isArray(value) && value.length === 0);
  290. },
  291. /**
  292. * Returns true if the passed value is a JavaScript Array, false otherwise.
  293. *
  294. * @param {Object} target The target to test
  295. * @return {Boolean}
  296. * @method
  297. */
  298. isArray: ('isArray' in Array) ? Array.isArray : function(value) {
  299. return toString.call(value) === '[object Array]';
  300. },
  301. /**
  302. * Returns true if the passed value is a JavaScript Date object, false otherwise.
  303. * @param {Object} object The object to test
  304. * @return {Boolean}
  305. */
  306. isDate: function(value) {
  307. return toString.call(value) === '[object Date]';
  308. },
  309. /**
  310. * Returns true if the passed value is a JavaScript Object, false otherwise.
  311. * @param {Object} value The value to test
  312. * @return {Boolean}
  313. * @method
  314. */
  315. isObject: (toString.call(null) === '[object Object]') ?
  316. function(value) {
  317. // check ownerDocument here as well to exclude DOM nodes
  318. return value !== null && value !== undefined && toString.call(value) === '[object Object]' && value.ownerDocument === undefined;
  319. } :
  320. function(value) {
  321. return toString.call(value) === '[object Object]';
  322. },
  323. /**
  324. * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean.
  325. * @param {Object} value The value to test
  326. * @return {Boolean}
  327. */
  328. isPrimitive: function(value) {
  329. var type = typeof value;
  330. return type === 'string' || type === 'number' || type === 'boolean';
  331. },
  332. /**
  333. * Returns true if the passed value is a JavaScript Function, false otherwise.
  334. * @param {Object} value The value to test
  335. * @return {Boolean}
  336. * @method
  337. */
  338. isFunction:
  339. // Safari 3.x and 4.x returns 'function' for typeof <NodeList>, hence we need to fall back to using
  340. // Object.prorotype.toString (slower)
  341. (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') ? function(value) {
  342. return toString.call(value) === '[object Function]';
  343. } : function(value) {
  344. return typeof value === 'function';
  345. },
  346. /**
  347. * Returns true if the passed value is a number. Returns false for non-finite numbers.
  348. * @param {Object} value The value to test
  349. * @return {Boolean}
  350. */
  351. isNumber: function(value) {
  352. return typeof value === 'number' && isFinite(value);
  353. },
  354. /**
  355. * Validates that a value is numeric.
  356. * @param {Object} value Examples: 1, '1', '2.34'
  357. * @return {Boolean} True if numeric, false otherwise
  358. */
  359. isNumeric: function(value) {
  360. return !isNaN(parseFloat(value)) && isFinite(value);
  361. },
  362. /**
  363. * Returns true if the passed value is a string.
  364. * @param {Object} value The value to test
  365. * @return {Boolean}
  366. */
  367. isString: function(value) {
  368. return typeof value === 'string';
  369. },
  370. /**
  371. * Returns true if the passed value is a boolean.
  372. *
  373. * @param {Object} value The value to test
  374. * @return {Boolean}
  375. */
  376. isBoolean: function(value) {
  377. return typeof value === 'boolean';
  378. },
  379. /**
  380. * Returns true if the passed value is an HTMLElement
  381. * @param {Object} value The value to test
  382. * @return {Boolean}
  383. */
  384. isElement: function(value) {
  385. return value ? value.nodeType === 1 : false;
  386. },
  387. /**
  388. * Returns true if the passed value is a TextNode
  389. * @param {Object} value The value to test
  390. * @return {Boolean}
  391. */
  392. isTextNode: function(value) {
  393. return value ? value.nodeName === "#text" : false;
  394. },
  395. /**
  396. * Returns true if the passed value is defined.
  397. * @param {Object} value The value to test
  398. * @return {Boolean}
  399. */
  400. isDefined: function(value) {
  401. return typeof value !== 'undefined';
  402. },
  403. /**
  404. * Returns true if the passed value is iterable, false otherwise
  405. * @param {Object} value The value to test
  406. * @return {Boolean}
  407. */
  408. isIterable: function(value) {
  409. return (value && typeof value !== 'string') ? value.length !== undefined : false;
  410. }
  411. });
  412. Ext.apply(Ext, {
  413. /**
  414. * Clone almost any type of variable including array, object, DOM nodes and Date without keeping the old reference
  415. * @param {Object} item The variable to clone
  416. * @return {Object} clone
  417. */
  418. clone: function(item) {
  419. if (item === null || item === undefined) {
  420. return item;
  421. }
  422. // DOM nodes
  423. // TODO proxy this to Ext.Element.clone to handle automatic id attribute changing
  424. // recursively
  425. if (item.nodeType && item.cloneNode) {
  426. return item.cloneNode(true);
  427. }
  428. var type = toString.call(item);
  429. // Date
  430. if (type === '[object Date]') {
  431. return new Date(item.getTime());
  432. }
  433. var i, j, k, clone, key;
  434. // Array
  435. if (type === '[object Array]') {
  436. i = item.length;
  437. clone = [];
  438. while (i--) {
  439. clone[i] = Ext.clone(item[i]);
  440. }
  441. }
  442. // Object
  443. else if (type === '[object Object]' && item.constructor === Object) {
  444. clone = {};
  445. for (key in item) {
  446. clone[key] = Ext.clone(item[key]);
  447. }
  448. if (enumerables) {
  449. for (j = enumerables.length; j--;) {
  450. k = enumerables[j];
  451. clone[k] = item[k];
  452. }
  453. }
  454. }
  455. return clone || item;
  456. },
  457. /**
  458. * @private
  459. * Generate a unique reference of Ext in the global scope, useful for sandboxing
  460. */
  461. getUniqueGlobalNamespace: function() {
  462. var uniqueGlobalNamespace = this.uniqueGlobalNamespace;
  463. if (uniqueGlobalNamespace === undefined) {
  464. var i = 0;
  465. do {
  466. uniqueGlobalNamespace = 'ExtBox' + (++i);
  467. } while (Ext.global[uniqueGlobalNamespace] !== undefined);
  468. Ext.global[uniqueGlobalNamespace] = Ext;
  469. this.uniqueGlobalNamespace = uniqueGlobalNamespace;
  470. }
  471. return uniqueGlobalNamespace;
  472. },
  473. /**
  474. * @private
  475. */
  476. functionFactory: function() {
  477. var args = Array.prototype.slice.call(arguments);
  478. if (args.length > 0) {
  479. args[args.length - 1] = 'var Ext=window.' + this.getUniqueGlobalNamespace() + ';' +
  480. args[args.length - 1];
  481. }
  482. return Function.prototype.constructor.apply(Function.prototype, args);
  483. }
  484. });
  485. /**
  486. * Old alias to {@link Ext#typeOf}
  487. * @deprecated 4.0.0 Use {@link Ext#typeOf} instead
  488. * @method
  489. * @alias Ext#typeOf
  490. */
  491. Ext.type = Ext.typeOf;
  492. })();
  493. /**
  494. * @author Jacky Nguyen <jacky@sencha.com>
  495. * @docauthor Jacky Nguyen <jacky@sencha.com>
  496. * @class Ext.Version
  497. *
  498. * A utility class that wrap around a string version number and provide convenient
  499. * method to perform comparison. See also: {@link Ext.Version#compare compare}. Example:
  500. var version = new Ext.Version('1.0.2beta');
  501. console.log("Version is " + version); // Version is 1.0.2beta
  502. console.log(version.getMajor()); // 1
  503. console.log(version.getMinor()); // 0
  504. console.log(version.getPatch()); // 2
  505. console.log(version.getBuild()); // 0
  506. console.log(version.getRelease()); // beta
  507. console.log(version.isGreaterThan('1.0.1')); // True
  508. console.log(version.isGreaterThan('1.0.2alpha')); // True
  509. console.log(version.isGreaterThan('1.0.2RC')); // False
  510. console.log(version.isGreaterThan('1.0.2')); // False
  511. console.log(version.isLessThan('1.0.2')); // True
  512. console.log(version.match(1.0)); // True
  513. console.log(version.match('1.0.2')); // True
  514. * @markdown
  515. */
  516. (function() {
  517. // Current core version
  518. var version = '4.0.7', Version;
  519. Ext.Version = Version = Ext.extend(Object, {
  520. /**
  521. * @param {String/Number} version The version number in the follow standard format: major[.minor[.patch[.build[release]]]]
  522. * Examples: 1.0 or 1.2.3beta or 1.2.3.4RC
  523. * @return {Ext.Version} this
  524. */
  525. constructor: function(version) {
  526. var parts, releaseStartIndex;
  527. if (version instanceof Version) {
  528. return version;
  529. }
  530. this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, '');
  531. releaseStartIndex = this.version.search(/([^\d\.])/);
  532. if (releaseStartIndex !== -1) {
  533. this.release = this.version.substr(releaseStartIndex, version.length);
  534. this.shortVersion = this.version.substr(0, releaseStartIndex);
  535. }
  536. this.shortVersion = this.shortVersion.replace(/[^\d]/g, '');
  537. parts = this.version.split('.');
  538. this.major = parseInt(parts.shift() || 0, 10);
  539. this.minor = parseInt(parts.shift() || 0, 10);
  540. this.patch = parseInt(parts.shift() || 0, 10);
  541. this.build = parseInt(parts.shift() || 0, 10);
  542. return this;
  543. },
  544. /**
  545. * Override the native toString method
  546. * @private
  547. * @return {String} version
  548. */
  549. toString: function() {
  550. return this.version;
  551. },
  552. /**
  553. * Override the native valueOf method
  554. * @private
  555. * @return {String} version
  556. */
  557. valueOf: function() {
  558. return this.version;
  559. },
  560. /**
  561. * Returns the major component value
  562. * @return {Number} major
  563. */
  564. getMajor: function() {
  565. return this.major || 0;
  566. },
  567. /**
  568. * Returns the minor component value
  569. * @return {Number} minor
  570. */
  571. getMinor: function() {
  572. return this.minor || 0;
  573. },
  574. /**
  575. * Returns the patch component value
  576. * @return {Number} patch
  577. */
  578. getPatch: function() {
  579. return this.patch || 0;
  580. },
  581. /**
  582. * Returns the build component value
  583. * @return {Number} build
  584. */
  585. getBuild: function() {
  586. return this.build || 0;
  587. },
  588. /**
  589. * Returns the release component value
  590. * @return {Number} release
  591. */
  592. getRelease: function() {
  593. return this.release || '';
  594. },
  595. /**
  596. * Returns whether this version if greater than the supplied argument
  597. * @param {String/Number} target The version to compare with
  598. * @return {Boolean} True if this version if greater than the target, false otherwise
  599. */
  600. isGreaterThan: function(target) {
  601. return Version.compare(this.version, target) === 1;
  602. },
  603. /**
  604. * Returns whether this version if smaller than the supplied argument
  605. * @param {String/Number} target The version to compare with
  606. * @return {Boolean} True if this version if smaller than the target, false otherwise
  607. */
  608. isLessThan: function(target) {
  609. return Version.compare(this.version, target) === -1;
  610. },
  611. /**
  612. * Returns whether this version equals to the supplied argument
  613. * @param {String/Number} target The version to compare with
  614. * @return {Boolean} True if this version equals to the target, false otherwise
  615. */
  616. equals: function(target) {
  617. return Version.compare(this.version, target) === 0;
  618. },
  619. /**
  620. * Returns whether this version matches the supplied argument. Example:
  621. * <pre><code>
  622. * var version = new Ext.Version('1.0.2beta');
  623. * console.log(version.match(1)); // True
  624. * console.log(version.match(1.0)); // True
  625. * console.log(version.match('1.0.2')); // True
  626. * console.log(version.match('1.0.2RC')); // False
  627. * </code></pre>
  628. * @param {String/Number} target The version to compare with
  629. * @return {Boolean} True if this version matches the target, false otherwise
  630. */
  631. match: function(target) {
  632. target = String(target);
  633. return this.version.substr(0, target.length) === target;
  634. },
  635. /**
  636. * Returns this format: [major, minor, patch, build, release]. Useful for comparison
  637. * @return {Number[]}
  638. */
  639. toArray: function() {
  640. return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()];
  641. },
  642. /**
  643. * Returns shortVersion version without dots and release
  644. * @return {String}
  645. */
  646. getShortVersion: function() {
  647. return this.shortVersion;
  648. }
  649. });
  650. Ext.apply(Version, {
  651. // @private
  652. releaseValueMap: {
  653. 'dev': -6,
  654. 'alpha': -5,
  655. 'a': -5,
  656. 'beta': -4,
  657. 'b': -4,
  658. 'rc': -3,
  659. '#': -2,
  660. 'p': -1,
  661. 'pl': -1
  662. },
  663. /**
  664. * Converts a version component to a comparable value
  665. *
  666. * @static
  667. * @param {Object} value The value to convert
  668. * @return {Object}
  669. */
  670. getComponentValue: function(value) {
  671. return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10));
  672. },
  673. /**
  674. * Compare 2 specified versions, starting from left to right. If a part contains special version strings,
  675. * they are handled in the following order:
  676. * 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else'
  677. *
  678. * @static
  679. * @param {String} current The current version to compare to
  680. * @param {String} target The target version to compare to
  681. * @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent
  682. */
  683. compare: function(current, target) {
  684. var currentValue, targetValue, i;
  685. current = new Version(current).toArray();
  686. target = new Version(target).toArray();
  687. for (i = 0; i < Math.max(current.length, target.length); i++) {
  688. currentValue = this.getComponentValue(current[i]);
  689. targetValue = this.getComponentValue(target[i]);
  690. if (currentValue < targetValue) {
  691. return -1;
  692. } else if (currentValue > targetValue) {
  693. return 1;
  694. }
  695. }
  696. return 0;
  697. }
  698. });
  699. Ext.apply(Ext, {
  700. /**
  701. * @private
  702. */
  703. versions: {},
  704. /**
  705. * @private
  706. */
  707. lastRegisteredVersion: null,
  708. /**
  709. * Set version number for the given package name.
  710. *
  711. * @param {String} packageName The package name, for example: 'core', 'touch', 'extjs'
  712. * @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev'
  713. * @return {Ext}
  714. */
  715. setVersion: function(packageName, version) {
  716. Ext.versions[packageName] = new Version(version);
  717. Ext.lastRegisteredVersion = Ext.versions[packageName];
  718. return this;
  719. },
  720. /**
  721. * Get the version number of the supplied package name; will return the last registered version
  722. * (last Ext.setVersion call) if there's no package name given.
  723. *
  724. * @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs'
  725. * @return {Ext.Version} The version
  726. */
  727. getVersion: function(packageName) {
  728. if (packageName === undefined) {
  729. return Ext.lastRegisteredVersion;
  730. }
  731. return Ext.versions[packageName];
  732. },
  733. /**
  734. * Create a closure for deprecated code.
  735. *
  736. // This means Ext.oldMethod is only supported in 4.0.0beta and older.
  737. // If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC',
  738. // the closure will not be invoked
  739. Ext.deprecate('extjs', '4.0.0beta', function() {
  740. Ext.oldMethod = Ext.newMethod;
  741. ...
  742. });
  743. * @param {String} packageName The package name
  744. * @param {String} since The last version before it's deprecated
  745. * @param {Function} closure The callback function to be executed with the specified version is less than the current version
  746. * @param {Object} scope The execution scope (<tt>this</tt>) if the closure
  747. * @markdown
  748. */
  749. deprecate: function(packageName, since, closure, scope) {
  750. if (Version.compare(Ext.getVersion(packageName), since) < 1) {
  751. closure.call(scope);
  752. }
  753. }
  754. }); // End Versioning
  755. Ext.setVersion('core', version);
  756. })();
  757. /**
  758. * @class Ext.String
  759. *
  760. * A collection of useful static methods to deal with strings
  761. * @singleton
  762. */
  763. Ext.String = {
  764. trimRegex: /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g,
  765. escapeRe: /('|\\)/g,
  766. formatRe: /\{(\d+)\}/g,
  767. escapeRegexRe: /([-.*+?^${}()|[\]\/\\])/g,
  768. /**
  769. * Convert certain characters (&, <, >, and ") to their HTML character equivalents for literal display in web pages.
  770. * @param {String} value The string to encode
  771. * @return {String} The encoded text
  772. * @method
  773. */
  774. htmlEncode: (function() {
  775. var entities = {
  776. '&': '&amp;',
  777. '>': '&gt;',
  778. '<': '&lt;',
  779. '"': '&quot;'
  780. }, keys = [], p, regex;
  781. for (p in entities) {
  782. keys.push(p);
  783. }
  784. regex = new RegExp('(' + keys.join('|') + ')', 'g');
  785. return function(value) {
  786. return (!value) ? value : String(value).replace(regex, function(match, capture) {
  787. return entities[capture];
  788. });
  789. };
  790. })(),
  791. /**
  792. * Convert certain characters (&, <, >, and ") from their HTML character equivalents.
  793. * @param {String} value The string to decode
  794. * @return {String} The decoded text
  795. * @method
  796. */
  797. htmlDecode: (function() {
  798. var entities = {
  799. '&amp;': '&',
  800. '&gt;': '>',
  801. '&lt;': '<',
  802. '&quot;': '"'
  803. }, keys = [], p, regex;
  804. for (p in entities) {
  805. keys.push(p);
  806. }
  807. regex = new RegExp('(' + keys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
  808. return function(value) {
  809. return (!value) ? value : String(value).replace(regex, function(match, capture) {
  810. if (capture in entities) {
  811. return entities[capture];
  812. } else {
  813. return String.fromCharCode(parseInt(capture.substr(2), 10));
  814. }
  815. });
  816. };
  817. })(),
  818. /**
  819. * Appends content to the query string of a URL, handling logic for whether to place
  820. * a question mark or ampersand.
  821. * @param {String} url The URL to append to.
  822. * @param {String} string The content to append to the URL.
  823. * @return (String) The resulting URL
  824. */
  825. urlAppend : function(url, string) {
  826. if (!Ext.isEmpty(string)) {
  827. return url + (url.indexOf('?') === -1 ? '?' : '&') + string;
  828. }
  829. return url;
  830. },
  831. /**
  832. * Trims whitespace from either end of a string, leaving spaces within the string intact. Example:
  833. * @example
  834. var s = ' foo bar ';
  835. alert('-' + s + '-'); //alerts "- foo bar -"
  836. alert('-' + Ext.String.trim(s) + '-'); //alerts "-foo bar-"
  837. * @param {String} string The string to escape
  838. * @return {String} The trimmed string
  839. */
  840. trim: function(string) {
  841. return string.replace(Ext.String.trimRegex, "");
  842. },
  843. /**
  844. * Capitalize the given string
  845. * @param {String} string
  846. * @return {String}
  847. */
  848. capitalize: function(string) {
  849. return string.charAt(0).toUpperCase() + string.substr(1);
  850. },
  851. /**
  852. * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
  853. * @param {String} value The string to truncate
  854. * @param {Number} length The maximum length to allow before truncating
  855. * @param {Boolean} word True to try to find a common word break
  856. * @return {String} The converted text
  857. */
  858. ellipsis: function(value, len, word) {
  859. if (value && value.length > len) {
  860. if (word) {
  861. var vs = value.substr(0, len - 2),
  862. index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
  863. if (index !== -1 && index >= (len - 15)) {
  864. return vs.substr(0, index) + "...";
  865. }
  866. }
  867. return value.substr(0, len - 3) + "...";
  868. }
  869. return value;
  870. },
  871. /**
  872. * Escapes the passed string for use in a regular expression
  873. * @param {String} string
  874. * @return {String}
  875. */
  876. escapeRegex: function(string) {
  877. return string.replace(Ext.String.escapeRegexRe, "\\$1");
  878. },
  879. /**
  880. * Escapes the passed string for ' and \
  881. * @param {String} string The string to escape
  882. * @return {String} The escaped string
  883. */
  884. escape: function(string) {
  885. return string.replace(Ext.String.escapeRe, "\\$1");
  886. },
  887. /**
  888. * Utility function that allows you to easily switch a string between two alternating values. The passed value
  889. * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
  890. * they are already different, the first value passed in is returned. Note that this method returns the new value
  891. * but does not change the current string.
  892. * <pre><code>
  893. // alternate sort directions
  894. sort = Ext.String.toggle(sort, 'ASC', 'DESC');
  895. // instead of conditional logic:
  896. sort = (sort == 'ASC' ? 'DESC' : 'ASC');
  897. </code></pre>
  898. * @param {String} string The current string
  899. * @param {String} value The value to compare to the current string
  900. * @param {String} other The new value to use if the string already equals the first value passed in
  901. * @return {String} The new value
  902. */
  903. toggle: function(string, value, other) {
  904. return string === value ? other : value;
  905. },
  906. /**
  907. * Pads the left side of a string with a specified character. This is especially useful
  908. * for normalizing number and date strings. Example usage:
  909. *
  910. * <pre><code>
  911. var s = Ext.String.leftPad('123', 5, '0');
  912. // s now contains the string: '00123'
  913. </code></pre>
  914. * @param {String} string The original string
  915. * @param {Number} size The total length of the output string
  916. * @param {String} character (optional) The character with which to pad the original string (defaults to empty string " ")
  917. * @return {String} The padded string
  918. */
  919. leftPad: function(string, size, character) {
  920. var result = String(string);
  921. character = character || " ";
  922. while (result.length < size) {
  923. result = character + result;
  924. }
  925. return result;
  926. },
  927. /**
  928. * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
  929. * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
  930. * <pre><code>
  931. var cls = 'my-class', text = 'Some text';
  932. var s = Ext.String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text);
  933. // s now contains the string: '&lt;div class="my-class">Some text&lt;/div>'
  934. </code></pre>
  935. * @param {String} string The tokenized string to be formatted
  936. * @param {String} value1 The value to replace token {0}
  937. * @param {String} value2 Etc...
  938. * @return {String} The formatted string
  939. */
  940. format: function(format) {
  941. var args = Ext.Array.toArray(arguments, 1);
  942. return format.replace(Ext.String.formatRe, function(m, i) {
  943. return args[i];
  944. });
  945. },
  946. /**
  947. * Returns a string with a specified number of repititions a given string pattern.
  948. * The pattern be separated by a different string.
  949. *
  950. * var s = Ext.String.repeat('---', 4); // = '------------'
  951. * var t = Ext.String.repeat('--', 3, '/'); // = '--/--/--'
  952. *
  953. * @param {String} pattern The pattern to repeat.
  954. * @param {Number} count The number of times to repeat the pattern (may be 0).
  955. * @param {String} sep An option string to separate each pattern.
  956. */
  957. repeat: function(pattern, count, sep) {
  958. for (var buf = [], i = count; i--; ) {
  959. buf.push(pattern);
  960. }
  961. return buf.join(sep || '');
  962. }
  963. };
  964. /**
  965. * @class Ext.Number
  966. *
  967. * A collection of useful static methods to deal with numbers
  968. * @singleton
  969. */
  970. (function() {
  971. var isToFixedBroken = (0.9).toFixed() !== '1';
  972. Ext.Number = {
  973. /**
  974. * Checks whether or not the passed number is within a desired range. If the number is already within the
  975. * range it is returned, otherwise the min or max value is returned depending on which side of the range is
  976. * exceeded. Note that this method returns the constrained value but does not change the current number.
  977. * @param {Number} number The number to check
  978. * @param {Number} min The minimum number in the range
  979. * @param {Number} max The maximum number in the range
  980. * @return {Number} The constrained value if outside the range, otherwise the current value
  981. */
  982. constrain: function(number, min, max) {
  983. number = parseFloat(number);
  984. if (!isNaN(min)) {
  985. number = Math.max(number, min);
  986. }
  987. if (!isNaN(max)) {
  988. number = Math.min(number, max);
  989. }
  990. return number;
  991. },
  992. /**
  993. * Snaps the passed number between stopping points based upon a passed increment value.
  994. * @param {Number} value The unsnapped value.
  995. * @param {Number} increment The increment by which the value must move.
  996. * @param {Number} minValue The minimum value to which the returned value must be constrained. Overrides the increment..
  997. * @param {Number} maxValue The maximum value to which the returned value must be constrained. Overrides the increment..
  998. * @return {Number} The value of the nearest snap target.
  999. */
  1000. snap : function(value, increment, minValue, maxValue) {
  1001. var newValue = value,
  1002. m;
  1003. if (!(increment && value)) {
  1004. return value;
  1005. }
  1006. m = value % increment;
  1007. if (m !== 0) {
  1008. newValue -= m;
  1009. if (m * 2 >= increment) {
  1010. newValue += increment;
  1011. } else if (m * 2 < -increment) {
  1012. newValue -= increment;
  1013. }
  1014. }
  1015. return Ext.Number.constrain(newValue, minValue, maxValue);
  1016. },
  1017. /**
  1018. * Formats a number using fixed-point notation
  1019. * @param {Number} value The number to format
  1020. * @param {Number} precision The number of digits to show after the decimal point
  1021. */
  1022. toFixed: function(value, precision) {
  1023. if (isToFixedBroken) {
  1024. precision = precision || 0;
  1025. var pow = Math.pow(10, precision);
  1026. return (Math.round(value * pow) / pow).toFixed(precision);
  1027. }
  1028. return value.toFixed(precision);
  1029. },
  1030. /**
  1031. * Validate that a value is numeric and convert it to a number if necessary. Returns the specified default value if
  1032. * it is not.
  1033. Ext.Number.from('1.23', 1); // returns 1.23
  1034. Ext.Number.from('abc', 1); // returns 1
  1035. * @param {Object} value
  1036. * @param {Number} defaultValue The value to return if the original value is non-numeric
  1037. * @return {Number} value, if numeric, defaultValue otherwise
  1038. */
  1039. from: function(value, defaultValue) {
  1040. if (isFinite(value)) {
  1041. value = parseFloat(value);
  1042. }
  1043. return !isNaN(value) ? value : defaultValue;
  1044. }
  1045. };
  1046. })();
  1047. /**
  1048. * @deprecated 4.0.0 Please use {@link Ext.Number#from} instead.
  1049. * @member Ext
  1050. * @method num
  1051. * @alias Ext.Number#from
  1052. */
  1053. Ext.num = function() {
  1054. return Ext.Number.from.apply(this, arguments);
  1055. };
  1056. /**
  1057. * @class Ext.Array
  1058. * @singleton
  1059. * @author Jacky Nguyen <jacky@sencha.com>
  1060. * @docauthor Jacky Nguyen <jacky@sencha.com>
  1061. *
  1062. * A set of useful static methods to deal with arrays; provide missing methods for older browsers.
  1063. */
  1064. (function() {
  1065. var arrayPrototype = Array.prototype,
  1066. slice = arrayPrototype.slice,
  1067. supportsSplice = function () {
  1068. var array = [],
  1069. lengthBefore,
  1070. j = 20;
  1071. if (!array.splice) {
  1072. return false;
  1073. }
  1074. // This detects a bug in IE8 splice method:
  1075. // see http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/6e946d03-e09f-4b22-a4dd-cd5e276bf05a/
  1076. while (j--) {
  1077. array.push("A");
  1078. }
  1079. array.splice(15, 0, "F", "F", "F", "F", "F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F");
  1080. lengthBefore = array.length; //41
  1081. array.splice(13, 0, "XXX"); // add one element
  1082. if (lengthBefore+1 != array.length) {
  1083. return false;
  1084. }
  1085. // end IE8 bug
  1086. return true;
  1087. }(),
  1088. supportsForEach = 'forEach' in arrayPrototype,
  1089. supportsMap = 'map' in arrayPrototype,
  1090. supportsIndexOf = 'indexOf' in arrayPrototype,
  1091. supportsEvery = 'every' in arrayPrototype,
  1092. supportsSome = 'some' in arrayPrototype,
  1093. supportsFilter = 'filter' in arrayPrototype,
  1094. supportsSort = function() {
  1095. var a = [1,2,3,4,5].sort(function(){ return 0; });
  1096. return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
  1097. }(),
  1098. supportsSliceOnNodeList = true,
  1099. ExtArray;
  1100. try {
  1101. // IE 6 - 8 will throw an error when using Array.prototype.slice on NodeList
  1102. if (typeof document !== 'undefined') {
  1103. slice.call(document.getElementsByTagName('body'));
  1104. }
  1105. } catch (e) {
  1106. supportsSliceOnNodeList = false;
  1107. }
  1108. function fixArrayIndex (array, index) {
  1109. return (index < 0) ? Math.max(0, array.length + index)
  1110. : Math.min(array.length, index);
  1111. }
  1112. /*
  1113. Does the same work as splice, but with a slightly more convenient signature. The splice
  1114. method has bugs in IE8, so this is the implementation we use on that platform.
  1115. The rippling of items in the array can be tricky. Consider two use cases:
  1116. index=2
  1117. removeCount=2
  1118. /=====\
  1119. +---+---+---+---+---+---+---+---+
  1120. | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  1121. +---+---+---+---+---+---+---+---+
  1122. / \/ \/ \/ \
  1123. / /\ /\ /\ \
  1124. / / \/ \/ \ +--------------------------+
  1125. / / /\ /\ +--------------------------+ \
  1126. / / / \/ +--------------------------+ \ \
  1127. / / / /+--------------------------+ \ \ \
  1128. / / / / \ \ \ \
  1129. v v v v v v v v
  1130. +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
  1131. | 0 | 1 | 4 | 5 | 6 | 7 | | 0 | 1 | a | b | c | 4 | 5 | 6 | 7 |
  1132. +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
  1133. A B \=========/
  1134. insert=[a,b,c]
  1135. In case A, it is obvious that copying of [4,5,6,7] must be left-to-right so
  1136. that we don't end up with [0,1,6,7,6,7]. In case B, we have the opposite; we
  1137. must go right-to-left or else we would end up with [0,1,a,b,c,4,4,4,4].
  1138. */
  1139. function replaceSim (array, index, removeCount, insert) {
  1140. var add = insert ? insert.length : 0,
  1141. length = array.length,
  1142. pos = fixArrayIndex(array, index);
  1143. // we try to use Array.push when we can for efficiency...
  1144. if (pos === length) {
  1145. if (add) {
  1146. array.push.apply(array, insert);
  1147. }
  1148. } else {
  1149. var remove = Math.min(removeCount, length - pos),
  1150. tailOldPos = pos + remove,
  1151. tailNewPos = tailOldPos + add - remove,
  1152. tailCount = length - tailOldPos,
  1153. lengthAfterRemove = length - remove,
  1154. i;
  1155. if (tailNewPos < tailOldPos) { // case A
  1156. for (i = 0; i < tailCount; ++i) {
  1157. array[tailNewPos+i] = array[tailOldPos+i];
  1158. }
  1159. } else if (tailNewPos > tailOldPos) { // case B
  1160. for (i = tailCount; i--; ) {
  1161. array[tailNewPos+i] = array[tailOldPos+i];
  1162. }
  1163. } // else, add == remove (nothing to do)
  1164. if (add && pos === lengthAfterRemove) {
  1165. array.length = lengthAfterRemove; // truncate array
  1166. array.push.apply(array, insert);
  1167. } else {
  1168. array.length = lengthAfterRemove + add; // reserves space
  1169. for (i = 0; i < add; ++i) {
  1170. array[pos+i] = insert[i];
  1171. }
  1172. }
  1173. }
  1174. return array;
  1175. }
  1176. function replaceNative (array, index, removeCount, insert) {
  1177. if (insert && insert.length) {
  1178. if (index < array.length) {
  1179. array.splice.apply(array, [index, removeCount].concat(insert));
  1180. } else {
  1181. array.push.apply(array, insert);
  1182. }
  1183. } else {
  1184. array.splice(index, removeCount);
  1185. }
  1186. return array;
  1187. }
  1188. function eraseSim (array, index, removeCount) {
  1189. return replaceSim(array, index, removeCount);
  1190. }
  1191. function eraseNative (array, index, removeCount) {
  1192. array.splice(index, removeCount);
  1193. return array;
  1194. }
  1195. function spliceSim (array, index, removeCount) {
  1196. var pos = fixArrayIndex(array, index),
  1197. removed = array.slice(index, fixArrayIndex(array, pos+removeCount));
  1198. if (arguments.length < 4) {
  1199. replaceSim(array, pos, removeCount);
  1200. } else {
  1201. replaceSim(array, pos, removeCount, slice.call(arguments, 3));
  1202. }
  1203. return removed;
  1204. }
  1205. function spliceNative (array) {
  1206. return array.splice.apply(array, slice.call(arguments, 1));
  1207. }
  1208. var erase = supportsSplice ? eraseNative : eraseSim,
  1209. replace = supportsSplice ? replaceNative : replaceSim,
  1210. splice = supportsSplice ? spliceNative : spliceSim;
  1211. // NOTE: from here on, use erase, replace or splice (not native methods)...
  1212. ExtArray = Ext.Array = {
  1213. /**
  1214. * Iterates an array or an iterable value and invoke the given callback function for each item.
  1215. *
  1216. * var countries = ['Vietnam', 'Singapore', 'United States', 'Russia'];
  1217. *
  1218. * Ext.Array.each(countries, function(name, index, countriesItSelf) {
  1219. * console.log(name);
  1220. * });
  1221. *
  1222. * var sum = function() {
  1223. * var sum = 0;
  1224. *
  1225. * Ext.Array.each(arguments, function(value) {
  1226. * sum += value;
  1227. * });
  1228. *
  1229. * return sum;
  1230. * };
  1231. *
  1232. * sum(1, 2, 3); // returns 6
  1233. *
  1234. * The iteration can be stopped by returning false in the function callback.
  1235. *
  1236. * Ext.Array.each(countries, function(name, index, countriesItSelf) {
  1237. * if (name === 'Singapore') {
  1238. * return false; // break here
  1239. * }
  1240. * });
  1241. *
  1242. * {@link Ext#each Ext.each} is alias for {@link Ext.Array#each Ext.Array.each}
  1243. *
  1244. * @param {Array/NodeList/Object} iterable The value to be iterated. If this
  1245. * argument is not iterable, the callback function is called once.
  1246. * @param {Function} fn The callback function. If it returns false, the iteration stops and this method returns
  1247. * the current `index`.
  1248. * @param {Object} fn.item The item at the current `index` in the passed `array`
  1249. * @param {Number} fn.index The current `index` within the `array`
  1250. * @param {Array} fn.allItems The `array` itself which was passed as the first argument
  1251. * @param {Boolean} fn.return Return false to stop iteration.
  1252. * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
  1253. * @param {Boolean} reverse (Optional) Reverse the iteration order (loop from the end to the beginning)
  1254. * Defaults false
  1255. * @return {Boolean} See description for the `fn` parameter.
  1256. */
  1257. each: function(array, fn, scope, reverse) {
  1258. array = ExtArray.from(array);
  1259. var i,
  1260. ln = array.length;
  1261. if (reverse !== true) {
  1262. for (i = 0; i < ln; i++) {
  1263. if (fn.call(scope || array[i], array[i], i, array) === false) {
  1264. return i;
  1265. }
  1266. }
  1267. }
  1268. else {
  1269. for (i = ln - 1; i > -1; i--) {
  1270. if (fn.call(scope || array[i], array[i], i, array) === false) {
  1271. return i;
  1272. }
  1273. }
  1274. }
  1275. return true;
  1276. },
  1277. /**
  1278. * Iterates an array and invoke the given callback function for each item. Note that this will simply
  1279. * delegate to the native Array.prototype.forEach method if supported. It doesn't support stopping the
  1280. * iteration by returning false in the callback function like {@link Ext.Array#each}. However, performance
  1281. * could be much better in modern browsers comparing with {@link Ext.Array#each}
  1282. *
  1283. * @param {Array} array The array to iterate
  1284. * @param {Function} fn The callback function.
  1285. * @param {Object} fn.item The item at the current `index` in the passed `array`
  1286. * @param {Number} fn.index The current `index` within the `array`
  1287. * @param {Array} fn.allItems The `array` itself which was passed as the first argument
  1288. * @param {Object} scope (Optional) The execution scope (`this`) in which the specified function is executed.
  1289. */
  1290. forEach: function(array, fn, scope) {
  1291. if (supportsForEach) {
  1292. return array.forEach(fn, scope);
  1293. }
  1294. var i = 0,
  1295. ln = array.length;
  1296. for (; i < ln; i++) {
  1297. fn.call(scope, array[i], i, array);
  1298. }
  1299. },
  1300. /**
  1301. * Get the index of the provided `item` in the given `array`, a supplement for the
  1302. * missing arrayPrototype.indexOf in Internet Explorer.
  1303. *
  1304. * @param {Array} array The array to check
  1305. * @param {Object} item The item to look for
  1306. * @param {Number} from (Optional) The index at which to begin the search
  1307. * @return {Number} The index of item in the array (or -1 if it is not found)
  1308. */
  1309. indexOf: function(array, item, from) {
  1310. if (supportsIndexOf) {
  1311. return array.indexOf(item, from);
  1312. }
  1313. var i, length = array.length;
  1314. for (i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++) {
  1315. if (array[i] === item) {
  1316. return i;
  1317. }
  1318. }
  1319. return -1;
  1320. },
  1321. /**
  1322. * Checks whether or not the given `array` contains the specified `item`
  1323. *
  1324. * @param {Array} array The array to check
  1325. * @param {Object} item The item to look for
  1326. * @return {Boolean} True if the array contains the item, false otherwise
  1327. */
  1328. contains: function(array, item) {
  1329. if (supportsIndexOf) {
  1330. return array.indexOf(item) !== -1;
  1331. }
  1332. var i, ln;
  1333. for (i = 0, ln = array.length; i < ln; i++) {
  1334. if (array[i] === item) {
  1335. return true;
  1336. }
  1337. }
  1338. return false;
  1339. },
  1340. /**
  1341. * Converts any iterable (numeric indices and a length property) into a true array.
  1342. *
  1343. * function test() {
  1344. * var args = Ext.Array.toArray(arguments),
  1345. * fromSecondToLastArgs = Ext.Array.toArray(arguments, 1);
  1346. *
  1347. * alert(args.join(' '));
  1348. * alert(fromSecondToLastArgs.join(' '));
  1349. * }
  1350. *
  1351. * test('just', 'testing', 'here'); // alerts 'just testing here';
  1352. * // alerts 'testing here';
  1353. *
  1354. * Ext.Array.toArray(document.getElementsByTagName('div')); // will convert the NodeList into an array
  1355. * Ext.Array.toArray('splitted'); // returns ['s', 'p', 'l', 'i', 't', 't', 'e', 'd']
  1356. * Ext.Array.toArray('splitted', 0, 3); // returns ['s', 'p', 'l', 'i']
  1357. *
  1358. * {@link Ext#toArray Ext.toArray} is alias for {@link Ext.Array#toArray Ext.Array.toArray}
  1359. *
  1360. * @param {Object} iterable the iterable object to be turned into a true Array.
  1361. * @param {Number} start (Optional) a zero-based index that specifies the start of extraction. Defaults to 0
  1362. * @param {Number} end (Optional) a zero-based index that specifies the end of extraction. Defaults to the last
  1363. * index of the iterable value
  1364. * @return {Array} array
  1365. */
  1366. toArray: function(iterable, start, end){
  1367. if (!iterable || !iterable.length) {
  1368. return [];
  1369. }
  1370. if (typeof iterable === 'string') {
  1371. iterable = iterable.split('');
  1372. }
  1373. if (supportsSliceOnNodeList) {
  1374. return slice.call(iterable, start || 0, end || iterable.length);
  1375. }
  1376. var array = [],
  1377. i;
  1378. start = start || 0;
  1379. end = end ? ((end < 0) ? iterable.length + end : end) : iterable.length;
  1380. for (i = start; i < end; i++) {
  1381. array.push(iterable[i]);
  1382. }
  1383. return array;
  1384. },
  1385. /**
  1386. * Plucks the value of a property from each item in the Array. Example:
  1387. *
  1388. * Ext.Array.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className]
  1389. *
  1390. * @param {Array/NodeList} array The Array of items to pluck the value from.
  1391. * @param {String} propertyName The property name to pluck from each element.
  1392. * @return {Array} The value from each item in the Array.
  1393. */
  1394. pluck: function(array, propertyName) {
  1395. var ret = [],
  1396. i, ln, item;
  1397. for (i = 0, ln = array.length; i < ln; i++) {
  1398. item = array[i];
  1399. ret.push(item[propertyName]);
  1400. }
  1401. return ret;
  1402. },
  1403. /**
  1404. * Creates a new array with the results of calling a provided function on every element in this array.
  1405. *
  1406. * @param {Array} array
  1407. * @param {Function} fn Callback function for each item
  1408. * @param {Object} scope Callback function scope
  1409. * @return {Array} results
  1410. */
  1411. map: function(array, fn, scope) {
  1412. if (supportsMap) {
  1413. return array.map(fn, scope);
  1414. }
  1415. var results = [],
  1416. i = 0,
  1417. len = array.length;
  1418. for (; i < len; i++) {
  1419. results[i] = fn.call(scope, array[i], i, array);
  1420. }
  1421. return results;
  1422. },
  1423. /**
  1424. * Executes the specified function for each array element until the function returns a falsy value.
  1425. * If such an item is found, the function will return false immediately.
  1426. * Otherwise, it will return true.
  1427. *
  1428. * @param {Array} array
  1429. * @param {Function} fn Callback function for each item
  1430. * @param {Object} scope Callback function scope
  1431. * @return {Boolean} True if no false value is returned by the callback function.
  1432. */
  1433. every: function(array, fn, scope) {
  1434. if (supportsEvery) {
  1435. return array.every(fn, scope);
  1436. }
  1437. var i = 0,
  1438. ln = array.length;
  1439. for (; i < ln; ++i) {
  1440. if (!fn.call(scope, array[i], i, array)) {
  1441. return false;
  1442. }
  1443. }
  1444. return true;
  1445. },
  1446. /**
  1447. * Executes the specified function for each array element until the function returns a truthy value.
  1448. * If such an item is found, the function will return true immediately. Otherwise, it will return false.
  1449. *
  1450. * @param {Array} array
  1451. * @param {Function} fn Callback function for each item
  1452. * @param {Object} scope Callback function scope
  1453. * @return {Boolean} True if the callback function returns a truthy value.
  1454. */
  1455. some: function(array, fn, scope) {
  1456. if (supportsSome) {
  1457. return array.some(fn, scope);
  1458. }
  1459. var i = 0,
  1460. ln = array.length;
  1461. for (; i < ln; ++i) {
  1462. if (fn.call(scope, array[i], i, array)) {
  1463. return true;
  1464. }
  1465. }
  1466. return false;
  1467. },
  1468. /**
  1469. * Filter through an array and remove empty item as defined in {@link Ext#isEmpty Ext.isEmpty}
  1470. *
  1471. * See {@link Ext.Array#filter}
  1472. *
  1473. * @param {Array} array
  1474. * @return {Array} results
  1475. */
  1476. clean: function(array) {
  1477. var results = [],
  1478. i = 0,
  1479. ln = array.length,
  1480. item;
  1481. for (; i < ln; i++) {
  1482. item = array[i];
  1483. if (!Ext.isEmpty(item)) {
  1484. results.push(item);
  1485. }
  1486. }
  1487. return results;
  1488. },
  1489. /**
  1490. * Returns a new array with unique items
  1491. *
  1492. * @param {Array} array
  1493. * @return {Array} results
  1494. */
  1495. unique: function(array) {
  1496. var clone = [],
  1497. i = 0,
  1498. ln = array.length,
  1499. item;
  1500. for (; i < ln; i++) {
  1501. item = array[i];
  1502. if (ExtArray.indexOf(clone, item) === -1) {
  1503. clone.push(item);
  1504. }
  1505. }
  1506. return clone;
  1507. },
  1508. /**
  1509. * Creates a new array with all of the elements of this array for which
  1510. * the provided filtering function returns true.
  1511. *
  1512. * @param {Array} array
  1513. * @param {Function} fn Callback function for each item
  1514. * @param {Object} scope Callback function scope
  1515. * @return {Array} results
  1516. */
  1517. filter: function(array, fn, scope) {
  1518. if (supportsFilter) {
  1519. return array.filter(fn, scope);
  1520. }
  1521. var results = [],
  1522. i = 0,
  1523. ln = array.length;
  1524. for (; i < ln; i++) {
  1525. if (fn.call(scope, array[i], i, array)) {
  1526. results.push(array[i]);
  1527. }
  1528. }
  1529. return results;
  1530. },
  1531. /**
  1532. * Converts a value to an array if it's not already an array; returns:
  1533. *
  1534. * - An empty array if given value is `undefined` or `null`
  1535. * - Itself if given value is already an array
  1536. * - An array copy if given value is {@link Ext#isIterable iterable} (arguments, NodeList and alike)
  1537. * - An array with one item which is the given value, otherwise
  1538. *
  1539. * @param {Object} value The value to convert to an array if it's not already is an array
  1540. * @param {Boolean} newReference (Optional) True to clone the given array and return a new reference if necessary,
  1541. * defaults to false
  1542. * @return {Array} array
  1543. */
  1544. from: function(value, newReference) {
  1545. if (value === undefined || value === null) {
  1546. return [];
  1547. }
  1548. if (Ext.isArray(value)) {
  1549. return (newReference) ? slice.call(value) : value;
  1550. }
  1551. if (value && value.length !== undefined && typeof value !== 'string') {
  1552. return Ext.toArray(value);
  1553. }
  1554. return [value];
  1555. },
  1556. /**
  1557. * Removes the specified item from the array if it exists
  1558. *
  1559. * @param {Array} array The array
  1560. * @param {Object} item The item to remove
  1561. * @return {Array} The passed array itself
  1562. */
  1563. remove: function(array, item) {
  1564. var index = ExtArray.indexOf(array, item);
  1565. if (index !== -1) {
  1566. erase(array, index, 1);
  1567. }
  1568. return array;
  1569. },
  1570. /**
  1571. * Push an item into the array only if the array doesn't contain it yet
  1572. *
  1573. * @param {Array} array The array
  1574. * @param {Object} item The item to include
  1575. */
  1576. include: function(array, item) {
  1577. if (!ExtArray.contains(array, item)) {
  1578. array.push(item);
  1579. }
  1580. },
  1581. /**
  1582. * Clone a flat array without referencing the previous one. Note that this is different
  1583. * from Ext.clone since it doesn't handle recursive cloning. It's simply a convenient, easy-to-remember method
  1584. * for Array.prototype.slice.call(array)
  1585. *
  1586. * @param {Array} array The array
  1587. * @return {Array} The clone array
  1588. */
  1589. clone: function(array) {
  1590. return slice.call(array);
  1591. },
  1592. /**
  1593. * Merge multiple arrays into one with unique items.
  1594. *
  1595. * {@link Ext.Array#union} is alias for {@link Ext.Array#merge}
  1596. *
  1597. * @param {Array} array1
  1598. * @param {Array} array2
  1599. * @param {Array} etc
  1600. * @return {Array} merged
  1601. */
  1602. merge: function() {
  1603. var args = slice.call(arguments),
  1604. array = [],
  1605. i, ln;
  1606. for (i = 0, ln = args.length; i < ln; i++) {
  1607. array = array.concat(args[i]);
  1608. }
  1609. return ExtArray.unique(array);
  1610. },
  1611. /**
  1612. * Merge multiple arrays into one with unique items that exist in all of the arrays.
  1613. *
  1614. * @param {Array} array1
  1615. * @param {Array} array2
  1616. * @param {Array} etc
  1617. * @return {Array} intersect
  1618. */
  1619. intersect: function() {
  1620. var intersect = [],
  1621. arrays = slice.call(arguments),
  1622. i, j, k, minArray, array, x, y, ln, arraysLn, arrayLn;
  1623. if (!arrays.length) {
  1624. return intersect;
  1625. }
  1626. // Find the smallest array
  1627. for (i = x = 0,ln = arrays.length; i < ln,array = arrays[i]; i++) {
  1628. if (!minArray || array.length < minArray.length) {
  1629. minArray = array;
  1630. x = i;
  1631. }
  1632. }
  1633. minArray = ExtArray.unique(minArray);
  1634. erase(arrays, x, 1);
  1635. // Use the smallest unique'd array as the anchor loop. If the other array(s) do contain
  1636. // an item in the small array, we're likely to find it before reaching the end
  1637. // of the inner loop and can terminate the search early.
  1638. for (i = 0,ln = minArray.length; i < ln,x = minArray[i]; i++) {
  1639. var count = 0;
  1640. for (j = 0,arraysLn = arrays.length; j < arraysLn,array = arrays[j]; j++) {
  1641. for (k = 0,arrayLn = array.length; k < arrayLn,y = array[k]; k++) {
  1642. if (x === y) {
  1643. count++;
  1644. break;
  1645. }
  1646. }
  1647. }
  1648. if (count === arraysLn) {
  1649. intersect.push(x);
  1650. }
  1651. }
  1652. return intersect;
  1653. },
  1654. /**
  1655. * Perform a set difference A-B by subtracting all items in array B from array A.
  1656. *
  1657. * @param {Array} arrayA
  1658. * @param {Array} arrayB
  1659. * @return {Array} difference
  1660. */
  1661. difference: function(arrayA, arrayB) {
  1662. var clone = slice.call(arrayA),
  1663. ln = clone.length,
  1664. i, j, lnB;
  1665. for (i = 0,lnB = arrayB.length; i < lnB; i++) {
  1666. for (j = 0; j < ln; j++) {
  1667. if (clone[j] === arrayB[i]) {
  1668. erase(clone, j, 1);
  1669. j--;
  1670. ln--;
  1671. }
  1672. }
  1673. }
  1674. return clone;
  1675. },
  1676. /**
  1677. * Returns a shallow copy of a part of an array. This is equivalent to the native
  1678. * call "Array.prototype.slice.call(array, begin, end)". This is often used when "array"
  1679. * is "arguments" since the arguments object does not supply a slice method but can
  1680. * be the context object to Array.prototype.slice.
  1681. *
  1682. * @param {Array} array The array (or arguments object).
  1683. * @param {Number} begin The index at which to begin. Negative values are offsets from
  1684. * the end of the array.
  1685. * @param {Number} end The index at which to end. The copied items do not include
  1686. * end. Negative values are offsets from the end of the array. If end is omitted,
  1687. * all items up to the end of the array are copied.
  1688. * @return {Array} The copied piece of the array.
  1689. */
  1690. // Note: IE6 will return [] on slice.call(x, undefined).
  1691. slice: ([1,2].slice(1, undefined).length ?
  1692. function (array, begin, end) {
  1693. return slice.call(array, begin, end);
  1694. } :
  1695. // at least IE6 uses arguments.length for variadic signature
  1696. function (array, begin, end) {
  1697. // After tested for IE 6, the one below is of the best performance
  1698. // see http://jsperf.com/slice-fix
  1699. if (typeof begin === 'undefined') {
  1700. return slice.call(array);
  1701. }
  1702. if (typeof end === 'undefined') {
  1703. return slice.call(array, begin);
  1704. }
  1705. return slice.call(array, begin, end);
  1706. }
  1707. ),
  1708. /**
  1709. * Sorts the elements of an Array.
  1710. * By default, this method sorts the elements alphabetically and ascending.
  1711. *
  1712. * @param {Array} array The array to sort.
  1713. * @param {Function} sortFn (optional) The comparison function.
  1714. * @return {Array} The sorted array.
  1715. */
  1716. sort: function(array, sortFn) {
  1717. if (supportsSort) {
  1718. if (sortFn) {
  1719. return array.sort(sortFn);
  1720. } else {
  1721. return array.sort();
  1722. }
  1723. }
  1724. var length = array.length,
  1725. i = 0,
  1726. comparison,
  1727. j, min, tmp;
  1728. for (; i < length; i++) {
  1729. min = i;
  1730. for (j = i + 1; j < length; j++) {
  1731. if (sortFn) {
  1732. comparison = sortFn(array[j], array[min]);
  1733. if (comparison < 0) {
  1734. min = j;
  1735. }
  1736. } else if (array[j] < array[min]) {
  1737. min = j;
  1738. }
  1739. }
  1740. if (min !== i) {
  1741. tmp = array[i];
  1742. array[i] = array[min];
  1743. array[min] = tmp;
  1744. }
  1745. }
  1746. return array;
  1747. },
  1748. /**
  1749. * Recursively flattens into 1-d Array. Injects Arrays inline.
  1750. *
  1751. * @param {Array} array The array to flatten
  1752. * @return {Array} The 1-d array.
  1753. */
  1754. flatten: function(array) {
  1755. var worker = [];
  1756. function rFlatten(a) {
  1757. var i, ln, v;
  1758. for (i = 0, ln = a.length; i < ln; i++) {
  1759. v = a[i];
  1760. if (Ext.isArray(v)) {
  1761. rFlatten(v);
  1762. } else {
  1763. worker.push(v);
  1764. }
  1765. }
  1766. return worker;
  1767. }
  1768. return rFlatten(array);
  1769. },
  1770. /**
  1771. * Returns the minimum value in the Array.
  1772. *
  1773. * @param {Array/NodeList} array The Array from which to select the minimum value.
  1774. * @param {Function} comparisonFn (optional) a function to perform the comparision which determines minimization.
  1775. * If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1
  1776. * @return {Object} minValue The minimum value
  1777. */
  1778. min: function(array, comparisonFn) {
  1779. var min = array[0],
  1780. i, ln, item;
  1781. for (i = 0, ln = array.length; i < ln; i++) {
  1782. item = array[i];
  1783. if (comparisonFn) {
  1784. if (comparisonFn(min, item) === 1) {
  1785. min = item;
  1786. }
  1787. }
  1788. else {
  1789. if (item < min) {
  1790. min = item;
  1791. }
  1792. }
  1793. }
  1794. return min;
  1795. },
  1796. /**
  1797. * Returns the maximum value in the Array.
  1798. *
  1799. * @param {Array/NodeList} array The Array from which to select the maximum value.
  1800. * @param {Function} comparisonFn (optional) a function to perform the comparision which determines maximization.
  1801. * If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1
  1802. * @return {Object} maxValue The maximum value
  1803. */
  1804. max: function(array, comparisonFn) {
  1805. var max = array[0],
  1806. i, ln, item;
  1807. for (i = 0, ln = array.length; i < ln; i++) {
  1808. item = array[i];
  1809. if (comparisonFn) {
  1810. if (comparisonFn(max, item) === -1) {
  1811. max = item;
  1812. }
  1813. }
  1814. else {
  1815. if (item > max) {
  1816. max = item;
  1817. }
  1818. }
  1819. }
  1820. return max;
  1821. },
  1822. /**
  1823. * Calculates the mean of all items in the array.
  1824. *
  1825. * @param {Array} array The Array to calculate the mean value of.
  1826. * @return {Number} The mean.
  1827. */
  1828. mean: function(array) {
  1829. return array.length > 0 ? ExtArray.sum(array) / array.length : undefined;
  1830. },
  1831. /**
  1832. * Calculates the sum of all items in the given array.
  1833. *
  1834. * @param {Array} array The Array to calculate the sum value of.
  1835. * @return {Number} The sum.
  1836. */
  1837. sum: function(array) {
  1838. var sum = 0,
  1839. i, ln, item;
  1840. for (i = 0,ln = array.length; i < ln; i++) {
  1841. item = array[i];
  1842. sum += item;
  1843. }
  1844. return sum;
  1845. },
  1846. /**
  1847. * Removes items from an array. This is functionally equivalent to the splice method
  1848. * of Array, but works around bugs in IE8's splice method and does not copy the
  1849. * removed elements in order to return them (because very often they are ignored).
  1850. *
  1851. * @param {Array} array The Array on which to replace.
  1852. * @param {Number} index The index in the array at which to operate.
  1853. * @param {Number} removeCount The number of items to remove at index.
  1854. * @return {Array} The array passed.
  1855. * @method
  1856. */
  1857. erase: erase,
  1858. /**
  1859. * Inserts items in to an array.
  1860. *
  1861. * @param {Array} array The Array on which to replace.
  1862. * @param {Number} index The index in the array at which to operate.
  1863. * @param {Array} items The array of items to insert at index.
  1864. * @return {Array} The array passed.
  1865. */
  1866. insert: function (array, index, items) {
  1867. return replace(array, index, 0, items);
  1868. },
  1869. /**
  1870. * Replaces items in an array. This is functionally equivalent to the splice method
  1871. * of Array, but works around bugs in IE8's splice method and is often more convenient
  1872. * to call because it accepts an array of items to insert rather than use a variadic
  1873. * argument list.
  1874. *
  1875. * @param {Array} array The Array on which to replace.
  1876. * @param {Number} index The index in the array at which to operate.
  1877. * @param {Number} removeCount The number of items to remove at index (can be 0).
  1878. * @param {Array} insert (optional) An array of items to insert at index.
  1879. * @return {Array} The array passed.
  1880. * @method
  1881. */
  1882. replace: replace,
  1883. /**
  1884. * Replaces items in an array. This is equivalent to the splice method of Array, but
  1885. * works around bugs in IE8's splice method. The signature is exactly the same as the
  1886. * splice method except that the array is the first argument. All arguments following
  1887. * removeCount are inserted in the array at index.
  1888. *
  1889. * @param {Array} array The Array on which to replace.
  1890. * @param {Number} index The index in the array at which to operate.
  1891. * @param {Number} removeCount The number of items to remove at index (can be 0).
  1892. * @return {Array} An array containing the removed items.
  1893. * @method
  1894. */
  1895. splice: splice
  1896. };
  1897. /**
  1898. * @method
  1899. * @member Ext
  1900. * @alias Ext.Array#each
  1901. */
  1902. Ext.each = ExtArray.each;
  1903. /**
  1904. * @method
  1905. * @member Ext.Array
  1906. * @alias Ext.Array#merge
  1907. */
  1908. ExtArray.union = ExtArray.merge;
  1909. /**
  1910. * Old alias to {@link Ext.Array#min}
  1911. * @deprecated 4.0.0 Use {@link Ext.Array#min} instead
  1912. * @method
  1913. * @member Ext
  1914. * @alias Ext.Array#min
  1915. */
  1916. Ext.min = ExtArray.min;
  1917. /**
  1918. * Old alias to {@link Ext.Array#max}
  1919. * @deprecated 4.0.0 Use {@link Ext.Array#max} instead
  1920. * @method
  1921. * @member Ext
  1922. * @alias Ext.Array#max
  1923. */
  1924. Ext.max = ExtArray.max;
  1925. /**
  1926. * Old alias to {@link Ext.Array#sum}
  1927. * @deprecated 4.0.0 Use {@link Ext.Array#sum} instead
  1928. * @method
  1929. * @member Ext
  1930. * @alias Ext.Array#sum
  1931. */
  1932. Ext.sum = ExtArray.sum;
  1933. /**
  1934. * Old alias to {@link Ext.Array#mean}
  1935. * @deprecated 4.0.0 Use {@link Ext.Array#mean} instead
  1936. * @method
  1937. * @member Ext
  1938. * @alias Ext.Array#mean
  1939. */
  1940. Ext.mean = ExtArray.mean;
  1941. /**
  1942. * Old alias to {@link Ext.Array#flatten}
  1943. * @deprecated 4.0.0 Use {@link Ext.Array#flatten} instead
  1944. * @method
  1945. * @member Ext
  1946. * @alias Ext.Array#flatten
  1947. */
  1948. Ext.flatten = ExtArray.flatten;
  1949. /**
  1950. * Old alias to {@link Ext.Array#clean}
  1951. * @deprecated 4.0.0 Use {@link Ext.Array#clean} instead
  1952. * @method
  1953. * @member Ext
  1954. * @alias Ext.Array#clean
  1955. */
  1956. Ext.clean = ExtArray.clean;
  1957. /**
  1958. * Old alias to {@link Ext.Array#unique}
  1959. * @deprecated 4.0.0 Use {@link Ext.Array#unique} instead
  1960. * @method
  1961. * @member Ext
  1962. * @alias Ext.Array#unique
  1963. */
  1964. Ext.unique = ExtArray.unique;
  1965. /**
  1966. * Old alias to {@link Ext.Array#pluck Ext.Array.pluck}
  1967. * @deprecated 4.0.0 Use {@link Ext.Array#pluck Ext.Array.pluck} instead
  1968. * @method
  1969. * @member Ext
  1970. * @alias Ext.Array#pluck
  1971. */
  1972. Ext.pluck = ExtArray.pluck;
  1973. /**
  1974. * @method
  1975. * @member Ext
  1976. * @alias Ext.Array#toArray
  1977. */
  1978. Ext.toArray = function() {
  1979. return ExtArray.toArray.apply(ExtArray, arguments);
  1980. };
  1981. })();
  1982. /**
  1983. * @class Ext.Function
  1984. *
  1985. * A collection of useful static methods to deal with function callbacks
  1986. * @singleton
  1987. */
  1988. Ext.Function = {
  1989. /**
  1990. * A very commonly used method throughout the framework. It acts as a wrapper around another method
  1991. * which originally accepts 2 arguments for `name` and `value`.
  1992. * The wrapped function then allows "flexible" value setting of either:
  1993. *
  1994. * - `name` and `value` as 2 arguments
  1995. * - one single object argument with multiple key - value pairs
  1996. *
  1997. * For example:
  1998. *
  1999. * var setValue = Ext.Function.flexSetter(function(name, value) {
  2000. * this[name] = value;
  2001. * });
  2002. *
  2003. * // Afterwards
  2004. * // Setting a single name - value
  2005. * setValue('name1', 'value1');
  2006. *
  2007. * // Settings multiple name - value pairs
  2008. * setValue({
  2009. * name1: 'value1',
  2010. * name2: 'value2',
  2011. * name3: 'value3'
  2012. * });
  2013. *
  2014. * @param {Function} setter
  2015. * @returns {Function} flexSetter
  2016. */
  2017. flexSetter: function(fn) {
  2018. return function(a, b) {
  2019. var k, i;
  2020. if (a === null) {
  2021. return this;
  2022. }
  2023. if (typeof a !== 'string') {
  2024. for (k in a) {
  2025. if (a.hasOwnProperty(k)) {
  2026. fn.call(this, k, a[k]);
  2027. }
  2028. }
  2029. if (Ext.enumerables) {
  2030. for (i = Ext.enumerables.length; i--;) {
  2031. k = Ext.enumerables[i];
  2032. if (a.hasOwnProperty(k)) {
  2033. fn.call(this, k, a[k]);
  2034. }
  2035. }
  2036. }
  2037. } else {
  2038. fn.call(this, a, b);
  2039. }
  2040. return this;
  2041. };
  2042. },
  2043. /**
  2044. * Create a new function from the provided `fn`, change `this` to the provided scope, optionally
  2045. * overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2046. *
  2047. * {@link Ext#bind Ext.bind} is alias for {@link Ext.Function#bind Ext.Function.bind}
  2048. *
  2049. * @param {Function} fn The function to delegate.
  2050. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2051. * **If omitted, defaults to the browser window.**
  2052. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2053. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2054. * if a number the args are inserted at the specified position
  2055. * @return {Function} The new function
  2056. */
  2057. bind: function(fn, scope, args, appendArgs) {
  2058. if (arguments.length === 2) {
  2059. return function() {
  2060. return fn.apply(scope, arguments);
  2061. }
  2062. }
  2063. var method = fn,
  2064. slice = Array.prototype.slice;
  2065. return function() {
  2066. var callArgs = args || arguments;
  2067. if (appendArgs === true) {
  2068. callArgs = slice.call(arguments, 0);
  2069. callArgs = callArgs.concat(args);
  2070. }
  2071. else if (typeof appendArgs == 'number') {
  2072. callArgs = slice.call(arguments, 0); // copy arguments first
  2073. Ext.Array.insert(callArgs, appendArgs, args);
  2074. }
  2075. return method.apply(scope || window, callArgs);
  2076. };
  2077. },
  2078. /**
  2079. * Create a new function from the provided `fn`, the arguments of which are pre-set to `args`.
  2080. * New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones.
  2081. * This is especially useful when creating callbacks.
  2082. *
  2083. * For example:
  2084. *
  2085. * var originalFunction = function(){
  2086. * alert(Ext.Array.from(arguments).join(' '));
  2087. * };
  2088. *
  2089. * var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']);
  2090. *
  2091. * callback(); // alerts 'Hello World'
  2092. * callback('by Me'); // alerts 'Hello World by Me'
  2093. *
  2094. * {@link Ext#pass Ext.pass} is alias for {@link Ext.Function#pass Ext.Function.pass}
  2095. *
  2096. * @param {Function} fn The original function
  2097. * @param {Array} args The arguments to pass to new callback
  2098. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2099. * @return {Function} The new callback function
  2100. */
  2101. pass: function(fn, args, scope) {
  2102. if (args) {
  2103. args = Ext.Array.from(args);
  2104. }
  2105. return function() {
  2106. return fn.apply(scope, args.concat(Ext.Array.toArray(arguments)));
  2107. };
  2108. },
  2109. /**
  2110. * Create an alias to the provided method property with name `methodName` of `object`.
  2111. * Note that the execution scope will still be bound to the provided `object` itself.
  2112. *
  2113. * @param {Object/Function} object
  2114. * @param {String} methodName
  2115. * @return {Function} aliasFn
  2116. */
  2117. alias: function(object, methodName) {
  2118. return function() {
  2119. return object[methodName].apply(object, arguments);
  2120. };
  2121. },
  2122. /**
  2123. * Creates an interceptor function. The passed function is called before the original one. If it returns false,
  2124. * the original one is not called. The resulting function returns the results of the original function.
  2125. * The passed function is called with the parameters of the original function. Example usage:
  2126. *
  2127. * var sayHi = function(name){
  2128. * alert('Hi, ' + name);
  2129. * }
  2130. *
  2131. * sayHi('Fred'); // alerts "Hi, Fred"
  2132. *
  2133. * // create a new function that validates input without
  2134. * // directly modifying the original function:
  2135. * var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){
  2136. * return name == 'Brian';
  2137. * });
  2138. *
  2139. * sayHiToFriend('Fred'); // no alert
  2140. * sayHiToFriend('Brian'); // alerts "Hi, Brian"
  2141. *
  2142. * @param {Function} origFn The original function.
  2143. * @param {Function} newFn The function to call before the original
  2144. * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
  2145. * **If omitted, defaults to the scope in which the original function is called or the browser window.**
  2146. * @param {Object} returnValue (optional) The value to return if the passed function return false (defaults to null).
  2147. * @return {Function} The new function
  2148. */
  2149. createInterceptor: function(origFn, newFn, scope, returnValue) {
  2150. var method = origFn;
  2151. if (!Ext.isFunction(newFn)) {
  2152. return origFn;
  2153. }
  2154. else {
  2155. return function() {
  2156. var me = this,
  2157. args = arguments;
  2158. newFn.target = me;
  2159. newFn.method = origFn;
  2160. return (newFn.apply(scope || me || window, args) !== false) ? origFn.apply(me || window, args) : returnValue || null;
  2161. };
  2162. }
  2163. },
  2164. /**
  2165. * Creates a delegate (callback) which, when called, executes after a specific delay.
  2166. *
  2167. * @param {Function} fn The function which will be called on a delay when the returned function is called.
  2168. * Optionally, a replacement (or additional) argument list may be specified.
  2169. * @param {Number} delay The number of milliseconds to defer execution by whenever called.
  2170. * @param {Object} scope (optional) The scope (`this` reference) used by the function at execution time.
  2171. * @param {Array} args (optional) Override arguments for the call. (Defaults to the arguments passed by the caller)
  2172. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2173. * if a number the args are inserted at the specified position.
  2174. * @return {Function} A function which, when called, executes the original function after the specified delay.
  2175. */
  2176. createDelayed: function(fn, delay, scope, args, appendArgs) {
  2177. if (scope || args) {
  2178. fn = Ext.Function.bind(fn, scope, args, appendArgs);
  2179. }
  2180. return function() {
  2181. var me = this;
  2182. setTimeout(function() {
  2183. fn.apply(me, arguments);
  2184. }, delay);
  2185. };
  2186. },
  2187. /**
  2188. * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
  2189. *
  2190. * var sayHi = function(name){
  2191. * alert('Hi, ' + name);
  2192. * }
  2193. *
  2194. * // executes immediately:
  2195. * sayHi('Fred');
  2196. *
  2197. * // executes after 2 seconds:
  2198. * Ext.Function.defer(sayHi, 2000, this, ['Fred']);
  2199. *
  2200. * // this syntax is sometimes useful for deferring
  2201. * // execution of an anonymous function:
  2202. * Ext.Function.defer(function(){
  2203. * alert('Anonymous');
  2204. * }, 100);
  2205. *
  2206. * {@link Ext#defer Ext.defer} is alias for {@link Ext.Function#defer Ext.Function.defer}
  2207. *
  2208. * @param {Function} fn The function to defer.
  2209. * @param {Number} millis The number of milliseconds for the setTimeout call
  2210. * (if less than or equal to 0 the function is executed immediately)
  2211. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2212. * **If omitted, defaults to the browser window.**
  2213. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2214. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2215. * if a number the args are inserted at the specified position
  2216. * @return {Number} The timeout id that can be used with clearTimeout
  2217. */
  2218. defer: function(fn, millis, obj, args, appendArgs) {
  2219. fn = Ext.Function.bind(fn, obj, args, appendArgs);
  2220. if (millis > 0) {
  2221. return setTimeout(fn, millis);
  2222. }
  2223. fn();
  2224. return 0;
  2225. },
  2226. /**
  2227. * Create a combined function call sequence of the original function + the passed function.
  2228. * The resulting function returns the results of the original function.
  2229. * The passed function is called with the parameters of the original function. Example usage:
  2230. *
  2231. * var sayHi = function(name){
  2232. * alert('Hi, ' + name);
  2233. * }
  2234. *
  2235. * sayHi('Fred'); // alerts "Hi, Fred"
  2236. *
  2237. * var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){
  2238. * alert('Bye, ' + name);
  2239. * });
  2240. *
  2241. * sayGoodbye('Fred'); // both alerts show
  2242. *
  2243. * @param {Function} origFn The original function.
  2244. * @param {Function} newFn The function to sequence
  2245. * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
  2246. * If omitted, defaults to the scope in which the original function is called or the browser window.
  2247. * @return {Function} The new function
  2248. */
  2249. createSequence: function(origFn, newFn, scope) {
  2250. if (!Ext.isFunction(newFn)) {
  2251. return origFn;
  2252. }
  2253. else {
  2254. return function() {
  2255. var retval = origFn.apply(this || window, arguments);
  2256. newFn.apply(scope || this || window, arguments);
  2257. return retval;
  2258. };
  2259. }
  2260. },
  2261. /**
  2262. * Creates a delegate function, optionally with a bound scope which, when called, buffers
  2263. * the execution of the passed function for the configured number of milliseconds.
  2264. * If called again within that period, the impending invocation will be canceled, and the
  2265. * timeout period will begin again.
  2266. *
  2267. * @param {Function} fn The function to invoke on a buffered timer.
  2268. * @param {Number} buffer The number of milliseconds by which to buffer the invocation of the
  2269. * function.
  2270. * @param {Object} scope (optional) The scope (`this` reference) in which
  2271. * the passed function is executed. If omitted, defaults to the scope specified by the caller.
  2272. * @param {Array} args (optional) Override arguments for the call. Defaults to the arguments
  2273. * passed by the caller.
  2274. * @return {Function} A function which invokes the passed function after buffering for the specified time.
  2275. */
  2276. createBuffered: function(fn, buffer, scope, args) {
  2277. return function(){
  2278. var timerId;
  2279. return function() {
  2280. var me = this;
  2281. if (timerId) {
  2282. clearTimeout(timerId);
  2283. timerId = null;
  2284. }
  2285. timerId = setTimeout(function(){
  2286. fn.apply(scope || me, args || arguments);
  2287. }, buffer);
  2288. };
  2289. }();
  2290. },
  2291. /**
  2292. * Creates a throttled version of the passed function which, when called repeatedly and
  2293. * rapidly, invokes the passed function only after a certain interval has elapsed since the
  2294. * previous invocation.
  2295. *
  2296. * This is useful for wrapping functions which may be called repeatedly, such as
  2297. * a handler of a mouse move event when the processing is expensive.
  2298. *
  2299. * @param {Function} fn The function to execute at a regular time interval.
  2300. * @param {Number} interval The interval **in milliseconds** on which the passed function is executed.
  2301. * @param {Object} scope (optional) The scope (`this` reference) in which
  2302. * the passed function is executed. If omitted, defaults to the scope specified by the caller.
  2303. * @returns {Function} A function which invokes the passed function at the specified interval.
  2304. */
  2305. createThrottled: function(fn, interval, scope) {
  2306. var lastCallTime, elapsed, lastArgs, timer, execute = function() {
  2307. fn.apply(scope || this, lastArgs);
  2308. lastCallTime = new Date().getTime();
  2309. };
  2310. return function() {
  2311. elapsed = new Date().getTime() - lastCallTime;
  2312. lastArgs = arguments;
  2313. clearTimeout(timer);
  2314. if (!lastCallTime || (elapsed >= interval)) {
  2315. execute();
  2316. } else {
  2317. timer = setTimeout(execute, interval - elapsed);
  2318. }
  2319. };
  2320. },
  2321. /**
  2322. * Adds behavior to an existing method that is executed before the
  2323. * original behavior of the function. For example:
  2324. *
  2325. * var soup = {
  2326. * contents: [],
  2327. * add: function(ingredient) {
  2328. * this.contents.push(ingredient);
  2329. * }
  2330. * };
  2331. * Ext.Function.interceptBefore(soup, "add", function(ingredient){
  2332. * if (!this.contents.length && ingredient !== "water") {
  2333. * // Always add water to start with
  2334. * this.contents.push("water");
  2335. * }
  2336. * });
  2337. * soup.add("onions");
  2338. * soup.add("salt");
  2339. * soup.contents; // will contain: water, onions, salt
  2340. *
  2341. * @param {Object} object The target object
  2342. * @param {String} methodName Name of the method to override
  2343. * @param {Function} fn Function with the new behavior. It will
  2344. * be called with the same arguments as the original method. The
  2345. * return value of this function will be the return value of the
  2346. * new method.
  2347. * @return {Function} The new function just created.
  2348. */
  2349. interceptBefore: function(object, methodName, fn) {
  2350. var method = object[methodName] || Ext.emptyFn;
  2351. return object[methodName] = function() {
  2352. var ret = fn.apply(this, arguments);
  2353. method.apply(this, arguments);
  2354. return ret;
  2355. };
  2356. },
  2357. /**
  2358. * Adds behavior to an existing method that is executed after the
  2359. * original behavior of the function. For example:
  2360. *
  2361. * var soup = {
  2362. * contents: [],
  2363. * add: function(ingredient) {
  2364. * this.contents.push(ingredient);
  2365. * }
  2366. * };
  2367. * Ext.Function.interceptAfter(soup, "add", function(ingredient){
  2368. * // Always add a bit of extra salt
  2369. * this.contents.push("salt");
  2370. * });
  2371. * soup.add("water");
  2372. * soup.add("onions");
  2373. * soup.contents; // will contain: water, salt, onions, salt
  2374. *
  2375. * @param {Object} object The target object
  2376. * @param {String} methodName Name of the method to override
  2377. * @param {Function} fn Function with the new behavior. It will
  2378. * be called with the same arguments as the original method. The
  2379. * return value of this function will be the return value of the
  2380. * new method.
  2381. * @return {Function} The new function just created.
  2382. */
  2383. interceptAfter: function(object, methodName, fn) {
  2384. var method = object[methodName] || Ext.emptyFn;
  2385. return object[methodName] = function() {
  2386. method.apply(this, arguments);
  2387. return fn.apply(this, arguments);
  2388. };
  2389. }
  2390. };
  2391. /**
  2392. * @method
  2393. * @member Ext
  2394. * @alias Ext.Function#defer
  2395. */
  2396. Ext.defer = Ext.Function.alias(Ext.Function, 'defer');
  2397. /**
  2398. * @method
  2399. * @member Ext
  2400. * @alias Ext.Function#pass
  2401. */
  2402. Ext.pass = Ext.Function.alias(Ext.Function, 'pass');
  2403. /**
  2404. * @method
  2405. * @member Ext
  2406. * @alias Ext.Function#bind
  2407. */
  2408. Ext.bind = Ext.Function.alias(Ext.Function, 'bind');
  2409. /**
  2410. * @author Jacky Nguyen <jacky@sencha.com>
  2411. * @docauthor Jacky Nguyen <jacky@sencha.com>
  2412. * @class Ext.Object
  2413. *
  2414. * A collection of useful static methods to deal with objects.
  2415. *
  2416. * @singleton
  2417. */
  2418. (function() {
  2419. var ExtObject = Ext.Object = {
  2420. /**
  2421. * Converts a `name` - `value` pair to an array of objects with support for nested structures. Useful to construct
  2422. * query strings. For example:
  2423. *
  2424. * var objects = Ext.Object.toQueryObjects('hobbies', ['reading', 'cooking', 'swimming']);
  2425. *
  2426. * // objects then equals:
  2427. * [
  2428. * { name: 'hobbies', value: 'reading' },
  2429. * { name: 'hobbies', value: 'cooking' },
  2430. * { name: 'hobbies', value: 'swimming' },
  2431. * ];
  2432. *
  2433. * var objects = Ext.Object.toQueryObjects('dateOfBirth', {
  2434. * day: 3,
  2435. * month: 8,
  2436. * year: 1987,
  2437. * extra: {
  2438. * hour: 4
  2439. * minute: 30
  2440. * }
  2441. * }, true); // Recursive
  2442. *
  2443. * // objects then equals:
  2444. * [
  2445. * { name: 'dateOfBirth[day]', value: 3 },
  2446. * { name: 'dateOfBirth[month]', value: 8 },
  2447. * { name: 'dateOfBirth[year]', value: 1987 },
  2448. * { name: 'dateOfBirth[extra][hour]', value: 4 },
  2449. * { name: 'dateOfBirth[extra][minute]', value: 30 },
  2450. * ];
  2451. *
  2452. * @param {String} name
  2453. * @param {Object/Array} value
  2454. * @param {Boolean} [recursive=false] True to traverse object recursively
  2455. * @return {Array}
  2456. */
  2457. toQueryObjects: function(name, value, recursive) {
  2458. var self = ExtObject.toQueryObjects,
  2459. objects = [],
  2460. i, ln;
  2461. if (Ext.isArray(value)) {
  2462. for (i = 0, ln = value.length; i < ln; i++) {
  2463. if (recursive) {
  2464. objects = objects.concat(self(name + '[' + i + ']', value[i], true));
  2465. }
  2466. else {
  2467. objects.push({
  2468. name: name,
  2469. value: value[i]
  2470. });
  2471. }
  2472. }
  2473. }
  2474. else if (Ext.isObject(value)) {
  2475. for (i in value) {
  2476. if (value.hasOwnProperty(i)) {
  2477. if (recursive) {
  2478. objects = objects.concat(self(name + '[' + i + ']', value[i], true));
  2479. }
  2480. else {
  2481. objects.push({
  2482. name: name,
  2483. value: value[i]
  2484. });
  2485. }
  2486. }
  2487. }
  2488. }
  2489. else {
  2490. objects.push({
  2491. name: name,
  2492. value: value
  2493. });
  2494. }
  2495. return objects;
  2496. },
  2497. /**
  2498. * Takes an object and converts it to an encoded query string.
  2499. *
  2500. * Non-recursive:
  2501. *
  2502. * Ext.Object.toQueryString({foo: 1, bar: 2}); // returns "foo=1&bar=2"
  2503. * Ext.Object.toQueryString({foo: null, bar: 2}); // returns "foo=&bar=2"
  2504. * Ext.Object.toQueryString({'some price': '$300'}); // returns "some%20price=%24300"
  2505. * Ext.Object.toQueryString({date: new Date(2011, 0, 1)}); // returns "date=%222011-01-01T00%3A00%3A00%22"
  2506. * Ext.Object.toQueryString({colors: ['red', 'green', 'blue']}); // returns "colors=red&colors=green&colors=blue"
  2507. *
  2508. * Recursive:
  2509. *
  2510. * Ext.Object.toQueryString({
  2511. * username: 'Jacky',
  2512. * dateOfBirth: {
  2513. * day: 1,
  2514. * month: 2,
  2515. * year: 1911
  2516. * },
  2517. * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
  2518. * }, true); // returns the following string (broken down and url-decoded for ease of reading purpose):
  2519. * // username=Jacky
  2520. * // &dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911
  2521. * // &hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff
  2522. *
  2523. * @param {Object} object The object to encode
  2524. * @param {Boolean} [recursive=false] Whether or not to interpret the object in recursive format.
  2525. * (PHP / Ruby on Rails servers and similar).
  2526. * @return {String} queryString
  2527. */
  2528. toQueryString: function(object, recursive) {
  2529. var paramObjects = [],
  2530. params = [],
  2531. i, j, ln, paramObject, value;
  2532. for (i in object) {
  2533. if (object.hasOwnProperty(i)) {
  2534. paramObjects = paramObjects.concat(ExtObject.toQueryObjects(i, object[i], recursive));
  2535. }
  2536. }
  2537. for (j = 0, ln = paramObjects.length; j < ln; j++) {
  2538. paramObject = paramObjects[j];
  2539. value = paramObject.value;
  2540. if (Ext.isEmpty(value)) {
  2541. value = '';
  2542. }
  2543. else if (Ext.isDate(value)) {
  2544. value = Ext.Date.toString(value);
  2545. }
  2546. params.push(encodeURIComponent(paramObject.name) + '=' + encodeURIComponent(String(value)));
  2547. }
  2548. return params.join('&');
  2549. },
  2550. /**
  2551. * Converts a query string back into an object.
  2552. *
  2553. * Non-recursive:
  2554. *
  2555. * Ext.Object.fromQueryString(foo=1&bar=2); // returns {foo: 1, bar: 2}
  2556. * Ext.Object.fromQueryString(foo=&bar=2); // returns {foo: null, bar: 2}
  2557. * Ext.Object.fromQueryString(some%20price=%24300); // returns {'some price': '$300'}
  2558. * Ext.Object.fromQueryString(colors=red&colors=green&colors=blue); // returns {colors: ['red', 'green', 'blue']}
  2559. *
  2560. * Recursive:
  2561. *
  2562. * Ext.Object.fromQueryString("username=Jacky&dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911&hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff", true);
  2563. * // returns
  2564. * {
  2565. * username: 'Jacky',
  2566. * dateOfBirth: {
  2567. * day: '1',
  2568. * month: '2',
  2569. * year: '1911'
  2570. * },
  2571. * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
  2572. * }
  2573. *
  2574. * @param {String} queryString The query string to decode
  2575. * @param {Boolean} [recursive=false] Whether or not to recursively decode the string. This format is supported by
  2576. * PHP / Ruby on Rails servers and similar.
  2577. * @return {Object}
  2578. */
  2579. fromQueryString: function(queryString, recursive) {
  2580. var parts = queryString.replace(/^\?/, '').split('&'),
  2581. object = {},
  2582. temp, components, name, value, i, ln,
  2583. part, j, subLn, matchedKeys, matchedName,
  2584. keys, key, nextKey;
  2585. for (i = 0, ln = parts.length; i < ln; i++) {
  2586. part = parts[i];
  2587. if (part.length > 0) {
  2588. components = part.split('=');
  2589. name = decodeURIComponent(components[0]);
  2590. value = (components[1] !== undefined) ? decodeURIComponent(components[1]) : '';
  2591. if (!recursive) {
  2592. if (object.hasOwnProperty(name)) {
  2593. if (!Ext.isArray(object[name])) {
  2594. object[name] = [object[name]];
  2595. }
  2596. object[name].push(value);
  2597. }
  2598. else {
  2599. object[name] = value;
  2600. }
  2601. }
  2602. else {
  2603. matchedKeys = name.match(/(\[):?([^\]]*)\]/g);
  2604. matchedName = name.match(/^([^\[]+)/);
  2605. name = matchedName[0];
  2606. keys = [];
  2607. if (matchedKeys === null) {
  2608. object[name] = value;
  2609. continue;
  2610. }
  2611. for (j = 0, subLn = matchedKeys.length; j < subLn; j++) {
  2612. key = matchedKeys[j];
  2613. key = (key.length === 2) ? '' : key.substring(1, key.length - 1);
  2614. keys.push(key);
  2615. }
  2616. keys.unshift(name);
  2617. temp = object;
  2618. for (j = 0, subLn = keys.length; j < subLn; j++) {
  2619. key = keys[j];
  2620. if (j === subLn - 1) {
  2621. if (Ext.isArray(temp) && key === '') {
  2622. temp.push(value);
  2623. }
  2624. else {
  2625. temp[key] = value;
  2626. }
  2627. }
  2628. else {
  2629. if (temp[key] === undefined || typeof temp[key] === 'string') {
  2630. nextKey = keys[j+1];
  2631. temp[key] = (Ext.isNumeric(nextKey) || nextKey === '') ? [] : {};
  2632. }
  2633. temp = temp[key];
  2634. }
  2635. }
  2636. }
  2637. }
  2638. }
  2639. return object;
  2640. },
  2641. /**
  2642. * Iterates through an object and invokes the given callback function for each iteration.
  2643. * The iteration can be stopped by returning `false` in the callback function. For example:
  2644. *
  2645. * var person = {
  2646. * name: 'Jacky'
  2647. * hairColor: 'black'
  2648. * loves: ['food', 'sleeping', 'wife']
  2649. * };
  2650. *
  2651. * Ext.Object.each(person, function(key, value, myself) {
  2652. * console.log(key + ":" + value);
  2653. *
  2654. * if (key === 'hairColor') {
  2655. * return false; // stop the iteration
  2656. * }
  2657. * });
  2658. *
  2659. * @param {Object} object The object to iterate
  2660. * @param {Function} fn The callback function.
  2661. * @param {String} fn.key
  2662. * @param {Object} fn.value
  2663. * @param {Object} fn.object The object itself
  2664. * @param {Object} [scope] The execution scope (`this`) of the callback function
  2665. */
  2666. each: function(object, fn, scope) {
  2667. for (var property in object) {
  2668. if (object.hasOwnProperty(property)) {
  2669. if (fn.call(scope || object, property, object[property], object) === false) {
  2670. return;
  2671. }
  2672. }
  2673. }
  2674. },
  2675. /**
  2676. * Merges any number of objects recursively without referencing them or their children.
  2677. *
  2678. * var extjs = {
  2679. * companyName: 'Ext JS',
  2680. * products: ['Ext JS', 'Ext GWT', 'Ext Designer'],
  2681. * isSuperCool: true
  2682. * office: {
  2683. * size: 2000,
  2684. * location: 'Palo Alto',
  2685. * isFun: true
  2686. * }
  2687. * };
  2688. *
  2689. * var newStuff = {
  2690. * companyName: 'Sencha Inc.',
  2691. * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
  2692. * office: {
  2693. * size: 40000,
  2694. * location: 'Redwood City'
  2695. * }
  2696. * };
  2697. *
  2698. * var sencha = Ext.Object.merge(extjs, newStuff);
  2699. *
  2700. * // extjs and sencha then equals to
  2701. * {
  2702. * companyName: 'Sencha Inc.',
  2703. * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
  2704. * isSuperCool: true
  2705. * office: {
  2706. * size: 30000,
  2707. * location: 'Redwood City'
  2708. * isFun: true
  2709. * }
  2710. * }
  2711. *
  2712. * @param {Object...} object Any number of objects to merge.
  2713. * @return {Object} merged The object that is created as a result of merging all the objects passed in.
  2714. */
  2715. merge: function(source, key, value) {
  2716. if (typeof key === 'string') {
  2717. if (value && value.constructor === Object) {
  2718. if (source[key] && source[key].constructor === Object) {
  2719. ExtObject.merge(source[key], value);
  2720. }
  2721. else {
  2722. source[key] = Ext.clone(value);
  2723. }
  2724. }
  2725. else {
  2726. source[key] = value;
  2727. }
  2728. return source;
  2729. }
  2730. var i = 1,
  2731. ln = arguments.length,
  2732. object, property;
  2733. for (; i < ln; i++) {
  2734. object = arguments[i];
  2735. for (property in object) {
  2736. if (object.hasOwnProperty(property)) {
  2737. ExtObject.merge(source, property, object[property]);
  2738. }
  2739. }
  2740. }
  2741. return source;
  2742. },
  2743. /**
  2744. * Returns the first matching key corresponding to the given value.
  2745. * If no matching value is found, null is returned.
  2746. *
  2747. * var person = {
  2748. * name: 'Jacky',
  2749. * loves: 'food'
  2750. * };
  2751. *
  2752. * alert(Ext.Object.getKey(person, 'food')); // alerts 'loves'
  2753. *
  2754. * @param {Object} object
  2755. * @param {Object} value The value to find
  2756. */
  2757. getKey: function(object, value) {
  2758. for (var property in object) {
  2759. if (object.hasOwnProperty(property) && object[property] === value) {
  2760. return property;
  2761. }
  2762. }
  2763. return null;
  2764. },
  2765. /**
  2766. * Gets all values of the given object as an array.
  2767. *
  2768. * var values = Ext.Object.getValues({
  2769. * name: 'Jacky',
  2770. * loves: 'food'
  2771. * }); // ['Jacky', 'food']
  2772. *
  2773. * @param {Object} object
  2774. * @return {Array} An array of values from the object
  2775. */
  2776. getValues: function(object) {
  2777. var values = [],
  2778. property;
  2779. for (property in object) {
  2780. if (object.hasOwnProperty(property)) {
  2781. values.push(object[property]);
  2782. }
  2783. }
  2784. return values;
  2785. },
  2786. /**
  2787. * Gets all keys of the given object as an array.
  2788. *
  2789. * var values = Ext.Object.getKeys({
  2790. * name: 'Jacky',
  2791. * loves: 'food'
  2792. * }); // ['name', 'loves']
  2793. *
  2794. * @param {Object} object
  2795. * @return {String[]} An array of keys from the object
  2796. * @method
  2797. */
  2798. getKeys: ('keys' in Object.prototype) ? Object.keys : function(object) {
  2799. var keys = [],
  2800. property;
  2801. for (property in object) {
  2802. if (object.hasOwnProperty(property)) {
  2803. keys.push(property);
  2804. }
  2805. }
  2806. return keys;
  2807. },
  2808. /**
  2809. * Gets the total number of this object's own properties
  2810. *
  2811. * var size = Ext.Object.getSize({
  2812. * name: 'Jacky',
  2813. * loves: 'food'
  2814. * }); // size equals 2
  2815. *
  2816. * @param {Object} object
  2817. * @return {Number} size
  2818. */
  2819. getSize: function(object) {
  2820. var size = 0,
  2821. property;
  2822. for (property in object) {
  2823. if (object.hasOwnProperty(property)) {
  2824. size++;
  2825. }
  2826. }
  2827. return size;
  2828. }
  2829. };
  2830. /**
  2831. * A convenient alias method for {@link Ext.Object#merge}.
  2832. *
  2833. * @member Ext
  2834. * @method merge
  2835. * @alias Ext.Object#merge
  2836. */
  2837. Ext.merge = Ext.Object.merge;
  2838. /**
  2839. * Alias for {@link Ext.Object#toQueryString}.
  2840. *
  2841. * @member Ext
  2842. * @method urlEncode
  2843. * @alias Ext.Object#toQueryString
  2844. * @deprecated 4.0.0 Use {@link Ext.Object#toQueryString} instead
  2845. */
  2846. Ext.urlEncode = function() {
  2847. var args = Ext.Array.from(arguments),
  2848. prefix = '';
  2849. // Support for the old `pre` argument
  2850. if ((typeof args[1] === 'string')) {
  2851. prefix = args[1] + '&';
  2852. args[1] = false;
  2853. }
  2854. return prefix + Ext.Object.toQueryString.apply(Ext.Object, args);
  2855. };
  2856. /**
  2857. * Alias for {@link Ext.Object#fromQueryString}.
  2858. *
  2859. * @member Ext
  2860. * @method urlDecode
  2861. * @alias Ext.Object#fromQueryString
  2862. * @deprecated 4.0.0 Use {@link Ext.Object#fromQueryString} instead
  2863. */
  2864. Ext.urlDecode = function() {
  2865. return Ext.Object.fromQueryString.apply(Ext.Object, arguments);
  2866. };
  2867. })();
  2868. /**
  2869. * @class Ext.Date
  2870. * A set of useful static methods to deal with date
  2871. * Note that if Ext.Date is required and loaded, it will copy all methods / properties to
  2872. * this object for convenience
  2873. *
  2874. * The date parsing and formatting syntax contains a subset of
  2875. * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
  2876. * supported will provide results equivalent to their PHP versions.
  2877. *
  2878. * The following is a list of all currently supported formats:
  2879. * <pre class="">
  2880. Format Description Example returned values
  2881. ------ ----------------------------------------------------------------------- -----------------------
  2882. d Day of the month, 2 digits with leading zeros 01 to 31
  2883. D A short textual representation of the day of the week Mon to Sun
  2884. j Day of the month without leading zeros 1 to 31
  2885. l A full textual representation of the day of the week Sunday to Saturday
  2886. N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
  2887. S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
  2888. w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday)
  2889. z The day of the year (starting from 0) 0 to 364 (365 in leap years)
  2890. W ISO-8601 week number of year, weeks starting on Monday 01 to 53
  2891. F A full textual representation of a month, such as January or March January to December
  2892. m Numeric representation of a month, with leading zeros 01 to 12
  2893. M A short textual representation of a month Jan to Dec
  2894. n Numeric representation of a month, without leading zeros 1 to 12
  2895. t Number of days in the given month 28 to 31
  2896. L Whether it&#39;s a leap year 1 if it is a leap year, 0 otherwise.
  2897. o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004
  2898. belongs to the previous or next year, that year is used instead)
  2899. Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
  2900. y A two digit representation of a year Examples: 99 or 03
  2901. a Lowercase Ante meridiem and Post meridiem am or pm
  2902. A Uppercase Ante meridiem and Post meridiem AM or PM
  2903. g 12-hour format of an hour without leading zeros 1 to 12
  2904. G 24-hour format of an hour without leading zeros 0 to 23
  2905. h 12-hour format of an hour with leading zeros 01 to 12
  2906. H 24-hour format of an hour with leading zeros 00 to 23
  2907. i Minutes, with leading zeros 00 to 59
  2908. s Seconds, with leading zeros 00 to 59
  2909. u Decimal fraction of a second Examples:
  2910. (minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or
  2911. 100 (i.e. 0.100s) or
  2912. 999 (i.e. 0.999s) or
  2913. 999876543210 (i.e. 0.999876543210s)
  2914. O Difference to Greenwich time (GMT) in hours and minutes Example: +1030
  2915. P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00
  2916. T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ...
  2917. Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400
  2918. c ISO 8601 date
  2919. Notes: Examples:
  2920. 1) If unspecified, the month / day defaults to the current month / day, 1991 or
  2921. the time defaults to midnight, while the timezone defaults to the 1992-10 or
  2922. browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
  2923. and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or
  2924. are optional. 1995-07-18T17:21:28-02:00 or
  2925. 2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or
  2926. least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or
  2927. of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or
  2928. Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or
  2929. date-time granularity which are supported, or see 2000-02-13T21:25:33
  2930. http://www.w3.org/TR/NOTE-datetime for more info. 2001-01-12 22:26:34
  2931. U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463
  2932. MS Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
  2933. \/Date(1238606590509+0800)\/
  2934. </pre>
  2935. *
  2936. * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
  2937. * <pre><code>
  2938. // Sample date:
  2939. // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
  2940. var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
  2941. console.log(Ext.Date.format(dt, 'Y-m-d')); // 2007-01-10
  2942. console.log(Ext.Date.format(dt, 'F j, Y, g:i a')); // January 10, 2007, 3:05 pm
  2943. console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
  2944. </code></pre>
  2945. *
  2946. * Here are some standard date/time patterns that you might find helpful. They
  2947. * are not part of the source of Ext.Date, but to use them you can simply copy this
  2948. * block of code into any script that is included after Ext.Date and they will also become
  2949. * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
  2950. * <pre><code>
  2951. Ext.Date.patterns = {
  2952. ISO8601Long:"Y-m-d H:i:s",
  2953. ISO8601Short:"Y-m-d",
  2954. ShortDate: "n/j/Y",
  2955. LongDate: "l, F d, Y",
  2956. FullDateTime: "l, F d, Y g:i:s A",
  2957. MonthDay: "F d",
  2958. ShortTime: "g:i A",
  2959. LongTime: "g:i:s A",
  2960. SortableDateTime: "Y-m-d\\TH:i:s",
  2961. UniversalSortableDateTime: "Y-m-d H:i:sO",
  2962. YearMonth: "F, Y"
  2963. };
  2964. </code></pre>
  2965. *
  2966. * Example usage:
  2967. * <pre><code>
  2968. var dt = new Date();
  2969. console.log(Ext.Date.format(dt, Ext.Date.patterns.ShortDate));
  2970. </code></pre>
  2971. * <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
  2972. * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
  2973. * @singleton
  2974. */
  2975. /*
  2976. * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
  2977. * (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)
  2978. * They generate precompiled functions from format patterns instead of parsing and
  2979. * processing each pattern every time a date is formatted. These functions are available
  2980. * on every Date object.
  2981. */
  2982. (function() {
  2983. // create private copy of Ext's Ext.util.Format.format() method
  2984. // - to remove unnecessary dependency
  2985. // - to resolve namespace conflict with MS-Ajax's implementation
  2986. function xf(format) {
  2987. var args = Array.prototype.slice.call(arguments, 1);
  2988. return format.replace(/\{(\d+)\}/g, function(m, i) {
  2989. return args[i];
  2990. });
  2991. }
  2992. Ext.Date = {
  2993. /**
  2994. * Returns the current timestamp
  2995. * @return {Date} The current timestamp
  2996. * @method
  2997. */
  2998. now: Date.now || function() {
  2999. return +new Date();
  3000. },
  3001. /**
  3002. * @private
  3003. * Private for now
  3004. */
  3005. toString: function(date) {
  3006. var pad = Ext.String.leftPad;
  3007. return date.getFullYear() + "-"
  3008. + pad(date.getMonth() + 1, 2, '0') + "-"
  3009. + pad(date.getDate(), 2, '0') + "T"
  3010. + pad(date.getHours(), 2, '0') + ":"
  3011. + pad(date.getMinutes(), 2, '0') + ":"
  3012. + pad(date.getSeconds(), 2, '0');
  3013. },
  3014. /**
  3015. * Returns the number of milliseconds between two dates
  3016. * @param {Date} dateA The first date
  3017. * @param {Date} dateB (optional) The second date, defaults to now
  3018. * @return {Number} The difference in milliseconds
  3019. */
  3020. getElapsed: function(dateA, dateB) {
  3021. return Math.abs(dateA - (dateB || new Date()));
  3022. },
  3023. /**
  3024. * Global flag which determines if strict date parsing should be used.
  3025. * Strict date parsing will not roll-over invalid dates, which is the
  3026. * default behaviour of javascript Date objects.
  3027. * (see {@link #parse} for more information)
  3028. * Defaults to <tt>false</tt>.
  3029. * @type Boolean
  3030. */
  3031. useStrict: false,
  3032. // private
  3033. formatCodeToRegex: function(character, currentGroup) {
  3034. // Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below)
  3035. var p = utilDate.parseCodes[character];
  3036. if (p) {
  3037. p = typeof p == 'function'? p() : p;
  3038. utilDate.parseCodes[character] = p; // reassign function result to prevent repeated execution
  3039. }
  3040. return p ? Ext.applyIf({
  3041. c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
  3042. }, p) : {
  3043. g: 0,
  3044. c: null,
  3045. s: Ext.String.escapeRegex(character) // treat unrecognised characters as literals
  3046. };
  3047. },
  3048. /**
  3049. * <p>An object hash in which each property is a date parsing function. The property name is the
  3050. * format string which that function parses.</p>
  3051. * <p>This object is automatically populated with date parsing functions as
  3052. * date formats are requested for Ext standard formatting strings.</p>
  3053. * <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
  3054. * may be used as a format string to {@link #parse}.<p>
  3055. * <p>Example:</p><pre><code>
  3056. Ext.Date.parseFunctions['x-date-format'] = myDateParser;
  3057. </code></pre>
  3058. * <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
  3059. * <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
  3060. * <li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
  3061. * (i.e. prevent javascript Date "rollover") (The default must be false).
  3062. * Invalid date strings should return null when parsed.</div></li>
  3063. * </ul></div></p>
  3064. * <p>To enable Dates to also be <i>formatted</i> according to that format, a corresponding
  3065. * formatting function must be placed into the {@link #formatFunctions} property.
  3066. * @property parseFunctions
  3067. * @type Object
  3068. */
  3069. parseFunctions: {
  3070. "MS": function(input, strict) {
  3071. // note: the timezone offset is ignored since the MS Ajax server sends
  3072. // a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
  3073. var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/');
  3074. var r = (input || '').match(re);
  3075. return r? new Date(((r[1] || '') + r[2]) * 1) : null;
  3076. }
  3077. },
  3078. parseRegexes: [],
  3079. /**
  3080. * <p>An object hash in which each property is a date formatting function. The property name is the
  3081. * format string which corresponds to the produced formatted date string.</p>
  3082. * <p>This object is automatically populated with date formatting functions as
  3083. * date formats are requested for Ext standard formatting strings.</p>
  3084. * <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
  3085. * may be used as a format string to {@link #format}. Example:</p><pre><code>
  3086. Ext.Date.formatFunctions['x-date-format'] = myDateFormatter;
  3087. </code></pre>
  3088. * <p>A formatting function should return a string representation of the passed Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
  3089. * <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
  3090. * </ul></div></p>
  3091. * <p>To enable date strings to also be <i>parsed</i> according to that format, a corresponding
  3092. * parsing function must be placed into the {@link #parseFunctions} property.
  3093. * @property formatFunctions
  3094. * @type Object
  3095. */
  3096. formatFunctions: {
  3097. "MS": function() {
  3098. // UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF))
  3099. return '\\/Date(' + this.getTime() + ')\\/';
  3100. }
  3101. },
  3102. y2kYear : 50,
  3103. /**
  3104. * Date interval constant
  3105. * @type String
  3106. */
  3107. MILLI : "ms",
  3108. /**
  3109. * Date interval constant
  3110. * @type String
  3111. */
  3112. SECOND : "s",
  3113. /**
  3114. * Date interval constant
  3115. * @type String
  3116. */
  3117. MINUTE : "mi",
  3118. /** Date interval constant
  3119. * @type String
  3120. */
  3121. HOUR : "h",
  3122. /**
  3123. * Date interval constant
  3124. * @type String
  3125. */
  3126. DAY : "d",
  3127. /**
  3128. * Date interval constant
  3129. * @type String
  3130. */
  3131. MONTH : "mo",
  3132. /**
  3133. * Date interval constant
  3134. * @type String
  3135. */
  3136. YEAR : "y",
  3137. /**
  3138. * <p>An object hash containing default date values used during date parsing.</p>
  3139. * <p>The following properties are available:<div class="mdetail-params"><ul>
  3140. * <li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
  3141. * <li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
  3142. * <li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
  3143. * <li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
  3144. * <li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
  3145. * <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
  3146. * <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
  3147. * </ul></div></p>
  3148. * <p>Override these properties to customize the default date values used by the {@link #parse} method.</p>
  3149. * <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt>
  3150. * and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect.
  3151. * It is the responsiblity of the developer to account for this.</b></p>
  3152. * Example Usage:
  3153. * <pre><code>
  3154. // set default day value to the first day of the month
  3155. Ext.Date.defaults.d = 1;
  3156. // parse a February date string containing only year and month values.
  3157. // setting the default day value to 1 prevents weird date rollover issues
  3158. // when attempting to parse the following date string on, for example, March 31st 2009.
  3159. Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
  3160. </code></pre>
  3161. * @property defaults
  3162. * @type Object
  3163. */
  3164. defaults: {},
  3165. /**
  3166. * @property {String[]} dayNames
  3167. * An array of textual day names.
  3168. * Override these values for international dates.
  3169. * Example:
  3170. * <pre><code>
  3171. Ext.Date.dayNames = [
  3172. 'SundayInYourLang',
  3173. 'MondayInYourLang',
  3174. ...
  3175. ];
  3176. </code></pre>
  3177. */
  3178. dayNames : [
  3179. "Sunday",
  3180. "Monday",
  3181. "Tuesday",
  3182. "Wednesday",
  3183. "Thursday",
  3184. "Friday",
  3185. "Saturday"
  3186. ],
  3187. /**
  3188. * @property {String[]} monthNames
  3189. * An array of textual month names.
  3190. * Override these values for international dates.
  3191. * Example:
  3192. * <pre><code>
  3193. Ext.Date.monthNames = [
  3194. 'JanInYourLang',
  3195. 'FebInYourLang',
  3196. ...
  3197. ];
  3198. </code></pre>
  3199. */
  3200. monthNames : [
  3201. "January",
  3202. "February",
  3203. "March",
  3204. "April",
  3205. "May",
  3206. "June",
  3207. "July",
  3208. "August",
  3209. "September",
  3210. "October",
  3211. "November",
  3212. "December"
  3213. ],
  3214. /**
  3215. * @property {Object} monthNumbers
  3216. * An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).
  3217. * Override these values for international dates.
  3218. * Example:
  3219. * <pre><code>
  3220. Ext.Date.monthNumbers = {
  3221. 'ShortJanNameInYourLang':0,
  3222. 'ShortFebNameInYourLang':1,
  3223. ...
  3224. };
  3225. </code></pre>
  3226. */
  3227. monthNumbers : {
  3228. Jan:0,
  3229. Feb:1,
  3230. Mar:2,
  3231. Apr:3,
  3232. May:4,
  3233. Jun:5,
  3234. Jul:6,
  3235. Aug:7,
  3236. Sep:8,
  3237. Oct:9,
  3238. Nov:10,
  3239. Dec:11
  3240. },
  3241. /**
  3242. * @property {String} defaultFormat
  3243. * <p>The date format string that the {@link Ext.util.Format#dateRenderer}
  3244. * and {@link Ext.util.Format#date} functions use. See {@link Ext.Date} for details.</p>
  3245. * <p>This may be overridden in a locale file.</p>
  3246. */
  3247. defaultFormat : "m/d/Y",
  3248. /**
  3249. * Get the short month name for the given month number.
  3250. * Override this function for international dates.
  3251. * @param {Number} month A zero-based javascript month number.
  3252. * @return {String} The short month name.
  3253. */
  3254. getShortMonthName : function(month) {
  3255. return utilDate.monthNames[month].substring(0, 3);
  3256. },
  3257. /**
  3258. * Get the short day name for the given day number.
  3259. * Override this function for international dates.
  3260. * @param {Number} day A zero-based javascript day number.
  3261. * @return {String} The short day name.
  3262. */
  3263. getShortDayName : function(day) {
  3264. return utilDate.dayNames[day].substring(0, 3);
  3265. },
  3266. /**
  3267. * Get the zero-based javascript month number for the given short/full month name.
  3268. * Override this function for international dates.
  3269. * @param {String} name The short/full month name.
  3270. * @return {Number} The zero-based javascript month number.
  3271. */
  3272. getMonthNumber : function(name) {
  3273. // handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive)
  3274. return utilDate.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
  3275. },
  3276. /**
  3277. * Checks if the specified format contains hour information
  3278. * @param {String} format The format to check
  3279. * @return {Boolean} True if the format contains hour information
  3280. * @method
  3281. */
  3282. formatContainsHourInfo : (function(){
  3283. var stripEscapeRe = /(\\.)/g,
  3284. hourInfoRe = /([gGhHisucUOPZ]|MS)/;
  3285. return function(format){
  3286. return hourInfoRe.test(format.replace(stripEscapeRe, ''));
  3287. };
  3288. })(),
  3289. /**
  3290. * Checks if the specified format contains information about
  3291. * anything other than the time.
  3292. * @param {String} format The format to check
  3293. * @return {Boolean} True if the format contains information about
  3294. * date/day information.
  3295. * @method
  3296. */
  3297. formatContainsDateInfo : (function(){
  3298. var stripEscapeRe = /(\\.)/g,
  3299. dateInfoRe = /([djzmnYycU]|MS)/;
  3300. return function(format){
  3301. return dateInfoRe.test(format.replace(stripEscapeRe, ''));
  3302. };
  3303. })(),
  3304. /**
  3305. * The base format-code to formatting-function hashmap used by the {@link #format} method.
  3306. * Formatting functions are strings (or functions which return strings) which
  3307. * will return the appropriate value when evaluated in the context of the Date object
  3308. * from which the {@link #format} method is called.
  3309. * Add to / override these mappings for custom date formatting.
  3310. * Note: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found.
  3311. * Example:
  3312. * <pre><code>
  3313. Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
  3314. console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
  3315. </code></pre>
  3316. * @type Object
  3317. */
  3318. formatCodes : {
  3319. d: "Ext.String.leftPad(this.getDate(), 2, '0')",
  3320. D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name
  3321. j: "this.getDate()",
  3322. l: "Ext.Date.dayNames[this.getDay()]",
  3323. N: "(this.getDay() ? this.getDay() : 7)",
  3324. S: "Ext.Date.getSuffix(this)",
  3325. w: "this.getDay()",
  3326. z: "Ext.Date.getDayOfYear(this)",
  3327. W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')",
  3328. F: "Ext.Date.monthNames[this.getMonth()]",
  3329. m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')",
  3330. M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name
  3331. n: "(this.getMonth() + 1)",
  3332. t: "Ext.Date.getDaysInMonth(this)",
  3333. L: "(Ext.Date.isLeapYear(this) ? 1 : 0)",
  3334. o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))",
  3335. Y: "Ext.String.leftPad(this.getFullYear(), 4, '0')",
  3336. y: "('' + this.getFullYear()).substring(2, 4)",
  3337. a: "(this.getHours() < 12 ? 'am' : 'pm')",
  3338. A: "(this.getHours() < 12 ? 'AM' : 'PM')",
  3339. g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
  3340. G: "this.getHours()",
  3341. h: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
  3342. H: "Ext.String.leftPad(this.getHours(), 2, '0')",
  3343. i: "Ext.String.leftPad(this.getMinutes(), 2, '0')",
  3344. s: "Ext.String.leftPad(this.getSeconds(), 2, '0')",
  3345. u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')",
  3346. O: "Ext.Date.getGMTOffset(this)",
  3347. P: "Ext.Date.getGMTOffset(this, true)",
  3348. T: "Ext.Date.getTimezone(this)",
  3349. Z: "(this.getTimezoneOffset() * -60)",
  3350. c: function() { // ISO-8601 -- GMT format
  3351. for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
  3352. var e = c.charAt(i);
  3353. code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal
  3354. }
  3355. return code.join(" + ");
  3356. },
  3357. /*
  3358. c: function() { // ISO-8601 -- UTC format
  3359. return [
  3360. "this.getUTCFullYear()", "'-'",
  3361. "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
  3362. "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')",
  3363. "'T'",
  3364. "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'",
  3365. "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
  3366. "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')",
  3367. "'Z'"
  3368. ].join(" + ");
  3369. },
  3370. */
  3371. U: "Math.round(this.getTime() / 1000)"
  3372. },
  3373. /**
  3374. * Checks if the passed Date parameters will cause a javascript Date "rollover".
  3375. * @param {Number} year 4-digit year
  3376. * @param {Number} month 1-based month-of-year
  3377. * @param {Number} day Day of month
  3378. * @param {Number} hour (optional) Hour
  3379. * @param {Number} minute (optional) Minute
  3380. * @param {Number} second (optional) Second
  3381. * @param {Number} millisecond (optional) Millisecond
  3382. * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise.
  3383. */
  3384. isValid : function(y, m, d, h, i, s, ms) {
  3385. // setup defaults
  3386. h = h || 0;
  3387. i = i || 0;
  3388. s = s || 0;
  3389. ms = ms || 0;
  3390. // Special handling for year < 100
  3391. var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.YEAR, y < 100 ? y - 100 : 0);
  3392. return y == dt.getFullYear() &&
  3393. m == dt.getMonth() + 1 &&
  3394. d == dt.getDate() &&
  3395. h == dt.getHours() &&
  3396. i == dt.getMinutes() &&
  3397. s == dt.getSeconds() &&
  3398. ms == dt.getMilliseconds();
  3399. },
  3400. /**
  3401. * Parses the passed string using the specified date format.
  3402. * Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
  3403. * The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
  3404. * which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash,
  3405. * the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
  3406. * Keep in mind that the input date string must precisely match the specified format string
  3407. * in order for the parse operation to be successful (failed parse operations return a null value).
  3408. * <p>Example:</p><pre><code>
  3409. //dt = Fri May 25 2007 (current date)
  3410. var dt = new Date();
  3411. //dt = Thu May 25 2006 (today&#39;s month/day in 2006)
  3412. dt = Ext.Date.parse("2006", "Y");
  3413. //dt = Sun Jan 15 2006 (all date parts specified)
  3414. dt = Ext.Date.parse("2006-01-15", "Y-m-d");
  3415. //dt = Sun Jan 15 2006 15:20:01
  3416. dt = Ext.Date.parse("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
  3417. // attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
  3418. dt = Ext.Date.parse("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
  3419. </code></pre>
  3420. * @param {String} input The raw date string.
  3421. * @param {String} format The expected date string format.
  3422. * @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover")
  3423. (defaults to false). Invalid date strings will return null when parsed.
  3424. * @return {Date} The parsed Date.
  3425. */
  3426. parse : function(input, format, strict) {
  3427. var p = utilDate.parseFunctions;
  3428. if (p[format] == null) {
  3429. utilDate.createParser(format);
  3430. }
  3431. return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict);
  3432. },
  3433. // Backwards compat
  3434. parseDate: function(input, format, strict){
  3435. return utilDate.parse(input, format, strict);
  3436. },
  3437. // private
  3438. getFormatCode : function(character) {
  3439. var f = utilDate.formatCodes[character];
  3440. if (f) {
  3441. f = typeof f == 'function'? f() : f;
  3442. utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution
  3443. }
  3444. // note: unknown characters are treated as literals
  3445. return f || ("'" + Ext.String.escape(character) + "'");
  3446. },
  3447. // private
  3448. createFormat : function(format) {
  3449. var code = [],
  3450. special = false,
  3451. ch = '';
  3452. for (var i = 0; i < format.length; ++i) {
  3453. ch = format.charAt(i);
  3454. if (!special && ch == "\\") {
  3455. special = true;
  3456. } else if (special) {
  3457. special = false;
  3458. code.push("'" + Ext.String.escape(ch) + "'");
  3459. } else {
  3460. code.push(utilDate.getFormatCode(ch));
  3461. }
  3462. }
  3463. utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+'));
  3464. },
  3465. // private
  3466. createParser : (function() {
  3467. var code = [
  3468. "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
  3469. "def = Ext.Date.defaults,",
  3470. "results = String(input).match(Ext.Date.parseRegexes[{0}]);", // either null, or an array of matched strings
  3471. "if(results){",
  3472. "{1}",
  3473. "if(u != null){", // i.e. unix time is defined
  3474. "v = new Date(u * 1000);", // give top priority to UNIX time
  3475. "}else{",
  3476. // create Date object representing midnight of the current day;
  3477. // this will provide us with our date defaults
  3478. // (note: clearTime() handles Daylight Saving Time automatically)
  3479. "dt = Ext.Date.clearTime(new Date);",
  3480. // date calculations (note: these calculations create a dependency on Ext.Number.from())
  3481. "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));",
  3482. "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));",
  3483. "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));",
  3484. // time calculations (note: these calculations create a dependency on Ext.Number.from())
  3485. "h = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));",
  3486. "i = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));",
  3487. "s = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));",
  3488. "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));",
  3489. "if(z >= 0 && y >= 0){",
  3490. // both the year and zero-based day of year are defined and >= 0.
  3491. // these 2 values alone provide sufficient info to create a full date object
  3492. // create Date object representing January 1st for the given year
  3493. // handle years < 100 appropriately
  3494. "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
  3495. // then add day of year, checking for Date "rollover" if necessary
  3496. "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);",
  3497. "}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
  3498. "v = null;", // invalid date, so return null
  3499. "}else{",
  3500. // plain old Date object
  3501. // handle years < 100 properly
  3502. "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
  3503. "}",
  3504. "}",
  3505. "}",
  3506. "if(v){",
  3507. // favour UTC offset over GMT offset
  3508. "if(zz != null){",
  3509. // reset to UTC, then add offset
  3510. "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
  3511. "}else if(o){",
  3512. // reset to GMT, then add offset
  3513. "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
  3514. "}",
  3515. "}",
  3516. "return v;"
  3517. ].join('\n');
  3518. return function(format) {
  3519. var regexNum = utilDate.parseRegexes.length,
  3520. currentGroup = 1,
  3521. calc = [],
  3522. regex = [],
  3523. special = false,
  3524. ch = "";
  3525. for (var i = 0; i < format.length; ++i) {
  3526. ch = format.charAt(i);
  3527. if (!special && ch == "\\") {
  3528. special = true;
  3529. } else if (special) {
  3530. special = false;
  3531. regex.push(Ext.String.escape(ch));
  3532. } else {
  3533. var obj = utilDate.formatCodeToRegex(ch, currentGroup);
  3534. currentGroup += obj.g;
  3535. regex.push(obj.s);
  3536. if (obj.g && obj.c) {
  3537. calc.push(obj.c);
  3538. }
  3539. }
  3540. }
  3541. utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i');
  3542. utilDate.parseFunctions[format] = Ext.functionFactory("input", "strict", xf(code, regexNum, calc.join('')));
  3543. };
  3544. })(),
  3545. // private
  3546. parseCodes : {
  3547. /*
  3548. * Notes:
  3549. * g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)
  3550. * c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)
  3551. * s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'
  3552. */
  3553. d: {
  3554. g:1,
  3555. c:"d = parseInt(results[{0}], 10);\n",
  3556. s:"(\\d{2})" // day of month with leading zeroes (01 - 31)
  3557. },
  3558. j: {
  3559. g:1,
  3560. c:"d = parseInt(results[{0}], 10);\n",
  3561. s:"(\\d{1,2})" // day of month without leading zeroes (1 - 31)
  3562. },
  3563. D: function() {
  3564. for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names
  3565. return {
  3566. g:0,
  3567. c:null,
  3568. s:"(?:" + a.join("|") +")"
  3569. };
  3570. },
  3571. l: function() {
  3572. return {
  3573. g:0,
  3574. c:null,
  3575. s:"(?:" + utilDate.dayNames.join("|") + ")"
  3576. };
  3577. },
  3578. N: {
  3579. g:0,
  3580. c:null,
  3581. s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))
  3582. },
  3583. S: {
  3584. g:0,
  3585. c:null,
  3586. s:"(?:st|nd|rd|th)"
  3587. },
  3588. w: {
  3589. g:0,
  3590. c:null,
  3591. s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday))
  3592. },
  3593. z: {
  3594. g:1,
  3595. c:"z = parseInt(results[{0}], 10);\n",
  3596. s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years))
  3597. },
  3598. W: {
  3599. g:0,
  3600. c:null,
  3601. s:"(?:\\d{2})" // ISO-8601 week number (with leading zero)
  3602. },
  3603. F: function() {
  3604. return {
  3605. g:1,
  3606. c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
  3607. s:"(" + utilDate.monthNames.join("|") + ")"
  3608. };
  3609. },
  3610. M: function() {
  3611. for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names
  3612. return Ext.applyIf({
  3613. s:"(" + a.join("|") + ")"
  3614. }, utilDate.formatCodeToRegex("F"));
  3615. },
  3616. m: {
  3617. g:1,
  3618. c:"m = parseInt(results[{0}], 10) - 1;\n",
  3619. s:"(\\d{2})" // month number with leading zeros (01 - 12)
  3620. },
  3621. n: {
  3622. g:1,
  3623. c:"m = parseInt(results[{0}], 10) - 1;\n",
  3624. s:"(\\d{1,2})" // month number without leading zeros (1 - 12)
  3625. },
  3626. t: {
  3627. g:0,
  3628. c:null,
  3629. s:"(?:\\d{2})" // no. of days in the month (28 - 31)
  3630. },
  3631. L: {
  3632. g:0,
  3633. c:null,
  3634. s:"(?:1|0)"
  3635. },
  3636. o: function() {
  3637. return utilDate.formatCodeToRegex("Y");
  3638. },
  3639. Y: {
  3640. g:1,
  3641. c:"y = parseInt(results[{0}], 10);\n",
  3642. s:"(\\d{4})" // 4-digit year
  3643. },
  3644. y: {
  3645. g:1,
  3646. c:"var ty = parseInt(results[{0}], 10);\n"
  3647. + "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
  3648. s:"(\\d{1,2})"
  3649. },
  3650. /*
  3651. * In the am/pm parsing routines, we allow both upper and lower case
  3652. * even though it doesn't exactly match the spec. It gives much more flexibility
  3653. * in being able to specify case insensitive regexes.
  3654. */
  3655. a: {
  3656. g:1,
  3657. c:"if (/(am)/i.test(results[{0}])) {\n"
  3658. + "if (!h || h == 12) { h = 0; }\n"
  3659. + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
  3660. s:"(am|pm|AM|PM)"
  3661. },
  3662. A: {
  3663. g:1,
  3664. c:"if (/(am)/i.test(results[{0}])) {\n"
  3665. + "if (!h || h == 12) { h = 0; }\n"
  3666. + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
  3667. s:"(AM|PM|am|pm)"
  3668. },
  3669. g: function() {
  3670. return utilDate.formatCodeToRegex("G");
  3671. },
  3672. G: {
  3673. g:1,
  3674. c:"h = parseInt(results[{0}], 10);\n",
  3675. s:"(\\d{1,2})" // 24-hr format of an hour without leading zeroes (0 - 23)
  3676. },
  3677. h: function() {
  3678. return utilDate.formatCodeToRegex("H");
  3679. },
  3680. H: {
  3681. g:1,
  3682. c:"h = parseInt(results[{0}], 10);\n",
  3683. s:"(\\d{2})" // 24-hr format of an hour with leading zeroes (00 - 23)
  3684. },
  3685. i: {
  3686. g:1,
  3687. c:"i = parseInt(results[{0}], 10);\n",
  3688. s:"(\\d{2})" // minutes with leading zeros (00 - 59)
  3689. },
  3690. s: {
  3691. g:1,
  3692. c:"s = parseInt(results[{0}], 10);\n",
  3693. s:"(\\d{2})" // seconds with leading zeros (00 - 59)
  3694. },
  3695. u: {
  3696. g:1,
  3697. c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",
  3698. s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
  3699. },
  3700. O: {
  3701. g:1,
  3702. c:[
  3703. "o = results[{0}];",
  3704. "var sn = o.substring(0,1),", // get + / - sign
  3705. "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
  3706. "mn = o.substring(3,5) % 60;", // get minutes
  3707. "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
  3708. ].join("\n"),
  3709. s: "([+\-]\\d{4})" // GMT offset in hrs and mins
  3710. },
  3711. P: {
  3712. g:1,
  3713. c:[
  3714. "o = results[{0}];",
  3715. "var sn = o.substring(0,1),", // get + / - sign
  3716. "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
  3717. "mn = o.substring(4,6) % 60;", // get minutes
  3718. "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
  3719. ].join("\n"),
  3720. s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
  3721. },
  3722. T: {
  3723. g:0,
  3724. c:null,
  3725. s:"[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars
  3726. },
  3727. Z: {
  3728. g:1,
  3729. c:"zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400
  3730. + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n",
  3731. s:"([+\-]?\\d{1,5})" // leading '+' sign is optional for UTC offset
  3732. },
  3733. c: function() {
  3734. var calc = [],
  3735. arr = [
  3736. utilDate.formatCodeToRegex("Y", 1), // year
  3737. utilDate.formatCodeToRegex("m", 2), // month
  3738. utilDate.formatCodeToRegex("d", 3), // day
  3739. utilDate.formatCodeToRegex("h", 4), // hour
  3740. utilDate.formatCodeToRegex("i", 5), // minute
  3741. utilDate.formatCodeToRegex("s", 6), // second
  3742. {c:"ms = results[7] || '0'; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n"}, // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
  3743. {c:[ // allow either "Z" (i.e. UTC) or "-0530" or "+08:00" (i.e. UTC offset) timezone delimiters. assumes local timezone if no timezone is specified
  3744. "if(results[8]) {", // timezone specified
  3745. "if(results[8] == 'Z'){",
  3746. "zz = 0;", // UTC
  3747. "}else if (results[8].indexOf(':') > -1){",
  3748. utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator
  3749. "}else{",
  3750. utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator
  3751. "}",
  3752. "}"
  3753. ].join('\n')}
  3754. ];
  3755. for (var i = 0, l = arr.length; i < l; ++i) {
  3756. calc.push(arr[i].c);
  3757. }
  3758. return {
  3759. g:1,
  3760. c:calc.join(""),
  3761. s:[
  3762. arr[0].s, // year (required)
  3763. "(?:", "-", arr[1].s, // month (optional)
  3764. "(?:", "-", arr[2].s, // day (optional)
  3765. "(?:",
  3766. "(?:T| )?", // time delimiter -- either a "T" or a single blank space
  3767. arr[3].s, ":", arr[4].s, // hour AND minute, delimited by a single colon (optional). MUST be preceded by either a "T" or a single blank space
  3768. "(?::", arr[5].s, ")?", // seconds (optional)
  3769. "(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional)
  3770. "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional)
  3771. ")?",
  3772. ")?",
  3773. ")?"
  3774. ].join("")
  3775. };
  3776. },
  3777. U: {
  3778. g:1,
  3779. c:"u = parseInt(results[{0}], 10);\n",
  3780. s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
  3781. }
  3782. },
  3783. //Old Ext.Date prototype methods.
  3784. // private
  3785. dateFormat: function(date, format) {
  3786. return utilDate.format(date, format);
  3787. },
  3788. /**
  3789. * Formats a date given the supplied format string.
  3790. * @param {Date} date The date to format
  3791. * @param {String} format The format string
  3792. * @return {String} The formatted date
  3793. */
  3794. format: function(date, format) {
  3795. if (utilDate.formatFunctions[format] == null) {
  3796. utilDate.createFormat(format);
  3797. }
  3798. var result = utilDate.formatFunctions[format].call(date);
  3799. return result + '';
  3800. },
  3801. /**
  3802. * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
  3803. *
  3804. * Note: The date string returned by the javascript Date object's toString() method varies
  3805. * between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
  3806. * For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
  3807. * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
  3808. * (which may or may not be present), failing which it proceeds to get the timezone abbreviation
  3809. * from the GMT offset portion of the date string.
  3810. * @param {Date} date The date
  3811. * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
  3812. */
  3813. getTimezone : function(date) {
  3814. // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
  3815. //
  3816. // Opera : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
  3817. // Safari : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone (same as FF)
  3818. // FF : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone
  3819. // IE : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev
  3820. // IE : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev
  3821. //
  3822. // this crazy regex attempts to guess the correct timezone abbreviation despite these differences.
  3823. // step 1: (?:\((.*)\) -- find timezone in parentheses
  3824. // step 2: ([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?) -- if nothing was found in step 1, find timezone from timezone offset portion of date string
  3825. // step 3: remove all non uppercase characters found in step 1 and 2
  3826. return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
  3827. },
  3828. /**
  3829. * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
  3830. * @param {Date} date The date
  3831. * @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
  3832. * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
  3833. */
  3834. getGMTOffset : function(date, colon) {
  3835. var offset = date.getTimezoneOffset();
  3836. return (offset > 0 ? "-" : "+")
  3837. + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0")
  3838. + (colon ? ":" : "")
  3839. + Ext.String.leftPad(Math.abs(offset % 60), 2, "0");
  3840. },
  3841. /**
  3842. * Get the numeric day number of the year, adjusted for leap year.
  3843. * @param {Date} date The date
  3844. * @return {Number} 0 to 364 (365 in leap years).
  3845. */
  3846. getDayOfYear: function(date) {
  3847. var num = 0,
  3848. d = Ext.Date.clone(date),
  3849. m = date.getMonth(),
  3850. i;
  3851. for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
  3852. num += utilDate.getDaysInMonth(d);
  3853. }
  3854. return num + date.getDate() - 1;
  3855. },
  3856. /**
  3857. * Get the numeric ISO-8601 week number of the year.
  3858. * (equivalent to the format specifier 'W', but without a leading zero).
  3859. * @param {Date} date The date
  3860. * @return {Number} 1 to 53
  3861. * @method
  3862. */
  3863. getWeekOfYear : (function() {
  3864. // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
  3865. var ms1d = 864e5, // milliseconds in a day
  3866. ms7d = 7 * ms1d; // milliseconds in a week
  3867. return function(date) { // return a closure so constants get calculated only once
  3868. var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number
  3869. AWN = Math.floor(DC3 / 7), // an Absolute Week Number
  3870. Wyr = new Date(AWN * ms7d).getUTCFullYear();
  3871. return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
  3872. };
  3873. })(),
  3874. /**
  3875. * Checks if the current date falls within a leap year.
  3876. * @param {Date} date The date
  3877. * @return {Boolean} True if the current date falls within a leap year, false otherwise.
  3878. */
  3879. isLeapYear : function(date) {
  3880. var year = date.getFullYear();
  3881. return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
  3882. },
  3883. /**
  3884. * Get the first day of the current month, adjusted for leap year. The returned value
  3885. * is the numeric day index within the week (0-6) which can be used in conjunction with
  3886. * the {@link #monthNames} array to retrieve the textual day name.
  3887. * Example:
  3888. * <pre><code>
  3889. var dt = new Date('1/10/2007'),
  3890. firstDay = Ext.Date.getFirstDayOfMonth(dt);
  3891. console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
  3892. * </code></pre>
  3893. * @param {Date} date The date
  3894. * @return {Number} The day number (0-6).
  3895. */
  3896. getFirstDayOfMonth : function(date) {
  3897. var day = (date.getDay() - (date.getDate() - 1)) % 7;
  3898. return (day < 0) ? (day + 7) : day;
  3899. },
  3900. /**
  3901. * Get the last day of the current month, adjusted for leap year. The returned value
  3902. * is the numeric day index within the week (0-6) which can be used in conjunction with
  3903. * the {@link #monthNames} array to retrieve the textual day name.
  3904. * Example:
  3905. * <pre><code>
  3906. var dt = new Date('1/10/2007'),
  3907. lastDay = Ext.Date.getLastDayOfMonth(dt);
  3908. console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
  3909. * </code></pre>
  3910. * @param {Date} date The date
  3911. * @return {Number} The day number (0-6).
  3912. */
  3913. getLastDayOfMonth : function(date) {
  3914. return utilDate.getLastDateOfMonth(date).getDay();
  3915. },
  3916. /**
  3917. * Get the date of the first day of the month in which this date resides.
  3918. * @param {Date} date The date
  3919. * @return {Date}
  3920. */
  3921. getFirstDateOfMonth : function(date) {
  3922. return new Date(date.getFullYear(), date.getMonth(), 1);
  3923. },
  3924. /**
  3925. * Get the date of the last day of the month in which this date resides.
  3926. * @param {Date} date The date
  3927. * @return {Date}
  3928. */
  3929. getLastDateOfMonth : function(date) {
  3930. return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date));
  3931. },
  3932. /**
  3933. * Get the number of days in the current month, adjusted for leap year.
  3934. * @param {Date} date The date
  3935. * @return {Number} The number of days in the month.
  3936. * @method
  3937. */
  3938. getDaysInMonth: (function() {
  3939. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  3940. return function(date) { // return a closure for efficiency
  3941. var m = date.getMonth();
  3942. return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m];
  3943. };
  3944. })(),
  3945. /**
  3946. * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
  3947. * @param {Date} date The date
  3948. * @return {String} 'st, 'nd', 'rd' or 'th'.
  3949. */
  3950. getSuffix : function(date) {
  3951. switch (date.getDate()) {
  3952. case 1:
  3953. case 21:
  3954. case 31:
  3955. return "st";
  3956. case 2:
  3957. case 22:
  3958. return "nd";
  3959. case 3:
  3960. case 23:
  3961. return "rd";
  3962. default:
  3963. return "th";
  3964. }
  3965. },
  3966. /**
  3967. * Creates and returns a new Date instance with the exact same date value as the called instance.
  3968. * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
  3969. * variable will also be changed. When the intention is to create a new variable that will not
  3970. * modify the original instance, you should create a clone.
  3971. *
  3972. * Example of correctly cloning a date:
  3973. * <pre><code>
  3974. //wrong way:
  3975. var orig = new Date('10/1/2006');
  3976. var copy = orig;
  3977. copy.setDate(5);
  3978. console.log(orig); //returns 'Thu Oct 05 2006'!
  3979. //correct way:
  3980. var orig = new Date('10/1/2006'),
  3981. copy = Ext.Date.clone(orig);
  3982. copy.setDate(5);
  3983. console.log(orig); //returns 'Thu Oct 01 2006'
  3984. * </code></pre>
  3985. * @param {Date} date The date
  3986. * @return {Date} The new Date instance.
  3987. */
  3988. clone : function(date) {
  3989. return new Date(date.getTime());
  3990. },
  3991. /**
  3992. * Checks if the current date is affected by Daylight Saving Time (DST).
  3993. * @param {Date} date The date
  3994. * @return {Boolean} True if the current date is affected by DST.
  3995. */
  3996. isDST : function(date) {
  3997. // adapted from http://sencha.com/forum/showthread.php?p=247172#post247172
  3998. // courtesy of @geoffrey.mcgill
  3999. return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset();
  4000. },
  4001. /**
  4002. * Attempts to clear all time information from this Date by setting the time to midnight of the same day,
  4003. * automatically adjusting for Daylight Saving Time (DST) where applicable.
  4004. * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
  4005. * @param {Date} date The date
  4006. * @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
  4007. * @return {Date} this or the clone.
  4008. */
  4009. clearTime : function(date, clone) {
  4010. if (clone) {
  4011. return Ext.Date.clearTime(Ext.Date.clone(date));
  4012. }
  4013. // get current date before clearing time
  4014. var d = date.getDate();
  4015. // clear time
  4016. date.setHours(0);
  4017. date.setMinutes(0);
  4018. date.setSeconds(0);
  4019. date.setMilliseconds(0);
  4020. if (date.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
  4021. // note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
  4022. // refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule
  4023. // increment hour until cloned date == current date
  4024. for (var hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr));
  4025. date.setDate(d);
  4026. date.setHours(c.getHours());
  4027. }
  4028. return date;
  4029. },
  4030. /**
  4031. * Provides a convenient method for performing basic date arithmetic. This method
  4032. * does not modify the Date instance being called - it creates and returns
  4033. * a new Date instance containing the resulting date value.
  4034. *
  4035. * Examples:
  4036. * <pre><code>
  4037. // Basic usage:
  4038. var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
  4039. console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
  4040. // Negative values will be subtracted:
  4041. var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
  4042. console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
  4043. * </code></pre>
  4044. *
  4045. * @param {Date} date The date to modify
  4046. * @param {String} interval A valid date interval enum value.
  4047. * @param {Number} value The amount to add to the current date.
  4048. * @return {Date} The new Date instance.
  4049. */
  4050. add : function(date, interval, value) {
  4051. var d = Ext.Date.clone(date),
  4052. Date = Ext.Date;
  4053. if (!interval || value === 0) return d;
  4054. switch(interval.toLowerCase()) {
  4055. case Ext.Date.MILLI:
  4056. d.setMilliseconds(d.getMilliseconds() + value);
  4057. break;
  4058. case Ext.Date.SECOND:
  4059. d.setSeconds(d.getSeconds() + value);
  4060. break;
  4061. case Ext.Date.MINUTE:
  4062. d.setMinutes(d.getMinutes() + value);
  4063. break;
  4064. case Ext.Date.HOUR:
  4065. d.setHours(d.getHours() + value);
  4066. break;
  4067. case Ext.Date.DAY:
  4068. d.setDate(d.getDate() + value);
  4069. break;
  4070. case Ext.Date.MONTH:
  4071. var day = date.getDate();
  4072. if (day > 28) {
  4073. day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), 'mo', value)).getDate());
  4074. }
  4075. d.setDate(day);
  4076. d.setMonth(date.getMonth() + value);
  4077. break;
  4078. case Ext.Date.YEAR:
  4079. d.setFullYear(date.getFullYear() + value);
  4080. break;
  4081. }
  4082. return d;
  4083. },
  4084. /**
  4085. * Checks if a date falls on or between the given start and end dates.
  4086. * @param {Date} date The date to check
  4087. * @param {Date} start Start date
  4088. * @param {Date} end End date
  4089. * @return {Boolean} true if this date falls on or between the given start and end dates.
  4090. */
  4091. between : function(date, start, end) {
  4092. var t = date.getTime();
  4093. return start.getTime() <= t && t <= end.getTime();
  4094. },
  4095. //Maintains compatibility with old static and prototype window.Date methods.
  4096. compat: function() {
  4097. var nativeDate = window.Date,
  4098. p, u,
  4099. statics = ['useStrict', 'formatCodeToRegex', 'parseFunctions', 'parseRegexes', 'formatFunctions', 'y2kYear', 'MILLI', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'MONTH', 'YEAR', 'defaults', 'dayNames', 'monthNames', 'monthNumbers', 'getShortMonthName', 'getShortDayName', 'getMonthNumber', 'formatCodes', 'isValid', 'parseDate', 'getFormatCode', 'createFormat', 'createParser', 'parseCodes'],
  4100. proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'];
  4101. //Append statics
  4102. Ext.Array.forEach(statics, function(s) {
  4103. nativeDate[s] = utilDate[s];
  4104. });
  4105. //Append to prototype
  4106. Ext.Array.forEach(proto, function(s) {
  4107. nativeDate.prototype[s] = function() {
  4108. var args = Array.prototype.slice.call(arguments);
  4109. args.unshift(this);
  4110. return utilDate[s].apply(utilDate, args);
  4111. };
  4112. });
  4113. }
  4114. };
  4115. var utilDate = Ext.Date;
  4116. })();
  4117. /**
  4118. * @author Jacky Nguyen <jacky@sencha.com>
  4119. * @docauthor Jacky Nguyen <jacky@sencha.com>
  4120. * @class Ext.Base
  4121. *
  4122. * The root of all classes created with {@link Ext#define}.
  4123. *
  4124. * Ext.Base is the building block of all Ext classes. All classes in Ext inherit from Ext.Base.
  4125. * All prototype and static members of this class are inherited by all other classes.
  4126. */
  4127. (function(flexSetter) {
  4128. var Base = Ext.Base = function() {};
  4129. Base.prototype = {
  4130. $className: 'Ext.Base',
  4131. $class: Base,
  4132. /**
  4133. * Get the reference to the current class from which this object was instantiated. Unlike {@link Ext.Base#statics},
  4134. * `this.self` is scope-dependent and it's meant to be used for dynamic inheritance. See {@link Ext.Base#statics}
  4135. * for a detailed comparison
  4136. *
  4137. * Ext.define('My.Cat', {
  4138. * statics: {
  4139. * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
  4140. * },
  4141. *
  4142. * constructor: function() {
  4143. * alert(this.self.speciesName); / dependent on 'this'
  4144. *
  4145. * return this;
  4146. * },
  4147. *
  4148. * clone: function() {
  4149. * return new this.self();
  4150. * }
  4151. * });
  4152. *
  4153. *
  4154. * Ext.define('My.SnowLeopard', {
  4155. * extend: 'My.Cat',
  4156. * statics: {
  4157. * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
  4158. * }
  4159. * });
  4160. *
  4161. * var cat = new My.Cat(); // alerts 'Cat'
  4162. * var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard'
  4163. *
  4164. * var clone = snowLeopard.clone();
  4165. * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
  4166. *
  4167. * @type Ext.Class
  4168. * @protected
  4169. */
  4170. self: Base,
  4171. // Default constructor, simply returns `this`
  4172. constructor: function() {
  4173. return this;
  4174. },
  4175. //<feature classSystem.config>
  4176. /**
  4177. * Initialize configuration for this class. a typical example:
  4178. *
  4179. * Ext.define('My.awesome.Class', {
  4180. * // The default config
  4181. * config: {
  4182. * name: 'Awesome',
  4183. * isAwesome: true
  4184. * },
  4185. *
  4186. * constructor: function(config) {
  4187. * this.initConfig(config);
  4188. *
  4189. * return this;
  4190. * }
  4191. * });
  4192. *
  4193. * var awesome = new My.awesome.Class({
  4194. * name: 'Super Awesome'
  4195. * });
  4196. *
  4197. * alert(awesome.getName()); // 'Super Awesome'
  4198. *
  4199. * @protected
  4200. * @param {Object} config
  4201. * @return {Object} mixins The mixin prototypes as key - value pairs
  4202. */
  4203. initConfig: function(config) {
  4204. if (!this.$configInited) {
  4205. this.config = Ext.Object.merge({}, this.config || {}, config || {});
  4206. this.applyConfig(this.config);
  4207. this.$configInited = true;
  4208. }
  4209. return this;
  4210. },
  4211. /**
  4212. * @private
  4213. */
  4214. setConfig: function(config) {
  4215. this.applyConfig(config || {});
  4216. return this;
  4217. },
  4218. /**
  4219. * @private
  4220. */
  4221. applyConfig: flexSetter(function(name, value) {
  4222. var setter = 'set' + Ext.String.capitalize(name);
  4223. if (typeof this[setter] === 'function') {
  4224. this[setter].call(this, value);
  4225. }
  4226. return this;
  4227. }),
  4228. //</feature>
  4229. /**
  4230. * Call the parent's overridden method. For example:
  4231. *
  4232. * Ext.define('My.own.A', {
  4233. * constructor: function(test) {
  4234. * alert(test);
  4235. * }
  4236. * });
  4237. *
  4238. * Ext.define('My.own.B', {
  4239. * extend: 'My.own.A',
  4240. *
  4241. * constructor: function(test) {
  4242. * alert(test);
  4243. *
  4244. * this.callParent([test + 1]);
  4245. * }
  4246. * });
  4247. *
  4248. * Ext.define('My.own.C', {
  4249. * extend: 'My.own.B',
  4250. *
  4251. * constructor: function() {
  4252. * alert("Going to call parent's overriden constructor...");
  4253. *
  4254. * this.callParent(arguments);
  4255. * }
  4256. * });
  4257. *
  4258. * var a = new My.own.A(1); // alerts '1'
  4259. * var b = new My.own.B(1); // alerts '1', then alerts '2'
  4260. * var c = new My.own.C(2); // alerts "Going to call parent's overriden constructor..."
  4261. * // alerts '2', then alerts '3'
  4262. *
  4263. * @protected
  4264. * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
  4265. * from the current method, for example: `this.callParent(arguments)`
  4266. * @return {Object} Returns the result from the superclass' method
  4267. */
  4268. callParent: function(args) {
  4269. var method = this.callParent.caller,
  4270. parentClass, methodName;
  4271. if (!method.$owner) {
  4272. method = method.caller;
  4273. }
  4274. parentClass = method.$owner.superclass;
  4275. methodName = method.$name;
  4276. return parentClass[methodName].apply(this, args || []);
  4277. },
  4278. /**
  4279. * Get the reference to the class from which this object was instantiated. Note that unlike {@link Ext.Base#self},
  4280. * `this.statics()` is scope-independent and it always returns the class from which it was called, regardless of what
  4281. * `this` points to during run-time
  4282. *
  4283. * Ext.define('My.Cat', {
  4284. * statics: {
  4285. * totalCreated: 0,
  4286. * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
  4287. * },
  4288. *
  4289. * constructor: function() {
  4290. * var statics = this.statics();
  4291. *
  4292. * alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to
  4293. * // equivalent to: My.Cat.speciesName
  4294. *
  4295. * alert(this.self.speciesName); // dependent on 'this'
  4296. *
  4297. * statics.totalCreated++;
  4298. *
  4299. * return this;
  4300. * },
  4301. *
  4302. * clone: function() {
  4303. * var cloned = new this.self; // dependent on 'this'
  4304. *
  4305. * cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName
  4306. *
  4307. * return cloned;
  4308. * }
  4309. * });
  4310. *
  4311. *
  4312. * Ext.define('My.SnowLeopard', {
  4313. * extend: 'My.Cat',
  4314. *
  4315. * statics: {
  4316. * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
  4317. * },
  4318. *
  4319. * constructor: function() {
  4320. * this.callParent();
  4321. * }
  4322. * });
  4323. *
  4324. * var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat'
  4325. *
  4326. * var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'
  4327. *
  4328. * var clone = snowLeopard.clone();
  4329. * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
  4330. * alert(clone.groupName); // alerts 'Cat'
  4331. *
  4332. * alert(My.Cat.totalCreated); // alerts 3
  4333. *
  4334. * @protected
  4335. * @return {Ext.Class}
  4336. */
  4337. statics: function() {
  4338. var method = this.statics.caller,
  4339. self = this.self;
  4340. if (!method) {
  4341. return self;
  4342. }
  4343. return method.$owner;
  4344. },
  4345. /**
  4346. * Call the original method that was previously overridden with {@link Ext.Base#override}
  4347. *
  4348. * Ext.define('My.Cat', {
  4349. * constructor: function() {
  4350. * alert("I'm a cat!");
  4351. *
  4352. * return this;
  4353. * }
  4354. * });
  4355. *
  4356. * My.Cat.override({
  4357. * constructor: function() {
  4358. * alert("I'm going to be a cat!");
  4359. *
  4360. * var instance = this.callOverridden();
  4361. *
  4362. * alert("Meeeeoooowwww");
  4363. *
  4364. * return instance;
  4365. * }
  4366. * });
  4367. *
  4368. * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
  4369. * // alerts "I'm a cat!"
  4370. * // alerts "Meeeeoooowwww"
  4371. *
  4372. * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
  4373. * @return {Object} Returns the result after calling the overridden method
  4374. * @protected
  4375. */
  4376. callOverridden: function(args) {
  4377. var method = this.callOverridden.caller;
  4378. return method.$previous.apply(this, args || []);
  4379. },
  4380. destroy: function() {}
  4381. };
  4382. // These static properties will be copied to every newly created class with {@link Ext#define}
  4383. Ext.apply(Ext.Base, {
  4384. /**
  4385. * Create a new instance of this Class.
  4386. *
  4387. * Ext.define('My.cool.Class', {
  4388. * ...
  4389. * });
  4390. *
  4391. * My.cool.Class.create({
  4392. * someConfig: true
  4393. * });
  4394. *
  4395. * All parameters are passed to the constructor of the class.
  4396. *
  4397. * @return {Object} the created instance.
  4398. * @static
  4399. * @inheritable
  4400. */
  4401. create: function() {
  4402. return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0)));
  4403. },
  4404. /**
  4405. * @private
  4406. * @inheritable
  4407. */
  4408. own: function(name, value) {
  4409. if (typeof value == 'function') {
  4410. this.ownMethod(name, value);
  4411. }
  4412. else {
  4413. this.prototype[name] = value;
  4414. }
  4415. },
  4416. /**
  4417. * @private
  4418. * @inheritable
  4419. */
  4420. ownMethod: function(name, fn) {
  4421. var originalFn;
  4422. if (typeof fn.$owner !== 'undefined' && fn !== Ext.emptyFn) {
  4423. originalFn = fn;
  4424. fn = function() {
  4425. return originalFn.apply(this, arguments);
  4426. };
  4427. }
  4428. fn.$owner = this;
  4429. fn.$name = name;
  4430. this.prototype[name] = fn;
  4431. },
  4432. /**
  4433. * Add / override static properties of this class.
  4434. *
  4435. * Ext.define('My.cool.Class', {
  4436. * ...
  4437. * });
  4438. *
  4439. * My.cool.Class.addStatics({
  4440. * someProperty: 'someValue', // My.cool.Class.someProperty = 'someValue'
  4441. * method1: function() { ... }, // My.cool.Class.method1 = function() { ... };
  4442. * method2: function() { ... } // My.cool.Class.method2 = function() { ... };
  4443. * });
  4444. *
  4445. * @param {Object} members
  4446. * @return {Ext.Base} this
  4447. * @static
  4448. * @inheritable
  4449. */
  4450. addStatics: function(members) {
  4451. for (var name in members) {
  4452. if (members.hasOwnProperty(name)) {
  4453. this[name] = members[name];
  4454. }
  4455. }
  4456. return this;
  4457. },
  4458. /**
  4459. * @private
  4460. * @param {Object} members
  4461. */
  4462. addInheritableStatics: function(members) {
  4463. var inheritableStatics,
  4464. hasInheritableStatics,
  4465. prototype = this.prototype,
  4466. name, member;
  4467. inheritableStatics = prototype.$inheritableStatics;
  4468. hasInheritableStatics = prototype.$hasInheritableStatics;
  4469. if (!inheritableStatics) {
  4470. inheritableStatics = prototype.$inheritableStatics = [];
  4471. hasInheritableStatics = prototype.$hasInheritableStatics = {};
  4472. }
  4473. for (name in members) {
  4474. if (members.hasOwnProperty(name)) {
  4475. member = members[name];
  4476. this[name] = member;
  4477. if (!hasInheritableStatics[name]) {
  4478. hasInheritableStatics[name] = true;
  4479. inheritableStatics.push(name);
  4480. }
  4481. }
  4482. }
  4483. return this;
  4484. },
  4485. /**
  4486. * Add methods / properties to the prototype of this class.
  4487. *
  4488. * Ext.define('My.awesome.Cat', {
  4489. * constructor: function() {
  4490. * ...
  4491. * }
  4492. * });
  4493. *
  4494. * My.awesome.Cat.implement({
  4495. * meow: function() {
  4496. * alert('Meowww...');
  4497. * }
  4498. * });
  4499. *
  4500. * var kitty = new My.awesome.Cat;
  4501. * kitty.meow();
  4502. *
  4503. * @param {Object} members
  4504. * @static
  4505. * @inheritable
  4506. */
  4507. implement: function(members) {
  4508. var prototype = this.prototype,
  4509. enumerables = Ext.enumerables,
  4510. name, i, member;
  4511. for (name in members) {
  4512. if (members.hasOwnProperty(name)) {
  4513. member = members[name];
  4514. if (typeof member === 'function') {
  4515. member.$owner = this;
  4516. member.$name = name;
  4517. }
  4518. prototype[name] = member;
  4519. }
  4520. }
  4521. if (enumerables) {
  4522. for (i = enumerables.length; i--;) {
  4523. name = enumerables[i];
  4524. if (members.hasOwnProperty(name)) {
  4525. member = members[name];
  4526. member.$owner = this;
  4527. member.$name = name;
  4528. prototype[name] = member;
  4529. }
  4530. }
  4531. }
  4532. },
  4533. /**
  4534. * Borrow another class' members to the prototype of this class.
  4535. *
  4536. * Ext.define('Bank', {
  4537. * money: '$$$',
  4538. * printMoney: function() {
  4539. * alert('$$$$$$$');
  4540. * }
  4541. * });
  4542. *
  4543. * Ext.define('Thief', {
  4544. * ...
  4545. * });
  4546. *
  4547. * Thief.borrow(Bank, ['money', 'printMoney']);
  4548. *
  4549. * var steve = new Thief();
  4550. *
  4551. * alert(steve.money); // alerts '$$$'
  4552. * steve.printMoney(); // alerts '$$$$$$$'
  4553. *
  4554. * @param {Ext.Base} fromClass The class to borrow members from
  4555. * @param {String/String[]} members The names of the members to borrow
  4556. * @return {Ext.Base} this
  4557. * @static
  4558. * @inheritable
  4559. */
  4560. borrow: function(fromClass, members) {
  4561. var fromPrototype = fromClass.prototype,
  4562. i, ln, member;
  4563. members = Ext.Array.from(members);
  4564. for (i = 0, ln = members.length; i < ln; i++) {
  4565. member = members[i];
  4566. this.own(member, fromPrototype[member]);
  4567. }
  4568. return this;
  4569. },
  4570. /**
  4571. * Override prototype members of this class. Overridden methods can be invoked via
  4572. * {@link Ext.Base#callOverridden}
  4573. *
  4574. * Ext.define('My.Cat', {
  4575. * constructor: function() {
  4576. * alert("I'm a cat!");
  4577. *
  4578. * return this;
  4579. * }
  4580. * });
  4581. *
  4582. * My.Cat.override({
  4583. * constructor: function() {
  4584. * alert("I'm going to be a cat!");
  4585. *
  4586. * var instance = this.callOverridden();
  4587. *
  4588. * alert("Meeeeoooowwww");
  4589. *
  4590. * return instance;
  4591. * }
  4592. * });
  4593. *
  4594. * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
  4595. * // alerts "I'm a cat!"
  4596. * // alerts "Meeeeoooowwww"
  4597. *
  4598. * @param {Object} members
  4599. * @return {Ext.Base} this
  4600. * @static
  4601. * @inheritable
  4602. */
  4603. override: function(members) {
  4604. var prototype = this.prototype,
  4605. enumerables = Ext.enumerables,
  4606. name, i, member, previous;
  4607. if (arguments.length === 2) {
  4608. name = members;
  4609. member = arguments[1];
  4610. if (typeof member == 'function') {
  4611. if (typeof prototype[name] == 'function') {
  4612. previous = prototype[name];
  4613. member.$previous = previous;
  4614. }
  4615. this.ownMethod(name, member);
  4616. }
  4617. else {
  4618. prototype[name] = member;
  4619. }
  4620. return this;
  4621. }
  4622. for (name in members) {
  4623. if (members.hasOwnProperty(name)) {
  4624. member = members[name];
  4625. if (typeof member === 'function') {
  4626. if (typeof prototype[name] === 'function') {
  4627. previous = prototype[name];
  4628. member.$previous = previous;
  4629. }
  4630. this.ownMethod(name, member);
  4631. }
  4632. else {
  4633. prototype[name] = member;
  4634. }
  4635. }
  4636. }
  4637. if (enumerables) {
  4638. for (i = enumerables.length; i--;) {
  4639. name = enumerables[i];
  4640. if (members.hasOwnProperty(name)) {
  4641. if (typeof prototype[name] !== 'undefined') {
  4642. previous = prototype[name];
  4643. members[name].$previous = previous;
  4644. }
  4645. this.ownMethod(name, members[name]);
  4646. }
  4647. }
  4648. }
  4649. return this;
  4650. },
  4651. //<feature classSystem.mixins>
  4652. /**
  4653. * Used internally by the mixins pre-processor
  4654. * @private
  4655. * @inheritable
  4656. */
  4657. mixin: function(name, cls) {
  4658. var mixin = cls.prototype,
  4659. my = this.prototype,
  4660. key, fn;
  4661. for (key in mixin) {
  4662. if (mixin.hasOwnProperty(key)) {
  4663. if (typeof my[key] === 'undefined' && key !== 'mixins' && key !== 'mixinId') {
  4664. if (typeof mixin[key] === 'function') {
  4665. fn = mixin[key];
  4666. if (typeof fn.$owner === 'undefined') {
  4667. this.ownMethod(key, fn);
  4668. }
  4669. else {
  4670. my[key] = fn;
  4671. }
  4672. }
  4673. else {
  4674. my[key] = mixin[key];
  4675. }
  4676. }
  4677. //<feature classSystem.config>
  4678. else if (key === 'config' && my.config && mixin.config) {
  4679. Ext.Object.merge(my.config, mixin.config);
  4680. }
  4681. //</feature>
  4682. }
  4683. }
  4684. if (typeof mixin.onClassMixedIn !== 'undefined') {
  4685. mixin.onClassMixedIn.call(cls, this);
  4686. }
  4687. if (!my.hasOwnProperty('mixins')) {
  4688. if ('mixins' in my) {
  4689. my.mixins = Ext.Object.merge({}, my.mixins);
  4690. }
  4691. else {
  4692. my.mixins = {};
  4693. }
  4694. }
  4695. my.mixins[name] = mixin;
  4696. },
  4697. //</feature>
  4698. /**
  4699. * Get the current class' name in string format.
  4700. *
  4701. * Ext.define('My.cool.Class', {
  4702. * constructor: function() {
  4703. * alert(this.self.getName()); // alerts 'My.cool.Class'
  4704. * }
  4705. * });
  4706. *
  4707. * My.cool.Class.getName(); // 'My.cool.Class'
  4708. *
  4709. * @return {String} className
  4710. * @static
  4711. * @inheritable
  4712. */
  4713. getName: function() {
  4714. return Ext.getClassName(this);
  4715. },
  4716. /**
  4717. * Create aliases for existing prototype methods. Example:
  4718. *
  4719. * Ext.define('My.cool.Class', {
  4720. * method1: function() { ... },
  4721. * method2: function() { ... }
  4722. * });
  4723. *
  4724. * var test = new My.cool.Class();
  4725. *
  4726. * My.cool.Class.createAlias({
  4727. * method3: 'method1',
  4728. * method4: 'method2'
  4729. * });
  4730. *
  4731. * test.method3(); // test.method1()
  4732. *
  4733. * My.cool.Class.createAlias('method5', 'method3');
  4734. *
  4735. * test.method5(); // test.method3() -> test.method1()
  4736. *
  4737. * @param {String/Object} alias The new method name, or an object to set multiple aliases. See
  4738. * {@link Ext.Function#flexSetter flexSetter}
  4739. * @param {String/Object} origin The original method name
  4740. * @static
  4741. * @inheritable
  4742. * @method
  4743. */
  4744. createAlias: flexSetter(function(alias, origin) {
  4745. this.prototype[alias] = function() {
  4746. return this[origin].apply(this, arguments);
  4747. }
  4748. })
  4749. });
  4750. })(Ext.Function.flexSetter);
  4751. /**
  4752. * @author Jacky Nguyen <jacky@sencha.com>
  4753. * @docauthor Jacky Nguyen <jacky@sencha.com>
  4754. * @class Ext.Class
  4755. *
  4756. * Handles class creation throughout the framework. This is a low level factory that is used by Ext.ClassManager and generally
  4757. * should not be used directly. If you choose to use Ext.Class you will lose out on the namespace, aliasing and depency loading
  4758. * features made available by Ext.ClassManager. The only time you would use Ext.Class directly is to create an anonymous class.
  4759. *
  4760. * If you wish to create a class you should use {@link Ext#define Ext.define} which aliases
  4761. * {@link Ext.ClassManager#create Ext.ClassManager.create} to enable namespacing and dynamic dependency resolution.
  4762. *
  4763. * Ext.Class is the factory and **not** the superclass of everything. For the base class that **all** Ext classes inherit
  4764. * from, see {@link Ext.Base}.
  4765. */
  4766. (function() {
  4767. var Class,
  4768. Base = Ext.Base,
  4769. baseStaticProperties = [],
  4770. baseStaticProperty;
  4771. for (baseStaticProperty in Base) {
  4772. if (Base.hasOwnProperty(baseStaticProperty)) {
  4773. baseStaticProperties.push(baseStaticProperty);
  4774. }
  4775. }
  4776. /**
  4777. * @method constructor
  4778. * Creates new class.
  4779. * @param {Object} classData An object represent the properties of this class
  4780. * @param {Function} createdFn (Optional) The callback function to be executed when this class is fully created.
  4781. * Note that the creation process can be asynchronous depending on the pre-processors used.
  4782. * @return {Ext.Base} The newly created class
  4783. */
  4784. Ext.Class = Class = function(newClass, classData, onClassCreated) {
  4785. if (typeof newClass != 'function') {
  4786. onClassCreated = classData;
  4787. classData = newClass;
  4788. newClass = function() {
  4789. return this.constructor.apply(this, arguments);
  4790. };
  4791. }
  4792. if (!classData) {
  4793. classData = {};
  4794. }
  4795. var preprocessorStack = classData.preprocessors || Class.getDefaultPreprocessors(),
  4796. registeredPreprocessors = Class.getPreprocessors(),
  4797. index = 0,
  4798. preprocessors = [],
  4799. preprocessor, staticPropertyName, process, i, j, ln;
  4800. for (i = 0, ln = baseStaticProperties.length; i < ln; i++) {
  4801. staticPropertyName = baseStaticProperties[i];
  4802. newClass[staticPropertyName] = Base[staticPropertyName];
  4803. }
  4804. delete classData.preprocessors;
  4805. for (j = 0, ln = preprocessorStack.length; j < ln; j++) {
  4806. preprocessor = preprocessorStack[j];
  4807. if (typeof preprocessor == 'string') {
  4808. preprocessor = registeredPreprocessors[preprocessor];
  4809. if (!preprocessor.always) {
  4810. if (classData.hasOwnProperty(preprocessor.name)) {
  4811. preprocessors.push(preprocessor.fn);
  4812. }
  4813. }
  4814. else {
  4815. preprocessors.push(preprocessor.fn);
  4816. }
  4817. }
  4818. else {
  4819. preprocessors.push(preprocessor);
  4820. }
  4821. }
  4822. classData.onClassCreated = onClassCreated || Ext.emptyFn;
  4823. classData.onBeforeClassCreated = function(cls, data) {
  4824. onClassCreated = data.onClassCreated;
  4825. delete data.onBeforeClassCreated;
  4826. delete data.onClassCreated;
  4827. cls.implement(data);
  4828. onClassCreated.call(cls, cls);
  4829. };
  4830. process = function(cls, data) {
  4831. preprocessor = preprocessors[index++];
  4832. if (!preprocessor) {
  4833. data.onBeforeClassCreated.apply(this, arguments);
  4834. return;
  4835. }
  4836. if (preprocessor.call(this, cls, data, process) !== false) {
  4837. process.apply(this, arguments);
  4838. }
  4839. };
  4840. process.call(Class, newClass, classData);
  4841. return newClass;
  4842. };
  4843. Ext.apply(Class, {
  4844. /** @private */
  4845. preprocessors: {},
  4846. /**
  4847. * Register a new pre-processor to be used during the class creation process
  4848. *
  4849. * @member Ext.Class
  4850. * @param {String} name The pre-processor's name
  4851. * @param {Function} fn The callback function to be executed. Typical format:
  4852. *
  4853. * function(cls, data, fn) {
  4854. * // Your code here
  4855. *
  4856. * // Execute this when the processing is finished.
  4857. * // Asynchronous processing is perfectly ok
  4858. * if (fn) {
  4859. * fn.call(this, cls, data);
  4860. * }
  4861. * });
  4862. *
  4863. * @param {Function} fn.cls The created class
  4864. * @param {Object} fn.data The set of properties passed in {@link Ext.Class} constructor
  4865. * @param {Function} fn.fn The callback function that **must** to be executed when this pre-processor finishes,
  4866. * regardless of whether the processing is synchronous or aynchronous
  4867. *
  4868. * @return {Ext.Class} this
  4869. * @static
  4870. */
  4871. registerPreprocessor: function(name, fn, always) {
  4872. this.preprocessors[name] = {
  4873. name: name,
  4874. always: always || false,
  4875. fn: fn
  4876. };
  4877. return this;
  4878. },
  4879. /**
  4880. * Retrieve a pre-processor callback function by its name, which has been registered before
  4881. *
  4882. * @param {String} name
  4883. * @return {Function} preprocessor
  4884. * @static
  4885. */
  4886. getPreprocessor: function(name) {
  4887. return this.preprocessors[name];
  4888. },
  4889. getPreprocessors: function() {
  4890. return this.preprocessors;
  4891. },
  4892. /**
  4893. * Retrieve the array stack of default pre-processors
  4894. *
  4895. * @return {Function[]} defaultPreprocessors
  4896. * @static
  4897. */
  4898. getDefaultPreprocessors: function() {
  4899. return this.defaultPreprocessors || [];
  4900. },
  4901. /**
  4902. * Set the default array stack of default pre-processors
  4903. *
  4904. * @param {Function/Function[]} preprocessors
  4905. * @return {Ext.Class} this
  4906. * @static
  4907. */
  4908. setDefaultPreprocessors: function(preprocessors) {
  4909. this.defaultPreprocessors = Ext.Array.from(preprocessors);
  4910. return this;
  4911. },
  4912. /**
  4913. * Inserts this pre-processor at a specific position in the stack, optionally relative to
  4914. * any existing pre-processor. For example:
  4915. *
  4916. * Ext.Class.registerPreprocessor('debug', function(cls, data, fn) {
  4917. * // Your code here
  4918. *
  4919. * if (fn) {
  4920. * fn.call(this, cls, data);
  4921. * }
  4922. * }).setDefaultPreprocessorPosition('debug', 'last');
  4923. *
  4924. * @param {String} name The pre-processor name. Note that it needs to be registered with
  4925. * {@link #registerPreprocessor registerPreprocessor} before this
  4926. * @param {String} offset The insertion position. Four possible values are:
  4927. * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
  4928. * @param {String} relativeName
  4929. * @return {Ext.Class} this
  4930. * @static
  4931. */
  4932. setDefaultPreprocessorPosition: function(name, offset, relativeName) {
  4933. var defaultPreprocessors = this.defaultPreprocessors,
  4934. index;
  4935. if (typeof offset == 'string') {
  4936. if (offset === 'first') {
  4937. defaultPreprocessors.unshift(name);
  4938. return this;
  4939. }
  4940. else if (offset === 'last') {
  4941. defaultPreprocessors.push(name);
  4942. return this;
  4943. }
  4944. offset = (offset === 'after') ? 1 : -1;
  4945. }
  4946. index = Ext.Array.indexOf(defaultPreprocessors, relativeName);
  4947. if (index !== -1) {
  4948. Ext.Array.splice(defaultPreprocessors, Math.max(0, index + offset), 0, name);
  4949. }
  4950. return this;
  4951. }
  4952. });
  4953. /**
  4954. * @cfg {String} extend
  4955. * The parent class that this class extends. For example:
  4956. *
  4957. * Ext.define('Person', {
  4958. * say: function(text) { alert(text); }
  4959. * });
  4960. *
  4961. * Ext.define('Developer', {
  4962. * extend: 'Person',
  4963. * say: function(text) { this.callParent(["print "+text]); }
  4964. * });
  4965. */
  4966. Class.registerPreprocessor('extend', function(cls, data) {
  4967. var extend = data.extend,
  4968. base = Ext.Base,
  4969. basePrototype = base.prototype,
  4970. prototype = function() {},
  4971. parent, i, k, ln, staticName, parentStatics,
  4972. parentPrototype, clsPrototype;
  4973. if (extend && extend !== Object) {
  4974. parent = extend;
  4975. }
  4976. else {
  4977. parent = base;
  4978. }
  4979. parentPrototype = parent.prototype;
  4980. prototype.prototype = parentPrototype;
  4981. clsPrototype = cls.prototype = new prototype();
  4982. if (!('$class' in parent)) {
  4983. for (i in basePrototype) {
  4984. if (!parentPrototype[i]) {
  4985. parentPrototype[i] = basePrototype[i];
  4986. }
  4987. }
  4988. }
  4989. clsPrototype.self = cls;
  4990. cls.superclass = clsPrototype.superclass = parentPrototype;
  4991. delete data.extend;
  4992. //<feature classSystem.inheritableStatics>
  4993. // Statics inheritance
  4994. parentStatics = parentPrototype.$inheritableStatics;
  4995. if (parentStatics) {
  4996. for (k = 0, ln = parentStatics.length; k < ln; k++) {
  4997. staticName = parentStatics[k];
  4998. if (!cls.hasOwnProperty(staticName)) {
  4999. cls[staticName] = parent[staticName];
  5000. }
  5001. }
  5002. }
  5003. //</feature>
  5004. //<feature classSystem.config>
  5005. // Merge the parent class' config object without referencing it
  5006. if (parentPrototype.config) {
  5007. clsPrototype.config = Ext.Object.merge({}, parentPrototype.config);
  5008. }
  5009. else {
  5010. clsPrototype.config = {};
  5011. }
  5012. //</feature>
  5013. //<feature classSystem.onClassExtended>
  5014. if (clsPrototype.$onExtended) {
  5015. clsPrototype.$onExtended.call(cls, cls, data);
  5016. }
  5017. if (data.onClassExtended) {
  5018. clsPrototype.$onExtended = data.onClassExtended;
  5019. delete data.onClassExtended;
  5020. }
  5021. //</feature>
  5022. }, true);
  5023. //<feature classSystem.statics>
  5024. /**
  5025. * @cfg {Object} statics
  5026. * List of static methods for this class. For example:
  5027. *
  5028. * Ext.define('Computer', {
  5029. * statics: {
  5030. * factory: function(brand) {
  5031. * // 'this' in static methods refer to the class itself
  5032. * return new this(brand);
  5033. * }
  5034. * },
  5035. *
  5036. * constructor: function() { ... }
  5037. * });
  5038. *
  5039. * var dellComputer = Computer.factory('Dell');
  5040. */
  5041. Class.registerPreprocessor('statics', function(cls, data) {
  5042. cls.addStatics(data.statics);
  5043. delete data.statics;
  5044. });
  5045. //</feature>
  5046. //<feature classSystem.inheritableStatics>
  5047. /**
  5048. * @cfg {Object} inheritableStatics
  5049. * List of inheritable static methods for this class.
  5050. * Otherwise just like {@link #statics} but subclasses inherit these methods.
  5051. */
  5052. Class.registerPreprocessor('inheritableStatics', function(cls, data) {
  5053. cls.addInheritableStatics(data.inheritableStatics);
  5054. delete data.inheritableStatics;
  5055. });
  5056. //</feature>
  5057. //<feature classSystem.config>
  5058. /**
  5059. * @cfg {Object} config
  5060. * List of configuration options with their default values, for which automatically
  5061. * accessor methods are generated. For example:
  5062. *
  5063. * Ext.define('SmartPhone', {
  5064. * config: {
  5065. * hasTouchScreen: false,
  5066. * operatingSystem: 'Other',
  5067. * price: 500
  5068. * },
  5069. * constructor: function(cfg) {
  5070. * this.initConfig(cfg);
  5071. * }
  5072. * });
  5073. *
  5074. * var iPhone = new SmartPhone({
  5075. * hasTouchScreen: true,
  5076. * operatingSystem: 'iOS'
  5077. * });
  5078. *
  5079. * iPhone.getPrice(); // 500;
  5080. * iPhone.getOperatingSystem(); // 'iOS'
  5081. * iPhone.getHasTouchScreen(); // true;
  5082. * iPhone.hasTouchScreen(); // true
  5083. */
  5084. Class.registerPreprocessor('config', function(cls, data) {
  5085. var prototype = cls.prototype;
  5086. Ext.Object.each(data.config, function(name) {
  5087. var cName = name.charAt(0).toUpperCase() + name.substr(1),
  5088. pName = name,
  5089. apply = 'apply' + cName,
  5090. setter = 'set' + cName,
  5091. getter = 'get' + cName;
  5092. if (!(apply in prototype) && !data.hasOwnProperty(apply)) {
  5093. data[apply] = function(val) {
  5094. return val;
  5095. };
  5096. }
  5097. if (!(setter in prototype) && !data.hasOwnProperty(setter)) {
  5098. data[setter] = function(val) {
  5099. var ret = this[apply].call(this, val, this[pName]);
  5100. if (typeof ret != 'undefined') {
  5101. this[pName] = ret;
  5102. }
  5103. return this;
  5104. };
  5105. }
  5106. if (!(getter in prototype) && !data.hasOwnProperty(getter)) {
  5107. data[getter] = function() {
  5108. return this[pName];
  5109. };
  5110. }
  5111. });
  5112. Ext.Object.merge(prototype.config, data.config);
  5113. delete data.config;
  5114. });
  5115. //</feature>
  5116. //<feature classSystem.mixins>
  5117. /**
  5118. * @cfg {Object} mixins
  5119. * List of classes to mix into this class. For example:
  5120. *
  5121. * Ext.define('CanSing', {
  5122. * sing: function() {
  5123. * alert("I'm on the highway to hell...")
  5124. * }
  5125. * });
  5126. *
  5127. * Ext.define('Musician', {
  5128. * extend: 'Person',
  5129. *
  5130. * mixins: {
  5131. * canSing: 'CanSing'
  5132. * }
  5133. * })
  5134. */
  5135. Class.registerPreprocessor('mixins', function(cls, data) {
  5136. var mixins = data.mixins,
  5137. name, mixin, i, ln;
  5138. delete data.mixins;
  5139. Ext.Function.interceptBefore(data, 'onClassCreated', function(cls) {
  5140. if (mixins instanceof Array) {
  5141. for (i = 0,ln = mixins.length; i < ln; i++) {
  5142. mixin = mixins[i];
  5143. name = mixin.prototype.mixinId || mixin.$className;
  5144. cls.mixin(name, mixin);
  5145. }
  5146. }
  5147. else {
  5148. for (name in mixins) {
  5149. if (mixins.hasOwnProperty(name)) {
  5150. cls.mixin(name, mixins[name]);
  5151. }
  5152. }
  5153. }
  5154. });
  5155. });
  5156. //</feature>
  5157. Class.setDefaultPreprocessors([
  5158. 'extend'
  5159. //<feature classSystem.statics>
  5160. ,'statics'
  5161. //</feature>
  5162. //<feature classSystem.inheritableStatics>
  5163. ,'inheritableStatics'
  5164. //</feature>
  5165. //<feature classSystem.config>
  5166. ,'config'
  5167. //</feature>
  5168. //<feature classSystem.mixins>
  5169. ,'mixins'
  5170. //</feature>
  5171. ]);
  5172. //<feature classSystem.backwardsCompatible>
  5173. // Backwards compatible
  5174. Ext.extend = function(subclass, superclass, members) {
  5175. if (arguments.length === 2 && Ext.isObject(superclass)) {
  5176. members = superclass;
  5177. superclass = subclass;
  5178. subclass = null;
  5179. }
  5180. var cls;
  5181. if (!superclass) {
  5182. Ext.Error.raise("Attempting to extend from a class which has not been loaded on the page.");
  5183. }
  5184. members.extend = superclass;
  5185. members.preprocessors = [
  5186. 'extend'
  5187. //<feature classSystem.statics>
  5188. ,'statics'
  5189. //</feature>
  5190. //<feature classSystem.inheritableStatics>
  5191. ,'inheritableStatics'
  5192. //</feature>
  5193. //<feature classSystem.mixins>
  5194. ,'mixins'
  5195. //</feature>
  5196. //<feature classSystem.config>
  5197. ,'config'
  5198. //</feature>
  5199. ];
  5200. if (subclass) {
  5201. cls = new Class(subclass, members);
  5202. }
  5203. else {
  5204. cls = new Class(members);
  5205. }
  5206. cls.prototype.override = function(o) {
  5207. for (var m in o) {
  5208. if (o.hasOwnProperty(m)) {
  5209. this[m] = o[m];
  5210. }
  5211. }
  5212. };
  5213. return cls;
  5214. };
  5215. //</feature>
  5216. })();
  5217. /**
  5218. * @author Jacky Nguyen <jacky@sencha.com>
  5219. * @docauthor Jacky Nguyen <jacky@sencha.com>
  5220. * @class Ext.ClassManager
  5221. *
  5222. * Ext.ClassManager manages all classes and handles mapping from string class name to
  5223. * actual class objects throughout the whole framework. It is not generally accessed directly, rather through
  5224. * these convenient shorthands:
  5225. *
  5226. * - {@link Ext#define Ext.define}
  5227. * - {@link Ext#create Ext.create}
  5228. * - {@link Ext#widget Ext.widget}
  5229. * - {@link Ext#getClass Ext.getClass}
  5230. * - {@link Ext#getClassName Ext.getClassName}
  5231. *
  5232. * # Basic syntax:
  5233. *
  5234. * Ext.define(className, properties);
  5235. *
  5236. * in which `properties` is an object represent a collection of properties that apply to the class. See
  5237. * {@link Ext.ClassManager#create} for more detailed instructions.
  5238. *
  5239. * Ext.define('Person', {
  5240. * name: 'Unknown',
  5241. *
  5242. * constructor: function(name) {
  5243. * if (name) {
  5244. * this.name = name;
  5245. * }
  5246. *
  5247. * return this;
  5248. * },
  5249. *
  5250. * eat: function(foodType) {
  5251. * alert("I'm eating: " + foodType);
  5252. *
  5253. * return this;
  5254. * }
  5255. * });
  5256. *
  5257. * var aaron = new Person("Aaron");
  5258. * aaron.eat("Sandwich"); // alert("I'm eating: Sandwich");
  5259. *
  5260. * Ext.Class has a powerful set of extensible {@link Ext.Class#registerPreprocessor pre-processors} which takes care of
  5261. * everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc.
  5262. *
  5263. * # Inheritance:
  5264. *
  5265. * Ext.define('Developer', {
  5266. * extend: 'Person',
  5267. *
  5268. * constructor: function(name, isGeek) {
  5269. * this.isGeek = isGeek;
  5270. *
  5271. * // Apply a method from the parent class' prototype
  5272. * this.callParent([name]);
  5273. *
  5274. * return this;
  5275. *
  5276. * },
  5277. *
  5278. * code: function(language) {
  5279. * alert("I'm coding in: " + language);
  5280. *
  5281. * this.eat("Bugs");
  5282. *
  5283. * return this;
  5284. * }
  5285. * });
  5286. *
  5287. * var jacky = new Developer("Jacky", true);
  5288. * jacky.code("JavaScript"); // alert("I'm coding in: JavaScript");
  5289. * // alert("I'm eating: Bugs");
  5290. *
  5291. * See {@link Ext.Base#callParent} for more details on calling superclass' methods
  5292. *
  5293. * # Mixins:
  5294. *
  5295. * Ext.define('CanPlayGuitar', {
  5296. * playGuitar: function() {
  5297. * alert("F#...G...D...A");
  5298. * }
  5299. * });
  5300. *
  5301. * Ext.define('CanComposeSongs', {
  5302. * composeSongs: function() { ... }
  5303. * });
  5304. *
  5305. * Ext.define('CanSing', {
  5306. * sing: function() {
  5307. * alert("I'm on the highway to hell...")
  5308. * }
  5309. * });
  5310. *
  5311. * Ext.define('Musician', {
  5312. * extend: 'Person',
  5313. *
  5314. * mixins: {
  5315. * canPlayGuitar: 'CanPlayGuitar',
  5316. * canComposeSongs: 'CanComposeSongs',
  5317. * canSing: 'CanSing'
  5318. * }
  5319. * })
  5320. *
  5321. * Ext.define('CoolPerson', {
  5322. * extend: 'Person',
  5323. *
  5324. * mixins: {
  5325. * canPlayGuitar: 'CanPlayGuitar',
  5326. * canSing: 'CanSing'
  5327. * },
  5328. *
  5329. * sing: function() {
  5330. * alert("Ahem....");
  5331. *
  5332. * this.mixins.canSing.sing.call(this);
  5333. *
  5334. * alert("[Playing guitar at the same time...]");
  5335. *
  5336. * this.playGuitar();
  5337. * }
  5338. * });
  5339. *
  5340. * var me = new CoolPerson("Jacky");
  5341. *
  5342. * me.sing(); // alert("Ahem...");
  5343. * // alert("I'm on the highway to hell...");
  5344. * // alert("[Playing guitar at the same time...]");
  5345. * // alert("F#...G...D...A");
  5346. *
  5347. * # Config:
  5348. *
  5349. * Ext.define('SmartPhone', {
  5350. * config: {
  5351. * hasTouchScreen: false,
  5352. * operatingSystem: 'Other',
  5353. * price: 500
  5354. * },
  5355. *
  5356. * isExpensive: false,
  5357. *
  5358. * constructor: function(config) {
  5359. * this.initConfig(config);
  5360. *
  5361. * return this;
  5362. * },
  5363. *
  5364. * applyPrice: function(price) {
  5365. * this.isExpensive = (price > 500);
  5366. *
  5367. * return price;
  5368. * },
  5369. *
  5370. * applyOperatingSystem: function(operatingSystem) {
  5371. * if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) {
  5372. * return 'Other';
  5373. * }
  5374. *
  5375. * return operatingSystem;
  5376. * }
  5377. * });
  5378. *
  5379. * var iPhone = new SmartPhone({
  5380. * hasTouchScreen: true,
  5381. * operatingSystem: 'iOS'
  5382. * });
  5383. *
  5384. * iPhone.getPrice(); // 500;
  5385. * iPhone.getOperatingSystem(); // 'iOS'
  5386. * iPhone.getHasTouchScreen(); // true;
  5387. * iPhone.hasTouchScreen(); // true
  5388. *
  5389. * iPhone.isExpensive; // false;
  5390. * iPhone.setPrice(600);
  5391. * iPhone.getPrice(); // 600
  5392. * iPhone.isExpensive; // true;
  5393. *
  5394. * iPhone.setOperatingSystem('AlienOS');
  5395. * iPhone.getOperatingSystem(); // 'Other'
  5396. *
  5397. * # Statics:
  5398. *
  5399. * Ext.define('Computer', {
  5400. * statics: {
  5401. * factory: function(brand) {
  5402. * // 'this' in static methods refer to the class itself
  5403. * return new this(brand);
  5404. * }
  5405. * },
  5406. *
  5407. * constructor: function() { ... }
  5408. * });
  5409. *
  5410. * var dellComputer = Computer.factory('Dell');
  5411. *
  5412. * Also see {@link Ext.Base#statics} and {@link Ext.Base#self} for more details on accessing
  5413. * static properties within class methods
  5414. *
  5415. * @singleton
  5416. */
  5417. (function(Class, alias) {
  5418. var slice = Array.prototype.slice;
  5419. var Manager = Ext.ClassManager = {
  5420. /**
  5421. * @property {Object} classes
  5422. * All classes which were defined through the ClassManager. Keys are the
  5423. * name of the classes and the values are references to the classes.
  5424. * @private
  5425. */
  5426. classes: {},
  5427. /**
  5428. * @private
  5429. */
  5430. existCache: {},
  5431. /**
  5432. * @private
  5433. */
  5434. namespaceRewrites: [{
  5435. from: 'Ext.',
  5436. to: Ext
  5437. }],
  5438. /**
  5439. * @private
  5440. */
  5441. maps: {
  5442. alternateToName: {},
  5443. aliasToName: {},
  5444. nameToAliases: {}
  5445. },
  5446. /** @private */
  5447. enableNamespaceParseCache: true,
  5448. /** @private */
  5449. namespaceParseCache: {},
  5450. /** @private */
  5451. instantiators: [],
  5452. /**
  5453. * Checks if a class has already been created.
  5454. *
  5455. * @param {String} className
  5456. * @return {Boolean} exist
  5457. */
  5458. isCreated: function(className) {
  5459. var i, ln, part, root, parts;
  5460. if (this.classes.hasOwnProperty(className) || this.existCache.hasOwnProperty(className)) {
  5461. return true;
  5462. }
  5463. root = Ext.global;
  5464. parts = this.parseNamespace(className);
  5465. for (i = 0, ln = parts.length; i < ln; i++) {
  5466. part = parts[i];
  5467. if (typeof part !== 'string') {
  5468. root = part;
  5469. } else {
  5470. if (!root || !root[part]) {
  5471. return false;
  5472. }
  5473. root = root[part];
  5474. }
  5475. }
  5476. Ext.Loader.historyPush(className);
  5477. this.existCache[className] = true;
  5478. return true;
  5479. },
  5480. /**
  5481. * Supports namespace rewriting
  5482. * @private
  5483. */
  5484. parseNamespace: function(namespace) {
  5485. var cache = this.namespaceParseCache;
  5486. if (this.enableNamespaceParseCache) {
  5487. if (cache.hasOwnProperty(namespace)) {
  5488. return cache[namespace];
  5489. }
  5490. }
  5491. var parts = [],
  5492. rewrites = this.namespaceRewrites,
  5493. rewrite, from, to, i, ln, root = Ext.global;
  5494. for (i = 0, ln = rewrites.length; i < ln; i++) {
  5495. rewrite = rewrites[i];
  5496. from = rewrite.from;
  5497. to = rewrite.to;
  5498. if (namespace === from || namespace.substring(0, from.length) === from) {
  5499. namespace = namespace.substring(from.length);
  5500. if (typeof to !== 'string') {
  5501. root = to;
  5502. } else {
  5503. parts = parts.concat(to.split('.'));
  5504. }
  5505. break;
  5506. }
  5507. }
  5508. parts.push(root);
  5509. parts = parts.concat(namespace.split('.'));
  5510. if (this.enableNamespaceParseCache) {
  5511. cache[namespace] = parts;
  5512. }
  5513. return parts;
  5514. },
  5515. /**
  5516. * Creates a namespace and assign the `value` to the created object
  5517. *
  5518. * Ext.ClassManager.setNamespace('MyCompany.pkg.Example', someObject);
  5519. *
  5520. * alert(MyCompany.pkg.Example === someObject); // alerts true
  5521. *
  5522. * @param {String} name
  5523. * @param {Object} value
  5524. */
  5525. setNamespace: function(name, value) {
  5526. var root = Ext.global,
  5527. parts = this.parseNamespace(name),
  5528. ln = parts.length - 1,
  5529. leaf = parts[ln],
  5530. i, part;
  5531. for (i = 0; i < ln; i++) {
  5532. part = parts[i];
  5533. if (typeof part !== 'string') {
  5534. root = part;
  5535. } else {
  5536. if (!root[part]) {
  5537. root[part] = {};
  5538. }
  5539. root = root[part];
  5540. }
  5541. }
  5542. root[leaf] = value;
  5543. return root[leaf];
  5544. },
  5545. /**
  5546. * The new Ext.ns, supports namespace rewriting
  5547. * @private
  5548. */
  5549. createNamespaces: function() {
  5550. var root = Ext.global,
  5551. parts, part, i, j, ln, subLn;
  5552. for (i = 0, ln = arguments.length; i < ln; i++) {
  5553. parts = this.parseNamespace(arguments[i]);
  5554. for (j = 0, subLn = parts.length; j < subLn; j++) {
  5555. part = parts[j];
  5556. if (typeof part !== 'string') {
  5557. root = part;
  5558. } else {
  5559. if (!root[part]) {
  5560. root[part] = {};
  5561. }
  5562. root = root[part];
  5563. }
  5564. }
  5565. }
  5566. return root;
  5567. },
  5568. /**
  5569. * Sets a name reference to a class.
  5570. *
  5571. * @param {String} name
  5572. * @param {Object} value
  5573. * @return {Ext.ClassManager} this
  5574. */
  5575. set: function(name, value) {
  5576. var targetName = this.getName(value);
  5577. this.classes[name] = this.setNamespace(name, value);
  5578. if (targetName && targetName !== name) {
  5579. this.maps.alternateToName[name] = targetName;
  5580. }
  5581. return this;
  5582. },
  5583. /**
  5584. * Retrieve a class by its name.
  5585. *
  5586. * @param {String} name
  5587. * @return {Ext.Class} class
  5588. */
  5589. get: function(name) {
  5590. if (this.classes.hasOwnProperty(name)) {
  5591. return this.classes[name];
  5592. }
  5593. var root = Ext.global,
  5594. parts = this.parseNamespace(name),
  5595. part, i, ln;
  5596. for (i = 0, ln = parts.length; i < ln; i++) {
  5597. part = parts[i];
  5598. if (typeof part !== 'string') {
  5599. root = part;
  5600. } else {
  5601. if (!root || !root[part]) {
  5602. return null;
  5603. }
  5604. root = root[part];
  5605. }
  5606. }
  5607. return root;
  5608. },
  5609. /**
  5610. * Register the alias for a class.
  5611. *
  5612. * @param {Ext.Class/String} cls a reference to a class or a className
  5613. * @param {String} alias Alias to use when referring to this class
  5614. */
  5615. setAlias: function(cls, alias) {
  5616. var aliasToNameMap = this.maps.aliasToName,
  5617. nameToAliasesMap = this.maps.nameToAliases,
  5618. className;
  5619. if (typeof cls === 'string') {
  5620. className = cls;
  5621. } else {
  5622. className = this.getName(cls);
  5623. }
  5624. if (alias && aliasToNameMap[alias] !== className) {
  5625. aliasToNameMap[alias] = className;
  5626. }
  5627. if (!nameToAliasesMap[className]) {
  5628. nameToAliasesMap[className] = [];
  5629. }
  5630. if (alias) {
  5631. Ext.Array.include(nameToAliasesMap[className], alias);
  5632. }
  5633. return this;
  5634. },
  5635. /**
  5636. * Get a reference to the class by its alias.
  5637. *
  5638. * @param {String} alias
  5639. * @return {Ext.Class} class
  5640. */
  5641. getByAlias: function(alias) {
  5642. return this.get(this.getNameByAlias(alias));
  5643. },
  5644. /**
  5645. * Get the name of a class by its alias.
  5646. *
  5647. * @param {String} alias
  5648. * @return {String} className
  5649. */
  5650. getNameByAlias: function(alias) {
  5651. return this.maps.aliasToName[alias] || '';
  5652. },
  5653. /**
  5654. * Get the name of a class by its alternate name.
  5655. *
  5656. * @param {String} alternate
  5657. * @return {String} className
  5658. */
  5659. getNameByAlternate: function(alternate) {
  5660. return this.maps.alternateToName[alternate] || '';
  5661. },
  5662. /**
  5663. * Get the aliases of a class by the class name
  5664. *
  5665. * @param {String} name
  5666. * @return {String[]} aliases
  5667. */
  5668. getAliasesByName: function(name) {
  5669. return this.maps.nameToAliases[name] || [];
  5670. },
  5671. /**
  5672. * Get the name of the class by its reference or its instance.
  5673. *
  5674. * Ext.ClassManager.getName(Ext.Action); // returns "Ext.Action"
  5675. *
  5676. * {@link Ext#getClassName Ext.getClassName} is alias for {@link Ext.ClassManager#getName Ext.ClassManager.getName}.
  5677. *
  5678. * @param {Ext.Class/Object} object
  5679. * @return {String} className
  5680. */
  5681. getName: function(object) {
  5682. return object && object.$className || '';
  5683. },
  5684. /**
  5685. * Get the class of the provided object; returns null if it's not an instance
  5686. * of any class created with Ext.define.
  5687. *
  5688. * var component = new Ext.Component();
  5689. *
  5690. * Ext.ClassManager.getClass(component); // returns Ext.Component
  5691. *
  5692. * {@link Ext#getClass Ext.getClass} is alias for {@link Ext.ClassManager#getClass Ext.ClassManager.getClass}.
  5693. *
  5694. * @param {Object} object
  5695. * @return {Ext.Class} class
  5696. */
  5697. getClass: function(object) {
  5698. return object && object.self || null;
  5699. },
  5700. /**
  5701. * Defines a class.
  5702. *
  5703. * {@link Ext#define Ext.define} and {@link Ext.ClassManager#create Ext.ClassManager.create} are almost aliases
  5704. * of each other, with the only exception that Ext.define allows definition of {@link Ext.Class#override overrides}.
  5705. * To avoid trouble, always use Ext.define.
  5706. *
  5707. * Ext.define('My.awesome.Class', {
  5708. * someProperty: 'something',
  5709. * someMethod: function() { ... }
  5710. * ...
  5711. *
  5712. * }, function() {
  5713. * alert('Created!');
  5714. * alert(this === My.awesome.Class); // alerts true
  5715. *
  5716. * var myInstance = new this();
  5717. * });
  5718. *
  5719. * @param {String} className The class name to create in string dot-namespaced format, for example:
  5720. * `My.very.awesome.Class`, `FeedViewer.plugin.CoolPager`. It is highly recommended to follow this simple convention:
  5721. *
  5722. * - The root and the class name are 'CamelCased'
  5723. * - Everything else is lower-cased
  5724. *
  5725. * @param {Object} data The key-value pairs of properties to apply to this class. Property names can be of any valid
  5726. * strings, except those in the reserved list below:
  5727. *
  5728. * - {@link Ext.Base#self self}
  5729. * - {@link Ext.Class#alias alias}
  5730. * - {@link Ext.Class#alternateClassName alternateClassName}
  5731. * - {@link Ext.Class#config config}
  5732. * - {@link Ext.Class#extend extend}
  5733. * - {@link Ext.Class#inheritableStatics inheritableStatics}
  5734. * - {@link Ext.Class#mixins mixins}
  5735. * - {@link Ext.Class#override override} (only when using {@link Ext#define Ext.define})
  5736. * - {@link Ext.Class#requires requires}
  5737. * - {@link Ext.Class#singleton singleton}
  5738. * - {@link Ext.Class#statics statics}
  5739. * - {@link Ext.Class#uses uses}
  5740. *
  5741. * @param {Function} [createdFn] callback to execute after the class is created, the execution scope of which
  5742. * (`this`) will be the newly created class itself.
  5743. *
  5744. * @return {Ext.Base}
  5745. */
  5746. create: function(className, data, createdFn) {
  5747. var manager = this;
  5748. data.$className = className;
  5749. return new Class(data, function() {
  5750. var postprocessorStack = data.postprocessors || manager.defaultPostprocessors,
  5751. registeredPostprocessors = manager.postprocessors,
  5752. index = 0,
  5753. postprocessors = [],
  5754. postprocessor, process, i, ln;
  5755. delete data.postprocessors;
  5756. for (i = 0, ln = postprocessorStack.length; i < ln; i++) {
  5757. postprocessor = postprocessorStack[i];
  5758. if (typeof postprocessor === 'string') {
  5759. postprocessor = registeredPostprocessors[postprocessor];
  5760. if (!postprocessor.always) {
  5761. if (data[postprocessor.name] !== undefined) {
  5762. postprocessors.push(postprocessor.fn);
  5763. }
  5764. }
  5765. else {
  5766. postprocessors.push(postprocessor.fn);
  5767. }
  5768. }
  5769. else {
  5770. postprocessors.push(postprocessor);
  5771. }
  5772. }
  5773. process = function(clsName, cls, clsData) {
  5774. postprocessor = postprocessors[index++];
  5775. if (!postprocessor) {
  5776. manager.set(className, cls);
  5777. Ext.Loader.historyPush(className);
  5778. if (createdFn) {
  5779. createdFn.call(cls, cls);
  5780. }
  5781. return;
  5782. }
  5783. if (postprocessor.call(this, clsName, cls, clsData, process) !== false) {
  5784. process.apply(this, arguments);
  5785. }
  5786. };
  5787. process.call(manager, className, this, data);
  5788. });
  5789. },
  5790. /**
  5791. * Instantiate a class by its alias.
  5792. *
  5793. * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
  5794. * attempt to load the class via synchronous loading.
  5795. *
  5796. * var window = Ext.ClassManager.instantiateByAlias('widget.window', { width: 600, height: 800, ... });
  5797. *
  5798. * {@link Ext#createByAlias Ext.createByAlias} is alias for {@link Ext.ClassManager#instantiateByAlias Ext.ClassManager.instantiateByAlias}.
  5799. *
  5800. * @param {String} alias
  5801. * @param {Object...} args Additional arguments after the alias will be passed to the
  5802. * class constructor.
  5803. * @return {Object} instance
  5804. */
  5805. instantiateByAlias: function() {
  5806. var alias = arguments[0],
  5807. args = slice.call(arguments),
  5808. className = this.getNameByAlias(alias);
  5809. if (!className) {
  5810. className = this.maps.aliasToName[alias];
  5811. Ext.syncRequire(className);
  5812. }
  5813. args[0] = className;
  5814. return this.instantiate.apply(this, args);
  5815. },
  5816. /**
  5817. * Instantiate a class by either full name, alias or alternate name.
  5818. *
  5819. * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
  5820. * attempt to load the class via synchronous loading.
  5821. *
  5822. * For example, all these three lines return the same result:
  5823. *
  5824. * // alias
  5825. * var window = Ext.ClassManager.instantiate('widget.window', { width: 600, height: 800, ... });
  5826. *
  5827. * // alternate name
  5828. * var window = Ext.ClassManager.instantiate('Ext.Window', { width: 600, height: 800, ... });
  5829. *
  5830. * // full class name
  5831. * var window = Ext.ClassManager.instantiate('Ext.window.Window', { width: 600, height: 800, ... });
  5832. *
  5833. * {@link Ext#create Ext.create} is alias for {@link Ext.ClassManager#instantiate Ext.ClassManager.instantiate}.
  5834. *
  5835. * @param {String} name
  5836. * @param {Object...} args Additional arguments after the name will be passed to the class' constructor.
  5837. * @return {Object} instance
  5838. */
  5839. instantiate: function() {
  5840. var name = arguments[0],
  5841. args = slice.call(arguments, 1),
  5842. alias = name,
  5843. possibleName, cls;
  5844. if (typeof name !== 'function') {
  5845. cls = this.get(name);
  5846. }
  5847. else {
  5848. cls = name;
  5849. }
  5850. // No record of this class name, it's possibly an alias, so look it up
  5851. if (!cls) {
  5852. possibleName = this.getNameByAlias(name);
  5853. if (possibleName) {
  5854. name = possibleName;
  5855. cls = this.get(name);
  5856. }
  5857. }
  5858. // Still no record of this class name, it's possibly an alternate name, so look it up
  5859. if (!cls) {
  5860. possibleName = this.getNameByAlternate(name);
  5861. if (possibleName) {
  5862. name = possibleName;
  5863. cls = this.get(name);
  5864. }
  5865. }
  5866. // Still not existing at this point, try to load it via synchronous mode as the last resort
  5867. if (!cls) {
  5868. Ext.syncRequire(name);
  5869. cls = this.get(name);
  5870. }
  5871. return this.getInstantiator(args.length)(cls, args);
  5872. },
  5873. /**
  5874. * @private
  5875. * @param name
  5876. * @param args
  5877. */
  5878. dynInstantiate: function(name, args) {
  5879. args = Ext.Array.from(args, true);
  5880. args.unshift(name);
  5881. return this.instantiate.apply(this, args);
  5882. },
  5883. /**
  5884. * @private
  5885. * @param length
  5886. */
  5887. getInstantiator: function(length) {
  5888. if (!this.instantiators[length]) {
  5889. var i = length,
  5890. args = [];
  5891. for (i = 0; i < length; i++) {
  5892. args.push('a['+i+']');
  5893. }
  5894. this.instantiators[length] = new Function('c', 'a', 'return new c('+args.join(',')+')');
  5895. }
  5896. return this.instantiators[length];
  5897. },
  5898. /**
  5899. * @private
  5900. */
  5901. postprocessors: {},
  5902. /**
  5903. * @private
  5904. */
  5905. defaultPostprocessors: [],
  5906. /**
  5907. * Register a post-processor function.
  5908. *
  5909. * @param {String} name
  5910. * @param {Function} postprocessor
  5911. */
  5912. registerPostprocessor: function(name, fn, always) {
  5913. this.postprocessors[name] = {
  5914. name: name,
  5915. always: always || false,
  5916. fn: fn
  5917. };
  5918. return this;
  5919. },
  5920. /**
  5921. * Set the default post processors array stack which are applied to every class.
  5922. *
  5923. * @param {String/String[]} The name of a registered post processor or an array of registered names.
  5924. * @return {Ext.ClassManager} this
  5925. */
  5926. setDefaultPostprocessors: function(postprocessors) {
  5927. this.defaultPostprocessors = Ext.Array.from(postprocessors);
  5928. return this;
  5929. },
  5930. /**
  5931. * Insert this post-processor at a specific position in the stack, optionally relative to
  5932. * any existing post-processor
  5933. *
  5934. * @param {String} name The post-processor name. Note that it needs to be registered with
  5935. * {@link Ext.ClassManager#registerPostprocessor} before this
  5936. * @param {String} offset The insertion position. Four possible values are:
  5937. * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
  5938. * @param {String} relativeName
  5939. * @return {Ext.ClassManager} this
  5940. */
  5941. setDefaultPostprocessorPosition: function(name, offset, relativeName) {
  5942. var defaultPostprocessors = this.defaultPostprocessors,
  5943. index;
  5944. if (typeof offset === 'string') {
  5945. if (offset === 'first') {
  5946. defaultPostprocessors.unshift(name);
  5947. return this;
  5948. }
  5949. else if (offset === 'last') {
  5950. defaultPostprocessors.push(name);
  5951. return this;
  5952. }
  5953. offset = (offset === 'after') ? 1 : -1;
  5954. }
  5955. index = Ext.Array.indexOf(defaultPostprocessors, relativeName);
  5956. if (index !== -1) {
  5957. Ext.Array.splice(defaultPostprocessors, Math.max(0, index + offset), 0, name);
  5958. }
  5959. return this;
  5960. },
  5961. /**
  5962. * Converts a string expression to an array of matching class names. An expression can either refers to class aliases
  5963. * or class names. Expressions support wildcards:
  5964. *
  5965. * // returns ['Ext.window.Window']
  5966. * var window = Ext.ClassManager.getNamesByExpression('widget.window');
  5967. *
  5968. * // returns ['widget.panel', 'widget.window', ...]
  5969. * var allWidgets = Ext.ClassManager.getNamesByExpression('widget.*');
  5970. *
  5971. * // returns ['Ext.data.Store', 'Ext.data.ArrayProxy', ...]
  5972. * var allData = Ext.ClassManager.getNamesByExpression('Ext.data.*');
  5973. *
  5974. * @param {String} expression
  5975. * @return {String[]} classNames
  5976. */
  5977. getNamesByExpression: function(expression) {
  5978. var nameToAliasesMap = this.maps.nameToAliases,
  5979. names = [],
  5980. name, alias, aliases, possibleName, regex, i, ln;
  5981. if (expression.indexOf('*') !== -1) {
  5982. expression = expression.replace(/\*/g, '(.*?)');
  5983. regex = new RegExp('^' + expression + '$');
  5984. for (name in nameToAliasesMap) {
  5985. if (nameToAliasesMap.hasOwnProperty(name)) {
  5986. aliases = nameToAliasesMap[name];
  5987. if (name.search(regex) !== -1) {
  5988. names.push(name);
  5989. }
  5990. else {
  5991. for (i = 0, ln = aliases.length; i < ln; i++) {
  5992. alias = aliases[i];
  5993. if (alias.search(regex) !== -1) {
  5994. names.push(name);
  5995. break;
  5996. }
  5997. }
  5998. }
  5999. }
  6000. }
  6001. } else {
  6002. possibleName = this.getNameByAlias(expression);
  6003. if (possibleName) {
  6004. names.push(possibleName);
  6005. } else {
  6006. possibleName = this.getNameByAlternate(expression);
  6007. if (possibleName) {
  6008. names.push(possibleName);
  6009. } else {
  6010. names.push(expression);
  6011. }
  6012. }
  6013. }
  6014. return names;
  6015. }
  6016. };
  6017. var defaultPostprocessors = Manager.defaultPostprocessors;
  6018. //<feature classSystem.alias>
  6019. /**
  6020. * @cfg {String[]} alias
  6021. * @member Ext.Class
  6022. * List of short aliases for class names. Most useful for defining xtypes for widgets:
  6023. *
  6024. * Ext.define('MyApp.CoolPanel', {
  6025. * extend: 'Ext.panel.Panel',
  6026. * alias: ['widget.coolpanel'],
  6027. * title: 'Yeah!'
  6028. * });
  6029. *
  6030. * // Using Ext.create
  6031. * Ext.widget('widget.coolpanel');
  6032. * // Using the shorthand for widgets and in xtypes
  6033. * Ext.widget('panel', {
  6034. * items: [
  6035. * {xtype: 'coolpanel', html: 'Foo'},
  6036. * {xtype: 'coolpanel', html: 'Bar'}
  6037. * ]
  6038. * });
  6039. */
  6040. Manager.registerPostprocessor('alias', function(name, cls, data) {
  6041. var aliases = data.alias,
  6042. i, ln;
  6043. delete data.alias;
  6044. for (i = 0, ln = aliases.length; i < ln; i++) {
  6045. alias = aliases[i];
  6046. this.setAlias(cls, alias);
  6047. }
  6048. });
  6049. /**
  6050. * @cfg {Boolean} singleton
  6051. * @member Ext.Class
  6052. * When set to true, the class will be instantiated as singleton. For example:
  6053. *
  6054. * Ext.define('Logger', {
  6055. * singleton: true,
  6056. * log: function(msg) {
  6057. * console.log(msg);
  6058. * }
  6059. * });
  6060. *
  6061. * Logger.log('Hello');
  6062. */
  6063. Manager.registerPostprocessor('singleton', function(name, cls, data, fn) {
  6064. fn.call(this, name, new cls(), data);
  6065. return false;
  6066. });
  6067. /**
  6068. * @cfg {String/String[]} alternateClassName
  6069. * @member Ext.Class
  6070. * Defines alternate names for this class. For example:
  6071. *
  6072. * Ext.define('Developer', {
  6073. * alternateClassName: ['Coder', 'Hacker'],
  6074. * code: function(msg) {
  6075. * alert('Typing... ' + msg);
  6076. * }
  6077. * });
  6078. *
  6079. * var joe = Ext.create('Developer');
  6080. * joe.code('stackoverflow');
  6081. *
  6082. * var rms = Ext.create('Hacker');
  6083. * rms.code('hack hack');
  6084. */
  6085. Manager.registerPostprocessor('alternateClassName', function(name, cls, data) {
  6086. var alternates = data.alternateClassName,
  6087. i, ln, alternate;
  6088. if (!(alternates instanceof Array)) {
  6089. alternates = [alternates];
  6090. }
  6091. for (i = 0, ln = alternates.length; i < ln; i++) {
  6092. alternate = alternates[i];
  6093. this.set(alternate, cls);
  6094. }
  6095. });
  6096. Manager.setDefaultPostprocessors(['alias', 'singleton', 'alternateClassName']);
  6097. Ext.apply(Ext, {
  6098. /**
  6099. * @method
  6100. * @member Ext
  6101. * @alias Ext.ClassManager#instantiate
  6102. */
  6103. create: alias(Manager, 'instantiate'),
  6104. /**
  6105. * @private
  6106. * API to be stablized
  6107. *
  6108. * @param {Object} item
  6109. * @param {String} namespace
  6110. */
  6111. factory: function(item, namespace) {
  6112. if (item instanceof Array) {
  6113. var i, ln;
  6114. for (i = 0, ln = item.length; i < ln; i++) {
  6115. item[i] = Ext.factory(item[i], namespace);
  6116. }
  6117. return item;
  6118. }
  6119. var isString = (typeof item === 'string');
  6120. if (isString || (item instanceof Object && item.constructor === Object)) {
  6121. var name, config = {};
  6122. if (isString) {
  6123. name = item;
  6124. }
  6125. else {
  6126. name = item.className;
  6127. config = item;
  6128. delete config.className;
  6129. }
  6130. if (namespace !== undefined && name.indexOf(namespace) === -1) {
  6131. name = namespace + '.' + Ext.String.capitalize(name);
  6132. }
  6133. return Ext.create(name, config);
  6134. }
  6135. if (typeof item === 'function') {
  6136. return Ext.create(item);
  6137. }
  6138. return item;
  6139. },
  6140. /**
  6141. * Convenient shorthand to create a widget by its xtype, also see {@link Ext.ClassManager#instantiateByAlias}
  6142. *
  6143. * var button = Ext.widget('button'); // Equivalent to Ext.create('widget.button')
  6144. * var panel = Ext.widget('panel'); // Equivalent to Ext.create('widget.panel')
  6145. *
  6146. * @method
  6147. * @member Ext
  6148. * @param {String} name xtype of the widget to create.
  6149. * @param {Object...} args arguments for the widget constructor.
  6150. * @return {Object} widget instance
  6151. */
  6152. widget: function(name) {
  6153. var args = slice.call(arguments);
  6154. args[0] = 'widget.' + name;
  6155. return Manager.instantiateByAlias.apply(Manager, args);
  6156. },
  6157. /**
  6158. * @method
  6159. * @member Ext
  6160. * @alias Ext.ClassManager#instantiateByAlias
  6161. */
  6162. createByAlias: alias(Manager, 'instantiateByAlias'),
  6163. /**
  6164. * @cfg {String} override
  6165. * @member Ext.Class
  6166. *
  6167. * Defines an override applied to a class. Note that **overrides can only be created using
  6168. * {@link Ext#define}.** {@link Ext.ClassManager#create} only creates classes.
  6169. *
  6170. * To define an override, include the override property. The content of an override is
  6171. * aggregated with the specified class in order to extend or modify that class. This can be
  6172. * as simple as setting default property values or it can extend and/or replace methods.
  6173. * This can also extend the statics of the class.
  6174. *
  6175. * One use for an override is to break a large class into manageable pieces.
  6176. *
  6177. * // File: /src/app/Panel.js
  6178. *
  6179. * Ext.define('My.app.Panel', {
  6180. * extend: 'Ext.panel.Panel',
  6181. * requires: [
  6182. * 'My.app.PanelPart2',
  6183. * 'My.app.PanelPart3'
  6184. * ]
  6185. *
  6186. * constructor: function (config) {
  6187. * this.callSuper(arguments); // calls Ext.panel.Panel's constructor
  6188. * //...
  6189. * },
  6190. *
  6191. * statics: {
  6192. * method: function () {
  6193. * return 'abc';
  6194. * }
  6195. * }
  6196. * });
  6197. *
  6198. * // File: /src/app/PanelPart2.js
  6199. * Ext.define('My.app.PanelPart2', {
  6200. * override: 'My.app.Panel',
  6201. *
  6202. * constructor: function (config) {
  6203. * this.callSuper(arguments); // calls My.app.Panel's constructor
  6204. * //...
  6205. * }
  6206. * });
  6207. *
  6208. * Another use of overrides is to provide optional parts of classes that can be
  6209. * independently required. In this case, the class may even be unaware of the
  6210. * override altogether.
  6211. *
  6212. * Ext.define('My.ux.CoolTip', {
  6213. * override: 'Ext.tip.ToolTip',
  6214. *
  6215. * constructor: function (config) {
  6216. * this.callSuper(arguments); // calls Ext.tip.ToolTip's constructor
  6217. * //...
  6218. * }
  6219. * });
  6220. *
  6221. * The above override can now be required as normal.
  6222. *
  6223. * Ext.define('My.app.App', {
  6224. * requires: [
  6225. * 'My.ux.CoolTip'
  6226. * ]
  6227. * });
  6228. *
  6229. * Overrides can also contain statics:
  6230. *
  6231. * Ext.define('My.app.BarMod', {
  6232. * override: 'Ext.foo.Bar',
  6233. *
  6234. * statics: {
  6235. * method: function (x) {
  6236. * return this.callSuper([x * 2]); // call Ext.foo.Bar.method
  6237. * }
  6238. * }
  6239. * });
  6240. *
  6241. * IMPORTANT: An override is only included in a build if the class it overrides is
  6242. * required. Otherwise, the override, like the target class, is not included.
  6243. */
  6244. /**
  6245. * @method
  6246. *
  6247. * @member Ext
  6248. * @alias Ext.ClassManager#create
  6249. */
  6250. define: function (className, data, createdFn) {
  6251. if (!data.override) {
  6252. return Manager.create.apply(Manager, arguments);
  6253. }
  6254. var requires = data.requires,
  6255. uses = data.uses,
  6256. overrideName = className;
  6257. className = data.override;
  6258. // hoist any 'requires' or 'uses' from the body onto the faux class:
  6259. data = Ext.apply({}, data);
  6260. delete data.requires;
  6261. delete data.uses;
  6262. delete data.override;
  6263. // make sure className is in the requires list:
  6264. if (typeof requires == 'string') {
  6265. requires = [ className, requires ];
  6266. } else if (requires) {
  6267. requires = requires.slice(0);
  6268. requires.unshift(className);
  6269. } else {
  6270. requires = [ className ];
  6271. }
  6272. // TODO - we need to rework this to allow the override to not require the target class
  6273. // and rather 'wait' for it in such a way that if the target class is not in the build,
  6274. // neither are any of its overrides.
  6275. //
  6276. // Also, this should process the overrides for a class ASAP (ideally before any derived
  6277. // classes) if the target class 'requires' the overrides. Without some special handling, the
  6278. // overrides so required will be processed before the class and have to be bufferred even
  6279. // in a build.
  6280. //
  6281. // TODO - we should probably support the "config" processor on an override (to config new
  6282. // functionaliy like Aria) and maybe inheritableStatics (although static is now supported
  6283. // by callSuper). If inheritableStatics causes those statics to be included on derived class
  6284. // constructors, that probably means "no" to this since an override can come after other
  6285. // classes extend the target.
  6286. return Manager.create(overrideName, {
  6287. requires: requires,
  6288. uses: uses,
  6289. isPartial: true,
  6290. constructor: function () {
  6291. }
  6292. }, function () {
  6293. var cls = Manager.get(className);
  6294. if (cls.override) { // if (normal class)
  6295. cls.override(data);
  6296. } else { // else (singleton)
  6297. cls.self.override(data);
  6298. }
  6299. if (createdFn) {
  6300. // called once the override is applied and with the context of the
  6301. // overridden class (the override itself is a meaningless, name-only
  6302. // thing).
  6303. createdFn.call(cls);
  6304. }
  6305. });
  6306. },
  6307. /**
  6308. * @method
  6309. * @member Ext
  6310. * @alias Ext.ClassManager#getName
  6311. */
  6312. getClassName: alias(Manager, 'getName'),
  6313. /**
  6314. * Returns the displayName property or className or object.
  6315. * When all else fails, returns "Anonymous".
  6316. * @param {Object} object
  6317. * @return {String}
  6318. */
  6319. getDisplayName: function(object) {
  6320. if (object.displayName) {
  6321. return object.displayName;
  6322. }
  6323. if (object.$name && object.$class) {
  6324. return Ext.getClassName(object.$class) + '#' + object.$name;
  6325. }
  6326. if (object.$className) {
  6327. return object.$className;
  6328. }
  6329. return 'Anonymous';
  6330. },
  6331. /**
  6332. * @method
  6333. * @member Ext
  6334. * @alias Ext.ClassManager#getClass
  6335. */
  6336. getClass: alias(Manager, 'getClass'),
  6337. /**
  6338. * Creates namespaces to be used for scoping variables and classes so that they are not global.
  6339. * Specifying the last node of a namespace implicitly creates all other nodes. Usage:
  6340. *
  6341. * Ext.namespace('Company', 'Company.data');
  6342. *
  6343. * // equivalent and preferable to the above syntax
  6344. * Ext.namespace('Company.data');
  6345. *
  6346. * Company.Widget = function() { ... };
  6347. *
  6348. * Company.data.CustomStore = function(config) { ... };
  6349. *
  6350. * @method
  6351. * @member Ext
  6352. * @param {String} namespace1
  6353. * @param {String} namespace2
  6354. * @param {String} etc
  6355. * @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created)
  6356. */
  6357. namespace: alias(Manager, 'createNamespaces')
  6358. });
  6359. /**
  6360. * Old name for {@link Ext#widget}.
  6361. * @deprecated 4.0.0 Use {@link Ext#widget} instead.
  6362. * @method
  6363. * @member Ext
  6364. * @alias Ext#widget
  6365. */
  6366. Ext.createWidget = Ext.widget;
  6367. /**
  6368. * Convenient alias for {@link Ext#namespace Ext.namespace}
  6369. * @method
  6370. * @member Ext
  6371. * @alias Ext#namespace
  6372. */
  6373. Ext.ns = Ext.namespace;
  6374. Class.registerPreprocessor('className', function(cls, data) {
  6375. if (data.$className) {
  6376. cls.$className = data.$className;
  6377. }
  6378. }, true);
  6379. Class.setDefaultPreprocessorPosition('className', 'first');
  6380. Class.registerPreprocessor('xtype', function(cls, data) {
  6381. var xtypes = Ext.Array.from(data.xtype),
  6382. widgetPrefix = 'widget.',
  6383. aliases = Ext.Array.from(data.alias),
  6384. i, ln, xtype;
  6385. data.xtype = xtypes[0];
  6386. data.xtypes = xtypes;
  6387. aliases = data.alias = Ext.Array.from(data.alias);
  6388. for (i = 0,ln = xtypes.length; i < ln; i++) {
  6389. xtype = xtypes[i];
  6390. aliases.push(widgetPrefix + xtype);
  6391. }
  6392. data.alias = aliases;
  6393. });
  6394. Class.setDefaultPreprocessorPosition('xtype', 'last');
  6395. Class.registerPreprocessor('alias', function(cls, data) {
  6396. var aliases = Ext.Array.from(data.alias),
  6397. xtypes = Ext.Array.from(data.xtypes),
  6398. widgetPrefix = 'widget.',
  6399. widgetPrefixLength = widgetPrefix.length,
  6400. i, ln, alias, xtype;
  6401. for (i = 0, ln = aliases.length; i < ln; i++) {
  6402. alias = aliases[i];
  6403. if (alias.substring(0, widgetPrefixLength) === widgetPrefix) {
  6404. xtype = alias.substring(widgetPrefixLength);
  6405. Ext.Array.include(xtypes, xtype);
  6406. if (!cls.xtype) {
  6407. cls.xtype = data.xtype = xtype;
  6408. }
  6409. }
  6410. }
  6411. data.alias = aliases;
  6412. data.xtypes = xtypes;
  6413. });
  6414. Class.setDefaultPreprocessorPosition('alias', 'last');
  6415. })(Ext.Class, Ext.Function.alias);
  6416. /**
  6417. * @class Ext.Loader
  6418. * @singleton
  6419. * @author Jacky Nguyen <jacky@sencha.com>
  6420. * @docauthor Jacky Nguyen <jacky@sencha.com>
  6421. *
  6422. * Ext.Loader is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used
  6423. * via the {@link Ext#require} shorthand. Ext.Loader supports both asynchronous and synchronous loading
  6424. * approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons
  6425. * of each approach:
  6426. *
  6427. * # Asynchronous Loading
  6428. *
  6429. * - Advantages:
  6430. * + Cross-domain
  6431. * + No web server needed: you can run the application via the file system protocol
  6432. * (i.e: `file://path/to/your/index.html`)
  6433. * + Best possible debugging experience: error messages come with the exact file name and line number
  6434. *
  6435. * - Disadvantages:
  6436. * + Dependencies need to be specified before-hand
  6437. *
  6438. * ### Method 1: Explicitly include what you need:
  6439. *
  6440. * // Syntax
  6441. * Ext.require({String/Array} expressions);
  6442. *
  6443. * // Example: Single alias
  6444. * Ext.require('widget.window');
  6445. *
  6446. * // Example: Single class name
  6447. * Ext.require('Ext.window.Window');
  6448. *
  6449. * // Example: Multiple aliases / class names mix
  6450. * Ext.require(['widget.window', 'layout.border', 'Ext.data.Connection']);
  6451. *
  6452. * // Wildcards
  6453. * Ext.require(['widget.*', 'layout.*', 'Ext.data.*']);
  6454. *
  6455. * ### Method 2: Explicitly exclude what you don't need:
  6456. *
  6457. * // Syntax: Note that it must be in this chaining format.
  6458. * Ext.exclude({String/Array} expressions)
  6459. * .require({String/Array} expressions);
  6460. *
  6461. * // Include everything except Ext.data.*
  6462. * Ext.exclude('Ext.data.*').require('*'); 
  6463. *
  6464. * // Include all widgets except widget.checkbox*,
  6465. * // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc.
  6466. * Ext.exclude('widget.checkbox*').require('widget.*');
  6467. *
  6468. * # Synchronous Loading on Demand
  6469. *
  6470. * - Advantages:
  6471. * + There's no need to specify dependencies before-hand, which is always the convenience of including
  6472. * ext-all.js before
  6473. *
  6474. * - Disadvantages:
  6475. * + Not as good debugging experience since file name won't be shown (except in Firebug at the moment)
  6476. * + Must be from the same domain due to XHR restriction
  6477. * + Need a web server, same reason as above
  6478. *
  6479. * There's one simple rule to follow: Instantiate everything with Ext.create instead of the `new` keyword
  6480. *
  6481. * Ext.create('widget.window', { ... }); // Instead of new Ext.window.Window({...});
  6482. *
  6483. * Ext.create('Ext.window.Window', {}); // Same as above, using full class name instead of alias
  6484. *
  6485. * Ext.widget('window', {}); // Same as above, all you need is the traditional `xtype`
  6486. *
  6487. * Behind the scene, {@link Ext.ClassManager} will automatically check whether the given class name / alias has already
  6488. * existed on the page. If it's not, Ext.Loader will immediately switch itself to synchronous mode and automatic load
  6489. * the given class and all its dependencies.
  6490. *
  6491. * # Hybrid Loading - The Best of Both Worlds
  6492. *
  6493. * It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple:
  6494. *
  6495. * ### Step 1: Start writing your application using synchronous approach.
  6496. *
  6497. * Ext.Loader will automatically fetch all dependencies on demand as they're needed during run-time. For example:
  6498. *
  6499. * Ext.onReady(function(){
  6500. * var window = Ext.createWidget('window', {
  6501. * width: 500,
  6502. * height: 300,
  6503. * layout: {
  6504. * type: 'border',
  6505. * padding: 5
  6506. * },
  6507. * title: 'Hello Dialog',
  6508. * items: [{
  6509. * title: 'Navigation',
  6510. * collapsible: true,
  6511. * region: 'west',
  6512. * width: 200,
  6513. * html: 'Hello',
  6514. * split: true
  6515. * }, {
  6516. * title: 'TabPanel',
  6517. * region: 'center'
  6518. * }]
  6519. * });
  6520. *
  6521. * window.show();
  6522. * })
  6523. *
  6524. * ### Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these:
  6525. *
  6526. * [Ext.Loader] Synchronously loading 'Ext.window.Window'; consider adding Ext.require('Ext.window.Window') before your application's code ClassManager.js:432
  6527. * [Ext.Loader] Synchronously loading 'Ext.layout.container.Border'; consider adding Ext.require('Ext.layout.container.Border') before your application's code
  6528. *
  6529. * Simply copy and paste the suggested code above `Ext.onReady`, e.g.:
  6530. *
  6531. * Ext.require('Ext.window.Window');
  6532. * Ext.require('Ext.layout.container.Border');
  6533. *
  6534. * Ext.onReady(...);
  6535. *
  6536. * Everything should now load via asynchronous mode.
  6537. *
  6538. * # Deployment
  6539. *
  6540. * It's important to note that dynamic loading should only be used during development on your local machines.
  6541. * During production, all dependencies should be combined into one single JavaScript file. Ext.Loader makes
  6542. * the whole process of transitioning from / to between development / maintenance and production as easy as
  6543. * possible. Internally {@link Ext.Loader#history Ext.Loader.history} maintains the list of all dependencies
  6544. * your application needs in the exact loading sequence. It's as simple as concatenating all files in this
  6545. * array into one, then include it on top of your application.
  6546. *
  6547. * This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final.
  6548. */
  6549. (function(Manager, Class, flexSetter, alias) {
  6550. var
  6551. dependencyProperties = ['extend', 'mixins', 'requires'],
  6552. Loader;
  6553. Loader = Ext.Loader = {
  6554. /**
  6555. * @private
  6556. */
  6557. documentHead: typeof document !== 'undefined' && (document.head || document.getElementsByTagName('head')[0]),
  6558. /**
  6559. * Flag indicating whether there are still files being loaded
  6560. * @private
  6561. */
  6562. isLoading: false,
  6563. /**
  6564. * Maintain the queue for all dependencies. Each item in the array is an object of the format:
  6565. * {
  6566. * requires: [...], // The required classes for this queue item
  6567. * callback: function() { ... } // The function to execute when all classes specified in requires exist
  6568. * }
  6569. * @private
  6570. */
  6571. queue: [],
  6572. /**
  6573. * Maintain the list of files that have already been handled so that they never get double-loaded
  6574. * @private
  6575. */
  6576. isFileLoaded: {},
  6577. /**
  6578. * Maintain the list of listeners to execute when all required scripts are fully loaded
  6579. * @private
  6580. */
  6581. readyListeners: [],
  6582. /**
  6583. * Contains optional dependencies to be loaded last
  6584. * @private
  6585. */
  6586. optionalRequires: [],
  6587. /**
  6588. * Map of fully qualified class names to an array of dependent classes.
  6589. * @private
  6590. */
  6591. requiresMap: {},
  6592. /**
  6593. * @private
  6594. */
  6595. numPendingFiles: 0,
  6596. /**
  6597. * @private
  6598. */
  6599. numLoadedFiles: 0,
  6600. /** @private */
  6601. hasFileLoadError: false,
  6602. /**
  6603. * @private
  6604. */
  6605. classNameToFilePathMap: {},
  6606. /**
  6607. * @property {String[]} history
  6608. * An array of class names to keep track of the dependency loading order.
  6609. * This is not guaranteed to be the same everytime due to the asynchronous nature of the Loader.
  6610. */
  6611. history: [],
  6612. /**
  6613. * Configuration
  6614. * @private
  6615. */
  6616. config: {
  6617. /**
  6618. * @cfg {Boolean} enabled
  6619. * Whether or not to enable the dynamic dependency loading feature.
  6620. */
  6621. enabled: false,
  6622. /**
  6623. * @cfg {Boolean} disableCaching
  6624. * Appends current timestamp to script files to prevent caching.
  6625. */
  6626. disableCaching: true,
  6627. /**
  6628. * @cfg {String} disableCachingParam
  6629. * The get parameter name for the cache buster's timestamp.
  6630. */
  6631. disableCachingParam: '_dc',
  6632. /**
  6633. * @cfg {Object} paths
  6634. * The mapping from namespaces to file paths
  6635. *
  6636. * {
  6637. * 'Ext': '.', // This is set by default, Ext.layout.container.Container will be
  6638. * // loaded from ./layout/Container.js
  6639. *
  6640. * 'My': './src/my_own_folder' // My.layout.Container will be loaded from
  6641. * // ./src/my_own_folder/layout/Container.js
  6642. * }
  6643. *
  6644. * Note that all relative paths are relative to the current HTML document.
  6645. * If not being specified, for example, `Other.awesome.Class`
  6646. * will simply be loaded from `./Other/awesome/Class.js`
  6647. */
  6648. paths: {
  6649. 'Ext': '.'
  6650. }
  6651. },
  6652. /**
  6653. * Set the configuration for the loader. This should be called right after ext-core.js
  6654. * (or ext-core-debug.js) is included in the page, e.g.:
  6655. *
  6656. * <script type="text/javascript" src="ext-core-debug.js"></script>
  6657. * <script type="text/javascript">
  6658. * Ext.Loader.setConfig({
  6659. * enabled: true,
  6660. * paths: {
  6661. * 'My': 'my_own_path'
  6662. * }
  6663. * });
  6664. * <script>
  6665. * <script type="text/javascript">
  6666. * Ext.require(...);
  6667. *
  6668. * Ext.onReady(function() {
  6669. * // application code here
  6670. * });
  6671. * </script>
  6672. *
  6673. * Refer to config options of {@link Ext.Loader} for the list of possible properties.
  6674. *
  6675. * @param {String/Object} name Name of the value to override, or a config object to override multiple values.
  6676. * @param {Object} value (optional) The new value to set, needed if first parameter is String.
  6677. * @return {Ext.Loader} this
  6678. */
  6679. setConfig: function(name, value) {
  6680. if (Ext.isObject(name) && arguments.length === 1) {
  6681. Ext.Object.merge(this.config, name);
  6682. }
  6683. else {
  6684. this.config[name] = (Ext.isObject(value)) ? Ext.Object.merge(this.config[name], value) : value;
  6685. }
  6686. return this;
  6687. },
  6688. /**
  6689. * Get the config value corresponding to the specified name.
  6690. * If no name is given, will return the config object.
  6691. * @param {String} name The config property name
  6692. * @return {Object}
  6693. */
  6694. getConfig: function(name) {
  6695. if (name) {
  6696. return this.config[name];
  6697. }
  6698. return this.config;
  6699. },
  6700. /**
  6701. * Sets the path of a namespace. For Example:
  6702. *
  6703. * Ext.Loader.setPath('Ext', '.');
  6704. *
  6705. * @param {String/Object} name See {@link Ext.Function#flexSetter flexSetter}
  6706. * @param {String} path See {@link Ext.Function#flexSetter flexSetter}
  6707. * @return {Ext.Loader} this
  6708. * @method
  6709. */
  6710. setPath: flexSetter(function(name, path) {
  6711. this.config.paths[name] = path;
  6712. return this;
  6713. }),
  6714. /**
  6715. * Translates a className to a file path by adding the the proper prefix and converting the .'s to /'s.
  6716. * For example:
  6717. *
  6718. * Ext.Loader.setPath('My', '/path/to/My');
  6719. *
  6720. * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js'
  6721. *
  6722. * Note that the deeper namespace levels, if explicitly set, are always resolved first. For example:
  6723. *
  6724. * Ext.Loader.setPath({
  6725. * 'My': '/path/to/lib',
  6726. * 'My.awesome': '/other/path/for/awesome/stuff',
  6727. * 'My.awesome.more': '/more/awesome/path'
  6728. * });
  6729. *
  6730. * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js'
  6731. *
  6732. * alert(Ext.Loader.getPath('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js'
  6733. *
  6734. * alert(Ext.Loader.getPath('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js'
  6735. *
  6736. * alert(Ext.Loader.getPath('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js'
  6737. *
  6738. * @param {String} className
  6739. * @return {String} path
  6740. */
  6741. getPath: function(className) {
  6742. var path = '',
  6743. paths = this.config.paths,
  6744. prefix = this.getPrefix(className);
  6745. if (prefix.length > 0) {
  6746. if (prefix === className) {
  6747. return paths[prefix];
  6748. }
  6749. path = paths[prefix];
  6750. className = className.substring(prefix.length + 1);
  6751. }
  6752. if (path.length > 0) {
  6753. path += '/';
  6754. }
  6755. return path.replace(/\/\.\//g, '/') + className.replace(/\./g, "/") + '.js';
  6756. },
  6757. /**
  6758. * @private
  6759. * @param {String} className
  6760. */
  6761. getPrefix: function(className) {
  6762. var paths = this.config.paths,
  6763. prefix, deepestPrefix = '';
  6764. if (paths.hasOwnProperty(className)) {
  6765. return className;
  6766. }
  6767. for (prefix in paths) {
  6768. if (paths.hasOwnProperty(prefix) && prefix + '.' === className.substring(0, prefix.length + 1)) {
  6769. if (prefix.length > deepestPrefix.length) {
  6770. deepestPrefix = prefix;
  6771. }
  6772. }
  6773. }
  6774. return deepestPrefix;
  6775. },
  6776. /**
  6777. * Refresh all items in the queue. If all dependencies for an item exist during looping,
  6778. * it will execute the callback and call refreshQueue again. Triggers onReady when the queue is
  6779. * empty
  6780. * @private
  6781. */
  6782. refreshQueue: function() {
  6783. var ln = this.queue.length,
  6784. i, item, j, requires;
  6785. if (ln === 0) {
  6786. this.triggerReady();
  6787. return;
  6788. }
  6789. for (i = 0; i < ln; i++) {
  6790. item = this.queue[i];
  6791. if (item) {
  6792. requires = item.requires;
  6793. // Don't bother checking when the number of files loaded
  6794. // is still less than the array length
  6795. if (requires.length > this.numLoadedFiles) {
  6796. continue;
  6797. }
  6798. j = 0;
  6799. do {
  6800. if (Manager.isCreated(requires[j])) {
  6801. // Take out from the queue
  6802. Ext.Array.erase(requires, j, 1);
  6803. }
  6804. else {
  6805. j++;
  6806. }
  6807. } while (j < requires.length);
  6808. if (item.requires.length === 0) {
  6809. Ext.Array.erase(this.queue, i, 1);
  6810. item.callback.call(item.scope);
  6811. this.refreshQueue();
  6812. break;
  6813. }
  6814. }
  6815. }
  6816. return this;
  6817. },
  6818. /**
  6819. * Inject a script element to document's head, call onLoad and onError accordingly
  6820. * @private
  6821. */
  6822. injectScriptElement: function(url, onLoad, onError, scope) {
  6823. var script = document.createElement('script'),
  6824. me = this,
  6825. onLoadFn = function() {
  6826. me.cleanupScriptElement(script);
  6827. onLoad.call(scope);
  6828. },
  6829. onErrorFn = function() {
  6830. me.cleanupScriptElement(script);
  6831. onError.call(scope);
  6832. };
  6833. script.type = 'text/javascript';
  6834. script.src = url;
  6835. script.onload = onLoadFn;
  6836. script.onerror = onErrorFn;
  6837. script.onreadystatechange = function() {
  6838. if (this.readyState === 'loaded' || this.readyState === 'complete') {
  6839. onLoadFn();
  6840. }
  6841. };
  6842. this.documentHead.appendChild(script);
  6843. return script;
  6844. },
  6845. /**
  6846. * @private
  6847. */
  6848. cleanupScriptElement: function(script) {
  6849. script.onload = null;
  6850. script.onreadystatechange = null;
  6851. script.onerror = null;
  6852. return this;
  6853. },
  6854. /**
  6855. * Load a script file, supports both asynchronous and synchronous approaches
  6856. *
  6857. * @param {String} url
  6858. * @param {Function} onLoad
  6859. * @param {Object} scope
  6860. * @param {Boolean} synchronous
  6861. * @private
  6862. */
  6863. loadScriptFile: function(url, onLoad, onError, scope, synchronous) {
  6864. var me = this,
  6865. noCacheUrl = url + (this.getConfig('disableCaching') ? ('?' + this.getConfig('disableCachingParam') + '=' + Ext.Date.now()) : ''),
  6866. fileName = url.split('/').pop(),
  6867. isCrossOriginRestricted = false,
  6868. xhr, status, onScriptError;
  6869. scope = scope || this;
  6870. this.isLoading = true;
  6871. if (!synchronous) {
  6872. onScriptError = function() {
  6873. onError.call(scope, "Failed loading '" + url + "', please verify that the file exists", synchronous);
  6874. };
  6875. if (!Ext.isReady && Ext.onDocumentReady) {
  6876. Ext.onDocumentReady(function() {
  6877. me.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
  6878. });
  6879. }
  6880. else {
  6881. this.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
  6882. }
  6883. }
  6884. else {
  6885. if (typeof XMLHttpRequest !== 'undefined') {
  6886. xhr = new XMLHttpRequest();
  6887. } else {
  6888. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  6889. }
  6890. try {
  6891. xhr.open('GET', noCacheUrl, false);
  6892. xhr.send(null);
  6893. } catch (e) {
  6894. isCrossOriginRestricted = true;
  6895. }
  6896. status = (xhr.status === 1223) ? 204 : xhr.status;
  6897. if (!isCrossOriginRestricted) {
  6898. isCrossOriginRestricted = (status === 0);
  6899. }
  6900. if (isCrossOriginRestricted
  6901. ) {
  6902. onError.call(this, "Failed loading synchronously via XHR: '" + url + "'; It's likely that the file is either " +
  6903. "being loaded from a different domain or from the local file system whereby cross origin " +
  6904. "requests are not allowed due to security reasons. Use asynchronous loading with " +
  6905. "Ext.require instead.", synchronous);
  6906. }
  6907. else if (status >= 200 && status < 300
  6908. ) {
  6909. // Firebug friendly, file names are still shown even though they're eval'ed code
  6910. new Function(xhr.responseText + "\n//@ sourceURL=" + fileName)();
  6911. onLoad.call(scope);
  6912. }
  6913. else {
  6914. onError.call(this, "Failed loading synchronously via XHR: '" + url + "'; please " +
  6915. "verify that the file exists. " +
  6916. "XHR status code: " + status, synchronous);
  6917. }
  6918. // Prevent potential IE memory leak
  6919. xhr = null;
  6920. }
  6921. },
  6922. /**
  6923. * Explicitly exclude files from being loaded. Useful when used in conjunction with a broad include expression.
  6924. * Can be chained with more `require` and `exclude` methods, e.g.:
  6925. *
  6926. * Ext.exclude('Ext.data.*').require('*');
  6927. *
  6928. * Ext.exclude('widget.button*').require('widget.*');
  6929. *
  6930. * {@link Ext#exclude Ext.exclude} is alias for {@link Ext.Loader#exclude Ext.Loader.exclude} for convenience.
  6931. *
  6932. * @param {String/String[]} excludes
  6933. * @return {Object} object contains `require` method for chaining
  6934. */
  6935. exclude: function(excludes) {
  6936. var me = this;
  6937. return {
  6938. require: function(expressions, fn, scope) {
  6939. return me.require(expressions, fn, scope, excludes);
  6940. },
  6941. syncRequire: function(expressions, fn, scope) {
  6942. return me.syncRequire(expressions, fn, scope, excludes);
  6943. }
  6944. };
  6945. },
  6946. /**
  6947. * Synchronously loads all classes by the given names and all their direct dependencies;
  6948. * optionally executes the given callback function when finishes, within the optional scope.
  6949. *
  6950. * {@link Ext#syncRequire Ext.syncRequire} is alias for {@link Ext.Loader#syncRequire Ext.Loader.syncRequire} for convenience.
  6951. *
  6952. * @param {String/String[]} expressions Can either be a string or an array of string
  6953. * @param {Function} fn (Optional) The callback function
  6954. * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
  6955. * @param {String/String[]} excludes (Optional) Classes to be excluded, useful when being used with expressions
  6956. */
  6957. syncRequire: function() {
  6958. this.syncModeEnabled = true;
  6959. this.require.apply(this, arguments);
  6960. this.refreshQueue();
  6961. this.syncModeEnabled = false;
  6962. },
  6963. /**
  6964. * Loads all classes by the given names and all their direct dependencies;
  6965. * optionally executes the given callback function when finishes, within the optional scope.
  6966. *
  6967. * {@link Ext#require Ext.require} is alias for {@link Ext.Loader#require Ext.Loader.require} for convenience.
  6968. *
  6969. * @param {String/String[]} expressions Can either be a string or an array of string
  6970. * @param {Function} fn (Optional) The callback function
  6971. * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
  6972. * @param {String/String[]} excludes (Optional) Classes to be excluded, useful when being used with expressions
  6973. */
  6974. require: function(expressions, fn, scope, excludes) {
  6975. var filePath, expression, exclude, className, excluded = {},
  6976. excludedClassNames = [],
  6977. possibleClassNames = [],
  6978. possibleClassName, classNames = [],
  6979. i, j, ln, subLn;
  6980. expressions = Ext.Array.from(expressions);
  6981. excludes = Ext.Array.from(excludes);
  6982. fn = fn || Ext.emptyFn;
  6983. scope = scope || Ext.global;
  6984. for (i = 0, ln = excludes.length; i < ln; i++) {
  6985. exclude = excludes[i];
  6986. if (typeof exclude === 'string' && exclude.length > 0) {
  6987. excludedClassNames = Manager.getNamesByExpression(exclude);
  6988. for (j = 0, subLn = excludedClassNames.length; j < subLn; j++) {
  6989. excluded[excludedClassNames[j]] = true;
  6990. }
  6991. }
  6992. }
  6993. for (i = 0, ln = expressions.length; i < ln; i++) {
  6994. expression = expressions[i];
  6995. if (typeof expression === 'string' && expression.length > 0) {
  6996. possibleClassNames = Manager.getNamesByExpression(expression);
  6997. for (j = 0, subLn = possibleClassNames.length; j < subLn; j++) {
  6998. possibleClassName = possibleClassNames[j];
  6999. if (!excluded.hasOwnProperty(possibleClassName) && !Manager.isCreated(possibleClassName)) {
  7000. Ext.Array.include(classNames, possibleClassName);
  7001. }
  7002. }
  7003. }
  7004. }
  7005. // If the dynamic dependency feature is not being used, throw an error
  7006. // if the dependencies are not defined
  7007. if (!this.config.enabled) {
  7008. if (classNames.length > 0) {
  7009. Ext.Error.raise({
  7010. sourceClass: "Ext.Loader",
  7011. sourceMethod: "require",
  7012. msg: "Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. " +
  7013. "Missing required class" + ((classNames.length > 1) ? "es" : "") + ": " + classNames.join(', ')
  7014. });
  7015. }
  7016. }
  7017. if (classNames.length === 0) {
  7018. fn.call(scope);
  7019. return this;
  7020. }
  7021. this.queue.push({
  7022. requires: classNames,
  7023. callback: fn,
  7024. scope: scope
  7025. });
  7026. classNames = classNames.slice();
  7027. for (i = 0, ln = classNames.length; i < ln; i++) {
  7028. className = classNames[i];
  7029. if (!this.isFileLoaded.hasOwnProperty(className)) {
  7030. this.isFileLoaded[className] = false;
  7031. filePath = this.getPath(className);
  7032. this.classNameToFilePathMap[className] = filePath;
  7033. this.numPendingFiles++;
  7034. this.loadScriptFile(
  7035. filePath,
  7036. Ext.Function.pass(this.onFileLoaded, [className, filePath], this),
  7037. Ext.Function.pass(this.onFileLoadError, [className, filePath]),
  7038. this,
  7039. this.syncModeEnabled
  7040. );
  7041. }
  7042. }
  7043. return this;
  7044. },
  7045. /**
  7046. * @private
  7047. * @param {String} className
  7048. * @param {String} filePath
  7049. */
  7050. onFileLoaded: function(className, filePath) {
  7051. this.numLoadedFiles++;
  7052. this.isFileLoaded[className] = true;
  7053. this.numPendingFiles--;
  7054. if (this.numPendingFiles === 0) {
  7055. this.refreshQueue();
  7056. }
  7057. },
  7058. /**
  7059. * @private
  7060. */
  7061. onFileLoadError: function(className, filePath, errorMessage, isSynchronous) {
  7062. this.numPendingFiles--;
  7063. this.hasFileLoadError = true;
  7064. },
  7065. /**
  7066. * @private
  7067. */
  7068. addOptionalRequires: function(requires) {
  7069. var optionalRequires = this.optionalRequires,
  7070. i, ln, require;
  7071. requires = Ext.Array.from(requires);
  7072. for (i = 0, ln = requires.length; i < ln; i++) {
  7073. require = requires[i];
  7074. Ext.Array.include(optionalRequires, require);
  7075. }
  7076. return this;
  7077. },
  7078. /**
  7079. * @private
  7080. */
  7081. triggerReady: function(force) {
  7082. var readyListeners = this.readyListeners,
  7083. optionalRequires, listener;
  7084. if (this.isLoading || force) {
  7085. this.isLoading = false;
  7086. if (this.optionalRequires.length) {
  7087. // Clone then empty the array to eliminate potential recursive loop issue
  7088. optionalRequires = Ext.Array.clone(this.optionalRequires);
  7089. // Empty the original array
  7090. this.optionalRequires.length = 0;
  7091. this.require(optionalRequires, Ext.Function.pass(this.triggerReady, [true], this), this);
  7092. return this;
  7093. }
  7094. while (readyListeners.length) {
  7095. listener = readyListeners.shift();
  7096. listener.fn.call(listener.scope);
  7097. if (this.isLoading) {
  7098. return this;
  7099. }
  7100. }
  7101. }
  7102. return this;
  7103. },
  7104. /**
  7105. * Adds new listener to be executed when all required scripts are fully loaded.
  7106. *
  7107. * @param {Function} fn The function callback to be executed
  7108. * @param {Object} scope The execution scope (`this`) of the callback function
  7109. * @param {Boolean} withDomReady Whether or not to wait for document dom ready as well
  7110. */
  7111. onReady: function(fn, scope, withDomReady, options) {
  7112. var oldFn;
  7113. if (withDomReady !== false && Ext.onDocumentReady) {
  7114. oldFn = fn;
  7115. fn = function() {
  7116. Ext.onDocumentReady(oldFn, scope, options);
  7117. };
  7118. }
  7119. if (!this.isLoading) {
  7120. fn.call(scope);
  7121. }
  7122. else {
  7123. this.readyListeners.push({
  7124. fn: fn,
  7125. scope: scope
  7126. });
  7127. }
  7128. },
  7129. /**
  7130. * @private
  7131. * @param {String} className
  7132. */
  7133. historyPush: function(className) {
  7134. if (className && this.isFileLoaded.hasOwnProperty(className)) {
  7135. Ext.Array.include(this.history, className);
  7136. }
  7137. return this;
  7138. }
  7139. };
  7140. /**
  7141. * @member Ext
  7142. * @method require
  7143. * @alias Ext.Loader#require
  7144. */
  7145. Ext.require = alias(Loader, 'require');
  7146. /**
  7147. * @member Ext
  7148. * @method syncRequire
  7149. * @alias Ext.Loader#syncRequire
  7150. */
  7151. Ext.syncRequire = alias(Loader, 'syncRequire');
  7152. /**
  7153. * @member Ext
  7154. * @method exclude
  7155. * @alias Ext.Loader#exclude
  7156. */
  7157. Ext.exclude = alias(Loader, 'exclude');
  7158. /**
  7159. * @member Ext
  7160. * @method onReady
  7161. * @alias Ext.Loader#onReady
  7162. */
  7163. Ext.onReady = function(fn, scope, options) {
  7164. Loader.onReady(fn, scope, true, options);
  7165. };
  7166. /**
  7167. * @cfg {String[]} requires
  7168. * @member Ext.Class
  7169. * List of classes that have to be loaded before instantiating this class.
  7170. * For example:
  7171. *
  7172. * Ext.define('Mother', {
  7173. * requires: ['Child'],
  7174. * giveBirth: function() {
  7175. * // we can be sure that child class is available.
  7176. * return new Child();
  7177. * }
  7178. * });
  7179. */
  7180. Class.registerPreprocessor('loader', function(cls, data, continueFn) {
  7181. var me = this,
  7182. dependencies = [],
  7183. className = Manager.getName(cls),
  7184. i, j, ln, subLn, value, propertyName, propertyValue;
  7185. /*
  7186. Basically loop through the dependencyProperties, look for string class names and push
  7187. them into a stack, regardless of whether the property's value is a string, array or object. For example:
  7188. {
  7189. extend: 'Ext.MyClass',
  7190. requires: ['Ext.some.OtherClass'],
  7191. mixins: {
  7192. observable: 'Ext.util.Observable';
  7193. }
  7194. }
  7195. which will later be transformed into:
  7196. {
  7197. extend: Ext.MyClass,
  7198. requires: [Ext.some.OtherClass],
  7199. mixins: {
  7200. observable: Ext.util.Observable;
  7201. }
  7202. }
  7203. */
  7204. for (i = 0, ln = dependencyProperties.length; i < ln; i++) {
  7205. propertyName = dependencyProperties[i];
  7206. if (data.hasOwnProperty(propertyName)) {
  7207. propertyValue = data[propertyName];
  7208. if (typeof propertyValue === 'string') {
  7209. dependencies.push(propertyValue);
  7210. }
  7211. else if (propertyValue instanceof Array) {
  7212. for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
  7213. value = propertyValue[j];
  7214. if (typeof value === 'string') {
  7215. dependencies.push(value);
  7216. }
  7217. }
  7218. }
  7219. else if (typeof propertyValue != 'function') {
  7220. for (j in propertyValue) {
  7221. if (propertyValue.hasOwnProperty(j)) {
  7222. value = propertyValue[j];
  7223. if (typeof value === 'string') {
  7224. dependencies.push(value);
  7225. }
  7226. }
  7227. }
  7228. }
  7229. }
  7230. }
  7231. if (dependencies.length === 0) {
  7232. // Loader.historyPush(className);
  7233. return;
  7234. }
  7235. Loader.require(dependencies, function() {
  7236. for (i = 0, ln = dependencyProperties.length; i < ln; i++) {
  7237. propertyName = dependencyProperties[i];
  7238. if (data.hasOwnProperty(propertyName)) {
  7239. propertyValue = data[propertyName];
  7240. if (typeof propertyValue === 'string') {
  7241. data[propertyName] = Manager.get(propertyValue);
  7242. }
  7243. else if (propertyValue instanceof Array) {
  7244. for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
  7245. value = propertyValue[j];
  7246. if (typeof value === 'string') {
  7247. data[propertyName][j] = Manager.get(value);
  7248. }
  7249. }
  7250. }
  7251. else if (typeof propertyValue != 'function') {
  7252. for (var k in propertyValue) {
  7253. if (propertyValue.hasOwnProperty(k)) {
  7254. value = propertyValue[k];
  7255. if (typeof value === 'string') {
  7256. data[propertyName][k] = Manager.get(value);
  7257. }
  7258. }
  7259. }
  7260. }
  7261. }
  7262. }
  7263. continueFn.call(me, cls, data);
  7264. });
  7265. return false;
  7266. }, true);
  7267. Class.setDefaultPreprocessorPosition('loader', 'after', 'className');
  7268. /**
  7269. * @cfg {String[]} uses
  7270. * @member Ext.Class
  7271. * List of classes to load together with this class. These aren't neccessarily loaded before
  7272. * this class is instantiated. For example:
  7273. *
  7274. * Ext.define('Mother', {
  7275. * uses: ['Child'],
  7276. * giveBirth: function() {
  7277. * // This code might, or might not work:
  7278. * // return new Child();
  7279. *
  7280. * // Instead use Ext.create() to load the class at the spot if not loaded already:
  7281. * return Ext.create('Child');
  7282. * }
  7283. * });
  7284. */
  7285. Manager.registerPostprocessor('uses', function(name, cls, data) {
  7286. var uses = Ext.Array.from(data.uses),
  7287. items = [],
  7288. i, ln, item;
  7289. for (i = 0, ln = uses.length; i < ln; i++) {
  7290. item = uses[i];
  7291. if (typeof item === 'string') {
  7292. items.push(item);
  7293. }
  7294. }
  7295. Loader.addOptionalRequires(items);
  7296. });
  7297. Manager.setDefaultPostprocessorPosition('uses', 'last');
  7298. })(Ext.ClassManager, Ext.Class, Ext.Function.flexSetter, Ext.Function.alias);
  7299. /**
  7300. * @author Brian Moeskau <brian@sencha.com>
  7301. * @docauthor Brian Moeskau <brian@sencha.com>
  7302. *
  7303. * A wrapper class for the native JavaScript Error object that adds a few useful capabilities for handling
  7304. * errors in an Ext application. When you use Ext.Error to {@link #raise} an error from within any class that
  7305. * uses the Ext 4 class system, the Error class can automatically add the source class and method from which
  7306. * the error was raised. It also includes logic to automatically log the eroor to the console, if available,
  7307. * with additional metadata about the error. In all cases, the error will always be thrown at the end so that
  7308. * execution will halt.
  7309. *
  7310. * Ext.Error also offers a global error {@link #handle handling} method that can be overridden in order to
  7311. * handle application-wide errors in a single spot. You can optionally {@link #ignore} errors altogether,
  7312. * although in a real application it's usually a better idea to override the handling function and perform
  7313. * logging or some other method of reporting the errors in a way that is meaningful to the application.
  7314. *
  7315. * At its simplest you can simply raise an error as a simple string from within any code:
  7316. *
  7317. * Example usage:
  7318. *
  7319. * Ext.Error.raise('Something bad happened!');
  7320. *
  7321. * If raised from plain JavaScript code, the error will be logged to the console (if available) and the message
  7322. * displayed. In most cases however you'll be raising errors from within a class, and it may often be useful to add
  7323. * additional metadata about the error being raised. The {@link #raise} method can also take a config object.
  7324. * In this form the `msg` attribute becomes the error description, and any other data added to the config gets
  7325. * added to the error object and, if the console is available, logged to the console for inspection.
  7326. *
  7327. * Example usage:
  7328. *
  7329. * Ext.define('Ext.Foo', {
  7330. * doSomething: function(option){
  7331. * if (someCondition === false) {
  7332. * Ext.Error.raise({
  7333. * msg: 'You cannot do that!',
  7334. * option: option, // whatever was passed into the method
  7335. * 'error code': 100 // other arbitrary info
  7336. * });
  7337. * }
  7338. * }
  7339. * });
  7340. *
  7341. * If a console is available (that supports the `console.dir` function) you'll see console output like:
  7342. *
  7343. * An error was raised with the following data:
  7344. * option: Object { foo: "bar"}
  7345. * foo: "bar"
  7346. * error code: 100
  7347. * msg: "You cannot do that!"
  7348. * sourceClass: "Ext.Foo"
  7349. * sourceMethod: "doSomething"
  7350. *
  7351. * uncaught exception: You cannot do that!
  7352. *
  7353. * As you can see, the error will report exactly where it was raised and will include as much information as the
  7354. * raising code can usefully provide.
  7355. *
  7356. * If you want to handle all application errors globally you can simply override the static {@link #handle} method
  7357. * and provide whatever handling logic you need. If the method returns true then the error is considered handled
  7358. * and will not be thrown to the browser. If anything but true is returned then the error will be thrown normally.
  7359. *
  7360. * Example usage:
  7361. *
  7362. * Ext.Error.handle = function(err) {
  7363. * if (err.someProperty == 'NotReallyAnError') {
  7364. * // maybe log something to the application here if applicable
  7365. * return true;
  7366. * }
  7367. * // any non-true return value (including none) will cause the error to be thrown
  7368. * }
  7369. *
  7370. */
  7371. Ext.Error = Ext.extend(Error, {
  7372. statics: {
  7373. /**
  7374. * @property {Boolean} ignore
  7375. * Static flag that can be used to globally disable error reporting to the browser if set to true
  7376. * (defaults to false). Note that if you ignore Ext errors it's likely that some other code may fail
  7377. * and throw a native JavaScript error thereafter, so use with caution. In most cases it will probably
  7378. * be preferable to supply a custom error {@link #handle handling} function instead.
  7379. *
  7380. * Example usage:
  7381. *
  7382. * Ext.Error.ignore = true;
  7383. *
  7384. * @static
  7385. */
  7386. ignore: false,
  7387. /**
  7388. * @property {Boolean} notify
  7389. * Static flag that can be used to globally control error notification to the user. Unlike
  7390. * Ex.Error.ignore, this does not effect exceptions. They are still thrown. This value can be
  7391. * set to false to disable the alert notification (default is true for IE6 and IE7).
  7392. *
  7393. * Only the first error will generate an alert. Internally this flag is set to false when the
  7394. * first error occurs prior to displaying the alert.
  7395. *
  7396. * This flag is not used in a release build.
  7397. *
  7398. * Example usage:
  7399. *
  7400. * Ext.Error.notify = false;
  7401. *
  7402. * @static
  7403. */
  7404. //notify: Ext.isIE6 || Ext.isIE7,
  7405. /**
  7406. * Raise an error that can include additional data and supports automatic console logging if available.
  7407. * You can pass a string error message or an object with the `msg` attribute which will be used as the
  7408. * error message. The object can contain any other name-value attributes (or objects) to be logged
  7409. * along with the error.
  7410. *
  7411. * Note that after displaying the error message a JavaScript error will ultimately be thrown so that
  7412. * execution will halt.
  7413. *
  7414. * Example usage:
  7415. *
  7416. * Ext.Error.raise('A simple string error message');
  7417. *
  7418. * // or...
  7419. *
  7420. * Ext.define('Ext.Foo', {
  7421. * doSomething: function(option){
  7422. * if (someCondition === false) {
  7423. * Ext.Error.raise({
  7424. * msg: 'You cannot do that!',
  7425. * option: option, // whatever was passed into the method
  7426. * 'error code': 100 // other arbitrary info
  7427. * });
  7428. * }
  7429. * }
  7430. * });
  7431. *
  7432. * @param {String/Object} err The error message string, or an object containing the attribute "msg" that will be
  7433. * used as the error message. Any other data included in the object will also be logged to the browser console,
  7434. * if available.
  7435. * @static
  7436. */
  7437. raise: function(err){
  7438. err = err || {};
  7439. if (Ext.isString(err)) {
  7440. err = { msg: err };
  7441. }
  7442. var method = this.raise.caller;
  7443. if (method) {
  7444. if (method.$name) {
  7445. err.sourceMethod = method.$name;
  7446. }
  7447. if (method.$owner) {
  7448. err.sourceClass = method.$owner.$className;
  7449. }
  7450. }
  7451. if (Ext.Error.handle(err) !== true) {
  7452. var msg = Ext.Error.prototype.toString.call(err);
  7453. Ext.log({
  7454. msg: msg,
  7455. level: 'error',
  7456. dump: err,
  7457. stack: true
  7458. });
  7459. throw new Ext.Error(err);
  7460. }
  7461. },
  7462. /**
  7463. * Globally handle any Ext errors that may be raised, optionally providing custom logic to
  7464. * handle different errors individually. Return true from the function to bypass throwing the
  7465. * error to the browser, otherwise the error will be thrown and execution will halt.
  7466. *
  7467. * Example usage:
  7468. *
  7469. * Ext.Error.handle = function(err) {
  7470. * if (err.someProperty == 'NotReallyAnError') {
  7471. * // maybe log something to the application here if applicable
  7472. * return true;
  7473. * }
  7474. * // any non-true return value (including none) will cause the error to be thrown
  7475. * }
  7476. *
  7477. * @param {Ext.Error} err The Ext.Error object being raised. It will contain any attributes that were originally
  7478. * raised with it, plus properties about the method and class from which the error originated (if raised from a
  7479. * class that uses the Ext 4 class system).
  7480. * @static
  7481. */
  7482. handle: function(){
  7483. return Ext.Error.ignore;
  7484. }
  7485. },
  7486. // This is the standard property that is the name of the constructor.
  7487. name: 'Ext.Error',
  7488. /**
  7489. * Creates new Error object.
  7490. * @param {String/Object} config The error message string, or an object containing the
  7491. * attribute "msg" that will be used as the error message. Any other data included in
  7492. * the object will be applied to the error instance and logged to the browser console, if available.
  7493. */
  7494. constructor: function(config){
  7495. if (Ext.isString(config)) {
  7496. config = { msg: config };
  7497. }
  7498. var me = this;
  7499. Ext.apply(me, config);
  7500. me.message = me.message || me.msg; // 'message' is standard ('msg' is non-standard)
  7501. // note: the above does not work in old WebKit (me.message is readonly) (Safari 4)
  7502. },
  7503. /**
  7504. * Provides a custom string representation of the error object. This is an override of the base JavaScript
  7505. * `Object.toString` method, which is useful so that when logged to the browser console, an error object will
  7506. * be displayed with a useful message instead of `[object Object]`, the default `toString` result.
  7507. *
  7508. * The default implementation will include the error message along with the raising class and method, if available,
  7509. * but this can be overridden with a custom implementation either at the prototype level (for all errors) or on
  7510. * a particular error instance, if you want to provide a custom description that will show up in the console.
  7511. * @return {String} The error message. If raised from within the Ext 4 class system, the error message will also
  7512. * include the raising class and method names, if available.
  7513. */
  7514. toString: function(){
  7515. var me = this,
  7516. className = me.className ? me.className : '',
  7517. methodName = me.methodName ? '.' + me.methodName + '(): ' : '',
  7518. msg = me.msg || '(No description provided)';
  7519. return className + methodName + msg;
  7520. }
  7521. });
  7522. /*
  7523. * This mechanism is used to notify the user of the first error encountered on the page. This
  7524. * was previously internal to Ext.Error.raise and is a desirable feature since errors often
  7525. * slip silently under the radar. It cannot live in Ext.Error.raise since there are times
  7526. * where exceptions are handled in a try/catch.
  7527. */
  7528. /*
  7529. This file is part of Ext JS 4
  7530. Copyright (c) 2011 Sencha Inc
  7531. Contact: http://www.sencha.com/contact
  7532. GNU General Public License Usage
  7533. 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.
  7534. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
  7535. */
  7536. /**
  7537. * @class Ext.JSON
  7538. * Modified version of Douglas Crockford's JSON.js that doesn't
  7539. * mess with the Object prototype
  7540. * http://www.json.org/js.html
  7541. * @singleton
  7542. */
  7543. Ext.JSON = new(function() {
  7544. var useHasOwn = !! {}.hasOwnProperty,
  7545. isNative = function() {
  7546. var useNative = null;
  7547. return function() {
  7548. if (useNative === null) {
  7549. useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]';
  7550. }
  7551. return useNative;
  7552. };
  7553. }(),
  7554. pad = function(n) {
  7555. return n < 10 ? "0" + n : n;
  7556. },
  7557. doDecode = function(json) {
  7558. return eval("(" + json + ')');
  7559. },
  7560. doEncode = function(o) {
  7561. if (!Ext.isDefined(o) || o === null) {
  7562. return "null";
  7563. } else if (Ext.isArray(o)) {
  7564. return encodeArray(o);
  7565. } else if (Ext.isDate(o)) {
  7566. return Ext.JSON.encodeDate(o);
  7567. } else if (Ext.isString(o)) {
  7568. return encodeString(o);
  7569. } else if (typeof o == "number") {
  7570. //don't use isNumber here, since finite checks happen inside isNumber
  7571. return isFinite(o) ? String(o) : "null";
  7572. } else if (Ext.isBoolean(o)) {
  7573. return String(o);
  7574. } else if (Ext.isObject(o)) {
  7575. return encodeObject(o);
  7576. } else if (typeof o === "function") {
  7577. return "null";
  7578. }
  7579. return 'undefined';
  7580. },
  7581. m = {
  7582. "\b": '\\b',
  7583. "\t": '\\t',
  7584. "\n": '\\n',
  7585. "\f": '\\f',
  7586. "\r": '\\r',
  7587. '"': '\\"',
  7588. "\\": '\\\\',
  7589. '\x0b': '\\u000b' //ie doesn't handle \v
  7590. },
  7591. charToReplace = /[\\\"\x00-\x1f\x7f-\uffff]/g,
  7592. encodeString = function(s) {
  7593. return '"' + s.replace(charToReplace, function(a) {
  7594. var c = m[a];
  7595. return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  7596. }) + '"';
  7597. },
  7598. encodeArray = function(o) {
  7599. var a = ["[", ""],
  7600. // Note empty string in case there are no serializable members.
  7601. len = o.length,
  7602. i;
  7603. for (i = 0; i < len; i += 1) {
  7604. a.push(doEncode(o[i]), ',');
  7605. }
  7606. // Overwrite trailing comma (or empty string)
  7607. a[a.length - 1] = ']';
  7608. return a.join("");
  7609. },
  7610. encodeObject = function(o) {
  7611. var a = ["{", ""],
  7612. // Note empty string in case there are no serializable members.
  7613. i;
  7614. for (i in o) {
  7615. if (!useHasOwn || o.hasOwnProperty(i)) {
  7616. a.push(doEncode(i), ":", doEncode(o[i]), ',');
  7617. }
  7618. }
  7619. // Overwrite trailing comma (or empty string)
  7620. a[a.length - 1] = '}';
  7621. return a.join("");
  7622. };
  7623. /**
  7624. * <p>Encodes a Date. This returns the actual string which is inserted into the JSON string as the literal expression.
  7625. * <b>The returned value includes enclosing double quotation marks.</b></p>
  7626. * <p>The default return format is "yyyy-mm-ddThh:mm:ss".</p>
  7627. * <p>To override this:</p><pre><code>
  7628. Ext.JSON.encodeDate = function(d) {
  7629. return Ext.Date.format(d, '"Y-m-d"');
  7630. };
  7631. </code></pre>
  7632. * @param {Date} d The Date to encode
  7633. * @return {String} The string literal to use in a JSON string.
  7634. */
  7635. this.encodeDate = function(o) {
  7636. return '"' + o.getFullYear() + "-"
  7637. + pad(o.getMonth() + 1) + "-"
  7638. + pad(o.getDate()) + "T"
  7639. + pad(o.getHours()) + ":"
  7640. + pad(o.getMinutes()) + ":"
  7641. + pad(o.getSeconds()) + '"';
  7642. };
  7643. /**
  7644. * Encodes an Object, Array or other value
  7645. * @param {Object} o The variable to encode
  7646. * @return {String} The JSON string
  7647. */
  7648. this.encode = function() {
  7649. var ec;
  7650. return function(o) {
  7651. if (!ec) {
  7652. // setup encoding function on first access
  7653. ec = isNative() ? JSON.stringify : doEncode;
  7654. }
  7655. return ec(o);
  7656. };
  7657. }();
  7658. /**
  7659. * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set.
  7660. * @param {String} json The JSON string
  7661. * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid.
  7662. * @return {Object} The resulting object
  7663. */
  7664. this.decode = function() {
  7665. var dc;
  7666. return function(json, safe) {
  7667. if (!dc) {
  7668. // setup decoding function on first access
  7669. dc = isNative() ? JSON.parse : doDecode;
  7670. }
  7671. try {
  7672. return dc(json);
  7673. } catch (e) {
  7674. if (safe === true) {
  7675. return null;
  7676. }
  7677. Ext.Error.raise({
  7678. sourceClass: "Ext.JSON",
  7679. sourceMethod: "decode",
  7680. msg: "You're trying to decode an invalid JSON String: " + json
  7681. });
  7682. }
  7683. };
  7684. }();
  7685. })();
  7686. /**
  7687. * Shorthand for {@link Ext.JSON#encode}
  7688. * @member Ext
  7689. * @method encode
  7690. * @alias Ext.JSON#encode
  7691. */
  7692. Ext.encode = Ext.JSON.encode;
  7693. /**
  7694. * Shorthand for {@link Ext.JSON#decode}
  7695. * @member Ext
  7696. * @method decode
  7697. * @alias Ext.JSON#decode
  7698. */
  7699. Ext.decode = Ext.JSON.decode;
  7700. /**
  7701. * @class Ext
  7702. The Ext namespace (global object) encapsulates all classes, singletons, and utility methods provided by Sencha's libraries.</p>
  7703. Most user interface Components are at a lower level of nesting in the namespace, but many common utility functions are provided
  7704. as direct properties of the Ext namespace.
  7705. Also many frequently used methods from other classes are provided as shortcuts within the Ext namespace.
  7706. For example {@link Ext#getCmp Ext.getCmp} aliases {@link Ext.ComponentManager#get Ext.ComponentManager.get}.
  7707. Many applications are initiated with {@link Ext#onReady Ext.onReady} which is called once the DOM is ready.
  7708. This ensures all scripts have been loaded, preventing dependency issues. For example
  7709. Ext.onReady(function(){
  7710. new Ext.Component({
  7711. renderTo: document.body,
  7712. html: 'DOM ready!'
  7713. });
  7714. });
  7715. For more information about how to use the Ext classes, see
  7716. - <a href="http://www.sencha.com/learn/">The Learning Center</a>
  7717. - <a href="http://www.sencha.com/learn/Ext_FAQ">The FAQ</a>
  7718. - <a href="http://www.sencha.com/forum/">The forums</a>
  7719. * @singleton
  7720. * @markdown
  7721. */
  7722. Ext.apply(Ext, {
  7723. userAgent: navigator.userAgent.toLowerCase(),
  7724. cache: {},
  7725. idSeed: 1000,
  7726. windowId: 'ext-window',
  7727. documentId: 'ext-document',
  7728. /**
  7729. * True when the document is fully initialized and ready for action
  7730. * @type Boolean
  7731. */
  7732. isReady: false,
  7733. /**
  7734. * True to automatically uncache orphaned Ext.Elements periodically
  7735. * @type Boolean
  7736. */
  7737. enableGarbageCollector: true,
  7738. /**
  7739. * True to automatically purge event listeners during garbageCollection.
  7740. * @type Boolean
  7741. */
  7742. enableListenerCollection: true,
  7743. /**
  7744. * Generates unique ids. If the element already has an id, it is unchanged
  7745. * @param {HTMLElement/Ext.Element} el (optional) The element to generate an id for
  7746. * @param {String} prefix (optional) Id prefix (defaults "ext-gen")
  7747. * @return {String} The generated Id.
  7748. */
  7749. id: function(el, prefix) {
  7750. var me = this,
  7751. sandboxPrefix = '';
  7752. el = Ext.getDom(el, true) || {};
  7753. if (el === document) {
  7754. el.id = me.documentId;
  7755. }
  7756. else if (el === window) {
  7757. el.id = me.windowId;
  7758. }
  7759. if (!el.id) {
  7760. if (me.isSandboxed) {
  7761. if (!me.uniqueGlobalNamespace) {
  7762. me.getUniqueGlobalNamespace();
  7763. }
  7764. sandboxPrefix = me.uniqueGlobalNamespace + '-';
  7765. }
  7766. el.id = sandboxPrefix + (prefix || "ext-gen") + (++Ext.idSeed);
  7767. }
  7768. return el.id;
  7769. },
  7770. /**
  7771. * Returns the current document body as an {@link Ext.Element}.
  7772. * @return Ext.Element The document body
  7773. */
  7774. getBody: function() {
  7775. return Ext.get(document.body || false);
  7776. },
  7777. /**
  7778. * Returns the current document head as an {@link Ext.Element}.
  7779. * @return Ext.Element The document head
  7780. * @method
  7781. */
  7782. getHead: function() {
  7783. var head;
  7784. return function() {
  7785. if (head == undefined) {
  7786. head = Ext.get(document.getElementsByTagName("head")[0]);
  7787. }
  7788. return head;
  7789. };
  7790. }(),
  7791. /**
  7792. * Returns the current HTML document object as an {@link Ext.Element}.
  7793. * @return Ext.Element The document
  7794. */
  7795. getDoc: function() {
  7796. return Ext.get(document);
  7797. },
  7798. /**
  7799. * This is shorthand reference to {@link Ext.ComponentManager#get}.
  7800. * Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#id id}
  7801. * @param {String} id The component {@link Ext.Component#id id}
  7802. * @return Ext.Component The Component, <tt>undefined</tt> if not found, or <tt>null</tt> if a
  7803. * Class was found.
  7804. */
  7805. getCmp: function(id) {
  7806. return Ext.ComponentManager.get(id);
  7807. },
  7808. /**
  7809. * Returns the current orientation of the mobile device
  7810. * @return {String} Either 'portrait' or 'landscape'
  7811. */
  7812. getOrientation: function() {
  7813. return window.innerHeight > window.innerWidth ? 'portrait' : 'landscape';
  7814. },
  7815. /**
  7816. * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the
  7817. * DOM (if applicable) and calling their destroy functions (if available). This method is primarily
  7818. * intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of
  7819. * {@link Ext.util.Observable} can be passed in. Any number of elements and/or components can be
  7820. * passed into this function in a single call as separate arguments.
  7821. * @param {Ext.Element/Ext.Component/Ext.Element[]/Ext.Component[]...} arg1
  7822. * An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy
  7823. */
  7824. destroy: function() {
  7825. var ln = arguments.length,
  7826. i, arg;
  7827. for (i = 0; i < ln; i++) {
  7828. arg = arguments[i];
  7829. if (arg) {
  7830. if (Ext.isArray(arg)) {
  7831. this.destroy.apply(this, arg);
  7832. }
  7833. else if (Ext.isFunction(arg.destroy)) {
  7834. arg.destroy();
  7835. }
  7836. else if (arg.dom) {
  7837. arg.remove();
  7838. }
  7839. }
  7840. }
  7841. },
  7842. /**
  7843. * Execute a callback function in a particular scope. If no function is passed the call is ignored.
  7844. *
  7845. * For example, these lines are equivalent:
  7846. *
  7847. * Ext.callback(myFunc, this, [arg1, arg2]);
  7848. * Ext.isFunction(myFunc) && myFunc.apply(this, [arg1, arg2]);
  7849. *
  7850. * @param {Function} callback The callback to execute
  7851. * @param {Object} scope (optional) The scope to execute in
  7852. * @param {Array} args (optional) The arguments to pass to the function
  7853. * @param {Number} delay (optional) Pass a number to delay the call by a number of milliseconds.
  7854. */
  7855. callback: function(callback, scope, args, delay){
  7856. if(Ext.isFunction(callback)){
  7857. args = args || [];
  7858. scope = scope || window;
  7859. if (delay) {
  7860. Ext.defer(callback, delay, scope, args);
  7861. } else {
  7862. callback.apply(scope, args);
  7863. }
  7864. }
  7865. },
  7866. /**
  7867. * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
  7868. * @param {String} value The string to encode
  7869. * @return {String} The encoded text
  7870. */
  7871. htmlEncode : function(value) {
  7872. return Ext.String.htmlEncode(value);
  7873. },
  7874. /**
  7875. * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
  7876. * @param {String} value The string to decode
  7877. * @return {String} The decoded text
  7878. */
  7879. htmlDecode : function(value) {
  7880. return Ext.String.htmlDecode(value);
  7881. },
  7882. /**
  7883. * Appends content to the query string of a URL, handling logic for whether to place
  7884. * a question mark or ampersand.
  7885. * @param {String} url The URL to append to.
  7886. * @param {String} s The content to append to the URL.
  7887. * @return (String) The resulting URL
  7888. */
  7889. urlAppend : function(url, s) {
  7890. if (!Ext.isEmpty(s)) {
  7891. return url + (url.indexOf('?') === -1 ? '?' : '&') + s;
  7892. }
  7893. return url;
  7894. }
  7895. });
  7896. Ext.ns = Ext.namespace;
  7897. // for old browsers
  7898. window.undefined = window.undefined;
  7899. /**
  7900. * @class Ext
  7901. * Ext core utilities and functions.
  7902. * @singleton
  7903. */
  7904. (function(){
  7905. /*
  7906. FF 3.6 - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.17) Gecko/20110420 Firefox/3.6.17
  7907. FF 4.0.1 - Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
  7908. FF 5.0 - Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0
  7909. IE6 - Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;)
  7910. IE7 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1;)
  7911. IE8 - Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
  7912. IE9 - Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
  7913. Chrome 11 - Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.60 Safari/534.24
  7914. Safari 5 - Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1
  7915. Opera 11.11 - Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11
  7916. */
  7917. var check = function(regex){
  7918. return regex.test(Ext.userAgent);
  7919. },
  7920. isStrict = document.compatMode == "CSS1Compat",
  7921. version = function (is, regex) {
  7922. var m;
  7923. return (is && (m = regex.exec(Ext.userAgent))) ? parseFloat(m[1]) : 0;
  7924. },
  7925. docMode = document.documentMode,
  7926. isOpera = check(/opera/),
  7927. isOpera10_5 = isOpera && check(/version\/10\.5/),
  7928. isChrome = check(/\bchrome\b/),
  7929. isWebKit = check(/webkit/),
  7930. isSafari = !isChrome && check(/safari/),
  7931. isSafari2 = isSafari && check(/applewebkit\/4/), // unique to Safari 2
  7932. isSafari3 = isSafari && check(/version\/3/),
  7933. isSafari4 = isSafari && check(/version\/4/),
  7934. isSafari5 = isSafari && check(/version\/5/),
  7935. isIE = !isOpera && check(/msie/),
  7936. isIE7 = isIE && (check(/msie 7/) || docMode == 7),
  7937. isIE8 = isIE && (check(/msie 8/) && docMode != 7 && docMode != 9 || docMode == 8),
  7938. isIE9 = isIE && (check(/msie 9/) && docMode != 7 && docMode != 8 || docMode == 9),
  7939. isIE6 = isIE && check(/msie 6/),
  7940. isGecko = !isWebKit && check(/gecko/),
  7941. isGecko3 = isGecko && check(/rv:1\.9/),
  7942. isGecko4 = isGecko && check(/rv:2\.0/),
  7943. isGecko5 = isGecko && check(/rv:5\./),
  7944. isFF3_0 = isGecko3 && check(/rv:1\.9\.0/),
  7945. isFF3_5 = isGecko3 && check(/rv:1\.9\.1/),
  7946. isFF3_6 = isGecko3 && check(/rv:1\.9\.2/),
  7947. isWindows = check(/windows|win32/),
  7948. isMac = check(/macintosh|mac os x/),
  7949. isLinux = check(/linux/),
  7950. scrollbarSize = null,
  7951. chromeVersion = version(true, /\bchrome\/(\d+\.\d+)/),
  7952. firefoxVersion = version(true, /\bfirefox\/(\d+\.\d+)/),
  7953. ieVersion = version(isIE, /msie (\d+\.\d+)/),
  7954. operaVersion = version(isOpera, /version\/(\d+\.\d+)/),
  7955. safariVersion = version(isSafari, /version\/(\d+\.\d+)/),
  7956. webKitVersion = version(isWebKit, /webkit\/(\d+\.\d+)/),
  7957. isSecure = /^https/i.test(window.location.protocol);
  7958. // remove css image flicker
  7959. try {
  7960. document.execCommand("BackgroundImageCache", false, true);
  7961. } catch(e) {}
  7962. Ext.setVersion('extjs', '4.0.7');
  7963. Ext.apply(Ext, {
  7964. /**
  7965. * URL to a blank file used by Ext when in secure mode for iframe src and onReady src to prevent
  7966. * the IE insecure content warning (<tt>'about:blank'</tt>, except for IE in secure mode, which is <tt>'javascript:""'</tt>).
  7967. * @type String
  7968. */
  7969. SSL_SECURE_URL : isSecure && isIE ? 'javascript:""' : 'about:blank',
  7970. /**
  7971. * True if the {@link Ext.fx.Anim} Class is available
  7972. * @type Boolean
  7973. * @property enableFx
  7974. */
  7975. /**
  7976. * True to scope the reset CSS to be just applied to Ext components. Note that this wraps root containers
  7977. * with an additional element. Also remember that when you turn on this option, you have to use ext-all-scoped {
  7978. * unless you use the bootstrap.js to load your javascript, in which case it will be handled for you.
  7979. * @type Boolean
  7980. */
  7981. scopeResetCSS : Ext.buildSettings.scopeResetCSS,
  7982. /**
  7983. * EXPERIMENTAL - True to cascade listener removal to child elements when an element is removed.
  7984. * Currently not optimized for performance.
  7985. * @type Boolean
  7986. */
  7987. enableNestedListenerRemoval : false,
  7988. /**
  7989. * Indicates whether to use native browser parsing for JSON methods.
  7990. * This option is ignored if the browser does not support native JSON methods.
  7991. * <b>Note: Native JSON methods will not work with objects that have functions.
  7992. * Also, property names must be quoted, otherwise the data will not parse.</b> (Defaults to false)
  7993. * @type Boolean
  7994. */
  7995. USE_NATIVE_JSON : false,
  7996. /**
  7997. * Return the dom node for the passed String (id), dom node, or Ext.Element.
  7998. * Optional 'strict' flag is needed for IE since it can return 'name' and
  7999. * 'id' elements by using getElementById.
  8000. * Here are some examples:
  8001. * <pre><code>
  8002. // gets dom node based on id
  8003. var elDom = Ext.getDom('elId');
  8004. // gets dom node based on the dom node
  8005. var elDom1 = Ext.getDom(elDom);
  8006. // If we don&#39;t know if we are working with an
  8007. // Ext.Element or a dom node use Ext.getDom
  8008. function(el){
  8009. var dom = Ext.getDom(el);
  8010. // do something with the dom node
  8011. }
  8012. * </code></pre>
  8013. * <b>Note</b>: the dom node to be found actually needs to exist (be rendered, etc)
  8014. * when this method is called to be successful.
  8015. * @param {String/HTMLElement/Ext.Element} el
  8016. * @return HTMLElement
  8017. */
  8018. getDom : function(el, strict) {
  8019. if (!el || !document) {
  8020. return null;
  8021. }
  8022. if (el.dom) {
  8023. return el.dom;
  8024. } else {
  8025. if (typeof el == 'string') {
  8026. var e = document.getElementById(el);
  8027. // IE returns elements with the 'name' and 'id' attribute.
  8028. // we do a strict check to return the element with only the id attribute
  8029. if (e && isIE && strict) {
  8030. if (el == e.getAttribute('id')) {
  8031. return e;
  8032. } else {
  8033. return null;
  8034. }
  8035. }
  8036. return e;
  8037. } else {
  8038. return el;
  8039. }
  8040. }
  8041. },
  8042. /**
  8043. * Removes a DOM node from the document.
  8044. * <p>Removes this element from the document, removes all DOM event listeners, and deletes the cache reference.
  8045. * All DOM event listeners are removed from this element. If {@link Ext#enableNestedListenerRemoval Ext.enableNestedListenerRemoval} is
  8046. * <code>true</code>, then DOM event listeners are also removed from all child nodes. The body node
  8047. * will be ignored if passed in.</p>
  8048. * @param {HTMLElement} node The node to remove
  8049. * @method
  8050. */
  8051. removeNode : isIE6 || isIE7 ? function() {
  8052. var d;
  8053. return function(n){
  8054. if(n && n.tagName != 'BODY'){
  8055. (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
  8056. d = d || document.createElement('div');
  8057. d.appendChild(n);
  8058. d.innerHTML = '';
  8059. delete Ext.cache[n.id];
  8060. }
  8061. };
  8062. }() : function(n) {
  8063. if (n && n.parentNode && n.tagName != 'BODY') {
  8064. (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
  8065. n.parentNode.removeChild(n);
  8066. delete Ext.cache[n.id];
  8067. }
  8068. },
  8069. isStrict: isStrict,
  8070. isIEQuirks: isIE && !isStrict,
  8071. /**
  8072. * True if the detected browser is Opera.
  8073. * @type Boolean
  8074. */
  8075. isOpera : isOpera,
  8076. /**
  8077. * True if the detected browser is Opera 10.5x.
  8078. * @type Boolean
  8079. */
  8080. isOpera10_5 : isOpera10_5,
  8081. /**
  8082. * True if the detected browser uses WebKit.
  8083. * @type Boolean
  8084. */
  8085. isWebKit : isWebKit,
  8086. /**
  8087. * True if the detected browser is Chrome.
  8088. * @type Boolean
  8089. */
  8090. isChrome : isChrome,
  8091. /**
  8092. * True if the detected browser is Safari.
  8093. * @type Boolean
  8094. */
  8095. isSafari : isSafari,
  8096. /**
  8097. * True if the detected browser is Safari 3.x.
  8098. * @type Boolean
  8099. */
  8100. isSafari3 : isSafari3,
  8101. /**
  8102. * True if the detected browser is Safari 4.x.
  8103. * @type Boolean
  8104. */
  8105. isSafari4 : isSafari4,
  8106. /**
  8107. * True if the detected browser is Safari 5.x.
  8108. * @type Boolean
  8109. */
  8110. isSafari5 : isSafari5,
  8111. /**
  8112. * True if the detected browser is Safari 2.x.
  8113. * @type Boolean
  8114. */
  8115. isSafari2 : isSafari2,
  8116. /**
  8117. * True if the detected browser is Internet Explorer.
  8118. * @type Boolean
  8119. */
  8120. isIE : isIE,
  8121. /**
  8122. * True if the detected browser is Internet Explorer 6.x.
  8123. * @type Boolean
  8124. */
  8125. isIE6 : isIE6,
  8126. /**
  8127. * True if the detected browser is Internet Explorer 7.x.
  8128. * @type Boolean
  8129. */
  8130. isIE7 : isIE7,
  8131. /**
  8132. * True if the detected browser is Internet Explorer 8.x.
  8133. * @type Boolean
  8134. */
  8135. isIE8 : isIE8,
  8136. /**
  8137. * True if the detected browser is Internet Explorer 9.x.
  8138. * @type Boolean
  8139. */
  8140. isIE9 : isIE9,
  8141. /**
  8142. * True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox).
  8143. * @type Boolean
  8144. */
  8145. isGecko : isGecko,
  8146. /**
  8147. * True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x).
  8148. * @type Boolean
  8149. */
  8150. isGecko3 : isGecko3,
  8151. /**
  8152. * True if the detected browser uses a Gecko 2.0+ layout engine (e.g. Firefox 4.x).
  8153. * @type Boolean
  8154. */
  8155. isGecko4 : isGecko4,
  8156. /**
  8157. * True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x).
  8158. * @type Boolean
  8159. */
  8160. isGecko5 : isGecko5,
  8161. /**
  8162. * True if the detected browser uses FireFox 3.0
  8163. * @type Boolean
  8164. */
  8165. isFF3_0 : isFF3_0,
  8166. /**
  8167. * True if the detected browser uses FireFox 3.5
  8168. * @type Boolean
  8169. */
  8170. isFF3_5 : isFF3_5,
  8171. /**
  8172. * True if the detected browser uses FireFox 3.6
  8173. * @type Boolean
  8174. */
  8175. isFF3_6 : isFF3_6,
  8176. /**
  8177. * True if the detected browser uses FireFox 4
  8178. * @type Boolean
  8179. */
  8180. isFF4 : 4 <= firefoxVersion && firefoxVersion < 5,
  8181. /**
  8182. * True if the detected browser uses FireFox 5
  8183. * @type Boolean
  8184. */
  8185. isFF5 : 5 <= firefoxVersion && firefoxVersion < 6,
  8186. /**
  8187. * True if the detected platform is Linux.
  8188. * @type Boolean
  8189. */
  8190. isLinux : isLinux,
  8191. /**
  8192. * True if the detected platform is Windows.
  8193. * @type Boolean
  8194. */
  8195. isWindows : isWindows,
  8196. /**
  8197. * True if the detected platform is Mac OS.
  8198. * @type Boolean
  8199. */
  8200. isMac : isMac,
  8201. /**
  8202. * The current version of Chrome (0 if the browser is not Chrome).
  8203. * @type Number
  8204. */
  8205. chromeVersion: chromeVersion,
  8206. /**
  8207. * The current version of Firefox (0 if the browser is not Firefox).
  8208. * @type Number
  8209. */
  8210. firefoxVersion: firefoxVersion,
  8211. /**
  8212. * The current version of IE (0 if the browser is not IE). This does not account
  8213. * for the documentMode of the current page, which is factored into {@link #isIE7},
  8214. * {@link #isIE8} and {@link #isIE9}. Thus this is not always true:
  8215. *
  8216. * Ext.isIE8 == (Ext.ieVersion == 8)
  8217. *
  8218. * @type Number
  8219. * @markdown
  8220. */
  8221. ieVersion: ieVersion,
  8222. /**
  8223. * The current version of Opera (0 if the browser is not Opera).
  8224. * @type Number
  8225. */
  8226. operaVersion: operaVersion,
  8227. /**
  8228. * The current version of Safari (0 if the browser is not Safari).
  8229. * @type Number
  8230. */
  8231. safariVersion: safariVersion,
  8232. /**
  8233. * The current version of WebKit (0 if the browser does not use WebKit).
  8234. * @type Number
  8235. */
  8236. webKitVersion: webKitVersion,
  8237. /**
  8238. * True if the page is running over SSL
  8239. * @type Boolean
  8240. */
  8241. isSecure: isSecure,
  8242. /**
  8243. * URL to a 1x1 transparent gif image used by Ext to create inline icons with CSS background images.
  8244. * In older versions of IE, this defaults to "http://sencha.com/s.gif" and you should change this to a URL on your server.
  8245. * For other browsers it uses an inline data URL.
  8246. * @type String
  8247. */
  8248. BLANK_IMAGE_URL : (isIE6 || isIE7) ? '/' + '/www.sencha.com/s.gif' : 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==',
  8249. /**
  8250. * <p>Utility method for returning a default value if the passed value is empty.</p>
  8251. * <p>The value is deemed to be empty if it is<div class="mdetail-params"><ul>
  8252. * <li>null</li>
  8253. * <li>undefined</li>
  8254. * <li>an empty array</li>
  8255. * <li>a zero length string (Unless the <tt>allowBlank</tt> parameter is <tt>true</tt>)</li>
  8256. * </ul></div>
  8257. * @param {Object} value The value to test
  8258. * @param {Object} defaultValue The value to return if the original value is empty
  8259. * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
  8260. * @return {Object} value, if non-empty, else defaultValue
  8261. * @deprecated 4.0.0 Use {@link Ext#valueFrom} instead
  8262. */
  8263. value : function(v, defaultValue, allowBlank){
  8264. return Ext.isEmpty(v, allowBlank) ? defaultValue : v;
  8265. },
  8266. /**
  8267. * Escapes the passed string for use in a regular expression
  8268. * @param {String} str
  8269. * @return {String}
  8270. * @deprecated 4.0.0 Use {@link Ext.String#escapeRegex} instead
  8271. */
  8272. escapeRe : function(s) {
  8273. return s.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1");
  8274. },
  8275. /**
  8276. * Applies event listeners to elements by selectors when the document is ready.
  8277. * The event name is specified with an <tt>&#64;</tt> suffix.
  8278. * <pre><code>
  8279. Ext.addBehaviors({
  8280. // add a listener for click on all anchors in element with id foo
  8281. '#foo a&#64;click' : function(e, t){
  8282. // do something
  8283. },
  8284. // add the same listener to multiple selectors (separated by comma BEFORE the &#64;)
  8285. '#foo a, #bar span.some-class&#64;mouseover' : function(){
  8286. // do something
  8287. }
  8288. });
  8289. * </code></pre>
  8290. * @param {Object} obj The list of behaviors to apply
  8291. */
  8292. addBehaviors : function(o){
  8293. if(!Ext.isReady){
  8294. Ext.onReady(function(){
  8295. Ext.addBehaviors(o);
  8296. });
  8297. } else {
  8298. var cache = {}, // simple cache for applying multiple behaviors to same selector does query multiple times
  8299. parts,
  8300. b,
  8301. s;
  8302. for (b in o) {
  8303. if ((parts = b.split('@'))[1]) { // for Object prototype breakers
  8304. s = parts[0];
  8305. if(!cache[s]){
  8306. cache[s] = Ext.select(s);
  8307. }
  8308. cache[s].on(parts[1], o[b]);
  8309. }
  8310. }
  8311. cache = null;
  8312. }
  8313. },
  8314. /**
  8315. * Returns the size of the browser scrollbars. This can differ depending on
  8316. * operating system settings, such as the theme or font size.
  8317. * @param {Boolean} force (optional) true to force a recalculation of the value.
  8318. * @return {Object} An object containing the width of a vertical scrollbar and the
  8319. * height of a horizontal scrollbar.
  8320. */
  8321. getScrollbarSize: function (force) {
  8322. if(!Ext.isReady){
  8323. return 0;
  8324. }
  8325. if(force === true || scrollbarSize === null){
  8326. // BrowserBug: IE9
  8327. // When IE9 positions an element offscreen via offsets, the offsetWidth is
  8328. // inaccurately reported. For IE9 only, we render on screen before removing.
  8329. var cssClass = Ext.isIE9 ? '' : Ext.baseCSSPrefix + 'hide-offsets',
  8330. // Append our div, do our calculation and then remove it
  8331. div = Ext.getBody().createChild('<div class="' + cssClass + '" style="width:100px;height:50px;overflow:hidden;"><div style="height:200px;"></div></div>'),
  8332. child = div.child('div', true),
  8333. w1 = child.offsetWidth;
  8334. div.setStyle('overflow', (Ext.isWebKit || Ext.isGecko) ? 'auto' : 'scroll');
  8335. var w2 = child.offsetWidth, width = w1 - w2;
  8336. div.remove();
  8337. // We assume width == height for now. TODO: is this always true?
  8338. scrollbarSize = { width: width, height: width };
  8339. }
  8340. return scrollbarSize;
  8341. },
  8342. /**
  8343. * Utility method for getting the width of the browser's vertical scrollbar. This
  8344. * can differ depending on operating system settings, such as the theme or font size.
  8345. *
  8346. * This method is deprected in favor of {@link #getScrollbarSize}.
  8347. *
  8348. * @param {Boolean} force (optional) true to force a recalculation of the value.
  8349. * @return {Number} The width of a vertical scrollbar.
  8350. * @deprecated
  8351. */
  8352. getScrollBarWidth: function(force){
  8353. var size = Ext.getScrollbarSize(force);
  8354. return size.width + 2; // legacy fudge factor
  8355. },
  8356. /**
  8357. * Copies a set of named properties fom the source object to the destination object.
  8358. *
  8359. * Example:
  8360. *
  8361. * ImageComponent = Ext.extend(Ext.Component, {
  8362. * initComponent: function() {
  8363. * this.autoEl = { tag: 'img' };
  8364. * MyComponent.superclass.initComponent.apply(this, arguments);
  8365. * this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height');
  8366. * }
  8367. * });
  8368. *
  8369. * Important note: To borrow class prototype methods, use {@link Ext.Base#borrow} instead.
  8370. *
  8371. * @param {Object} dest The destination object.
  8372. * @param {Object} source The source object.
  8373. * @param {String/String[]} names Either an Array of property names, or a comma-delimited list
  8374. * of property names to copy.
  8375. * @param {Boolean} usePrototypeKeys (Optional) Defaults to false. Pass true to copy keys off of the prototype as well as the instance.
  8376. * @return {Object} The modified object.
  8377. */
  8378. copyTo : function(dest, source, names, usePrototypeKeys){
  8379. if(typeof names == 'string'){
  8380. names = names.split(/[,;\s]/);
  8381. }
  8382. Ext.each(names, function(name){
  8383. if(usePrototypeKeys || source.hasOwnProperty(name)){
  8384. dest[name] = source[name];
  8385. }
  8386. }, this);
  8387. return dest;
  8388. },
  8389. /**
  8390. * Attempts to destroy and then remove a set of named properties of the passed object.
  8391. * @param {Object} o The object (most likely a Component) who's properties you wish to destroy.
  8392. * @param {String...} args One or more names of the properties to destroy and remove from the object.
  8393. */
  8394. destroyMembers : function(o){
  8395. for (var i = 1, a = arguments, len = a.length; i < len; i++) {
  8396. Ext.destroy(o[a[i]]);
  8397. delete o[a[i]];
  8398. }
  8399. },
  8400. /**
  8401. * Logs a message. If a console is present it will be used. On Opera, the method
  8402. * "opera.postError" is called. In other cases, the message is logged to an array
  8403. * "Ext.log.out". An attached debugger can watch this array and view the log. The
  8404. * log buffer is limited to a maximum of "Ext.log.max" entries (defaults to 250).
  8405. * The `Ext.log.out` array can also be written to a popup window by entering the
  8406. * following in the URL bar (a "bookmarklet"):
  8407. *
  8408. * javascript:void(Ext.log.show());
  8409. *
  8410. * If additional parameters are passed, they are joined and appended to the message.
  8411. * A technique for tracing entry and exit of a function is this:
  8412. *
  8413. * function foo () {
  8414. * Ext.log({ indent: 1 }, '>> foo');
  8415. *
  8416. * // log statements in here or methods called from here will be indented
  8417. * // by one step
  8418. *
  8419. * Ext.log({ outdent: 1 }, '<< foo');
  8420. * }
  8421. *
  8422. * This method does nothing in a release build.
  8423. *
  8424. * @param {String/Object} message The message to log or an options object with any
  8425. * of the following properties:
  8426. *
  8427. * - `msg`: The message to log (required).
  8428. * - `level`: One of: "error", "warn", "info" or "log" (the default is "log").
  8429. * - `dump`: An object to dump to the log as part of the message.
  8430. * - `stack`: True to include a stack trace in the log.
  8431. * - `indent`: Cause subsequent log statements to be indented one step.
  8432. * - `outdent`: Cause this and following statements to be one step less indented.
  8433. * @markdown
  8434. */
  8435. log :
  8436. Ext.emptyFn,
  8437. /**
  8438. * Partitions the set into two sets: a true set and a false set.
  8439. * Example:
  8440. * Example2:
  8441. * <pre><code>
  8442. // Example 1:
  8443. Ext.partition([true, false, true, true, false]); // [[true, true, true], [false, false]]
  8444. // Example 2:
  8445. Ext.partition(
  8446. Ext.query("p"),
  8447. function(val){
  8448. return val.className == "class1"
  8449. }
  8450. );
  8451. // true are those paragraph elements with a className of "class1",
  8452. // false set are those that do not have that className.
  8453. * </code></pre>
  8454. * @param {Array/NodeList} arr The array to partition
  8455. * @param {Function} truth (optional) a function to determine truth. If this is omitted the element
  8456. * itself must be able to be evaluated for its truthfulness.
  8457. * @return {Array} [array of truish values, array of falsy values]
  8458. * @deprecated 4.0.0 Will be removed in the next major version
  8459. */
  8460. partition : function(arr, truth){
  8461. var ret = [[],[]];
  8462. Ext.each(arr, function(v, i, a) {
  8463. ret[ (truth && truth(v, i, a)) || (!truth && v) ? 0 : 1].push(v);
  8464. });
  8465. return ret;
  8466. },
  8467. /**
  8468. * Invokes a method on each item in an Array.
  8469. * <pre><code>
  8470. // Example:
  8471. Ext.invoke(Ext.query("p"), "getAttribute", "id");
  8472. // [el1.getAttribute("id"), el2.getAttribute("id"), ..., elN.getAttribute("id")]
  8473. * </code></pre>
  8474. * @param {Array/NodeList} arr The Array of items to invoke the method on.
  8475. * @param {String} methodName The method name to invoke.
  8476. * @param {Object...} args Arguments to send into the method invocation.
  8477. * @return {Array} The results of invoking the method on each item in the array.
  8478. * @deprecated 4.0.0 Will be removed in the next major version
  8479. */
  8480. invoke : function(arr, methodName){
  8481. var ret = [],
  8482. args = Array.prototype.slice.call(arguments, 2);
  8483. Ext.each(arr, function(v,i) {
  8484. if (v && typeof v[methodName] == 'function') {
  8485. ret.push(v[methodName].apply(v, args));
  8486. } else {
  8487. ret.push(undefined);
  8488. }
  8489. });
  8490. return ret;
  8491. },
  8492. /**
  8493. * <p>Zips N sets together.</p>
  8494. * <pre><code>
  8495. // Example 1:
  8496. Ext.zip([1,2,3],[4,5,6]); // [[1,4],[2,5],[3,6]]
  8497. // Example 2:
  8498. Ext.zip(
  8499. [ "+", "-", "+"],
  8500. [ 12, 10, 22],
  8501. [ 43, 15, 96],
  8502. function(a, b, c){
  8503. return "$" + a + "" + b + "." + c
  8504. }
  8505. ); // ["$+12.43", "$-10.15", "$+22.96"]
  8506. * </code></pre>
  8507. * @param {Array/NodeList...} arr This argument may be repeated. Array(s) to contribute values.
  8508. * @param {Function} zipper (optional) The last item in the argument list. This will drive how the items are zipped together.
  8509. * @return {Array} The zipped set.
  8510. * @deprecated 4.0.0 Will be removed in the next major version
  8511. */
  8512. zip : function(){
  8513. var parts = Ext.partition(arguments, function( val ){ return typeof val != 'function'; }),
  8514. arrs = parts[0],
  8515. fn = parts[1][0],
  8516. len = Ext.max(Ext.pluck(arrs, "length")),
  8517. ret = [];
  8518. for (var i = 0; i < len; i++) {
  8519. ret[i] = [];
  8520. if(fn){
  8521. ret[i] = fn.apply(fn, Ext.pluck(arrs, i));
  8522. }else{
  8523. for (var j = 0, aLen = arrs.length; j < aLen; j++){
  8524. ret[i].push( arrs[j][i] );
  8525. }
  8526. }
  8527. }
  8528. return ret;
  8529. },
  8530. /**
  8531. * Turns an array into a sentence, joined by a specified connector - e.g.:
  8532. * Ext.toSentence(['Adama', 'Tigh', 'Roslin']); //'Adama, Tigh and Roslin'
  8533. * Ext.toSentence(['Adama', 'Tigh', 'Roslin'], 'or'); //'Adama, Tigh or Roslin'
  8534. * @param {String[]} items The array to create a sentence from
  8535. * @param {String} connector The string to use to connect the last two words. Usually 'and' or 'or' - defaults to 'and'.
  8536. * @return {String} The sentence string
  8537. * @deprecated 4.0.0 Will be removed in the next major version
  8538. */
  8539. toSentence: function(items, connector) {
  8540. var length = items.length;
  8541. if (length <= 1) {
  8542. return items[0];
  8543. } else {
  8544. var head = items.slice(0, length - 1),
  8545. tail = items[length - 1];
  8546. return Ext.util.Format.format("{0} {1} {2}", head.join(", "), connector || 'and', tail);
  8547. }
  8548. },
  8549. /**
  8550. * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
  8551. * you may want to set this to true.
  8552. * @type Boolean
  8553. */
  8554. useShims: isIE6
  8555. });
  8556. })();
  8557. /**
  8558. * Loads Ext.app.Application class and starts it up with given configuration after the page is ready.
  8559. *
  8560. * See Ext.app.Application for details.
  8561. *
  8562. * @param {Object} config
  8563. */
  8564. Ext.application = function(config) {
  8565. Ext.require('Ext.app.Application');
  8566. Ext.onReady(function() {
  8567. Ext.create('Ext.app.Application', config);
  8568. });
  8569. };
  8570. /**
  8571. * @class Ext.util.Format
  8572. This class is a centralized place for formatting functions. It includes
  8573. functions to format various different types of data, such as text, dates and numeric values.
  8574. __Localization__
  8575. This class contains several options for localization. These can be set once the library has loaded,
  8576. all calls to the functions from that point will use the locale settings that were specified.
  8577. Options include:
  8578. - thousandSeparator
  8579. - decimalSeparator
  8580. - currenyPrecision
  8581. - currencySign
  8582. - currencyAtEnd
  8583. This class also uses the default date format defined here: {@link Ext.Date#defaultFormat}.
  8584. __Using with renderers__
  8585. There are two helper functions that return a new function that can be used in conjunction with
  8586. grid renderers:
  8587. columns: [{
  8588. dataIndex: 'date',
  8589. renderer: Ext.util.Format.dateRenderer('Y-m-d')
  8590. }, {
  8591. dataIndex: 'time',
  8592. renderer: Ext.util.Format.numberRenderer('0.000')
  8593. }]
  8594. Functions that only take a single argument can also be passed directly:
  8595. columns: [{
  8596. dataIndex: 'cost',
  8597. renderer: Ext.util.Format.usMoney
  8598. }, {
  8599. dataIndex: 'productCode',
  8600. renderer: Ext.util.Format.uppercase
  8601. }]
  8602. __Using with XTemplates__
  8603. XTemplates can also directly use Ext.util.Format functions:
  8604. new Ext.XTemplate([
  8605. 'Date: {startDate:date("Y-m-d")}',
  8606. 'Cost: {cost:usMoney}'
  8607. ]);
  8608. * @markdown
  8609. * @singleton
  8610. */
  8611. (function() {
  8612. Ext.ns('Ext.util');
  8613. Ext.util.Format = {};
  8614. var UtilFormat = Ext.util.Format,
  8615. stripTagsRE = /<\/?[^>]+>/gi,
  8616. stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
  8617. nl2brRe = /\r?\n/g,
  8618. // A RegExp to remove from a number format string, all characters except digits and '.'
  8619. formatCleanRe = /[^\d\.]/g,
  8620. // A RegExp to remove from a number format string, all characters except digits and the local decimal separator.
  8621. // Created on first use. The local decimal separator character must be initialized for this to be created.
  8622. I18NFormatCleanRe;
  8623. Ext.apply(UtilFormat, {
  8624. /**
  8625. * @property {String} thousandSeparator
  8626. * <p>The character that the {@link #number} function uses as a thousand separator.</p>
  8627. * <p>This may be overridden in a locale file.</p>
  8628. */
  8629. thousandSeparator: ',',
  8630. /**
  8631. * @property {String} decimalSeparator
  8632. * <p>The character that the {@link #number} function uses as a decimal point.</p>
  8633. * <p>This may be overridden in a locale file.</p>
  8634. */
  8635. decimalSeparator: '.',
  8636. /**
  8637. * @property {Number} currencyPrecision
  8638. * <p>The number of decimal places that the {@link #currency} function displays.</p>
  8639. * <p>This may be overridden in a locale file.</p>
  8640. */
  8641. currencyPrecision: 2,
  8642. /**
  8643. * @property {String} currencySign
  8644. * <p>The currency sign that the {@link #currency} function displays.</p>
  8645. * <p>This may be overridden in a locale file.</p>
  8646. */
  8647. currencySign: '$',
  8648. /**
  8649. * @property {Boolean} currencyAtEnd
  8650. * <p>This may be set to <code>true</code> to make the {@link #currency} function
  8651. * append the currency sign to the formatted value.</p>
  8652. * <p>This may be overridden in a locale file.</p>
  8653. */
  8654. currencyAtEnd: false,
  8655. /**
  8656. * Checks a reference and converts it to empty string if it is undefined
  8657. * @param {Object} value Reference to check
  8658. * @return {Object} Empty string if converted, otherwise the original value
  8659. */
  8660. undef : function(value) {
  8661. return value !== undefined ? value : "";
  8662. },
  8663. /**
  8664. * Checks a reference and converts it to the default value if it's empty
  8665. * @param {Object} value Reference to check
  8666. * @param {String} defaultValue The value to insert of it's undefined (defaults to "")
  8667. * @return {String}
  8668. */
  8669. defaultValue : function(value, defaultValue) {
  8670. return value !== undefined && value !== '' ? value : defaultValue;
  8671. },
  8672. /**
  8673. * Returns a substring from within an original string
  8674. * @param {String} value The original text
  8675. * @param {Number} start The start index of the substring
  8676. * @param {Number} length The length of the substring
  8677. * @return {String} The substring
  8678. */
  8679. substr : function(value, start, length) {
  8680. return String(value).substr(start, length);
  8681. },
  8682. /**
  8683. * Converts a string to all lower case letters
  8684. * @param {String} value The text to convert
  8685. * @return {String} The converted text
  8686. */
  8687. lowercase : function(value) {
  8688. return String(value).toLowerCase();
  8689. },
  8690. /**
  8691. * Converts a string to all upper case letters
  8692. * @param {String} value The text to convert
  8693. * @return {String} The converted text
  8694. */
  8695. uppercase : function(value) {
  8696. return String(value).toUpperCase();
  8697. },
  8698. /**
  8699. * Format a number as US currency
  8700. * @param {Number/String} value The numeric value to format
  8701. * @return {String} The formatted currency string
  8702. */
  8703. usMoney : function(v) {
  8704. return UtilFormat.currency(v, '$', 2);
  8705. },
  8706. /**
  8707. * Format a number as a currency
  8708. * @param {Number/String} value The numeric value to format
  8709. * @param {String} sign The currency sign to use (defaults to {@link #currencySign})
  8710. * @param {Number} decimals The number of decimals to use for the currency (defaults to {@link #currencyPrecision})
  8711. * @param {Boolean} end True if the currency sign should be at the end of the string (defaults to {@link #currencyAtEnd})
  8712. * @return {String} The formatted currency string
  8713. */
  8714. currency: function(v, currencySign, decimals, end) {
  8715. var negativeSign = '',
  8716. format = ",0",
  8717. i = 0;
  8718. v = v - 0;
  8719. if (v < 0) {
  8720. v = -v;
  8721. negativeSign = '-';
  8722. }
  8723. decimals = decimals || UtilFormat.currencyPrecision;
  8724. format += format + (decimals > 0 ? '.' : '');
  8725. for (; i < decimals; i++) {
  8726. format += '0';
  8727. }
  8728. v = UtilFormat.number(v, format);
  8729. if ((end || UtilFormat.currencyAtEnd) === true) {
  8730. return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign);
  8731. } else {
  8732. return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v);
  8733. }
  8734. },
  8735. /**
  8736. * Formats the passed date using the specified format pattern.
  8737. * @param {String/Date} value The value to format. If a string is passed, it is converted to a Date by the Javascript
  8738. * Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method.
  8739. * @param {String} format (Optional) Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
  8740. * @return {String} The formatted date string.
  8741. */
  8742. date: function(v, format) {
  8743. if (!v) {
  8744. return "";
  8745. }
  8746. if (!Ext.isDate(v)) {
  8747. v = new Date(Date.parse(v));
  8748. }
  8749. return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat);
  8750. },
  8751. /**
  8752. * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
  8753. * @param {String} format Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
  8754. * @return {Function} The date formatting function
  8755. */
  8756. dateRenderer : function(format) {
  8757. return function(v) {
  8758. return UtilFormat.date(v, format);
  8759. };
  8760. },
  8761. /**
  8762. * Strips all HTML tags
  8763. * @param {Object} value The text from which to strip tags
  8764. * @return {String} The stripped text
  8765. */
  8766. stripTags : function(v) {
  8767. return !v ? v : String(v).replace(stripTagsRE, "");
  8768. },
  8769. /**
  8770. * Strips all script tags
  8771. * @param {Object} value The text from which to strip script tags
  8772. * @return {String} The stripped text
  8773. */
  8774. stripScripts : function(v) {
  8775. return !v ? v : String(v).replace(stripScriptsRe, "");
  8776. },
  8777. /**
  8778. * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
  8779. * @param {Number/String} size The numeric value to format
  8780. * @return {String} The formatted file size
  8781. */
  8782. fileSize : function(size) {
  8783. if (size < 1024) {
  8784. return size + " bytes";
  8785. } else if (size < 1048576) {
  8786. return (Math.round(((size*10) / 1024))/10) + " KB";
  8787. } else {
  8788. return (Math.round(((size*10) / 1048576))/10) + " MB";
  8789. }
  8790. },
  8791. /**
  8792. * It does simple math for use in a template, for example:<pre><code>
  8793. * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
  8794. * </code></pre>
  8795. * @return {Function} A function that operates on the passed value.
  8796. * @method
  8797. */
  8798. math : function(){
  8799. var fns = {};
  8800. return function(v, a){
  8801. if (!fns[a]) {
  8802. fns[a] = Ext.functionFactory('v', 'return v ' + a + ';');
  8803. }
  8804. return fns[a](v);
  8805. };
  8806. }(),
  8807. /**
  8808. * Rounds the passed number to the required decimal precision.
  8809. * @param {Number/String} value The numeric value to round.
  8810. * @param {Number} precision The number of decimal places to which to round the first parameter's value.
  8811. * @return {Number} The rounded value.
  8812. */
  8813. round : function(value, precision) {
  8814. var result = Number(value);
  8815. if (typeof precision == 'number') {
  8816. precision = Math.pow(10, precision);
  8817. result = Math.round(value * precision) / precision;
  8818. }
  8819. return result;
  8820. },
  8821. /**
  8822. * <p>Formats the passed number according to the passed format string.</p>
  8823. * <p>The number of digits after the decimal separator character specifies the number of
  8824. * decimal places in the resulting string. The <u>local-specific</u> decimal character is used in the result.</p>
  8825. * <p>The <i>presence</i> of a thousand separator character in the format string specifies that
  8826. * the <u>locale-specific</u> thousand separator (if any) is inserted separating thousand groups.</p>
  8827. * <p>By default, "," is expected as the thousand separator, and "." is expected as the decimal separator.</p>
  8828. * <p><b>New to Ext JS 4</b></p>
  8829. * <p>Locale-specific characters are always used in the formatted output when inserting
  8830. * thousand and decimal separators.</p>
  8831. * <p>The format string must specify separator characters according to US/UK conventions ("," as the
  8832. * thousand separator, and "." as the decimal separator)</p>
  8833. * <p>To allow specification of format strings according to local conventions for separator characters, add
  8834. * the string <code>/i</code> to the end of the format string.</p>
  8835. * <div style="margin-left:40px">examples (123456.789):
  8836. * <div style="margin-left:10px">
  8837. * 0 - (123456) show only digits, no precision<br>
  8838. * 0.00 - (123456.78) show only digits, 2 precision<br>
  8839. * 0.0000 - (123456.7890) show only digits, 4 precision<br>
  8840. * 0,000 - (123,456) show comma and digits, no precision<br>
  8841. * 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
  8842. * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
  8843. * To allow specification of the formatting string using UK/US grouping characters (,) and decimal (.) for international numbers, add /i to the end.
  8844. * For example: 0.000,00/i
  8845. * </div></div>
  8846. * @param {Number} v The number to format.
  8847. * @param {String} format The way you would like to format this text.
  8848. * @return {String} The formatted number.
  8849. */
  8850. number: function(v, formatString) {
  8851. if (!formatString) {
  8852. return v;
  8853. }
  8854. v = Ext.Number.from(v, NaN);
  8855. if (isNaN(v)) {
  8856. return '';
  8857. }
  8858. var comma = UtilFormat.thousandSeparator,
  8859. dec = UtilFormat.decimalSeparator,
  8860. i18n = false,
  8861. neg = v < 0,
  8862. hasComma,
  8863. psplit;
  8864. v = Math.abs(v);
  8865. // The "/i" suffix allows caller to use a locale-specific formatting string.
  8866. // Clean the format string by removing all but numerals and the decimal separator.
  8867. // Then split the format string into pre and post decimal segments according to *what* the
  8868. // decimal separator is. If they are specifying "/i", they are using the local convention in the format string.
  8869. if (formatString.substr(formatString.length - 2) == '/i') {
  8870. if (!I18NFormatCleanRe) {
  8871. I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g');
  8872. }
  8873. formatString = formatString.substr(0, formatString.length - 2);
  8874. i18n = true;
  8875. hasComma = formatString.indexOf(comma) != -1;
  8876. psplit = formatString.replace(I18NFormatCleanRe, '').split(dec);
  8877. } else {
  8878. hasComma = formatString.indexOf(',') != -1;
  8879. psplit = formatString.replace(formatCleanRe, '').split('.');
  8880. }
  8881. if (1 < psplit.length) {
  8882. v = v.toFixed(psplit[1].length);
  8883. } else if(2 < psplit.length) {
  8884. } else {
  8885. v = v.toFixed(0);
  8886. }
  8887. var fnum = v.toString();
  8888. psplit = fnum.split('.');
  8889. if (hasComma) {
  8890. var cnum = psplit[0],
  8891. parr = [],
  8892. j = cnum.length,
  8893. m = Math.floor(j / 3),
  8894. n = cnum.length % 3 || 3,
  8895. i;
  8896. for (i = 0; i < j; i += n) {
  8897. if (i !== 0) {
  8898. n = 3;
  8899. }
  8900. parr[parr.length] = cnum.substr(i, n);
  8901. m -= 1;
  8902. }
  8903. fnum = parr.join(comma);
  8904. if (psplit[1]) {
  8905. fnum += dec + psplit[1];
  8906. }
  8907. } else {
  8908. if (psplit[1]) {
  8909. fnum = psplit[0] + dec + psplit[1];
  8910. }
  8911. }
  8912. if (neg) {
  8913. /*
  8914. * Edge case. If we have a very small negative number it will get rounded to 0,
  8915. * however the initial check at the top will still report as negative. Replace
  8916. * everything but 1-9 and check if the string is empty to determine a 0 value.
  8917. */
  8918. neg = fnum.replace(/[^1-9]/g, '') !== '';
  8919. }
  8920. return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum);
  8921. },
  8922. /**
  8923. * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
  8924. * @param {String} format Any valid number format string for {@link #number}
  8925. * @return {Function} The number formatting function
  8926. */
  8927. numberRenderer : function(format) {
  8928. return function(v) {
  8929. return UtilFormat.number(v, format);
  8930. };
  8931. },
  8932. /**
  8933. * Selectively do a plural form of a word based on a numeric value. For example, in a template,
  8934. * {commentCount:plural("Comment")} would result in "1 Comment" if commentCount was 1 or would be "x Comments"
  8935. * if the value is 0 or greater than 1.
  8936. * @param {Number} value The value to compare against
  8937. * @param {String} singular The singular form of the word
  8938. * @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
  8939. */
  8940. plural : function(v, s, p) {
  8941. return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
  8942. },
  8943. /**
  8944. * Converts newline characters to the HTML tag &lt;br/>
  8945. * @param {String} The string value to format.
  8946. * @return {String} The string with embedded &lt;br/> tags in place of newlines.
  8947. */
  8948. nl2br : function(v) {
  8949. return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
  8950. },
  8951. /**
  8952. * Alias for {@link Ext.String#capitalize}.
  8953. * @method
  8954. * @alias Ext.String#capitalize
  8955. */
  8956. capitalize: Ext.String.capitalize,
  8957. /**
  8958. * Alias for {@link Ext.String#ellipsis}.
  8959. * @method
  8960. * @alias Ext.String#ellipsis
  8961. */
  8962. ellipsis: Ext.String.ellipsis,
  8963. /**
  8964. * Alias for {@link Ext.String#format}.
  8965. * @method
  8966. * @alias Ext.String#format
  8967. */
  8968. format: Ext.String.format,
  8969. /**
  8970. * Alias for {@link Ext.String#htmlDecode}.
  8971. * @method
  8972. * @alias Ext.String#htmlDecode
  8973. */
  8974. htmlDecode: Ext.String.htmlDecode,
  8975. /**
  8976. * Alias for {@link Ext.String#htmlEncode}.
  8977. * @method
  8978. * @alias Ext.String#htmlEncode
  8979. */
  8980. htmlEncode: Ext.String.htmlEncode,
  8981. /**
  8982. * Alias for {@link Ext.String#leftPad}.
  8983. * @method
  8984. * @alias Ext.String#leftPad
  8985. */
  8986. leftPad: Ext.String.leftPad,
  8987. /**
  8988. * Alias for {@link Ext.String#trim}.
  8989. * @method
  8990. * @alias Ext.String#trim
  8991. */
  8992. trim : Ext.String.trim,
  8993. /**
  8994. * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
  8995. * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
  8996. * @param {Number/String} v The encoded margins
  8997. * @return {Object} An object with margin sizes for top, right, bottom and left
  8998. */
  8999. parseBox : function(box) {
  9000. if (Ext.isNumber(box)) {
  9001. box = box.toString();
  9002. }
  9003. var parts = box.split(' '),
  9004. ln = parts.length;
  9005. if (ln == 1) {
  9006. parts[1] = parts[2] = parts[3] = parts[0];
  9007. }
  9008. else if (ln == 2) {
  9009. parts[2] = parts[0];
  9010. parts[3] = parts[1];
  9011. }
  9012. else if (ln == 3) {
  9013. parts[3] = parts[1];
  9014. }
  9015. return {
  9016. top :parseInt(parts[0], 10) || 0,
  9017. right :parseInt(parts[1], 10) || 0,
  9018. bottom:parseInt(parts[2], 10) || 0,
  9019. left :parseInt(parts[3], 10) || 0
  9020. };
  9021. },
  9022. /**
  9023. * Escapes the passed string for use in a regular expression
  9024. * @param {String} str
  9025. * @return {String}
  9026. */
  9027. escapeRegex : function(s) {
  9028. return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1");
  9029. }
  9030. });
  9031. })();
  9032. /**
  9033. * @class Ext.util.TaskRunner
  9034. * Provides the ability to execute one or more arbitrary tasks in a multithreaded
  9035. * manner. Generally, you can use the singleton {@link Ext.TaskManager} instead, but
  9036. * if needed, you can create separate instances of TaskRunner. Any number of
  9037. * separate tasks can be started at any time and will run independently of each
  9038. * other. Example usage:
  9039. * <pre><code>
  9040. // Start a simple clock task that updates a div once per second
  9041. var updateClock = function(){
  9042. Ext.fly('clock').update(new Date().format('g:i:s A'));
  9043. }
  9044. var task = {
  9045. run: updateClock,
  9046. interval: 1000 //1 second
  9047. }
  9048. var runner = new Ext.util.TaskRunner();
  9049. runner.start(task);
  9050. // equivalent using TaskManager
  9051. Ext.TaskManager.start({
  9052. run: updateClock,
  9053. interval: 1000
  9054. });
  9055. * </code></pre>
  9056. * <p>See the {@link #start} method for details about how to configure a task object.</p>
  9057. * Also see {@link Ext.util.DelayedTask}.
  9058. *
  9059. * @constructor
  9060. * @param {Number} [interval=10] The minimum precision in milliseconds supported by this TaskRunner instance
  9061. */
  9062. Ext.ns('Ext.util');
  9063. Ext.util.TaskRunner = function(interval) {
  9064. interval = interval || 10;
  9065. var tasks = [],
  9066. removeQueue = [],
  9067. id = 0,
  9068. running = false,
  9069. // private
  9070. stopThread = function() {
  9071. running = false;
  9072. clearInterval(id);
  9073. id = 0;
  9074. },
  9075. // private
  9076. startThread = function() {
  9077. if (!running) {
  9078. running = true;
  9079. id = setInterval(runTasks, interval);
  9080. }
  9081. },
  9082. // private
  9083. removeTask = function(t) {
  9084. removeQueue.push(t);
  9085. if (t.onStop) {
  9086. t.onStop.apply(t.scope || t);
  9087. }
  9088. },
  9089. // private
  9090. runTasks = function() {
  9091. var rqLen = removeQueue.length,
  9092. now = new Date().getTime(),
  9093. i;
  9094. if (rqLen > 0) {
  9095. for (i = 0; i < rqLen; i++) {
  9096. Ext.Array.remove(tasks, removeQueue[i]);
  9097. }
  9098. removeQueue = [];
  9099. if (tasks.length < 1) {
  9100. stopThread();
  9101. return;
  9102. }
  9103. }
  9104. i = 0;
  9105. var t,
  9106. itime,
  9107. rt,
  9108. len = tasks.length;
  9109. for (; i < len; ++i) {
  9110. t = tasks[i];
  9111. itime = now - t.taskRunTime;
  9112. if (t.interval <= itime) {
  9113. rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
  9114. t.taskRunTime = now;
  9115. if (rt === false || t.taskRunCount === t.repeat) {
  9116. removeTask(t);
  9117. return;
  9118. }
  9119. }
  9120. if (t.duration && t.duration <= (now - t.taskStartTime)) {
  9121. removeTask(t);
  9122. }
  9123. }
  9124. };
  9125. /**
  9126. * Starts a new task.
  9127. * @method start
  9128. * @param {Object} task <p>A config object that supports the following properties:<ul>
  9129. * <li><code>run</code> : Function<div class="sub-desc"><p>The function to execute each time the task is invoked. The
  9130. * function will be called at each interval and passed the <code>args</code> argument if specified, and the
  9131. * current invocation count if not.</p>
  9132. * <p>If a particular scope (<code>this</code> reference) is required, be sure to specify it using the <code>scope</code> argument.</p>
  9133. * <p>Return <code>false</code> from this function to terminate the task.</p></div></li>
  9134. * <li><code>interval</code> : Number<div class="sub-desc">The frequency in milliseconds with which the task
  9135. * should be invoked.</div></li>
  9136. * <li><code>args</code> : Array<div class="sub-desc">(optional) An array of arguments to be passed to the function
  9137. * specified by <code>run</code>. If not specified, the current invocation count is passed.</div></li>
  9138. * <li><code>scope</code> : Object<div class="sub-desc">(optional) The scope (<tt>this</tt> reference) in which to execute the
  9139. * <code>run</code> function. Defaults to the task config object.</div></li>
  9140. * <li><code>duration</code> : Number<div class="sub-desc">(optional) The length of time in milliseconds to invoke
  9141. * the task before stopping automatically (defaults to indefinite).</div></li>
  9142. * <li><code>repeat</code> : Number<div class="sub-desc">(optional) The number of times to invoke the task before
  9143. * stopping automatically (defaults to indefinite).</div></li>
  9144. * </ul></p>
  9145. * <p>Before each invocation, Ext injects the property <code>taskRunCount</code> into the task object so
  9146. * that calculations based on the repeat count can be performed.</p>
  9147. * @return {Object} The task
  9148. */
  9149. this.start = function(task) {
  9150. tasks.push(task);
  9151. task.taskStartTime = new Date().getTime();
  9152. task.taskRunTime = 0;
  9153. task.taskRunCount = 0;
  9154. startThread();
  9155. return task;
  9156. };
  9157. /**
  9158. * Stops an existing running task.
  9159. * @method stop
  9160. * @param {Object} task The task to stop
  9161. * @return {Object} The task
  9162. */
  9163. this.stop = function(task) {
  9164. removeTask(task);
  9165. return task;
  9166. };
  9167. /**
  9168. * Stops all tasks that are currently running.
  9169. * @method stopAll
  9170. */
  9171. this.stopAll = function() {
  9172. stopThread();
  9173. for (var i = 0, len = tasks.length; i < len; i++) {
  9174. if (tasks[i].onStop) {
  9175. tasks[i].onStop();
  9176. }
  9177. }
  9178. tasks = [];
  9179. removeQueue = [];
  9180. };
  9181. };
  9182. /**
  9183. * @class Ext.TaskManager
  9184. * @extends Ext.util.TaskRunner
  9185. * A static {@link Ext.util.TaskRunner} instance that can be used to start and stop arbitrary tasks. See
  9186. * {@link Ext.util.TaskRunner} for supported methods and task config properties.
  9187. * <pre><code>
  9188. // Start a simple clock task that updates a div once per second
  9189. var task = {
  9190. run: function(){
  9191. Ext.fly('clock').update(new Date().format('g:i:s A'));
  9192. },
  9193. interval: 1000 //1 second
  9194. }
  9195. Ext.TaskManager.start(task);
  9196. </code></pre>
  9197. * <p>See the {@link #start} method for details about how to configure a task object.</p>
  9198. * @singleton
  9199. */
  9200. Ext.TaskManager = Ext.create('Ext.util.TaskRunner');
  9201. /**
  9202. * @class Ext.is
  9203. *
  9204. * Determines information about the current platform the application is running on.
  9205. *
  9206. * @singleton
  9207. */
  9208. Ext.is = {
  9209. init : function(navigator) {
  9210. var platforms = this.platforms,
  9211. ln = platforms.length,
  9212. i, platform;
  9213. navigator = navigator || window.navigator;
  9214. for (i = 0; i < ln; i++) {
  9215. platform = platforms[i];
  9216. this[platform.identity] = platform.regex.test(navigator[platform.property]);
  9217. }
  9218. /**
  9219. * @property Desktop True if the browser is running on a desktop machine
  9220. * @type {Boolean}
  9221. */
  9222. this.Desktop = this.Mac || this.Windows || (this.Linux && !this.Android);
  9223. /**
  9224. * @property Tablet True if the browser is running on a tablet (iPad)
  9225. */
  9226. this.Tablet = this.iPad;
  9227. /**
  9228. * @property Phone True if the browser is running on a phone.
  9229. * @type {Boolean}
  9230. */
  9231. this.Phone = !this.Desktop && !this.Tablet;
  9232. /**
  9233. * @property iOS True if the browser is running on iOS
  9234. * @type {Boolean}
  9235. */
  9236. this.iOS = this.iPhone || this.iPad || this.iPod;
  9237. /**
  9238. * @property Standalone Detects when application has been saved to homescreen.
  9239. * @type {Boolean}
  9240. */
  9241. this.Standalone = !!window.navigator.standalone;
  9242. },
  9243. /**
  9244. * @property iPhone True when the browser is running on a iPhone
  9245. * @type {Boolean}
  9246. */
  9247. platforms: [{
  9248. property: 'platform',
  9249. regex: /iPhone/i,
  9250. identity: 'iPhone'
  9251. },
  9252. /**
  9253. * @property iPod True when the browser is running on a iPod
  9254. * @type {Boolean}
  9255. */
  9256. {
  9257. property: 'platform',
  9258. regex: /iPod/i,
  9259. identity: 'iPod'
  9260. },
  9261. /**
  9262. * @property iPad True when the browser is running on a iPad
  9263. * @type {Boolean}
  9264. */
  9265. {
  9266. property: 'userAgent',
  9267. regex: /iPad/i,
  9268. identity: 'iPad'
  9269. },
  9270. /**
  9271. * @property Blackberry True when the browser is running on a Blackberry
  9272. * @type {Boolean}
  9273. */
  9274. {
  9275. property: 'userAgent',
  9276. regex: /Blackberry/i,
  9277. identity: 'Blackberry'
  9278. },
  9279. /**
  9280. * @property Android True when the browser is running on an Android device
  9281. * @type {Boolean}
  9282. */
  9283. {
  9284. property: 'userAgent',
  9285. regex: /Android/i,
  9286. identity: 'Android'
  9287. },
  9288. /**
  9289. * @property Mac True when the browser is running on a Mac
  9290. * @type {Boolean}
  9291. */
  9292. {
  9293. property: 'platform',
  9294. regex: /Mac/i,
  9295. identity: 'Mac'
  9296. },
  9297. /**
  9298. * @property Windows True when the browser is running on Windows
  9299. * @type {Boolean}
  9300. */
  9301. {
  9302. property: 'platform',
  9303. regex: /Win/i,
  9304. identity: 'Windows'
  9305. },
  9306. /**
  9307. * @property Linux True when the browser is running on Linux
  9308. * @type {Boolean}
  9309. */
  9310. {
  9311. property: 'platform',
  9312. regex: /Linux/i,
  9313. identity: 'Linux'
  9314. }]
  9315. };
  9316. Ext.is.init();
  9317. /**
  9318. * @class Ext.supports
  9319. *
  9320. * Determines information about features are supported in the current environment
  9321. *
  9322. * @singleton
  9323. */
  9324. Ext.supports = {
  9325. init : function() {
  9326. var doc = document,
  9327. div = doc.createElement('div'),
  9328. tests = this.tests,
  9329. ln = tests.length,
  9330. i, test;
  9331. div.innerHTML = [
  9332. '<div style="height:30px;width:50px;">',
  9333. '<div style="height:20px;width:20px;"></div>',
  9334. '</div>',
  9335. '<div style="width: 200px; height: 200px; position: relative; padding: 5px;">',
  9336. '<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></div>',
  9337. '</div>',
  9338. '<div style="float:left; background-color:transparent;"></div>'
  9339. ].join('');
  9340. doc.body.appendChild(div);
  9341. for (i = 0; i < ln; i++) {
  9342. test = tests[i];
  9343. this[test.identity] = test.fn.call(this, doc, div);
  9344. }
  9345. doc.body.removeChild(div);
  9346. },
  9347. /**
  9348. * @property CSS3BoxShadow True if document environment supports the CSS3 box-shadow style.
  9349. * @type {Boolean}
  9350. */
  9351. CSS3BoxShadow: Ext.isDefined(document.documentElement.style.boxShadow),
  9352. /**
  9353. * @property ClassList True if document environment supports the HTML5 classList API.
  9354. * @type {Boolean}
  9355. */
  9356. ClassList: !!document.documentElement.classList,
  9357. /**
  9358. * @property OrientationChange True if the device supports orientation change
  9359. * @type {Boolean}
  9360. */
  9361. OrientationChange: ((typeof window.orientation != 'undefined') && ('onorientationchange' in window)),
  9362. /**
  9363. * @property DeviceMotion True if the device supports device motion (acceleration and rotation rate)
  9364. * @type {Boolean}
  9365. */
  9366. DeviceMotion: ('ondevicemotion' in window),
  9367. /**
  9368. * @property Touch True if the device supports touch
  9369. * @type {Boolean}
  9370. */
  9371. // is.Desktop is needed due to the bug in Chrome 5.0.375, Safari 3.1.2
  9372. // and Safari 4.0 (they all have 'ontouchstart' in the window object).
  9373. Touch: ('ontouchstart' in window) && (!Ext.is.Desktop),
  9374. tests: [
  9375. /**
  9376. * @property Transitions True if the device supports CSS3 Transitions
  9377. * @type {Boolean}
  9378. */
  9379. {
  9380. identity: 'Transitions',
  9381. fn: function(doc, div) {
  9382. var prefix = [
  9383. 'webkit',
  9384. 'Moz',
  9385. 'o',
  9386. 'ms',
  9387. 'khtml'
  9388. ],
  9389. TE = 'TransitionEnd',
  9390. transitionEndName = [
  9391. prefix[0] + TE,
  9392. 'transitionend', //Moz bucks the prefixing convention
  9393. prefix[2] + TE,
  9394. prefix[3] + TE,
  9395. prefix[4] + TE
  9396. ],
  9397. ln = prefix.length,
  9398. i = 0,
  9399. out = false;
  9400. div = Ext.get(div);
  9401. for (; i < ln; i++) {
  9402. if (div.getStyle(prefix[i] + "TransitionProperty")) {
  9403. Ext.supports.CSS3Prefix = prefix[i];
  9404. Ext.supports.CSS3TransitionEnd = transitionEndName[i];
  9405. out = true;
  9406. break;
  9407. }
  9408. }
  9409. return out;
  9410. }
  9411. },
  9412. /**
  9413. * @property RightMargin True if the device supports right margin.
  9414. * See https://bugs.webkit.org/show_bug.cgi?id=13343 for why this is needed.
  9415. * @type {Boolean}
  9416. */
  9417. {
  9418. identity: 'RightMargin',
  9419. fn: function(doc, div) {
  9420. var view = doc.defaultView;
  9421. return !(view && view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px');
  9422. }
  9423. },
  9424. /**
  9425. * @property DisplayChangeInputSelectionBug True if INPUT elements lose their
  9426. * selection when their display style is changed. Essentially, if a text input
  9427. * has focus and its display style is changed, the I-beam disappears.
  9428. *
  9429. * This bug is encountered due to the work around in place for the {@link #RightMargin}
  9430. * bug. This has been observed in Safari 4.0.4 and older, and appears to be fixed
  9431. * in Safari 5. It's not clear if Safari 4.1 has the bug, but it has the same WebKit
  9432. * version number as Safari 5 (according to http://unixpapa.com/js/gecko.html).
  9433. */
  9434. {
  9435. identity: 'DisplayChangeInputSelectionBug',
  9436. fn: function() {
  9437. var webKitVersion = Ext.webKitVersion;
  9438. // WebKit but older than Safari 5 or Chrome 6:
  9439. return 0 < webKitVersion && webKitVersion < 533;
  9440. }
  9441. },
  9442. /**
  9443. * @property DisplayChangeTextAreaSelectionBug True if TEXTAREA elements lose their
  9444. * selection when their display style is changed. Essentially, if a text area has
  9445. * focus and its display style is changed, the I-beam disappears.
  9446. *
  9447. * This bug is encountered due to the work around in place for the {@link #RightMargin}
  9448. * bug. This has been observed in Chrome 10 and Safari 5 and older, and appears to
  9449. * be fixed in Chrome 11.
  9450. */
  9451. {
  9452. identity: 'DisplayChangeTextAreaSelectionBug',
  9453. fn: function() {
  9454. var webKitVersion = Ext.webKitVersion;
  9455. /*
  9456. Has bug w/textarea:
  9457. (Chrome) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US)
  9458. AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.127
  9459. Safari/534.16
  9460. (Safari) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-us)
  9461. AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5
  9462. Safari/533.21.1
  9463. No bug:
  9464. (Chrome) Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7)
  9465. AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.57
  9466. Safari/534.24
  9467. */
  9468. return 0 < webKitVersion && webKitVersion < 534.24;
  9469. }
  9470. },
  9471. /**
  9472. * @property TransparentColor True if the device supports transparent color
  9473. * @type {Boolean}
  9474. */
  9475. {
  9476. identity: 'TransparentColor',
  9477. fn: function(doc, div, view) {
  9478. view = doc.defaultView;
  9479. return !(view && view.getComputedStyle(div.lastChild, null).backgroundColor != 'transparent');
  9480. }
  9481. },
  9482. /**
  9483. * @property ComputedStyle True if the browser supports document.defaultView.getComputedStyle()
  9484. * @type {Boolean}
  9485. */
  9486. {
  9487. identity: 'ComputedStyle',
  9488. fn: function(doc, div, view) {
  9489. view = doc.defaultView;
  9490. return view && view.getComputedStyle;
  9491. }
  9492. },
  9493. /**
  9494. * @property SVG True if the device supports SVG
  9495. * @type {Boolean}
  9496. */
  9497. {
  9498. identity: 'Svg',
  9499. fn: function(doc) {
  9500. return !!doc.createElementNS && !!doc.createElementNS( "http:/" + "/www.w3.org/2000/svg", "svg").createSVGRect;
  9501. }
  9502. },
  9503. /**
  9504. * @property Canvas True if the device supports Canvas
  9505. * @type {Boolean}
  9506. */
  9507. {
  9508. identity: 'Canvas',
  9509. fn: function(doc) {
  9510. return !!doc.createElement('canvas').getContext;
  9511. }
  9512. },
  9513. /**
  9514. * @property VML True if the device supports VML
  9515. * @type {Boolean}
  9516. */
  9517. {
  9518. identity: 'Vml',
  9519. fn: function(doc) {
  9520. var d = doc.createElement("div");
  9521. d.innerHTML = "<!--[if vml]><br><br><![endif]-->";
  9522. return (d.childNodes.length == 2);
  9523. }
  9524. },
  9525. /**
  9526. * @property Float True if the device supports CSS float
  9527. * @type {Boolean}
  9528. */
  9529. {
  9530. identity: 'Float',
  9531. fn: function(doc, div) {
  9532. return !!div.lastChild.style.cssFloat;
  9533. }
  9534. },
  9535. /**
  9536. * @property AudioTag True if the device supports the HTML5 audio tag
  9537. * @type {Boolean}
  9538. */
  9539. {
  9540. identity: 'AudioTag',
  9541. fn: function(doc) {
  9542. return !!doc.createElement('audio').canPlayType;
  9543. }
  9544. },
  9545. /**
  9546. * @property History True if the device supports HTML5 history
  9547. * @type {Boolean}
  9548. */
  9549. {
  9550. identity: 'History',
  9551. fn: function() {
  9552. return !!(window.history && history.pushState);
  9553. }
  9554. },
  9555. /**
  9556. * @property CSS3DTransform True if the device supports CSS3DTransform
  9557. * @type {Boolean}
  9558. */
  9559. {
  9560. identity: 'CSS3DTransform',
  9561. fn: function() {
  9562. return (typeof WebKitCSSMatrix != 'undefined' && new WebKitCSSMatrix().hasOwnProperty('m41'));
  9563. }
  9564. },
  9565. /**
  9566. * @property CSS3LinearGradient True if the device supports CSS3 linear gradients
  9567. * @type {Boolean}
  9568. */
  9569. {
  9570. identity: 'CSS3LinearGradient',
  9571. fn: function(doc, div) {
  9572. var property = 'background-image:',
  9573. webkit = '-webkit-gradient(linear, left top, right bottom, from(black), to(white))',
  9574. w3c = 'linear-gradient(left top, black, white)',
  9575. moz = '-moz-' + w3c,
  9576. options = [property + webkit, property + w3c, property + moz];
  9577. div.style.cssText = options.join(';');
  9578. return ("" + div.style.backgroundImage).indexOf('gradient') !== -1;
  9579. }
  9580. },
  9581. /**
  9582. * @property CSS3BorderRadius True if the device supports CSS3 border radius
  9583. * @type {Boolean}
  9584. */
  9585. {
  9586. identity: 'CSS3BorderRadius',
  9587. fn: function(doc, div) {
  9588. var domPrefixes = ['borderRadius', 'BorderRadius', 'MozBorderRadius', 'WebkitBorderRadius', 'OBorderRadius', 'KhtmlBorderRadius'],
  9589. pass = false,
  9590. i;
  9591. for (i = 0; i < domPrefixes.length; i++) {
  9592. if (document.body.style[domPrefixes[i]] !== undefined) {
  9593. return true;
  9594. }
  9595. }
  9596. return pass;
  9597. }
  9598. },
  9599. /**
  9600. * @property GeoLocation True if the device supports GeoLocation
  9601. * @type {Boolean}
  9602. */
  9603. {
  9604. identity: 'GeoLocation',
  9605. fn: function() {
  9606. return (typeof navigator != 'undefined' && typeof navigator.geolocation != 'undefined') || (typeof google != 'undefined' && typeof google.gears != 'undefined');
  9607. }
  9608. },
  9609. /**
  9610. * @property MouseEnterLeave True if the browser supports mouseenter and mouseleave events
  9611. * @type {Boolean}
  9612. */
  9613. {
  9614. identity: 'MouseEnterLeave',
  9615. fn: function(doc, div){
  9616. return ('onmouseenter' in div && 'onmouseleave' in div);
  9617. }
  9618. },
  9619. /**
  9620. * @property MouseWheel True if the browser supports the mousewheel event
  9621. * @type {Boolean}
  9622. */
  9623. {
  9624. identity: 'MouseWheel',
  9625. fn: function(doc, div) {
  9626. return ('onmousewheel' in div);
  9627. }
  9628. },
  9629. /**
  9630. * @property Opacity True if the browser supports normal css opacity
  9631. * @type {Boolean}
  9632. */
  9633. {
  9634. identity: 'Opacity',
  9635. fn: function(doc, div){
  9636. // Not a strict equal comparison in case opacity can be converted to a number.
  9637. if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
  9638. return false;
  9639. }
  9640. div.firstChild.style.cssText = 'opacity:0.73';
  9641. return div.firstChild.style.opacity == '0.73';
  9642. }
  9643. },
  9644. /**
  9645. * @property Placeholder True if the browser supports the HTML5 placeholder attribute on inputs
  9646. * @type {Boolean}
  9647. */
  9648. {
  9649. identity: 'Placeholder',
  9650. fn: function(doc) {
  9651. return 'placeholder' in doc.createElement('input');
  9652. }
  9653. },
  9654. /**
  9655. * @property Direct2DBug True if when asking for an element's dimension via offsetWidth or offsetHeight,
  9656. * getBoundingClientRect, etc. the browser returns the subpixel width rounded to the nearest pixel.
  9657. * @type {Boolean}
  9658. */
  9659. {
  9660. identity: 'Direct2DBug',
  9661. fn: function() {
  9662. return Ext.isString(document.body.style.msTransformOrigin);
  9663. }
  9664. },
  9665. /**
  9666. * @property BoundingClientRect True if the browser supports the getBoundingClientRect method on elements
  9667. * @type {Boolean}
  9668. */
  9669. {
  9670. identity: 'BoundingClientRect',
  9671. fn: function(doc, div) {
  9672. return Ext.isFunction(div.getBoundingClientRect);
  9673. }
  9674. },
  9675. {
  9676. identity: 'IncludePaddingInWidthCalculation',
  9677. fn: function(doc, div){
  9678. var el = Ext.get(div.childNodes[1].firstChild);
  9679. return el.getWidth() == 210;
  9680. }
  9681. },
  9682. {
  9683. identity: 'IncludePaddingInHeightCalculation',
  9684. fn: function(doc, div){
  9685. var el = Ext.get(div.childNodes[1].firstChild);
  9686. return el.getHeight() == 210;
  9687. }
  9688. },
  9689. /**
  9690. * @property ArraySort True if the Array sort native method isn't bugged.
  9691. * @type {Boolean}
  9692. */
  9693. {
  9694. identity: 'ArraySort',
  9695. fn: function() {
  9696. var a = [1,2,3,4,5].sort(function(){ return 0; });
  9697. return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
  9698. }
  9699. },
  9700. /**
  9701. * @property Range True if browser support document.createRange native method.
  9702. * @type {Boolean}
  9703. */
  9704. {
  9705. identity: 'Range',
  9706. fn: function() {
  9707. return !!document.createRange;
  9708. }
  9709. },
  9710. /**
  9711. * @property CreateContextualFragment True if browser support CreateContextualFragment range native methods.
  9712. * @type {Boolean}
  9713. */
  9714. {
  9715. identity: 'CreateContextualFragment',
  9716. fn: function() {
  9717. var range = Ext.supports.Range ? document.createRange() : false;
  9718. return range && !!range.createContextualFragment;
  9719. }
  9720. },
  9721. /**
  9722. * @property WindowOnError True if browser supports window.onerror.
  9723. * @type {Boolean}
  9724. */
  9725. {
  9726. identity: 'WindowOnError',
  9727. fn: function () {
  9728. // sadly, we cannot feature detect this...
  9729. return Ext.isIE || Ext.isGecko || Ext.webKitVersion >= 534.16; // Chrome 10+
  9730. }
  9731. }
  9732. ]
  9733. };
  9734. /*
  9735. This file is part of Ext JS 4
  9736. Copyright (c) 2011 Sencha Inc
  9737. Contact: http://www.sencha.com/contact
  9738. GNU General Public License Usage
  9739. 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.
  9740. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
  9741. */
  9742. /**
  9743. * @class Ext.DomHelper
  9744. * @alternateClassName Ext.core.DomHelper
  9745. *
  9746. * <p>The DomHelper class provides a layer of abstraction from DOM and transparently supports creating
  9747. * elements via DOM or using HTML fragments. It also has the ability to create HTML fragment templates
  9748. * from your DOM building code.</p>
  9749. *
  9750. * <p><b><u>DomHelper element specification object</u></b></p>
  9751. * <p>A specification object is used when creating elements. Attributes of this object
  9752. * are assumed to be element attributes, except for 4 special attributes:
  9753. * <div class="mdetail-params"><ul>
  9754. * <li><b><tt>tag</tt></b> : <div class="sub-desc">The tag name of the element</div></li>
  9755. * <li><b><tt>children</tt></b> : or <tt>cn</tt><div class="sub-desc">An array of the
  9756. * same kind of element definition objects to be created and appended. These can be nested
  9757. * as deep as you want.</div></li>
  9758. * <li><b><tt>cls</tt></b> : <div class="sub-desc">The class attribute of the element.
  9759. * This will end up being either the "class" attribute on a HTML fragment or className
  9760. * for a DOM node, depending on whether DomHelper is using fragments or DOM.</div></li>
  9761. * <li><b><tt>html</tt></b> : <div class="sub-desc">The innerHTML for the element</div></li>
  9762. * </ul></div></p>
  9763. * <p><b>NOTE:</b> For other arbitrary attributes, the value will currently <b>not</b> be automatically
  9764. * HTML-escaped prior to building the element's HTML string. This means that if your attribute value
  9765. * contains special characters that would not normally be allowed in a double-quoted attribute value,
  9766. * you <b>must</b> manually HTML-encode it beforehand (see {@link Ext.String#htmlEncode}) or risk
  9767. * malformed HTML being created. This behavior may change in a future release.</p>
  9768. *
  9769. * <p><b><u>Insertion methods</u></b></p>
  9770. * <p>Commonly used insertion methods:
  9771. * <div class="mdetail-params"><ul>
  9772. * <li><tt>{@link #append}</tt> : <div class="sub-desc"></div></li>
  9773. * <li><tt>{@link #insertBefore}</tt> : <div class="sub-desc"></div></li>
  9774. * <li><tt>{@link #insertAfter}</tt> : <div class="sub-desc"></div></li>
  9775. * <li><tt>{@link #overwrite}</tt> : <div class="sub-desc"></div></li>
  9776. * <li><tt>{@link #createTemplate}</tt> : <div class="sub-desc"></div></li>
  9777. * <li><tt>{@link #insertHtml}</tt> : <div class="sub-desc"></div></li>
  9778. * </ul></div></p>
  9779. *
  9780. * <p><b><u>Example</u></b></p>
  9781. * <p>This is an example, where an unordered list with 3 children items is appended to an existing
  9782. * element with id <tt>'my-div'</tt>:<br>
  9783. <pre><code>
  9784. var dh = Ext.DomHelper; // create shorthand alias
  9785. // specification object
  9786. var spec = {
  9787. id: 'my-ul',
  9788. tag: 'ul',
  9789. cls: 'my-list',
  9790. // append children after creating
  9791. children: [ // may also specify 'cn' instead of 'children'
  9792. {tag: 'li', id: 'item0', html: 'List Item 0'},
  9793. {tag: 'li', id: 'item1', html: 'List Item 1'},
  9794. {tag: 'li', id: 'item2', html: 'List Item 2'}
  9795. ]
  9796. };
  9797. var list = dh.append(
  9798. 'my-div', // the context element 'my-div' can either be the id or the actual node
  9799. spec // the specification object
  9800. );
  9801. </code></pre></p>
  9802. * <p>Element creation specification parameters in this class may also be passed as an Array of
  9803. * specification objects. This can be used to insert multiple sibling nodes into an existing
  9804. * container very efficiently. For example, to add more list items to the example above:<pre><code>
  9805. dh.append('my-ul', [
  9806. {tag: 'li', id: 'item3', html: 'List Item 3'},
  9807. {tag: 'li', id: 'item4', html: 'List Item 4'}
  9808. ]);
  9809. * </code></pre></p>
  9810. *
  9811. * <p><b><u>Templating</u></b></p>
  9812. * <p>The real power is in the built-in templating. Instead of creating or appending any elements,
  9813. * <tt>{@link #createTemplate}</tt> returns a Template object which can be used over and over to
  9814. * insert new elements. Revisiting the example above, we could utilize templating this time:
  9815. * <pre><code>
  9816. // create the node
  9817. var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
  9818. // get template
  9819. var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});
  9820. for(var i = 0; i < 5, i++){
  9821. tpl.append(list, [i]); // use template to append to the actual node
  9822. }
  9823. * </code></pre></p>
  9824. * <p>An example using a template:<pre><code>
  9825. var html = '<a id="{0}" href="{1}" class="nav">{2}</a>';
  9826. var tpl = new Ext.DomHelper.createTemplate(html);
  9827. tpl.append('blog-roll', ['link1', 'http://www.edspencer.net/', "Ed&#39;s Site"]);
  9828. tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin&#39;s Site"]);
  9829. * </code></pre></p>
  9830. *
  9831. * <p>The same example using named parameters:<pre><code>
  9832. var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
  9833. var tpl = new Ext.DomHelper.createTemplate(html);
  9834. tpl.append('blog-roll', {
  9835. id: 'link1',
  9836. url: 'http://www.edspencer.net/',
  9837. text: "Ed&#39;s Site"
  9838. });
  9839. tpl.append('blog-roll', {
  9840. id: 'link2',
  9841. url: 'http://www.dustindiaz.com/',
  9842. text: "Dustin&#39;s Site"
  9843. });
  9844. * </code></pre></p>
  9845. *
  9846. * <p><b><u>Compiling Templates</u></b></p>
  9847. * <p>Templates are applied using regular expressions. The performance is great, but if
  9848. * you are adding a bunch of DOM elements using the same template, you can increase
  9849. * performance even further by {@link Ext.Template#compile "compiling"} the template.
  9850. * The way "{@link Ext.Template#compile compile()}" works is the template is parsed and
  9851. * broken up at the different variable points and a dynamic function is created and eval'ed.
  9852. * The generated function performs string concatenation of these parts and the passed
  9853. * variables instead of using regular expressions.
  9854. * <pre><code>
  9855. var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
  9856. var tpl = new Ext.DomHelper.createTemplate(html);
  9857. tpl.compile();
  9858. //... use template like normal
  9859. * </code></pre></p>
  9860. *
  9861. * <p><b><u>Performance Boost</u></b></p>
  9862. * <p>DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead
  9863. * of DOM can significantly boost performance.</p>
  9864. * <p>Element creation specification parameters may also be strings. If {@link #useDom} is <tt>false</tt>,
  9865. * then the string is used as innerHTML. If {@link #useDom} is <tt>true</tt>, a string specification
  9866. * results in the creation of a text node. Usage:</p>
  9867. * <pre><code>
  9868. Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance
  9869. * </code></pre>
  9870. * @singleton
  9871. */
  9872. Ext.ns('Ext.core');
  9873. Ext.core.DomHelper = Ext.DomHelper = function(){
  9874. var tempTableEl = null,
  9875. emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,
  9876. tableRe = /^table|tbody|tr|td$/i,
  9877. confRe = /tag|children|cn|html$/i,
  9878. tableElRe = /td|tr|tbody/i,
  9879. endRe = /end/i,
  9880. pub,
  9881. // kill repeat to save bytes
  9882. afterbegin = 'afterbegin',
  9883. afterend = 'afterend',
  9884. beforebegin = 'beforebegin',
  9885. beforeend = 'beforeend',
  9886. ts = '<table>',
  9887. te = '</table>',
  9888. tbs = ts+'<tbody>',
  9889. tbe = '</tbody>'+te,
  9890. trs = tbs + '<tr>',
  9891. tre = '</tr>'+tbe;
  9892. // private
  9893. function doInsert(el, o, returnElement, pos, sibling, append){
  9894. el = Ext.getDom(el);
  9895. var newNode;
  9896. if (pub.useDom) {
  9897. newNode = createDom(o, null);
  9898. if (append) {
  9899. el.appendChild(newNode);
  9900. } else {
  9901. (sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el);
  9902. }
  9903. } else {
  9904. newNode = Ext.DomHelper.insertHtml(pos, el, Ext.DomHelper.createHtml(o));
  9905. }
  9906. return returnElement ? Ext.get(newNode, true) : newNode;
  9907. }
  9908. function createDom(o, parentNode){
  9909. var el,
  9910. doc = document,
  9911. useSet,
  9912. attr,
  9913. val,
  9914. cn;
  9915. if (Ext.isArray(o)) { // Allow Arrays of siblings to be inserted
  9916. el = doc.createDocumentFragment(); // in one shot using a DocumentFragment
  9917. for (var i = 0, l = o.length; i < l; i++) {
  9918. createDom(o[i], el);
  9919. }
  9920. } else if (typeof o == 'string') { // Allow a string as a child spec.
  9921. el = doc.createTextNode(o);
  9922. } else {
  9923. el = doc.createElement( o.tag || 'div' );
  9924. useSet = !!el.setAttribute; // In IE some elements don't have setAttribute
  9925. for (attr in o) {
  9926. if(!confRe.test(attr)){
  9927. val = o[attr];
  9928. if(attr == 'cls'){
  9929. el.className = val;
  9930. }else{
  9931. if(useSet){
  9932. el.setAttribute(attr, val);
  9933. }else{
  9934. el[attr] = val;
  9935. }
  9936. }
  9937. }
  9938. }
  9939. Ext.DomHelper.applyStyles(el, o.style);
  9940. if ((cn = o.children || o.cn)) {
  9941. createDom(cn, el);
  9942. } else if (o.html) {
  9943. el.innerHTML = o.html;
  9944. }
  9945. }
  9946. if(parentNode){
  9947. parentNode.appendChild(el);
  9948. }
  9949. return el;
  9950. }
  9951. // build as innerHTML where available
  9952. function createHtml(o){
  9953. var b = '',
  9954. attr,
  9955. val,
  9956. key,
  9957. cn,
  9958. i;
  9959. if(typeof o == "string"){
  9960. b = o;
  9961. } else if (Ext.isArray(o)) {
  9962. for (i=0; i < o.length; i++) {
  9963. if(o[i]) {
  9964. b += createHtml(o[i]);
  9965. }
  9966. }
  9967. } else {
  9968. b += '<' + (o.tag = o.tag || 'div');
  9969. for (attr in o) {
  9970. val = o[attr];
  9971. if(!confRe.test(attr)){
  9972. if (typeof val == "object") {
  9973. b += ' ' + attr + '="';
  9974. for (key in val) {
  9975. b += key + ':' + val[key] + ';';
  9976. }
  9977. b += '"';
  9978. }else{
  9979. b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"';
  9980. }
  9981. }
  9982. }
  9983. // Now either just close the tag or try to add children and close the tag.
  9984. if (emptyTags.test(o.tag)) {
  9985. b += '/>';
  9986. } else {
  9987. b += '>';
  9988. if ((cn = o.children || o.cn)) {
  9989. b += createHtml(cn);
  9990. } else if(o.html){
  9991. b += o.html;
  9992. }
  9993. b += '</' + o.tag + '>';
  9994. }
  9995. }
  9996. return b;
  9997. }
  9998. function ieTable(depth, s, h, e){
  9999. tempTableEl.innerHTML = [s, h, e].join('');
  10000. var i = -1,
  10001. el = tempTableEl,
  10002. ns;
  10003. while(++i < depth){
  10004. el = el.firstChild;
  10005. }
  10006. // If the result is multiple siblings, then encapsulate them into one fragment.
  10007. ns = el.nextSibling;
  10008. if (ns){
  10009. var df = document.createDocumentFragment();
  10010. while(el){
  10011. ns = el.nextSibling;
  10012. df.appendChild(el);
  10013. el = ns;
  10014. }
  10015. el = df;
  10016. }
  10017. return el;
  10018. }
  10019. /**
  10020. * @ignore
  10021. * Nasty code for IE's broken table implementation
  10022. */
  10023. function insertIntoTable(tag, where, el, html) {
  10024. var node,
  10025. before;
  10026. tempTableEl = tempTableEl || document.createElement('div');
  10027. if(tag == 'td' && (where == afterbegin || where == beforeend) ||
  10028. !tableElRe.test(tag) && (where == beforebegin || where == afterend)) {
  10029. return null;
  10030. }
  10031. before = where == beforebegin ? el :
  10032. where == afterend ? el.nextSibling :
  10033. where == afterbegin ? el.firstChild : null;
  10034. if (where == beforebegin || where == afterend) {
  10035. el = el.parentNode;
  10036. }
  10037. if (tag == 'td' || (tag == 'tr' && (where == beforeend || where == afterbegin))) {
  10038. node = ieTable(4, trs, html, tre);
  10039. } else if ((tag == 'tbody' && (where == beforeend || where == afterbegin)) ||
  10040. (tag == 'tr' && (where == beforebegin || where == afterend))) {
  10041. node = ieTable(3, tbs, html, tbe);
  10042. } else {
  10043. node = ieTable(2, ts, html, te);
  10044. }
  10045. el.insertBefore(node, before);
  10046. return node;
  10047. }
  10048. /**
  10049. * @ignore
  10050. * Fix for IE9 createContextualFragment missing method
  10051. */
  10052. function createContextualFragment(html){
  10053. var div = document.createElement("div"),
  10054. fragment = document.createDocumentFragment(),
  10055. i = 0,
  10056. length, childNodes;
  10057. div.innerHTML = html;
  10058. childNodes = div.childNodes;
  10059. length = childNodes.length;
  10060. for (; i < length; i++) {
  10061. fragment.appendChild(childNodes[i].cloneNode(true));
  10062. }
  10063. return fragment;
  10064. }
  10065. pub = {
  10066. /**
  10067. * Returns the markup for the passed Element(s) config.
  10068. * @param {Object} o The DOM object spec (and children)
  10069. * @return {String}
  10070. */
  10071. markup : function(o){
  10072. return createHtml(o);
  10073. },
  10074. /**
  10075. * Applies a style specification to an element.
  10076. * @param {String/HTMLElement} el The element to apply styles to
  10077. * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or
  10078. * a function which returns such a specification.
  10079. */
  10080. applyStyles : function(el, styles){
  10081. if (styles) {
  10082. el = Ext.fly(el);
  10083. if (typeof styles == "function") {
  10084. styles = styles.call();
  10085. }
  10086. if (typeof styles == "string") {
  10087. styles = Ext.Element.parseStyles(styles);
  10088. }
  10089. if (typeof styles == "object") {
  10090. el.setStyle(styles);
  10091. }
  10092. }
  10093. },
  10094. /**
  10095. * Inserts an HTML fragment into the DOM.
  10096. * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
  10097. *
  10098. * For example take the following HTML: `<div>Contents</div>`
  10099. *
  10100. * Using different `where` values inserts element to the following places:
  10101. *
  10102. * - beforeBegin: `<HERE><div>Contents</div>`
  10103. * - afterBegin: `<div><HERE>Contents</div>`
  10104. * - beforeEnd: `<div>Contents<HERE></div>`
  10105. * - afterEnd: `<div>Contents</div><HERE>`
  10106. *
  10107. * @param {HTMLElement/TextNode} el The context element
  10108. * @param {String} html The HTML fragment
  10109. * @return {HTMLElement} The new node
  10110. */
  10111. insertHtml : function(where, el, html){
  10112. var hash = {},
  10113. hashVal,
  10114. range,
  10115. rangeEl,
  10116. setStart,
  10117. frag,
  10118. rs;
  10119. where = where.toLowerCase();
  10120. // add these here because they are used in both branches of the condition.
  10121. hash[beforebegin] = ['BeforeBegin', 'previousSibling'];
  10122. hash[afterend] = ['AfterEnd', 'nextSibling'];
  10123. // if IE and context element is an HTMLElement
  10124. if (el.insertAdjacentHTML) {
  10125. if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){
  10126. return rs;
  10127. }
  10128. // add these two to the hash.
  10129. hash[afterbegin] = ['AfterBegin', 'firstChild'];
  10130. hash[beforeend] = ['BeforeEnd', 'lastChild'];
  10131. if ((hashVal = hash[where])) {
  10132. el.insertAdjacentHTML(hashVal[0], html);
  10133. return el[hashVal[1]];
  10134. }
  10135. // if (not IE and context element is an HTMLElement) or TextNode
  10136. } else {
  10137. // we cannot insert anything inside a textnode so...
  10138. if (Ext.isTextNode(el)) {
  10139. where = where === 'afterbegin' ? 'beforebegin' : where;
  10140. where = where === 'beforeend' ? 'afterend' : where;
  10141. }
  10142. range = Ext.supports.CreateContextualFragment ? el.ownerDocument.createRange() : undefined;
  10143. setStart = 'setStart' + (endRe.test(where) ? 'After' : 'Before');
  10144. if (hash[where]) {
  10145. if (range) {
  10146. range[setStart](el);
  10147. frag = range.createContextualFragment(html);
  10148. } else {
  10149. frag = createContextualFragment(html);
  10150. }
  10151. el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);
  10152. return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling'];
  10153. } else {
  10154. rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child';
  10155. if (el.firstChild) {
  10156. if (range) {
  10157. range[setStart](el[rangeEl]);
  10158. frag = range.createContextualFragment(html);
  10159. } else {
  10160. frag = createContextualFragment(html);
  10161. }
  10162. if(where == afterbegin){
  10163. el.insertBefore(frag, el.firstChild);
  10164. }else{
  10165. el.appendChild(frag);
  10166. }
  10167. } else {
  10168. el.innerHTML = html;
  10169. }
  10170. return el[rangeEl];
  10171. }
  10172. }
  10173. },
  10174. /**
  10175. * Creates new DOM element(s) and inserts them before el.
  10176. * @param {String/HTMLElement/Ext.Element} el The context element
  10177. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  10178. * @param {Boolean} returnElement (optional) true to return a Ext.Element
  10179. * @return {HTMLElement/Ext.Element} The new node
  10180. */
  10181. insertBefore : function(el, o, returnElement){
  10182. return doInsert(el, o, returnElement, beforebegin);
  10183. },
  10184. /**
  10185. * Creates new DOM element(s) and inserts them after el.
  10186. * @param {String/HTMLElement/Ext.Element} el The context element
  10187. * @param {Object} o The DOM object spec (and children)
  10188. * @param {Boolean} returnElement (optional) true to return a Ext.Element
  10189. * @return {HTMLElement/Ext.Element} The new node
  10190. */
  10191. insertAfter : function(el, o, returnElement){
  10192. return doInsert(el, o, returnElement, afterend, 'nextSibling');
  10193. },
  10194. /**
  10195. * Creates new DOM element(s) and inserts them as the first child of el.
  10196. * @param {String/HTMLElement/Ext.Element} el The context element
  10197. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  10198. * @param {Boolean} returnElement (optional) true to return a Ext.Element
  10199. * @return {HTMLElement/Ext.Element} The new node
  10200. */
  10201. insertFirst : function(el, o, returnElement){
  10202. return doInsert(el, o, returnElement, afterbegin, 'firstChild');
  10203. },
  10204. /**
  10205. * Creates new DOM element(s) and appends them to el.
  10206. * @param {String/HTMLElement/Ext.Element} el The context element
  10207. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  10208. * @param {Boolean} returnElement (optional) true to return a Ext.Element
  10209. * @return {HTMLElement/Ext.Element} The new node
  10210. */
  10211. append : function(el, o, returnElement){
  10212. return doInsert(el, o, returnElement, beforeend, '', true);
  10213. },
  10214. /**
  10215. * Creates new DOM element(s) and overwrites the contents of el with them.
  10216. * @param {String/HTMLElement/Ext.Element} el The context element
  10217. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  10218. * @param {Boolean} returnElement (optional) true to return a Ext.Element
  10219. * @return {HTMLElement/Ext.Element} The new node
  10220. */
  10221. overwrite : function(el, o, returnElement){
  10222. el = Ext.getDom(el);
  10223. el.innerHTML = createHtml(o);
  10224. return returnElement ? Ext.get(el.firstChild) : el.firstChild;
  10225. },
  10226. createHtml : createHtml,
  10227. /**
  10228. * Creates new DOM element(s) without inserting them to the document.
  10229. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  10230. * @return {HTMLElement} The new uninserted node
  10231. * @method
  10232. */
  10233. createDom: createDom,
  10234. /** True to force the use of DOM instead of html fragments @type Boolean */
  10235. useDom : false,
  10236. /**
  10237. * Creates a new Ext.Template from the DOM object spec.
  10238. * @param {Object} o The DOM object spec (and children)
  10239. * @return {Ext.Template} The new template
  10240. */
  10241. createTemplate : function(o){
  10242. var html = Ext.DomHelper.createHtml(o);
  10243. return Ext.create('Ext.Template', html);
  10244. }
  10245. };
  10246. return pub;
  10247. }();
  10248. /*
  10249. * This is code is also distributed under MIT license for use
  10250. * with jQuery and prototype JavaScript libraries.
  10251. */
  10252. /**
  10253. * @class Ext.DomQuery
  10254. Provides high performance selector/xpath processing by compiling queries into reusable functions. New pseudo classes and matchers can be plugged. It works on HTML and XML documents (if a content node is passed in).
  10255. <p>
  10256. DomQuery supports most of the <a href="http://www.w3.org/TR/2005/WD-css3-selectors-20051215/#selectors">CSS3 selectors spec</a>, along with some custom selectors and basic XPath.</p>
  10257. <p>
  10258. All selectors, attribute filters and pseudos below can be combined infinitely in any order. For example "div.foo:nth-child(odd)[@foo=bar].bar:first" would be a perfectly valid selector. Node filters are processed in the order in which they appear, which allows you to optimize your queries for your document structure.
  10259. </p>
  10260. <h4>Element Selectors:</h4>
  10261. <ul class="list">
  10262. <li> <b>*</b> any element</li>
  10263. <li> <b>E</b> an element with the tag E</li>
  10264. <li> <b>E F</b> All descendent elements of E that have the tag F</li>
  10265. <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
  10266. <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
  10267. <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
  10268. </ul>
  10269. <h4>Attribute Selectors:</h4>
  10270. <p>The use of &#64; and quotes are optional. For example, div[&#64;foo='bar'] is also a valid attribute selector.</p>
  10271. <ul class="list">
  10272. <li> <b>E[foo]</b> has an attribute "foo"</li>
  10273. <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
  10274. <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
  10275. <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
  10276. <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
  10277. <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
  10278. <li> <b>E[foo!=bar]</b> attribute "foo" does not equal "bar"</li>
  10279. </ul>
  10280. <h4>Pseudo Classes:</h4>
  10281. <ul class="list">
  10282. <li> <b>E:first-child</b> E is the first child of its parent</li>
  10283. <li> <b>E:last-child</b> E is the last child of its parent</li>
  10284. <li> <b>E:nth-child(<i>n</i>)</b> E is the <i>n</i>th child of its parent (1 based as per the spec)</li>
  10285. <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
  10286. <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
  10287. <li> <b>E:only-child</b> E is the only child of its parent</li>
  10288. <li> <b>E:checked</b> E is an element that is has a checked attribute that is true (e.g. a radio or checkbox) </li>
  10289. <li> <b>E:first</b> the first E in the resultset</li>
  10290. <li> <b>E:last</b> the last E in the resultset</li>
  10291. <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
  10292. <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
  10293. <li> <b>E:even</b> shortcut for :nth-child(even)</li>
  10294. <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
  10295. <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
  10296. <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
  10297. <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
  10298. <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
  10299. <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
  10300. <li> <b>E:any(S1|S2|S2)</b> an E element which matches any of the simple selectors S1, S2 or S3//\\</li>
  10301. </ul>
  10302. <h4>CSS Value Selectors:</h4>
  10303. <ul class="list">
  10304. <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
  10305. <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
  10306. <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
  10307. <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
  10308. <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
  10309. <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
  10310. </ul>
  10311. * @singleton
  10312. */
  10313. Ext.ns('Ext.core');
  10314. Ext.core.DomQuery = Ext.DomQuery = function(){
  10315. var cache = {},
  10316. simpleCache = {},
  10317. valueCache = {},
  10318. nonSpace = /\S/,
  10319. trimRe = /^\s+|\s+$/g,
  10320. tplRe = /\{(\d+)\}/g,
  10321. modeRe = /^(\s?[\/>+~]\s?|\s|$)/,
  10322. tagTokenRe = /^(#)?([\w-\*]+)/,
  10323. nthRe = /(\d*)n\+?(\d*)/,
  10324. nthRe2 = /\D/,
  10325. startIdRe = /^\s*\#/,
  10326. // This is for IE MSXML which does not support expandos.
  10327. // IE runs the same speed using setAttribute, however FF slows way down
  10328. // and Safari completely fails so they need to continue to use expandos.
  10329. isIE = window.ActiveXObject ? true : false,
  10330. key = 30803;
  10331. // this eval is stop the compressor from
  10332. // renaming the variable to something shorter
  10333. eval("var batch = 30803;");
  10334. // Retrieve the child node from a particular
  10335. // parent at the specified index.
  10336. function child(parent, index){
  10337. var i = 0,
  10338. n = parent.firstChild;
  10339. while(n){
  10340. if(n.nodeType == 1){
  10341. if(++i == index){
  10342. return n;
  10343. }
  10344. }
  10345. n = n.nextSibling;
  10346. }
  10347. return null;
  10348. }
  10349. // retrieve the next element node
  10350. function next(n){
  10351. while((n = n.nextSibling) && n.nodeType != 1);
  10352. return n;
  10353. }
  10354. // retrieve the previous element node
  10355. function prev(n){
  10356. while((n = n.previousSibling) && n.nodeType != 1);
  10357. return n;
  10358. }
  10359. // Mark each child node with a nodeIndex skipping and
  10360. // removing empty text nodes.
  10361. function children(parent){
  10362. var n = parent.firstChild,
  10363. nodeIndex = -1,
  10364. nextNode;
  10365. while(n){
  10366. nextNode = n.nextSibling;
  10367. // clean worthless empty nodes.
  10368. if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
  10369. parent.removeChild(n);
  10370. }else{
  10371. // add an expando nodeIndex
  10372. n.nodeIndex = ++nodeIndex;
  10373. }
  10374. n = nextNode;
  10375. }
  10376. return this;
  10377. }
  10378. // nodeSet - array of nodes
  10379. // cls - CSS Class
  10380. function byClassName(nodeSet, cls){
  10381. if(!cls){
  10382. return nodeSet;
  10383. }
  10384. var result = [], ri = -1;
  10385. for(var i = 0, ci; ci = nodeSet[i]; i++){
  10386. if((' '+ci.className+' ').indexOf(cls) != -1){
  10387. result[++ri] = ci;
  10388. }
  10389. }
  10390. return result;
  10391. };
  10392. function attrValue(n, attr){
  10393. // if its an array, use the first node.
  10394. if(!n.tagName && typeof n.length != "undefined"){
  10395. n = n[0];
  10396. }
  10397. if(!n){
  10398. return null;
  10399. }
  10400. if(attr == "for"){
  10401. return n.htmlFor;
  10402. }
  10403. if(attr == "class" || attr == "className"){
  10404. return n.className;
  10405. }
  10406. return n.getAttribute(attr) || n[attr];
  10407. };
  10408. // ns - nodes
  10409. // mode - false, /, >, +, ~
  10410. // tagName - defaults to "*"
  10411. function getNodes(ns, mode, tagName){
  10412. var result = [], ri = -1, cs;
  10413. if(!ns){
  10414. return result;
  10415. }
  10416. tagName = tagName || "*";
  10417. // convert to array
  10418. if(typeof ns.getElementsByTagName != "undefined"){
  10419. ns = [ns];
  10420. }
  10421. // no mode specified, grab all elements by tagName
  10422. // at any depth
  10423. if(!mode){
  10424. for(var i = 0, ni; ni = ns[i]; i++){
  10425. cs = ni.getElementsByTagName(tagName);
  10426. for(var j = 0, ci; ci = cs[j]; j++){
  10427. result[++ri] = ci;
  10428. }
  10429. }
  10430. // Direct Child mode (/ or >)
  10431. // E > F or E/F all direct children elements of E that have the tag
  10432. } else if(mode == "/" || mode == ">"){
  10433. var utag = tagName.toUpperCase();
  10434. for(var i = 0, ni, cn; ni = ns[i]; i++){
  10435. cn = ni.childNodes;
  10436. for(var j = 0, cj; cj = cn[j]; j++){
  10437. if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
  10438. result[++ri] = cj;
  10439. }
  10440. }
  10441. }
  10442. // Immediately Preceding mode (+)
  10443. // E + F all elements with the tag F that are immediately preceded by an element with the tag E
  10444. }else if(mode == "+"){
  10445. var utag = tagName.toUpperCase();
  10446. for(var i = 0, n; n = ns[i]; i++){
  10447. while((n = n.nextSibling) && n.nodeType != 1);
  10448. if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
  10449. result[++ri] = n;
  10450. }
  10451. }
  10452. // Sibling mode (~)
  10453. // E ~ F all elements with the tag F that are preceded by a sibling element with the tag E
  10454. }else if(mode == "~"){
  10455. var utag = tagName.toUpperCase();
  10456. for(var i = 0, n; n = ns[i]; i++){
  10457. while((n = n.nextSibling)){
  10458. if (n.nodeName == utag || n.nodeName == tagName || tagName == '*'){
  10459. result[++ri] = n;
  10460. }
  10461. }
  10462. }
  10463. }
  10464. return result;
  10465. }
  10466. function concat(a, b){
  10467. if(b.slice){
  10468. return a.concat(b);
  10469. }
  10470. for(var i = 0, l = b.length; i < l; i++){
  10471. a[a.length] = b[i];
  10472. }
  10473. return a;
  10474. }
  10475. function byTag(cs, tagName){
  10476. if(cs.tagName || cs == document){
  10477. cs = [cs];
  10478. }
  10479. if(!tagName){
  10480. return cs;
  10481. }
  10482. var result = [], ri = -1;
  10483. tagName = tagName.toLowerCase();
  10484. for(var i = 0, ci; ci = cs[i]; i++){
  10485. if(ci.nodeType == 1 && ci.tagName.toLowerCase() == tagName){
  10486. result[++ri] = ci;
  10487. }
  10488. }
  10489. return result;
  10490. }
  10491. function byId(cs, id){
  10492. if(cs.tagName || cs == document){
  10493. cs = [cs];
  10494. }
  10495. if(!id){
  10496. return cs;
  10497. }
  10498. var result = [], ri = -1;
  10499. for(var i = 0, ci; ci = cs[i]; i++){
  10500. if(ci && ci.id == id){
  10501. result[++ri] = ci;
  10502. return result;
  10503. }
  10504. }
  10505. return result;
  10506. }
  10507. // operators are =, !=, ^=, $=, *=, %=, |= and ~=
  10508. // custom can be "{"
  10509. function byAttribute(cs, attr, value, op, custom){
  10510. var result = [],
  10511. ri = -1,
  10512. useGetStyle = custom == "{",
  10513. fn = Ext.DomQuery.operators[op],
  10514. a,
  10515. xml,
  10516. hasXml;
  10517. for(var i = 0, ci; ci = cs[i]; i++){
  10518. // skip non-element nodes.
  10519. if(ci.nodeType != 1){
  10520. continue;
  10521. }
  10522. // only need to do this for the first node
  10523. if(!hasXml){
  10524. xml = Ext.DomQuery.isXml(ci);
  10525. hasXml = true;
  10526. }
  10527. // we only need to change the property names if we're dealing with html nodes, not XML
  10528. if(!xml){
  10529. if(useGetStyle){
  10530. a = Ext.DomQuery.getStyle(ci, attr);
  10531. } else if (attr == "class" || attr == "className"){
  10532. a = ci.className;
  10533. } else if (attr == "for"){
  10534. a = ci.htmlFor;
  10535. } else if (attr == "href"){
  10536. // getAttribute href bug
  10537. // http://www.glennjones.net/Post/809/getAttributehrefbug.htm
  10538. a = ci.getAttribute("href", 2);
  10539. } else{
  10540. a = ci.getAttribute(attr);
  10541. }
  10542. }else{
  10543. a = ci.getAttribute(attr);
  10544. }
  10545. if((fn && fn(a, value)) || (!fn && a)){
  10546. result[++ri] = ci;
  10547. }
  10548. }
  10549. return result;
  10550. }
  10551. function byPseudo(cs, name, value){
  10552. return Ext.DomQuery.pseudos[name](cs, value);
  10553. }
  10554. function nodupIEXml(cs){
  10555. var d = ++key,
  10556. r;
  10557. cs[0].setAttribute("_nodup", d);
  10558. r = [cs[0]];
  10559. for(var i = 1, len = cs.length; i < len; i++){
  10560. var c = cs[i];
  10561. if(!c.getAttribute("_nodup") != d){
  10562. c.setAttribute("_nodup", d);
  10563. r[r.length] = c;
  10564. }
  10565. }
  10566. for(var i = 0, len = cs.length; i < len; i++){
  10567. cs[i].removeAttribute("_nodup");
  10568. }
  10569. return r;
  10570. }
  10571. function nodup(cs){
  10572. if(!cs){
  10573. return [];
  10574. }
  10575. var len = cs.length, c, i, r = cs, cj, ri = -1;
  10576. if(!len || typeof cs.nodeType != "undefined" || len == 1){
  10577. return cs;
  10578. }
  10579. if(isIE && typeof cs[0].selectSingleNode != "undefined"){
  10580. return nodupIEXml(cs);
  10581. }
  10582. var d = ++key;
  10583. cs[0]._nodup = d;
  10584. for(i = 1; c = cs[i]; i++){
  10585. if(c._nodup != d){
  10586. c._nodup = d;
  10587. }else{
  10588. r = [];
  10589. for(var j = 0; j < i; j++){
  10590. r[++ri] = cs[j];
  10591. }
  10592. for(j = i+1; cj = cs[j]; j++){
  10593. if(cj._nodup != d){
  10594. cj._nodup = d;
  10595. r[++ri] = cj;
  10596. }
  10597. }
  10598. return r;
  10599. }
  10600. }
  10601. return r;
  10602. }
  10603. function quickDiffIEXml(c1, c2){
  10604. var d = ++key,
  10605. r = [];
  10606. for(var i = 0, len = c1.length; i < len; i++){
  10607. c1[i].setAttribute("_qdiff", d);
  10608. }
  10609. for(var i = 0, len = c2.length; i < len; i++){
  10610. if(c2[i].getAttribute("_qdiff") != d){
  10611. r[r.length] = c2[i];
  10612. }
  10613. }
  10614. for(var i = 0, len = c1.length; i < len; i++){
  10615. c1[i].removeAttribute("_qdiff");
  10616. }
  10617. return r;
  10618. }
  10619. function quickDiff(c1, c2){
  10620. var len1 = c1.length,
  10621. d = ++key,
  10622. r = [];
  10623. if(!len1){
  10624. return c2;
  10625. }
  10626. if(isIE && typeof c1[0].selectSingleNode != "undefined"){
  10627. return quickDiffIEXml(c1, c2);
  10628. }
  10629. for(var i = 0; i < len1; i++){
  10630. c1[i]._qdiff = d;
  10631. }
  10632. for(var i = 0, len = c2.length; i < len; i++){
  10633. if(c2[i]._qdiff != d){
  10634. r[r.length] = c2[i];
  10635. }
  10636. }
  10637. return r;
  10638. }
  10639. function quickId(ns, mode, root, id){
  10640. if(ns == root){
  10641. var d = root.ownerDocument || root;
  10642. return d.getElementById(id);
  10643. }
  10644. ns = getNodes(ns, mode, "*");
  10645. return byId(ns, id);
  10646. }
  10647. return {
  10648. getStyle : function(el, name){
  10649. return Ext.fly(el).getStyle(name);
  10650. },
  10651. /**
  10652. * Compiles a selector/xpath query into a reusable function. The returned function
  10653. * takes one parameter "root" (optional), which is the context node from where the query should start.
  10654. * @param {String} selector The selector/xpath query
  10655. * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
  10656. * @return {Function}
  10657. */
  10658. compile : function(path, type){
  10659. type = type || "select";
  10660. // setup fn preamble
  10661. var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"],
  10662. mode,
  10663. lastPath,
  10664. matchers = Ext.DomQuery.matchers,
  10665. matchersLn = matchers.length,
  10666. modeMatch,
  10667. // accept leading mode switch
  10668. lmode = path.match(modeRe);
  10669. if(lmode && lmode[1]){
  10670. fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
  10671. path = path.replace(lmode[1], "");
  10672. }
  10673. // strip leading slashes
  10674. while(path.substr(0, 1)=="/"){
  10675. path = path.substr(1);
  10676. }
  10677. while(path && lastPath != path){
  10678. lastPath = path;
  10679. var tokenMatch = path.match(tagTokenRe);
  10680. if(type == "select"){
  10681. if(tokenMatch){
  10682. // ID Selector
  10683. if(tokenMatch[1] == "#"){
  10684. fn[fn.length] = 'n = quickId(n, mode, root, "'+tokenMatch[2]+'");';
  10685. }else{
  10686. fn[fn.length] = 'n = getNodes(n, mode, "'+tokenMatch[2]+'");';
  10687. }
  10688. path = path.replace(tokenMatch[0], "");
  10689. }else if(path.substr(0, 1) != '@'){
  10690. fn[fn.length] = 'n = getNodes(n, mode, "*");';
  10691. }
  10692. // type of "simple"
  10693. }else{
  10694. if(tokenMatch){
  10695. if(tokenMatch[1] == "#"){
  10696. fn[fn.length] = 'n = byId(n, "'+tokenMatch[2]+'");';
  10697. }else{
  10698. fn[fn.length] = 'n = byTag(n, "'+tokenMatch[2]+'");';
  10699. }
  10700. path = path.replace(tokenMatch[0], "");
  10701. }
  10702. }
  10703. while(!(modeMatch = path.match(modeRe))){
  10704. var matched = false;
  10705. for(var j = 0; j < matchersLn; j++){
  10706. var t = matchers[j];
  10707. var m = path.match(t.re);
  10708. if(m){
  10709. fn[fn.length] = t.select.replace(tplRe, function(x, i){
  10710. return m[i];
  10711. });
  10712. path = path.replace(m[0], "");
  10713. matched = true;
  10714. break;
  10715. }
  10716. }
  10717. // prevent infinite loop on bad selector
  10718. if(!matched){
  10719. }
  10720. }
  10721. if(modeMatch[1]){
  10722. fn[fn.length] = 'mode="'+modeMatch[1].replace(trimRe, "")+'";';
  10723. path = path.replace(modeMatch[1], "");
  10724. }
  10725. }
  10726. // close fn out
  10727. fn[fn.length] = "return nodup(n);\n}";
  10728. // eval fn and return it
  10729. eval(fn.join(""));
  10730. return f;
  10731. },
  10732. /**
  10733. * Selects an array of DOM nodes using JavaScript-only implementation.
  10734. *
  10735. * Use {@link #select} to take advantage of browsers built-in support for CSS selectors.
  10736. *
  10737. * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
  10738. * @param {HTMLElement/String} root (optional) The start of the query (defaults to document).
  10739. * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are
  10740. * no matches, and empty Array is returned.
  10741. */
  10742. jsSelect: function(path, root, type){
  10743. // set root to doc if not specified.
  10744. root = root || document;
  10745. if(typeof root == "string"){
  10746. root = document.getElementById(root);
  10747. }
  10748. var paths = path.split(","),
  10749. results = [];
  10750. // loop over each selector
  10751. for(var i = 0, len = paths.length; i < len; i++){
  10752. var subPath = paths[i].replace(trimRe, "");
  10753. // compile and place in cache
  10754. if(!cache[subPath]){
  10755. cache[subPath] = Ext.DomQuery.compile(subPath);
  10756. if(!cache[subPath]){
  10757. }
  10758. }
  10759. var result = cache[subPath](root);
  10760. if(result && result != document){
  10761. results = results.concat(result);
  10762. }
  10763. }
  10764. // if there were multiple selectors, make sure dups
  10765. // are eliminated
  10766. if(paths.length > 1){
  10767. return nodup(results);
  10768. }
  10769. return results;
  10770. },
  10771. isXml: function(el) {
  10772. var docEl = (el ? el.ownerDocument || el : 0).documentElement;
  10773. return docEl ? docEl.nodeName !== "HTML" : false;
  10774. },
  10775. /**
  10776. * Selects an array of DOM nodes by CSS/XPath selector.
  10777. *
  10778. * Uses [document.querySelectorAll][0] if browser supports that, otherwise falls back to
  10779. * {@link Ext.DomQuery#jsSelect} to do the work.
  10780. *
  10781. * Aliased as {@link Ext#query}.
  10782. *
  10783. * [0]: https://developer.mozilla.org/en/DOM/document.querySelectorAll
  10784. *
  10785. * @param {String} path The selector/xpath query
  10786. * @param {HTMLElement} root (optional) The start of the query (defaults to document).
  10787. * @return {HTMLElement[]} An array of DOM elements (not a NodeList as returned by `querySelectorAll`).
  10788. * Empty array when no matches.
  10789. * @method
  10790. */
  10791. select : document.querySelectorAll ? function(path, root, type) {
  10792. root = root || document;
  10793. /*
  10794. * Safari 3.x can't handle uppercase or unicode characters when in quirks mode.
  10795. */
  10796. if (!Ext.DomQuery.isXml(root) && !(Ext.isSafari3 && !Ext.isStrict)) {
  10797. try {
  10798. /*
  10799. * This checking here is to "fix" the behaviour of querySelectorAll
  10800. * for non root document queries. The way qsa works is intentional,
  10801. * however it's definitely not the expected way it should work.
  10802. * More info: http://ejohn.org/blog/thoughts-on-queryselectorall/
  10803. *
  10804. * We only modify the path for single selectors (ie, no multiples),
  10805. * without a full parser it makes it difficult to do this correctly.
  10806. */
  10807. var isDocumentRoot = root.nodeType === 9,
  10808. _path = path,
  10809. _root = root;
  10810. if (!isDocumentRoot && path.indexOf(',') === -1 && !startIdRe.test(path)) {
  10811. _path = '#' + Ext.id(root) + ' ' + path;
  10812. _root = root.parentNode;
  10813. }
  10814. return Ext.Array.toArray(_root.querySelectorAll(_path));
  10815. }
  10816. catch (e) {
  10817. }
  10818. }
  10819. return Ext.DomQuery.jsSelect.call(this, path, root, type);
  10820. } : function(path, root, type) {
  10821. return Ext.DomQuery.jsSelect.call(this, path, root, type);
  10822. },
  10823. /**
  10824. * Selects a single element.
  10825. * @param {String} selector The selector/xpath query
  10826. * @param {HTMLElement} root (optional) The start of the query (defaults to document).
  10827. * @return {HTMLElement} The DOM element which matched the selector.
  10828. */
  10829. selectNode : function(path, root){
  10830. return Ext.DomQuery.select(path, root)[0];
  10831. },
  10832. /**
  10833. * Selects the value of a node, optionally replacing null with the defaultValue.
  10834. * @param {String} selector The selector/xpath query
  10835. * @param {HTMLElement} root (optional) The start of the query (defaults to document).
  10836. * @param {String} defaultValue (optional) When specified, this is return as empty value.
  10837. * @return {String}
  10838. */
  10839. selectValue : function(path, root, defaultValue){
  10840. path = path.replace(trimRe, "");
  10841. if(!valueCache[path]){
  10842. valueCache[path] = Ext.DomQuery.compile(path, "select");
  10843. }
  10844. var n = valueCache[path](root), v;
  10845. n = n[0] ? n[0] : n;
  10846. // overcome a limitation of maximum textnode size
  10847. // Rumored to potentially crash IE6 but has not been confirmed.
  10848. // http://reference.sitepoint.com/javascript/Node/normalize
  10849. // https://developer.mozilla.org/En/DOM/Node.normalize
  10850. if (typeof n.normalize == 'function') n.normalize();
  10851. v = (n && n.firstChild ? n.firstChild.nodeValue : null);
  10852. return ((v === null||v === undefined||v==='') ? defaultValue : v);
  10853. },
  10854. /**
  10855. * Selects the value of a node, parsing integers and floats. Returns the defaultValue, or 0 if none is specified.
  10856. * @param {String} selector The selector/xpath query
  10857. * @param {HTMLElement} root (optional) The start of the query (defaults to document).
  10858. * @param {Number} defaultValue (optional) When specified, this is return as empty value.
  10859. * @return {Number}
  10860. */
  10861. selectNumber : function(path, root, defaultValue){
  10862. var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0);
  10863. return parseFloat(v);
  10864. },
  10865. /**
  10866. * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
  10867. * @param {String/HTMLElement/HTMLElement[]} el An element id, element or array of elements
  10868. * @param {String} selector The simple selector to test
  10869. * @return {Boolean}
  10870. */
  10871. is : function(el, ss){
  10872. if(typeof el == "string"){
  10873. el = document.getElementById(el);
  10874. }
  10875. var isArray = Ext.isArray(el),
  10876. result = Ext.DomQuery.filter(isArray ? el : [el], ss);
  10877. return isArray ? (result.length == el.length) : (result.length > 0);
  10878. },
  10879. /**
  10880. * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
  10881. * @param {HTMLElement[]} el An array of elements to filter
  10882. * @param {String} selector The simple selector to test
  10883. * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
  10884. * the selector instead of the ones that match
  10885. * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are
  10886. * no matches, and empty Array is returned.
  10887. */
  10888. filter : function(els, ss, nonMatches){
  10889. ss = ss.replace(trimRe, "");
  10890. if(!simpleCache[ss]){
  10891. simpleCache[ss] = Ext.DomQuery.compile(ss, "simple");
  10892. }
  10893. var result = simpleCache[ss](els);
  10894. return nonMatches ? quickDiff(result, els) : result;
  10895. },
  10896. /**
  10897. * Collection of matching regular expressions and code snippets.
  10898. * Each capture group within () will be replace the {} in the select
  10899. * statement as specified by their index.
  10900. */
  10901. matchers : [{
  10902. re: /^\.([\w-]+)/,
  10903. select: 'n = byClassName(n, " {1} ");'
  10904. }, {
  10905. re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
  10906. select: 'n = byPseudo(n, "{1}", "{2}");'
  10907. },{
  10908. re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
  10909. select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
  10910. }, {
  10911. re: /^#([\w-]+)/,
  10912. select: 'n = byId(n, "{1}");'
  10913. },{
  10914. re: /^@([\w-]+)/,
  10915. select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
  10916. }
  10917. ],
  10918. /**
  10919. * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
  10920. * New operators can be added as long as the match the format <i>c</i>= where <i>c</i> is any character other than space, &gt; &lt;.
  10921. */
  10922. operators : {
  10923. "=" : function(a, v){
  10924. return a == v;
  10925. },
  10926. "!=" : function(a, v){
  10927. return a != v;
  10928. },
  10929. "^=" : function(a, v){
  10930. return a && a.substr(0, v.length) == v;
  10931. },
  10932. "$=" : function(a, v){
  10933. return a && a.substr(a.length-v.length) == v;
  10934. },
  10935. "*=" : function(a, v){
  10936. return a && a.indexOf(v) !== -1;
  10937. },
  10938. "%=" : function(a, v){
  10939. return (a % v) == 0;
  10940. },
  10941. "|=" : function(a, v){
  10942. return a && (a == v || a.substr(0, v.length+1) == v+'-');
  10943. },
  10944. "~=" : function(a, v){
  10945. return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
  10946. }
  10947. },
  10948. /**
  10949. Object hash of "pseudo class" filter functions which are used when filtering selections.
  10950. Each function is passed two parameters:
  10951. - **c** : Array
  10952. An Array of DOM elements to filter.
  10953. - **v** : String
  10954. The argument (if any) supplied in the selector.
  10955. A filter function returns an Array of DOM elements which conform to the pseudo class.
  10956. In addition to the provided pseudo classes listed above such as `first-child` and `nth-child`,
  10957. developers may add additional, custom psuedo class filters to select elements according to application-specific requirements.
  10958. For example, to filter `a` elements to only return links to __external__ resources:
  10959. Ext.DomQuery.pseudos.external = function(c, v){
  10960. var r = [], ri = -1;
  10961. for(var i = 0, ci; ci = c[i]; i++){
  10962. // Include in result set only if it's a link to an external resource
  10963. if(ci.hostname != location.hostname){
  10964. r[++ri] = ci;
  10965. }
  10966. }
  10967. return r;
  10968. };
  10969. Then external links could be gathered with the following statement:
  10970. var externalLinks = Ext.select("a:external");
  10971. * @markdown
  10972. */
  10973. pseudos : {
  10974. "first-child" : function(c){
  10975. var r = [], ri = -1, n;
  10976. for(var i = 0, ci; ci = n = c[i]; i++){
  10977. while((n = n.previousSibling) && n.nodeType != 1);
  10978. if(!n){
  10979. r[++ri] = ci;
  10980. }
  10981. }
  10982. return r;
  10983. },
  10984. "last-child" : function(c){
  10985. var r = [], ri = -1, n;
  10986. for(var i = 0, ci; ci = n = c[i]; i++){
  10987. while((n = n.nextSibling) && n.nodeType != 1);
  10988. if(!n){
  10989. r[++ri] = ci;
  10990. }
  10991. }
  10992. return r;
  10993. },
  10994. "nth-child" : function(c, a) {
  10995. var r = [], ri = -1,
  10996. m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a),
  10997. f = (m[1] || 1) - 0, l = m[2] - 0;
  10998. for(var i = 0, n; n = c[i]; i++){
  10999. var pn = n.parentNode;
  11000. if (batch != pn._batch) {
  11001. var j = 0;
  11002. for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
  11003. if(cn.nodeType == 1){
  11004. cn.nodeIndex = ++j;
  11005. }
  11006. }
  11007. pn._batch = batch;
  11008. }
  11009. if (f == 1) {
  11010. if (l == 0 || n.nodeIndex == l){
  11011. r[++ri] = n;
  11012. }
  11013. } else if ((n.nodeIndex + l) % f == 0){
  11014. r[++ri] = n;
  11015. }
  11016. }
  11017. return r;
  11018. },
  11019. "only-child" : function(c){
  11020. var r = [], ri = -1;;
  11021. for(var i = 0, ci; ci = c[i]; i++){
  11022. if(!prev(ci) && !next(ci)){
  11023. r[++ri] = ci;
  11024. }
  11025. }
  11026. return r;
  11027. },
  11028. "empty" : function(c){
  11029. var r = [], ri = -1;
  11030. for(var i = 0, ci; ci = c[i]; i++){
  11031. var cns = ci.childNodes, j = 0, cn, empty = true;
  11032. while(cn = cns[j]){
  11033. ++j;
  11034. if(cn.nodeType == 1 || cn.nodeType == 3){
  11035. empty = false;
  11036. break;
  11037. }
  11038. }
  11039. if(empty){
  11040. r[++ri] = ci;
  11041. }
  11042. }
  11043. return r;
  11044. },
  11045. "contains" : function(c, v){
  11046. var r = [], ri = -1;
  11047. for(var i = 0, ci; ci = c[i]; i++){
  11048. if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
  11049. r[++ri] = ci;
  11050. }
  11051. }
  11052. return r;
  11053. },
  11054. "nodeValue" : function(c, v){
  11055. var r = [], ri = -1;
  11056. for(var i = 0, ci; ci = c[i]; i++){
  11057. if(ci.firstChild && ci.firstChild.nodeValue == v){
  11058. r[++ri] = ci;
  11059. }
  11060. }
  11061. return r;
  11062. },
  11063. "checked" : function(c){
  11064. var r = [], ri = -1;
  11065. for(var i = 0, ci; ci = c[i]; i++){
  11066. if(ci.checked == true){
  11067. r[++ri] = ci;
  11068. }
  11069. }
  11070. return r;
  11071. },
  11072. "not" : function(c, ss){
  11073. return Ext.DomQuery.filter(c, ss, true);
  11074. },
  11075. "any" : function(c, selectors){
  11076. var ss = selectors.split('|'),
  11077. r = [], ri = -1, s;
  11078. for(var i = 0, ci; ci = c[i]; i++){
  11079. for(var j = 0; s = ss[j]; j++){
  11080. if(Ext.DomQuery.is(ci, s)){
  11081. r[++ri] = ci;
  11082. break;
  11083. }
  11084. }
  11085. }
  11086. return r;
  11087. },
  11088. "odd" : function(c){
  11089. return this["nth-child"](c, "odd");
  11090. },
  11091. "even" : function(c){
  11092. return this["nth-child"](c, "even");
  11093. },
  11094. "nth" : function(c, a){
  11095. return c[a-1] || [];
  11096. },
  11097. "first" : function(c){
  11098. return c[0] || [];
  11099. },
  11100. "last" : function(c){
  11101. return c[c.length-1] || [];
  11102. },
  11103. "has" : function(c, ss){
  11104. var s = Ext.DomQuery.select,
  11105. r = [], ri = -1;
  11106. for(var i = 0, ci; ci = c[i]; i++){
  11107. if(s(ss, ci).length > 0){
  11108. r[++ri] = ci;
  11109. }
  11110. }
  11111. return r;
  11112. },
  11113. "next" : function(c, ss){
  11114. var is = Ext.DomQuery.is,
  11115. r = [], ri = -1;
  11116. for(var i = 0, ci; ci = c[i]; i++){
  11117. var n = next(ci);
  11118. if(n && is(n, ss)){
  11119. r[++ri] = ci;
  11120. }
  11121. }
  11122. return r;
  11123. },
  11124. "prev" : function(c, ss){
  11125. var is = Ext.DomQuery.is,
  11126. r = [], ri = -1;
  11127. for(var i = 0, ci; ci = c[i]; i++){
  11128. var n = prev(ci);
  11129. if(n && is(n, ss)){
  11130. r[++ri] = ci;
  11131. }
  11132. }
  11133. return r;
  11134. }
  11135. }
  11136. };
  11137. }();
  11138. /**
  11139. * Shorthand of {@link Ext.DomQuery#select}
  11140. * @member Ext
  11141. * @method query
  11142. * @alias Ext.DomQuery#select
  11143. */
  11144. Ext.query = Ext.DomQuery.select;
  11145. /**
  11146. * @class Ext.Element
  11147. * @alternateClassName Ext.core.Element
  11148. *
  11149. * Encapsulates a DOM element, adding simple DOM manipulation facilities, normalizing for browser differences.
  11150. *
  11151. * All instances of this class inherit the methods of {@link Ext.fx.Anim} making visual effects easily available to all
  11152. * DOM elements.
  11153. *
  11154. * Note that the events documented in this class are not Ext events, they encapsulate browser events. Some older browsers
  11155. * may not support the full range of events. Which events are supported is beyond the control of Ext JS.
  11156. *
  11157. * Usage:
  11158. *
  11159. * // by id
  11160. * var el = Ext.get("my-div");
  11161. *
  11162. * // by DOM element reference
  11163. * var el = Ext.get(myDivElement);
  11164. *
  11165. * # Animations
  11166. *
  11167. * When an element is manipulated, by default there is no animation.
  11168. *
  11169. * var el = Ext.get("my-div");
  11170. *
  11171. * // no animation
  11172. * el.setWidth(100);
  11173. *
  11174. * Many of the functions for manipulating an element have an optional "animate" parameter. This parameter can be
  11175. * specified as boolean (true) for default animation effects.
  11176. *
  11177. * // default animation
  11178. * el.setWidth(100, true);
  11179. *
  11180. * To configure the effects, an object literal with animation options to use as the Element animation configuration
  11181. * object can also be specified. Note that the supported Element animation configuration options are a subset of the
  11182. * {@link Ext.fx.Anim} animation options specific to Fx effects. The supported Element animation configuration options
  11183. * are:
  11184. *
  11185. * Option Default Description
  11186. * --------- -------- ---------------------------------------------
  11187. * {@link Ext.fx.Anim#duration duration} .35 The duration of the animation in seconds
  11188. * {@link Ext.fx.Anim#easing easing} easeOut The easing method
  11189. * {@link Ext.fx.Anim#callback callback} none A function to execute when the anim completes
  11190. * {@link Ext.fx.Anim#scope scope} this The scope (this) of the callback function
  11191. *
  11192. * Usage:
  11193. *
  11194. * // Element animation options object
  11195. * var opt = {
  11196. * {@link Ext.fx.Anim#duration duration}: 1,
  11197. * {@link Ext.fx.Anim#easing easing}: 'elasticIn',
  11198. * {@link Ext.fx.Anim#callback callback}: this.foo,
  11199. * {@link Ext.fx.Anim#scope scope}: this
  11200. * };
  11201. * // animation with some options set
  11202. * el.setWidth(100, opt);
  11203. *
  11204. * The Element animation object being used for the animation will be set on the options object as "anim", which allows
  11205. * you to stop or manipulate the animation. Here is an example:
  11206. *
  11207. * // using the "anim" property to get the Anim object
  11208. * if(opt.anim.isAnimated()){
  11209. * opt.anim.stop();
  11210. * }
  11211. *
  11212. * # Composite (Collections of) Elements
  11213. *
  11214. * For working with collections of Elements, see {@link Ext.CompositeElement}
  11215. *
  11216. * @constructor
  11217. * Creates new Element directly.
  11218. * @param {String/HTMLElement} element
  11219. * @param {Boolean} forceNew (optional) By default the constructor checks to see if there is already an instance of this
  11220. * element in the cache and if there is it returns the same instance. This will skip that check (useful for extending
  11221. * this class).
  11222. * @return {Object}
  11223. */
  11224. (function() {
  11225. var DOC = document,
  11226. EC = Ext.cache;
  11227. Ext.Element = Ext.core.Element = function(element, forceNew) {
  11228. var dom = typeof element == "string" ? DOC.getElementById(element) : element,
  11229. id;
  11230. if (!dom) {
  11231. return null;
  11232. }
  11233. id = dom.id;
  11234. if (!forceNew && id && EC[id]) {
  11235. // element object already exists
  11236. return EC[id].el;
  11237. }
  11238. /**
  11239. * @property {HTMLElement} dom
  11240. * The DOM element
  11241. */
  11242. this.dom = dom;
  11243. /**
  11244. * @property {String} id
  11245. * The DOM element ID
  11246. */
  11247. this.id = id || Ext.id(dom);
  11248. };
  11249. var DH = Ext.DomHelper,
  11250. El = Ext.Element;
  11251. El.prototype = {
  11252. /**
  11253. * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
  11254. * @param {Object} o The object with the attributes
  11255. * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
  11256. * @return {Ext.Element} this
  11257. */
  11258. set: function(o, useSet) {
  11259. var el = this.dom,
  11260. attr,
  11261. val;
  11262. useSet = (useSet !== false) && !!el.setAttribute;
  11263. for (attr in o) {
  11264. if (o.hasOwnProperty(attr)) {
  11265. val = o[attr];
  11266. if (attr == 'style') {
  11267. DH.applyStyles(el, val);
  11268. } else if (attr == 'cls') {
  11269. el.className = val;
  11270. } else if (useSet) {
  11271. el.setAttribute(attr, val);
  11272. } else {
  11273. el[attr] = val;
  11274. }
  11275. }
  11276. }
  11277. return this;
  11278. },
  11279. // Mouse events
  11280. /**
  11281. * @event click
  11282. * Fires when a mouse click is detected within the element.
  11283. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11284. * @param {HTMLElement} t The target of the event.
  11285. */
  11286. /**
  11287. * @event contextmenu
  11288. * Fires when a right click is detected within the element.
  11289. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11290. * @param {HTMLElement} t The target of the event.
  11291. */
  11292. /**
  11293. * @event dblclick
  11294. * Fires when a mouse double click is detected within the element.
  11295. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11296. * @param {HTMLElement} t The target of the event.
  11297. */
  11298. /**
  11299. * @event mousedown
  11300. * Fires when a mousedown is detected within the element.
  11301. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11302. * @param {HTMLElement} t The target of the event.
  11303. */
  11304. /**
  11305. * @event mouseup
  11306. * Fires when a mouseup is detected within the element.
  11307. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11308. * @param {HTMLElement} t The target of the event.
  11309. */
  11310. /**
  11311. * @event mouseover
  11312. * Fires when a mouseover is detected within the element.
  11313. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11314. * @param {HTMLElement} t The target of the event.
  11315. */
  11316. /**
  11317. * @event mousemove
  11318. * Fires when a mousemove is detected with the element.
  11319. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11320. * @param {HTMLElement} t The target of the event.
  11321. */
  11322. /**
  11323. * @event mouseout
  11324. * Fires when a mouseout is detected with the element.
  11325. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11326. * @param {HTMLElement} t The target of the event.
  11327. */
  11328. /**
  11329. * @event mouseenter
  11330. * Fires when the mouse enters the element.
  11331. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11332. * @param {HTMLElement} t The target of the event.
  11333. */
  11334. /**
  11335. * @event mouseleave
  11336. * Fires when the mouse leaves the element.
  11337. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11338. * @param {HTMLElement} t The target of the event.
  11339. */
  11340. // Keyboard events
  11341. /**
  11342. * @event keypress
  11343. * Fires when a keypress is detected within the element.
  11344. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11345. * @param {HTMLElement} t The target of the event.
  11346. */
  11347. /**
  11348. * @event keydown
  11349. * Fires when a keydown is detected within the element.
  11350. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11351. * @param {HTMLElement} t The target of the event.
  11352. */
  11353. /**
  11354. * @event keyup
  11355. * Fires when a keyup is detected within the element.
  11356. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11357. * @param {HTMLElement} t The target of the event.
  11358. */
  11359. // HTML frame/object events
  11360. /**
  11361. * @event load
  11362. * Fires when the user agent finishes loading all content within the element. Only supported by window, frames,
  11363. * objects and images.
  11364. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11365. * @param {HTMLElement} t The target of the event.
  11366. */
  11367. /**
  11368. * @event unload
  11369. * Fires when the user agent removes all content from a window or frame. For elements, it fires when the target
  11370. * element or any of its content has been removed.
  11371. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11372. * @param {HTMLElement} t The target of the event.
  11373. */
  11374. /**
  11375. * @event abort
  11376. * Fires when an object/image is stopped from loading before completely loaded.
  11377. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11378. * @param {HTMLElement} t The target of the event.
  11379. */
  11380. /**
  11381. * @event error
  11382. * Fires when an object/image/frame cannot be loaded properly.
  11383. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11384. * @param {HTMLElement} t The target of the event.
  11385. */
  11386. /**
  11387. * @event resize
  11388. * Fires when a document view is resized.
  11389. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11390. * @param {HTMLElement} t The target of the event.
  11391. */
  11392. /**
  11393. * @event scroll
  11394. * Fires when a document view is scrolled.
  11395. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11396. * @param {HTMLElement} t The target of the event.
  11397. */
  11398. // Form events
  11399. /**
  11400. * @event select
  11401. * Fires when a user selects some text in a text field, including input and textarea.
  11402. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11403. * @param {HTMLElement} t The target of the event.
  11404. */
  11405. /**
  11406. * @event change
  11407. * Fires when a control loses the input focus and its value has been modified since gaining focus.
  11408. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11409. * @param {HTMLElement} t The target of the event.
  11410. */
  11411. /**
  11412. * @event submit
  11413. * Fires when a form is submitted.
  11414. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11415. * @param {HTMLElement} t The target of the event.
  11416. */
  11417. /**
  11418. * @event reset
  11419. * Fires when a form is reset.
  11420. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11421. * @param {HTMLElement} t The target of the event.
  11422. */
  11423. /**
  11424. * @event focus
  11425. * Fires when an element receives focus either via the pointing device or by tab navigation.
  11426. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11427. * @param {HTMLElement} t The target of the event.
  11428. */
  11429. /**
  11430. * @event blur
  11431. * Fires when an element loses focus either via the pointing device or by tabbing navigation.
  11432. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11433. * @param {HTMLElement} t The target of the event.
  11434. */
  11435. // User Interface events
  11436. /**
  11437. * @event DOMFocusIn
  11438. * Where supported. Similar to HTML focus event, but can be applied to any focusable element.
  11439. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11440. * @param {HTMLElement} t The target of the event.
  11441. */
  11442. /**
  11443. * @event DOMFocusOut
  11444. * Where supported. Similar to HTML blur event, but can be applied to any focusable element.
  11445. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11446. * @param {HTMLElement} t The target of the event.
  11447. */
  11448. /**
  11449. * @event DOMActivate
  11450. * Where supported. Fires when an element is activated, for instance, through a mouse click or a keypress.
  11451. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11452. * @param {HTMLElement} t The target of the event.
  11453. */
  11454. // DOM Mutation events
  11455. /**
  11456. * @event DOMSubtreeModified
  11457. * Where supported. Fires when the subtree is modified.
  11458. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11459. * @param {HTMLElement} t The target of the event.
  11460. */
  11461. /**
  11462. * @event DOMNodeInserted
  11463. * Where supported. Fires when a node has been added as a child of another node.
  11464. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11465. * @param {HTMLElement} t The target of the event.
  11466. */
  11467. /**
  11468. * @event DOMNodeRemoved
  11469. * Where supported. Fires when a descendant node of the element is removed.
  11470. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11471. * @param {HTMLElement} t The target of the event.
  11472. */
  11473. /**
  11474. * @event DOMNodeRemovedFromDocument
  11475. * Where supported. Fires when a node is being removed from a document.
  11476. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11477. * @param {HTMLElement} t The target of the event.
  11478. */
  11479. /**
  11480. * @event DOMNodeInsertedIntoDocument
  11481. * Where supported. Fires when a node is being inserted into a document.
  11482. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11483. * @param {HTMLElement} t The target of the event.
  11484. */
  11485. /**
  11486. * @event DOMAttrModified
  11487. * Where supported. Fires when an attribute has been modified.
  11488. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11489. * @param {HTMLElement} t The target of the event.
  11490. */
  11491. /**
  11492. * @event DOMCharacterDataModified
  11493. * Where supported. Fires when the character data has been modified.
  11494. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11495. * @param {HTMLElement} t The target of the event.
  11496. */
  11497. /**
  11498. * @property {String} defaultUnit
  11499. * The default unit to append to CSS values where a unit isn't provided.
  11500. */
  11501. defaultUnit: "px",
  11502. /**
  11503. * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
  11504. * @param {String} selector The simple selector to test
  11505. * @return {Boolean} True if this element matches the selector, else false
  11506. */
  11507. is: function(simpleSelector) {
  11508. return Ext.DomQuery.is(this.dom, simpleSelector);
  11509. },
  11510. /**
  11511. * Tries to focus the element. Any exceptions are caught and ignored.
  11512. * @param {Number} defer (optional) Milliseconds to defer the focus
  11513. * @return {Ext.Element} this
  11514. */
  11515. focus: function(defer,
  11516. /* private */
  11517. dom) {
  11518. var me = this;
  11519. dom = dom || me.dom;
  11520. try {
  11521. if (Number(defer)) {
  11522. Ext.defer(me.focus, defer, null, [null, dom]);
  11523. } else {
  11524. dom.focus();
  11525. }
  11526. } catch(e) {}
  11527. return me;
  11528. },
  11529. /**
  11530. * Tries to blur the element. Any exceptions are caught and ignored.
  11531. * @return {Ext.Element} this
  11532. */
  11533. blur: function() {
  11534. try {
  11535. this.dom.blur();
  11536. } catch(e) {}
  11537. return this;
  11538. },
  11539. /**
  11540. * Returns the value of the "value" attribute
  11541. * @param {Boolean} asNumber true to parse the value as a number
  11542. * @return {String/Number}
  11543. */
  11544. getValue: function(asNumber) {
  11545. var val = this.dom.value;
  11546. return asNumber ? parseInt(val, 10) : val;
  11547. },
  11548. /**
  11549. * Appends an event handler to this element.
  11550. *
  11551. * @param {String} eventName The name of event to handle.
  11552. *
  11553. * @param {Function} fn The handler function the event invokes. This function is passed the following parameters:
  11554. *
  11555. * - **evt** : EventObject
  11556. *
  11557. * The {@link Ext.EventObject EventObject} describing the event.
  11558. *
  11559. * - **el** : HtmlElement
  11560. *
  11561. * The DOM element which was the target of the event. Note that this may be filtered by using the delegate option.
  11562. *
  11563. * - **o** : Object
  11564. *
  11565. * The options object from the addListener call.
  11566. *
  11567. * @param {Object} scope (optional) The scope (**this** reference) in which the handler function is executed. **If
  11568. * omitted, defaults to this Element.**
  11569. *
  11570. * @param {Object} options (optional) An object containing handler configuration properties. This may contain any of
  11571. * the following properties:
  11572. *
  11573. * - **scope** Object :
  11574. *
  11575. * The scope (**this** reference) in which the handler function is executed. **If omitted, defaults to this
  11576. * Element.**
  11577. *
  11578. * - **delegate** String:
  11579. *
  11580. * A simple selector to filter the target or look for a descendant of the target. See below for additional details.
  11581. *
  11582. * - **stopEvent** Boolean:
  11583. *
  11584. * True to stop the event. That is stop propagation, and prevent the default action.
  11585. *
  11586. * - **preventDefault** Boolean:
  11587. *
  11588. * True to prevent the default action
  11589. *
  11590. * - **stopPropagation** Boolean:
  11591. *
  11592. * True to prevent event propagation
  11593. *
  11594. * - **normalized** Boolean:
  11595. *
  11596. * False to pass a browser event to the handler function instead of an Ext.EventObject
  11597. *
  11598. * - **target** Ext.Element:
  11599. *
  11600. * Only call the handler if the event was fired on the target Element, _not_ if the event was bubbled up from a
  11601. * child node.
  11602. *
  11603. * - **delay** Number:
  11604. *
  11605. * The number of milliseconds to delay the invocation of the handler after the event fires.
  11606. *
  11607. * - **single** Boolean:
  11608. *
  11609. * True to add a handler to handle just the next firing of the event, and then remove itself.
  11610. *
  11611. * - **buffer** Number:
  11612. *
  11613. * Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed by the specified number of
  11614. * milliseconds. If the event fires again within that time, the original handler is _not_ invoked, but the new
  11615. * handler is scheduled in its place.
  11616. *
  11617. * **Combining Options**
  11618. *
  11619. * In the following examples, the shorthand form {@link #on} is used rather than the more verbose addListener. The
  11620. * two are equivalent. Using the options argument, it is possible to combine different types of listeners:
  11621. *
  11622. * A delayed, one-time listener that auto stops the event and adds a custom argument (forumId) to the options
  11623. * object. The options object is available as the third parameter in the handler function.
  11624. *
  11625. * Code:
  11626. *
  11627. * el.on('click', this.onClick, this, {
  11628. * single: true,
  11629. * delay: 100,
  11630. * stopEvent : true,
  11631. * forumId: 4
  11632. * });
  11633. *
  11634. * **Attaching multiple handlers in 1 call**
  11635. *
  11636. * The method also allows for a single argument to be passed which is a config object containing properties which
  11637. * specify multiple handlers.
  11638. *
  11639. * Code:
  11640. *
  11641. * el.on({
  11642. * 'click' : {
  11643. * fn: this.onClick,
  11644. * scope: this,
  11645. * delay: 100
  11646. * },
  11647. * 'mouseover' : {
  11648. * fn: this.onMouseOver,
  11649. * scope: this
  11650. * },
  11651. * 'mouseout' : {
  11652. * fn: this.onMouseOut,
  11653. * scope: this
  11654. * }
  11655. * });
  11656. *
  11657. * Or a shorthand syntax:
  11658. *
  11659. * Code:
  11660. *
  11661. * el.on({
  11662. * 'click' : this.onClick,
  11663. * 'mouseover' : this.onMouseOver,
  11664. * 'mouseout' : this.onMouseOut,
  11665. * scope: this
  11666. * });
  11667. *
  11668. * **delegate**
  11669. *
  11670. * This is a configuration option that you can pass along when registering a handler for an event to assist with
  11671. * event delegation. Event delegation is a technique that is used to reduce memory consumption and prevent exposure
  11672. * to memory-leaks. By registering an event for a container element as opposed to each element within a container.
  11673. * By setting this configuration option to a simple selector, the target element will be filtered to look for a
  11674. * descendant of the target. For example:
  11675. *
  11676. * // using this markup:
  11677. * <div id='elId'>
  11678. * <p id='p1'>paragraph one</p>
  11679. * <p id='p2' class='clickable'>paragraph two</p>
  11680. * <p id='p3'>paragraph three</p>
  11681. * </div>
  11682. *
  11683. * // utilize event delegation to registering just one handler on the container element:
  11684. * el = Ext.get('elId');
  11685. * el.on(
  11686. * 'click',
  11687. * function(e,t) {
  11688. * // handle click
  11689. * console.info(t.id); // 'p2'
  11690. * },
  11691. * this,
  11692. * {
  11693. * // filter the target element to be a descendant with the class 'clickable'
  11694. * delegate: '.clickable'
  11695. * }
  11696. * );
  11697. *
  11698. * @return {Ext.Element} this
  11699. */
  11700. addListener: function(eventName, fn, scope, options) {
  11701. Ext.EventManager.on(this.dom, eventName, fn, scope || this, options);
  11702. return this;
  11703. },
  11704. /**
  11705. * Removes an event handler from this element.
  11706. *
  11707. * **Note**: if a *scope* was explicitly specified when {@link #addListener adding} the listener,
  11708. * the same scope must be specified here.
  11709. *
  11710. * Example:
  11711. *
  11712. * el.removeListener('click', this.handlerFn);
  11713. * // or
  11714. * el.un('click', this.handlerFn);
  11715. *
  11716. * @param {String} eventName The name of the event from which to remove the handler.
  11717. * @param {Function} fn The handler function to remove. **This must be a reference to the function passed into the
  11718. * {@link #addListener} call.**
  11719. * @param {Object} scope If a scope (**this** reference) was specified when the listener was added, then this must
  11720. * refer to the same object.
  11721. * @return {Ext.Element} this
  11722. */
  11723. removeListener: function(eventName, fn, scope) {
  11724. Ext.EventManager.un(this.dom, eventName, fn, scope || this);
  11725. return this;
  11726. },
  11727. /**
  11728. * Removes all previous added listeners from this element
  11729. * @return {Ext.Element} this
  11730. */
  11731. removeAllListeners: function() {
  11732. Ext.EventManager.removeAll(this.dom);
  11733. return this;
  11734. },
  11735. /**
  11736. * Recursively removes all previous added listeners from this element and its children
  11737. * @return {Ext.Element} this
  11738. */
  11739. purgeAllListeners: function() {
  11740. Ext.EventManager.purgeElement(this);
  11741. return this;
  11742. },
  11743. /**
  11744. * Test if size has a unit, otherwise appends the passed unit string, or the default for this Element.
  11745. * @param size {Mixed} The size to set
  11746. * @param units {String} The units to append to a numeric size value
  11747. * @private
  11748. */
  11749. addUnits: function(size, units) {
  11750. // Most common case first: Size is set to a number
  11751. if (Ext.isNumber(size)) {
  11752. return size + (units || this.defaultUnit || 'px');
  11753. }
  11754. // Size set to a value which means "auto"
  11755. if (size === "" || size == "auto" || size == null) {
  11756. return size || '';
  11757. }
  11758. // Otherwise, warn if it's not a valid CSS measurement
  11759. if (!unitPattern.test(size)) {
  11760. return size || '';
  11761. }
  11762. return size;
  11763. },
  11764. /**
  11765. * Tests various css rules/browsers to determine if this element uses a border box
  11766. * @return {Boolean}
  11767. */
  11768. isBorderBox: function() {
  11769. return Ext.isBorderBox || noBoxAdjust[(this.dom.tagName || "").toLowerCase()];
  11770. },
  11771. /**
  11772. * Removes this element's dom reference. Note that event and cache removal is handled at {@link Ext#removeNode
  11773. * Ext.removeNode}
  11774. */
  11775. remove: function() {
  11776. var me = this,
  11777. dom = me.dom;
  11778. if (dom) {
  11779. delete me.dom;
  11780. Ext.removeNode(dom);
  11781. }
  11782. },
  11783. /**
  11784. * Sets up event handlers to call the passed functions when the mouse is moved into and out of the Element.
  11785. * @param {Function} overFn The function to call when the mouse enters the Element.
  11786. * @param {Function} outFn The function to call when the mouse leaves the Element.
  11787. * @param {Object} scope (optional) The scope (`this` reference) in which the functions are executed. Defaults
  11788. * to the Element's DOM element.
  11789. * @param {Object} options (optional) Options for the listener. See {@link Ext.util.Observable#addListener the
  11790. * options parameter}.
  11791. * @return {Ext.Element} this
  11792. */
  11793. hover: function(overFn, outFn, scope, options) {
  11794. var me = this;
  11795. me.on('mouseenter', overFn, scope || me.dom, options);
  11796. me.on('mouseleave', outFn, scope || me.dom, options);
  11797. return me;
  11798. },
  11799. /**
  11800. * Returns true if this element is an ancestor of the passed element
  11801. * @param {HTMLElement/String} el The element to check
  11802. * @return {Boolean} True if this element is an ancestor of el, else false
  11803. */
  11804. contains: function(el) {
  11805. return ! el ? false: Ext.Element.isAncestor(this.dom, el.dom ? el.dom: el);
  11806. },
  11807. /**
  11808. * Returns the value of a namespaced attribute from the element's underlying DOM node.
  11809. * @param {String} namespace The namespace in which to look for the attribute
  11810. * @param {String} name The attribute name
  11811. * @return {String} The attribute value
  11812. */
  11813. getAttributeNS: function(ns, name) {
  11814. return this.getAttribute(name, ns);
  11815. },
  11816. /**
  11817. * Returns the value of an attribute from the element's underlying DOM node.
  11818. * @param {String} name The attribute name
  11819. * @param {String} namespace (optional) The namespace in which to look for the attribute
  11820. * @return {String} The attribute value
  11821. * @method
  11822. */
  11823. getAttribute: (Ext.isIE && !(Ext.isIE9 && document.documentMode === 9)) ?
  11824. function(name, ns) {
  11825. var d = this.dom,
  11826. type;
  11827. if(ns) {
  11828. type = typeof d[ns + ":" + name];
  11829. if (type != 'undefined' && type != 'unknown') {
  11830. return d[ns + ":" + name] || null;
  11831. }
  11832. return null;
  11833. }
  11834. if (name === "for") {
  11835. name = "htmlFor";
  11836. }
  11837. return d[name] || null;
  11838. }: function(name, ns) {
  11839. var d = this.dom;
  11840. if (ns) {
  11841. return d.getAttributeNS(ns, name) || d.getAttribute(ns + ":" + name);
  11842. }
  11843. return d.getAttribute(name) || d[name] || null;
  11844. },
  11845. /**
  11846. * Update the innerHTML of this element
  11847. * @param {String} html The new HTML
  11848. * @return {Ext.Element} this
  11849. */
  11850. update: function(html) {
  11851. if (this.dom) {
  11852. this.dom.innerHTML = html;
  11853. }
  11854. return this;
  11855. }
  11856. };
  11857. var ep = El.prototype;
  11858. El.addMethods = function(o) {
  11859. Ext.apply(ep, o);
  11860. };
  11861. /**
  11862. * @method
  11863. * @alias Ext.Element#addListener
  11864. * Shorthand for {@link #addListener}.
  11865. */
  11866. ep.on = ep.addListener;
  11867. /**
  11868. * @method
  11869. * @alias Ext.Element#removeListener
  11870. * Shorthand for {@link #removeListener}.
  11871. */
  11872. ep.un = ep.removeListener;
  11873. /**
  11874. * @method
  11875. * @alias Ext.Element#removeAllListeners
  11876. * Alias for {@link #removeAllListeners}.
  11877. */
  11878. ep.clearListeners = ep.removeAllListeners;
  11879. /**
  11880. * @method destroy
  11881. * @member Ext.Element
  11882. * Removes this element's dom reference. Note that event and cache removal is handled at {@link Ext#removeNode
  11883. * Ext.removeNode}. Alias to {@link #remove}.
  11884. */
  11885. ep.destroy = ep.remove;
  11886. /**
  11887. * @property {Boolean} autoBoxAdjust
  11888. * true to automatically adjust width and height settings for box-model issues (default to true)
  11889. */
  11890. ep.autoBoxAdjust = true;
  11891. // private
  11892. var unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i,
  11893. docEl;
  11894. /**
  11895. * Retrieves Ext.Element objects. {@link Ext#get} is an alias for {@link Ext.Element#get}.
  11896. *
  11897. * **This method does not retrieve {@link Ext.Component Component}s.** This method retrieves Ext.Element
  11898. * objects which encapsulate DOM elements. To retrieve a Component by its ID, use {@link Ext.ComponentManager#get}.
  11899. *
  11900. * Uses simple caching to consistently return the same object. Automatically fixes if an object was recreated with
  11901. * the same id via AJAX or DOM.
  11902. *
  11903. * @param {String/HTMLElement/Ext.Element} el The id of the node, a DOM Node or an existing Element.
  11904. * @return {Ext.Element} The Element object (or null if no matching element was found)
  11905. * @static
  11906. */
  11907. El.get = function(el) {
  11908. var ex,
  11909. elm,
  11910. id;
  11911. if (!el) {
  11912. return null;
  11913. }
  11914. if (typeof el == "string") {
  11915. // element id
  11916. if (! (elm = DOC.getElementById(el))) {
  11917. return null;
  11918. }
  11919. if (EC[el] && EC[el].el) {
  11920. ex = EC[el].el;
  11921. ex.dom = elm;
  11922. } else {
  11923. ex = El.addToCache(new El(elm));
  11924. }
  11925. return ex;
  11926. } else if (el.tagName) {
  11927. // dom element
  11928. if (! (id = el.id)) {
  11929. id = Ext.id(el);
  11930. }
  11931. if (EC[id] && EC[id].el) {
  11932. ex = EC[id].el;
  11933. ex.dom = el;
  11934. } else {
  11935. ex = El.addToCache(new El(el));
  11936. }
  11937. return ex;
  11938. } else if (el instanceof El) {
  11939. if (el != docEl) {
  11940. // refresh dom element in case no longer valid,
  11941. // catch case where it hasn't been appended
  11942. // If an el instance is passed, don't pass to getElementById without some kind of id
  11943. if (Ext.isIE && (el.id == undefined || el.id == '')) {
  11944. el.dom = el.dom;
  11945. } else {
  11946. el.dom = DOC.getElementById(el.id) || el.dom;
  11947. }
  11948. }
  11949. return el;
  11950. } else if (el.isComposite) {
  11951. return el;
  11952. } else if (Ext.isArray(el)) {
  11953. return El.select(el);
  11954. } else if (el == DOC) {
  11955. // create a bogus element object representing the document object
  11956. if (!docEl) {
  11957. var f = function() {};
  11958. f.prototype = El.prototype;
  11959. docEl = new f();
  11960. docEl.dom = DOC;
  11961. }
  11962. return docEl;
  11963. }
  11964. return null;
  11965. };
  11966. /**
  11967. * Retrieves Ext.Element objects like {@link Ext#get} but is optimized for sub-elements.
  11968. * This is helpful for performance, because in IE (prior to IE 9), `getElementById` uses
  11969. * an non-optimized search. In those browsers, starting the search for an element with a
  11970. * matching ID at a parent of that element will greatly speed up the process.
  11971. *
  11972. * Unlike {@link Ext#get}, this method only accepts ID's. If the ID is not a child of
  11973. * this element, it will still be found if it exists in the document, but will be slower
  11974. * than calling {@link Ext#get} directly.
  11975. *
  11976. * @param {String} id The id of the element to get.
  11977. * @return {Ext.Element} The Element object (or null if no matching element was found)
  11978. * @member Ext.Element
  11979. * @method getById
  11980. * @markdown
  11981. */
  11982. ep.getById = (!Ext.isIE6 && !Ext.isIE7 && !Ext.isIE8) ? El.get :
  11983. function (id) {
  11984. var dom = this.dom,
  11985. cached, el, ret;
  11986. if (dom) {
  11987. el = dom.all[id];
  11988. if (el) {
  11989. // calling El.get here is a real hit (2x slower) because it has to
  11990. // redetermine that we are giving it a dom el.
  11991. cached = EC[id];
  11992. if (cached && cached.el) {
  11993. ret = cached.el;
  11994. ret.dom = el;
  11995. } else {
  11996. ret = El.addToCache(new El(el));
  11997. }
  11998. return ret;
  11999. }
  12000. }
  12001. return El.get(id);
  12002. };
  12003. El.addToCache = function(el, id) {
  12004. if (el) {
  12005. id = id || el.id;
  12006. EC[id] = {
  12007. el: el,
  12008. data: {},
  12009. events: {}
  12010. };
  12011. }
  12012. return el;
  12013. };
  12014. // private method for getting and setting element data
  12015. El.data = function(el, key, value) {
  12016. el = El.get(el);
  12017. if (!el) {
  12018. return null;
  12019. }
  12020. var c = EC[el.id].data;
  12021. if (arguments.length == 2) {
  12022. return c[key];
  12023. } else {
  12024. return (c[key] = value);
  12025. }
  12026. };
  12027. // private
  12028. // Garbage collection - uncache elements/purge listeners on orphaned elements
  12029. // so we don't hold a reference and cause the browser to retain them
  12030. function garbageCollect() {
  12031. if (!Ext.enableGarbageCollector) {
  12032. clearInterval(El.collectorThreadId);
  12033. } else {
  12034. var eid,
  12035. el,
  12036. d,
  12037. o;
  12038. for (eid in EC) {
  12039. if (!EC.hasOwnProperty(eid)) {
  12040. continue;
  12041. }
  12042. o = EC[eid];
  12043. if (o.skipGarbageCollection) {
  12044. continue;
  12045. }
  12046. el = o.el;
  12047. d = el.dom;
  12048. // -------------------------------------------------------
  12049. // Determining what is garbage:
  12050. // -------------------------------------------------------
  12051. // !d
  12052. // dom node is null, definitely garbage
  12053. // -------------------------------------------------------
  12054. // !d.parentNode
  12055. // no parentNode == direct orphan, definitely garbage
  12056. // -------------------------------------------------------
  12057. // !d.offsetParent && !document.getElementById(eid)
  12058. // display none elements have no offsetParent so we will
  12059. // also try to look it up by it's id. However, check
  12060. // offsetParent first so we don't do unneeded lookups.
  12061. // This enables collection of elements that are not orphans
  12062. // directly, but somewhere up the line they have an orphan
  12063. // parent.
  12064. // -------------------------------------------------------
  12065. if (!d || !d.parentNode || (!d.offsetParent && !DOC.getElementById(eid))) {
  12066. if (d && Ext.enableListenerCollection) {
  12067. Ext.EventManager.removeAll(d);
  12068. }
  12069. delete EC[eid];
  12070. }
  12071. }
  12072. // Cleanup IE Object leaks
  12073. if (Ext.isIE) {
  12074. var t = {};
  12075. for (eid in EC) {
  12076. if (!EC.hasOwnProperty(eid)) {
  12077. continue;
  12078. }
  12079. t[eid] = EC[eid];
  12080. }
  12081. EC = Ext.cache = t;
  12082. }
  12083. }
  12084. }
  12085. El.collectorThreadId = setInterval(garbageCollect, 30000);
  12086. var flyFn = function() {};
  12087. flyFn.prototype = El.prototype;
  12088. // dom is optional
  12089. El.Flyweight = function(dom) {
  12090. this.dom = dom;
  12091. };
  12092. El.Flyweight.prototype = new flyFn();
  12093. El.Flyweight.prototype.isFlyweight = true;
  12094. El._flyweights = {};
  12095. /**
  12096. * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference
  12097. * to this element - the dom node can be overwritten by other code. {@link Ext#fly} is alias for
  12098. * {@link Ext.Element#fly}.
  12099. *
  12100. * Use this to make one-time references to DOM elements which are not going to be accessed again either by
  12101. * application code, or by Ext's classes. If accessing an element which will be processed regularly, then {@link
  12102. * Ext#get Ext.get} will be more appropriate to take advantage of the caching provided by the Ext.Element
  12103. * class.
  12104. *
  12105. * @param {String/HTMLElement} el The dom node or id
  12106. * @param {String} named (optional) Allows for creation of named reusable flyweights to prevent conflicts (e.g.
  12107. * internally Ext uses "_global")
  12108. * @return {Ext.Element} The shared Element object (or null if no matching element was found)
  12109. * @static
  12110. */
  12111. El.fly = function(el, named) {
  12112. var ret = null;
  12113. named = named || '_global';
  12114. el = Ext.getDom(el);
  12115. if (el) {
  12116. (El._flyweights[named] = El._flyweights[named] || new El.Flyweight()).dom = el;
  12117. ret = El._flyweights[named];
  12118. }
  12119. return ret;
  12120. };
  12121. /**
  12122. * @member Ext
  12123. * @method get
  12124. * @alias Ext.Element#get
  12125. */
  12126. Ext.get = El.get;
  12127. /**
  12128. * @member Ext
  12129. * @method fly
  12130. * @alias Ext.Element#fly
  12131. */
  12132. Ext.fly = El.fly;
  12133. // speedy lookup for elements never to box adjust
  12134. var noBoxAdjust = Ext.isStrict ? {
  12135. select: 1
  12136. }: {
  12137. input: 1,
  12138. select: 1,
  12139. textarea: 1
  12140. };
  12141. if (Ext.isIE || Ext.isGecko) {
  12142. noBoxAdjust['button'] = 1;
  12143. }
  12144. })();
  12145. /**
  12146. * @class Ext.Element
  12147. */
  12148. Ext.Element.addMethods({
  12149. /**
  12150. * Looks at this node and then at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
  12151. * @param {String} selector The simple selector to test
  12152. * @param {Number/String/HTMLElement/Ext.Element} maxDepth (optional)
  12153. * The max depth to search as a number or element (defaults to 50 || document.body)
  12154. * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
  12155. * @return {HTMLElement} The matching DOM node (or null if no match was found)
  12156. */
  12157. findParent : function(simpleSelector, maxDepth, returnEl) {
  12158. var p = this.dom,
  12159. b = document.body,
  12160. depth = 0,
  12161. stopEl;
  12162. maxDepth = maxDepth || 50;
  12163. if (isNaN(maxDepth)) {
  12164. stopEl = Ext.getDom(maxDepth);
  12165. maxDepth = Number.MAX_VALUE;
  12166. }
  12167. while (p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl) {
  12168. if (Ext.DomQuery.is(p, simpleSelector)) {
  12169. return returnEl ? Ext.get(p) : p;
  12170. }
  12171. depth++;
  12172. p = p.parentNode;
  12173. }
  12174. return null;
  12175. },
  12176. /**
  12177. * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
  12178. * @param {String} selector The simple selector to test
  12179. * @param {Number/String/HTMLElement/Ext.Element} maxDepth (optional)
  12180. * The max depth to search as a number or element (defaults to 10 || document.body)
  12181. * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
  12182. * @return {HTMLElement} The matching DOM node (or null if no match was found)
  12183. */
  12184. findParentNode : function(simpleSelector, maxDepth, returnEl) {
  12185. var p = Ext.fly(this.dom.parentNode, '_internal');
  12186. return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
  12187. },
  12188. /**
  12189. * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
  12190. * This is a shortcut for findParentNode() that always returns an Ext.Element.
  12191. * @param {String} selector The simple selector to test
  12192. * @param {Number/String/HTMLElement/Ext.Element} maxDepth (optional)
  12193. * The max depth to search as a number or element (defaults to 10 || document.body)
  12194. * @return {Ext.Element} The matching DOM node (or null if no match was found)
  12195. */
  12196. up : function(simpleSelector, maxDepth) {
  12197. return this.findParentNode(simpleSelector, maxDepth, true);
  12198. },
  12199. /**
  12200. * Creates a {@link Ext.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
  12201. * @param {String} selector The CSS selector
  12202. * @return {Ext.CompositeElement/Ext.CompositeElement} The composite element
  12203. */
  12204. select : function(selector) {
  12205. return Ext.Element.select(selector, false, this.dom);
  12206. },
  12207. /**
  12208. * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
  12209. * @param {String} selector The CSS selector
  12210. * @return {HTMLElement[]} An array of the matched nodes
  12211. */
  12212. query : function(selector) {
  12213. return Ext.DomQuery.select(selector, this.dom);
  12214. },
  12215. /**
  12216. * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
  12217. * @param {String} selector The CSS selector
  12218. * @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.Element (defaults to false)
  12219. * @return {HTMLElement/Ext.Element} The child Ext.Element (or DOM node if returnDom = true)
  12220. */
  12221. down : function(selector, returnDom) {
  12222. var n = Ext.DomQuery.selectNode(selector, this.dom);
  12223. return returnDom ? n : Ext.get(n);
  12224. },
  12225. /**
  12226. * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
  12227. * @param {String} selector The CSS selector
  12228. * @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.Element (defaults to false)
  12229. * @return {HTMLElement/Ext.Element} The child Ext.Element (or DOM node if returnDom = true)
  12230. */
  12231. child : function(selector, returnDom) {
  12232. var node,
  12233. me = this,
  12234. id;
  12235. id = Ext.get(me).id;
  12236. // Escape . or :
  12237. id = id.replace(/[\.:]/g, "\\$0");
  12238. node = Ext.DomQuery.selectNode('#' + id + " > " + selector, me.dom);
  12239. return returnDom ? node : Ext.get(node);
  12240. },
  12241. /**
  12242. * Gets the parent node for this element, optionally chaining up trying to match a selector
  12243. * @param {String} selector (optional) Find a parent node that matches the passed simple selector
  12244. * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
  12245. * @return {Ext.Element/HTMLElement} The parent node or null
  12246. */
  12247. parent : function(selector, returnDom) {
  12248. return this.matchNode('parentNode', 'parentNode', selector, returnDom);
  12249. },
  12250. /**
  12251. * Gets the next sibling, skipping text nodes
  12252. * @param {String} selector (optional) Find the next sibling that matches the passed simple selector
  12253. * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
  12254. * @return {Ext.Element/HTMLElement} The next sibling or null
  12255. */
  12256. next : function(selector, returnDom) {
  12257. return this.matchNode('nextSibling', 'nextSibling', selector, returnDom);
  12258. },
  12259. /**
  12260. * Gets the previous sibling, skipping text nodes
  12261. * @param {String} selector (optional) Find the previous sibling that matches the passed simple selector
  12262. * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
  12263. * @return {Ext.Element/HTMLElement} The previous sibling or null
  12264. */
  12265. prev : function(selector, returnDom) {
  12266. return this.matchNode('previousSibling', 'previousSibling', selector, returnDom);
  12267. },
  12268. /**
  12269. * Gets the first child, skipping text nodes
  12270. * @param {String} selector (optional) Find the next sibling that matches the passed simple selector
  12271. * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
  12272. * @return {Ext.Element/HTMLElement} The first child or null
  12273. */
  12274. first : function(selector, returnDom) {
  12275. return this.matchNode('nextSibling', 'firstChild', selector, returnDom);
  12276. },
  12277. /**
  12278. * Gets the last child, skipping text nodes
  12279. * @param {String} selector (optional) Find the previous sibling that matches the passed simple selector
  12280. * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
  12281. * @return {Ext.Element/HTMLElement} The last child or null
  12282. */
  12283. last : function(selector, returnDom) {
  12284. return this.matchNode('previousSibling', 'lastChild', selector, returnDom);
  12285. },
  12286. matchNode : function(dir, start, selector, returnDom) {
  12287. if (!this.dom) {
  12288. return null;
  12289. }
  12290. var n = this.dom[start];
  12291. while (n) {
  12292. if (n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))) {
  12293. return !returnDom ? Ext.get(n) : n;
  12294. }
  12295. n = n[dir];
  12296. }
  12297. return null;
  12298. }
  12299. });
  12300. /**
  12301. * @class Ext.Element
  12302. */
  12303. Ext.Element.addMethods({
  12304. /**
  12305. * Appends the passed element(s) to this element
  12306. * @param {String/HTMLElement/Ext.Element} el
  12307. * The id of the node, a DOM Node or an existing Element.
  12308. * @return {Ext.Element} this
  12309. */
  12310. appendChild : function(el) {
  12311. return Ext.get(el).appendTo(this);
  12312. },
  12313. /**
  12314. * Appends this element to the passed element
  12315. * @param {String/HTMLElement/Ext.Element} el The new parent element.
  12316. * The id of the node, a DOM Node or an existing Element.
  12317. * @return {Ext.Element} this
  12318. */
  12319. appendTo : function(el) {
  12320. Ext.getDom(el).appendChild(this.dom);
  12321. return this;
  12322. },
  12323. /**
  12324. * Inserts this element before the passed element in the DOM
  12325. * @param {String/HTMLElement/Ext.Element} el The element before which this element will be inserted.
  12326. * The id of the node, a DOM Node or an existing Element.
  12327. * @return {Ext.Element} this
  12328. */
  12329. insertBefore : function(el) {
  12330. el = Ext.getDom(el);
  12331. el.parentNode.insertBefore(this.dom, el);
  12332. return this;
  12333. },
  12334. /**
  12335. * Inserts this element after the passed element in the DOM
  12336. * @param {String/HTMLElement/Ext.Element} el The element to insert after.
  12337. * The id of the node, a DOM Node or an existing Element.
  12338. * @return {Ext.Element} this
  12339. */
  12340. insertAfter : function(el) {
  12341. el = Ext.getDom(el);
  12342. el.parentNode.insertBefore(this.dom, el.nextSibling);
  12343. return this;
  12344. },
  12345. /**
  12346. * Inserts (or creates) an element (or DomHelper config) as the first child of this element
  12347. * @param {String/HTMLElement/Ext.Element/Object} el The id or element to insert or a DomHelper config
  12348. * to create and insert
  12349. * @return {Ext.Element} The new child
  12350. */
  12351. insertFirst : function(el, returnDom) {
  12352. el = el || {};
  12353. if (el.nodeType || el.dom || typeof el == 'string') { // element
  12354. el = Ext.getDom(el);
  12355. this.dom.insertBefore(el, this.dom.firstChild);
  12356. return !returnDom ? Ext.get(el) : el;
  12357. }
  12358. else { // dh config
  12359. return this.createChild(el, this.dom.firstChild, returnDom);
  12360. }
  12361. },
  12362. /**
  12363. * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
  12364. * @param {String/HTMLElement/Ext.Element/Object/Array} el The id, element to insert or a DomHelper config
  12365. * to create and insert *or* an array of any of those.
  12366. * @param {String} where (optional) 'before' or 'after' defaults to before
  12367. * @param {Boolean} returnDom (optional) True to return the .;ll;l,raw DOM element instead of Ext.Element
  12368. * @return {Ext.Element} The inserted Element. If an array is passed, the last inserted element is returned.
  12369. */
  12370. insertSibling: function(el, where, returnDom){
  12371. var me = this, rt,
  12372. isAfter = (where || 'before').toLowerCase() == 'after',
  12373. insertEl;
  12374. if(Ext.isArray(el)){
  12375. insertEl = me;
  12376. Ext.each(el, function(e) {
  12377. rt = Ext.fly(insertEl, '_internal').insertSibling(e, where, returnDom);
  12378. if(isAfter){
  12379. insertEl = rt;
  12380. }
  12381. });
  12382. return rt;
  12383. }
  12384. el = el || {};
  12385. if(el.nodeType || el.dom){
  12386. rt = me.dom.parentNode.insertBefore(Ext.getDom(el), isAfter ? me.dom.nextSibling : me.dom);
  12387. if (!returnDom) {
  12388. rt = Ext.get(rt);
  12389. }
  12390. }else{
  12391. if (isAfter && !me.dom.nextSibling) {
  12392. rt = Ext.DomHelper.append(me.dom.parentNode, el, !returnDom);
  12393. } else {
  12394. rt = Ext.DomHelper[isAfter ? 'insertAfter' : 'insertBefore'](me.dom, el, !returnDom);
  12395. }
  12396. }
  12397. return rt;
  12398. },
  12399. /**
  12400. * Replaces the passed element with this element
  12401. * @param {String/HTMLElement/Ext.Element} el The element to replace.
  12402. * The id of the node, a DOM Node or an existing Element.
  12403. * @return {Ext.Element} this
  12404. */
  12405. replace : function(el) {
  12406. el = Ext.get(el);
  12407. this.insertBefore(el);
  12408. el.remove();
  12409. return this;
  12410. },
  12411. /**
  12412. * Replaces this element with the passed element
  12413. * @param {String/HTMLElement/Ext.Element/Object} el The new element (id of the node, a DOM Node
  12414. * or an existing Element) or a DomHelper config of an element to create
  12415. * @return {Ext.Element} this
  12416. */
  12417. replaceWith: function(el){
  12418. var me = this;
  12419. if(el.nodeType || el.dom || typeof el == 'string'){
  12420. el = Ext.get(el);
  12421. me.dom.parentNode.insertBefore(el, me.dom);
  12422. }else{
  12423. el = Ext.DomHelper.insertBefore(me.dom, el);
  12424. }
  12425. delete Ext.cache[me.id];
  12426. Ext.removeNode(me.dom);
  12427. me.id = Ext.id(me.dom = el);
  12428. Ext.Element.addToCache(me.isFlyweight ? new Ext.Element(me.dom) : me);
  12429. return me;
  12430. },
  12431. /**
  12432. * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
  12433. * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
  12434. * automatically generated with the specified attributes.
  12435. * @param {HTMLElement} insertBefore (optional) a child element of this element
  12436. * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
  12437. * @return {Ext.Element} The new child element
  12438. */
  12439. createChild : function(config, insertBefore, returnDom) {
  12440. config = config || {tag:'div'};
  12441. if (insertBefore) {
  12442. return Ext.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
  12443. }
  12444. else {
  12445. return Ext.DomHelper[!this.dom.firstChild ? 'insertFirst' : 'append'](this.dom, config, returnDom !== true);
  12446. }
  12447. },
  12448. /**
  12449. * Creates and wraps this element with another element
  12450. * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
  12451. * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Ext.Element
  12452. * @return {HTMLElement/Ext.Element} The newly created wrapper element
  12453. */
  12454. wrap : function(config, returnDom) {
  12455. var newEl = Ext.DomHelper.insertBefore(this.dom, config || {tag: "div"}, !returnDom),
  12456. d = newEl.dom || newEl;
  12457. d.appendChild(this.dom);
  12458. return newEl;
  12459. },
  12460. /**
  12461. * Inserts an html fragment into this element
  12462. * @param {String} where Where to insert the html in relation to this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
  12463. * See {@link Ext.DomHelper#insertHtml} for details.
  12464. * @param {String} html The HTML fragment
  12465. * @param {Boolean} returnEl (optional) True to return an Ext.Element (defaults to false)
  12466. * @return {HTMLElement/Ext.Element} The inserted node (or nearest related if more than 1 inserted)
  12467. */
  12468. insertHtml : function(where, html, returnEl) {
  12469. var el = Ext.DomHelper.insertHtml(where, this.dom, html);
  12470. return returnEl ? Ext.get(el) : el;
  12471. }
  12472. });
  12473. /**
  12474. * @class Ext.Element
  12475. */
  12476. (function(){
  12477. // local style camelizing for speed
  12478. var ELEMENT = Ext.Element,
  12479. supports = Ext.supports,
  12480. view = document.defaultView,
  12481. opacityRe = /alpha\(opacity=(.*)\)/i,
  12482. trimRe = /^\s+|\s+$/g,
  12483. spacesRe = /\s+/,
  12484. wordsRe = /\w/g,
  12485. adjustDirect2DTableRe = /table-row|table-.*-group/,
  12486. INTERNAL = '_internal',
  12487. PADDING = 'padding',
  12488. MARGIN = 'margin',
  12489. BORDER = 'border',
  12490. LEFT = '-left',
  12491. RIGHT = '-right',
  12492. TOP = '-top',
  12493. BOTTOM = '-bottom',
  12494. WIDTH = '-width',
  12495. MATH = Math,
  12496. HIDDEN = 'hidden',
  12497. ISCLIPPED = 'isClipped',
  12498. OVERFLOW = 'overflow',
  12499. OVERFLOWX = 'overflow-x',
  12500. OVERFLOWY = 'overflow-y',
  12501. ORIGINALCLIP = 'originalClip',
  12502. // special markup used throughout Ext when box wrapping elements
  12503. borders = {l: BORDER + LEFT + WIDTH, r: BORDER + RIGHT + WIDTH, t: BORDER + TOP + WIDTH, b: BORDER + BOTTOM + WIDTH},
  12504. paddings = {l: PADDING + LEFT, r: PADDING + RIGHT, t: PADDING + TOP, b: PADDING + BOTTOM},
  12505. margins = {l: MARGIN + LEFT, r: MARGIN + RIGHT, t: MARGIN + TOP, b: MARGIN + BOTTOM},
  12506. data = ELEMENT.data;
  12507. ELEMENT.boxMarkup = '<div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div><div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div><div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>';
  12508. // These property values are read from the parentNode if they cannot be read
  12509. // from the child:
  12510. ELEMENT.inheritedProps = {
  12511. fontSize: 1,
  12512. fontStyle: 1,
  12513. opacity: 1
  12514. };
  12515. Ext.override(ELEMENT, {
  12516. /**
  12517. * TODO: Look at this
  12518. */
  12519. // private ==> used by Fx
  12520. adjustWidth : function(width) {
  12521. var me = this,
  12522. isNum = (typeof width == 'number');
  12523. if(isNum && me.autoBoxAdjust && !me.isBorderBox()){
  12524. width -= (me.getBorderWidth("lr") + me.getPadding("lr"));
  12525. }
  12526. return (isNum && width < 0) ? 0 : width;
  12527. },
  12528. // private ==> used by Fx
  12529. adjustHeight : function(height) {
  12530. var me = this,
  12531. isNum = (typeof height == "number");
  12532. if(isNum && me.autoBoxAdjust && !me.isBorderBox()){
  12533. height -= (me.getBorderWidth("tb") + me.getPadding("tb"));
  12534. }
  12535. return (isNum && height < 0) ? 0 : height;
  12536. },
  12537. /**
  12538. * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
  12539. * @param {String/String[]} className The CSS classes to add separated by space, or an array of classes
  12540. * @return {Ext.Element} this
  12541. */
  12542. addCls : function(className){
  12543. var me = this,
  12544. cls = [],
  12545. space = ((me.dom.className.replace(trimRe, '') == '') ? "" : " "),
  12546. i, len, v;
  12547. if (className === undefined) {
  12548. return me;
  12549. }
  12550. // Separate case is for speed
  12551. if (Object.prototype.toString.call(className) !== '[object Array]') {
  12552. if (typeof className === 'string') {
  12553. className = className.replace(trimRe, '').split(spacesRe);
  12554. if (className.length === 1) {
  12555. className = className[0];
  12556. if (!me.hasCls(className)) {
  12557. me.dom.className += space + className;
  12558. }
  12559. } else {
  12560. this.addCls(className);
  12561. }
  12562. }
  12563. } else {
  12564. for (i = 0, len = className.length; i < len; i++) {
  12565. v = className[i];
  12566. if (typeof v == 'string' && (' ' + me.dom.className + ' ').indexOf(' ' + v + ' ') == -1) {
  12567. cls.push(v);
  12568. }
  12569. }
  12570. if (cls.length) {
  12571. me.dom.className += space + cls.join(" ");
  12572. }
  12573. }
  12574. return me;
  12575. },
  12576. /**
  12577. * Removes one or more CSS classes from the element.
  12578. * @param {String/String[]} className The CSS classes to remove separated by space, or an array of classes
  12579. * @return {Ext.Element} this
  12580. */
  12581. removeCls : function(className){
  12582. var me = this,
  12583. i, idx, len, cls, elClasses;
  12584. if (className === undefined) {
  12585. return me;
  12586. }
  12587. if (Object.prototype.toString.call(className) !== '[object Array]') {
  12588. className = className.replace(trimRe, '').split(spacesRe);
  12589. }
  12590. if (me.dom && me.dom.className) {
  12591. elClasses = me.dom.className.replace(trimRe, '').split(spacesRe);
  12592. for (i = 0, len = className.length; i < len; i++) {
  12593. cls = className[i];
  12594. if (typeof cls == 'string') {
  12595. cls = cls.replace(trimRe, '');
  12596. idx = Ext.Array.indexOf(elClasses, cls);
  12597. if (idx != -1) {
  12598. Ext.Array.erase(elClasses, idx, 1);
  12599. }
  12600. }
  12601. }
  12602. me.dom.className = elClasses.join(" ");
  12603. }
  12604. return me;
  12605. },
  12606. /**
  12607. * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
  12608. * @param {String/String[]} className The CSS class to add, or an array of classes
  12609. * @return {Ext.Element} this
  12610. */
  12611. radioCls : function(className){
  12612. var cn = this.dom.parentNode.childNodes,
  12613. v, i, len;
  12614. className = Ext.isArray(className) ? className : [className];
  12615. for (i = 0, len = cn.length; i < len; i++) {
  12616. v = cn[i];
  12617. if (v && v.nodeType == 1) {
  12618. Ext.fly(v, '_internal').removeCls(className);
  12619. }
  12620. }
  12621. return this.addCls(className);
  12622. },
  12623. /**
  12624. * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
  12625. * @param {String} className The CSS class to toggle
  12626. * @return {Ext.Element} this
  12627. * @method
  12628. */
  12629. toggleCls : Ext.supports.ClassList ?
  12630. function(className) {
  12631. this.dom.classList.toggle(Ext.String.trim(className));
  12632. return this;
  12633. } :
  12634. function(className) {
  12635. return this.hasCls(className) ? this.removeCls(className) : this.addCls(className);
  12636. },
  12637. /**
  12638. * Checks if the specified CSS class exists on this element's DOM node.
  12639. * @param {String} className The CSS class to check for
  12640. * @return {Boolean} True if the class exists, else false
  12641. * @method
  12642. */
  12643. hasCls : Ext.supports.ClassList ?
  12644. function(className) {
  12645. if (!className) {
  12646. return false;
  12647. }
  12648. className = className.split(spacesRe);
  12649. var ln = className.length,
  12650. i = 0;
  12651. for (; i < ln; i++) {
  12652. if (className[i] && this.dom.classList.contains(className[i])) {
  12653. return true;
  12654. }
  12655. }
  12656. return false;
  12657. } :
  12658. function(className){
  12659. return className && (' ' + this.dom.className + ' ').indexOf(' ' + className + ' ') != -1;
  12660. },
  12661. /**
  12662. * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
  12663. * @param {String} oldClassName The CSS class to replace
  12664. * @param {String} newClassName The replacement CSS class
  12665. * @return {Ext.Element} this
  12666. */
  12667. replaceCls : function(oldClassName, newClassName){
  12668. return this.removeCls(oldClassName).addCls(newClassName);
  12669. },
  12670. isStyle : function(style, val) {
  12671. return this.getStyle(style) == val;
  12672. },
  12673. /**
  12674. * Normalizes currentStyle and computedStyle.
  12675. * @param {String} property The style property whose value is returned.
  12676. * @return {String} The current value of the style property for this element.
  12677. * @method
  12678. */
  12679. getStyle : function() {
  12680. return view && view.getComputedStyle ?
  12681. function(prop){
  12682. var el = this.dom,
  12683. v, cs, out, display, cleaner;
  12684. if(el == document){
  12685. return null;
  12686. }
  12687. prop = ELEMENT.normalize(prop);
  12688. out = (v = el.style[prop]) ? v :
  12689. (cs = view.getComputedStyle(el, "")) ? cs[prop] : null;
  12690. // Ignore cases when the margin is correctly reported as 0, the bug only shows
  12691. // numbers larger.
  12692. if(prop == 'marginRight' && out != '0px' && !supports.RightMargin){
  12693. cleaner = ELEMENT.getRightMarginFixCleaner(el);
  12694. display = this.getStyle('display');
  12695. el.style.display = 'inline-block';
  12696. out = view.getComputedStyle(el, '').marginRight;
  12697. el.style.display = display;
  12698. cleaner();
  12699. }
  12700. if(prop == 'backgroundColor' && out == 'rgba(0, 0, 0, 0)' && !supports.TransparentColor){
  12701. out = 'transparent';
  12702. }
  12703. return out;
  12704. } :
  12705. function (prop) {
  12706. var el = this.dom,
  12707. m, cs;
  12708. if (el == document) {
  12709. return null;
  12710. }
  12711. prop = ELEMENT.normalize(prop);
  12712. do {
  12713. if (prop == 'opacity') {
  12714. if (el.style.filter.match) {
  12715. m = el.style.filter.match(opacityRe);
  12716. if(m){
  12717. var fv = parseFloat(m[1]);
  12718. if(!isNaN(fv)){
  12719. return fv ? fv / 100 : 0;
  12720. }
  12721. }
  12722. }
  12723. return 1;
  12724. }
  12725. // the try statement does have a cost, so we avoid it unless we are
  12726. // on IE6
  12727. if (!Ext.isIE6) {
  12728. return el.style[prop] || ((cs = el.currentStyle) ? cs[prop] : null);
  12729. }
  12730. try {
  12731. return el.style[prop] || ((cs = el.currentStyle) ? cs[prop] : null);
  12732. } catch (e) {
  12733. // in some cases, IE6 will throw Invalid Argument for properties
  12734. // like fontSize (see in /examples/tabs/tabs.html).
  12735. }
  12736. if (!ELEMENT.inheritedProps[prop]) {
  12737. break;
  12738. }
  12739. el = el.parentNode;
  12740. // this is _not_ perfect, but we can only hope that the style we
  12741. // need is inherited from a parentNode. If not and since IE won't
  12742. // give us the info we need, we are never going to be 100% right.
  12743. } while (el);
  12744. return null;
  12745. }
  12746. }(),
  12747. /**
  12748. * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
  12749. * are convert to standard 6 digit hex color.
  12750. * @param {String} attr The css attribute
  12751. * @param {String} defaultValue The default value to use when a valid color isn't found
  12752. * @param {String} prefix (optional) defaults to #. Use an empty string when working with
  12753. * color anims.
  12754. */
  12755. getColor : function(attr, defaultValue, prefix){
  12756. var v = this.getStyle(attr),
  12757. color = prefix || prefix === '' ? prefix : '#',
  12758. h;
  12759. if(!v || (/transparent|inherit/.test(v))) {
  12760. return defaultValue;
  12761. }
  12762. if(/^r/.test(v)){
  12763. Ext.each(v.slice(4, v.length -1).split(','), function(s){
  12764. h = parseInt(s, 10);
  12765. color += (h < 16 ? '0' : '') + h.toString(16);
  12766. });
  12767. }else{
  12768. v = v.replace('#', '');
  12769. color += v.length == 3 ? v.replace(/^(\w)(\w)(\w)$/, '$1$1$2$2$3$3') : v;
  12770. }
  12771. return(color.length > 5 ? color.toLowerCase() : defaultValue);
  12772. },
  12773. /**
  12774. * Wrapper for setting style properties, also takes single object parameter of multiple styles.
  12775. * @param {String/Object} property The style property to be set, or an object of multiple styles.
  12776. * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
  12777. * @return {Ext.Element} this
  12778. */
  12779. setStyle : function(prop, value){
  12780. var me = this,
  12781. tmp, style;
  12782. if (!me.dom) {
  12783. return me;
  12784. }
  12785. if (typeof prop === 'string') {
  12786. tmp = {};
  12787. tmp[prop] = value;
  12788. prop = tmp;
  12789. }
  12790. for (style in prop) {
  12791. if (prop.hasOwnProperty(style)) {
  12792. value = Ext.value(prop[style], '');
  12793. if (style == 'opacity') {
  12794. me.setOpacity(value);
  12795. }
  12796. else {
  12797. me.dom.style[ELEMENT.normalize(style)] = value;
  12798. }
  12799. }
  12800. }
  12801. return me;
  12802. },
  12803. /**
  12804. * Set the opacity of the element
  12805. * @param {Number} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
  12806. * @param {Boolean/Object} animate (optional) a standard Element animation config object or <tt>true</tt> for
  12807. * the default animation (<tt>{duration: .35, easing: 'easeIn'}</tt>)
  12808. * @return {Ext.Element} this
  12809. */
  12810. setOpacity: function(opacity, animate) {
  12811. var me = this,
  12812. dom = me.dom,
  12813. val,
  12814. style;
  12815. if (!me.dom) {
  12816. return me;
  12817. }
  12818. style = me.dom.style;
  12819. if (!animate || !me.anim) {
  12820. if (!Ext.supports.Opacity) {
  12821. opacity = opacity < 1 ? 'alpha(opacity=' + opacity * 100 + ')': '';
  12822. val = style.filter.replace(opacityRe, '').replace(trimRe, '');
  12823. style.zoom = 1;
  12824. style.filter = val + (val.length > 0 ? ' ': '') + opacity;
  12825. }
  12826. else {
  12827. style.opacity = opacity;
  12828. }
  12829. }
  12830. else {
  12831. if (!Ext.isObject(animate)) {
  12832. animate = {
  12833. duration: 350,
  12834. easing: 'ease-in'
  12835. };
  12836. }
  12837. me.animate(Ext.applyIf({
  12838. to: {
  12839. opacity: opacity
  12840. }
  12841. },
  12842. animate));
  12843. }
  12844. return me;
  12845. },
  12846. /**
  12847. * Clears any opacity settings from this element. Required in some cases for IE.
  12848. * @return {Ext.Element} this
  12849. */
  12850. clearOpacity : function(){
  12851. var style = this.dom.style;
  12852. if(!Ext.supports.Opacity){
  12853. if(!Ext.isEmpty(style.filter)){
  12854. style.filter = style.filter.replace(opacityRe, '').replace(trimRe, '');
  12855. }
  12856. }else{
  12857. style.opacity = style['-moz-opacity'] = style['-khtml-opacity'] = '';
  12858. }
  12859. return this;
  12860. },
  12861. /**
  12862. * @private
  12863. * Returns 1 if the browser returns the subpixel dimension rounded to the lowest pixel.
  12864. * @return {Number} 0 or 1
  12865. */
  12866. adjustDirect2DDimension: function(dimension) {
  12867. var me = this,
  12868. dom = me.dom,
  12869. display = me.getStyle('display'),
  12870. inlineDisplay = dom.style['display'],
  12871. inlinePosition = dom.style['position'],
  12872. originIndex = dimension === 'width' ? 0 : 1,
  12873. floating;
  12874. if (display === 'inline') {
  12875. dom.style['display'] = 'inline-block';
  12876. }
  12877. dom.style['position'] = display.match(adjustDirect2DTableRe) ? 'absolute' : 'static';
  12878. // floating will contain digits that appears after the decimal point
  12879. // if height or width are set to auto we fallback to msTransformOrigin calculation
  12880. floating = (parseFloat(me.getStyle(dimension)) || parseFloat(dom.currentStyle.msTransformOrigin.split(' ')[originIndex]) * 2) % 1;
  12881. dom.style['position'] = inlinePosition;
  12882. if (display === 'inline') {
  12883. dom.style['display'] = inlineDisplay;
  12884. }
  12885. return floating;
  12886. },
  12887. /**
  12888. * Returns the offset height of the element
  12889. * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
  12890. * @return {Number} The element's height
  12891. */
  12892. getHeight: function(contentHeight, preciseHeight) {
  12893. var me = this,
  12894. dom = me.dom,
  12895. hidden = Ext.isIE && me.isStyle('display', 'none'),
  12896. height, overflow, style, floating;
  12897. // IE Quirks mode acts more like a max-size measurement unless overflow is hidden during measurement.
  12898. // We will put the overflow back to it's original value when we are done measuring.
  12899. if (Ext.isIEQuirks) {
  12900. style = dom.style;
  12901. overflow = style.overflow;
  12902. me.setStyle({ overflow: 'hidden'});
  12903. }
  12904. height = dom.offsetHeight;
  12905. height = MATH.max(height, hidden ? 0 : dom.clientHeight) || 0;
  12906. // IE9 Direct2D dimension rounding bug
  12907. if (!hidden && Ext.supports.Direct2DBug) {
  12908. floating = me.adjustDirect2DDimension('height');
  12909. if (preciseHeight) {
  12910. height += floating;
  12911. }
  12912. else if (floating > 0 && floating < 0.5) {
  12913. height++;
  12914. }
  12915. }
  12916. if (contentHeight) {
  12917. height -= (me.getBorderWidth("tb") + me.getPadding("tb"));
  12918. }
  12919. if (Ext.isIEQuirks) {
  12920. me.setStyle({ overflow: overflow});
  12921. }
  12922. if (height < 0) {
  12923. height = 0;
  12924. }
  12925. return height;
  12926. },
  12927. /**
  12928. * Returns the offset width of the element
  12929. * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
  12930. * @return {Number} The element's width
  12931. */
  12932. getWidth: function(contentWidth, preciseWidth) {
  12933. var me = this,
  12934. dom = me.dom,
  12935. hidden = Ext.isIE && me.isStyle('display', 'none'),
  12936. rect, width, overflow, style, floating, parentPosition;
  12937. // IE Quirks mode acts more like a max-size measurement unless overflow is hidden during measurement.
  12938. // We will put the overflow back to it's original value when we are done measuring.
  12939. if (Ext.isIEQuirks) {
  12940. style = dom.style;
  12941. overflow = style.overflow;
  12942. me.setStyle({overflow: 'hidden'});
  12943. }
  12944. // Fix Opera 10.5x width calculation issues
  12945. if (Ext.isOpera10_5) {
  12946. if (dom.parentNode.currentStyle.position === 'relative') {
  12947. parentPosition = dom.parentNode.style.position;
  12948. dom.parentNode.style.position = 'static';
  12949. width = dom.offsetWidth;
  12950. dom.parentNode.style.position = parentPosition;
  12951. }
  12952. width = Math.max(width || 0, dom.offsetWidth);
  12953. // Gecko will in some cases report an offsetWidth that is actually less than the width of the
  12954. // text contents, because it measures fonts with sub-pixel precision but rounds the calculated
  12955. // value down. Using getBoundingClientRect instead of offsetWidth allows us to get the precise
  12956. // subpixel measurements so we can force them to always be rounded up. See
  12957. // https://bugzilla.mozilla.org/show_bug.cgi?id=458617
  12958. } else if (Ext.supports.BoundingClientRect) {
  12959. rect = dom.getBoundingClientRect();
  12960. width = rect.right - rect.left;
  12961. width = preciseWidth ? width : Math.ceil(width);
  12962. } else {
  12963. width = dom.offsetWidth;
  12964. }
  12965. width = MATH.max(width, hidden ? 0 : dom.clientWidth) || 0;
  12966. // IE9 Direct2D dimension rounding bug
  12967. if (!hidden && Ext.supports.Direct2DBug) {
  12968. floating = me.adjustDirect2DDimension('width');
  12969. if (preciseWidth) {
  12970. width += floating;
  12971. }
  12972. else if (floating > 0 && floating < 0.5) {
  12973. width++;
  12974. }
  12975. }
  12976. if (contentWidth) {
  12977. width -= (me.getBorderWidth("lr") + me.getPadding("lr"));
  12978. }
  12979. if (Ext.isIEQuirks) {
  12980. me.setStyle({ overflow: overflow});
  12981. }
  12982. if (width < 0) {
  12983. width = 0;
  12984. }
  12985. return width;
  12986. },
  12987. /**
  12988. * Set the width of this Element.
  12989. * @param {Number/String} width The new width. This may be one of:<div class="mdetail-params"><ul>
  12990. * <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).</li>
  12991. * <li>A String used to set the CSS width style. Animation may <b>not</b> be used.
  12992. * </ul></div>
  12993. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
  12994. * @return {Ext.Element} this
  12995. */
  12996. setWidth : function(width, animate){
  12997. var me = this;
  12998. width = me.adjustWidth(width);
  12999. if (!animate || !me.anim) {
  13000. me.dom.style.width = me.addUnits(width);
  13001. }
  13002. else {
  13003. if (!Ext.isObject(animate)) {
  13004. animate = {};
  13005. }
  13006. me.animate(Ext.applyIf({
  13007. to: {
  13008. width: width
  13009. }
  13010. }, animate));
  13011. }
  13012. return me;
  13013. },
  13014. /**
  13015. * Set the height of this Element.
  13016. * <pre><code>
  13017. // change the height to 200px and animate with default configuration
  13018. Ext.fly('elementId').setHeight(200, true);
  13019. // change the height to 150px and animate with a custom configuration
  13020. Ext.fly('elId').setHeight(150, {
  13021. duration : .5, // animation will have a duration of .5 seconds
  13022. // will change the content to "finished"
  13023. callback: function(){ this.{@link #update}("finished"); }
  13024. });
  13025. * </code></pre>
  13026. * @param {Number/String} height The new height. This may be one of:<div class="mdetail-params"><ul>
  13027. * <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels.)</li>
  13028. * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
  13029. * </ul></div>
  13030. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
  13031. * @return {Ext.Element} this
  13032. */
  13033. setHeight : function(height, animate){
  13034. var me = this;
  13035. height = me.adjustHeight(height);
  13036. if (!animate || !me.anim) {
  13037. me.dom.style.height = me.addUnits(height);
  13038. }
  13039. else {
  13040. if (!Ext.isObject(animate)) {
  13041. animate = {};
  13042. }
  13043. me.animate(Ext.applyIf({
  13044. to: {
  13045. height: height
  13046. }
  13047. }, animate));
  13048. }
  13049. return me;
  13050. },
  13051. /**
  13052. * Gets the width of the border(s) for the specified side(s)
  13053. * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
  13054. * passing <tt>'lr'</tt> would get the border <b><u>l</u></b>eft width + the border <b><u>r</u></b>ight width.
  13055. * @return {Number} The width of the sides passed added together
  13056. */
  13057. getBorderWidth : function(side){
  13058. return this.addStyles(side, borders);
  13059. },
  13060. /**
  13061. * Gets the width of the padding(s) for the specified side(s)
  13062. * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
  13063. * passing <tt>'lr'</tt> would get the padding <b><u>l</u></b>eft + the padding <b><u>r</u></b>ight.
  13064. * @return {Number} The padding of the sides passed added together
  13065. */
  13066. getPadding : function(side){
  13067. return this.addStyles(side, paddings);
  13068. },
  13069. /**
  13070. * Store the current overflow setting and clip overflow on the element - use <tt>{@link #unclip}</tt> to remove
  13071. * @return {Ext.Element} this
  13072. */
  13073. clip : function(){
  13074. var me = this,
  13075. dom = me.dom;
  13076. if(!data(dom, ISCLIPPED)){
  13077. data(dom, ISCLIPPED, true);
  13078. data(dom, ORIGINALCLIP, {
  13079. o: me.getStyle(OVERFLOW),
  13080. x: me.getStyle(OVERFLOWX),
  13081. y: me.getStyle(OVERFLOWY)
  13082. });
  13083. me.setStyle(OVERFLOW, HIDDEN);
  13084. me.setStyle(OVERFLOWX, HIDDEN);
  13085. me.setStyle(OVERFLOWY, HIDDEN);
  13086. }
  13087. return me;
  13088. },
  13089. /**
  13090. * Return clipping (overflow) to original clipping before <tt>{@link #clip}</tt> was called
  13091. * @return {Ext.Element} this
  13092. */
  13093. unclip : function(){
  13094. var me = this,
  13095. dom = me.dom,
  13096. clip;
  13097. if(data(dom, ISCLIPPED)){
  13098. data(dom, ISCLIPPED, false);
  13099. clip = data(dom, ORIGINALCLIP);
  13100. if(clip.o){
  13101. me.setStyle(OVERFLOW, clip.o);
  13102. }
  13103. if(clip.x){
  13104. me.setStyle(OVERFLOWX, clip.x);
  13105. }
  13106. if(clip.y){
  13107. me.setStyle(OVERFLOWY, clip.y);
  13108. }
  13109. }
  13110. return me;
  13111. },
  13112. // private
  13113. addStyles : function(sides, styles){
  13114. var totalSize = 0,
  13115. sidesArr = sides.match(wordsRe),
  13116. i = 0,
  13117. len = sidesArr.length,
  13118. side, size;
  13119. for (; i < len; i++) {
  13120. side = sidesArr[i];
  13121. size = side && parseInt(this.getStyle(styles[side]), 10);
  13122. if (size) {
  13123. totalSize += MATH.abs(size);
  13124. }
  13125. }
  13126. return totalSize;
  13127. },
  13128. margins : margins,
  13129. /**
  13130. * More flexible version of {@link #setStyle} for setting style properties.
  13131. * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
  13132. * a function which returns such a specification.
  13133. * @return {Ext.Element} this
  13134. */
  13135. applyStyles : function(style){
  13136. Ext.DomHelper.applyStyles(this.dom, style);
  13137. return this;
  13138. },
  13139. /**
  13140. * Returns an object with properties matching the styles requested.
  13141. * For example, el.getStyles('color', 'font-size', 'width') might return
  13142. * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
  13143. * @param {String} style1 A style name
  13144. * @param {String} style2 A style name
  13145. * @param {String} etc.
  13146. * @return {Object} The style object
  13147. */
  13148. getStyles : function(){
  13149. var styles = {},
  13150. len = arguments.length,
  13151. i = 0, style;
  13152. for(; i < len; ++i) {
  13153. style = arguments[i];
  13154. styles[style] = this.getStyle(style);
  13155. }
  13156. return styles;
  13157. },
  13158. /**
  13159. * <p>Wraps the specified element with a special 9 element markup/CSS block that renders by default as
  13160. * a gray container with a gradient background, rounded corners and a 4-way shadow.</p>
  13161. * <p>This special markup is used throughout Ext when box wrapping elements ({@link Ext.button.Button},
  13162. * {@link Ext.panel.Panel} when <tt>{@link Ext.panel.Panel#frame frame=true}</tt>, {@link Ext.window.Window}). The markup
  13163. * is of this form:</p>
  13164. * <pre><code>
  13165. Ext.Element.boxMarkup =
  13166. &#39;&lt;div class="{0}-tl">&lt;div class="{0}-tr">&lt;div class="{0}-tc">&lt;/div>&lt;/div>&lt;/div>
  13167. &lt;div class="{0}-ml">&lt;div class="{0}-mr">&lt;div class="{0}-mc">&lt;/div>&lt;/div>&lt;/div>
  13168. &lt;div class="{0}-bl">&lt;div class="{0}-br">&lt;div class="{0}-bc">&lt;/div>&lt;/div>&lt;/div>&#39;;
  13169. * </code></pre>
  13170. * <p>Example usage:</p>
  13171. * <pre><code>
  13172. // Basic box wrap
  13173. Ext.get("foo").boxWrap();
  13174. // You can also add a custom class and use CSS inheritance rules to customize the box look.
  13175. // 'x-box-blue' is a built-in alternative -- look at the related CSS definitions as an example
  13176. // for how to create a custom box wrap style.
  13177. Ext.get("foo").boxWrap().addCls("x-box-blue");
  13178. * </code></pre>
  13179. * @param {String} class (optional) A base CSS class to apply to the containing wrapper element
  13180. * (defaults to <tt>'x-box'</tt>). Note that there are a number of CSS rules that are dependent on
  13181. * this name to make the overall effect work, so if you supply an alternate base class, make sure you
  13182. * also supply all of the necessary rules.
  13183. * @return {Ext.Element} The outermost wrapping element of the created box structure.
  13184. */
  13185. boxWrap : function(cls){
  13186. cls = cls || Ext.baseCSSPrefix + 'box';
  13187. var el = Ext.get(this.insertHtml("beforeBegin", "<div class='" + cls + "'>" + Ext.String.format(ELEMENT.boxMarkup, cls) + "</div>"));
  13188. Ext.DomQuery.selectNode('.' + cls + '-mc', el.dom).appendChild(this.dom);
  13189. return el;
  13190. },
  13191. /**
  13192. * Set the size of this Element. If animation is true, both width and height will be animated concurrently.
  13193. * @param {Number/String} width The new width. This may be one of:<div class="mdetail-params"><ul>
  13194. * <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).</li>
  13195. * <li>A String used to set the CSS width style. Animation may <b>not</b> be used.
  13196. * <li>A size object in the format <code>{width: widthValue, height: heightValue}</code>.</li>
  13197. * </ul></div>
  13198. * @param {Number/String} height The new height. This may be one of:<div class="mdetail-params"><ul>
  13199. * <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels).</li>
  13200. * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
  13201. * </ul></div>
  13202. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
  13203. * @return {Ext.Element} this
  13204. */
  13205. setSize : function(width, height, animate){
  13206. var me = this;
  13207. if (Ext.isObject(width)) { // in case of object from getSize()
  13208. animate = height;
  13209. height = width.height;
  13210. width = width.width;
  13211. }
  13212. width = me.adjustWidth(width);
  13213. height = me.adjustHeight(height);
  13214. if(!animate || !me.anim){
  13215. // Must touch some property before setting style.width/height on non-quirk IE6,7, or the
  13216. // properties will not reflect the changes on the style immediately
  13217. if (!Ext.isIEQuirks && (Ext.isIE6 || Ext.isIE7)) {
  13218. me.dom.offsetTop;
  13219. }
  13220. me.dom.style.width = me.addUnits(width);
  13221. me.dom.style.height = me.addUnits(height);
  13222. }
  13223. else {
  13224. if (animate === true) {
  13225. animate = {};
  13226. }
  13227. me.animate(Ext.applyIf({
  13228. to: {
  13229. width: width,
  13230. height: height
  13231. }
  13232. }, animate));
  13233. }
  13234. return me;
  13235. },
  13236. /**
  13237. * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
  13238. * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
  13239. * if a height has not been set using CSS.
  13240. * @return {Number}
  13241. */
  13242. getComputedHeight : function(){
  13243. var me = this,
  13244. h = Math.max(me.dom.offsetHeight, me.dom.clientHeight);
  13245. if(!h){
  13246. h = parseFloat(me.getStyle('height')) || 0;
  13247. if(!me.isBorderBox()){
  13248. h += me.getFrameWidth('tb');
  13249. }
  13250. }
  13251. return h;
  13252. },
  13253. /**
  13254. * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
  13255. * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
  13256. * if a width has not been set using CSS.
  13257. * @return {Number}
  13258. */
  13259. getComputedWidth : function(){
  13260. var me = this,
  13261. w = Math.max(me.dom.offsetWidth, me.dom.clientWidth);
  13262. if(!w){
  13263. w = parseFloat(me.getStyle('width')) || 0;
  13264. if(!me.isBorderBox()){
  13265. w += me.getFrameWidth('lr');
  13266. }
  13267. }
  13268. return w;
  13269. },
  13270. /**
  13271. * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
  13272. for more information about the sides.
  13273. * @param {String} sides
  13274. * @return {Number}
  13275. */
  13276. getFrameWidth : function(sides, onlyContentBox){
  13277. return onlyContentBox && this.isBorderBox() ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
  13278. },
  13279. /**
  13280. * Sets up event handlers to add and remove a css class when the mouse is over this element
  13281. * @param {String} className
  13282. * @return {Ext.Element} this
  13283. */
  13284. addClsOnOver : function(className){
  13285. var dom = this.dom;
  13286. this.hover(
  13287. function(){
  13288. Ext.fly(dom, INTERNAL).addCls(className);
  13289. },
  13290. function(){
  13291. Ext.fly(dom, INTERNAL).removeCls(className);
  13292. }
  13293. );
  13294. return this;
  13295. },
  13296. /**
  13297. * Sets up event handlers to add and remove a css class when this element has the focus
  13298. * @param {String} className
  13299. * @return {Ext.Element} this
  13300. */
  13301. addClsOnFocus : function(className){
  13302. var me = this,
  13303. dom = me.dom;
  13304. me.on("focus", function(){
  13305. Ext.fly(dom, INTERNAL).addCls(className);
  13306. });
  13307. me.on("blur", function(){
  13308. Ext.fly(dom, INTERNAL).removeCls(className);
  13309. });
  13310. return me;
  13311. },
  13312. /**
  13313. * Sets up event handlers to add and remove a css class when the mouse is down and then up on this element (a click effect)
  13314. * @param {String} className
  13315. * @return {Ext.Element} this
  13316. */
  13317. addClsOnClick : function(className){
  13318. var dom = this.dom;
  13319. this.on("mousedown", function(){
  13320. Ext.fly(dom, INTERNAL).addCls(className);
  13321. var d = Ext.getDoc(),
  13322. fn = function(){
  13323. Ext.fly(dom, INTERNAL).removeCls(className);
  13324. d.removeListener("mouseup", fn);
  13325. };
  13326. d.on("mouseup", fn);
  13327. });
  13328. return this;
  13329. },
  13330. /**
  13331. * <p>Returns the dimensions of the element available to lay content out in.<p>
  13332. * <p>If the element (or any ancestor element) has CSS style <code>display : none</code>, the dimensions will be zero.</p>
  13333. * example:<pre><code>
  13334. var vpSize = Ext.getBody().getViewSize();
  13335. // all Windows created afterwards will have a default value of 90% height and 95% width
  13336. Ext.Window.override({
  13337. width: vpSize.width * 0.9,
  13338. height: vpSize.height * 0.95
  13339. });
  13340. // To handle window resizing you would have to hook onto onWindowResize.
  13341. * </code></pre>
  13342. *
  13343. * getViewSize utilizes clientHeight/clientWidth which excludes sizing of scrollbars.
  13344. * To obtain the size including scrollbars, use getStyleSize
  13345. *
  13346. * Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc.
  13347. */
  13348. getViewSize : function(){
  13349. var me = this,
  13350. dom = me.dom,
  13351. isDoc = (dom == Ext.getDoc().dom || dom == Ext.getBody().dom),
  13352. style, overflow, ret;
  13353. // If the body, use static methods
  13354. if (isDoc) {
  13355. ret = {
  13356. width : ELEMENT.getViewWidth(),
  13357. height : ELEMENT.getViewHeight()
  13358. };
  13359. // Else use clientHeight/clientWidth
  13360. }
  13361. else {
  13362. // IE 6 & IE Quirks mode acts more like a max-size measurement unless overflow is hidden during measurement.
  13363. // We will put the overflow back to it's original value when we are done measuring.
  13364. if (Ext.isIE6 || Ext.isIEQuirks) {
  13365. style = dom.style;
  13366. overflow = style.overflow;
  13367. me.setStyle({ overflow: 'hidden'});
  13368. }
  13369. ret = {
  13370. width : dom.clientWidth,
  13371. height : dom.clientHeight
  13372. };
  13373. if (Ext.isIE6 || Ext.isIEQuirks) {
  13374. me.setStyle({ overflow: overflow });
  13375. }
  13376. }
  13377. return ret;
  13378. },
  13379. /**
  13380. * <p>Returns the dimensions of the element available to lay content out in.<p>
  13381. *
  13382. * getStyleSize utilizes prefers style sizing if present, otherwise it chooses the larger of offsetHeight/clientHeight and offsetWidth/clientWidth.
  13383. * To obtain the size excluding scrollbars, use getViewSize
  13384. *
  13385. * Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc.
  13386. */
  13387. getStyleSize : function(){
  13388. var me = this,
  13389. doc = document,
  13390. d = this.dom,
  13391. isDoc = (d == doc || d == doc.body),
  13392. s = d.style,
  13393. w, h;
  13394. // If the body, use static methods
  13395. if (isDoc) {
  13396. return {
  13397. width : ELEMENT.getViewWidth(),
  13398. height : ELEMENT.getViewHeight()
  13399. };
  13400. }
  13401. // Use Styles if they are set
  13402. if(s.width && s.width != 'auto'){
  13403. w = parseFloat(s.width);
  13404. if(me.isBorderBox()){
  13405. w -= me.getFrameWidth('lr');
  13406. }
  13407. }
  13408. // Use Styles if they are set
  13409. if(s.height && s.height != 'auto'){
  13410. h = parseFloat(s.height);
  13411. if(me.isBorderBox()){
  13412. h -= me.getFrameWidth('tb');
  13413. }
  13414. }
  13415. // Use getWidth/getHeight if style not set.
  13416. return {width: w || me.getWidth(true), height: h || me.getHeight(true)};
  13417. },
  13418. /**
  13419. * Returns the size of the element.
  13420. * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
  13421. * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
  13422. */
  13423. getSize : function(contentSize){
  13424. return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
  13425. },
  13426. /**
  13427. * Forces the browser to repaint this element
  13428. * @return {Ext.Element} this
  13429. */
  13430. repaint : function(){
  13431. var dom = this.dom;
  13432. this.addCls(Ext.baseCSSPrefix + 'repaint');
  13433. setTimeout(function(){
  13434. Ext.fly(dom).removeCls(Ext.baseCSSPrefix + 'repaint');
  13435. }, 1);
  13436. return this;
  13437. },
  13438. /**
  13439. * Enable text selection for this element (normalized across browsers)
  13440. * @return {Ext.Element} this
  13441. */
  13442. selectable : function() {
  13443. var me = this;
  13444. me.dom.unselectable = "off";
  13445. // Prevent it from bubles up and enables it to be selectable
  13446. me.on('selectstart', function (e) {
  13447. e.stopPropagation();
  13448. return true;
  13449. });
  13450. me.applyStyles("-moz-user-select: text; -khtml-user-select: text;");
  13451. me.removeCls(Ext.baseCSSPrefix + 'unselectable');
  13452. return me;
  13453. },
  13454. /**
  13455. * Disables text selection for this element (normalized across browsers)
  13456. * @return {Ext.Element} this
  13457. */
  13458. unselectable : function(){
  13459. var me = this;
  13460. me.dom.unselectable = "on";
  13461. me.swallowEvent("selectstart", true);
  13462. me.applyStyles("-moz-user-select:-moz-none;-khtml-user-select:none;");
  13463. me.addCls(Ext.baseCSSPrefix + 'unselectable');
  13464. return me;
  13465. },
  13466. /**
  13467. * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
  13468. * then it returns the calculated width of the sides (see getPadding)
  13469. * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
  13470. * @return {Object/Number}
  13471. */
  13472. getMargin : function(side){
  13473. var me = this,
  13474. hash = {t:"top", l:"left", r:"right", b: "bottom"},
  13475. o = {},
  13476. key;
  13477. if (!side) {
  13478. for (key in me.margins){
  13479. o[hash[key]] = parseFloat(me.getStyle(me.margins[key])) || 0;
  13480. }
  13481. return o;
  13482. } else {
  13483. return me.addStyles.call(me, side, me.margins);
  13484. }
  13485. }
  13486. });
  13487. })();
  13488. /**
  13489. * @class Ext.Element
  13490. */
  13491. /**
  13492. * Visibility mode constant for use with {@link #setVisibilityMode}. Use visibility to hide element
  13493. * @static
  13494. * @type Number
  13495. */
  13496. Ext.Element.VISIBILITY = 1;
  13497. /**
  13498. * Visibility mode constant for use with {@link #setVisibilityMode}. Use display to hide element
  13499. * @static
  13500. * @type Number
  13501. */
  13502. Ext.Element.DISPLAY = 2;
  13503. /**
  13504. * Visibility mode constant for use with {@link #setVisibilityMode}. Use offsets (x and y positioning offscreen)
  13505. * to hide element.
  13506. * @static
  13507. * @type Number
  13508. */
  13509. Ext.Element.OFFSETS = 3;
  13510. Ext.Element.ASCLASS = 4;
  13511. /**
  13512. * Defaults to 'x-hide-nosize'
  13513. * @static
  13514. * @type String
  13515. */
  13516. Ext.Element.visibilityCls = Ext.baseCSSPrefix + 'hide-nosize';
  13517. Ext.Element.addMethods(function(){
  13518. var El = Ext.Element,
  13519. OPACITY = "opacity",
  13520. VISIBILITY = "visibility",
  13521. DISPLAY = "display",
  13522. HIDDEN = "hidden",
  13523. OFFSETS = "offsets",
  13524. ASCLASS = "asclass",
  13525. NONE = "none",
  13526. NOSIZE = 'nosize',
  13527. ORIGINALDISPLAY = 'originalDisplay',
  13528. VISMODE = 'visibilityMode',
  13529. ISVISIBLE = 'isVisible',
  13530. data = El.data,
  13531. getDisplay = function(dom){
  13532. var d = data(dom, ORIGINALDISPLAY);
  13533. if(d === undefined){
  13534. data(dom, ORIGINALDISPLAY, d = '');
  13535. }
  13536. return d;
  13537. },
  13538. getVisMode = function(dom){
  13539. var m = data(dom, VISMODE);
  13540. if(m === undefined){
  13541. data(dom, VISMODE, m = 1);
  13542. }
  13543. return m;
  13544. };
  13545. return {
  13546. /**
  13547. * @property {String} originalDisplay
  13548. * The element's default display mode
  13549. */
  13550. originalDisplay : "",
  13551. visibilityMode : 1,
  13552. /**
  13553. * Sets the element's visibility mode. When setVisible() is called it
  13554. * will use this to determine whether to set the visibility or the display property.
  13555. * @param {Number} visMode Ext.Element.VISIBILITY or Ext.Element.DISPLAY
  13556. * @return {Ext.Element} this
  13557. */
  13558. setVisibilityMode : function(visMode){
  13559. data(this.dom, VISMODE, visMode);
  13560. return this;
  13561. },
  13562. /**
  13563. * Checks whether the element is currently visible using both visibility and display properties.
  13564. * @return {Boolean} True if the element is currently visible, else false
  13565. */
  13566. isVisible : function() {
  13567. var me = this,
  13568. dom = me.dom,
  13569. visible = data(dom, ISVISIBLE);
  13570. if(typeof visible == 'boolean'){ //return the cached value if registered
  13571. return visible;
  13572. }
  13573. //Determine the current state based on display states
  13574. visible = !me.isStyle(VISIBILITY, HIDDEN) &&
  13575. !me.isStyle(DISPLAY, NONE) &&
  13576. !((getVisMode(dom) == El.ASCLASS) && me.hasCls(me.visibilityCls || El.visibilityCls));
  13577. data(dom, ISVISIBLE, visible);
  13578. return visible;
  13579. },
  13580. /**
  13581. * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
  13582. * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
  13583. * @param {Boolean} visible Whether the element is visible
  13584. * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
  13585. * @return {Ext.Element} this
  13586. */
  13587. setVisible : function(visible, animate){
  13588. var me = this, isDisplay, isVisibility, isOffsets, isNosize,
  13589. dom = me.dom,
  13590. visMode = getVisMode(dom);
  13591. // hideMode string override
  13592. if (typeof animate == 'string'){
  13593. switch (animate) {
  13594. case DISPLAY:
  13595. visMode = El.DISPLAY;
  13596. break;
  13597. case VISIBILITY:
  13598. visMode = El.VISIBILITY;
  13599. break;
  13600. case OFFSETS:
  13601. visMode = El.OFFSETS;
  13602. break;
  13603. case NOSIZE:
  13604. case ASCLASS:
  13605. visMode = El.ASCLASS;
  13606. break;
  13607. }
  13608. me.setVisibilityMode(visMode);
  13609. animate = false;
  13610. }
  13611. if (!animate || !me.anim) {
  13612. if(visMode == El.ASCLASS ){
  13613. me[visible?'removeCls':'addCls'](me.visibilityCls || El.visibilityCls);
  13614. } else if (visMode == El.DISPLAY){
  13615. return me.setDisplayed(visible);
  13616. } else if (visMode == El.OFFSETS){
  13617. if (!visible){
  13618. // Remember position for restoring, if we are not already hidden by offsets.
  13619. if (!me.hideModeStyles) {
  13620. me.hideModeStyles = {
  13621. position: me.getStyle('position'),
  13622. top: me.getStyle('top'),
  13623. left: me.getStyle('left')
  13624. };
  13625. }
  13626. me.applyStyles({position: 'absolute', top: '-10000px', left: '-10000px'});
  13627. }
  13628. // Only "restore" as position if we have actually been hidden using offsets.
  13629. // Calling setVisible(true) on a positioned element should not reposition it.
  13630. else if (me.hideModeStyles) {
  13631. me.applyStyles(me.hideModeStyles || {position: '', top: '', left: ''});
  13632. delete me.hideModeStyles;
  13633. }
  13634. }else{
  13635. me.fixDisplay();
  13636. // Show by clearing visibility style. Explicitly setting to "visible" overrides parent visibility setting.
  13637. dom.style.visibility = visible ? '' : HIDDEN;
  13638. }
  13639. }else{
  13640. // closure for composites
  13641. if(visible){
  13642. me.setOpacity(0.01);
  13643. me.setVisible(true);
  13644. }
  13645. if (!Ext.isObject(animate)) {
  13646. animate = {
  13647. duration: 350,
  13648. easing: 'ease-in'
  13649. };
  13650. }
  13651. me.animate(Ext.applyIf({
  13652. callback: function() {
  13653. visible || me.setVisible(false).setOpacity(1);
  13654. },
  13655. to: {
  13656. opacity: (visible) ? 1 : 0
  13657. }
  13658. }, animate));
  13659. }
  13660. data(dom, ISVISIBLE, visible); //set logical visibility state
  13661. return me;
  13662. },
  13663. /**
  13664. * @private
  13665. * Determine if the Element has a relevant height and width available based
  13666. * upon current logical visibility state
  13667. */
  13668. hasMetrics : function(){
  13669. var dom = this.dom;
  13670. return this.isVisible() || (getVisMode(dom) == El.OFFSETS) || (getVisMode(dom) == El.VISIBILITY);
  13671. },
  13672. /**
  13673. * Toggles the element's visibility or display, depending on visibility mode.
  13674. * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
  13675. * @return {Ext.Element} this
  13676. */
  13677. toggle : function(animate){
  13678. var me = this;
  13679. me.setVisible(!me.isVisible(), me.anim(animate));
  13680. return me;
  13681. },
  13682. /**
  13683. * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
  13684. * @param {Boolean/String} value Boolean value to display the element using its default display, or a string to set the display directly.
  13685. * @return {Ext.Element} this
  13686. */
  13687. setDisplayed : function(value) {
  13688. if(typeof value == "boolean"){
  13689. value = value ? getDisplay(this.dom) : NONE;
  13690. }
  13691. this.setStyle(DISPLAY, value);
  13692. return this;
  13693. },
  13694. // private
  13695. fixDisplay : function(){
  13696. var me = this;
  13697. if (me.isStyle(DISPLAY, NONE)) {
  13698. me.setStyle(VISIBILITY, HIDDEN);
  13699. me.setStyle(DISPLAY, getDisplay(this.dom)); // first try reverting to default
  13700. if (me.isStyle(DISPLAY, NONE)) { // if that fails, default to block
  13701. me.setStyle(DISPLAY, "block");
  13702. }
  13703. }
  13704. },
  13705. /**
  13706. * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
  13707. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
  13708. * @return {Ext.Element} this
  13709. */
  13710. hide : function(animate){
  13711. // hideMode override
  13712. if (typeof animate == 'string'){
  13713. this.setVisible(false, animate);
  13714. return this;
  13715. }
  13716. this.setVisible(false, this.anim(animate));
  13717. return this;
  13718. },
  13719. /**
  13720. * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
  13721. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
  13722. * @return {Ext.Element} this
  13723. */
  13724. show : function(animate){
  13725. // hideMode override
  13726. if (typeof animate == 'string'){
  13727. this.setVisible(true, animate);
  13728. return this;
  13729. }
  13730. this.setVisible(true, this.anim(animate));
  13731. return this;
  13732. }
  13733. };
  13734. }());
  13735. /**
  13736. * @class Ext.Element
  13737. */
  13738. Ext.applyIf(Ext.Element.prototype, {
  13739. // @private override base Ext.util.Animate mixin for animate for backwards compatibility
  13740. animate: function(config) {
  13741. var me = this;
  13742. if (!me.id) {
  13743. me = Ext.get(me.dom);
  13744. }
  13745. if (Ext.fx.Manager.hasFxBlock(me.id)) {
  13746. return me;
  13747. }
  13748. Ext.fx.Manager.queueFx(Ext.create('Ext.fx.Anim', me.anim(config)));
  13749. return this;
  13750. },
  13751. // @private override base Ext.util.Animate mixin for animate for backwards compatibility
  13752. anim: function(config) {
  13753. if (!Ext.isObject(config)) {
  13754. return (config) ? {} : false;
  13755. }
  13756. var me = this,
  13757. duration = config.duration || Ext.fx.Anim.prototype.duration,
  13758. easing = config.easing || 'ease',
  13759. animConfig;
  13760. if (config.stopAnimation) {
  13761. me.stopAnimation();
  13762. }
  13763. Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id));
  13764. // Clear any 'paused' defaults.
  13765. Ext.fx.Manager.setFxDefaults(me.id, {
  13766. delay: 0
  13767. });
  13768. animConfig = {
  13769. target: me,
  13770. remove: config.remove,
  13771. alternate: config.alternate || false,
  13772. duration: duration,
  13773. easing: easing,
  13774. callback: config.callback,
  13775. listeners: config.listeners,
  13776. iterations: config.iterations || 1,
  13777. scope: config.scope,
  13778. block: config.block,
  13779. concurrent: config.concurrent,
  13780. delay: config.delay || 0,
  13781. paused: true,
  13782. keyframes: config.keyframes,
  13783. from: config.from || {},
  13784. to: Ext.apply({}, config)
  13785. };
  13786. Ext.apply(animConfig.to, config.to);
  13787. // Anim API properties - backward compat
  13788. delete animConfig.to.to;
  13789. delete animConfig.to.from;
  13790. delete animConfig.to.remove;
  13791. delete animConfig.to.alternate;
  13792. delete animConfig.to.keyframes;
  13793. delete animConfig.to.iterations;
  13794. delete animConfig.to.listeners;
  13795. delete animConfig.to.target;
  13796. delete animConfig.to.paused;
  13797. delete animConfig.to.callback;
  13798. delete animConfig.to.scope;
  13799. delete animConfig.to.duration;
  13800. delete animConfig.to.easing;
  13801. delete animConfig.to.concurrent;
  13802. delete animConfig.to.block;
  13803. delete animConfig.to.stopAnimation;
  13804. delete animConfig.to.delay;
  13805. return animConfig;
  13806. },
  13807. /**
  13808. * Slides the element into view. An anchor point can be optionally passed to set the point of origin for the slide
  13809. * effect. This function automatically handles wrapping the element with a fixed-size container if needed. See the
  13810. * Fx class overview for valid anchor point options. Usage:
  13811. *
  13812. * // default: slide the element in from the top
  13813. * el.slideIn();
  13814. *
  13815. * // custom: slide the element in from the right with a 2-second duration
  13816. * el.slideIn('r', { duration: 2000 });
  13817. *
  13818. * // common config options shown with default values
  13819. * el.slideIn('t', {
  13820. * easing: 'easeOut',
  13821. * duration: 500
  13822. * });
  13823. *
  13824. * @param {String} [anchor='t'] One of the valid Fx anchor positions
  13825. * @param {Object} [options] Object literal with any of the Fx config options
  13826. * @return {Ext.Element} The Element
  13827. */
  13828. slideIn: function(anchor, obj, slideOut) {
  13829. var me = this,
  13830. elStyle = me.dom.style,
  13831. beforeAnim, wrapAnim;
  13832. anchor = anchor || "t";
  13833. obj = obj || {};
  13834. beforeAnim = function() {
  13835. var animScope = this,
  13836. listeners = obj.listeners,
  13837. box, position, restoreSize, wrap, anim;
  13838. if (!slideOut) {
  13839. me.fixDisplay();
  13840. }
  13841. box = me.getBox();
  13842. if ((anchor == 't' || anchor == 'b') && box.height === 0) {
  13843. box.height = me.dom.scrollHeight;
  13844. }
  13845. else if ((anchor == 'l' || anchor == 'r') && box.width === 0) {
  13846. box.width = me.dom.scrollWidth;
  13847. }
  13848. position = me.getPositioning();
  13849. me.setSize(box.width, box.height);
  13850. wrap = me.wrap({
  13851. style: {
  13852. visibility: slideOut ? 'visible' : 'hidden'
  13853. }
  13854. });
  13855. wrap.setPositioning(position);
  13856. if (wrap.isStyle('position', 'static')) {
  13857. wrap.position('relative');
  13858. }
  13859. me.clearPositioning('auto');
  13860. wrap.clip();
  13861. // This element is temporarily positioned absolute within its wrapper.
  13862. // Restore to its default, CSS-inherited visibility setting.
  13863. // We cannot explicitly poke visibility:visible into its style because that overrides the visibility of the wrap.
  13864. me.setStyle({
  13865. visibility: '',
  13866. position: 'absolute'
  13867. });
  13868. if (slideOut) {
  13869. wrap.setSize(box.width, box.height);
  13870. }
  13871. switch (anchor) {
  13872. case 't':
  13873. anim = {
  13874. from: {
  13875. width: box.width + 'px',
  13876. height: '0px'
  13877. },
  13878. to: {
  13879. width: box.width + 'px',
  13880. height: box.height + 'px'
  13881. }
  13882. };
  13883. elStyle.bottom = '0px';
  13884. break;
  13885. case 'l':
  13886. anim = {
  13887. from: {
  13888. width: '0px',
  13889. height: box.height + 'px'
  13890. },
  13891. to: {
  13892. width: box.width + 'px',
  13893. height: box.height + 'px'
  13894. }
  13895. };
  13896. elStyle.right = '0px';
  13897. break;
  13898. case 'r':
  13899. anim = {
  13900. from: {
  13901. x: box.x + box.width,
  13902. width: '0px',
  13903. height: box.height + 'px'
  13904. },
  13905. to: {
  13906. x: box.x,
  13907. width: box.width + 'px',
  13908. height: box.height + 'px'
  13909. }
  13910. };
  13911. break;
  13912. case 'b':
  13913. anim = {
  13914. from: {
  13915. y: box.y + box.height,
  13916. width: box.width + 'px',
  13917. height: '0px'
  13918. },
  13919. to: {
  13920. y: box.y,
  13921. width: box.width + 'px',
  13922. height: box.height + 'px'
  13923. }
  13924. };
  13925. break;
  13926. case 'tl':
  13927. anim = {
  13928. from: {
  13929. x: box.x,
  13930. y: box.y,
  13931. width: '0px',
  13932. height: '0px'
  13933. },
  13934. to: {
  13935. width: box.width + 'px',
  13936. height: box.height + 'px'
  13937. }
  13938. };
  13939. elStyle.bottom = '0px';
  13940. elStyle.right = '0px';
  13941. break;
  13942. case 'bl':
  13943. anim = {
  13944. from: {
  13945. x: box.x + box.width,
  13946. width: '0px',
  13947. height: '0px'
  13948. },
  13949. to: {
  13950. x: box.x,
  13951. width: box.width + 'px',
  13952. height: box.height + 'px'
  13953. }
  13954. };
  13955. elStyle.right = '0px';
  13956. break;
  13957. case 'br':
  13958. anim = {
  13959. from: {
  13960. x: box.x + box.width,
  13961. y: box.y + box.height,
  13962. width: '0px',
  13963. height: '0px'
  13964. },
  13965. to: {
  13966. x: box.x,
  13967. y: box.y,
  13968. width: box.width + 'px',
  13969. height: box.height + 'px'
  13970. }
  13971. };
  13972. break;
  13973. case 'tr':
  13974. anim = {
  13975. from: {
  13976. y: box.y + box.height,
  13977. width: '0px',
  13978. height: '0px'
  13979. },
  13980. to: {
  13981. y: box.y,
  13982. width: box.width + 'px',
  13983. height: box.height + 'px'
  13984. }
  13985. };
  13986. elStyle.bottom = '0px';
  13987. break;
  13988. }
  13989. wrap.show();
  13990. wrapAnim = Ext.apply({}, obj);
  13991. delete wrapAnim.listeners;
  13992. wrapAnim = Ext.create('Ext.fx.Anim', Ext.applyIf(wrapAnim, {
  13993. target: wrap,
  13994. duration: 500,
  13995. easing: 'ease-out',
  13996. from: slideOut ? anim.to : anim.from,
  13997. to: slideOut ? anim.from : anim.to
  13998. }));
  13999. // In the absence of a callback, this listener MUST be added first
  14000. wrapAnim.on('afteranimate', function() {
  14001. if (slideOut) {
  14002. me.setPositioning(position);
  14003. if (obj.useDisplay) {
  14004. me.setDisplayed(false);
  14005. } else {
  14006. me.hide();
  14007. }
  14008. }
  14009. else {
  14010. me.clearPositioning();
  14011. me.setPositioning(position);
  14012. }
  14013. if (wrap.dom) {
  14014. wrap.dom.parentNode.insertBefore(me.dom, wrap.dom);
  14015. wrap.remove();
  14016. }
  14017. me.setSize(box.width, box.height);
  14018. animScope.end();
  14019. });
  14020. // Add configured listeners after
  14021. if (listeners) {
  14022. wrapAnim.on(listeners);
  14023. }
  14024. };
  14025. me.animate({
  14026. duration: obj.duration ? obj.duration * 2 : 1000,
  14027. listeners: {
  14028. beforeanimate: {
  14029. fn: beforeAnim
  14030. },
  14031. afteranimate: {
  14032. fn: function() {
  14033. if (wrapAnim && wrapAnim.running) {
  14034. wrapAnim.end();
  14035. }
  14036. }
  14037. }
  14038. }
  14039. });
  14040. return me;
  14041. },
  14042. /**
  14043. * Slides the element out of view. An anchor point can be optionally passed to set the end point for the slide
  14044. * effect. When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will
  14045. * still take up space in the document. The element must be removed from the DOM using the 'remove' config option if
  14046. * desired. This function automatically handles wrapping the element with a fixed-size container if needed. See the
  14047. * Fx class overview for valid anchor point options. Usage:
  14048. *
  14049. * // default: slide the element out to the top
  14050. * el.slideOut();
  14051. *
  14052. * // custom: slide the element out to the right with a 2-second duration
  14053. * el.slideOut('r', { duration: 2000 });
  14054. *
  14055. * // common config options shown with default values
  14056. * el.slideOut('t', {
  14057. * easing: 'easeOut',
  14058. * duration: 500,
  14059. * remove: false,
  14060. * useDisplay: false
  14061. * });
  14062. *
  14063. * @param {String} [anchor='t'] One of the valid Fx anchor positions
  14064. * @param {Object} [options] Object literal with any of the Fx config options
  14065. * @return {Ext.Element} The Element
  14066. */
  14067. slideOut: function(anchor, o) {
  14068. return this.slideIn(anchor, o, true);
  14069. },
  14070. /**
  14071. * Fades the element out while slowly expanding it in all directions. When the effect is completed, the element will
  14072. * be hidden (visibility = 'hidden') but block elements will still take up space in the document. Usage:
  14073. *
  14074. * // default
  14075. * el.puff();
  14076. *
  14077. * // common config options shown with default values
  14078. * el.puff({
  14079. * easing: 'easeOut',
  14080. * duration: 500,
  14081. * useDisplay: false
  14082. * });
  14083. *
  14084. * @param {Object} options (optional) Object literal with any of the Fx config options
  14085. * @return {Ext.Element} The Element
  14086. */
  14087. puff: function(obj) {
  14088. var me = this,
  14089. beforeAnim;
  14090. obj = Ext.applyIf(obj || {}, {
  14091. easing: 'ease-out',
  14092. duration: 500,
  14093. useDisplay: false
  14094. });
  14095. beforeAnim = function() {
  14096. me.clearOpacity();
  14097. me.show();
  14098. var box = me.getBox(),
  14099. fontSize = me.getStyle('fontSize'),
  14100. position = me.getPositioning();
  14101. this.to = {
  14102. width: box.width * 2,
  14103. height: box.height * 2,
  14104. x: box.x - (box.width / 2),
  14105. y: box.y - (box.height /2),
  14106. opacity: 0,
  14107. fontSize: '200%'
  14108. };
  14109. this.on('afteranimate',function() {
  14110. if (me.dom) {
  14111. if (obj.useDisplay) {
  14112. me.setDisplayed(false);
  14113. } else {
  14114. me.hide();
  14115. }
  14116. me.clearOpacity();
  14117. me.setPositioning(position);
  14118. me.setStyle({fontSize: fontSize});
  14119. }
  14120. });
  14121. };
  14122. me.animate({
  14123. duration: obj.duration,
  14124. easing: obj.easing,
  14125. listeners: {
  14126. beforeanimate: {
  14127. fn: beforeAnim
  14128. }
  14129. }
  14130. });
  14131. return me;
  14132. },
  14133. /**
  14134. * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
  14135. * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
  14136. * take up space in the document. The element must be removed from the DOM using the 'remove' config option if
  14137. * desired. Usage:
  14138. *
  14139. * // default
  14140. * el.switchOff();
  14141. *
  14142. * // all config options shown with default values
  14143. * el.switchOff({
  14144. * easing: 'easeIn',
  14145. * duration: .3,
  14146. * remove: false,
  14147. * useDisplay: false
  14148. * });
  14149. *
  14150. * @param {Object} options (optional) Object literal with any of the Fx config options
  14151. * @return {Ext.Element} The Element
  14152. */
  14153. switchOff: function(obj) {
  14154. var me = this,
  14155. beforeAnim;
  14156. obj = Ext.applyIf(obj || {}, {
  14157. easing: 'ease-in',
  14158. duration: 500,
  14159. remove: false,
  14160. useDisplay: false
  14161. });
  14162. beforeAnim = function() {
  14163. var animScope = this,
  14164. size = me.getSize(),
  14165. xy = me.getXY(),
  14166. keyframe, position;
  14167. me.clearOpacity();
  14168. me.clip();
  14169. position = me.getPositioning();
  14170. keyframe = Ext.create('Ext.fx.Animator', {
  14171. target: me,
  14172. duration: obj.duration,
  14173. easing: obj.easing,
  14174. keyframes: {
  14175. 33: {
  14176. opacity: 0.3
  14177. },
  14178. 66: {
  14179. height: 1,
  14180. y: xy[1] + size.height / 2
  14181. },
  14182. 100: {
  14183. width: 1,
  14184. x: xy[0] + size.width / 2
  14185. }
  14186. }
  14187. });
  14188. keyframe.on('afteranimate', function() {
  14189. if (obj.useDisplay) {
  14190. me.setDisplayed(false);
  14191. } else {
  14192. me.hide();
  14193. }
  14194. me.clearOpacity();
  14195. me.setPositioning(position);
  14196. me.setSize(size);
  14197. animScope.end();
  14198. });
  14199. };
  14200. me.animate({
  14201. duration: (obj.duration * 2),
  14202. listeners: {
  14203. beforeanimate: {
  14204. fn: beforeAnim
  14205. }
  14206. }
  14207. });
  14208. return me;
  14209. },
  14210. /**
  14211. * Shows a ripple of exploding, attenuating borders to draw attention to an Element. Usage:
  14212. *
  14213. * // default: a single light blue ripple
  14214. * el.frame();
  14215. *
  14216. * // custom: 3 red ripples lasting 3 seconds total
  14217. * el.frame("#ff0000", 3, { duration: 3 });
  14218. *
  14219. * // common config options shown with default values
  14220. * el.frame("#C3DAF9", 1, {
  14221. * duration: 1 //duration of each individual ripple.
  14222. * // Note: Easing is not configurable and will be ignored if included
  14223. * });
  14224. *
  14225. * @param {String} [color='C3DAF9'] The color of the border. Should be a 6 char hex color without the leading #
  14226. * (defaults to light blue).
  14227. * @param {Number} [count=1] The number of ripples to display
  14228. * @param {Object} [options] Object literal with any of the Fx config options
  14229. * @return {Ext.Element} The Element
  14230. */
  14231. frame : function(color, count, obj){
  14232. var me = this,
  14233. beforeAnim;
  14234. color = color || '#C3DAF9';
  14235. count = count || 1;
  14236. obj = obj || {};
  14237. beforeAnim = function() {
  14238. me.show();
  14239. var animScope = this,
  14240. box = me.getBox(),
  14241. proxy = Ext.getBody().createChild({
  14242. style: {
  14243. position : 'absolute',
  14244. 'pointer-events': 'none',
  14245. 'z-index': 35000,
  14246. border : '0px solid ' + color
  14247. }
  14248. }),
  14249. proxyAnim;
  14250. proxyAnim = Ext.create('Ext.fx.Anim', {
  14251. target: proxy,
  14252. duration: obj.duration || 1000,
  14253. iterations: count,
  14254. from: {
  14255. top: box.y,
  14256. left: box.x,
  14257. borderWidth: 0,
  14258. opacity: 1,
  14259. height: box.height,
  14260. width: box.width
  14261. },
  14262. to: {
  14263. top: box.y - 20,
  14264. left: box.x - 20,
  14265. borderWidth: 10,
  14266. opacity: 0,
  14267. height: box.height + 40,
  14268. width: box.width + 40
  14269. }
  14270. });
  14271. proxyAnim.on('afteranimate', function() {
  14272. proxy.remove();
  14273. animScope.end();
  14274. });
  14275. };
  14276. me.animate({
  14277. duration: (obj.duration * 2) || 2000,
  14278. listeners: {
  14279. beforeanimate: {
  14280. fn: beforeAnim
  14281. }
  14282. }
  14283. });
  14284. return me;
  14285. },
  14286. /**
  14287. * Slides the element while fading it out of view. An anchor point can be optionally passed to set the ending point
  14288. * of the effect. Usage:
  14289. *
  14290. * // default: slide the element downward while fading out
  14291. * el.ghost();
  14292. *
  14293. * // custom: slide the element out to the right with a 2-second duration
  14294. * el.ghost('r', { duration: 2000 });
  14295. *
  14296. * // common config options shown with default values
  14297. * el.ghost('b', {
  14298. * easing: 'easeOut',
  14299. * duration: 500
  14300. * });
  14301. *
  14302. * @param {String} [anchor='b'] One of the valid Fx anchor positions
  14303. * @param {Object} [options] Object literal with any of the Fx config options
  14304. * @return {Ext.Element} The Element
  14305. */
  14306. ghost: function(anchor, obj) {
  14307. var me = this,
  14308. beforeAnim;
  14309. anchor = anchor || "b";
  14310. beforeAnim = function() {
  14311. var width = me.getWidth(),
  14312. height = me.getHeight(),
  14313. xy = me.getXY(),
  14314. position = me.getPositioning(),
  14315. to = {
  14316. opacity: 0
  14317. };
  14318. switch (anchor) {
  14319. case 't':
  14320. to.y = xy[1] - height;
  14321. break;
  14322. case 'l':
  14323. to.x = xy[0] - width;
  14324. break;
  14325. case 'r':
  14326. to.x = xy[0] + width;
  14327. break;
  14328. case 'b':
  14329. to.y = xy[1] + height;
  14330. break;
  14331. case 'tl':
  14332. to.x = xy[0] - width;
  14333. to.y = xy[1] - height;
  14334. break;
  14335. case 'bl':
  14336. to.x = xy[0] - width;
  14337. to.y = xy[1] + height;
  14338. break;
  14339. case 'br':
  14340. to.x = xy[0] + width;
  14341. to.y = xy[1] + height;
  14342. break;
  14343. case 'tr':
  14344. to.x = xy[0] + width;
  14345. to.y = xy[1] - height;
  14346. break;
  14347. }
  14348. this.to = to;
  14349. this.on('afteranimate', function () {
  14350. if (me.dom) {
  14351. me.hide();
  14352. me.clearOpacity();
  14353. me.setPositioning(position);
  14354. }
  14355. });
  14356. };
  14357. me.animate(Ext.applyIf(obj || {}, {
  14358. duration: 500,
  14359. easing: 'ease-out',
  14360. listeners: {
  14361. beforeanimate: {
  14362. fn: beforeAnim
  14363. }
  14364. }
  14365. }));
  14366. return me;
  14367. },
  14368. /**
  14369. * Highlights the Element by setting a color (applies to the background-color by default, but can be changed using
  14370. * the "attr" config option) and then fading back to the original color. If no original color is available, you
  14371. * should provide the "endColor" config option which will be cleared after the animation. Usage:
  14372. *
  14373. * // default: highlight background to yellow
  14374. * el.highlight();
  14375. *
  14376. * // custom: highlight foreground text to blue for 2 seconds
  14377. * el.highlight("0000ff", { attr: 'color', duration: 2000 });
  14378. *
  14379. * // common config options shown with default values
  14380. * el.highlight("ffff9c", {
  14381. * attr: "backgroundColor", //can be any valid CSS property (attribute) that supports a color value
  14382. * endColor: (current color) or "ffffff",
  14383. * easing: 'easeIn',
  14384. * duration: 1000
  14385. * });
  14386. *
  14387. * @param {String} [color='ffff9c'] The highlight color. Should be a 6 char hex color without the leading #
  14388. * @param {Object} [options] Object literal with any of the Fx config options
  14389. * @return {Ext.Element} The Element
  14390. */
  14391. highlight: function(color, o) {
  14392. var me = this,
  14393. dom = me.dom,
  14394. from = {},
  14395. restore, to, attr, lns, event, fn;
  14396. o = o || {};
  14397. lns = o.listeners || {};
  14398. attr = o.attr || 'backgroundColor';
  14399. from[attr] = color || 'ffff9c';
  14400. if (!o.to) {
  14401. to = {};
  14402. to[attr] = o.endColor || me.getColor(attr, 'ffffff', '');
  14403. }
  14404. else {
  14405. to = o.to;
  14406. }
  14407. // Don't apply directly on lns, since we reference it in our own callbacks below
  14408. o.listeners = Ext.apply(Ext.apply({}, lns), {
  14409. beforeanimate: function() {
  14410. restore = dom.style[attr];
  14411. me.clearOpacity();
  14412. me.show();
  14413. event = lns.beforeanimate;
  14414. if (event) {
  14415. fn = event.fn || event;
  14416. return fn.apply(event.scope || lns.scope || window, arguments);
  14417. }
  14418. },
  14419. afteranimate: function() {
  14420. if (dom) {
  14421. dom.style[attr] = restore;
  14422. }
  14423. event = lns.afteranimate;
  14424. if (event) {
  14425. fn = event.fn || event;
  14426. fn.apply(event.scope || lns.scope || window, arguments);
  14427. }
  14428. }
  14429. });
  14430. me.animate(Ext.apply({}, o, {
  14431. duration: 1000,
  14432. easing: 'ease-in',
  14433. from: from,
  14434. to: to
  14435. }));
  14436. return me;
  14437. },
  14438. /**
  14439. * @deprecated 4.0
  14440. * Creates a pause before any subsequent queued effects begin. If there are no effects queued after the pause it will
  14441. * have no effect. Usage:
  14442. *
  14443. * el.pause(1);
  14444. *
  14445. * @param {Number} seconds The length of time to pause (in seconds)
  14446. * @return {Ext.Element} The Element
  14447. */
  14448. pause: function(ms) {
  14449. var me = this;
  14450. Ext.fx.Manager.setFxDefaults(me.id, {
  14451. delay: ms
  14452. });
  14453. return me;
  14454. },
  14455. /**
  14456. * Fade an element in (from transparent to opaque). The ending opacity can be specified using the `opacity`
  14457. * config option. Usage:
  14458. *
  14459. * // default: fade in from opacity 0 to 100%
  14460. * el.fadeIn();
  14461. *
  14462. * // custom: fade in from opacity 0 to 75% over 2 seconds
  14463. * el.fadeIn({ opacity: .75, duration: 2000});
  14464. *
  14465. * // common config options shown with default values
  14466. * el.fadeIn({
  14467. * opacity: 1, //can be any value between 0 and 1 (e.g. .5)
  14468. * easing: 'easeOut',
  14469. * duration: 500
  14470. * });
  14471. *
  14472. * @param {Object} options (optional) Object literal with any of the Fx config options
  14473. * @return {Ext.Element} The Element
  14474. */
  14475. fadeIn: function(o) {
  14476. this.animate(Ext.apply({}, o, {
  14477. opacity: 1
  14478. }));
  14479. return this;
  14480. },
  14481. /**
  14482. * Fade an element out (from opaque to transparent). The ending opacity can be specified using the `opacity`
  14483. * config option. Note that IE may require `useDisplay:true` in order to redisplay correctly.
  14484. * Usage:
  14485. *
  14486. * // default: fade out from the element's current opacity to 0
  14487. * el.fadeOut();
  14488. *
  14489. * // custom: fade out from the element's current opacity to 25% over 2 seconds
  14490. * el.fadeOut({ opacity: .25, duration: 2000});
  14491. *
  14492. * // common config options shown with default values
  14493. * el.fadeOut({
  14494. * opacity: 0, //can be any value between 0 and 1 (e.g. .5)
  14495. * easing: 'easeOut',
  14496. * duration: 500,
  14497. * remove: false,
  14498. * useDisplay: false
  14499. * });
  14500. *
  14501. * @param {Object} options (optional) Object literal with any of the Fx config options
  14502. * @return {Ext.Element} The Element
  14503. */
  14504. fadeOut: function(o) {
  14505. this.animate(Ext.apply({}, o, {
  14506. opacity: 0
  14507. }));
  14508. return this;
  14509. },
  14510. /**
  14511. * @deprecated 4.0
  14512. * Animates the transition of an element's dimensions from a starting height/width to an ending height/width. This
  14513. * method is a convenience implementation of {@link #shift}. Usage:
  14514. *
  14515. * // change height and width to 100x100 pixels
  14516. * el.scale(100, 100);
  14517. *
  14518. * // common config options shown with default values. The height and width will default to
  14519. * // the element's existing values if passed as null.
  14520. * el.scale(
  14521. * [element's width],
  14522. * [element's height], {
  14523. * easing: 'easeOut',
  14524. * duration: .35
  14525. * }
  14526. * );
  14527. *
  14528. * @param {Number} width The new width (pass undefined to keep the original width)
  14529. * @param {Number} height The new height (pass undefined to keep the original height)
  14530. * @param {Object} options (optional) Object literal with any of the Fx config options
  14531. * @return {Ext.Element} The Element
  14532. */
  14533. scale: function(w, h, o) {
  14534. this.animate(Ext.apply({}, o, {
  14535. width: w,
  14536. height: h
  14537. }));
  14538. return this;
  14539. },
  14540. /**
  14541. * @deprecated 4.0
  14542. * Animates the transition of any combination of an element's dimensions, xy position and/or opacity. Any of these
  14543. * properties not specified in the config object will not be changed. This effect requires that at least one new
  14544. * dimension, position or opacity setting must be passed in on the config object in order for the function to have
  14545. * any effect. Usage:
  14546. *
  14547. * // slide the element horizontally to x position 200 while changing the height and opacity
  14548. * el.shift({ x: 200, height: 50, opacity: .8 });
  14549. *
  14550. * // common config options shown with default values.
  14551. * el.shift({
  14552. * width: [element's width],
  14553. * height: [element's height],
  14554. * x: [element's x position],
  14555. * y: [element's y position],
  14556. * opacity: [element's opacity],
  14557. * easing: 'easeOut',
  14558. * duration: .35
  14559. * });
  14560. *
  14561. * @param {Object} options Object literal with any of the Fx config options
  14562. * @return {Ext.Element} The Element
  14563. */
  14564. shift: function(config) {
  14565. this.animate(config);
  14566. return this;
  14567. }
  14568. });
  14569. /**
  14570. * @class Ext.Element
  14571. */
  14572. Ext.applyIf(Ext.Element, {
  14573. unitRe: /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i,
  14574. camelRe: /(-[a-z])/gi,
  14575. opacityRe: /alpha\(opacity=(.*)\)/i,
  14576. cssRe: /([a-z0-9-]+)\s*:\s*([^;\s]+(?:\s*[^;\s]+)*);?/gi,
  14577. propertyCache: {},
  14578. defaultUnit : "px",
  14579. borders: {l: 'border-left-width', r: 'border-right-width', t: 'border-top-width', b: 'border-bottom-width'},
  14580. paddings: {l: 'padding-left', r: 'padding-right', t: 'padding-top', b: 'padding-bottom'},
  14581. margins: {l: 'margin-left', r: 'margin-right', t: 'margin-top', b: 'margin-bottom'},
  14582. // Reference the prototype's version of the method. Signatures are identical.
  14583. addUnits : Ext.Element.prototype.addUnits,
  14584. /**
  14585. * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
  14586. * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
  14587. * @static
  14588. * @param {Number/String} box The encoded margins
  14589. * @return {Object} An object with margin sizes for top, right, bottom and left
  14590. */
  14591. parseBox : function(box) {
  14592. if (Ext.isObject(box)) {
  14593. return {
  14594. top: box.top || 0,
  14595. right: box.right || 0,
  14596. bottom: box.bottom || 0,
  14597. left: box.left || 0
  14598. };
  14599. } else {
  14600. if (typeof box != 'string') {
  14601. box = box.toString();
  14602. }
  14603. var parts = box.split(' '),
  14604. ln = parts.length;
  14605. if (ln == 1) {
  14606. parts[1] = parts[2] = parts[3] = parts[0];
  14607. }
  14608. else if (ln == 2) {
  14609. parts[2] = parts[0];
  14610. parts[3] = parts[1];
  14611. }
  14612. else if (ln == 3) {
  14613. parts[3] = parts[1];
  14614. }
  14615. return {
  14616. top :parseFloat(parts[0]) || 0,
  14617. right :parseFloat(parts[1]) || 0,
  14618. bottom:parseFloat(parts[2]) || 0,
  14619. left :parseFloat(parts[3]) || 0
  14620. };
  14621. }
  14622. },
  14623. /**
  14624. * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
  14625. * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
  14626. * @static
  14627. * @param {Number/String} box The encoded margins
  14628. * @param {String} units The type of units to add
  14629. * @return {String} An string with unitized (px if units is not specified) metrics for top, right, bottom and left
  14630. */
  14631. unitizeBox : function(box, units) {
  14632. var A = this.addUnits,
  14633. B = this.parseBox(box);
  14634. return A(B.top, units) + ' ' +
  14635. A(B.right, units) + ' ' +
  14636. A(B.bottom, units) + ' ' +
  14637. A(B.left, units);
  14638. },
  14639. // private
  14640. camelReplaceFn : function(m, a) {
  14641. return a.charAt(1).toUpperCase();
  14642. },
  14643. /**
  14644. * Normalizes CSS property keys from dash delimited to camel case JavaScript Syntax.
  14645. * For example:
  14646. * <ul>
  14647. * <li>border-width -> borderWidth</li>
  14648. * <li>padding-top -> paddingTop</li>
  14649. * </ul>
  14650. * @static
  14651. * @param {String} prop The property to normalize
  14652. * @return {String} The normalized string
  14653. */
  14654. normalize : function(prop) {
  14655. if (prop == 'float') {
  14656. prop = Ext.supports.Float ? 'cssFloat' : 'styleFloat';
  14657. }
  14658. return this.propertyCache[prop] || (this.propertyCache[prop] = prop.replace(this.camelRe, this.camelReplaceFn));
  14659. },
  14660. /**
  14661. * Retrieves the document height
  14662. * @static
  14663. * @return {Number} documentHeight
  14664. */
  14665. getDocumentHeight: function() {
  14666. return Math.max(!Ext.isStrict ? document.body.scrollHeight : document.documentElement.scrollHeight, this.getViewportHeight());
  14667. },
  14668. /**
  14669. * Retrieves the document width
  14670. * @static
  14671. * @return {Number} documentWidth
  14672. */
  14673. getDocumentWidth: function() {
  14674. return Math.max(!Ext.isStrict ? document.body.scrollWidth : document.documentElement.scrollWidth, this.getViewportWidth());
  14675. },
  14676. /**
  14677. * Retrieves the viewport height of the window.
  14678. * @static
  14679. * @return {Number} viewportHeight
  14680. */
  14681. getViewportHeight: function(){
  14682. return window.innerHeight;
  14683. },
  14684. /**
  14685. * Retrieves the viewport width of the window.
  14686. * @static
  14687. * @return {Number} viewportWidth
  14688. */
  14689. getViewportWidth : function() {
  14690. return window.innerWidth;
  14691. },
  14692. /**
  14693. * Retrieves the viewport size of the window.
  14694. * @static
  14695. * @return {Object} object containing width and height properties
  14696. */
  14697. getViewSize : function() {
  14698. return {
  14699. width: window.innerWidth,
  14700. height: window.innerHeight
  14701. };
  14702. },
  14703. /**
  14704. * Retrieves the current orientation of the window. This is calculated by
  14705. * determing if the height is greater than the width.
  14706. * @static
  14707. * @return {String} Orientation of window: 'portrait' or 'landscape'
  14708. */
  14709. getOrientation : function() {
  14710. if (Ext.supports.OrientationChange) {
  14711. return (window.orientation == 0) ? 'portrait' : 'landscape';
  14712. }
  14713. return (window.innerHeight > window.innerWidth) ? 'portrait' : 'landscape';
  14714. },
  14715. /**
  14716. * Returns the top Element that is located at the passed coordinates
  14717. * @static
  14718. * @param {Number} x The x coordinate
  14719. * @param {Number} y The y coordinate
  14720. * @return {String} The found Element
  14721. */
  14722. fromPoint: function(x, y) {
  14723. return Ext.get(document.elementFromPoint(x, y));
  14724. },
  14725. /**
  14726. * Converts a CSS string into an object with a property for each style.
  14727. * <p>
  14728. * The sample code below would return an object with 2 properties, one
  14729. * for background-color and one for color.</p>
  14730. * <pre><code>
  14731. var css = 'background-color: red;color: blue; ';
  14732. console.log(Ext.Element.parseStyles(css));
  14733. * </code></pre>
  14734. * @static
  14735. * @param {String} styles A CSS string
  14736. * @return {Object} styles
  14737. */
  14738. parseStyles: function(styles){
  14739. var out = {},
  14740. cssRe = this.cssRe,
  14741. matches;
  14742. if (styles) {
  14743. // Since we're using the g flag on the regex, we need to set the lastIndex.
  14744. // This automatically happens on some implementations, but not others, see:
  14745. // http://stackoverflow.com/questions/2645273/javascript-regular-expression-literal-persists-between-function-calls
  14746. // http://blog.stevenlevithan.com/archives/fixing-javascript-regexp
  14747. cssRe.lastIndex = 0;
  14748. while ((matches = cssRe.exec(styles))) {
  14749. out[matches[1]] = matches[2];
  14750. }
  14751. }
  14752. return out;
  14753. }
  14754. });
  14755. /**
  14756. * @class Ext.CompositeElementLite
  14757. * <p>This class encapsulates a <i>collection</i> of DOM elements, providing methods to filter
  14758. * members, or to perform collective actions upon the whole set.</p>
  14759. * <p>Although they are not listed, this class supports all of the methods of {@link Ext.Element} and
  14760. * {@link Ext.fx.Anim}. The methods from these classes will be performed on all the elements in this collection.</p>
  14761. * Example:<pre><code>
  14762. var els = Ext.select("#some-el div.some-class");
  14763. // or select directly from an existing element
  14764. var el = Ext.get('some-el');
  14765. el.select('div.some-class');
  14766. els.setWidth(100); // all elements become 100 width
  14767. els.hide(true); // all elements fade out and hide
  14768. // or
  14769. els.setWidth(100).hide(true);
  14770. </code></pre>
  14771. */
  14772. Ext.CompositeElementLite = function(els, root){
  14773. /**
  14774. * <p>The Array of DOM elements which this CompositeElement encapsulates. Read-only.</p>
  14775. * <p>This will not <i>usually</i> be accessed in developers' code, but developers wishing
  14776. * to augment the capabilities of the CompositeElementLite class may use it when adding
  14777. * methods to the class.</p>
  14778. * <p>For example to add the <code>nextAll</code> method to the class to <b>add</b> all
  14779. * following siblings of selected elements, the code would be</p><code><pre>
  14780. Ext.override(Ext.CompositeElementLite, {
  14781. nextAll: function() {
  14782. var els = this.elements, i, l = els.length, n, r = [], ri = -1;
  14783. // Loop through all elements in this Composite, accumulating
  14784. // an Array of all siblings.
  14785. for (i = 0; i < l; i++) {
  14786. for (n = els[i].nextSibling; n; n = n.nextSibling) {
  14787. r[++ri] = n;
  14788. }
  14789. }
  14790. // Add all found siblings to this Composite
  14791. return this.add(r);
  14792. }
  14793. });</pre></code>
  14794. * @property {HTMLElement} elements
  14795. */
  14796. this.elements = [];
  14797. this.add(els, root);
  14798. this.el = new Ext.Element.Flyweight();
  14799. };
  14800. Ext.CompositeElementLite.prototype = {
  14801. isComposite: true,
  14802. // private
  14803. getElement : function(el){
  14804. // Set the shared flyweight dom property to the current element
  14805. var e = this.el;
  14806. e.dom = el;
  14807. e.id = el.id;
  14808. return e;
  14809. },
  14810. // private
  14811. transformElement : function(el){
  14812. return Ext.getDom(el);
  14813. },
  14814. /**
  14815. * Returns the number of elements in this Composite.
  14816. * @return Number
  14817. */
  14818. getCount : function(){
  14819. return this.elements.length;
  14820. },
  14821. /**
  14822. * Adds elements to this Composite object.
  14823. * @param {HTMLElement[]/Ext.CompositeElement} els Either an Array of DOM elements to add, or another Composite object who's elements should be added.
  14824. * @return {Ext.CompositeElement} This Composite object.
  14825. */
  14826. add : function(els, root){
  14827. var me = this,
  14828. elements = me.elements;
  14829. if(!els){
  14830. return this;
  14831. }
  14832. if(typeof els == "string"){
  14833. els = Ext.Element.selectorFunction(els, root);
  14834. }else if(els.isComposite){
  14835. els = els.elements;
  14836. }else if(!Ext.isIterable(els)){
  14837. els = [els];
  14838. }
  14839. for(var i = 0, len = els.length; i < len; ++i){
  14840. elements.push(me.transformElement(els[i]));
  14841. }
  14842. return me;
  14843. },
  14844. invoke : function(fn, args){
  14845. var me = this,
  14846. els = me.elements,
  14847. len = els.length,
  14848. e,
  14849. i;
  14850. for(i = 0; i < len; i++) {
  14851. e = els[i];
  14852. if(e){
  14853. Ext.Element.prototype[fn].apply(me.getElement(e), args);
  14854. }
  14855. }
  14856. return me;
  14857. },
  14858. /**
  14859. * Returns a flyweight Element of the dom element object at the specified index
  14860. * @param {Number} index
  14861. * @return {Ext.Element}
  14862. */
  14863. item : function(index){
  14864. var me = this,
  14865. el = me.elements[index],
  14866. out = null;
  14867. if(el){
  14868. out = me.getElement(el);
  14869. }
  14870. return out;
  14871. },
  14872. // fixes scope with flyweight
  14873. addListener : function(eventName, handler, scope, opt){
  14874. var els = this.elements,
  14875. len = els.length,
  14876. i, e;
  14877. for(i = 0; i<len; i++) {
  14878. e = els[i];
  14879. if(e) {
  14880. Ext.EventManager.on(e, eventName, handler, scope || e, opt);
  14881. }
  14882. }
  14883. return this;
  14884. },
  14885. /**
  14886. * <p>Calls the passed function for each element in this composite.</p>
  14887. * @param {Function} fn The function to call. The function is passed the following parameters:<ul>
  14888. * <li><b>el</b> : Element<div class="sub-desc">The current Element in the iteration.
  14889. * <b>This is the flyweight (shared) Ext.Element instance, so if you require a
  14890. * a reference to the dom node, use el.dom.</b></div></li>
  14891. * <li><b>c</b> : Composite<div class="sub-desc">This Composite object.</div></li>
  14892. * <li><b>idx</b> : Number<div class="sub-desc">The zero-based index in the iteration.</div></li>
  14893. * </ul>
  14894. * @param {Object} [scope] The scope (<i>this</i> reference) in which the function is executed. (defaults to the Element)
  14895. * @return {Ext.CompositeElement} this
  14896. */
  14897. each : function(fn, scope){
  14898. var me = this,
  14899. els = me.elements,
  14900. len = els.length,
  14901. i, e;
  14902. for(i = 0; i<len; i++) {
  14903. e = els[i];
  14904. if(e){
  14905. e = this.getElement(e);
  14906. if(fn.call(scope || e, e, me, i) === false){
  14907. break;
  14908. }
  14909. }
  14910. }
  14911. return me;
  14912. },
  14913. /**
  14914. * Clears this Composite and adds the elements passed.
  14915. * @param {HTMLElement[]/Ext.CompositeElement} els Either an array of DOM elements, or another Composite from which to fill this Composite.
  14916. * @return {Ext.CompositeElement} this
  14917. */
  14918. fill : function(els){
  14919. var me = this;
  14920. me.elements = [];
  14921. me.add(els);
  14922. return me;
  14923. },
  14924. /**
  14925. * Filters this composite to only elements that match the passed selector.
  14926. * @param {String/Function} selector A string CSS selector or a comparison function.
  14927. * The comparison function will be called with the following arguments:<ul>
  14928. * <li><code>el</code> : Ext.Element<div class="sub-desc">The current DOM element.</div></li>
  14929. * <li><code>index</code> : Number<div class="sub-desc">The current index within the collection.</div></li>
  14930. * </ul>
  14931. * @return {Ext.CompositeElement} this
  14932. */
  14933. filter : function(selector){
  14934. var els = [],
  14935. me = this,
  14936. fn = Ext.isFunction(selector) ? selector
  14937. : function(el){
  14938. return el.is(selector);
  14939. };
  14940. me.each(function(el, self, i) {
  14941. if (fn(el, i) !== false) {
  14942. els[els.length] = me.transformElement(el);
  14943. }
  14944. });
  14945. me.elements = els;
  14946. return me;
  14947. },
  14948. /**
  14949. * Find the index of the passed element within the composite collection.
  14950. * @param el {Mixed} The id of an element, or an Ext.Element, or an HtmlElement to find within the composite collection.
  14951. * @return Number The index of the passed Ext.Element in the composite collection, or -1 if not found.
  14952. */
  14953. indexOf : function(el){
  14954. return Ext.Array.indexOf(this.elements, this.transformElement(el));
  14955. },
  14956. /**
  14957. * Replaces the specified element with the passed element.
  14958. * @param {String/HTMLElement/Ext.Element/Number} el The id of an element, the Element itself, the index of the element in this composite
  14959. * to replace.
  14960. * @param {String/Ext.Element} replacement The id of an element or the Element itself.
  14961. * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
  14962. * @return {Ext.CompositeElement} this
  14963. */
  14964. replaceElement : function(el, replacement, domReplace){
  14965. var index = !isNaN(el) ? el : this.indexOf(el),
  14966. d;
  14967. if(index > -1){
  14968. replacement = Ext.getDom(replacement);
  14969. if(domReplace){
  14970. d = this.elements[index];
  14971. d.parentNode.insertBefore(replacement, d);
  14972. Ext.removeNode(d);
  14973. }
  14974. Ext.Array.splice(this.elements, index, 1, replacement);
  14975. }
  14976. return this;
  14977. },
  14978. /**
  14979. * Removes all elements.
  14980. */
  14981. clear : function(){
  14982. this.elements = [];
  14983. }
  14984. };
  14985. Ext.CompositeElementLite.prototype.on = Ext.CompositeElementLite.prototype.addListener;
  14986. /**
  14987. * @private
  14988. * Copies all of the functions from Ext.Element's prototype onto CompositeElementLite's prototype.
  14989. * This is called twice - once immediately below, and once again after additional Ext.Element
  14990. * are added in Ext JS
  14991. */
  14992. Ext.CompositeElementLite.importElementMethods = function() {
  14993. var fnName,
  14994. ElProto = Ext.Element.prototype,
  14995. CelProto = Ext.CompositeElementLite.prototype;
  14996. for (fnName in ElProto) {
  14997. if (typeof ElProto[fnName] == 'function'){
  14998. (function(fnName) {
  14999. CelProto[fnName] = CelProto[fnName] || function() {
  15000. return this.invoke(fnName, arguments);
  15001. };
  15002. }).call(CelProto, fnName);
  15003. }
  15004. }
  15005. };
  15006. Ext.CompositeElementLite.importElementMethods();
  15007. if(Ext.DomQuery){
  15008. Ext.Element.selectorFunction = Ext.DomQuery.select;
  15009. }
  15010. /**
  15011. * Selects elements based on the passed CSS selector to enable {@link Ext.Element Element} methods
  15012. * to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or
  15013. * {@link Ext.CompositeElementLite CompositeElementLite} object.
  15014. * @param {String/HTMLElement[]} selector The CSS selector or an array of elements
  15015. * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
  15016. * @return {Ext.CompositeElementLite/Ext.CompositeElement}
  15017. * @member Ext.Element
  15018. * @method select
  15019. */
  15020. Ext.Element.select = function(selector, root){
  15021. var els;
  15022. if(typeof selector == "string"){
  15023. els = Ext.Element.selectorFunction(selector, root);
  15024. }else if(selector.length !== undefined){
  15025. els = selector;
  15026. }else{
  15027. }
  15028. return new Ext.CompositeElementLite(els);
  15029. };
  15030. /**
  15031. * Selects elements based on the passed CSS selector to enable {@link Ext.Element Element} methods
  15032. * to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or
  15033. * {@link Ext.CompositeElementLite CompositeElementLite} object.
  15034. * @param {String/HTMLElement[]} selector The CSS selector or an array of elements
  15035. * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
  15036. * @return {Ext.CompositeElementLite/Ext.CompositeElement}
  15037. * @member Ext
  15038. * @method select
  15039. */
  15040. Ext.select = Ext.Element.select;
  15041. /**
  15042. * @class Ext.util.DelayedTask
  15043. *
  15044. * The DelayedTask class provides a convenient way to "buffer" the execution of a method,
  15045. * performing setTimeout where a new timeout cancels the old timeout. When called, the
  15046. * task will wait the specified time period before executing. If durng that time period,
  15047. * the task is called again, the original call will be cancelled. This continues so that
  15048. * the function is only called a single time for each iteration.
  15049. *
  15050. * This method is especially useful for things like detecting whether a user has finished
  15051. * typing in a text field. An example would be performing validation on a keypress. You can
  15052. * use this class to buffer the keypress events for a certain number of milliseconds, and
  15053. * perform only if they stop for that amount of time.
  15054. *
  15055. * ## Usage
  15056. *
  15057. * var task = new Ext.util.DelayedTask(function(){
  15058. * alert(Ext.getDom('myInputField').value.length);
  15059. * });
  15060. *
  15061. * // Wait 500ms before calling our function. If the user presses another key
  15062. * // during that 500ms, it will be cancelled and we'll wait another 500ms.
  15063. * Ext.get('myInputField').on('keypress', function(){
  15064. * task.{@link #delay}(500);
  15065. * });
  15066. *
  15067. * Note that we are using a DelayedTask here to illustrate a point. The configuration
  15068. * option `buffer` for {@link Ext.util.Observable#addListener addListener/on} will
  15069. * also setup a delayed task for you to buffer events.
  15070. *
  15071. * @constructor The parameters to this constructor serve as defaults and are not required.
  15072. * @param {Function} fn (optional) The default function to call. If not specified here, it must be specified during the {@link #delay} call.
  15073. * @param {Object} scope (optional) The default scope (The <code><b>this</b></code> reference) in which the
  15074. * function is called. If not specified, <code>this</code> will refer to the browser window.
  15075. * @param {Array} args (optional) The default Array of arguments.
  15076. */
  15077. Ext.util.DelayedTask = function(fn, scope, args) {
  15078. var me = this,
  15079. id,
  15080. call = function() {
  15081. clearInterval(id);
  15082. id = null;
  15083. fn.apply(scope, args || []);
  15084. };
  15085. /**
  15086. * Cancels any pending timeout and queues a new one
  15087. * @param {Number} delay The milliseconds to delay
  15088. * @param {Function} newFn (optional) Overrides function passed to constructor
  15089. * @param {Object} newScope (optional) Overrides scope passed to constructor. Remember that if no scope
  15090. * is specified, <code>this</code> will refer to the browser window.
  15091. * @param {Array} newArgs (optional) Overrides args passed to constructor
  15092. */
  15093. this.delay = function(delay, newFn, newScope, newArgs) {
  15094. me.cancel();
  15095. fn = newFn || fn;
  15096. scope = newScope || scope;
  15097. args = newArgs || args;
  15098. id = setInterval(call, delay);
  15099. };
  15100. /**
  15101. * Cancel the last queued timeout
  15102. */
  15103. this.cancel = function(){
  15104. if (id) {
  15105. clearInterval(id);
  15106. id = null;
  15107. }
  15108. };
  15109. };
  15110. Ext.require('Ext.util.DelayedTask', function() {
  15111. Ext.util.Event = Ext.extend(Object, (function() {
  15112. function createBuffered(handler, listener, o, scope) {
  15113. listener.task = new Ext.util.DelayedTask();
  15114. return function() {
  15115. listener.task.delay(o.buffer, handler, scope, Ext.Array.toArray(arguments));
  15116. };
  15117. }
  15118. function createDelayed(handler, listener, o, scope) {
  15119. return function() {
  15120. var task = new Ext.util.DelayedTask();
  15121. if (!listener.tasks) {
  15122. listener.tasks = [];
  15123. }
  15124. listener.tasks.push(task);
  15125. task.delay(o.delay || 10, handler, scope, Ext.Array.toArray(arguments));
  15126. };
  15127. }
  15128. function createSingle(handler, listener, o, scope) {
  15129. return function() {
  15130. listener.ev.removeListener(listener.fn, scope);
  15131. return handler.apply(scope, arguments);
  15132. };
  15133. }
  15134. return {
  15135. isEvent: true,
  15136. constructor: function(observable, name) {
  15137. this.name = name;
  15138. this.observable = observable;
  15139. this.listeners = [];
  15140. },
  15141. addListener: function(fn, scope, options) {
  15142. var me = this,
  15143. listener;
  15144. scope = scope || me.observable;
  15145. if (!me.isListening(fn, scope)) {
  15146. listener = me.createListener(fn, scope, options);
  15147. if (me.firing) {
  15148. // if we are currently firing this event, don't disturb the listener loop
  15149. me.listeners = me.listeners.slice(0);
  15150. }
  15151. me.listeners.push(listener);
  15152. }
  15153. },
  15154. createListener: function(fn, scope, o) {
  15155. o = o || {};
  15156. scope = scope || this.observable;
  15157. var listener = {
  15158. fn: fn,
  15159. scope: scope,
  15160. o: o,
  15161. ev: this
  15162. },
  15163. handler = fn;
  15164. // The order is important. The 'single' wrapper must be wrapped by the 'buffer' and 'delayed' wrapper
  15165. // because the event removal that the single listener does destroys the listener's DelayedTask(s)
  15166. if (o.single) {
  15167. handler = createSingle(handler, listener, o, scope);
  15168. }
  15169. if (o.delay) {
  15170. handler = createDelayed(handler, listener, o, scope);
  15171. }
  15172. if (o.buffer) {
  15173. handler = createBuffered(handler, listener, o, scope);
  15174. }
  15175. listener.fireFn = handler;
  15176. return listener;
  15177. },
  15178. findListener: function(fn, scope) {
  15179. var listeners = this.listeners,
  15180. i = listeners.length,
  15181. listener,
  15182. s;
  15183. while (i--) {
  15184. listener = listeners[i];
  15185. if (listener) {
  15186. s = listener.scope;
  15187. if (listener.fn == fn && (s == scope || s == this.observable)) {
  15188. return i;
  15189. }
  15190. }
  15191. }
  15192. return - 1;
  15193. },
  15194. isListening: function(fn, scope) {
  15195. return this.findListener(fn, scope) !== -1;
  15196. },
  15197. removeListener: function(fn, scope) {
  15198. var me = this,
  15199. index,
  15200. listener,
  15201. k;
  15202. index = me.findListener(fn, scope);
  15203. if (index != -1) {
  15204. listener = me.listeners[index];
  15205. if (me.firing) {
  15206. me.listeners = me.listeners.slice(0);
  15207. }
  15208. // cancel and remove a buffered handler that hasn't fired yet
  15209. if (listener.task) {
  15210. listener.task.cancel();
  15211. delete listener.task;
  15212. }
  15213. // cancel and remove all delayed handlers that haven't fired yet
  15214. k = listener.tasks && listener.tasks.length;
  15215. if (k) {
  15216. while (k--) {
  15217. listener.tasks[k].cancel();
  15218. }
  15219. delete listener.tasks;
  15220. }
  15221. // remove this listener from the listeners array
  15222. Ext.Array.erase(me.listeners, index, 1);
  15223. return true;
  15224. }
  15225. return false;
  15226. },
  15227. // Iterate to stop any buffered/delayed events
  15228. clearListeners: function() {
  15229. var listeners = this.listeners,
  15230. i = listeners.length;
  15231. while (i--) {
  15232. this.removeListener(listeners[i].fn, listeners[i].scope);
  15233. }
  15234. },
  15235. fire: function() {
  15236. var me = this,
  15237. listeners = me.listeners,
  15238. count = listeners.length,
  15239. i,
  15240. args,
  15241. listener;
  15242. if (count > 0) {
  15243. me.firing = true;
  15244. for (i = 0; i < count; i++) {
  15245. listener = listeners[i];
  15246. args = arguments.length ? Array.prototype.slice.call(arguments, 0) : [];
  15247. if (listener.o) {
  15248. args.push(listener.o);
  15249. }
  15250. if (listener && listener.fireFn.apply(listener.scope || me.observable, args) === false) {
  15251. return (me.firing = false);
  15252. }
  15253. }
  15254. }
  15255. me.firing = false;
  15256. return true;
  15257. }
  15258. };
  15259. })());
  15260. });
  15261. /**
  15262. * @class Ext.EventManager
  15263. * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
  15264. * several useful events directly.
  15265. * See {@link Ext.EventObject} for more details on normalized event objects.
  15266. * @singleton
  15267. */
  15268. Ext.EventManager = {
  15269. // --------------------- onReady ---------------------
  15270. /**
  15271. * Check if we have bound our global onReady listener
  15272. * @private
  15273. */
  15274. hasBoundOnReady: false,
  15275. /**
  15276. * Check if fireDocReady has been called
  15277. * @private
  15278. */
  15279. hasFiredReady: false,
  15280. /**
  15281. * Timer for the document ready event in old IE versions
  15282. * @private
  15283. */
  15284. readyTimeout: null,
  15285. /**
  15286. * Checks if we have bound an onreadystatechange event
  15287. * @private
  15288. */
  15289. hasOnReadyStateChange: false,
  15290. /**
  15291. * Holds references to any onReady functions
  15292. * @private
  15293. */
  15294. readyEvent: new Ext.util.Event(),
  15295. /**
  15296. * Check the ready state for old IE versions
  15297. * @private
  15298. * @return {Boolean} True if the document is ready
  15299. */
  15300. checkReadyState: function(){
  15301. var me = Ext.EventManager;
  15302. if(window.attachEvent){
  15303. // See here for reference: http://javascript.nwbox.com/IEContentLoaded/
  15304. // licensed courtesy of http://developer.yahoo.com/yui/license.html
  15305. if (window != top) {
  15306. return false;
  15307. }
  15308. try{
  15309. document.documentElement.doScroll('left');
  15310. }catch(e){
  15311. return false;
  15312. }
  15313. me.fireDocReady();
  15314. return true;
  15315. }
  15316. if (document.readyState == 'complete') {
  15317. me.fireDocReady();
  15318. return true;
  15319. }
  15320. me.readyTimeout = setTimeout(arguments.callee, 2);
  15321. return false;
  15322. },
  15323. /**
  15324. * Binds the appropriate browser event for checking if the DOM has loaded.
  15325. * @private
  15326. */
  15327. bindReadyEvent: function(){
  15328. var me = Ext.EventManager;
  15329. if (me.hasBoundOnReady) {
  15330. return;
  15331. }
  15332. if (document.addEventListener) {
  15333. document.addEventListener('DOMContentLoaded', me.fireDocReady, false);
  15334. // fallback, load will ~always~ fire
  15335. window.addEventListener('load', me.fireDocReady, false);
  15336. } else {
  15337. // check if the document is ready, this will also kick off the scroll checking timer
  15338. if (!me.checkReadyState()) {
  15339. document.attachEvent('onreadystatechange', me.checkReadyState);
  15340. me.hasOnReadyStateChange = true;
  15341. }
  15342. // fallback, onload will ~always~ fire
  15343. window.attachEvent('onload', me.fireDocReady, false);
  15344. }
  15345. me.hasBoundOnReady = true;
  15346. },
  15347. /**
  15348. * We know the document is loaded, so trigger any onReady events.
  15349. * @private
  15350. */
  15351. fireDocReady: function(){
  15352. var me = Ext.EventManager;
  15353. // only unbind these events once
  15354. if (!me.hasFiredReady) {
  15355. me.hasFiredReady = true;
  15356. if (document.addEventListener) {
  15357. document.removeEventListener('DOMContentLoaded', me.fireDocReady, false);
  15358. window.removeEventListener('load', me.fireDocReady, false);
  15359. } else {
  15360. if (me.readyTimeout !== null) {
  15361. clearTimeout(me.readyTimeout);
  15362. }
  15363. if (me.hasOnReadyStateChange) {
  15364. document.detachEvent('onreadystatechange', me.checkReadyState);
  15365. }
  15366. window.detachEvent('onload', me.fireDocReady);
  15367. }
  15368. Ext.supports.init();
  15369. }
  15370. if (!Ext.isReady) {
  15371. Ext.isReady = true;
  15372. me.onWindowUnload();
  15373. me.readyEvent.fire();
  15374. }
  15375. },
  15376. /**
  15377. * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Can be
  15378. * accessed shorthanded as Ext.onReady().
  15379. * @param {Function} fn The method the event invokes.
  15380. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
  15381. * @param {Boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}.
  15382. */
  15383. onDocumentReady: function(fn, scope, options){
  15384. options = options || {};
  15385. var me = Ext.EventManager,
  15386. readyEvent = me.readyEvent;
  15387. // force single to be true so our event is only ever fired once.
  15388. options.single = true;
  15389. // Document already loaded, let's just fire it
  15390. if (Ext.isReady) {
  15391. readyEvent.addListener(fn, scope, options);
  15392. readyEvent.fire();
  15393. } else {
  15394. options.delay = options.delay || 1;
  15395. readyEvent.addListener(fn, scope, options);
  15396. me.bindReadyEvent();
  15397. }
  15398. },
  15399. // --------------------- event binding ---------------------
  15400. /**
  15401. * Contains a list of all document mouse downs, so we can ensure they fire even when stopEvent is called.
  15402. * @private
  15403. */
  15404. stoppedMouseDownEvent: new Ext.util.Event(),
  15405. /**
  15406. * Options to parse for the 4th argument to addListener.
  15407. * @private
  15408. */
  15409. propRe: /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|freezeEvent)$/,
  15410. /**
  15411. * Get the id of the element. If one has not been assigned, automatically assign it.
  15412. * @param {HTMLElement/Ext.Element} element The element to get the id for.
  15413. * @return {String} id
  15414. */
  15415. getId : function(element) {
  15416. var skipGarbageCollection = false,
  15417. id;
  15418. element = Ext.getDom(element);
  15419. if (element === document || element === window) {
  15420. id = element === document ? Ext.documentId : Ext.windowId;
  15421. }
  15422. else {
  15423. id = Ext.id(element);
  15424. }
  15425. // skip garbage collection for special elements (window, document, iframes)
  15426. if (element && (element.getElementById || element.navigator)) {
  15427. skipGarbageCollection = true;
  15428. }
  15429. if (!Ext.cache[id]){
  15430. Ext.Element.addToCache(new Ext.Element(element), id);
  15431. if (skipGarbageCollection) {
  15432. Ext.cache[id].skipGarbageCollection = true;
  15433. }
  15434. }
  15435. return id;
  15436. },
  15437. /**
  15438. * Convert a "config style" listener into a set of flat arguments so they can be passed to addListener
  15439. * @private
  15440. * @param {Object} element The element the event is for
  15441. * @param {Object} event The event configuration
  15442. * @param {Object} isRemove True if a removal should be performed, otherwise an add will be done.
  15443. */
  15444. prepareListenerConfig: function(element, config, isRemove){
  15445. var me = this,
  15446. propRe = me.propRe,
  15447. key, value, args;
  15448. // loop over all the keys in the object
  15449. for (key in config) {
  15450. if (config.hasOwnProperty(key)) {
  15451. // if the key is something else then an event option
  15452. if (!propRe.test(key)) {
  15453. value = config[key];
  15454. // if the value is a function it must be something like click: function(){}, scope: this
  15455. // which means that there might be multiple event listeners with shared options
  15456. if (Ext.isFunction(value)) {
  15457. // shared options
  15458. args = [element, key, value, config.scope, config];
  15459. } else {
  15460. // if its not a function, it must be an object like click: {fn: function(){}, scope: this}
  15461. args = [element, key, value.fn, value.scope, value];
  15462. }
  15463. if (isRemove === true) {
  15464. me.removeListener.apply(this, args);
  15465. } else {
  15466. me.addListener.apply(me, args);
  15467. }
  15468. }
  15469. }
  15470. }
  15471. },
  15472. /**
  15473. * Normalize cross browser event differences
  15474. * @private
  15475. * @param {Object} eventName The event name
  15476. * @param {Object} fn The function to execute
  15477. * @return {Object} The new event name/function
  15478. */
  15479. normalizeEvent: function(eventName, fn){
  15480. if (/mouseenter|mouseleave/.test(eventName) && !Ext.supports.MouseEnterLeave) {
  15481. if (fn) {
  15482. fn = Ext.Function.createInterceptor(fn, this.contains, this);
  15483. }
  15484. eventName = eventName == 'mouseenter' ? 'mouseover' : 'mouseout';
  15485. } else if (eventName == 'mousewheel' && !Ext.supports.MouseWheel && !Ext.isOpera){
  15486. eventName = 'DOMMouseScroll';
  15487. }
  15488. return {
  15489. eventName: eventName,
  15490. fn: fn
  15491. };
  15492. },
  15493. /**
  15494. * Checks whether the event's relatedTarget is contained inside (or <b>is</b>) the element.
  15495. * @private
  15496. * @param {Object} event
  15497. */
  15498. contains: function(event){
  15499. var parent = event.browserEvent.currentTarget,
  15500. child = this.getRelatedTarget(event);
  15501. if (parent && parent.firstChild) {
  15502. while (child) {
  15503. if (child === parent) {
  15504. return false;
  15505. }
  15506. child = child.parentNode;
  15507. if (child && (child.nodeType != 1)) {
  15508. child = null;
  15509. }
  15510. }
  15511. }
  15512. return true;
  15513. },
  15514. /**
  15515. * Appends an event handler to an element. The shorthand version {@link #on} is equivalent. Typically you will
  15516. * use {@link Ext.Element#addListener} directly on an Element in favor of calling this version.
  15517. * @param {String/HTMLElement} el The html element or id to assign the event handler to.
  15518. * @param {String} eventName The name of the event to listen for.
  15519. * @param {Function} handler The handler function the event invokes. This function is passed
  15520. * the following parameters:<ul>
  15521. * <li>evt : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li>
  15522. * <li>t : Element<div class="sub-desc">The {@link Ext.Element Element} which was the target of the event.
  15523. * Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
  15524. * <li>o : Object<div class="sub-desc">The options object from the addListener call.</div></li>
  15525. * </ul>
  15526. * @param {Object} scope (optional) The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.
  15527. * @param {Object} options (optional) An object containing handler configuration properties.
  15528. * This may contain any of the following properties:<ul>
  15529. * <li>scope : Object<div class="sub-desc">The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.</div></li>
  15530. * <li>delegate : String<div class="sub-desc">A simple selector to filter the target or look for a descendant of the target</div></li>
  15531. * <li>stopEvent : Boolean<div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li>
  15532. * <li>preventDefault : Boolean<div class="sub-desc">True to prevent the default action</div></li>
  15533. * <li>stopPropagation : Boolean<div class="sub-desc">True to prevent event propagation</div></li>
  15534. * <li>normalized : Boolean<div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li>
  15535. * <li>delay : Number<div class="sub-desc">The number of milliseconds to delay the invocation of the handler after te event fires.</div></li>
  15536. * <li>single : Boolean<div class="sub-desc">True to add a handler to handle just the next firing of the event, and then remove itself.</div></li>
  15537. * <li>buffer : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
  15538. * by the specified number of milliseconds. If the event fires again within that time, the original
  15539. * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
  15540. * <li>target : Element<div class="sub-desc">Only call the handler if the event was fired on the target Element, <i>not</i> if the event was bubbled up from a child node.</div></li>
  15541. * </ul><br>
  15542. * <p>See {@link Ext.Element#addListener} for examples of how to use these options.</p>
  15543. */
  15544. addListener: function(element, eventName, fn, scope, options){
  15545. // Check if we've been passed a "config style" event.
  15546. if (typeof eventName !== 'string') {
  15547. this.prepareListenerConfig(element, eventName);
  15548. return;
  15549. }
  15550. var dom = Ext.getDom(element),
  15551. bind,
  15552. wrap;
  15553. // create the wrapper function
  15554. options = options || {};
  15555. bind = this.normalizeEvent(eventName, fn);
  15556. wrap = this.createListenerWrap(dom, eventName, bind.fn, scope, options);
  15557. if (dom.attachEvent) {
  15558. dom.attachEvent('on' + bind.eventName, wrap);
  15559. } else {
  15560. dom.addEventListener(bind.eventName, wrap, options.capture || false);
  15561. }
  15562. if (dom == document && eventName == 'mousedown') {
  15563. this.stoppedMouseDownEvent.addListener(wrap);
  15564. }
  15565. // add all required data into the event cache
  15566. this.getEventListenerCache(dom, eventName).push({
  15567. fn: fn,
  15568. wrap: wrap,
  15569. scope: scope
  15570. });
  15571. },
  15572. /**
  15573. * Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically
  15574. * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version.
  15575. * @param {String/HTMLElement} el The id or html element from which to remove the listener.
  15576. * @param {String} eventName The name of the event.
  15577. * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
  15578. * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
  15579. * then this must refer to the same object.
  15580. */
  15581. removeListener : function(element, eventName, fn, scope) {
  15582. // handle our listener config object syntax
  15583. if (typeof eventName !== 'string') {
  15584. this.prepareListenerConfig(element, eventName, true);
  15585. return;
  15586. }
  15587. var dom = Ext.getDom(element),
  15588. cache = this.getEventListenerCache(dom, eventName),
  15589. bindName = this.normalizeEvent(eventName).eventName,
  15590. i = cache.length, j,
  15591. listener, wrap, tasks;
  15592. while (i--) {
  15593. listener = cache[i];
  15594. if (listener && (!fn || listener.fn == fn) && (!scope || listener.scope === scope)) {
  15595. wrap = listener.wrap;
  15596. // clear buffered calls
  15597. if (wrap.task) {
  15598. clearTimeout(wrap.task);
  15599. delete wrap.task;
  15600. }
  15601. // clear delayed calls
  15602. j = wrap.tasks && wrap.tasks.length;
  15603. if (j) {
  15604. while (j--) {
  15605. clearTimeout(wrap.tasks[j]);
  15606. }
  15607. delete wrap.tasks;
  15608. }
  15609. if (dom.detachEvent) {
  15610. dom.detachEvent('on' + bindName, wrap);
  15611. } else {
  15612. dom.removeEventListener(bindName, wrap, false);
  15613. }
  15614. if (wrap && dom == document && eventName == 'mousedown') {
  15615. this.stoppedMouseDownEvent.removeListener(wrap);
  15616. }
  15617. // remove listener from cache
  15618. Ext.Array.erase(cache, i, 1);
  15619. }
  15620. }
  15621. },
  15622. /**
  15623. * Removes all event handers from an element. Typically you will use {@link Ext.Element#removeAllListeners}
  15624. * directly on an Element in favor of calling this version.
  15625. * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
  15626. */
  15627. removeAll : function(element){
  15628. var dom = Ext.getDom(element),
  15629. cache, ev;
  15630. if (!dom) {
  15631. return;
  15632. }
  15633. cache = this.getElementEventCache(dom);
  15634. for (ev in cache) {
  15635. if (cache.hasOwnProperty(ev)) {
  15636. this.removeListener(dom, ev);
  15637. }
  15638. }
  15639. Ext.cache[dom.id].events = {};
  15640. },
  15641. /**
  15642. * Recursively removes all previous added listeners from an element and its children. Typically you will use {@link Ext.Element#purgeAllListeners}
  15643. * directly on an Element in favor of calling this version.
  15644. * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
  15645. * @param {String} eventName (optional) The name of the event.
  15646. */
  15647. purgeElement : function(element, eventName) {
  15648. var dom = Ext.getDom(element),
  15649. i = 0, len;
  15650. if(eventName) {
  15651. this.removeListener(dom, eventName);
  15652. }
  15653. else {
  15654. this.removeAll(dom);
  15655. }
  15656. if(dom && dom.childNodes) {
  15657. for(len = element.childNodes.length; i < len; i++) {
  15658. this.purgeElement(element.childNodes[i], eventName);
  15659. }
  15660. }
  15661. },
  15662. /**
  15663. * Create the wrapper function for the event
  15664. * @private
  15665. * @param {HTMLElement} dom The dom element
  15666. * @param {String} ename The event name
  15667. * @param {Function} fn The function to execute
  15668. * @param {Object} scope The scope to execute callback in
  15669. * @param {Object} options The options
  15670. * @return {Function} the wrapper function
  15671. */
  15672. createListenerWrap : function(dom, ename, fn, scope, options) {
  15673. options = options || {};
  15674. var f, gen;
  15675. return function wrap(e, args) {
  15676. // Compile the implementation upon first firing
  15677. if (!gen) {
  15678. f = ['if(!Ext) {return;}'];
  15679. if(options.buffer || options.delay || options.freezeEvent) {
  15680. f.push('e = new Ext.EventObjectImpl(e, ' + (options.freezeEvent ? 'true' : 'false' ) + ');');
  15681. } else {
  15682. f.push('e = Ext.EventObject.setEvent(e);');
  15683. }
  15684. if (options.delegate) {
  15685. f.push('var t = e.getTarget("' + options.delegate + '", this);');
  15686. f.push('if(!t) {return;}');
  15687. } else {
  15688. f.push('var t = e.target;');
  15689. }
  15690. if (options.target) {
  15691. f.push('if(e.target !== options.target) {return;}');
  15692. }
  15693. if(options.stopEvent) {
  15694. f.push('e.stopEvent();');
  15695. } else {
  15696. if(options.preventDefault) {
  15697. f.push('e.preventDefault();');
  15698. }
  15699. if(options.stopPropagation) {
  15700. f.push('e.stopPropagation();');
  15701. }
  15702. }
  15703. if(options.normalized === false) {
  15704. f.push('e = e.browserEvent;');
  15705. }
  15706. if(options.buffer) {
  15707. f.push('(wrap.task && clearTimeout(wrap.task));');
  15708. f.push('wrap.task = setTimeout(function(){');
  15709. }
  15710. if(options.delay) {
  15711. f.push('wrap.tasks = wrap.tasks || [];');
  15712. f.push('wrap.tasks.push(setTimeout(function(){');
  15713. }
  15714. // finally call the actual handler fn
  15715. f.push('fn.call(scope || dom, e, t, options);');
  15716. if(options.single) {
  15717. f.push('Ext.EventManager.removeListener(dom, ename, fn, scope);');
  15718. }
  15719. if(options.delay) {
  15720. f.push('}, ' + options.delay + '));');
  15721. }
  15722. if(options.buffer) {
  15723. f.push('}, ' + options.buffer + ');');
  15724. }
  15725. gen = Ext.functionFactory('e', 'options', 'fn', 'scope', 'ename', 'dom', 'wrap', 'args', f.join('\n'));
  15726. }
  15727. gen.call(dom, e, options, fn, scope, ename, dom, wrap, args);
  15728. };
  15729. },
  15730. /**
  15731. * Get the event cache for a particular element for a particular event
  15732. * @private
  15733. * @param {HTMLElement} element The element
  15734. * @param {Object} eventName The event name
  15735. * @return {Array} The events for the element
  15736. */
  15737. getEventListenerCache : function(element, eventName) {
  15738. if (!element) {
  15739. return [];
  15740. }
  15741. var eventCache = this.getElementEventCache(element);
  15742. return eventCache[eventName] || (eventCache[eventName] = []);
  15743. },
  15744. /**
  15745. * Gets the event cache for the object
  15746. * @private
  15747. * @param {HTMLElement} element The element
  15748. * @return {Object} The event cache for the object
  15749. */
  15750. getElementEventCache : function(element) {
  15751. if (!element) {
  15752. return {};
  15753. }
  15754. var elementCache = Ext.cache[this.getId(element)];
  15755. return elementCache.events || (elementCache.events = {});
  15756. },
  15757. // --------------------- utility methods ---------------------
  15758. mouseLeaveRe: /(mouseout|mouseleave)/,
  15759. mouseEnterRe: /(mouseover|mouseenter)/,
  15760. /**
  15761. * Stop the event (preventDefault and stopPropagation)
  15762. * @param {Event} The event to stop
  15763. */
  15764. stopEvent: function(event) {
  15765. this.stopPropagation(event);
  15766. this.preventDefault(event);
  15767. },
  15768. /**
  15769. * Cancels bubbling of the event.
  15770. * @param {Event} The event to stop bubbling.
  15771. */
  15772. stopPropagation: function(event) {
  15773. event = event.browserEvent || event;
  15774. if (event.stopPropagation) {
  15775. event.stopPropagation();
  15776. } else {
  15777. event.cancelBubble = true;
  15778. }
  15779. },
  15780. /**
  15781. * Prevents the browsers default handling of the event.
  15782. * @param {Event} The event to prevent the default
  15783. */
  15784. preventDefault: function(event) {
  15785. event = event.browserEvent || event;
  15786. if (event.preventDefault) {
  15787. event.preventDefault();
  15788. } else {
  15789. event.returnValue = false;
  15790. // Some keys events require setting the keyCode to -1 to be prevented
  15791. try {
  15792. // all ctrl + X and F1 -> F12
  15793. if (event.ctrlKey || event.keyCode > 111 && event.keyCode < 124) {
  15794. event.keyCode = -1;
  15795. }
  15796. } catch (e) {
  15797. // see this outdated document http://support.microsoft.com/kb/934364/en-us for more info
  15798. }
  15799. }
  15800. },
  15801. /**
  15802. * Gets the related target from the event.
  15803. * @param {Object} event The event
  15804. * @return {HTMLElement} The related target.
  15805. */
  15806. getRelatedTarget: function(event) {
  15807. event = event.browserEvent || event;
  15808. var target = event.relatedTarget;
  15809. if (!target) {
  15810. if (this.mouseLeaveRe.test(event.type)) {
  15811. target = event.toElement;
  15812. } else if (this.mouseEnterRe.test(event.type)) {
  15813. target = event.fromElement;
  15814. }
  15815. }
  15816. return this.resolveTextNode(target);
  15817. },
  15818. /**
  15819. * Gets the x coordinate from the event
  15820. * @param {Object} event The event
  15821. * @return {Number} The x coordinate
  15822. */
  15823. getPageX: function(event) {
  15824. return this.getXY(event)[0];
  15825. },
  15826. /**
  15827. * Gets the y coordinate from the event
  15828. * @param {Object} event The event
  15829. * @return {Number} The y coordinate
  15830. */
  15831. getPageY: function(event) {
  15832. return this.getXY(event)[1];
  15833. },
  15834. /**
  15835. * Gets the x & y coordinate from the event
  15836. * @param {Object} event The event
  15837. * @return {Number[]} The x/y coordinate
  15838. */
  15839. getPageXY: function(event) {
  15840. event = event.browserEvent || event;
  15841. var x = event.pageX,
  15842. y = event.pageY,
  15843. doc = document.documentElement,
  15844. body = document.body;
  15845. // pageX/pageY not available (undefined, not null), use clientX/clientY instead
  15846. if (!x && x !== 0) {
  15847. x = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  15848. y = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  15849. }
  15850. return [x, y];
  15851. },
  15852. /**
  15853. * Gets the target of the event.
  15854. * @param {Object} event The event
  15855. * @return {HTMLElement} target
  15856. */
  15857. getTarget: function(event) {
  15858. event = event.browserEvent || event;
  15859. return this.resolveTextNode(event.target || event.srcElement);
  15860. },
  15861. /**
  15862. * Resolve any text nodes accounting for browser differences.
  15863. * @private
  15864. * @param {HTMLElement} node The node
  15865. * @return {HTMLElement} The resolved node
  15866. */
  15867. // technically no need to browser sniff this, however it makes no sense to check this every time, for every event, whether the string is equal.
  15868. resolveTextNode: Ext.isGecko ?
  15869. function(node) {
  15870. if (!node) {
  15871. return;
  15872. }
  15873. // work around firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=101197
  15874. var s = HTMLElement.prototype.toString.call(node);
  15875. if (s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]') {
  15876. return;
  15877. }
  15878. return node.nodeType == 3 ? node.parentNode: node;
  15879. }: function(node) {
  15880. return node && node.nodeType == 3 ? node.parentNode: node;
  15881. },
  15882. // --------------------- custom event binding ---------------------
  15883. // Keep track of the current width/height
  15884. curWidth: 0,
  15885. curHeight: 0,
  15886. /**
  15887. * Adds a listener to be notified when the browser window is resized and provides resize event buffering (100 milliseconds),
  15888. * passes new viewport width and height to handlers.
  15889. * @param {Function} fn The handler function the window resize event invokes.
  15890. * @param {Object} scope The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
  15891. * @param {Boolean} options Options object as passed to {@link Ext.Element#addListener}
  15892. */
  15893. onWindowResize: function(fn, scope, options){
  15894. var resize = this.resizeEvent;
  15895. if(!resize){
  15896. this.resizeEvent = resize = new Ext.util.Event();
  15897. this.on(window, 'resize', this.fireResize, this, {buffer: 100});
  15898. }
  15899. resize.addListener(fn, scope, options);
  15900. },
  15901. /**
  15902. * Fire the resize event.
  15903. * @private
  15904. */
  15905. fireResize: function(){
  15906. var me = this,
  15907. w = Ext.Element.getViewWidth(),
  15908. h = Ext.Element.getViewHeight();
  15909. //whacky problem in IE where the resize event will sometimes fire even though the w/h are the same.
  15910. if(me.curHeight != h || me.curWidth != w){
  15911. me.curHeight = h;
  15912. me.curWidth = w;
  15913. me.resizeEvent.fire(w, h);
  15914. }
  15915. },
  15916. /**
  15917. * Removes the passed window resize listener.
  15918. * @param {Function} fn The method the event invokes
  15919. * @param {Object} scope The scope of handler
  15920. */
  15921. removeResizeListener: function(fn, scope){
  15922. if (this.resizeEvent) {
  15923. this.resizeEvent.removeListener(fn, scope);
  15924. }
  15925. },
  15926. onWindowUnload: function() {
  15927. var unload = this.unloadEvent;
  15928. if (!unload) {
  15929. this.unloadEvent = unload = new Ext.util.Event();
  15930. this.addListener(window, 'unload', this.fireUnload, this);
  15931. }
  15932. },
  15933. /**
  15934. * Fires the unload event for items bound with onWindowUnload
  15935. * @private
  15936. */
  15937. fireUnload: function() {
  15938. // wrap in a try catch, could have some problems during unload
  15939. try {
  15940. this.removeUnloadListener();
  15941. // Work around FF3 remembering the last scroll position when refreshing the grid and then losing grid view
  15942. if (Ext.isGecko3) {
  15943. var gridviews = Ext.ComponentQuery.query('gridview'),
  15944. i = 0,
  15945. ln = gridviews.length;
  15946. for (; i < ln; i++) {
  15947. gridviews[i].scrollToTop();
  15948. }
  15949. }
  15950. // Purge all elements in the cache
  15951. var el,
  15952. cache = Ext.cache;
  15953. for (el in cache) {
  15954. if (cache.hasOwnProperty(el)) {
  15955. Ext.EventManager.removeAll(el);
  15956. }
  15957. }
  15958. } catch(e) {
  15959. }
  15960. },
  15961. /**
  15962. * Removes the passed window unload listener.
  15963. * @param {Function} fn The method the event invokes
  15964. * @param {Object} scope The scope of handler
  15965. */
  15966. removeUnloadListener: function(){
  15967. if (this.unloadEvent) {
  15968. this.removeListener(window, 'unload', this.fireUnload);
  15969. }
  15970. },
  15971. /**
  15972. * note 1: IE fires ONLY the keydown event on specialkey autorepeat
  15973. * note 2: Safari < 3.1, Gecko (Mac/Linux) & Opera fire only the keypress event on specialkey autorepeat
  15974. * (research done by Jan Wolter at http://unixpapa.com/js/key.html)
  15975. * @private
  15976. */
  15977. useKeyDown: Ext.isWebKit ?
  15978. parseInt(navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1], 10) >= 525 :
  15979. !((Ext.isGecko && !Ext.isWindows) || Ext.isOpera),
  15980. /**
  15981. * Indicates which event to use for getting key presses.
  15982. * @return {String} The appropriate event name.
  15983. */
  15984. getKeyEvent: function(){
  15985. return this.useKeyDown ? 'keydown' : 'keypress';
  15986. }
  15987. };
  15988. /**
  15989. * Alias for {@link Ext.Loader#onReady Ext.Loader.onReady} with withDomReady set to true
  15990. * @member Ext
  15991. * @method onReady
  15992. */
  15993. Ext.onReady = function(fn, scope, options) {
  15994. Ext.Loader.onReady(fn, scope, true, options);
  15995. };
  15996. /**
  15997. * Alias for {@link Ext.EventManager#onDocumentReady Ext.EventManager.onDocumentReady}
  15998. * @member Ext
  15999. * @method onDocumentReady
  16000. */
  16001. Ext.onDocumentReady = Ext.EventManager.onDocumentReady;
  16002. /**
  16003. * Alias for {@link Ext.EventManager#addListener Ext.EventManager.addListener}
  16004. * @member Ext.EventManager
  16005. * @method on
  16006. */
  16007. Ext.EventManager.on = Ext.EventManager.addListener;
  16008. /**
  16009. * Alias for {@link Ext.EventManager#removeListener Ext.EventManager.removeListener}
  16010. * @member Ext.EventManager
  16011. * @method un
  16012. */
  16013. Ext.EventManager.un = Ext.EventManager.removeListener;
  16014. (function(){
  16015. var initExtCss = function() {
  16016. // find the body element
  16017. var bd = document.body || document.getElementsByTagName('body')[0],
  16018. baseCSSPrefix = Ext.baseCSSPrefix,
  16019. cls = [baseCSSPrefix + 'body'],
  16020. htmlCls = [],
  16021. html;
  16022. if (!bd) {
  16023. return false;
  16024. }
  16025. html = bd.parentNode;
  16026. function add (c) {
  16027. cls.push(baseCSSPrefix + c);
  16028. }
  16029. //Let's keep this human readable!
  16030. if (Ext.isIE) {
  16031. add('ie');
  16032. // very often CSS needs to do checks like "IE7+" or "IE6 or 7". To help
  16033. // reduce the clutter (since CSS/SCSS cannot do these tests), we add some
  16034. // additional classes:
  16035. //
  16036. // x-ie7p : IE7+ : 7 <= ieVer
  16037. // x-ie7m : IE7- : ieVer <= 7
  16038. // x-ie8p : IE8+ : 8 <= ieVer
  16039. // x-ie8m : IE8- : ieVer <= 8
  16040. // x-ie9p : IE9+ : 9 <= ieVer
  16041. // x-ie78 : IE7 or 8 : 7 <= ieVer <= 8
  16042. //
  16043. if (Ext.isIE6) {
  16044. add('ie6');
  16045. } else { // ignore pre-IE6 :)
  16046. add('ie7p');
  16047. if (Ext.isIE7) {
  16048. add('ie7');
  16049. } else {
  16050. add('ie8p');
  16051. if (Ext.isIE8) {
  16052. add('ie8');
  16053. } else {
  16054. add('ie9p');
  16055. if (Ext.isIE9) {
  16056. add('ie9');
  16057. }
  16058. }
  16059. }
  16060. }
  16061. if (Ext.isIE6 || Ext.isIE7) {
  16062. add('ie7m');
  16063. }
  16064. if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
  16065. add('ie8m');
  16066. }
  16067. if (Ext.isIE7 || Ext.isIE8) {
  16068. add('ie78');
  16069. }
  16070. }
  16071. if (Ext.isGecko) {
  16072. add('gecko');
  16073. if (Ext.isGecko3) {
  16074. add('gecko3');
  16075. }
  16076. if (Ext.isGecko4) {
  16077. add('gecko4');
  16078. }
  16079. if (Ext.isGecko5) {
  16080. add('gecko5');
  16081. }
  16082. }
  16083. if (Ext.isOpera) {
  16084. add('opera');
  16085. }
  16086. if (Ext.isWebKit) {
  16087. add('webkit');
  16088. }
  16089. if (Ext.isSafari) {
  16090. add('safari');
  16091. if (Ext.isSafari2) {
  16092. add('safari2');
  16093. }
  16094. if (Ext.isSafari3) {
  16095. add('safari3');
  16096. }
  16097. if (Ext.isSafari4) {
  16098. add('safari4');
  16099. }
  16100. if (Ext.isSafari5) {
  16101. add('safari5');
  16102. }
  16103. }
  16104. if (Ext.isChrome) {
  16105. add('chrome');
  16106. }
  16107. if (Ext.isMac) {
  16108. add('mac');
  16109. }
  16110. if (Ext.isLinux) {
  16111. add('linux');
  16112. }
  16113. if (!Ext.supports.CSS3BorderRadius) {
  16114. add('nbr');
  16115. }
  16116. if (!Ext.supports.CSS3LinearGradient) {
  16117. add('nlg');
  16118. }
  16119. if (!Ext.scopeResetCSS) {
  16120. add('reset');
  16121. }
  16122. // add to the parent to allow for selectors x-strict x-border-box, also set the isBorderBox property correctly
  16123. if (html) {
  16124. if (Ext.isStrict && (Ext.isIE6 || Ext.isIE7)) {
  16125. Ext.isBorderBox = false;
  16126. }
  16127. else {
  16128. Ext.isBorderBox = true;
  16129. }
  16130. htmlCls.push(baseCSSPrefix + (Ext.isBorderBox ? 'border-box' : 'strict'));
  16131. if (!Ext.isStrict) {
  16132. htmlCls.push(baseCSSPrefix + 'quirks');
  16133. }
  16134. Ext.fly(html, '_internal').addCls(htmlCls);
  16135. }
  16136. Ext.fly(bd, '_internal').addCls(cls);
  16137. return true;
  16138. };
  16139. Ext.onReady(initExtCss);
  16140. })();
  16141. /**
  16142. * @class Ext.EventObject
  16143. Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject
  16144. wraps the browser's native event-object normalizing cross-browser differences,
  16145. such as which mouse button is clicked, keys pressed, mechanisms to stop
  16146. event-propagation along with a method to prevent default actions from taking place.
  16147. For example:
  16148. function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject
  16149. e.preventDefault();
  16150. var target = e.getTarget(); // same as t (the target HTMLElement)
  16151. ...
  16152. }
  16153. var myDiv = {@link Ext#get Ext.get}("myDiv"); // get reference to an {@link Ext.Element}
  16154. myDiv.on( // 'on' is shorthand for addListener
  16155. "click", // perform an action on click of myDiv
  16156. handleClick // reference to the action handler
  16157. );
  16158. // other methods to do the same:
  16159. Ext.EventManager.on("myDiv", 'click', handleClick);
  16160. Ext.EventManager.addListener("myDiv", 'click', handleClick);
  16161. * @singleton
  16162. * @markdown
  16163. */
  16164. Ext.define('Ext.EventObjectImpl', {
  16165. uses: ['Ext.util.Point'],
  16166. /** Key constant @type Number */
  16167. BACKSPACE: 8,
  16168. /** Key constant @type Number */
  16169. TAB: 9,
  16170. /** Key constant @type Number */
  16171. NUM_CENTER: 12,
  16172. /** Key constant @type Number */
  16173. ENTER: 13,
  16174. /** Key constant @type Number */
  16175. RETURN: 13,
  16176. /** Key constant @type Number */
  16177. SHIFT: 16,
  16178. /** Key constant @type Number */
  16179. CTRL: 17,
  16180. /** Key constant @type Number */
  16181. ALT: 18,
  16182. /** Key constant @type Number */
  16183. PAUSE: 19,
  16184. /** Key constant @type Number */
  16185. CAPS_LOCK: 20,
  16186. /** Key constant @type Number */
  16187. ESC: 27,
  16188. /** Key constant @type Number */
  16189. SPACE: 32,
  16190. /** Key constant @type Number */
  16191. PAGE_UP: 33,
  16192. /** Key constant @type Number */
  16193. PAGE_DOWN: 34,
  16194. /** Key constant @type Number */
  16195. END: 35,
  16196. /** Key constant @type Number */
  16197. HOME: 36,
  16198. /** Key constant @type Number */
  16199. LEFT: 37,
  16200. /** Key constant @type Number */
  16201. UP: 38,
  16202. /** Key constant @type Number */
  16203. RIGHT: 39,
  16204. /** Key constant @type Number */
  16205. DOWN: 40,
  16206. /** Key constant @type Number */
  16207. PRINT_SCREEN: 44,
  16208. /** Key constant @type Number */
  16209. INSERT: 45,
  16210. /** Key constant @type Number */
  16211. DELETE: 46,
  16212. /** Key constant @type Number */
  16213. ZERO: 48,
  16214. /** Key constant @type Number */
  16215. ONE: 49,
  16216. /** Key constant @type Number */
  16217. TWO: 50,
  16218. /** Key constant @type Number */
  16219. THREE: 51,
  16220. /** Key constant @type Number */
  16221. FOUR: 52,
  16222. /** Key constant @type Number */
  16223. FIVE: 53,
  16224. /** Key constant @type Number */
  16225. SIX: 54,
  16226. /** Key constant @type Number */
  16227. SEVEN: 55,
  16228. /** Key constant @type Number */
  16229. EIGHT: 56,
  16230. /** Key constant @type Number */
  16231. NINE: 57,
  16232. /** Key constant @type Number */
  16233. A: 65,
  16234. /** Key constant @type Number */
  16235. B: 66,
  16236. /** Key constant @type Number */
  16237. C: 67,
  16238. /** Key constant @type Number */
  16239. D: 68,
  16240. /** Key constant @type Number */
  16241. E: 69,
  16242. /** Key constant @type Number */
  16243. F: 70,
  16244. /** Key constant @type Number */
  16245. G: 71,
  16246. /** Key constant @type Number */
  16247. H: 72,
  16248. /** Key constant @type Number */
  16249. I: 73,
  16250. /** Key constant @type Number */
  16251. J: 74,
  16252. /** Key constant @type Number */
  16253. K: 75,
  16254. /** Key constant @type Number */
  16255. L: 76,
  16256. /** Key constant @type Number */
  16257. M: 77,
  16258. /** Key constant @type Number */
  16259. N: 78,
  16260. /** Key constant @type Number */
  16261. O: 79,
  16262. /** Key constant @type Number */
  16263. P: 80,
  16264. /** Key constant @type Number */
  16265. Q: 81,
  16266. /** Key constant @type Number */
  16267. R: 82,
  16268. /** Key constant @type Number */
  16269. S: 83,
  16270. /** Key constant @type Number */
  16271. T: 84,
  16272. /** Key constant @type Number */
  16273. U: 85,
  16274. /** Key constant @type Number */
  16275. V: 86,
  16276. /** Key constant @type Number */
  16277. W: 87,
  16278. /** Key constant @type Number */
  16279. X: 88,
  16280. /** Key constant @type Number */
  16281. Y: 89,
  16282. /** Key constant @type Number */
  16283. Z: 90,
  16284. /** Key constant @type Number */
  16285. CONTEXT_MENU: 93,
  16286. /** Key constant @type Number */
  16287. NUM_ZERO: 96,
  16288. /** Key constant @type Number */
  16289. NUM_ONE: 97,
  16290. /** Key constant @type Number */
  16291. NUM_TWO: 98,
  16292. /** Key constant @type Number */
  16293. NUM_THREE: 99,
  16294. /** Key constant @type Number */
  16295. NUM_FOUR: 100,
  16296. /** Key constant @type Number */
  16297. NUM_FIVE: 101,
  16298. /** Key constant @type Number */
  16299. NUM_SIX: 102,
  16300. /** Key constant @type Number */
  16301. NUM_SEVEN: 103,
  16302. /** Key constant @type Number */
  16303. NUM_EIGHT: 104,
  16304. /** Key constant @type Number */
  16305. NUM_NINE: 105,
  16306. /** Key constant @type Number */
  16307. NUM_MULTIPLY: 106,
  16308. /** Key constant @type Number */
  16309. NUM_PLUS: 107,
  16310. /** Key constant @type Number */
  16311. NUM_MINUS: 109,
  16312. /** Key constant @type Number */
  16313. NUM_PERIOD: 110,
  16314. /** Key constant @type Number */
  16315. NUM_DIVISION: 111,
  16316. /** Key constant @type Number */
  16317. F1: 112,
  16318. /** Key constant @type Number */
  16319. F2: 113,
  16320. /** Key constant @type Number */
  16321. F3: 114,
  16322. /** Key constant @type Number */
  16323. F4: 115,
  16324. /** Key constant @type Number */
  16325. F5: 116,
  16326. /** Key constant @type Number */
  16327. F6: 117,
  16328. /** Key constant @type Number */
  16329. F7: 118,
  16330. /** Key constant @type Number */
  16331. F8: 119,
  16332. /** Key constant @type Number */
  16333. F9: 120,
  16334. /** Key constant @type Number */
  16335. F10: 121,
  16336. /** Key constant @type Number */
  16337. F11: 122,
  16338. /** Key constant @type Number */
  16339. F12: 123,
  16340. /**
  16341. * The mouse wheel delta scaling factor. This value depends on browser version and OS and
  16342. * attempts to produce a similar scrolling experience across all platforms and browsers.
  16343. *
  16344. * To change this value:
  16345. *
  16346. * Ext.EventObjectImpl.prototype.WHEEL_SCALE = 72;
  16347. *
  16348. * @type Number
  16349. * @markdown
  16350. */
  16351. WHEEL_SCALE: (function () {
  16352. var scale;
  16353. if (Ext.isGecko) {
  16354. // Firefox uses 3 on all platforms
  16355. scale = 3;
  16356. } else if (Ext.isMac) {
  16357. // Continuous scrolling devices have momentum and produce much more scroll than
  16358. // discrete devices on the same OS and browser. To make things exciting, Safari
  16359. // (and not Chrome) changed from small values to 120 (like IE).
  16360. if (Ext.isSafari && Ext.webKitVersion >= 532.0) {
  16361. // Safari changed the scrolling factor to match IE (for details see
  16362. // https://bugs.webkit.org/show_bug.cgi?id=24368). The WebKit version where this
  16363. // change was introduced was 532.0
  16364. // Detailed discussion:
  16365. // https://bugs.webkit.org/show_bug.cgi?id=29601
  16366. // http://trac.webkit.org/browser/trunk/WebKit/chromium/src/mac/WebInputEventFactory.mm#L1063
  16367. scale = 120;
  16368. } else {
  16369. // MS optical wheel mouse produces multiples of 12 which is close enough
  16370. // to help tame the speed of the continuous mice...
  16371. scale = 12;
  16372. }
  16373. // Momentum scrolling produces very fast scrolling, so increase the scale factor
  16374. // to help produce similar results cross platform. This could be even larger and
  16375. // it would help those mice, but other mice would become almost unusable as a
  16376. // result (since we cannot tell which device type is in use).
  16377. scale *= 3;
  16378. } else {
  16379. // IE, Opera and other Windows browsers use 120.
  16380. scale = 120;
  16381. }
  16382. return scale;
  16383. })(),
  16384. /**
  16385. * Simple click regex
  16386. * @private
  16387. */
  16388. clickRe: /(dbl)?click/,
  16389. // safari keypress events for special keys return bad keycodes
  16390. safariKeys: {
  16391. 3: 13, // enter
  16392. 63234: 37, // left
  16393. 63235: 39, // right
  16394. 63232: 38, // up
  16395. 63233: 40, // down
  16396. 63276: 33, // page up
  16397. 63277: 34, // page down
  16398. 63272: 46, // delete
  16399. 63273: 36, // home
  16400. 63275: 35 // end
  16401. },
  16402. // normalize button clicks, don't see any way to feature detect this.
  16403. btnMap: Ext.isIE ? {
  16404. 1: 0,
  16405. 4: 1,
  16406. 2: 2
  16407. } : {
  16408. 0: 0,
  16409. 1: 1,
  16410. 2: 2
  16411. },
  16412. constructor: function(event, freezeEvent){
  16413. if (event) {
  16414. this.setEvent(event.browserEvent || event, freezeEvent);
  16415. }
  16416. },
  16417. setEvent: function(event, freezeEvent){
  16418. var me = this, button, options;
  16419. if (event == me || (event && event.browserEvent)) { // already wrapped
  16420. return event;
  16421. }
  16422. me.browserEvent = event;
  16423. if (event) {
  16424. // normalize buttons
  16425. button = event.button ? me.btnMap[event.button] : (event.which ? event.which - 1 : -1);
  16426. if (me.clickRe.test(event.type) && button == -1) {
  16427. button = 0;
  16428. }
  16429. options = {
  16430. type: event.type,
  16431. button: button,
  16432. shiftKey: event.shiftKey,
  16433. // mac metaKey behaves like ctrlKey
  16434. ctrlKey: event.ctrlKey || event.metaKey || false,
  16435. altKey: event.altKey,
  16436. // in getKey these will be normalized for the mac
  16437. keyCode: event.keyCode,
  16438. charCode: event.charCode,
  16439. // cache the targets for the delayed and or buffered events
  16440. target: Ext.EventManager.getTarget(event),
  16441. relatedTarget: Ext.EventManager.getRelatedTarget(event),
  16442. currentTarget: event.currentTarget,
  16443. xy: (freezeEvent ? me.getXY() : null)
  16444. };
  16445. } else {
  16446. options = {
  16447. button: -1,
  16448. shiftKey: false,
  16449. ctrlKey: false,
  16450. altKey: false,
  16451. keyCode: 0,
  16452. charCode: 0,
  16453. target: null,
  16454. xy: [0, 0]
  16455. };
  16456. }
  16457. Ext.apply(me, options);
  16458. return me;
  16459. },
  16460. /**
  16461. * Stop the event (preventDefault and stopPropagation)
  16462. */
  16463. stopEvent: function(){
  16464. this.stopPropagation();
  16465. this.preventDefault();
  16466. },
  16467. /**
  16468. * Prevents the browsers default handling of the event.
  16469. */
  16470. preventDefault: function(){
  16471. if (this.browserEvent) {
  16472. Ext.EventManager.preventDefault(this.browserEvent);
  16473. }
  16474. },
  16475. /**
  16476. * Cancels bubbling of the event.
  16477. */
  16478. stopPropagation: function(){
  16479. var browserEvent = this.browserEvent;
  16480. if (browserEvent) {
  16481. if (browserEvent.type == 'mousedown') {
  16482. Ext.EventManager.stoppedMouseDownEvent.fire(this);
  16483. }
  16484. Ext.EventManager.stopPropagation(browserEvent);
  16485. }
  16486. },
  16487. /**
  16488. * Gets the character code for the event.
  16489. * @return {Number}
  16490. */
  16491. getCharCode: function(){
  16492. return this.charCode || this.keyCode;
  16493. },
  16494. /**
  16495. * Returns a normalized keyCode for the event.
  16496. * @return {Number} The key code
  16497. */
  16498. getKey: function(){
  16499. return this.normalizeKey(this.keyCode || this.charCode);
  16500. },
  16501. /**
  16502. * Normalize key codes across browsers
  16503. * @private
  16504. * @param {Number} key The key code
  16505. * @return {Number} The normalized code
  16506. */
  16507. normalizeKey: function(key){
  16508. // can't feature detect this
  16509. return Ext.isWebKit ? (this.safariKeys[key] || key) : key;
  16510. },
  16511. /**
  16512. * Gets the x coordinate of the event.
  16513. * @return {Number}
  16514. * @deprecated 4.0 Replaced by {@link #getX}
  16515. */
  16516. getPageX: function(){
  16517. return this.getX();
  16518. },
  16519. /**
  16520. * Gets the y coordinate of the event.
  16521. * @return {Number}
  16522. * @deprecated 4.0 Replaced by {@link #getY}
  16523. */
  16524. getPageY: function(){
  16525. return this.getY();
  16526. },
  16527. /**
  16528. * Gets the x coordinate of the event.
  16529. * @return {Number}
  16530. */
  16531. getX: function() {
  16532. return this.getXY()[0];
  16533. },
  16534. /**
  16535. * Gets the y coordinate of the event.
  16536. * @return {Number}
  16537. */
  16538. getY: function() {
  16539. return this.getXY()[1];
  16540. },
  16541. /**
  16542. * Gets the page coordinates of the event.
  16543. * @return {Number[]} The xy values like [x, y]
  16544. */
  16545. getXY: function() {
  16546. if (!this.xy) {
  16547. // same for XY
  16548. this.xy = Ext.EventManager.getPageXY(this.browserEvent);
  16549. }
  16550. return this.xy;
  16551. },
  16552. /**
  16553. * Gets the target for the event.
  16554. * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
  16555. * @param {Number/HTMLElement} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body)
  16556. * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
  16557. * @return {HTMLElement}
  16558. */
  16559. getTarget : function(selector, maxDepth, returnEl){
  16560. if (selector) {
  16561. return Ext.fly(this.target).findParent(selector, maxDepth, returnEl);
  16562. }
  16563. return returnEl ? Ext.get(this.target) : this.target;
  16564. },
  16565. /**
  16566. * Gets the related target.
  16567. * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
  16568. * @param {Number/HTMLElement} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body)
  16569. * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
  16570. * @return {HTMLElement}
  16571. */
  16572. getRelatedTarget : function(selector, maxDepth, returnEl){
  16573. if (selector) {
  16574. return Ext.fly(this.relatedTarget).findParent(selector, maxDepth, returnEl);
  16575. }
  16576. return returnEl ? Ext.get(this.relatedTarget) : this.relatedTarget;
  16577. },
  16578. /**
  16579. * Correctly scales a given wheel delta.
  16580. * @param {Number} delta The delta value.
  16581. */
  16582. correctWheelDelta : function (delta) {
  16583. var scale = this.WHEEL_SCALE,
  16584. ret = Math.round(delta / scale);
  16585. if (!ret && delta) {
  16586. ret = (delta < 0) ? -1 : 1; // don't allow non-zero deltas to go to zero!
  16587. }
  16588. return ret;
  16589. },
  16590. /**
  16591. * Returns the mouse wheel deltas for this event.
  16592. * @return {Object} An object with "x" and "y" properties holding the mouse wheel deltas.
  16593. */
  16594. getWheelDeltas : function () {
  16595. var me = this,
  16596. event = me.browserEvent,
  16597. dx = 0, dy = 0; // the deltas
  16598. if (Ext.isDefined(event.wheelDeltaX)) { // WebKit has both dimensions
  16599. dx = event.wheelDeltaX;
  16600. dy = event.wheelDeltaY;
  16601. } else if (event.wheelDelta) { // old WebKit and IE
  16602. dy = event.wheelDelta;
  16603. } else if (event.detail) { // Gecko
  16604. dy = -event.detail; // gecko is backwards
  16605. // Gecko sometimes returns really big values if the user changes settings to
  16606. // scroll a whole page per scroll
  16607. if (dy > 100) {
  16608. dy = 3;
  16609. } else if (dy < -100) {
  16610. dy = -3;
  16611. }
  16612. // Firefox 3.1 adds an axis field to the event to indicate direction of
  16613. // scroll. See https://developer.mozilla.org/en/Gecko-Specific_DOM_Events
  16614. if (Ext.isDefined(event.axis) && event.axis === event.HORIZONTAL_AXIS) {
  16615. dx = dy;
  16616. dy = 0;
  16617. }
  16618. }
  16619. return {
  16620. x: me.correctWheelDelta(dx),
  16621. y: me.correctWheelDelta(dy)
  16622. };
  16623. },
  16624. /**
  16625. * Normalizes mouse wheel y-delta across browsers. To get x-delta information, use
  16626. * {@link #getWheelDeltas} instead.
  16627. * @return {Number} The mouse wheel y-delta
  16628. */
  16629. getWheelDelta : function(){
  16630. var deltas = this.getWheelDeltas();
  16631. return deltas.y;
  16632. },
  16633. /**
  16634. * Returns true if the target of this event is a child of el. Unless the allowEl parameter is set, it will return false if if the target is el.
  16635. * Example usage:<pre><code>
  16636. // Handle click on any child of an element
  16637. Ext.getBody().on('click', function(e){
  16638. if(e.within('some-el')){
  16639. alert('Clicked on a child of some-el!');
  16640. }
  16641. });
  16642. // Handle click directly on an element, ignoring clicks on child nodes
  16643. Ext.getBody().on('click', function(e,t){
  16644. if((t.id == 'some-el') && !e.within(t, true)){
  16645. alert('Clicked directly on some-el!');
  16646. }
  16647. });
  16648. </code></pre>
  16649. * @param {String/HTMLElement/Ext.Element} el The id, DOM element or Ext.Element to check
  16650. * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
  16651. * @param {Boolean} allowEl (optional) true to also check if the passed element is the target or related target
  16652. * @return {Boolean}
  16653. */
  16654. within : function(el, related, allowEl){
  16655. if(el){
  16656. var t = related ? this.getRelatedTarget() : this.getTarget(),
  16657. result;
  16658. if (t) {
  16659. result = Ext.fly(el).contains(t);
  16660. if (!result && allowEl) {
  16661. result = t == Ext.getDom(el);
  16662. }
  16663. return result;
  16664. }
  16665. }
  16666. return false;
  16667. },
  16668. /**
  16669. * Checks if the key pressed was a "navigation" key
  16670. * @return {Boolean} True if the press is a navigation keypress
  16671. */
  16672. isNavKeyPress : function(){
  16673. var me = this,
  16674. k = this.normalizeKey(me.keyCode);
  16675. return (k >= 33 && k <= 40) || // Page Up/Down, End, Home, Left, Up, Right, Down
  16676. k == me.RETURN ||
  16677. k == me.TAB ||
  16678. k == me.ESC;
  16679. },
  16680. /**
  16681. * Checks if the key pressed was a "special" key
  16682. * @return {Boolean} True if the press is a special keypress
  16683. */
  16684. isSpecialKey : function(){
  16685. var k = this.normalizeKey(this.keyCode);
  16686. return (this.type == 'keypress' && this.ctrlKey) ||
  16687. this.isNavKeyPress() ||
  16688. (k == this.BACKSPACE) || // Backspace
  16689. (k >= 16 && k <= 20) || // Shift, Ctrl, Alt, Pause, Caps Lock
  16690. (k >= 44 && k <= 46); // Print Screen, Insert, Delete
  16691. },
  16692. /**
  16693. * Returns a point object that consists of the object coordinates.
  16694. * @return {Ext.util.Point} point
  16695. */
  16696. getPoint : function(){
  16697. var xy = this.getXY();
  16698. return Ext.create('Ext.util.Point', xy[0], xy[1]);
  16699. },
  16700. /**
  16701. * Returns true if the control, meta, shift or alt key was pressed during this event.
  16702. * @return {Boolean}
  16703. */
  16704. hasModifier : function(){
  16705. return this.ctrlKey || this.altKey || this.shiftKey || this.metaKey;
  16706. },
  16707. /**
  16708. * Injects a DOM event using the data in this object and (optionally) a new target.
  16709. * This is a low-level technique and not likely to be used by application code. The
  16710. * currently supported event types are:
  16711. * <p><b>HTMLEvents</b></p>
  16712. * <ul>
  16713. * <li>load</li>
  16714. * <li>unload</li>
  16715. * <li>select</li>
  16716. * <li>change</li>
  16717. * <li>submit</li>
  16718. * <li>reset</li>
  16719. * <li>resize</li>
  16720. * <li>scroll</li>
  16721. * </ul>
  16722. * <p><b>MouseEvents</b></p>
  16723. * <ul>
  16724. * <li>click</li>
  16725. * <li>dblclick</li>
  16726. * <li>mousedown</li>
  16727. * <li>mouseup</li>
  16728. * <li>mouseover</li>
  16729. * <li>mousemove</li>
  16730. * <li>mouseout</li>
  16731. * </ul>
  16732. * <p><b>UIEvents</b></p>
  16733. * <ul>
  16734. * <li>focusin</li>
  16735. * <li>focusout</li>
  16736. * <li>activate</li>
  16737. * <li>focus</li>
  16738. * <li>blur</li>
  16739. * </ul>
  16740. * @param {Ext.Element/HTMLElement} target (optional) If specified, the target for the event. This
  16741. * is likely to be used when relaying a DOM event. If not specified, {@link #getTarget}
  16742. * is used to determine the target.
  16743. */
  16744. injectEvent: function () {
  16745. var API,
  16746. dispatchers = {}; // keyed by event type (e.g., 'mousedown')
  16747. // Good reference: http://developer.yahoo.com/yui/docs/UserAction.js.html
  16748. // IE9 has createEvent, but this code causes major problems with htmleditor (it
  16749. // blocks all mouse events and maybe more). TODO
  16750. if (!Ext.isIE && document.createEvent) { // if (DOM compliant)
  16751. API = {
  16752. createHtmlEvent: function (doc, type, bubbles, cancelable) {
  16753. var event = doc.createEvent('HTMLEvents');
  16754. event.initEvent(type, bubbles, cancelable);
  16755. return event;
  16756. },
  16757. createMouseEvent: function (doc, type, bubbles, cancelable, detail,
  16758. clientX, clientY, ctrlKey, altKey, shiftKey, metaKey,
  16759. button, relatedTarget) {
  16760. var event = doc.createEvent('MouseEvents'),
  16761. view = doc.defaultView || window;
  16762. if (event.initMouseEvent) {
  16763. event.initMouseEvent(type, bubbles, cancelable, view, detail,
  16764. clientX, clientY, clientX, clientY, ctrlKey, altKey,
  16765. shiftKey, metaKey, button, relatedTarget);
  16766. } else { // old Safari
  16767. event = doc.createEvent('UIEvents');
  16768. event.initEvent(type, bubbles, cancelable);
  16769. event.view = view;
  16770. event.detail = detail;
  16771. event.screenX = clientX;
  16772. event.screenY = clientY;
  16773. event.clientX = clientX;
  16774. event.clientY = clientY;
  16775. event.ctrlKey = ctrlKey;
  16776. event.altKey = altKey;
  16777. event.metaKey = metaKey;
  16778. event.shiftKey = shiftKey;
  16779. event.button = button;
  16780. event.relatedTarget = relatedTarget;
  16781. }
  16782. return event;
  16783. },
  16784. createUIEvent: function (doc, type, bubbles, cancelable, detail) {
  16785. var event = doc.createEvent('UIEvents'),
  16786. view = doc.defaultView || window;
  16787. event.initUIEvent(type, bubbles, cancelable, view, detail);
  16788. return event;
  16789. },
  16790. fireEvent: function (target, type, event) {
  16791. target.dispatchEvent(event);
  16792. },
  16793. fixTarget: function (target) {
  16794. // Safari3 doesn't have window.dispatchEvent()
  16795. if (target == window && !target.dispatchEvent) {
  16796. return document;
  16797. }
  16798. return target;
  16799. }
  16800. };
  16801. } else if (document.createEventObject) { // else if (IE)
  16802. var crazyIEButtons = { 0: 1, 1: 4, 2: 2 };
  16803. API = {
  16804. createHtmlEvent: function (doc, type, bubbles, cancelable) {
  16805. var event = doc.createEventObject();
  16806. event.bubbles = bubbles;
  16807. event.cancelable = cancelable;
  16808. return event;
  16809. },
  16810. createMouseEvent: function (doc, type, bubbles, cancelable, detail,
  16811. clientX, clientY, ctrlKey, altKey, shiftKey, metaKey,
  16812. button, relatedTarget) {
  16813. var event = doc.createEventObject();
  16814. event.bubbles = bubbles;
  16815. event.cancelable = cancelable;
  16816. event.detail = detail;
  16817. event.screenX = clientX;
  16818. event.screenY = clientY;
  16819. event.clientX = clientX;
  16820. event.clientY = clientY;
  16821. event.ctrlKey = ctrlKey;
  16822. event.altKey = altKey;
  16823. event.shiftKey = shiftKey;
  16824. event.metaKey = metaKey;
  16825. event.button = crazyIEButtons[button] || button;
  16826. event.relatedTarget = relatedTarget; // cannot assign to/fromElement
  16827. return event;
  16828. },
  16829. createUIEvent: function (doc, type, bubbles, cancelable, detail) {
  16830. var event = doc.createEventObject();
  16831. event.bubbles = bubbles;
  16832. event.cancelable = cancelable;
  16833. return event;
  16834. },
  16835. fireEvent: function (target, type, event) {
  16836. target.fireEvent('on' + type, event);
  16837. },
  16838. fixTarget: function (target) {
  16839. if (target == document) {
  16840. // IE6,IE7 thinks window==document and doesn't have window.fireEvent()
  16841. // IE6,IE7 cannot properly call document.fireEvent()
  16842. return document.documentElement;
  16843. }
  16844. return target;
  16845. }
  16846. };
  16847. }
  16848. //----------------
  16849. // HTMLEvents
  16850. Ext.Object.each({
  16851. load: [false, false],
  16852. unload: [false, false],
  16853. select: [true, false],
  16854. change: [true, false],
  16855. submit: [true, true],
  16856. reset: [true, false],
  16857. resize: [true, false],
  16858. scroll: [true, false]
  16859. },
  16860. function (name, value) {
  16861. var bubbles = value[0], cancelable = value[1];
  16862. dispatchers[name] = function (targetEl, srcEvent) {
  16863. var e = API.createHtmlEvent(name, bubbles, cancelable);
  16864. API.fireEvent(targetEl, name, e);
  16865. };
  16866. });
  16867. //----------------
  16868. // MouseEvents
  16869. function createMouseEventDispatcher (type, detail) {
  16870. var cancelable = (type != 'mousemove');
  16871. return function (targetEl, srcEvent) {
  16872. var xy = srcEvent.getXY(),
  16873. e = API.createMouseEvent(targetEl.ownerDocument, type, true, cancelable,
  16874. detail, xy[0], xy[1], srcEvent.ctrlKey, srcEvent.altKey,
  16875. srcEvent.shiftKey, srcEvent.metaKey, srcEvent.button,
  16876. srcEvent.relatedTarget);
  16877. API.fireEvent(targetEl, type, e);
  16878. };
  16879. }
  16880. Ext.each(['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mousemove', 'mouseout'],
  16881. function (eventName) {
  16882. dispatchers[eventName] = createMouseEventDispatcher(eventName, 1);
  16883. });
  16884. //----------------
  16885. // UIEvents
  16886. Ext.Object.each({
  16887. focusin: [true, false],
  16888. focusout: [true, false],
  16889. activate: [true, true],
  16890. focus: [false, false],
  16891. blur: [false, false]
  16892. },
  16893. function (name, value) {
  16894. var bubbles = value[0], cancelable = value[1];
  16895. dispatchers[name] = function (targetEl, srcEvent) {
  16896. var e = API.createUIEvent(targetEl.ownerDocument, name, bubbles, cancelable, 1);
  16897. API.fireEvent(targetEl, name, e);
  16898. };
  16899. });
  16900. //---------
  16901. if (!API) {
  16902. // not even sure what ancient browsers fall into this category...
  16903. dispatchers = {}; // never mind all those we just built :P
  16904. API = {
  16905. fixTarget: function (t) {
  16906. return t;
  16907. }
  16908. };
  16909. }
  16910. function cannotInject (target, srcEvent) {
  16911. }
  16912. return function (target) {
  16913. var me = this,
  16914. dispatcher = dispatchers[me.type] || cannotInject,
  16915. t = target ? (target.dom || target) : me.getTarget();
  16916. t = API.fixTarget(t);
  16917. dispatcher(t, me);
  16918. };
  16919. }() // call to produce method
  16920. }, function() {
  16921. Ext.EventObject = new Ext.EventObjectImpl();
  16922. });
  16923. /**
  16924. * @class Ext.Element
  16925. */
  16926. (function(){
  16927. var doc = document,
  16928. activeElement = null,
  16929. isCSS1 = doc.compatMode == "CSS1Compat",
  16930. ELEMENT = Ext.Element,
  16931. fly = function(el){
  16932. if (!_fly) {
  16933. _fly = new Ext.Element.Flyweight();
  16934. }
  16935. _fly.dom = el;
  16936. return _fly;
  16937. }, _fly;
  16938. // If the browser does not support document.activeElement we need some assistance.
  16939. // This covers old Safari 3.2 (4.0 added activeElement along with just about all
  16940. // other browsers). We need this support to handle issues with old Safari.
  16941. if (!('activeElement' in doc) && doc.addEventListener) {
  16942. doc.addEventListener('focus',
  16943. function (ev) {
  16944. if (ev && ev.target) {
  16945. activeElement = (ev.target == doc) ? null : ev.target;
  16946. }
  16947. }, true);
  16948. }
  16949. /*
  16950. * Helper function to create the function that will restore the selection.
  16951. */
  16952. function makeSelectionRestoreFn (activeEl, start, end) {
  16953. return function () {
  16954. activeEl.selectionStart = start;
  16955. activeEl.selectionEnd = end;
  16956. };
  16957. }
  16958. Ext.apply(ELEMENT, {
  16959. isAncestor : function(p, c) {
  16960. var ret = false;
  16961. p = Ext.getDom(p);
  16962. c = Ext.getDom(c);
  16963. if (p && c) {
  16964. if (p.contains) {
  16965. return p.contains(c);
  16966. } else if (p.compareDocumentPosition) {
  16967. return !!(p.compareDocumentPosition(c) & 16);
  16968. } else {
  16969. while ((c = c.parentNode)) {
  16970. ret = c == p || ret;
  16971. }
  16972. }
  16973. }
  16974. return ret;
  16975. },
  16976. /**
  16977. * Returns the active element in the DOM. If the browser supports activeElement
  16978. * on the document, this is returned. If not, the focus is tracked and the active
  16979. * element is maintained internally.
  16980. * @return {HTMLElement} The active (focused) element in the document.
  16981. */
  16982. getActiveElement: function () {
  16983. return doc.activeElement || activeElement;
  16984. },
  16985. /**
  16986. * Creates a function to call to clean up problems with the work-around for the
  16987. * WebKit RightMargin bug. The work-around is to add "display: 'inline-block'" to
  16988. * the element before calling getComputedStyle and then to restore its original
  16989. * display value. The problem with this is that it corrupts the selection of an
  16990. * INPUT or TEXTAREA element (as in the "I-beam" goes away but ths focus remains).
  16991. * To cleanup after this, we need to capture the selection of any such element and
  16992. * then restore it after we have restored the display style.
  16993. *
  16994. * @param target {Element} The top-most element being adjusted.
  16995. * @private
  16996. */
  16997. getRightMarginFixCleaner: function (target) {
  16998. var supports = Ext.supports,
  16999. hasInputBug = supports.DisplayChangeInputSelectionBug,
  17000. hasTextAreaBug = supports.DisplayChangeTextAreaSelectionBug;
  17001. if (hasInputBug || hasTextAreaBug) {
  17002. var activeEl = doc.activeElement || activeElement, // save a call
  17003. tag = activeEl && activeEl.tagName,
  17004. start,
  17005. end;
  17006. if ((hasTextAreaBug && tag == 'TEXTAREA') ||
  17007. (hasInputBug && tag == 'INPUT' && activeEl.type == 'text')) {
  17008. if (ELEMENT.isAncestor(target, activeEl)) {
  17009. start = activeEl.selectionStart;
  17010. end = activeEl.selectionEnd;
  17011. if (Ext.isNumber(start) && Ext.isNumber(end)) { // to be safe...
  17012. // We don't create the raw closure here inline because that
  17013. // will be costly even if we don't want to return it (nested
  17014. // function decls and exprs are often instantiated on entry
  17015. // regardless of whether execution ever reaches them):
  17016. return makeSelectionRestoreFn(activeEl, start, end);
  17017. }
  17018. }
  17019. }
  17020. }
  17021. return Ext.emptyFn; // avoid special cases, just return a nop
  17022. },
  17023. getViewWidth : function(full) {
  17024. return full ? ELEMENT.getDocumentWidth() : ELEMENT.getViewportWidth();
  17025. },
  17026. getViewHeight : function(full) {
  17027. return full ? ELEMENT.getDocumentHeight() : ELEMENT.getViewportHeight();
  17028. },
  17029. getDocumentHeight: function() {
  17030. return Math.max(!isCSS1 ? doc.body.scrollHeight : doc.documentElement.scrollHeight, ELEMENT.getViewportHeight());
  17031. },
  17032. getDocumentWidth: function() {
  17033. return Math.max(!isCSS1 ? doc.body.scrollWidth : doc.documentElement.scrollWidth, ELEMENT.getViewportWidth());
  17034. },
  17035. getViewportHeight: function(){
  17036. return Ext.isIE ?
  17037. (Ext.isStrict ? doc.documentElement.clientHeight : doc.body.clientHeight) :
  17038. self.innerHeight;
  17039. },
  17040. getViewportWidth : function() {
  17041. return (!Ext.isStrict && !Ext.isOpera) ? doc.body.clientWidth :
  17042. Ext.isIE ? doc.documentElement.clientWidth : self.innerWidth;
  17043. },
  17044. getY : function(el) {
  17045. return ELEMENT.getXY(el)[1];
  17046. },
  17047. getX : function(el) {
  17048. return ELEMENT.getXY(el)[0];
  17049. },
  17050. getOffsetParent: function (el) {
  17051. el = Ext.getDom(el);
  17052. try {
  17053. // accessing offsetParent can throw "Unspecified Error" in IE6-8 (not 9)
  17054. return el.offsetParent;
  17055. } catch (e) {
  17056. var body = document.body; // safe bet, unless...
  17057. return (el == body) ? null : body;
  17058. }
  17059. },
  17060. getXY : function(el) {
  17061. var p,
  17062. pe,
  17063. b,
  17064. bt,
  17065. bl,
  17066. dbd,
  17067. x = 0,
  17068. y = 0,
  17069. scroll,
  17070. hasAbsolute,
  17071. bd = (doc.body || doc.documentElement),
  17072. ret;
  17073. el = Ext.getDom(el);
  17074. if(el != bd){
  17075. hasAbsolute = fly(el).isStyle("position", "absolute");
  17076. if (el.getBoundingClientRect) {
  17077. try {
  17078. b = el.getBoundingClientRect();
  17079. scroll = fly(document).getScroll();
  17080. ret = [ Math.round(b.left + scroll.left), Math.round(b.top + scroll.top) ];
  17081. } catch (e) {
  17082. // IE6-8 can also throw from getBoundingClientRect...
  17083. }
  17084. }
  17085. if (!ret) {
  17086. for (p = el; p; p = ELEMENT.getOffsetParent(p)) {
  17087. pe = fly(p);
  17088. x += p.offsetLeft;
  17089. y += p.offsetTop;
  17090. hasAbsolute = hasAbsolute || pe.isStyle("position", "absolute");
  17091. if (Ext.isGecko) {
  17092. y += bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
  17093. x += bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
  17094. if (p != el && !pe.isStyle('overflow','visible')) {
  17095. x += bl;
  17096. y += bt;
  17097. }
  17098. }
  17099. }
  17100. if (Ext.isSafari && hasAbsolute) {
  17101. x -= bd.offsetLeft;
  17102. y -= bd.offsetTop;
  17103. }
  17104. if (Ext.isGecko && !hasAbsolute) {
  17105. dbd = fly(bd);
  17106. x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
  17107. y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
  17108. }
  17109. p = el.parentNode;
  17110. while (p && p != bd) {
  17111. if (!Ext.isOpera || (p.tagName != 'TR' && !fly(p).isStyle("display", "inline"))) {
  17112. x -= p.scrollLeft;
  17113. y -= p.scrollTop;
  17114. }
  17115. p = p.parentNode;
  17116. }
  17117. ret = [x,y];
  17118. }
  17119. }
  17120. return ret || [0,0];
  17121. },
  17122. setXY : function(el, xy) {
  17123. (el = Ext.fly(el, '_setXY')).position();
  17124. var pts = el.translatePoints(xy),
  17125. style = el.dom.style,
  17126. pos;
  17127. for (pos in pts) {
  17128. if (!isNaN(pts[pos])) {
  17129. style[pos] = pts[pos] + "px";
  17130. }
  17131. }
  17132. },
  17133. setX : function(el, x) {
  17134. ELEMENT.setXY(el, [x, false]);
  17135. },
  17136. setY : function(el, y) {
  17137. ELEMENT.setXY(el, [false, y]);
  17138. },
  17139. /**
  17140. * Serializes a DOM form into a url encoded string
  17141. * @param {Object} form The form
  17142. * @return {String} The url encoded form
  17143. */
  17144. serializeForm: function(form) {
  17145. var fElements = form.elements || (document.forms[form] || Ext.getDom(form)).elements,
  17146. hasSubmit = false,
  17147. encoder = encodeURIComponent,
  17148. name,
  17149. data = '',
  17150. type,
  17151. hasValue;
  17152. Ext.each(fElements, function(element){
  17153. name = element.name;
  17154. type = element.type;
  17155. if (!element.disabled && name) {
  17156. if (/select-(one|multiple)/i.test(type)) {
  17157. Ext.each(element.options, function(opt){
  17158. if (opt.selected) {
  17159. hasValue = opt.hasAttribute ? opt.hasAttribute('value') : opt.getAttributeNode('value').specified;
  17160. data += Ext.String.format("{0}={1}&", encoder(name), encoder(hasValue ? opt.value : opt.text));
  17161. }
  17162. });
  17163. } else if (!(/file|undefined|reset|button/i.test(type))) {
  17164. if (!(/radio|checkbox/i.test(type) && !element.checked) && !(type == 'submit' && hasSubmit)) {
  17165. data += encoder(name) + '=' + encoder(element.value) + '&';
  17166. hasSubmit = /submit/i.test(type);
  17167. }
  17168. }
  17169. }
  17170. });
  17171. return data.substr(0, data.length - 1);
  17172. }
  17173. });
  17174. })();
  17175. /**
  17176. * @class Ext.Element
  17177. */
  17178. Ext.Element.addMethods((function(){
  17179. var focusRe = /button|input|textarea|select|object/;
  17180. return {
  17181. /**
  17182. * Monitors this Element for the mouse leaving. Calls the function after the specified delay only if
  17183. * the mouse was not moved back into the Element within the delay. If the mouse <i>was</i> moved
  17184. * back in, the function is not called.
  17185. * @param {Number} delay The delay <b>in milliseconds</b> to wait for possible mouse re-entry before calling the handler function.
  17186. * @param {Function} handler The function to call if the mouse remains outside of this Element for the specified time.
  17187. * @param {Object} scope The scope (<code>this</code> reference) in which the handler function executes. Defaults to this Element.
  17188. * @return {Object} The listeners object which was added to this element so that monitoring can be stopped. Example usage:<pre><code>
  17189. // Hide the menu if the mouse moves out for 250ms or more
  17190. this.mouseLeaveMonitor = this.menuEl.monitorMouseLeave(250, this.hideMenu, this);
  17191. ...
  17192. // Remove mouseleave monitor on menu destroy
  17193. this.menuEl.un(this.mouseLeaveMonitor);
  17194. </code></pre>
  17195. */
  17196. monitorMouseLeave: function(delay, handler, scope) {
  17197. var me = this,
  17198. timer,
  17199. listeners = {
  17200. mouseleave: function(e) {
  17201. timer = setTimeout(Ext.Function.bind(handler, scope||me, [e]), delay);
  17202. },
  17203. mouseenter: function() {
  17204. clearTimeout(timer);
  17205. },
  17206. freezeEvent: true
  17207. };
  17208. me.on(listeners);
  17209. return listeners;
  17210. },
  17211. /**
  17212. * Stops the specified event(s) from bubbling and optionally prevents the default action
  17213. * @param {String/String[]} eventName an event / array of events to stop from bubbling
  17214. * @param {Boolean} preventDefault (optional) true to prevent the default action too
  17215. * @return {Ext.Element} this
  17216. */
  17217. swallowEvent : function(eventName, preventDefault) {
  17218. var me = this;
  17219. function fn(e) {
  17220. e.stopPropagation();
  17221. if (preventDefault) {
  17222. e.preventDefault();
  17223. }
  17224. }
  17225. if (Ext.isArray(eventName)) {
  17226. Ext.each(eventName, function(e) {
  17227. me.on(e, fn);
  17228. });
  17229. return me;
  17230. }
  17231. me.on(eventName, fn);
  17232. return me;
  17233. },
  17234. /**
  17235. * Create an event handler on this element such that when the event fires and is handled by this element,
  17236. * it will be relayed to another object (i.e., fired again as if it originated from that object instead).
  17237. * @param {String} eventName The type of event to relay
  17238. * @param {Object} object Any object that extends {@link Ext.util.Observable} that will provide the context
  17239. * for firing the relayed event
  17240. */
  17241. relayEvent : function(eventName, observable) {
  17242. this.on(eventName, function(e) {
  17243. observable.fireEvent(eventName, e);
  17244. });
  17245. },
  17246. /**
  17247. * Removes Empty, or whitespace filled text nodes. Combines adjacent text nodes.
  17248. * @param {Boolean} forceReclean (optional) By default the element
  17249. * keeps track if it has been cleaned already so
  17250. * you can call this over and over. However, if you update the element and
  17251. * need to force a reclean, you can pass true.
  17252. */
  17253. clean : function(forceReclean) {
  17254. var me = this,
  17255. dom = me.dom,
  17256. n = dom.firstChild,
  17257. nx,
  17258. ni = -1;
  17259. if (Ext.Element.data(dom, 'isCleaned') && forceReclean !== true) {
  17260. return me;
  17261. }
  17262. while (n) {
  17263. nx = n.nextSibling;
  17264. if (n.nodeType == 3) {
  17265. // Remove empty/whitespace text nodes
  17266. if (!(/\S/.test(n.nodeValue))) {
  17267. dom.removeChild(n);
  17268. // Combine adjacent text nodes
  17269. } else if (nx && nx.nodeType == 3) {
  17270. n.appendData(Ext.String.trim(nx.data));
  17271. dom.removeChild(nx);
  17272. nx = n.nextSibling;
  17273. n.nodeIndex = ++ni;
  17274. }
  17275. } else {
  17276. // Recursively clean
  17277. Ext.fly(n).clean();
  17278. n.nodeIndex = ++ni;
  17279. }
  17280. n = nx;
  17281. }
  17282. Ext.Element.data(dom, 'isCleaned', true);
  17283. return me;
  17284. },
  17285. /**
  17286. * Direct access to the Ext.ElementLoader {@link Ext.ElementLoader#load} method. The method takes the same object
  17287. * parameter as {@link Ext.ElementLoader#load}
  17288. * @return {Ext.Element} this
  17289. */
  17290. load : function(options) {
  17291. this.getLoader().load(options);
  17292. return this;
  17293. },
  17294. /**
  17295. * Gets this element's {@link Ext.ElementLoader ElementLoader}
  17296. * @return {Ext.ElementLoader} The loader
  17297. */
  17298. getLoader : function() {
  17299. var dom = this.dom,
  17300. data = Ext.Element.data,
  17301. loader = data(dom, 'loader');
  17302. if (!loader) {
  17303. loader = Ext.create('Ext.ElementLoader', {
  17304. target: this
  17305. });
  17306. data(dom, 'loader', loader);
  17307. }
  17308. return loader;
  17309. },
  17310. /**
  17311. * Update the innerHTML of this element, optionally searching for and processing scripts
  17312. * @param {String} html The new HTML
  17313. * @param {Boolean} [loadScripts=false] True to look for and process scripts
  17314. * @param {Function} [callback] For async script loading you can be notified when the update completes
  17315. * @return {Ext.Element} this
  17316. */
  17317. update : function(html, loadScripts, callback) {
  17318. var me = this,
  17319. id,
  17320. dom,
  17321. interval;
  17322. if (!me.dom) {
  17323. return me;
  17324. }
  17325. html = html || '';
  17326. dom = me.dom;
  17327. if (loadScripts !== true) {
  17328. dom.innerHTML = html;
  17329. Ext.callback(callback, me);
  17330. return me;
  17331. }
  17332. id = Ext.id();
  17333. html += '<span id="' + id + '"></span>';
  17334. interval = setInterval(function(){
  17335. if (!document.getElementById(id)) {
  17336. return false;
  17337. }
  17338. clearInterval(interval);
  17339. var DOC = document,
  17340. hd = DOC.getElementsByTagName("head")[0],
  17341. re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig,
  17342. srcRe = /\ssrc=([\'\"])(.*?)\1/i,
  17343. typeRe = /\stype=([\'\"])(.*?)\1/i,
  17344. match,
  17345. attrs,
  17346. srcMatch,
  17347. typeMatch,
  17348. el,
  17349. s;
  17350. while ((match = re.exec(html))) {
  17351. attrs = match[1];
  17352. srcMatch = attrs ? attrs.match(srcRe) : false;
  17353. if (srcMatch && srcMatch[2]) {
  17354. s = DOC.createElement("script");
  17355. s.src = srcMatch[2];
  17356. typeMatch = attrs.match(typeRe);
  17357. if (typeMatch && typeMatch[2]) {
  17358. s.type = typeMatch[2];
  17359. }
  17360. hd.appendChild(s);
  17361. } else if (match[2] && match[2].length > 0) {
  17362. if (window.execScript) {
  17363. window.execScript(match[2]);
  17364. } else {
  17365. window.eval(match[2]);
  17366. }
  17367. }
  17368. }
  17369. el = DOC.getElementById(id);
  17370. if (el) {
  17371. Ext.removeNode(el);
  17372. }
  17373. Ext.callback(callback, me);
  17374. }, 20);
  17375. dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, '');
  17376. return me;
  17377. },
  17378. // inherit docs, overridden so we can add removeAnchor
  17379. removeAllListeners : function() {
  17380. this.removeAnchor();
  17381. Ext.EventManager.removeAll(this.dom);
  17382. return this;
  17383. },
  17384. /**
  17385. * Gets the parent node of the current element taking into account Ext.scopeResetCSS
  17386. * @protected
  17387. * @return {HTMLElement} The parent element
  17388. */
  17389. getScopeParent: function(){
  17390. var parent = this.dom.parentNode;
  17391. return Ext.scopeResetCSS ? parent.parentNode : parent;
  17392. },
  17393. /**
  17394. * Creates a proxy element of this element
  17395. * @param {String/Object} config The class name of the proxy element or a DomHelper config object
  17396. * @param {String/HTMLElement} [renderTo] The element or element id to render the proxy to (defaults to document.body)
  17397. * @param {Boolean} [matchBox=false] True to align and size the proxy to this element now.
  17398. * @return {Ext.Element} The new proxy element
  17399. */
  17400. createProxy : function(config, renderTo, matchBox) {
  17401. config = (typeof config == 'object') ? config : {tag : "div", cls: config};
  17402. var me = this,
  17403. proxy = renderTo ? Ext.DomHelper.append(renderTo, config, true) :
  17404. Ext.DomHelper.insertBefore(me.dom, config, true);
  17405. proxy.setVisibilityMode(Ext.Element.DISPLAY);
  17406. proxy.hide();
  17407. if (matchBox && me.setBox && me.getBox) { // check to make sure Element.position.js is loaded
  17408. proxy.setBox(me.getBox());
  17409. }
  17410. return proxy;
  17411. },
  17412. /**
  17413. * Checks whether this element can be focused.
  17414. * @return {Boolean} True if the element is focusable
  17415. */
  17416. focusable: function(){
  17417. var dom = this.dom,
  17418. nodeName = dom.nodeName.toLowerCase(),
  17419. canFocus = false,
  17420. hasTabIndex = !isNaN(dom.tabIndex);
  17421. if (!dom.disabled) {
  17422. if (focusRe.test(nodeName)) {
  17423. canFocus = true;
  17424. } else {
  17425. canFocus = nodeName == 'a' ? dom.href || hasTabIndex : hasTabIndex;
  17426. }
  17427. }
  17428. return canFocus && this.isVisible(true);
  17429. }
  17430. };
  17431. })());
  17432. Ext.Element.prototype.clearListeners = Ext.Element.prototype.removeAllListeners;
  17433. /**
  17434. * @class Ext.Element
  17435. */
  17436. Ext.Element.addMethods({
  17437. /**
  17438. * Gets the x,y coordinates specified by the anchor position on the element.
  17439. * @param {String} [anchor='c'] The specified anchor position. See {@link #alignTo}
  17440. * for details on supported anchor positions.
  17441. * @param {Boolean} [local] True to get the local (element top/left-relative) anchor position instead
  17442. * of page coordinates
  17443. * @param {Object} [size] An object containing the size to use for calculating anchor position
  17444. * {width: (target width), height: (target height)} (defaults to the element's current size)
  17445. * @return {Number[]} [x, y] An array containing the element's x and y coordinates
  17446. */
  17447. getAnchorXY : function(anchor, local, s){
  17448. //Passing a different size is useful for pre-calculating anchors,
  17449. //especially for anchored animations that change the el size.
  17450. anchor = (anchor || "tl").toLowerCase();
  17451. s = s || {};
  17452. var me = this,
  17453. vp = me.dom == document.body || me.dom == document,
  17454. w = s.width || vp ? Ext.Element.getViewWidth() : me.getWidth(),
  17455. h = s.height || vp ? Ext.Element.getViewHeight() : me.getHeight(),
  17456. xy,
  17457. r = Math.round,
  17458. o = me.getXY(),
  17459. scroll = me.getScroll(),
  17460. extraX = vp ? scroll.left : !local ? o[0] : 0,
  17461. extraY = vp ? scroll.top : !local ? o[1] : 0,
  17462. hash = {
  17463. c : [r(w * 0.5), r(h * 0.5)],
  17464. t : [r(w * 0.5), 0],
  17465. l : [0, r(h * 0.5)],
  17466. r : [w, r(h * 0.5)],
  17467. b : [r(w * 0.5), h],
  17468. tl : [0, 0],
  17469. bl : [0, h],
  17470. br : [w, h],
  17471. tr : [w, 0]
  17472. };
  17473. xy = hash[anchor];
  17474. return [xy[0] + extraX, xy[1] + extraY];
  17475. },
  17476. /**
  17477. * Anchors an element to another element and realigns it when the window is resized.
  17478. * @param {String/HTMLElement/Ext.Element} element The element to align to.
  17479. * @param {String} position The position to align to.
  17480. * @param {Number[]} [offsets] Offset the positioning by [x, y]
  17481. * @param {Boolean/Object} [animate] True for the default animation or a standard Element animation config object
  17482. * @param {Boolean/Number} [monitorScroll] True to monitor body scroll and reposition. If this parameter
  17483. * is a number, it is used as the buffer delay (defaults to 50ms).
  17484. * @param {Function} [callback] The function to call after the animation finishes
  17485. * @return {Ext.Element} this
  17486. */
  17487. anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
  17488. var me = this,
  17489. dom = me.dom,
  17490. scroll = !Ext.isEmpty(monitorScroll),
  17491. action = function(){
  17492. Ext.fly(dom).alignTo(el, alignment, offsets, animate);
  17493. Ext.callback(callback, Ext.fly(dom));
  17494. },
  17495. anchor = this.getAnchor();
  17496. // previous listener anchor, remove it
  17497. this.removeAnchor();
  17498. Ext.apply(anchor, {
  17499. fn: action,
  17500. scroll: scroll
  17501. });
  17502. Ext.EventManager.onWindowResize(action, null);
  17503. if(scroll){
  17504. Ext.EventManager.on(window, 'scroll', action, null,
  17505. {buffer: !isNaN(monitorScroll) ? monitorScroll : 50});
  17506. }
  17507. action.call(me); // align immediately
  17508. return me;
  17509. },
  17510. /**
  17511. * Remove any anchor to this element. See {@link #anchorTo}.
  17512. * @return {Ext.Element} this
  17513. */
  17514. removeAnchor : function(){
  17515. var me = this,
  17516. anchor = this.getAnchor();
  17517. if(anchor && anchor.fn){
  17518. Ext.EventManager.removeResizeListener(anchor.fn);
  17519. if(anchor.scroll){
  17520. Ext.EventManager.un(window, 'scroll', anchor.fn);
  17521. }
  17522. delete anchor.fn;
  17523. }
  17524. return me;
  17525. },
  17526. // private
  17527. getAnchor : function(){
  17528. var data = Ext.Element.data,
  17529. dom = this.dom;
  17530. if (!dom) {
  17531. return;
  17532. }
  17533. var anchor = data(dom, '_anchor');
  17534. if(!anchor){
  17535. anchor = data(dom, '_anchor', {});
  17536. }
  17537. return anchor;
  17538. },
  17539. getAlignVector: function(el, spec, offset) {
  17540. var me = this,
  17541. side = {t:"top", l:"left", r:"right", b: "bottom"},
  17542. thisRegion = me.getRegion(),
  17543. elRegion;
  17544. el = Ext.get(el);
  17545. if(!el || !el.dom){
  17546. }
  17547. elRegion = el.getRegion();
  17548. },
  17549. /**
  17550. * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
  17551. * supported position values.
  17552. * @param {String/HTMLElement/Ext.Element} element The element to align to.
  17553. * @param {String} [position="tl-bl?"] The position to align to (defaults to )
  17554. * @param {Number[]} [offsets] Offset the positioning by [x, y]
  17555. * @return {Number[]} [x, y]
  17556. */
  17557. getAlignToXY : function(el, p, o){
  17558. el = Ext.get(el);
  17559. if(!el || !el.dom){
  17560. }
  17561. o = o || [0,0];
  17562. p = (!p || p == "?" ? "tl-bl?" : (!(/-/).test(p) && p !== "" ? "tl-" + p : p || "tl-bl")).toLowerCase();
  17563. var me = this,
  17564. d = me.dom,
  17565. a1,
  17566. a2,
  17567. x,
  17568. y,
  17569. //constrain the aligned el to viewport if necessary
  17570. w,
  17571. h,
  17572. r,
  17573. dw = Ext.Element.getViewWidth() -10, // 10px of margin for ie
  17574. dh = Ext.Element.getViewHeight()-10, // 10px of margin for ie
  17575. p1y,
  17576. p1x,
  17577. p2y,
  17578. p2x,
  17579. swapY,
  17580. swapX,
  17581. doc = document,
  17582. docElement = doc.documentElement,
  17583. docBody = doc.body,
  17584. scrollX = (docElement.scrollLeft || docBody.scrollLeft || 0)+5,
  17585. scrollY = (docElement.scrollTop || docBody.scrollTop || 0)+5,
  17586. c = false, //constrain to viewport
  17587. p1 = "",
  17588. p2 = "",
  17589. m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
  17590. if(!m){
  17591. }
  17592. p1 = m[1];
  17593. p2 = m[2];
  17594. c = !!m[3];
  17595. //Subtract the aligned el's internal xy from the target's offset xy
  17596. //plus custom offset to get the aligned el's new offset xy
  17597. a1 = me.getAnchorXY(p1, true);
  17598. a2 = el.getAnchorXY(p2, false);
  17599. x = a2[0] - a1[0] + o[0];
  17600. y = a2[1] - a1[1] + o[1];
  17601. if(c){
  17602. w = me.getWidth();
  17603. h = me.getHeight();
  17604. r = el.getRegion();
  17605. //If we are at a viewport boundary and the aligned el is anchored on a target border that is
  17606. //perpendicular to the vp border, allow the aligned el to slide on that border,
  17607. //otherwise swap the aligned el to the opposite border of the target.
  17608. p1y = p1.charAt(0);
  17609. p1x = p1.charAt(p1.length-1);
  17610. p2y = p2.charAt(0);
  17611. p2x = p2.charAt(p2.length-1);
  17612. swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t"));
  17613. swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
  17614. if (x + w > dw + scrollX) {
  17615. x = swapX ? r.left-w : dw+scrollX-w;
  17616. }
  17617. if (x < scrollX) {
  17618. x = swapX ? r.right : scrollX;
  17619. }
  17620. if (y + h > dh + scrollY) {
  17621. y = swapY ? r.top-h : dh+scrollY-h;
  17622. }
  17623. if (y < scrollY){
  17624. y = swapY ? r.bottom : scrollY;
  17625. }
  17626. }
  17627. return [x,y];
  17628. },
  17629. /**
  17630. * Aligns this element with another element relative to the specified anchor points. If the other element is the
  17631. * document it aligns it to the viewport.
  17632. * The position parameter is optional, and can be specified in any one of the following formats:
  17633. * <ul>
  17634. * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
  17635. * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
  17636. * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
  17637. * deprecated in favor of the newer two anchor syntax below</i>.</li>
  17638. * <li><b>Two anchors</b>: If two values from the table below are passed separated by a dash, the first value is used as the
  17639. * element's anchor point, and the second value is used as the target's anchor point.</li>
  17640. * </ul>
  17641. * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
  17642. * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
  17643. * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
  17644. * that specified in order to enforce the viewport constraints.
  17645. * Following are all of the supported anchor positions:
  17646. <pre>
  17647. Value Description
  17648. ----- -----------------------------
  17649. tl The top left corner (default)
  17650. t The center of the top edge
  17651. tr The top right corner
  17652. l The center of the left edge
  17653. c In the center of the element
  17654. r The center of the right edge
  17655. bl The bottom left corner
  17656. b The center of the bottom edge
  17657. br The bottom right corner
  17658. </pre>
  17659. Example Usage:
  17660. <pre><code>
  17661. // align el to other-el using the default positioning ("tl-bl", non-constrained)
  17662. el.alignTo("other-el");
  17663. // align the top left corner of el with the top right corner of other-el (constrained to viewport)
  17664. el.alignTo("other-el", "tr?");
  17665. // align the bottom right corner of el with the center left edge of other-el
  17666. el.alignTo("other-el", "br-l?");
  17667. // align the center of el with the bottom left corner of other-el and
  17668. // adjust the x position by -6 pixels (and the y position by 0)
  17669. el.alignTo("other-el", "c-bl", [-6, 0]);
  17670. </code></pre>
  17671. * @param {String/HTMLElement/Ext.Element} element The element to align to.
  17672. * @param {String} [position="tl-bl?"] The position to align to
  17673. * @param {Number[]} [offsets] Offset the positioning by [x, y]
  17674. * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object
  17675. * @return {Ext.Element} this
  17676. */
  17677. alignTo : function(element, position, offsets, animate){
  17678. var me = this;
  17679. return me.setXY(me.getAlignToXY(element, position, offsets),
  17680. me.anim && !!animate ? me.anim(animate) : false);
  17681. },
  17682. // private ==> used outside of core
  17683. adjustForConstraints : function(xy, parent) {
  17684. var vector = this.getConstrainVector(parent, xy);
  17685. if (vector) {
  17686. xy[0] += vector[0];
  17687. xy[1] += vector[1];
  17688. }
  17689. return xy;
  17690. },
  17691. /**
  17692. * <p>Returns the <code>[X, Y]</code> vector by which this element must be translated to make a best attempt
  17693. * to constrain within the passed constraint. Returns <code>false</code> is this element does not need to be moved.</p>
  17694. * <p>Priority is given to constraining the top and left within the constraint.</p>
  17695. * <p>The constraint may either be an existing element into which this element is to be constrained, or
  17696. * an {@link Ext.util.Region Region} into which this element is to be constrained.</p>
  17697. * @param constrainTo {Mixed} The Element or {@link Ext.util.Region Region} into which this element is to be constrained.
  17698. * @param proposedPosition {Array} A proposed <code>[X, Y]</code> position to test for validity and to produce a vector for instead
  17699. * of using this Element's current position;
  17700. * @returns {Number[]/Boolean} <b>If</b> this element <i>needs</i> to be translated, an <code>[X, Y]</code>
  17701. * vector by which this element must be translated. Otherwise, <code>false</code>.
  17702. */
  17703. getConstrainVector: function(constrainTo, proposedPosition) {
  17704. if (!(constrainTo instanceof Ext.util.Region)) {
  17705. constrainTo = Ext.get(constrainTo).getViewRegion();
  17706. }
  17707. var thisRegion = this.getRegion(),
  17708. vector = [0, 0],
  17709. shadowSize = this.shadow && this.shadow.offset,
  17710. overflowed = false;
  17711. // Shift this region to occupy the proposed position
  17712. if (proposedPosition) {
  17713. thisRegion.translateBy(proposedPosition[0] - thisRegion.x, proposedPosition[1] - thisRegion.y);
  17714. }
  17715. // Reduce the constrain region to allow for shadow
  17716. // TODO: Rewrite the Shadow class. When that's done, get the extra for each side from the Shadow.
  17717. if (shadowSize) {
  17718. constrainTo.adjust(0, -shadowSize, -shadowSize, shadowSize);
  17719. }
  17720. // Constrain the X coordinate by however much this Element overflows
  17721. if (thisRegion.right > constrainTo.right) {
  17722. overflowed = true;
  17723. vector[0] = (constrainTo.right - thisRegion.right); // overflowed the right
  17724. }
  17725. if (thisRegion.left + vector[0] < constrainTo.left) {
  17726. overflowed = true;
  17727. vector[0] = (constrainTo.left - thisRegion.left); // overflowed the left
  17728. }
  17729. // Constrain the Y coordinate by however much this Element overflows
  17730. if (thisRegion.bottom > constrainTo.bottom) {
  17731. overflowed = true;
  17732. vector[1] = (constrainTo.bottom - thisRegion.bottom); // overflowed the bottom
  17733. }
  17734. if (thisRegion.top + vector[1] < constrainTo.top) {
  17735. overflowed = true;
  17736. vector[1] = (constrainTo.top - thisRegion.top); // overflowed the top
  17737. }
  17738. return overflowed ? vector : false;
  17739. },
  17740. /**
  17741. * Calculates the x, y to center this element on the screen
  17742. * @return {Number[]} The x, y values [x, y]
  17743. */
  17744. getCenterXY : function(){
  17745. return this.getAlignToXY(document, 'c-c');
  17746. },
  17747. /**
  17748. * Centers the Element in either the viewport, or another Element.
  17749. * @param {String/HTMLElement/Ext.Element} centerIn (optional) The element in which to center the element.
  17750. */
  17751. center : function(centerIn){
  17752. return this.alignTo(centerIn || document, 'c-c');
  17753. }
  17754. });
  17755. /**
  17756. * @class Ext.Element
  17757. */
  17758. (function(){
  17759. var ELEMENT = Ext.Element,
  17760. LEFT = "left",
  17761. RIGHT = "right",
  17762. TOP = "top",
  17763. BOTTOM = "bottom",
  17764. POSITION = "position",
  17765. STATIC = "static",
  17766. RELATIVE = "relative",
  17767. AUTO = "auto",
  17768. ZINDEX = "z-index";
  17769. Ext.override(Ext.Element, {
  17770. /**
  17771. * Gets the current X position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
  17772. * @return {Number} The X position of the element
  17773. */
  17774. getX : function(){
  17775. return ELEMENT.getX(this.dom);
  17776. },
  17777. /**
  17778. * Gets the current Y position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
  17779. * @return {Number} The Y position of the element
  17780. */
  17781. getY : function(){
  17782. return ELEMENT.getY(this.dom);
  17783. },
  17784. /**
  17785. * Gets the current position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
  17786. * @return {Number[]} The XY position of the element
  17787. */
  17788. getXY : function(){
  17789. return ELEMENT.getXY(this.dom);
  17790. },
  17791. /**
  17792. * Returns the offsets of this element from the passed element. Both element must be part of the DOM tree and not have display:none to have page coordinates.
  17793. * @param {String/HTMLElement/Ext.Element} element The element to get the offsets from.
  17794. * @return {Number[]} The XY page offsets (e.g. [100, -200])
  17795. */
  17796. getOffsetsTo : function(el){
  17797. var o = this.getXY(),
  17798. e = Ext.fly(el, '_internal').getXY();
  17799. return [o[0]-e[0],o[1]-e[1]];
  17800. },
  17801. /**
  17802. * Sets the X position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
  17803. * @param {Number} The X position of the element
  17804. * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
  17805. * @return {Ext.Element} this
  17806. */
  17807. setX : function(x, animate){
  17808. return this.setXY([x, this.getY()], animate);
  17809. },
  17810. /**
  17811. * Sets the Y position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
  17812. * @param {Number} The Y position of the element
  17813. * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
  17814. * @return {Ext.Element} this
  17815. */
  17816. setY : function(y, animate){
  17817. return this.setXY([this.getX(), y], animate);
  17818. },
  17819. /**
  17820. * Sets the element's left position directly using CSS style (instead of {@link #setX}).
  17821. * @param {String} left The left CSS property value
  17822. * @return {Ext.Element} this
  17823. */
  17824. setLeft : function(left){
  17825. this.setStyle(LEFT, this.addUnits(left));
  17826. return this;
  17827. },
  17828. /**
  17829. * Sets the element's top position directly using CSS style (instead of {@link #setY}).
  17830. * @param {String} top The top CSS property value
  17831. * @return {Ext.Element} this
  17832. */
  17833. setTop : function(top){
  17834. this.setStyle(TOP, this.addUnits(top));
  17835. return this;
  17836. },
  17837. /**
  17838. * Sets the element's CSS right style.
  17839. * @param {String} right The right CSS property value
  17840. * @return {Ext.Element} this
  17841. */
  17842. setRight : function(right){
  17843. this.setStyle(RIGHT, this.addUnits(right));
  17844. return this;
  17845. },
  17846. /**
  17847. * Sets the element's CSS bottom style.
  17848. * @param {String} bottom The bottom CSS property value
  17849. * @return {Ext.Element} this
  17850. */
  17851. setBottom : function(bottom){
  17852. this.setStyle(BOTTOM, this.addUnits(bottom));
  17853. return this;
  17854. },
  17855. /**
  17856. * Sets the position of the element in page coordinates, regardless of how the element is positioned.
  17857. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
  17858. * @param {Number[]} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
  17859. * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
  17860. * @return {Ext.Element} this
  17861. */
  17862. setXY: function(pos, animate) {
  17863. var me = this;
  17864. if (!animate || !me.anim) {
  17865. ELEMENT.setXY(me.dom, pos);
  17866. }
  17867. else {
  17868. if (!Ext.isObject(animate)) {
  17869. animate = {};
  17870. }
  17871. me.animate(Ext.applyIf({ to: { x: pos[0], y: pos[1] } }, animate));
  17872. }
  17873. return me;
  17874. },
  17875. /**
  17876. * Sets the position of the element in page coordinates, regardless of how the element is positioned.
  17877. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
  17878. * @param {Number} x X value for new position (coordinates are page-based)
  17879. * @param {Number} y Y value for new position (coordinates are page-based)
  17880. * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
  17881. * @return {Ext.Element} this
  17882. */
  17883. setLocation : function(x, y, animate){
  17884. return this.setXY([x, y], animate);
  17885. },
  17886. /**
  17887. * Sets the position of the element in page coordinates, regardless of how the element is positioned.
  17888. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
  17889. * @param {Number} x X value for new position (coordinates are page-based)
  17890. * @param {Number} y Y value for new position (coordinates are page-based)
  17891. * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
  17892. * @return {Ext.Element} this
  17893. */
  17894. moveTo : function(x, y, animate){
  17895. return this.setXY([x, y], animate);
  17896. },
  17897. /**
  17898. * Gets the left X coordinate
  17899. * @param {Boolean} local True to get the local css position instead of page coordinate
  17900. * @return {Number}
  17901. */
  17902. getLeft : function(local){
  17903. return !local ? this.getX() : parseInt(this.getStyle(LEFT), 10) || 0;
  17904. },
  17905. /**
  17906. * Gets the right X coordinate of the element (element X position + element width)
  17907. * @param {Boolean} local True to get the local css position instead of page coordinate
  17908. * @return {Number}
  17909. */
  17910. getRight : function(local){
  17911. var me = this;
  17912. return !local ? me.getX() + me.getWidth() : (me.getLeft(true) + me.getWidth()) || 0;
  17913. },
  17914. /**
  17915. * Gets the top Y coordinate
  17916. * @param {Boolean} local True to get the local css position instead of page coordinate
  17917. * @return {Number}
  17918. */
  17919. getTop : function(local) {
  17920. return !local ? this.getY() : parseInt(this.getStyle(TOP), 10) || 0;
  17921. },
  17922. /**
  17923. * Gets the bottom Y coordinate of the element (element Y position + element height)
  17924. * @param {Boolean} local True to get the local css position instead of page coordinate
  17925. * @return {Number}
  17926. */
  17927. getBottom : function(local){
  17928. var me = this;
  17929. return !local ? me.getY() + me.getHeight() : (me.getTop(true) + me.getHeight()) || 0;
  17930. },
  17931. /**
  17932. * Initializes positioning on this element. If a desired position is not passed, it will make the
  17933. * the element positioned relative IF it is not already positioned.
  17934. * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
  17935. * @param {Number} zIndex (optional) The zIndex to apply
  17936. * @param {Number} x (optional) Set the page X position
  17937. * @param {Number} y (optional) Set the page Y position
  17938. */
  17939. position : function(pos, zIndex, x, y) {
  17940. var me = this;
  17941. if (!pos && me.isStyle(POSITION, STATIC)){
  17942. me.setStyle(POSITION, RELATIVE);
  17943. } else if(pos) {
  17944. me.setStyle(POSITION, pos);
  17945. }
  17946. if (zIndex){
  17947. me.setStyle(ZINDEX, zIndex);
  17948. }
  17949. if (x || y) {
  17950. me.setXY([x || false, y || false]);
  17951. }
  17952. },
  17953. /**
  17954. * Clear positioning back to the default when the document was loaded
  17955. * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
  17956. * @return {Ext.Element} this
  17957. */
  17958. clearPositioning : function(value){
  17959. value = value || '';
  17960. this.setStyle({
  17961. left : value,
  17962. right : value,
  17963. top : value,
  17964. bottom : value,
  17965. "z-index" : "",
  17966. position : STATIC
  17967. });
  17968. return this;
  17969. },
  17970. /**
  17971. * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
  17972. * snapshot before performing an update and then restoring the element.
  17973. * @return {Object}
  17974. */
  17975. getPositioning : function(){
  17976. var l = this.getStyle(LEFT);
  17977. var t = this.getStyle(TOP);
  17978. return {
  17979. "position" : this.getStyle(POSITION),
  17980. "left" : l,
  17981. "right" : l ? "" : this.getStyle(RIGHT),
  17982. "top" : t,
  17983. "bottom" : t ? "" : this.getStyle(BOTTOM),
  17984. "z-index" : this.getStyle(ZINDEX)
  17985. };
  17986. },
  17987. /**
  17988. * Set positioning with an object returned by getPositioning().
  17989. * @param {Object} posCfg
  17990. * @return {Ext.Element} this
  17991. */
  17992. setPositioning : function(pc){
  17993. var me = this,
  17994. style = me.dom.style;
  17995. me.setStyle(pc);
  17996. if(pc.right == AUTO){
  17997. style.right = "";
  17998. }
  17999. if(pc.bottom == AUTO){
  18000. style.bottom = "";
  18001. }
  18002. return me;
  18003. },
  18004. /**
  18005. * Translates the passed page coordinates into left/top css values for this element
  18006. * @param {Number/Number[]} x The page x or an array containing [x, y]
  18007. * @param {Number} y (optional) The page y, required if x is not an array
  18008. * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
  18009. */
  18010. translatePoints: function(x, y) {
  18011. if (Ext.isArray(x)) {
  18012. y = x[1];
  18013. x = x[0];
  18014. }
  18015. var me = this,
  18016. relative = me.isStyle(POSITION, RELATIVE),
  18017. o = me.getXY(),
  18018. left = parseInt(me.getStyle(LEFT), 10),
  18019. top = parseInt(me.getStyle(TOP), 10);
  18020. if (!Ext.isNumber(left)) {
  18021. left = relative ? 0 : me.dom.offsetLeft;
  18022. }
  18023. if (!Ext.isNumber(top)) {
  18024. top = relative ? 0 : me.dom.offsetTop;
  18025. }
  18026. left = (Ext.isNumber(x)) ? x - o[0] + left : undefined;
  18027. top = (Ext.isNumber(y)) ? y - o[1] + top : undefined;
  18028. return {
  18029. left: left,
  18030. top: top
  18031. };
  18032. },
  18033. /**
  18034. * Sets the element's box. Use getBox() on another element to get a box obj. If animate is true then width, height, x and y will be animated concurrently.
  18035. * @param {Object} box The box to fill {x, y, width, height}
  18036. * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
  18037. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
  18038. * @return {Ext.Element} this
  18039. */
  18040. setBox: function(box, adjust, animate) {
  18041. var me = this,
  18042. w = box.width,
  18043. h = box.height;
  18044. if ((adjust && !me.autoBoxAdjust) && !me.isBorderBox()) {
  18045. w -= (me.getBorderWidth("lr") + me.getPadding("lr"));
  18046. h -= (me.getBorderWidth("tb") + me.getPadding("tb"));
  18047. }
  18048. me.setBounds(box.x, box.y, w, h, animate);
  18049. return me;
  18050. },
  18051. /**
  18052. * Return an object defining the area of this Element which can be passed to {@link #setBox} to
  18053. * set another Element's size/location to match this element.
  18054. * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
  18055. * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
  18056. * @return {Object} box An object in the format<pre><code>
  18057. {
  18058. x: &lt;Element's X position>,
  18059. y: &lt;Element's Y position>,
  18060. width: &lt;Element's width>,
  18061. height: &lt;Element's height>,
  18062. bottom: &lt;Element's lower bound>,
  18063. right: &lt;Element's rightmost bound>
  18064. }
  18065. </code></pre>
  18066. * The returned object may also be addressed as an Array where index 0 contains the X position
  18067. * and index 1 contains the Y position. So the result may also be used for {@link #setXY}
  18068. */
  18069. getBox: function(contentBox, local) {
  18070. var me = this,
  18071. xy,
  18072. left,
  18073. top,
  18074. getBorderWidth = me.getBorderWidth,
  18075. getPadding = me.getPadding,
  18076. l, r, t, b, w, h, bx;
  18077. if (!local) {
  18078. xy = me.getXY();
  18079. } else {
  18080. left = parseInt(me.getStyle("left"), 10) || 0;
  18081. top = parseInt(me.getStyle("top"), 10) || 0;
  18082. xy = [left, top];
  18083. }
  18084. w = me.getWidth();
  18085. h = me.getHeight();
  18086. if (!contentBox) {
  18087. bx = {
  18088. x: xy[0],
  18089. y: xy[1],
  18090. 0: xy[0],
  18091. 1: xy[1],
  18092. width: w,
  18093. height: h
  18094. };
  18095. } else {
  18096. l = getBorderWidth.call(me, "l") + getPadding.call(me, "l");
  18097. r = getBorderWidth.call(me, "r") + getPadding.call(me, "r");
  18098. t = getBorderWidth.call(me, "t") + getPadding.call(me, "t");
  18099. b = getBorderWidth.call(me, "b") + getPadding.call(me, "b");
  18100. bx = {
  18101. x: xy[0] + l,
  18102. y: xy[1] + t,
  18103. 0: xy[0] + l,
  18104. 1: xy[1] + t,
  18105. width: w - (l + r),
  18106. height: h - (t + b)
  18107. };
  18108. }
  18109. bx.right = bx.x + bx.width;
  18110. bx.bottom = bx.y + bx.height;
  18111. return bx;
  18112. },
  18113. /**
  18114. * Move this element relative to its current position.
  18115. * @param {String} direction Possible values are: "l" (or "left"), "r" (or "right"), "t" (or "top", or "up"), "b" (or "bottom", or "down").
  18116. * @param {Number} distance How far to move the element in pixels
  18117. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
  18118. */
  18119. move: function(direction, distance, animate) {
  18120. var me = this,
  18121. xy = me.getXY(),
  18122. x = xy[0],
  18123. y = xy[1],
  18124. left = [x - distance, y],
  18125. right = [x + distance, y],
  18126. top = [x, y - distance],
  18127. bottom = [x, y + distance],
  18128. hash = {
  18129. l: left,
  18130. left: left,
  18131. r: right,
  18132. right: right,
  18133. t: top,
  18134. top: top,
  18135. up: top,
  18136. b: bottom,
  18137. bottom: bottom,
  18138. down: bottom
  18139. };
  18140. direction = direction.toLowerCase();
  18141. me.moveTo(hash[direction][0], hash[direction][1], animate);
  18142. },
  18143. /**
  18144. * Quick set left and top adding default units
  18145. * @param {String} left The left CSS property value
  18146. * @param {String} top The top CSS property value
  18147. * @return {Ext.Element} this
  18148. */
  18149. setLeftTop: function(left, top) {
  18150. var me = this,
  18151. style = me.dom.style;
  18152. style.left = me.addUnits(left);
  18153. style.top = me.addUnits(top);
  18154. return me;
  18155. },
  18156. /**
  18157. * Returns the region of this element.
  18158. * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
  18159. * @return {Ext.util.Region} A Region containing "top, left, bottom, right" member data.
  18160. */
  18161. getRegion: function() {
  18162. return this.getPageBox(true);
  18163. },
  18164. /**
  18165. * Returns the <b>content</b> region of this element. That is the region within the borders and padding.
  18166. * @return {Ext.util.Region} A Region containing "top, left, bottom, right" member data.
  18167. */
  18168. getViewRegion: function() {
  18169. var me = this,
  18170. isBody = me.dom === document.body,
  18171. scroll, pos, top, left, width, height;
  18172. // For the body we want to do some special logic
  18173. if (isBody) {
  18174. scroll = me.getScroll();
  18175. left = scroll.left;
  18176. top = scroll.top;
  18177. width = Ext.Element.getViewportWidth();
  18178. height = Ext.Element.getViewportHeight();
  18179. }
  18180. else {
  18181. pos = me.getXY();
  18182. left = pos[0] + me.getBorderWidth('l') + me.getPadding('l');
  18183. top = pos[1] + me.getBorderWidth('t') + me.getPadding('t');
  18184. width = me.getWidth(true);
  18185. height = me.getHeight(true);
  18186. }
  18187. return Ext.create('Ext.util.Region', top, left + width, top + height, left);
  18188. },
  18189. /**
  18190. * Return an object defining the area of this Element which can be passed to {@link #setBox} to
  18191. * set another Element's size/location to match this element.
  18192. * @param {Boolean} asRegion(optional) If true an Ext.util.Region will be returned
  18193. * @return {Object} box An object in the format<pre><code>
  18194. {
  18195. x: &lt;Element's X position>,
  18196. y: &lt;Element's Y position>,
  18197. width: &lt;Element's width>,
  18198. height: &lt;Element's height>,
  18199. bottom: &lt;Element's lower bound>,
  18200. right: &lt;Element's rightmost bound>
  18201. }
  18202. </code></pre>
  18203. * The returned object may also be addressed as an Array where index 0 contains the X position
  18204. * and index 1 contains the Y position. So the result may also be used for {@link #setXY}
  18205. */
  18206. getPageBox : function(getRegion) {
  18207. var me = this,
  18208. el = me.dom,
  18209. isDoc = el === document.body,
  18210. w = isDoc ? Ext.Element.getViewWidth() : el.offsetWidth,
  18211. h = isDoc ? Ext.Element.getViewHeight() : el.offsetHeight,
  18212. xy = me.getXY(),
  18213. t = xy[1],
  18214. r = xy[0] + w,
  18215. b = xy[1] + h,
  18216. l = xy[0];
  18217. if (getRegion) {
  18218. return Ext.create('Ext.util.Region', t, r, b, l);
  18219. }
  18220. else {
  18221. return {
  18222. left: l,
  18223. top: t,
  18224. width: w,
  18225. height: h,
  18226. right: r,
  18227. bottom: b
  18228. };
  18229. }
  18230. },
  18231. /**
  18232. * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
  18233. * @param {Number} x X value for new position (coordinates are page-based)
  18234. * @param {Number} y Y value for new position (coordinates are page-based)
  18235. * @param {Number/String} width The new width. This may be one of:<div class="mdetail-params"><ul>
  18236. * <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels)</li>
  18237. * <li>A String used to set the CSS width style. Animation may <b>not</b> be used.
  18238. * </ul></div>
  18239. * @param {Number/String} height The new height. This may be one of:<div class="mdetail-params"><ul>
  18240. * <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels)</li>
  18241. * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
  18242. * </ul></div>
  18243. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
  18244. * @return {Ext.Element} this
  18245. */
  18246. setBounds: function(x, y, width, height, animate) {
  18247. var me = this;
  18248. if (!animate || !me.anim) {
  18249. me.setSize(width, height);
  18250. me.setLocation(x, y);
  18251. } else {
  18252. if (!Ext.isObject(animate)) {
  18253. animate = {};
  18254. }
  18255. me.animate(Ext.applyIf({
  18256. to: {
  18257. x: x,
  18258. y: y,
  18259. width: me.adjustWidth(width),
  18260. height: me.adjustHeight(height)
  18261. }
  18262. }, animate));
  18263. }
  18264. return me;
  18265. },
  18266. /**
  18267. * Sets the element's position and size the specified region. If animation is true then width, height, x and y will be animated concurrently.
  18268. * @param {Ext.util.Region} region The region to fill
  18269. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
  18270. * @return {Ext.Element} this
  18271. */
  18272. setRegion: function(region, animate) {
  18273. return this.setBounds(region.left, region.top, region.right - region.left, region.bottom - region.top, animate);
  18274. }
  18275. });
  18276. })();
  18277. /**
  18278. * @class Ext.Element
  18279. */
  18280. Ext.override(Ext.Element, {
  18281. /**
  18282. * Returns true if this element is scrollable.
  18283. * @return {Boolean}
  18284. */
  18285. isScrollable : function(){
  18286. var dom = this.dom;
  18287. return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
  18288. },
  18289. /**
  18290. * Returns the current scroll position of the element.
  18291. * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
  18292. */
  18293. getScroll : function() {
  18294. var d = this.dom,
  18295. doc = document,
  18296. body = doc.body,
  18297. docElement = doc.documentElement,
  18298. l,
  18299. t,
  18300. ret;
  18301. if (d == doc || d == body) {
  18302. if (Ext.isIE && Ext.isStrict) {
  18303. l = docElement.scrollLeft;
  18304. t = docElement.scrollTop;
  18305. } else {
  18306. l = window.pageXOffset;
  18307. t = window.pageYOffset;
  18308. }
  18309. ret = {
  18310. left: l || (body ? body.scrollLeft : 0),
  18311. top : t || (body ? body.scrollTop : 0)
  18312. };
  18313. } else {
  18314. ret = {
  18315. left: d.scrollLeft,
  18316. top : d.scrollTop
  18317. };
  18318. }
  18319. return ret;
  18320. },
  18321. /**
  18322. * Scrolls this element the specified scroll point. It does NOT do bounds checking so if you scroll to a weird value it will try to do it. For auto bounds checking, use scroll().
  18323. * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
  18324. * @param {Number} value The new scroll value
  18325. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
  18326. * @return {Ext.Element} this
  18327. */
  18328. scrollTo : function(side, value, animate) {
  18329. //check if we're scrolling top or left
  18330. var top = /top/i.test(side),
  18331. me = this,
  18332. dom = me.dom,
  18333. obj = {},
  18334. prop;
  18335. if (!animate || !me.anim) {
  18336. // just setting the value, so grab the direction
  18337. prop = 'scroll' + (top ? 'Top' : 'Left');
  18338. dom[prop] = value;
  18339. }
  18340. else {
  18341. if (!Ext.isObject(animate)) {
  18342. animate = {};
  18343. }
  18344. obj['scroll' + (top ? 'Top' : 'Left')] = value;
  18345. me.animate(Ext.applyIf({
  18346. to: obj
  18347. }, animate));
  18348. }
  18349. return me;
  18350. },
  18351. /**
  18352. * Scrolls this element into view within the passed container.
  18353. * @param {String/HTMLElement/Ext.Element} container (optional) The container element to scroll (defaults to document.body). Should be a
  18354. * string (id), dom node, or Ext.Element.
  18355. * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
  18356. * @return {Ext.Element} this
  18357. */
  18358. scrollIntoView : function(container, hscroll) {
  18359. container = Ext.getDom(container) || Ext.getBody().dom;
  18360. var el = this.dom,
  18361. offsets = this.getOffsetsTo(container),
  18362. // el's box
  18363. left = offsets[0] + container.scrollLeft,
  18364. top = offsets[1] + container.scrollTop,
  18365. bottom = top + el.offsetHeight,
  18366. right = left + el.offsetWidth,
  18367. // ct's box
  18368. ctClientHeight = container.clientHeight,
  18369. ctScrollTop = parseInt(container.scrollTop, 10),
  18370. ctScrollLeft = parseInt(container.scrollLeft, 10),
  18371. ctBottom = ctScrollTop + ctClientHeight,
  18372. ctRight = ctScrollLeft + container.clientWidth;
  18373. if (el.offsetHeight > ctClientHeight || top < ctScrollTop) {
  18374. container.scrollTop = top;
  18375. } else if (bottom > ctBottom) {
  18376. container.scrollTop = bottom - ctClientHeight;
  18377. }
  18378. // corrects IE, other browsers will ignore
  18379. container.scrollTop = container.scrollTop;
  18380. if (hscroll !== false) {
  18381. if (el.offsetWidth > container.clientWidth || left < ctScrollLeft) {
  18382. container.scrollLeft = left;
  18383. }
  18384. else if (right > ctRight) {
  18385. container.scrollLeft = right - container.clientWidth;
  18386. }
  18387. container.scrollLeft = container.scrollLeft;
  18388. }
  18389. return this;
  18390. },
  18391. // private
  18392. scrollChildIntoView : function(child, hscroll) {
  18393. Ext.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
  18394. },
  18395. /**
  18396. * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
  18397. * within this element's scrollable range.
  18398. * @param {String} direction Possible values are: "l" (or "left"), "r" (or "right"), "t" (or "top", or "up"), "b" (or "bottom", or "down").
  18399. * @param {Number} distance How far to scroll the element in pixels
  18400. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
  18401. * @return {Boolean} Returns true if a scroll was triggered or false if the element
  18402. * was scrolled as far as it could go.
  18403. */
  18404. scroll : function(direction, distance, animate) {
  18405. if (!this.isScrollable()) {
  18406. return false;
  18407. }
  18408. var el = this.dom,
  18409. l = el.scrollLeft, t = el.scrollTop,
  18410. w = el.scrollWidth, h = el.scrollHeight,
  18411. cw = el.clientWidth, ch = el.clientHeight,
  18412. scrolled = false, v,
  18413. hash = {
  18414. l: Math.min(l + distance, w-cw),
  18415. r: v = Math.max(l - distance, 0),
  18416. t: Math.max(t - distance, 0),
  18417. b: Math.min(t + distance, h-ch)
  18418. };
  18419. hash.d = hash.b;
  18420. hash.u = hash.t;
  18421. direction = direction.substr(0, 1);
  18422. if ((v = hash[direction]) > -1) {
  18423. scrolled = true;
  18424. this.scrollTo(direction == 'l' || direction == 'r' ? 'left' : 'top', v, this.anim(animate));
  18425. }
  18426. return scrolled;
  18427. }
  18428. });
  18429. /**
  18430. * @class Ext.Element
  18431. */
  18432. Ext.Element.addMethods(
  18433. function() {
  18434. var VISIBILITY = "visibility",
  18435. DISPLAY = "display",
  18436. HIDDEN = "hidden",
  18437. NONE = "none",
  18438. XMASKED = Ext.baseCSSPrefix + "masked",
  18439. XMASKEDRELATIVE = Ext.baseCSSPrefix + "masked-relative",
  18440. data = Ext.Element.data;
  18441. return {
  18442. /**
  18443. * Checks whether the element is currently visible using both visibility and display properties.
  18444. * @param {Boolean} [deep=false] True to walk the dom and see if parent elements are hidden
  18445. * @return {Boolean} True if the element is currently visible, else false
  18446. */
  18447. isVisible : function(deep) {
  18448. var vis = !this.isStyle(VISIBILITY, HIDDEN) && !this.isStyle(DISPLAY, NONE),
  18449. p = this.dom.parentNode;
  18450. if (deep !== true || !vis) {
  18451. return vis;
  18452. }
  18453. while (p && !(/^body/i.test(p.tagName))) {
  18454. if (!Ext.fly(p, '_isVisible').isVisible()) {
  18455. return false;
  18456. }
  18457. p = p.parentNode;
  18458. }
  18459. return true;
  18460. },
  18461. /**
  18462. * Returns true if display is not "none"
  18463. * @return {Boolean}
  18464. */
  18465. isDisplayed : function() {
  18466. return !this.isStyle(DISPLAY, NONE);
  18467. },
  18468. /**
  18469. * Convenience method for setVisibilityMode(Element.DISPLAY)
  18470. * @param {String} display (optional) What to set display to when visible
  18471. * @return {Ext.Element} this
  18472. */
  18473. enableDisplayMode : function(display) {
  18474. this.setVisibilityMode(Ext.Element.DISPLAY);
  18475. if (!Ext.isEmpty(display)) {
  18476. data(this.dom, 'originalDisplay', display);
  18477. }
  18478. return this;
  18479. },
  18480. /**
  18481. * Puts a mask over this element to disable user interaction. Requires core.css.
  18482. * This method can only be applied to elements which accept child nodes.
  18483. * @param {String} msg (optional) A message to display in the mask
  18484. * @param {String} msgCls (optional) A css class to apply to the msg element
  18485. * @return {Ext.Element} The mask element
  18486. */
  18487. mask : function(msg, msgCls) {
  18488. var me = this,
  18489. dom = me.dom,
  18490. setExpression = dom.style.setExpression,
  18491. dh = Ext.DomHelper,
  18492. EXTELMASKMSG = Ext.baseCSSPrefix + "mask-msg",
  18493. el,
  18494. mask;
  18495. if (!(/^body/i.test(dom.tagName) && me.getStyle('position') == 'static')) {
  18496. me.addCls(XMASKEDRELATIVE);
  18497. }
  18498. el = data(dom, 'maskMsg');
  18499. if (el) {
  18500. el.remove();
  18501. }
  18502. el = data(dom, 'mask');
  18503. if (el) {
  18504. el.remove();
  18505. }
  18506. mask = dh.append(dom, {cls : Ext.baseCSSPrefix + "mask"}, true);
  18507. data(dom, 'mask', mask);
  18508. me.addCls(XMASKED);
  18509. mask.setDisplayed(true);
  18510. if (typeof msg == 'string') {
  18511. var mm = dh.append(dom, {cls : EXTELMASKMSG, cn:{tag:'div'}}, true);
  18512. data(dom, 'maskMsg', mm);
  18513. mm.dom.className = msgCls ? EXTELMASKMSG + " " + msgCls : EXTELMASKMSG;
  18514. mm.dom.firstChild.innerHTML = msg;
  18515. mm.setDisplayed(true);
  18516. mm.center(me);
  18517. }
  18518. // NOTE: CSS expressions are resource intensive and to be used only as a last resort
  18519. // These expressions are removed as soon as they are no longer necessary - in the unmask method.
  18520. // In normal use cases an element will be masked for a limited period of time.
  18521. // Fix for https://sencha.jira.com/browse/EXTJSIV-19.
  18522. // IE6 strict mode and IE6-9 quirks mode takes off left+right padding when calculating width!
  18523. if (!Ext.supports.IncludePaddingInWidthCalculation && setExpression) {
  18524. mask.dom.style.setExpression('width', 'this.parentNode.offsetWidth + "px"');
  18525. }
  18526. // Some versions and modes of IE subtract top+bottom padding when calculating height.
  18527. // Different versions from those which make the same error for width!
  18528. if (!Ext.supports.IncludePaddingInHeightCalculation && setExpression) {
  18529. mask.dom.style.setExpression('height', 'this.parentNode.offsetHeight + "px"');
  18530. }
  18531. // ie will not expand full height automatically
  18532. else if (Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && me.getStyle('height') == 'auto') {
  18533. mask.setSize(undefined, me.getHeight());
  18534. }
  18535. return mask;
  18536. },
  18537. /**
  18538. * Removes a previously applied mask.
  18539. */
  18540. unmask : function() {
  18541. var me = this,
  18542. dom = me.dom,
  18543. mask = data(dom, 'mask'),
  18544. maskMsg = data(dom, 'maskMsg');
  18545. if (mask) {
  18546. // Remove resource-intensive CSS expressions as soon as they are not required.
  18547. if (mask.dom.style.clearExpression) {
  18548. mask.dom.style.clearExpression('width');
  18549. mask.dom.style.clearExpression('height');
  18550. }
  18551. if (maskMsg) {
  18552. maskMsg.remove();
  18553. data(dom, 'maskMsg', undefined);
  18554. }
  18555. mask.remove();
  18556. data(dom, 'mask', undefined);
  18557. me.removeCls([XMASKED, XMASKEDRELATIVE]);
  18558. }
  18559. },
  18560. /**
  18561. * Returns true if this element is masked. Also re-centers any displayed message within the mask.
  18562. * @return {Boolean}
  18563. */
  18564. isMasked : function() {
  18565. var me = this,
  18566. mask = data(me.dom, 'mask'),
  18567. maskMsg = data(me.dom, 'maskMsg');
  18568. if (mask && mask.isVisible()) {
  18569. if (maskMsg) {
  18570. maskMsg.center(me);
  18571. }
  18572. return true;
  18573. }
  18574. return false;
  18575. },
  18576. /**
  18577. * Creates an iframe shim for this element to keep selects and other windowed objects from
  18578. * showing through.
  18579. * @return {Ext.Element} The new shim element
  18580. */
  18581. createShim : function() {
  18582. var el = document.createElement('iframe'),
  18583. shim;
  18584. el.frameBorder = '0';
  18585. el.className = Ext.baseCSSPrefix + 'shim';
  18586. el.src = Ext.SSL_SECURE_URL;
  18587. shim = Ext.get(this.dom.parentNode.insertBefore(el, this.dom));
  18588. shim.autoBoxAdjust = false;
  18589. return shim;
  18590. }
  18591. };
  18592. }()
  18593. );
  18594. /**
  18595. * @class Ext.Element
  18596. */
  18597. Ext.Element.addMethods({
  18598. /**
  18599. * Convenience method for constructing a KeyMap
  18600. * @param {String/Number/Number[]/Object} key Either a string with the keys to listen for, the numeric key code, array of key codes or an object with the following options:
  18601. * <code>{key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}</code>
  18602. * @param {Function} fn The function to call
  18603. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the specified function is executed. Defaults to this Element.
  18604. * @return {Ext.util.KeyMap} The KeyMap created
  18605. */
  18606. addKeyListener : function(key, fn, scope){
  18607. var config;
  18608. if(typeof key != 'object' || Ext.isArray(key)){
  18609. config = {
  18610. key: key,
  18611. fn: fn,
  18612. scope: scope
  18613. };
  18614. }else{
  18615. config = {
  18616. key : key.key,
  18617. shift : key.shift,
  18618. ctrl : key.ctrl,
  18619. alt : key.alt,
  18620. fn: fn,
  18621. scope: scope
  18622. };
  18623. }
  18624. return Ext.create('Ext.util.KeyMap', this, config);
  18625. },
  18626. /**
  18627. * Creates a KeyMap for this element
  18628. * @param {Object} config The KeyMap config. See {@link Ext.util.KeyMap} for more details
  18629. * @return {Ext.util.KeyMap} The KeyMap created
  18630. */
  18631. addKeyMap : function(config){
  18632. return Ext.create('Ext.util.KeyMap', this, config);
  18633. }
  18634. });
  18635. //Import the newly-added Ext.Element functions into CompositeElementLite. We call this here because
  18636. //Element.keys.js is the last extra Ext.Element include in the ext-all.js build
  18637. Ext.CompositeElementLite.importElementMethods();
  18638. /**
  18639. * @class Ext.CompositeElementLite
  18640. */
  18641. Ext.apply(Ext.CompositeElementLite.prototype, {
  18642. addElements : function(els, root){
  18643. if(!els){
  18644. return this;
  18645. }
  18646. if(typeof els == "string"){
  18647. els = Ext.Element.selectorFunction(els, root);
  18648. }
  18649. var yels = this.elements;
  18650. Ext.each(els, function(e) {
  18651. yels.push(Ext.get(e));
  18652. });
  18653. return this;
  18654. },
  18655. /**
  18656. * Returns the first Element
  18657. * @return {Ext.Element}
  18658. */
  18659. first : function(){
  18660. return this.item(0);
  18661. },
  18662. /**
  18663. * Returns the last Element
  18664. * @return {Ext.Element}
  18665. */
  18666. last : function(){
  18667. return this.item(this.getCount()-1);
  18668. },
  18669. /**
  18670. * Returns true if this composite contains the passed element
  18671. * @param el {String/HTMLElement/Ext.Element/Number} The id of an element, or an Ext.Element, or an HtmlElement to find within the composite collection.
  18672. * @return Boolean
  18673. */
  18674. contains : function(el){
  18675. return this.indexOf(el) != -1;
  18676. },
  18677. /**
  18678. * Removes the specified element(s).
  18679. * @param {String/HTMLElement/Ext.Element/Number} el The id of an element, the Element itself, the index of the element in this composite
  18680. * or an array of any of those.
  18681. * @param {Boolean} removeDom (optional) True to also remove the element from the document
  18682. * @return {Ext.CompositeElement} this
  18683. */
  18684. removeElement : function(keys, removeDom){
  18685. var me = this,
  18686. els = this.elements,
  18687. el;
  18688. Ext.each(keys, function(val){
  18689. if ((el = (els[val] || els[val = me.indexOf(val)]))) {
  18690. if(removeDom){
  18691. if(el.dom){
  18692. el.remove();
  18693. }else{
  18694. Ext.removeNode(el);
  18695. }
  18696. }
  18697. Ext.Array.erase(els, val, 1);
  18698. }
  18699. });
  18700. return this;
  18701. }
  18702. });
  18703. /**
  18704. * @class Ext.CompositeElement
  18705. * @extends Ext.CompositeElementLite
  18706. * <p>This class encapsulates a <i>collection</i> of DOM elements, providing methods to filter
  18707. * members, or to perform collective actions upon the whole set.</p>
  18708. * <p>Although they are not listed, this class supports all of the methods of {@link Ext.Element} and
  18709. * {@link Ext.fx.Anim}. The methods from these classes will be performed on all the elements in this collection.</p>
  18710. * <p>All methods return <i>this</i> and can be chained.</p>
  18711. * Usage:
  18712. <pre><code>
  18713. var els = Ext.select("#some-el div.some-class", true);
  18714. // or select directly from an existing element
  18715. var el = Ext.get('some-el');
  18716. el.select('div.some-class', true);
  18717. els.setWidth(100); // all elements become 100 width
  18718. els.hide(true); // all elements fade out and hide
  18719. // or
  18720. els.setWidth(100).hide(true);
  18721. </code></pre>
  18722. */
  18723. Ext.CompositeElement = Ext.extend(Ext.CompositeElementLite, {
  18724. constructor : function(els, root){
  18725. this.elements = [];
  18726. this.add(els, root);
  18727. },
  18728. // private
  18729. getElement : function(el){
  18730. // In this case just return it, since we already have a reference to it
  18731. return el;
  18732. },
  18733. // private
  18734. transformElement : function(el){
  18735. return Ext.get(el);
  18736. }
  18737. });
  18738. /**
  18739. * Selects elements based on the passed CSS selector to enable {@link Ext.Element Element} methods
  18740. * to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or
  18741. * {@link Ext.CompositeElementLite CompositeElementLite} object.
  18742. * @param {String/HTMLElement[]} selector The CSS selector or an array of elements
  18743. * @param {Boolean} [unique] true to create a unique Ext.Element for each element (defaults to a shared flyweight object)
  18744. * @param {HTMLElement/String} [root] The root element of the query or id of the root
  18745. * @return {Ext.CompositeElementLite/Ext.CompositeElement}
  18746. * @member Ext.Element
  18747. * @method select
  18748. */
  18749. Ext.Element.select = function(selector, unique, root){
  18750. var els;
  18751. if(typeof selector == "string"){
  18752. els = Ext.Element.selectorFunction(selector, root);
  18753. }else if(selector.length !== undefined){
  18754. els = selector;
  18755. }else{
  18756. }
  18757. return (unique === true) ? new Ext.CompositeElement(els) : new Ext.CompositeElementLite(els);
  18758. };
  18759. /**
  18760. * Shorthand of {@link Ext.Element#select}.
  18761. * @member Ext
  18762. * @method select
  18763. * @alias Ext.Element#select
  18764. */
  18765. Ext.select = Ext.Element.select;
  18766. /*
  18767. This file is part of Ext JS 4
  18768. Copyright (c) 2011 Sencha Inc
  18769. Contact: http://www.sencha.com/contact
  18770. GNU General Public License Usage
  18771. 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.
  18772. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
  18773. */
  18774. /**
  18775. * Base class that provides a common interface for publishing events. Subclasses are expected to to have a property
  18776. * "events" with all the events defined, and, optionally, a property "listeners" with configured listeners defined.
  18777. *
  18778. * For example:
  18779. *
  18780. * Ext.define('Employee', {
  18781. * extend: 'Ext.util.Observable',
  18782. * constructor: function(config){
  18783. * this.name = config.name;
  18784. * this.addEvents({
  18785. * "fired" : true,
  18786. * "quit" : true
  18787. * });
  18788. *
  18789. * // Copy configured listeners into *this* object so that the base class's
  18790. * // constructor will add them.
  18791. * this.listeners = config.listeners;
  18792. *
  18793. * // Call our superclass constructor to complete construction process.
  18794. * this.callParent(arguments)
  18795. * }
  18796. * });
  18797. *
  18798. * This could then be used like this:
  18799. *
  18800. * var newEmployee = new Employee({
  18801. * name: employeeName,
  18802. * listeners: {
  18803. * quit: function() {
  18804. * // By default, "this" will be the object that fired the event.
  18805. * alert(this.name + " has quit!");
  18806. * }
  18807. * }
  18808. * });
  18809. */
  18810. Ext.define('Ext.util.Observable', {
  18811. /* Begin Definitions */
  18812. requires: ['Ext.util.Event'],
  18813. statics: {
  18814. /**
  18815. * Removes **all** added captures from the Observable.
  18816. *
  18817. * @param {Ext.util.Observable} o The Observable to release
  18818. * @static
  18819. */
  18820. releaseCapture: function(o) {
  18821. o.fireEvent = this.prototype.fireEvent;
  18822. },
  18823. /**
  18824. * Starts capture on the specified Observable. All events will be passed to the supplied function with the event
  18825. * name + standard signature of the event **before** the event is fired. If the supplied function returns false,
  18826. * the event will not fire.
  18827. *
  18828. * @param {Ext.util.Observable} o The Observable to capture events from.
  18829. * @param {Function} fn The function to call when an event is fired.
  18830. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. Defaults to
  18831. * the Observable firing the event.
  18832. * @static
  18833. */
  18834. capture: function(o, fn, scope) {
  18835. o.fireEvent = Ext.Function.createInterceptor(o.fireEvent, fn, scope);
  18836. },
  18837. /**
  18838. * Sets observability on the passed class constructor.
  18839. *
  18840. * This makes any event fired on any instance of the passed class also fire a single event through
  18841. * the **class** allowing for central handling of events on many instances at once.
  18842. *
  18843. * Usage:
  18844. *
  18845. * Ext.util.Observable.observe(Ext.data.Connection);
  18846. * Ext.data.Connection.on('beforerequest', function(con, options) {
  18847. * console.log('Ajax request made to ' + options.url);
  18848. * });
  18849. *
  18850. * @param {Function} c The class constructor to make observable.
  18851. * @param {Object} listeners An object containing a series of listeners to add. See {@link #addListener}.
  18852. * @static
  18853. */
  18854. observe: function(cls, listeners) {
  18855. if (cls) {
  18856. if (!cls.isObservable) {
  18857. Ext.applyIf(cls, new this());
  18858. this.capture(cls.prototype, cls.fireEvent, cls);
  18859. }
  18860. if (Ext.isObject(listeners)) {
  18861. cls.on(listeners);
  18862. }
  18863. return cls;
  18864. }
  18865. }
  18866. },
  18867. /* End Definitions */
  18868. /**
  18869. * @cfg {Object} listeners
  18870. *
  18871. * A config object containing one or more event handlers to be added to this object during initialization. This
  18872. * should be a valid listeners config object as specified in the {@link #addListener} example for attaching multiple
  18873. * handlers at once.
  18874. *
  18875. * **DOM events from Ext JS {@link Ext.Component Components}**
  18876. *
  18877. * While _some_ Ext JS Component classes export selected DOM events (e.g. "click", "mouseover" etc), this is usually
  18878. * only done when extra value can be added. For example the {@link Ext.view.View DataView}'s **`{@link
  18879. * Ext.view.View#itemclick itemclick}`** event passing the node clicked on. To access DOM events directly from a
  18880. * child element of a Component, we need to specify the `element` option to identify the Component property to add a
  18881. * DOM listener to:
  18882. *
  18883. * new Ext.panel.Panel({
  18884. * width: 400,
  18885. * height: 200,
  18886. * dockedItems: [{
  18887. * xtype: 'toolbar'
  18888. * }],
  18889. * listeners: {
  18890. * click: {
  18891. * element: 'el', //bind to the underlying el property on the panel
  18892. * fn: function(){ console.log('click el'); }
  18893. * },
  18894. * dblclick: {
  18895. * element: 'body', //bind to the underlying body property on the panel
  18896. * fn: function(){ console.log('dblclick body'); }
  18897. * }
  18898. * }
  18899. * });
  18900. */
  18901. // @private
  18902. isObservable: true,
  18903. constructor: function(config) {
  18904. var me = this;
  18905. Ext.apply(me, config);
  18906. if (me.listeners) {
  18907. me.on(me.listeners);
  18908. delete me.listeners;
  18909. }
  18910. me.events = me.events || {};
  18911. if (me.bubbleEvents) {
  18912. me.enableBubble(me.bubbleEvents);
  18913. }
  18914. },
  18915. // @private
  18916. eventOptionsRe : /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|element|vertical|horizontal|freezeEvent)$/,
  18917. /**
  18918. * Adds listeners to any Observable object (or Ext.Element) which are automatically removed when this Component is
  18919. * destroyed.
  18920. *
  18921. * @param {Ext.util.Observable/Ext.Element} item The item to which to add a listener/listeners.
  18922. * @param {Object/String} ename The event name, or an object containing event name properties.
  18923. * @param {Function} fn (optional) If the `ename` parameter was an event name, this is the handler function.
  18924. * @param {Object} scope (optional) If the `ename` parameter was an event name, this is the scope (`this` reference)
  18925. * in which the handler function is executed.
  18926. * @param {Object} opt (optional) If the `ename` parameter was an event name, this is the
  18927. * {@link Ext.util.Observable#addListener addListener} options.
  18928. */
  18929. addManagedListener : function(item, ename, fn, scope, options) {
  18930. var me = this,
  18931. managedListeners = me.managedListeners = me.managedListeners || [],
  18932. config;
  18933. if (typeof ename !== 'string') {
  18934. options = ename;
  18935. for (ename in options) {
  18936. if (options.hasOwnProperty(ename)) {
  18937. config = options[ename];
  18938. if (!me.eventOptionsRe.test(ename)) {
  18939. me.addManagedListener(item, ename, config.fn || config, config.scope || options.scope, config.fn ? config : options);
  18940. }
  18941. }
  18942. }
  18943. }
  18944. else {
  18945. managedListeners.push({
  18946. item: item,
  18947. ename: ename,
  18948. fn: fn,
  18949. scope: scope,
  18950. options: options
  18951. });
  18952. item.on(ename, fn, scope, options);
  18953. }
  18954. },
  18955. /**
  18956. * Removes listeners that were added by the {@link #mon} method.
  18957. *
  18958. * @param {Ext.util.Observable/Ext.Element} item The item from which to remove a listener/listeners.
  18959. * @param {Object/String} ename The event name, or an object containing event name properties.
  18960. * @param {Function} fn (optional) If the `ename` parameter was an event name, this is the handler function.
  18961. * @param {Object} scope (optional) If the `ename` parameter was an event name, this is the scope (`this` reference)
  18962. * in which the handler function is executed.
  18963. */
  18964. removeManagedListener : function(item, ename, fn, scope) {
  18965. var me = this,
  18966. options,
  18967. config,
  18968. managedListeners,
  18969. length,
  18970. i;
  18971. if (typeof ename !== 'string') {
  18972. options = ename;
  18973. for (ename in options) {
  18974. if (options.hasOwnProperty(ename)) {
  18975. config = options[ename];
  18976. if (!me.eventOptionsRe.test(ename)) {
  18977. me.removeManagedListener(item, ename, config.fn || config, config.scope || options.scope);
  18978. }
  18979. }
  18980. }
  18981. }
  18982. managedListeners = me.managedListeners ? me.managedListeners.slice() : [];
  18983. for (i = 0, length = managedListeners.length; i < length; i++) {
  18984. me.removeManagedListenerItem(false, managedListeners[i], item, ename, fn, scope);
  18985. }
  18986. },
  18987. /**
  18988. * Fires the specified event with the passed parameters (minus the event name, plus the `options` object passed
  18989. * to {@link #addListener}).
  18990. *
  18991. * An event may be set to bubble up an Observable parent hierarchy (See {@link Ext.Component#getBubbleTarget}) by
  18992. * calling {@link #enableBubble}.
  18993. *
  18994. * @param {String} eventName The name of the event to fire.
  18995. * @param {Object...} args Variable number of parameters are passed to handlers.
  18996. * @return {Boolean} returns false if any of the handlers return false otherwise it returns true.
  18997. */
  18998. fireEvent: function(eventName) {
  18999. var name = eventName.toLowerCase(),
  19000. events = this.events,
  19001. event = events && events[name],
  19002. bubbles = event && event.bubble;
  19003. return this.continueFireEvent(name, Ext.Array.slice(arguments, 1), bubbles);
  19004. },
  19005. /**
  19006. * Continue to fire event.
  19007. * @private
  19008. *
  19009. * @param {String} eventName
  19010. * @param {Array} args
  19011. * @param {Boolean} bubbles
  19012. */
  19013. continueFireEvent: function(eventName, args, bubbles) {
  19014. var target = this,
  19015. queue, event,
  19016. ret = true;
  19017. do {
  19018. if (target.eventsSuspended === true) {
  19019. if ((queue = target.eventQueue)) {
  19020. queue.push([eventName, args, bubbles]);
  19021. }
  19022. return ret;
  19023. } else {
  19024. event = target.events[eventName];
  19025. // Continue bubbling if event exists and it is `true` or the handler didn't returns false and it
  19026. // configure to bubble.
  19027. if (event && event != true) {
  19028. if ((ret = event.fire.apply(event, args)) === false) {
  19029. break;
  19030. }
  19031. }
  19032. }
  19033. } while (bubbles && (target = target.getBubbleParent()));
  19034. return ret;
  19035. },
  19036. /**
  19037. * Gets the bubbling parent for an Observable
  19038. * @private
  19039. * @return {Ext.util.Observable} The bubble parent. null is returned if no bubble target exists
  19040. */
  19041. getBubbleParent: function(){
  19042. var me = this, parent = me.getBubbleTarget && me.getBubbleTarget();
  19043. if (parent && parent.isObservable) {
  19044. return parent;
  19045. }
  19046. return null;
  19047. },
  19048. /**
  19049. * Appends an event handler to this object.
  19050. *
  19051. * @param {String} eventName The name of the event to listen for. May also be an object who's property names are
  19052. * event names.
  19053. * @param {Function} fn The method the event invokes. Will be called with arguments given to
  19054. * {@link #fireEvent} plus the `options` parameter described below.
  19055. * @param {Object} [scope] The scope (`this` reference) in which the handler function is executed. **If
  19056. * omitted, defaults to the object which fired the event.**
  19057. * @param {Object} [options] An object containing handler configuration.
  19058. *
  19059. * **Note:** Unlike in ExtJS 3.x, the options object will also be passed as the last argument to every event handler.
  19060. *
  19061. * This object may contain any of the following properties:
  19062. *
  19063. * - **scope** : Object
  19064. *
  19065. * The scope (`this` reference) in which the handler function is executed. **If omitted, defaults to the object
  19066. * which fired the event.**
  19067. *
  19068. * - **delay** : Number
  19069. *
  19070. * The number of milliseconds to delay the invocation of the handler after the event fires.
  19071. *
  19072. * - **single** : Boolean
  19073. *
  19074. * True to add a handler to handle just the next firing of the event, and then remove itself.
  19075. *
  19076. * - **buffer** : Number
  19077. *
  19078. * Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed by the specified number of
  19079. * milliseconds. If the event fires again within that time, the original handler is _not_ invoked, but the new
  19080. * handler is scheduled in its place.
  19081. *
  19082. * - **target** : Observable
  19083. *
  19084. * Only call the handler if the event was fired on the target Observable, _not_ if the event was bubbled up from a
  19085. * child Observable.
  19086. *
  19087. * - **element** : String
  19088. *
  19089. * **This option is only valid for listeners bound to {@link Ext.Component Components}.** The name of a Component
  19090. * property which references an element to add a listener to.
  19091. *
  19092. * This option is useful during Component construction to add DOM event listeners to elements of
  19093. * {@link Ext.Component Components} which will exist only after the Component is rendered.
  19094. * For example, to add a click listener to a Panel's body:
  19095. *
  19096. * new Ext.panel.Panel({
  19097. * title: 'The title',
  19098. * listeners: {
  19099. * click: this.handlePanelClick,
  19100. * element: 'body'
  19101. * }
  19102. * });
  19103. *
  19104. * **Combining Options**
  19105. *
  19106. * Using the options argument, it is possible to combine different types of listeners:
  19107. *
  19108. * A delayed, one-time listener.
  19109. *
  19110. * myPanel.on('hide', this.handleClick, this, {
  19111. * single: true,
  19112. * delay: 100
  19113. * });
  19114. *
  19115. * **Attaching multiple handlers in 1 call**
  19116. *
  19117. * The method also allows for a single argument to be passed which is a config object containing properties which
  19118. * specify multiple events. For example:
  19119. *
  19120. * myGridPanel.on({
  19121. * cellClick: this.onCellClick,
  19122. * mouseover: this.onMouseOver,
  19123. * mouseout: this.onMouseOut,
  19124. * scope: this // Important. Ensure "this" is correct during handler execution
  19125. * });
  19126. *
  19127. * One can also specify options for each event handler separately:
  19128. *
  19129. * myGridPanel.on({
  19130. * cellClick: {fn: this.onCellClick, scope: this, single: true},
  19131. * mouseover: {fn: panel.onMouseOver, scope: panel}
  19132. * });
  19133. *
  19134. */
  19135. addListener: function(ename, fn, scope, options) {
  19136. var me = this,
  19137. config,
  19138. event;
  19139. if (typeof ename !== 'string') {
  19140. options = ename;
  19141. for (ename in options) {
  19142. if (options.hasOwnProperty(ename)) {
  19143. config = options[ename];
  19144. if (!me.eventOptionsRe.test(ename)) {
  19145. me.addListener(ename, config.fn || config, config.scope || options.scope, config.fn ? config : options);
  19146. }
  19147. }
  19148. }
  19149. }
  19150. else {
  19151. ename = ename.toLowerCase();
  19152. me.events[ename] = me.events[ename] || true;
  19153. event = me.events[ename] || true;
  19154. if (Ext.isBoolean(event)) {
  19155. me.events[ename] = event = new Ext.util.Event(me, ename);
  19156. }
  19157. event.addListener(fn, scope, Ext.isObject(options) ? options : {});
  19158. }
  19159. },
  19160. /**
  19161. * Removes an event handler.
  19162. *
  19163. * @param {String} eventName The type of event the handler was associated with.
  19164. * @param {Function} fn The handler to remove. **This must be a reference to the function passed into the
  19165. * {@link #addListener} call.**
  19166. * @param {Object} scope (optional) The scope originally specified for the handler. It must be the same as the
  19167. * scope argument specified in the original call to {@link #addListener} or the listener will not be removed.
  19168. */
  19169. removeListener: function(ename, fn, scope) {
  19170. var me = this,
  19171. config,
  19172. event,
  19173. options;
  19174. if (typeof ename !== 'string') {
  19175. options = ename;
  19176. for (ename in options) {
  19177. if (options.hasOwnProperty(ename)) {
  19178. config = options[ename];
  19179. if (!me.eventOptionsRe.test(ename)) {
  19180. me.removeListener(ename, config.fn || config, config.scope || options.scope);
  19181. }
  19182. }
  19183. }
  19184. } else {
  19185. ename = ename.toLowerCase();
  19186. event = me.events[ename];
  19187. if (event && event.isEvent) {
  19188. event.removeListener(fn, scope);
  19189. }
  19190. }
  19191. },
  19192. /**
  19193. * Removes all listeners for this object including the managed listeners
  19194. */
  19195. clearListeners: function() {
  19196. var events = this.events,
  19197. event,
  19198. key;
  19199. for (key in events) {
  19200. if (events.hasOwnProperty(key)) {
  19201. event = events[key];
  19202. if (event.isEvent) {
  19203. event.clearListeners();
  19204. }
  19205. }
  19206. }
  19207. this.clearManagedListeners();
  19208. },
  19209. /**
  19210. * Removes all managed listeners for this object.
  19211. */
  19212. clearManagedListeners : function() {
  19213. var managedListeners = this.managedListeners || [],
  19214. i = 0,
  19215. len = managedListeners.length;
  19216. for (; i < len; i++) {
  19217. this.removeManagedListenerItem(true, managedListeners[i]);
  19218. }
  19219. this.managedListeners = [];
  19220. },
  19221. /**
  19222. * Remove a single managed listener item
  19223. * @private
  19224. * @param {Boolean} isClear True if this is being called during a clear
  19225. * @param {Object} managedListener The managed listener item
  19226. * See removeManagedListener for other args
  19227. */
  19228. removeManagedListenerItem: function(isClear, managedListener, item, ename, fn, scope){
  19229. if (isClear || (managedListener.item === item && managedListener.ename === ename && (!fn || managedListener.fn === fn) && (!scope || managedListener.scope === scope))) {
  19230. managedListener.item.un(managedListener.ename, managedListener.fn, managedListener.scope);
  19231. if (!isClear) {
  19232. Ext.Array.remove(this.managedListeners, managedListener);
  19233. }
  19234. }
  19235. },
  19236. /**
  19237. * Adds the specified events to the list of events which this Observable may fire.
  19238. *
  19239. * @param {Object/String} o Either an object with event names as properties with a value of `true` or the first
  19240. * event name string if multiple event names are being passed as separate parameters. Usage:
  19241. *
  19242. * this.addEvents({
  19243. * storeloaded: true,
  19244. * storecleared: true
  19245. * });
  19246. *
  19247. * @param {String...} more (optional) Additional event names if multiple event names are being passed as separate
  19248. * parameters. Usage:
  19249. *
  19250. * this.addEvents('storeloaded', 'storecleared');
  19251. *
  19252. */
  19253. addEvents: function(o) {
  19254. var me = this,
  19255. args,
  19256. len,
  19257. i;
  19258. me.events = me.events || {};
  19259. if (Ext.isString(o)) {
  19260. args = arguments;
  19261. i = args.length;
  19262. while (i--) {
  19263. me.events[args[i]] = me.events[args[i]] || true;
  19264. }
  19265. } else {
  19266. Ext.applyIf(me.events, o);
  19267. }
  19268. },
  19269. /**
  19270. * Checks to see if this object has any listeners for a specified event
  19271. *
  19272. * @param {String} eventName The name of the event to check for
  19273. * @return {Boolean} True if the event is being listened for, else false
  19274. */
  19275. hasListener: function(ename) {
  19276. var event = this.events[ename.toLowerCase()];
  19277. return event && event.isEvent === true && event.listeners.length > 0;
  19278. },
  19279. /**
  19280. * Suspends the firing of all events. (see {@link #resumeEvents})
  19281. *
  19282. * @param {Boolean} queueSuspended Pass as true to queue up suspended events to be fired
  19283. * after the {@link #resumeEvents} call instead of discarding all suspended events.
  19284. */
  19285. suspendEvents: function(queueSuspended) {
  19286. this.eventsSuspended = true;
  19287. if (queueSuspended && !this.eventQueue) {
  19288. this.eventQueue = [];
  19289. }
  19290. },
  19291. /**
  19292. * Resumes firing events (see {@link #suspendEvents}).
  19293. *
  19294. * If events were suspended using the `queueSuspended` parameter, then all events fired
  19295. * during event suspension will be sent to any listeners now.
  19296. */
  19297. resumeEvents: function() {
  19298. var me = this,
  19299. queued = me.eventQueue;
  19300. me.eventsSuspended = false;
  19301. delete me.eventQueue;
  19302. if (queued) {
  19303. Ext.each(queued, function(e) {
  19304. me.continueFireEvent.apply(me, e);
  19305. });
  19306. }
  19307. },
  19308. /**
  19309. * Relays selected events from the specified Observable as if the events were fired by `this`.
  19310. *
  19311. * @param {Object} origin The Observable whose events this object is to relay.
  19312. * @param {String[]} events Array of event names to relay.
  19313. * @param {String} prefix
  19314. */
  19315. relayEvents : function(origin, events, prefix) {
  19316. prefix = prefix || '';
  19317. var me = this,
  19318. len = events.length,
  19319. i = 0,
  19320. oldName,
  19321. newName;
  19322. for (; i < len; i++) {
  19323. oldName = events[i].substr(prefix.length);
  19324. newName = prefix + oldName;
  19325. me.events[newName] = me.events[newName] || true;
  19326. origin.on(oldName, me.createRelayer(newName));
  19327. }
  19328. },
  19329. /**
  19330. * @private
  19331. * Creates an event handling function which refires the event from this object as the passed event name.
  19332. * @param newName
  19333. * @returns {Function}
  19334. */
  19335. createRelayer: function(newName){
  19336. var me = this;
  19337. return function(){
  19338. return me.fireEvent.apply(me, [newName].concat(Array.prototype.slice.call(arguments, 0, -1)));
  19339. };
  19340. },
  19341. /**
  19342. * Enables events fired by this Observable to bubble up an owner hierarchy by calling `this.getBubbleTarget()` if
  19343. * present. There is no implementation in the Observable base class.
  19344. *
  19345. * This is commonly used by Ext.Components to bubble events to owner Containers.
  19346. * See {@link Ext.Component#getBubbleTarget}. The default implementation in Ext.Component returns the
  19347. * Component's immediate owner. But if a known target is required, this can be overridden to access the
  19348. * required target more quickly.
  19349. *
  19350. * Example:
  19351. *
  19352. * Ext.override(Ext.form.field.Base, {
  19353. * // Add functionality to Field's initComponent to enable the change event to bubble
  19354. * initComponent : Ext.Function.createSequence(Ext.form.field.Base.prototype.initComponent, function() {
  19355. * this.enableBubble('change');
  19356. * }),
  19357. *
  19358. * // We know that we want Field's events to bubble directly to the FormPanel.
  19359. * getBubbleTarget : function() {
  19360. * if (!this.formPanel) {
  19361. * this.formPanel = this.findParentByType('form');
  19362. * }
  19363. * return this.formPanel;
  19364. * }
  19365. * });
  19366. *
  19367. * var myForm = new Ext.formPanel({
  19368. * title: 'User Details',
  19369. * items: [{
  19370. * ...
  19371. * }],
  19372. * listeners: {
  19373. * change: function() {
  19374. * // Title goes red if form has been modified.
  19375. * myForm.header.setStyle('color', 'red');
  19376. * }
  19377. * }
  19378. * });
  19379. *
  19380. * @param {String/String[]} events The event name to bubble, or an Array of event names.
  19381. */
  19382. enableBubble: function(events) {
  19383. var me = this;
  19384. if (!Ext.isEmpty(events)) {
  19385. events = Ext.isArray(events) ? events: Ext.Array.toArray(arguments);
  19386. Ext.each(events,
  19387. function(ename) {
  19388. ename = ename.toLowerCase();
  19389. var ce = me.events[ename] || true;
  19390. if (Ext.isBoolean(ce)) {
  19391. ce = new Ext.util.Event(me, ename);
  19392. me.events[ename] = ce;
  19393. }
  19394. ce.bubble = true;
  19395. });
  19396. }
  19397. }
  19398. }, function() {
  19399. this.createAlias({
  19400. /**
  19401. * @method
  19402. * Shorthand for {@link #addListener}.
  19403. * @alias Ext.util.Observable#addListener
  19404. */
  19405. on: 'addListener',
  19406. /**
  19407. * @method
  19408. * Shorthand for {@link #removeListener}.
  19409. * @alias Ext.util.Observable#removeListener
  19410. */
  19411. un: 'removeListener',
  19412. /**
  19413. * @method
  19414. * Shorthand for {@link #addManagedListener}.
  19415. * @alias Ext.util.Observable#addManagedListener
  19416. */
  19417. mon: 'addManagedListener',
  19418. /**
  19419. * @method
  19420. * Shorthand for {@link #removeManagedListener}.
  19421. * @alias Ext.util.Observable#removeManagedListener
  19422. */
  19423. mun: 'removeManagedListener'
  19424. });
  19425. //deprecated, will be removed in 5.0
  19426. this.observeClass = this.observe;
  19427. Ext.apply(Ext.util.Observable.prototype, function(){
  19428. // this is considered experimental (along with beforeMethod, afterMethod, removeMethodListener?)
  19429. // allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call
  19430. // private
  19431. function getMethodEvent(method){
  19432. var e = (this.methodEvents = this.methodEvents || {})[method],
  19433. returnValue,
  19434. v,
  19435. cancel,
  19436. obj = this;
  19437. if (!e) {
  19438. this.methodEvents[method] = e = {};
  19439. e.originalFn = this[method];
  19440. e.methodName = method;
  19441. e.before = [];
  19442. e.after = [];
  19443. var makeCall = function(fn, scope, args){
  19444. if((v = fn.apply(scope || obj, args)) !== undefined){
  19445. if (typeof v == 'object') {
  19446. if(v.returnValue !== undefined){
  19447. returnValue = v.returnValue;
  19448. }else{
  19449. returnValue = v;
  19450. }
  19451. cancel = !!v.cancel;
  19452. }
  19453. else
  19454. if (v === false) {
  19455. cancel = true;
  19456. }
  19457. else {
  19458. returnValue = v;
  19459. }
  19460. }
  19461. };
  19462. this[method] = function(){
  19463. var args = Array.prototype.slice.call(arguments, 0),
  19464. b, i, len;
  19465. returnValue = v = undefined;
  19466. cancel = false;
  19467. for(i = 0, len = e.before.length; i < len; i++){
  19468. b = e.before[i];
  19469. makeCall(b.fn, b.scope, args);
  19470. if (cancel) {
  19471. return returnValue;
  19472. }
  19473. }
  19474. if((v = e.originalFn.apply(obj, args)) !== undefined){
  19475. returnValue = v;
  19476. }
  19477. for(i = 0, len = e.after.length; i < len; i++){
  19478. b = e.after[i];
  19479. makeCall(b.fn, b.scope, args);
  19480. if (cancel) {
  19481. return returnValue;
  19482. }
  19483. }
  19484. return returnValue;
  19485. };
  19486. }
  19487. return e;
  19488. }
  19489. return {
  19490. // these are considered experimental
  19491. // allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call
  19492. // adds an 'interceptor' called before the original method
  19493. beforeMethod : function(method, fn, scope){
  19494. getMethodEvent.call(this, method).before.push({
  19495. fn: fn,
  19496. scope: scope
  19497. });
  19498. },
  19499. // adds a 'sequence' called after the original method
  19500. afterMethod : function(method, fn, scope){
  19501. getMethodEvent.call(this, method).after.push({
  19502. fn: fn,
  19503. scope: scope
  19504. });
  19505. },
  19506. removeMethodListener: function(method, fn, scope){
  19507. var e = this.getMethodEvent(method),
  19508. i, len;
  19509. for(i = 0, len = e.before.length; i < len; i++){
  19510. if(e.before[i].fn == fn && e.before[i].scope == scope){
  19511. Ext.Array.erase(e.before, i, 1);
  19512. return;
  19513. }
  19514. }
  19515. for(i = 0, len = e.after.length; i < len; i++){
  19516. if(e.after[i].fn == fn && e.after[i].scope == scope){
  19517. Ext.Array.erase(e.after, i, 1);
  19518. return;
  19519. }
  19520. }
  19521. },
  19522. toggleEventLogging: function(toggle) {
  19523. Ext.util.Observable[toggle ? 'capture' : 'releaseCapture'](this, function(en) {
  19524. if (Ext.isDefined(Ext.global.console)) {
  19525. Ext.global.console.log(en, arguments);
  19526. }
  19527. });
  19528. }
  19529. };
  19530. }());
  19531. });
  19532. /**
  19533. * @class Ext.util.Animate
  19534. * This animation class is a mixin.
  19535. *
  19536. * Ext.util.Animate provides an API for the creation of animated transitions of properties and styles.
  19537. * This class is used as a mixin and currently applied to {@link Ext.Element}, {@link Ext.CompositeElement},
  19538. * {@link Ext.draw.Sprite}, {@link Ext.draw.CompositeSprite}, and {@link Ext.Component}. Note that Components
  19539. * have a limited subset of what attributes can be animated such as top, left, x, y, height, width, and
  19540. * opacity (color, paddings, and margins can not be animated).
  19541. *
  19542. * ## Animation Basics
  19543. *
  19544. * All animations require three things - `easing`, `duration`, and `to` (the final end value for each property)
  19545. * you wish to animate. Easing and duration are defaulted values specified below.
  19546. * Easing describes how the intermediate values used during a transition will be calculated.
  19547. * {@link Ext.fx.Anim#easing Easing} allows for a transition to change speed over its duration.
  19548. * You may use the defaults for easing and duration, but you must always set a
  19549. * {@link Ext.fx.Anim#to to} property which is the end value for all animations.
  19550. *
  19551. * Popular element 'to' configurations are:
  19552. *
  19553. * - opacity
  19554. * - x
  19555. * - y
  19556. * - color
  19557. * - height
  19558. * - width
  19559. *
  19560. * Popular sprite 'to' configurations are:
  19561. *
  19562. * - translation
  19563. * - path
  19564. * - scale
  19565. * - stroke
  19566. * - rotation
  19567. *
  19568. * The default duration for animations is 250 (which is a 1/4 of a second). Duration is denoted in
  19569. * milliseconds. Therefore 1 second is 1000, 1 minute would be 60000, and so on. The default easing curve
  19570. * used for all animations is 'ease'. Popular easing functions are included and can be found in {@link Ext.fx.Anim#easing Easing}.
  19571. *
  19572. * For example, a simple animation to fade out an element with a default easing and duration:
  19573. *
  19574. * var p1 = Ext.get('myElementId');
  19575. *
  19576. * p1.animate({
  19577. * to: {
  19578. * opacity: 0
  19579. * }
  19580. * });
  19581. *
  19582. * To make this animation fade out in a tenth of a second:
  19583. *
  19584. * var p1 = Ext.get('myElementId');
  19585. *
  19586. * p1.animate({
  19587. * duration: 100,
  19588. * to: {
  19589. * opacity: 0
  19590. * }
  19591. * });
  19592. *
  19593. * ## Animation Queues
  19594. *
  19595. * By default all animations are added to a queue which allows for animation via a chain-style API.
  19596. * For example, the following code will queue 4 animations which occur sequentially (one right after the other):
  19597. *
  19598. * p1.animate({
  19599. * to: {
  19600. * x: 500
  19601. * }
  19602. * }).animate({
  19603. * to: {
  19604. * y: 150
  19605. * }
  19606. * }).animate({
  19607. * to: {
  19608. * backgroundColor: '#f00' //red
  19609. * }
  19610. * }).animate({
  19611. * to: {
  19612. * opacity: 0
  19613. * }
  19614. * });
  19615. *
  19616. * You can change this behavior by calling the {@link Ext.util.Animate#syncFx syncFx} method and all
  19617. * subsequent animations for the specified target will be run concurrently (at the same time).
  19618. *
  19619. * p1.syncFx(); //this will make all animations run at the same time
  19620. *
  19621. * p1.animate({
  19622. * to: {
  19623. * x: 500
  19624. * }
  19625. * }).animate({
  19626. * to: {
  19627. * y: 150
  19628. * }
  19629. * }).animate({
  19630. * to: {
  19631. * backgroundColor: '#f00' //red
  19632. * }
  19633. * }).animate({
  19634. * to: {
  19635. * opacity: 0
  19636. * }
  19637. * });
  19638. *
  19639. * This works the same as:
  19640. *
  19641. * p1.animate({
  19642. * to: {
  19643. * x: 500,
  19644. * y: 150,
  19645. * backgroundColor: '#f00' //red
  19646. * opacity: 0
  19647. * }
  19648. * });
  19649. *
  19650. * The {@link Ext.util.Animate#stopAnimation stopAnimation} method can be used to stop any
  19651. * currently running animations and clear any queued animations.
  19652. *
  19653. * ## Animation Keyframes
  19654. *
  19655. * You can also set up complex animations with {@link Ext.fx.Anim#keyframes keyframes} which follow the
  19656. * CSS3 Animation configuration pattern. Note rotation, translation, and scaling can only be done for sprites.
  19657. * The previous example can be written with the following syntax:
  19658. *
  19659. * p1.animate({
  19660. * duration: 1000, //one second total
  19661. * keyframes: {
  19662. * 25: { //from 0 to 250ms (25%)
  19663. * x: 0
  19664. * },
  19665. * 50: { //from 250ms to 500ms (50%)
  19666. * y: 0
  19667. * },
  19668. * 75: { //from 500ms to 750ms (75%)
  19669. * backgroundColor: '#f00' //red
  19670. * },
  19671. * 100: { //from 750ms to 1sec
  19672. * opacity: 0
  19673. * }
  19674. * }
  19675. * });
  19676. *
  19677. * ## Animation Events
  19678. *
  19679. * Each animation you create has events for {@link Ext.fx.Anim#beforeanimate beforeanimate},
  19680. * {@link Ext.fx.Anim#afteranimate afteranimate}, and {@link Ext.fx.Anim#lastframe lastframe}.
  19681. * Keyframed animations adds an additional {@link Ext.fx.Animator#keyframe keyframe} event which
  19682. * fires for each keyframe in your animation.
  19683. *
  19684. * All animations support the {@link Ext.util.Observable#listeners listeners} configuration to attact functions to these events.
  19685. *
  19686. * startAnimate: function() {
  19687. * var p1 = Ext.get('myElementId');
  19688. * p1.animate({
  19689. * duration: 100,
  19690. * to: {
  19691. * opacity: 0
  19692. * },
  19693. * listeners: {
  19694. * beforeanimate: function() {
  19695. * // Execute my custom method before the animation
  19696. * this.myBeforeAnimateFn();
  19697. * },
  19698. * afteranimate: function() {
  19699. * // Execute my custom method after the animation
  19700. * this.myAfterAnimateFn();
  19701. * },
  19702. * scope: this
  19703. * });
  19704. * },
  19705. * myBeforeAnimateFn: function() {
  19706. * // My custom logic
  19707. * },
  19708. * myAfterAnimateFn: function() {
  19709. * // My custom logic
  19710. * }
  19711. *
  19712. * Due to the fact that animations run asynchronously, you can determine if an animation is currently
  19713. * running on any target by using the {@link Ext.util.Animate#getActiveAnimation getActiveAnimation}
  19714. * method. This method will return false if there are no active animations or return the currently
  19715. * running {@link Ext.fx.Anim} instance.
  19716. *
  19717. * In this example, we're going to wait for the current animation to finish, then stop any other
  19718. * queued animations before we fade our element's opacity to 0:
  19719. *
  19720. * var curAnim = p1.getActiveAnimation();
  19721. * if (curAnim) {
  19722. * curAnim.on('afteranimate', function() {
  19723. * p1.stopAnimation();
  19724. * p1.animate({
  19725. * to: {
  19726. * opacity: 0
  19727. * }
  19728. * });
  19729. * });
  19730. * }
  19731. *
  19732. * @docauthor Jamie Avins <jamie@sencha.com>
  19733. */
  19734. Ext.define('Ext.util.Animate', {
  19735. uses: ['Ext.fx.Manager', 'Ext.fx.Anim'],
  19736. /**
  19737. * <p>Perform custom animation on this object.<p>
  19738. * <p>This method is applicable to both the {@link Ext.Component Component} class and the {@link Ext.Element Element} class.
  19739. * It performs animated transitions of certain properties of this object over a specified timeline.</p>
  19740. * <p>The sole parameter is an object which specifies start property values, end property values, and properties which
  19741. * describe the timeline. Of the properties listed below, only <b><code>to</code></b> is mandatory.</p>
  19742. * <p>Properties include<ul>
  19743. * <li><code>from</code> <div class="sub-desc">An object which specifies start values for the properties being animated.
  19744. * If not supplied, properties are animated from current settings. The actual properties which may be animated depend upon
  19745. * ths object being animated. See the sections below on Element and Component animation.<div></li>
  19746. * <li><code>to</code> <div class="sub-desc">An object which specifies end values for the properties being animated.</div></li>
  19747. * <li><code>duration</code><div class="sub-desc">The duration <b>in milliseconds</b> for which the animation will run.</div></li>
  19748. * <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>
  19749. * <li>ease</li>
  19750. * <li>easeIn</li>
  19751. * <li>easeOut</li>
  19752. * <li>easeInOut</li>
  19753. * <li>backIn</li>
  19754. * <li>backOut</li>
  19755. * <li>elasticIn</li>
  19756. * <li>elasticOut</li>
  19757. * <li>bounceIn</li>
  19758. * <li>bounceOut</li>
  19759. * </ul></code></div></li>
  19760. * <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.
  19761. * 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>
  19762. * <li><code>listeners</code> <div class="sub-desc">This is a standard {@link Ext.util.Observable#listeners listeners} configuration object which may be used
  19763. * to inject behaviour at either the <code>beforeanimate</code> event or the <code>afteranimate</code> event.</div></li>
  19764. * </ul></p>
  19765. * <h3>Animating an {@link Ext.Element Element}</h3>
  19766. * When animating an Element, the following properties may be specified in <code>from</code>, <code>to</code>, and <code>keyframe</code> objects:<ul>
  19767. * <li><code>x</code> <div class="sub-desc">The page X position in pixels.</div></li>
  19768. * <li><code>y</code> <div class="sub-desc">The page Y position in pixels</div></li>
  19769. * <li><code>left</code> <div class="sub-desc">The element's CSS <code>left</code> value. Units must be supplied.</div></li>
  19770. * <li><code>top</code> <div class="sub-desc">The element's CSS <code>top</code> value. Units must be supplied.</div></li>
  19771. * <li><code>width</code> <div class="sub-desc">The element's CSS <code>width</code> value. Units must be supplied.</div></li>
  19772. * <li><code>height</code> <div class="sub-desc">The element's CSS <code>height</code> value. Units must be supplied.</div></li>
  19773. * <li><code>scrollLeft</code> <div class="sub-desc">The element's <code>scrollLeft</code> value.</div></li>
  19774. * <li><code>scrollTop</code> <div class="sub-desc">The element's <code>scrollLeft</code> value.</div></li>
  19775. * <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>
  19776. * </ul>
  19777. * <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
  19778. * 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
  19779. * directly animate certain properties of Components.</b></p>
  19780. * <h3>Animating a {@link Ext.Component Component}</h3>
  19781. * When animating an Element, the following properties may be specified in <code>from</code>, <code>to</code>, and <code>keyframe</code> objects:<ul>
  19782. * <li><code>x</code> <div class="sub-desc">The Component's page X position in pixels.</div></li>
  19783. * <li><code>y</code> <div class="sub-desc">The Component's page Y position in pixels</div></li>
  19784. * <li><code>left</code> <div class="sub-desc">The Component's <code>left</code> value in pixels.</div></li>
  19785. * <li><code>top</code> <div class="sub-desc">The Component's <code>top</code> value in pixels.</div></li>
  19786. * <li><code>width</code> <div class="sub-desc">The Component's <code>width</code> value in pixels.</div></li>
  19787. * <li><code>width</code> <div class="sub-desc">The Component's <code>width</code> value in pixels.</div></li>
  19788. * <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
  19789. * of the animation. <i>Use sparingly as laying out on every intermediate size change is an expensive operation</i>.</div></li>
  19790. * </ul>
  19791. * <p>For example, to animate a Window to a new size, ensuring that its internal layout, and any shadow is correct:</p>
  19792. * <pre><code>
  19793. myWindow = Ext.create('Ext.window.Window', {
  19794. title: 'Test Component animation',
  19795. width: 500,
  19796. height: 300,
  19797. layout: {
  19798. type: 'hbox',
  19799. align: 'stretch'
  19800. },
  19801. items: [{
  19802. title: 'Left: 33%',
  19803. margins: '5 0 5 5',
  19804. flex: 1
  19805. }, {
  19806. title: 'Left: 66%',
  19807. margins: '5 5 5 5',
  19808. flex: 2
  19809. }]
  19810. });
  19811. myWindow.show();
  19812. myWindow.header.el.on('click', function() {
  19813. myWindow.animate({
  19814. to: {
  19815. width: (myWindow.getWidth() == 500) ? 700 : 500,
  19816. height: (myWindow.getHeight() == 300) ? 400 : 300,
  19817. }
  19818. });
  19819. });
  19820. </code></pre>
  19821. * <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
  19822. * 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>
  19823. * @param {Object} config An object containing properties which describe the animation's start and end states, and the timeline of the animation.
  19824. * @return {Object} this
  19825. */
  19826. animate: function(animObj) {
  19827. var me = this;
  19828. if (Ext.fx.Manager.hasFxBlock(me.id)) {
  19829. return me;
  19830. }
  19831. Ext.fx.Manager.queueFx(Ext.create('Ext.fx.Anim', me.anim(animObj)));
  19832. return this;
  19833. },
  19834. // @private - process the passed fx configuration.
  19835. anim: function(config) {
  19836. if (!Ext.isObject(config)) {
  19837. return (config) ? {} : false;
  19838. }
  19839. var me = this;
  19840. if (config.stopAnimation) {
  19841. me.stopAnimation();
  19842. }
  19843. Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id));
  19844. return Ext.apply({
  19845. target: me,
  19846. paused: true
  19847. }, config);
  19848. },
  19849. /**
  19850. * @deprecated 4.0 Replaced by {@link #stopAnimation}
  19851. * Stops any running effects and clears this object's internal effects queue if it contains
  19852. * any additional effects that haven't started yet.
  19853. * @return {Ext.Element} The Element
  19854. * @method
  19855. */
  19856. stopFx: Ext.Function.alias(Ext.util.Animate, 'stopAnimation'),
  19857. /**
  19858. * Stops any running effects and clears this object's internal effects queue if it contains
  19859. * any additional effects that haven't started yet.
  19860. * @return {Ext.Element} The Element
  19861. */
  19862. stopAnimation: function() {
  19863. Ext.fx.Manager.stopAnimation(this.id);
  19864. return this;
  19865. },
  19866. /**
  19867. * Ensures that all effects queued after syncFx is called on this object are
  19868. * run concurrently. This is the opposite of {@link #sequenceFx}.
  19869. * @return {Object} this
  19870. */
  19871. syncFx: function() {
  19872. Ext.fx.Manager.setFxDefaults(this.id, {
  19873. concurrent: true
  19874. });
  19875. return this;
  19876. },
  19877. /**
  19878. * Ensures that all effects queued after sequenceFx is called on this object are
  19879. * run in sequence. This is the opposite of {@link #syncFx}.
  19880. * @return {Object} this
  19881. */
  19882. sequenceFx: function() {
  19883. Ext.fx.Manager.setFxDefaults(this.id, {
  19884. concurrent: false
  19885. });
  19886. return this;
  19887. },
  19888. /**
  19889. * @deprecated 4.0 Replaced by {@link #getActiveAnimation}
  19890. * @alias Ext.util.Animate#getActiveAnimation
  19891. * @method
  19892. */
  19893. hasActiveFx: Ext.Function.alias(Ext.util.Animate, 'getActiveAnimation'),
  19894. /**
  19895. * Returns the current animation if this object has any effects actively running or queued, else returns false.
  19896. * @return {Ext.fx.Anim/Boolean} Anim if element has active effects, else false
  19897. */
  19898. getActiveAnimation: function() {
  19899. return Ext.fx.Manager.getActiveAnimation(this.id);
  19900. }
  19901. }, function(){
  19902. // Apply Animate mixin manually until Element is defined in the proper 4.x way
  19903. Ext.applyIf(Ext.Element.prototype, this.prototype);
  19904. // We need to call this again so the animation methods get copied over to CE
  19905. Ext.CompositeElementLite.importElementMethods();
  19906. });
  19907. /**
  19908. * @class Ext.state.Provider
  19909. * <p>Abstract base class for state provider implementations. The provider is responsible
  19910. * for setting values and extracting values to/from the underlying storage source. The
  19911. * storage source can vary and the details should be implemented in a subclass. For example
  19912. * a provider could use a server side database or the browser localstorage where supported.</p>
  19913. *
  19914. * <p>This class provides methods for encoding and decoding <b>typed</b> variables including
  19915. * dates and defines the Provider interface. By default these methods put the value and the
  19916. * type information into a delimited string that can be stored. These should be overridden in
  19917. * a subclass if you want to change the format of the encoded value and subsequent decoding.</p>
  19918. */
  19919. Ext.define('Ext.state.Provider', {
  19920. mixins: {
  19921. observable: 'Ext.util.Observable'
  19922. },
  19923. /**
  19924. * @cfg {String} prefix A string to prefix to items stored in the underlying state store.
  19925. * Defaults to <tt>'ext-'</tt>
  19926. */
  19927. prefix: 'ext-',
  19928. constructor : function(config){
  19929. config = config || {};
  19930. var me = this;
  19931. Ext.apply(me, config);
  19932. /**
  19933. * @event statechange
  19934. * Fires when a state change occurs.
  19935. * @param {Ext.state.Provider} this This state provider
  19936. * @param {String} key The state key which was changed
  19937. * @param {String} value The encoded value for the state
  19938. */
  19939. me.addEvents("statechange");
  19940. me.state = {};
  19941. me.mixins.observable.constructor.call(me);
  19942. },
  19943. /**
  19944. * Returns the current value for a key
  19945. * @param {String} name The key name
  19946. * @param {Object} defaultValue A default value to return if the key's value is not found
  19947. * @return {Object} The state data
  19948. */
  19949. get : function(name, defaultValue){
  19950. return typeof this.state[name] == "undefined" ?
  19951. defaultValue : this.state[name];
  19952. },
  19953. /**
  19954. * Clears a value from the state
  19955. * @param {String} name The key name
  19956. */
  19957. clear : function(name){
  19958. var me = this;
  19959. delete me.state[name];
  19960. me.fireEvent("statechange", me, name, null);
  19961. },
  19962. /**
  19963. * Sets the value for a key
  19964. * @param {String} name The key name
  19965. * @param {Object} value The value to set
  19966. */
  19967. set : function(name, value){
  19968. var me = this;
  19969. me.state[name] = value;
  19970. me.fireEvent("statechange", me, name, value);
  19971. },
  19972. /**
  19973. * Decodes a string previously encoded with {@link #encodeValue}.
  19974. * @param {String} value The value to decode
  19975. * @return {Object} The decoded value
  19976. */
  19977. decodeValue : function(value){
  19978. // a -> Array
  19979. // n -> Number
  19980. // d -> Date
  19981. // b -> Boolean
  19982. // s -> String
  19983. // o -> Object
  19984. // -> Empty (null)
  19985. var me = this,
  19986. re = /^(a|n|d|b|s|o|e)\:(.*)$/,
  19987. matches = re.exec(unescape(value)),
  19988. all,
  19989. type,
  19990. value,
  19991. keyValue;
  19992. if(!matches || !matches[1]){
  19993. return; // non state
  19994. }
  19995. type = matches[1];
  19996. value = matches[2];
  19997. switch (type) {
  19998. case 'e':
  19999. return null;
  20000. case 'n':
  20001. return parseFloat(value);
  20002. case 'd':
  20003. return new Date(Date.parse(value));
  20004. case 'b':
  20005. return (value == '1');
  20006. case 'a':
  20007. all = [];
  20008. if(value != ''){
  20009. Ext.each(value.split('^'), function(val){
  20010. all.push(me.decodeValue(val));
  20011. }, me);
  20012. }
  20013. return all;
  20014. case 'o':
  20015. all = {};
  20016. if(value != ''){
  20017. Ext.each(value.split('^'), function(val){
  20018. keyValue = val.split('=');
  20019. all[keyValue[0]] = me.decodeValue(keyValue[1]);
  20020. }, me);
  20021. }
  20022. return all;
  20023. default:
  20024. return value;
  20025. }
  20026. },
  20027. /**
  20028. * Encodes a value including type information. Decode with {@link #decodeValue}.
  20029. * @param {Object} value The value to encode
  20030. * @return {String} The encoded value
  20031. */
  20032. encodeValue : function(value){
  20033. var flat = '',
  20034. i = 0,
  20035. enc,
  20036. len,
  20037. key;
  20038. if (value == null) {
  20039. return 'e:1';
  20040. } else if(typeof value == 'number') {
  20041. enc = 'n:' + value;
  20042. } else if(typeof value == 'boolean') {
  20043. enc = 'b:' + (value ? '1' : '0');
  20044. } else if(Ext.isDate(value)) {
  20045. enc = 'd:' + value.toGMTString();
  20046. } else if(Ext.isArray(value)) {
  20047. for (len = value.length; i < len; i++) {
  20048. flat += this.encodeValue(value[i]);
  20049. if (i != len - 1) {
  20050. flat += '^';
  20051. }
  20052. }
  20053. enc = 'a:' + flat;
  20054. } else if (typeof value == 'object') {
  20055. for (key in value) {
  20056. if (typeof value[key] != 'function' && value[key] !== undefined) {
  20057. flat += key + '=' + this.encodeValue(value[key]) + '^';
  20058. }
  20059. }
  20060. enc = 'o:' + flat.substring(0, flat.length-1);
  20061. } else {
  20062. enc = 's:' + value;
  20063. }
  20064. return escape(enc);
  20065. }
  20066. });
  20067. /**
  20068. * Provides searching of Components within Ext.ComponentManager (globally) or a specific
  20069. * Ext.container.Container on the document with a similar syntax to a CSS selector.
  20070. *
  20071. * Components can be retrieved by using their {@link Ext.Component xtype} with an optional . prefix
  20072. *
  20073. * - `component` or `.component`
  20074. * - `gridpanel` or `.gridpanel`
  20075. *
  20076. * An itemId or id must be prefixed with a #
  20077. *
  20078. * - `#myContainer`
  20079. *
  20080. * Attributes must be wrapped in brackets
  20081. *
  20082. * - `component[autoScroll]`
  20083. * - `panel[title="Test"]`
  20084. *
  20085. * Member expressions from candidate Components may be tested. If the expression returns a *truthy* value,
  20086. * the candidate Component will be included in the query:
  20087. *
  20088. * var disabledFields = myFormPanel.query("{isDisabled()}");
  20089. *
  20090. * Pseudo classes may be used to filter results in the same way as in {@link Ext.DomQuery DomQuery}:
  20091. *
  20092. * // Function receives array and returns a filtered array.
  20093. * Ext.ComponentQuery.pseudos.invalid = function(items) {
  20094. * var i = 0, l = items.length, c, result = [];
  20095. * for (; i < l; i++) {
  20096. * if (!(c = items[i]).isValid()) {
  20097. * result.push(c);
  20098. * }
  20099. * }
  20100. * return result;
  20101. * };
  20102. *
  20103. * var invalidFields = myFormPanel.query('field:invalid');
  20104. * if (invalidFields.length) {
  20105. * invalidFields[0].getEl().scrollIntoView(myFormPanel.body);
  20106. * for (var i = 0, l = invalidFields.length; i < l; i++) {
  20107. * invalidFields[i].getEl().frame("red");
  20108. * }
  20109. * }
  20110. *
  20111. * Default pseudos include:
  20112. *
  20113. * - not
  20114. * - last
  20115. *
  20116. * Queries return an array of components.
  20117. * Here are some example queries.
  20118. *
  20119. * // retrieve all Ext.Panels in the document by xtype
  20120. * var panelsArray = Ext.ComponentQuery.query('panel');
  20121. *
  20122. * // retrieve all Ext.Panels within the container with an id myCt
  20123. * var panelsWithinmyCt = Ext.ComponentQuery.query('#myCt panel');
  20124. *
  20125. * // retrieve all direct children which are Ext.Panels within myCt
  20126. * var directChildPanel = Ext.ComponentQuery.query('#myCt > panel');
  20127. *
  20128. * // retrieve all grids and trees
  20129. * var gridsAndTrees = Ext.ComponentQuery.query('gridpanel, treepanel');
  20130. *
  20131. * For easy access to queries based from a particular Container see the {@link Ext.container.Container#query},
  20132. * {@link Ext.container.Container#down} and {@link Ext.container.Container#child} methods. Also see
  20133. * {@link Ext.Component#up}.
  20134. */
  20135. Ext.define('Ext.ComponentQuery', {
  20136. singleton: true,
  20137. uses: ['Ext.ComponentManager']
  20138. }, function() {
  20139. var cq = this,
  20140. // A function source code pattern with a placeholder which accepts an expression which yields a truth value when applied
  20141. // as a member on each item in the passed array.
  20142. filterFnPattern = [
  20143. 'var r = [],',
  20144. 'i = 0,',
  20145. 'it = items,',
  20146. 'l = it.length,',
  20147. 'c;',
  20148. 'for (; i < l; i++) {',
  20149. 'c = it[i];',
  20150. 'if (c.{0}) {',
  20151. 'r.push(c);',
  20152. '}',
  20153. '}',
  20154. 'return r;'
  20155. ].join(''),
  20156. filterItems = function(items, operation) {
  20157. // Argument list for the operation is [ itemsArray, operationArg1, operationArg2...]
  20158. // The operation's method loops over each item in the candidate array and
  20159. // returns an array of items which match its criteria
  20160. return operation.method.apply(this, [ items ].concat(operation.args));
  20161. },
  20162. getItems = function(items, mode) {
  20163. var result = [],
  20164. i = 0,
  20165. length = items.length,
  20166. candidate,
  20167. deep = mode !== '>';
  20168. for (; i < length; i++) {
  20169. candidate = items[i];
  20170. if (candidate.getRefItems) {
  20171. result = result.concat(candidate.getRefItems(deep));
  20172. }
  20173. }
  20174. return result;
  20175. },
  20176. getAncestors = function(items) {
  20177. var result = [],
  20178. i = 0,
  20179. length = items.length,
  20180. candidate;
  20181. for (; i < length; i++) {
  20182. candidate = items[i];
  20183. while (!!(candidate = (candidate.ownerCt || candidate.floatParent))) {
  20184. result.push(candidate);
  20185. }
  20186. }
  20187. return result;
  20188. },
  20189. // Filters the passed candidate array and returns only items which match the passed xtype
  20190. filterByXType = function(items, xtype, shallow) {
  20191. if (xtype === '*') {
  20192. return items.slice();
  20193. }
  20194. else {
  20195. var result = [],
  20196. i = 0,
  20197. length = items.length,
  20198. candidate;
  20199. for (; i < length; i++) {
  20200. candidate = items[i];
  20201. if (candidate.isXType(xtype, shallow)) {
  20202. result.push(candidate);
  20203. }
  20204. }
  20205. return result;
  20206. }
  20207. },
  20208. // Filters the passed candidate array and returns only items which have the passed className
  20209. filterByClassName = function(items, className) {
  20210. var EA = Ext.Array,
  20211. result = [],
  20212. i = 0,
  20213. length = items.length,
  20214. candidate;
  20215. for (; i < length; i++) {
  20216. candidate = items[i];
  20217. if (candidate.el ? candidate.el.hasCls(className) : EA.contains(candidate.initCls(), className)) {
  20218. result.push(candidate);
  20219. }
  20220. }
  20221. return result;
  20222. },
  20223. // Filters the passed candidate array and returns only items which have the specified property match
  20224. filterByAttribute = function(items, property, operator, value) {
  20225. var result = [],
  20226. i = 0,
  20227. length = items.length,
  20228. candidate;
  20229. for (; i < length; i++) {
  20230. candidate = items[i];
  20231. if (!value ? !!candidate[property] : (String(candidate[property]) === value)) {
  20232. result.push(candidate);
  20233. }
  20234. }
  20235. return result;
  20236. },
  20237. // Filters the passed candidate array and returns only items which have the specified itemId or id
  20238. filterById = function(items, id) {
  20239. var result = [],
  20240. i = 0,
  20241. length = items.length,
  20242. candidate;
  20243. for (; i < length; i++) {
  20244. candidate = items[i];
  20245. if (candidate.getItemId() === id) {
  20246. result.push(candidate);
  20247. }
  20248. }
  20249. return result;
  20250. },
  20251. // Filters the passed candidate array and returns only items which the named pseudo class matcher filters in
  20252. filterByPseudo = function(items, name, value) {
  20253. return cq.pseudos[name](items, value);
  20254. },
  20255. // Determines leading mode
  20256. // > for direct child, and ^ to switch to ownerCt axis
  20257. modeRe = /^(\s?([>\^])\s?|\s|$)/,
  20258. // Matches a token with possibly (true|false) appended for the "shallow" parameter
  20259. tokenRe = /^(#)?([\w\-]+|\*)(?:\((true|false)\))?/,
  20260. matchers = [{
  20261. // Checks for .xtype with possibly (true|false) appended for the "shallow" parameter
  20262. re: /^\.([\w\-]+)(?:\((true|false)\))?/,
  20263. method: filterByXType
  20264. },{
  20265. // checks for [attribute=value]
  20266. re: /^(?:[\[](?:@)?([\w\-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]])/,
  20267. method: filterByAttribute
  20268. }, {
  20269. // checks for #cmpItemId
  20270. re: /^#([\w\-]+)/,
  20271. method: filterById
  20272. }, {
  20273. // checks for :<pseudo_class>(<selector>)
  20274. re: /^\:([\w\-]+)(?:\(((?:\{[^\}]+\})|(?:(?!\{)[^\s>\/]*?(?!\})))\))?/,
  20275. method: filterByPseudo
  20276. }, {
  20277. // checks for {<member_expression>}
  20278. re: /^(?:\{([^\}]+)\})/,
  20279. method: filterFnPattern
  20280. }];
  20281. // @class Ext.ComponentQuery.Query
  20282. // This internal class is completely hidden in documentation.
  20283. cq.Query = Ext.extend(Object, {
  20284. constructor: function(cfg) {
  20285. cfg = cfg || {};
  20286. Ext.apply(this, cfg);
  20287. },
  20288. // Executes this Query upon the selected root.
  20289. // The root provides the initial source of candidate Component matches which are progressively
  20290. // filtered by iterating through this Query's operations cache.
  20291. // If no root is provided, all registered Components are searched via the ComponentManager.
  20292. // root may be a Container who's descendant Components are filtered
  20293. // root may be a Component with an implementation of getRefItems which provides some nested Components such as the
  20294. // docked items within a Panel.
  20295. // root may be an array of candidate Components to filter using this Query.
  20296. execute : function(root) {
  20297. var operations = this.operations,
  20298. i = 0,
  20299. length = operations.length,
  20300. operation,
  20301. workingItems;
  20302. // no root, use all Components in the document
  20303. if (!root) {
  20304. workingItems = Ext.ComponentManager.all.getArray();
  20305. }
  20306. // Root is a candidate Array
  20307. else if (Ext.isArray(root)) {
  20308. workingItems = root;
  20309. }
  20310. // We are going to loop over our operations and take care of them
  20311. // one by one.
  20312. for (; i < length; i++) {
  20313. operation = operations[i];
  20314. // The mode operation requires some custom handling.
  20315. // All other operations essentially filter down our current
  20316. // working items, while mode replaces our current working
  20317. // items by getting children from each one of our current
  20318. // working items. The type of mode determines the type of
  20319. // children we get. (e.g. > only gets direct children)
  20320. if (operation.mode === '^') {
  20321. workingItems = getAncestors(workingItems || [root]);
  20322. }
  20323. else if (operation.mode) {
  20324. workingItems = getItems(workingItems || [root], operation.mode);
  20325. }
  20326. else {
  20327. workingItems = filterItems(workingItems || getItems([root]), operation);
  20328. }
  20329. // If this is the last operation, it means our current working
  20330. // items are the final matched items. Thus return them!
  20331. if (i === length -1) {
  20332. return workingItems;
  20333. }
  20334. }
  20335. return [];
  20336. },
  20337. is: function(component) {
  20338. var operations = this.operations,
  20339. components = Ext.isArray(component) ? component : [component],
  20340. originalLength = components.length,
  20341. lastOperation = operations[operations.length-1],
  20342. ln, i;
  20343. components = filterItems(components, lastOperation);
  20344. if (components.length === originalLength) {
  20345. if (operations.length > 1) {
  20346. for (i = 0, ln = components.length; i < ln; i++) {
  20347. if (Ext.Array.indexOf(this.execute(), components[i]) === -1) {
  20348. return false;
  20349. }
  20350. }
  20351. }
  20352. return true;
  20353. }
  20354. return false;
  20355. }
  20356. });
  20357. Ext.apply(this, {
  20358. // private cache of selectors and matching ComponentQuery.Query objects
  20359. cache: {},
  20360. // private cache of pseudo class filter functions
  20361. pseudos: {
  20362. not: function(components, selector){
  20363. var CQ = Ext.ComponentQuery,
  20364. i = 0,
  20365. length = components.length,
  20366. results = [],
  20367. index = -1,
  20368. component;
  20369. for(; i < length; ++i) {
  20370. component = components[i];
  20371. if (!CQ.is(component, selector)) {
  20372. results[++index] = component;
  20373. }
  20374. }
  20375. return results;
  20376. },
  20377. last: function(components) {
  20378. return components[components.length - 1];
  20379. }
  20380. },
  20381. /**
  20382. * Returns an array of matched Components from within the passed root object.
  20383. *
  20384. * This method filters returned Components in a similar way to how CSS selector based DOM
  20385. * queries work using a textual selector string.
  20386. *
  20387. * See class summary for details.
  20388. *
  20389. * @param {String} selector The selector string to filter returned Components
  20390. * @param {Ext.container.Container} root The Container within which to perform the query.
  20391. * If omitted, all Components within the document are included in the search.
  20392. *
  20393. * This parameter may also be an array of Components to filter according to the selector.</p>
  20394. * @returns {Ext.Component[]} The matched Components.
  20395. *
  20396. * @member Ext.ComponentQuery
  20397. */
  20398. query: function(selector, root) {
  20399. var selectors = selector.split(','),
  20400. length = selectors.length,
  20401. i = 0,
  20402. results = [],
  20403. noDupResults = [],
  20404. dupMatcher = {},
  20405. query, resultsLn, cmp;
  20406. for (; i < length; i++) {
  20407. selector = Ext.String.trim(selectors[i]);
  20408. query = this.cache[selector];
  20409. if (!query) {
  20410. this.cache[selector] = query = this.parse(selector);
  20411. }
  20412. results = results.concat(query.execute(root));
  20413. }
  20414. // multiple selectors, potential to find duplicates
  20415. // lets filter them out.
  20416. if (length > 1) {
  20417. resultsLn = results.length;
  20418. for (i = 0; i < resultsLn; i++) {
  20419. cmp = results[i];
  20420. if (!dupMatcher[cmp.id]) {
  20421. noDupResults.push(cmp);
  20422. dupMatcher[cmp.id] = true;
  20423. }
  20424. }
  20425. results = noDupResults;
  20426. }
  20427. return results;
  20428. },
  20429. /**
  20430. * Tests whether the passed Component matches the selector string.
  20431. * @param {Ext.Component} component The Component to test
  20432. * @param {String} selector The selector string to test against.
  20433. * @return {Boolean} True if the Component matches the selector.
  20434. * @member Ext.ComponentQuery
  20435. */
  20436. is: function(component, selector) {
  20437. if (!selector) {
  20438. return true;
  20439. }
  20440. var query = this.cache[selector];
  20441. if (!query) {
  20442. this.cache[selector] = query = this.parse(selector);
  20443. }
  20444. return query.is(component);
  20445. },
  20446. parse: function(selector) {
  20447. var operations = [],
  20448. length = matchers.length,
  20449. lastSelector,
  20450. tokenMatch,
  20451. matchedChar,
  20452. modeMatch,
  20453. selectorMatch,
  20454. i, matcher, method;
  20455. // We are going to parse the beginning of the selector over and
  20456. // over again, slicing off the selector any portions we converted into an
  20457. // operation, until it is an empty string.
  20458. while (selector && lastSelector !== selector) {
  20459. lastSelector = selector;
  20460. // First we check if we are dealing with a token like #, * or an xtype
  20461. tokenMatch = selector.match(tokenRe);
  20462. if (tokenMatch) {
  20463. matchedChar = tokenMatch[1];
  20464. // If the token is prefixed with a # we push a filterById operation to our stack
  20465. if (matchedChar === '#') {
  20466. operations.push({
  20467. method: filterById,
  20468. args: [Ext.String.trim(tokenMatch[2])]
  20469. });
  20470. }
  20471. // If the token is prefixed with a . we push a filterByClassName operation to our stack
  20472. // FIXME: Not enabled yet. just needs \. adding to the tokenRe prefix
  20473. else if (matchedChar === '.') {
  20474. operations.push({
  20475. method: filterByClassName,
  20476. args: [Ext.String.trim(tokenMatch[2])]
  20477. });
  20478. }
  20479. // If the token is a * or an xtype string, we push a filterByXType
  20480. // operation to the stack.
  20481. else {
  20482. operations.push({
  20483. method: filterByXType,
  20484. args: [Ext.String.trim(tokenMatch[2]), Boolean(tokenMatch[3])]
  20485. });
  20486. }
  20487. // Now we slice of the part we just converted into an operation
  20488. selector = selector.replace(tokenMatch[0], '');
  20489. }
  20490. // If the next part of the query is not a space or > or ^, it means we
  20491. // are going to check for more things that our current selection
  20492. // has to comply to.
  20493. while (!(modeMatch = selector.match(modeRe))) {
  20494. // Lets loop over each type of matcher and execute it
  20495. // on our current selector.
  20496. for (i = 0; selector && i < length; i++) {
  20497. matcher = matchers[i];
  20498. selectorMatch = selector.match(matcher.re);
  20499. method = matcher.method;
  20500. // If we have a match, add an operation with the method
  20501. // associated with this matcher, and pass the regular
  20502. // expression matches are arguments to the operation.
  20503. if (selectorMatch) {
  20504. operations.push({
  20505. method: Ext.isString(matcher.method)
  20506. // Turn a string method into a function by formatting the string with our selector matche expression
  20507. // A new method is created for different match expressions, eg {id=='textfield-1024'}
  20508. // Every expression may be different in different selectors.
  20509. ? Ext.functionFactory('items', Ext.String.format.apply(Ext.String, [method].concat(selectorMatch.slice(1))))
  20510. : matcher.method,
  20511. args: selectorMatch.slice(1)
  20512. });
  20513. selector = selector.replace(selectorMatch[0], '');
  20514. break; // Break on match
  20515. }
  20516. }
  20517. }
  20518. // Now we are going to check for a mode change. This means a space
  20519. // or a > to determine if we are going to select all the children
  20520. // of the currently matched items, or a ^ if we are going to use the
  20521. // ownerCt axis as the candidate source.
  20522. if (modeMatch[1]) { // Assignment, and test for truthiness!
  20523. operations.push({
  20524. mode: modeMatch[2]||modeMatch[1]
  20525. });
  20526. selector = selector.replace(modeMatch[0], '');
  20527. }
  20528. }
  20529. // Now that we have all our operations in an array, we are going
  20530. // to create a new Query using these operations.
  20531. return new cq.Query({
  20532. operations: operations
  20533. });
  20534. }
  20535. });
  20536. });
  20537. /**
  20538. * @class Ext.util.HashMap
  20539. * <p>
  20540. * Represents a collection of a set of key and value pairs. Each key in the HashMap
  20541. * must be unique, the same key cannot exist twice. Access to items is provided via
  20542. * the key only. Sample usage:
  20543. * <pre><code>
  20544. var map = new Ext.util.HashMap();
  20545. map.add('key1', 1);
  20546. map.add('key2', 2);
  20547. map.add('key3', 3);
  20548. map.each(function(key, value, length){
  20549. console.log(key, value, length);
  20550. });
  20551. * </code></pre>
  20552. * </p>
  20553. *
  20554. * <p>The HashMap is an unordered class,
  20555. * there is no guarantee when iterating over the items that they will be in any particular
  20556. * order. If this is required, then use a {@link Ext.util.MixedCollection}.
  20557. * </p>
  20558. */
  20559. Ext.define('Ext.util.HashMap', {
  20560. mixins: {
  20561. observable: 'Ext.util.Observable'
  20562. },
  20563. /**
  20564. * @cfg {Function} keyFn A function that is used to retrieve a default key for a passed object.
  20565. * A default is provided that returns the <b>id</b> property on the object. This function is only used
  20566. * if the add method is called with a single argument.
  20567. */
  20568. /**
  20569. * Creates new HashMap.
  20570. * @param {Object} config (optional) Config object.
  20571. */
  20572. constructor: function(config) {
  20573. config = config || {};
  20574. var me = this,
  20575. keyFn = config.keyFn;
  20576. me.addEvents(
  20577. /**
  20578. * @event add
  20579. * Fires when a new item is added to the hash
  20580. * @param {Ext.util.HashMap} this.
  20581. * @param {String} key The key of the added item.
  20582. * @param {Object} value The value of the added item.
  20583. */
  20584. 'add',
  20585. /**
  20586. * @event clear
  20587. * Fires when the hash is cleared.
  20588. * @param {Ext.util.HashMap} this.
  20589. */
  20590. 'clear',
  20591. /**
  20592. * @event remove
  20593. * Fires when an item is removed from the hash.
  20594. * @param {Ext.util.HashMap} this.
  20595. * @param {String} key The key of the removed item.
  20596. * @param {Object} value The value of the removed item.
  20597. */
  20598. 'remove',
  20599. /**
  20600. * @event replace
  20601. * Fires when an item is replaced in the hash.
  20602. * @param {Ext.util.HashMap} this.
  20603. * @param {String} key The key of the replaced item.
  20604. * @param {Object} value The new value for the item.
  20605. * @param {Object} old The old value for the item.
  20606. */
  20607. 'replace'
  20608. );
  20609. me.mixins.observable.constructor.call(me, config);
  20610. me.clear(true);
  20611. if (keyFn) {
  20612. me.getKey = keyFn;
  20613. }
  20614. },
  20615. /**
  20616. * Gets the number of items in the hash.
  20617. * @return {Number} The number of items in the hash.
  20618. */
  20619. getCount: function() {
  20620. return this.length;
  20621. },
  20622. /**
  20623. * Implementation for being able to extract the key from an object if only
  20624. * a single argument is passed.
  20625. * @private
  20626. * @param {String} key The key
  20627. * @param {Object} value The value
  20628. * @return {Array} [key, value]
  20629. */
  20630. getData: function(key, value) {
  20631. // if we have no value, it means we need to get the key from the object
  20632. if (value === undefined) {
  20633. value = key;
  20634. key = this.getKey(value);
  20635. }
  20636. return [key, value];
  20637. },
  20638. /**
  20639. * Extracts the key from an object. This is a default implementation, it may be overridden
  20640. * @param {Object} o The object to get the key from
  20641. * @return {String} The key to use.
  20642. */
  20643. getKey: function(o) {
  20644. return o.id;
  20645. },
  20646. /**
  20647. * Adds an item to the collection. Fires the {@link #add} event when complete.
  20648. * @param {String} key <p>The key to associate with the item, or the new item.</p>
  20649. * <p>If a {@link #getKey} implementation was specified for this HashMap,
  20650. * or if the key of the stored items is in a property called <tt><b>id</b></tt>,
  20651. * the HashMap will be able to <i>derive</i> the key for the new item.
  20652. * In this case just pass the new item in this parameter.</p>
  20653. * @param {Object} o The item to add.
  20654. * @return {Object} The item added.
  20655. */
  20656. add: function(key, value) {
  20657. var me = this,
  20658. data;
  20659. if (arguments.length === 1) {
  20660. value = key;
  20661. key = me.getKey(value);
  20662. }
  20663. if (me.containsKey(key)) {
  20664. return me.replace(key, value);
  20665. }
  20666. data = me.getData(key, value);
  20667. key = data[0];
  20668. value = data[1];
  20669. me.map[key] = value;
  20670. ++me.length;
  20671. me.fireEvent('add', me, key, value);
  20672. return value;
  20673. },
  20674. /**
  20675. * Replaces an item in the hash. If the key doesn't exist, the
  20676. * {@link #add} method will be used.
  20677. * @param {String} key The key of the item.
  20678. * @param {Object} value The new value for the item.
  20679. * @return {Object} The new value of the item.
  20680. */
  20681. replace: function(key, value) {
  20682. var me = this,
  20683. map = me.map,
  20684. old;
  20685. if (!me.containsKey(key)) {
  20686. me.add(key, value);
  20687. }
  20688. old = map[key];
  20689. map[key] = value;
  20690. me.fireEvent('replace', me, key, value, old);
  20691. return value;
  20692. },
  20693. /**
  20694. * Remove an item from the hash.
  20695. * @param {Object} o The value of the item to remove.
  20696. * @return {Boolean} True if the item was successfully removed.
  20697. */
  20698. remove: function(o) {
  20699. var key = this.findKey(o);
  20700. if (key !== undefined) {
  20701. return this.removeAtKey(key);
  20702. }
  20703. return false;
  20704. },
  20705. /**
  20706. * Remove an item from the hash.
  20707. * @param {String} key The key to remove.
  20708. * @return {Boolean} True if the item was successfully removed.
  20709. */
  20710. removeAtKey: function(key) {
  20711. var me = this,
  20712. value;
  20713. if (me.containsKey(key)) {
  20714. value = me.map[key];
  20715. delete me.map[key];
  20716. --me.length;
  20717. me.fireEvent('remove', me, key, value);
  20718. return true;
  20719. }
  20720. return false;
  20721. },
  20722. /**
  20723. * Retrieves an item with a particular key.
  20724. * @param {String} key The key to lookup.
  20725. * @return {Object} The value at that key. If it doesn't exist, <tt>undefined</tt> is returned.
  20726. */
  20727. get: function(key) {
  20728. return this.map[key];
  20729. },
  20730. /**
  20731. * Removes all items from the hash.
  20732. * @return {Ext.util.HashMap} this
  20733. */
  20734. clear: function(/* private */ initial) {
  20735. var me = this;
  20736. me.map = {};
  20737. me.length = 0;
  20738. if (initial !== true) {
  20739. me.fireEvent('clear', me);
  20740. }
  20741. return me;
  20742. },
  20743. /**
  20744. * Checks whether a key exists in the hash.
  20745. * @param {String} key The key to check for.
  20746. * @return {Boolean} True if they key exists in the hash.
  20747. */
  20748. containsKey: function(key) {
  20749. return this.map[key] !== undefined;
  20750. },
  20751. /**
  20752. * Checks whether a value exists in the hash.
  20753. * @param {Object} value The value to check for.
  20754. * @return {Boolean} True if the value exists in the dictionary.
  20755. */
  20756. contains: function(value) {
  20757. return this.containsKey(this.findKey(value));
  20758. },
  20759. /**
  20760. * Return all of the keys in the hash.
  20761. * @return {Array} An array of keys.
  20762. */
  20763. getKeys: function() {
  20764. return this.getArray(true);
  20765. },
  20766. /**
  20767. * Return all of the values in the hash.
  20768. * @return {Array} An array of values.
  20769. */
  20770. getValues: function() {
  20771. return this.getArray(false);
  20772. },
  20773. /**
  20774. * Gets either the keys/values in an array from the hash.
  20775. * @private
  20776. * @param {Boolean} isKey True to extract the keys, otherwise, the value
  20777. * @return {Array} An array of either keys/values from the hash.
  20778. */
  20779. getArray: function(isKey) {
  20780. var arr = [],
  20781. key,
  20782. map = this.map;
  20783. for (key in map) {
  20784. if (map.hasOwnProperty(key)) {
  20785. arr.push(isKey ? key: map[key]);
  20786. }
  20787. }
  20788. return arr;
  20789. },
  20790. /**
  20791. * Executes the specified function once for each item in the hash.
  20792. * Returning false from the function will cease iteration.
  20793. *
  20794. * The paramaters passed to the function are:
  20795. * <div class="mdetail-params"><ul>
  20796. * <li><b>key</b> : String<p class="sub-desc">The key of the item</p></li>
  20797. * <li><b>value</b> : Number<p class="sub-desc">The value of the item</p></li>
  20798. * <li><b>length</b> : Number<p class="sub-desc">The total number of items in the hash</p></li>
  20799. * </ul></div>
  20800. * @param {Function} fn The function to execute.
  20801. * @param {Object} scope The scope to execute in. Defaults to <tt>this</tt>.
  20802. * @return {Ext.util.HashMap} this
  20803. */
  20804. each: function(fn, scope) {
  20805. // copy items so they may be removed during iteration.
  20806. var items = Ext.apply({}, this.map),
  20807. key,
  20808. length = this.length;
  20809. scope = scope || this;
  20810. for (key in items) {
  20811. if (items.hasOwnProperty(key)) {
  20812. if (fn.call(scope, key, items[key], length) === false) {
  20813. break;
  20814. }
  20815. }
  20816. }
  20817. return this;
  20818. },
  20819. /**
  20820. * Performs a shallow copy on this hash.
  20821. * @return {Ext.util.HashMap} The new hash object.
  20822. */
  20823. clone: function() {
  20824. var hash = new this.self(),
  20825. map = this.map,
  20826. key;
  20827. hash.suspendEvents();
  20828. for (key in map) {
  20829. if (map.hasOwnProperty(key)) {
  20830. hash.add(key, map[key]);
  20831. }
  20832. }
  20833. hash.resumeEvents();
  20834. return hash;
  20835. },
  20836. /**
  20837. * @private
  20838. * Find the key for a value.
  20839. * @param {Object} value The value to find.
  20840. * @return {Object} The value of the item. Returns <tt>undefined</tt> if not found.
  20841. */
  20842. findKey: function(value) {
  20843. var key,
  20844. map = this.map;
  20845. for (key in map) {
  20846. if (map.hasOwnProperty(key) && map[key] === value) {
  20847. return key;
  20848. }
  20849. }
  20850. return undefined;
  20851. }
  20852. });
  20853. /**
  20854. * @class Ext.state.Manager
  20855. * This is the global state manager. By default all components that are "state aware" check this class
  20856. * for state information if you don't pass them a custom state provider. In order for this class
  20857. * to be useful, it must be initialized with a provider when your application initializes. Example usage:
  20858. <pre><code>
  20859. // in your initialization function
  20860. init : function(){
  20861. Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
  20862. var win = new Window(...);
  20863. win.restoreState();
  20864. }
  20865. </code></pre>
  20866. * This class passes on calls from components to the underlying {@link Ext.state.Provider} so that
  20867. * there is a common interface that can be used without needing to refer to a specific provider instance
  20868. * in every component.
  20869. * @singleton
  20870. * @docauthor Evan Trimboli <evan@sencha.com>
  20871. */
  20872. Ext.define('Ext.state.Manager', {
  20873. singleton: true,
  20874. requires: ['Ext.state.Provider'],
  20875. constructor: function() {
  20876. this.provider = Ext.create('Ext.state.Provider');
  20877. },
  20878. /**
  20879. * Configures the default state provider for your application
  20880. * @param {Ext.state.Provider} stateProvider The state provider to set
  20881. */
  20882. setProvider : function(stateProvider){
  20883. this.provider = stateProvider;
  20884. },
  20885. /**
  20886. * Returns the current value for a key
  20887. * @param {String} name The key name
  20888. * @param {Object} defaultValue The default value to return if the key lookup does not match
  20889. * @return {Object} The state data
  20890. */
  20891. get : function(key, defaultValue){
  20892. return this.provider.get(key, defaultValue);
  20893. },
  20894. /**
  20895. * Sets the value for a key
  20896. * @param {String} name The key name
  20897. * @param {Object} value The state data
  20898. */
  20899. set : function(key, value){
  20900. this.provider.set(key, value);
  20901. },
  20902. /**
  20903. * Clears a value from the state
  20904. * @param {String} name The key name
  20905. */
  20906. clear : function(key){
  20907. this.provider.clear(key);
  20908. },
  20909. /**
  20910. * Gets the currently configured state provider
  20911. * @return {Ext.state.Provider} The state provider
  20912. */
  20913. getProvider : function(){
  20914. return this.provider;
  20915. }
  20916. });
  20917. /**
  20918. * @class Ext.state.Stateful
  20919. * A mixin for being able to save the state of an object to an underlying
  20920. * {@link Ext.state.Provider}.
  20921. */
  20922. Ext.define('Ext.state.Stateful', {
  20923. /* Begin Definitions */
  20924. mixins: {
  20925. observable: 'Ext.util.Observable'
  20926. },
  20927. requires: ['Ext.state.Manager'],
  20928. /* End Definitions */
  20929. /**
  20930. * @cfg {Boolean} stateful
  20931. * <p>A flag which causes the object to attempt to restore the state of
  20932. * internal properties from a saved state on startup. The object must have
  20933. * a <code>{@link #stateId}</code> for state to be managed.
  20934. * Auto-generated ids are not guaranteed to be stable across page loads and
  20935. * cannot be relied upon to save and restore the same state for a object.<p>
  20936. * <p>For state saving to work, the state manager's provider must have been
  20937. * set to an implementation of {@link Ext.state.Provider} which overrides the
  20938. * {@link Ext.state.Provider#set set} and {@link Ext.state.Provider#get get}
  20939. * methods to save and recall name/value pairs. A built-in implementation,
  20940. * {@link Ext.state.CookieProvider} is available.</p>
  20941. * <p>To set the state provider for the current page:</p>
  20942. * <pre><code>
  20943. Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
  20944. expires: new Date(new Date().getTime()+(1000*60*60*24*7)), //7 days from now
  20945. }));
  20946. * </code></pre>
  20947. * <p>A stateful object attempts to save state when one of the events
  20948. * listed in the <code>{@link #stateEvents}</code> configuration fires.</p>
  20949. * <p>To save state, a stateful object first serializes its state by
  20950. * calling <b><code>{@link #getState}</code></b>. By default, this function does
  20951. * nothing. The developer must provide an implementation which returns an
  20952. * object hash which represents the restorable state of the object.</p>
  20953. * <p>The value yielded by getState is passed to {@link Ext.state.Manager#set}
  20954. * which uses the configured {@link Ext.state.Provider} to save the object
  20955. * keyed by the <code>{@link #stateId}</code>.</p>
  20956. * <p>During construction, a stateful object attempts to <i>restore</i>
  20957. * its state by calling {@link Ext.state.Manager#get} passing the
  20958. * <code>{@link #stateId}</code></p>
  20959. * <p>The resulting object is passed to <b><code>{@link #applyState}</code></b>.
  20960. * The default implementation of <code>{@link #applyState}</code> simply copies
  20961. * properties into the object, but a developer may override this to support
  20962. * more behaviour.</p>
  20963. * <p>You can perform extra processing on state save and restore by attaching
  20964. * handlers to the {@link #beforestaterestore}, {@link #staterestore},
  20965. * {@link #beforestatesave} and {@link #statesave} events.</p>
  20966. */
  20967. stateful: true,
  20968. /**
  20969. * @cfg {String} stateId
  20970. * The unique id for this object to use for state management purposes.
  20971. * <p>See {@link #stateful} for an explanation of saving and restoring state.</p>
  20972. */
  20973. /**
  20974. * @cfg {String[]} stateEvents
  20975. * <p>An array of events that, when fired, should trigger this object to
  20976. * save its state. Defaults to none. <code>stateEvents</code> may be any type
  20977. * of event supported by this object, including browser or custom events
  20978. * (e.g., <tt>['click', 'customerchange']</tt>).</p>
  20979. * <p>See <code>{@link #stateful}</code> for an explanation of saving and
  20980. * restoring object state.</p>
  20981. */
  20982. /**
  20983. * @cfg {Number} saveDelay
  20984. * A buffer to be applied if many state events are fired within a short period.
  20985. */
  20986. saveDelay: 100,
  20987. autoGenIdRe: /^((\w+-)|(ext-comp-))\d{4,}$/i,
  20988. constructor: function(config) {
  20989. var me = this;
  20990. config = config || {};
  20991. if (Ext.isDefined(config.stateful)) {
  20992. me.stateful = config.stateful;
  20993. }
  20994. if (Ext.isDefined(config.saveDelay)) {
  20995. me.saveDelay = config.saveDelay;
  20996. }
  20997. me.stateId = me.stateId || config.stateId;
  20998. if (!me.stateEvents) {
  20999. me.stateEvents = [];
  21000. }
  21001. if (config.stateEvents) {
  21002. me.stateEvents.concat(config.stateEvents);
  21003. }
  21004. this.addEvents(
  21005. /**
  21006. * @event beforestaterestore
  21007. * Fires before the state of the object is restored. Return false from an event handler to stop the restore.
  21008. * @param {Ext.state.Stateful} this
  21009. * @param {Object} state The hash of state values returned from the StateProvider. If this
  21010. * event is not vetoed, then the state object is passed to <b><tt>applyState</tt></b>. By default,
  21011. * that simply copies property values into this object. The method maybe overriden to
  21012. * provide custom state restoration.
  21013. */
  21014. 'beforestaterestore',
  21015. /**
  21016. * @event staterestore
  21017. * Fires after the state of the object is restored.
  21018. * @param {Ext.state.Stateful} this
  21019. * @param {Object} state The hash of state values returned from the StateProvider. This is passed
  21020. * to <b><tt>applyState</tt></b>. By default, that simply copies property values into this
  21021. * object. The method maybe overriden to provide custom state restoration.
  21022. */
  21023. 'staterestore',
  21024. /**
  21025. * @event beforestatesave
  21026. * Fires before the state of the object is saved to the configured state provider. Return false to stop the save.
  21027. * @param {Ext.state.Stateful} this
  21028. * @param {Object} state The hash of state values. This is determined by calling
  21029. * <b><tt>getState()</tt></b> on the object. This method must be provided by the
  21030. * developer to return whetever representation of state is required, by default, Ext.state.Stateful
  21031. * has a null implementation.
  21032. */
  21033. 'beforestatesave',
  21034. /**
  21035. * @event statesave
  21036. * Fires after the state of the object is saved to the configured state provider.
  21037. * @param {Ext.state.Stateful} this
  21038. * @param {Object} state The hash of state values. This is determined by calling
  21039. * <b><tt>getState()</tt></b> on the object. This method must be provided by the
  21040. * developer to return whetever representation of state is required, by default, Ext.state.Stateful
  21041. * has a null implementation.
  21042. */
  21043. 'statesave'
  21044. );
  21045. me.mixins.observable.constructor.call(me);
  21046. if (me.stateful !== false) {
  21047. me.initStateEvents();
  21048. me.initState();
  21049. }
  21050. },
  21051. /**
  21052. * Initializes any state events for this object.
  21053. * @private
  21054. */
  21055. initStateEvents: function() {
  21056. this.addStateEvents(this.stateEvents);
  21057. },
  21058. /**
  21059. * Add events that will trigger the state to be saved.
  21060. * @param {String/String[]} events The event name or an array of event names.
  21061. */
  21062. addStateEvents: function(events){
  21063. if (!Ext.isArray(events)) {
  21064. events = [events];
  21065. }
  21066. var me = this,
  21067. i = 0,
  21068. len = events.length;
  21069. for (; i < len; ++i) {
  21070. me.on(events[i], me.onStateChange, me);
  21071. }
  21072. },
  21073. /**
  21074. * This method is called when any of the {@link #stateEvents} are fired.
  21075. * @private
  21076. */
  21077. onStateChange: function(){
  21078. var me = this,
  21079. delay = me.saveDelay;
  21080. if (delay > 0) {
  21081. if (!me.stateTask) {
  21082. me.stateTask = Ext.create('Ext.util.DelayedTask', me.saveState, me);
  21083. }
  21084. me.stateTask.delay(me.saveDelay);
  21085. } else {
  21086. me.saveState();
  21087. }
  21088. },
  21089. /**
  21090. * Saves the state of the object to the persistence store.
  21091. * @private
  21092. */
  21093. saveState: function() {
  21094. var me = this,
  21095. id,
  21096. state;
  21097. if (me.stateful !== false) {
  21098. id = me.getStateId();
  21099. if (id) {
  21100. state = me.getState();
  21101. if (me.fireEvent('beforestatesave', me, state) !== false) {
  21102. Ext.state.Manager.set(id, state);
  21103. me.fireEvent('statesave', me, state);
  21104. }
  21105. }
  21106. }
  21107. },
  21108. /**
  21109. * Gets the current state of the object. By default this function returns null,
  21110. * it should be overridden in subclasses to implement methods for getting the state.
  21111. * @return {Object} The current state
  21112. */
  21113. getState: function(){
  21114. return null;
  21115. },
  21116. /**
  21117. * Applies the state to the object. This should be overridden in subclasses to do
  21118. * more complex state operations. By default it applies the state properties onto
  21119. * the current object.
  21120. * @param {Object} state The state
  21121. */
  21122. applyState: function(state) {
  21123. if (state) {
  21124. Ext.apply(this, state);
  21125. }
  21126. },
  21127. /**
  21128. * Gets the state id for this object.
  21129. * @return {String} The state id, null if not found.
  21130. */
  21131. getStateId: function() {
  21132. var me = this,
  21133. id = me.stateId;
  21134. if (!id) {
  21135. id = me.autoGenIdRe.test(String(me.id)) ? null : me.id;
  21136. }
  21137. return id;
  21138. },
  21139. /**
  21140. * Initializes the state of the object upon construction.
  21141. * @private
  21142. */
  21143. initState: function(){
  21144. var me = this,
  21145. id = me.getStateId(),
  21146. state;
  21147. if (me.stateful !== false) {
  21148. if (id) {
  21149. state = Ext.state.Manager.get(id);
  21150. if (state) {
  21151. state = Ext.apply({}, state);
  21152. if (me.fireEvent('beforestaterestore', me, state) !== false) {
  21153. me.applyState(state);
  21154. me.fireEvent('staterestore', me, state);
  21155. }
  21156. }
  21157. }
  21158. }
  21159. },
  21160. /**
  21161. * Conditionally saves a single property from this object to the given state object.
  21162. * The idea is to only save state which has changed from the initial state so that
  21163. * current software settings do not override future software settings. Only those
  21164. * values that are user-changed state should be saved.
  21165. *
  21166. * @param {String} propName The name of the property to save.
  21167. * @param {Object} state The state object in to which to save the property.
  21168. * @param {String} stateName (optional) The name to use for the property in state.
  21169. * @return {Boolean} True if the property was saved, false if not.
  21170. */
  21171. savePropToState: function (propName, state, stateName) {
  21172. var me = this,
  21173. value = me[propName],
  21174. config = me.initialConfig;
  21175. if (me.hasOwnProperty(propName)) {
  21176. if (!config || config[propName] !== value) {
  21177. if (state) {
  21178. state[stateName || propName] = value;
  21179. }
  21180. return true;
  21181. }
  21182. }
  21183. return false;
  21184. },
  21185. savePropsToState: function (propNames, state) {
  21186. var me = this;
  21187. Ext.each(propNames, function (propName) {
  21188. me.savePropToState(propName, state);
  21189. });
  21190. return state;
  21191. },
  21192. /**
  21193. * Destroys this stateful object.
  21194. */
  21195. destroy: function(){
  21196. var task = this.stateTask;
  21197. if (task) {
  21198. task.cancel();
  21199. }
  21200. this.clearListeners();
  21201. }
  21202. });
  21203. /**
  21204. * Base Manager class
  21205. */
  21206. Ext.define('Ext.AbstractManager', {
  21207. /* Begin Definitions */
  21208. requires: ['Ext.util.HashMap'],
  21209. /* End Definitions */
  21210. typeName: 'type',
  21211. constructor: function(config) {
  21212. Ext.apply(this, config || {});
  21213. /**
  21214. * @property {Ext.util.HashMap} all
  21215. * Contains all of the items currently managed
  21216. */
  21217. this.all = Ext.create('Ext.util.HashMap');
  21218. this.types = {};
  21219. },
  21220. /**
  21221. * Returns an item by id.
  21222. * For additional details see {@link Ext.util.HashMap#get}.
  21223. * @param {String} id The id of the item
  21224. * @return {Object} The item, undefined if not found.
  21225. */
  21226. get : function(id) {
  21227. return this.all.get(id);
  21228. },
  21229. /**
  21230. * Registers an item to be managed
  21231. * @param {Object} item The item to register
  21232. */
  21233. register: function(item) {
  21234. this.all.add(item);
  21235. },
  21236. /**
  21237. * Unregisters an item by removing it from this manager
  21238. * @param {Object} item The item to unregister
  21239. */
  21240. unregister: function(item) {
  21241. this.all.remove(item);
  21242. },
  21243. /**
  21244. * Registers a new item constructor, keyed by a type key.
  21245. * @param {String} type The mnemonic string by which the class may be looked up.
  21246. * @param {Function} cls The new instance class.
  21247. */
  21248. registerType : function(type, cls) {
  21249. this.types[type] = cls;
  21250. cls[this.typeName] = type;
  21251. },
  21252. /**
  21253. * Checks if an item type is registered.
  21254. * @param {String} type The mnemonic string by which the class may be looked up
  21255. * @return {Boolean} Whether the type is registered.
  21256. */
  21257. isRegistered : function(type){
  21258. return this.types[type] !== undefined;
  21259. },
  21260. /**
  21261. * Creates and returns an instance of whatever this manager manages, based on the supplied type and
  21262. * config object.
  21263. * @param {Object} config The config object
  21264. * @param {String} defaultType If no type is discovered in the config object, we fall back to this type
  21265. * @return {Object} The instance of whatever this manager is managing
  21266. */
  21267. create: function(config, defaultType) {
  21268. var type = config[this.typeName] || config.type || defaultType,
  21269. Constructor = this.types[type];
  21270. return new Constructor(config);
  21271. },
  21272. /**
  21273. * Registers a function that will be called when an item with the specified id is added to the manager.
  21274. * This will happen on instantiation.
  21275. * @param {String} id The item id
  21276. * @param {Function} fn The callback function. Called with a single parameter, the item.
  21277. * @param {Object} scope The scope (this reference) in which the callback is executed.
  21278. * Defaults to the item.
  21279. */
  21280. onAvailable : function(id, fn, scope){
  21281. var all = this.all,
  21282. item;
  21283. if (all.containsKey(id)) {
  21284. item = all.get(id);
  21285. fn.call(scope || item, item);
  21286. } else {
  21287. all.on('add', function(map, key, item){
  21288. if (key == id) {
  21289. fn.call(scope || item, item);
  21290. all.un('add', fn, scope);
  21291. }
  21292. });
  21293. }
  21294. },
  21295. /**
  21296. * Executes the specified function once for each item in the collection.
  21297. * @param {Function} fn The function to execute.
  21298. * @param {String} fn.key The key of the item
  21299. * @param {Number} fn.value The value of the item
  21300. * @param {Number} fn.length The total number of items in the collection
  21301. * @param {Boolean} fn.return False to cease iteration.
  21302. * @param {Object} scope The scope to execute in. Defaults to `this`.
  21303. */
  21304. each: function(fn, scope){
  21305. this.all.each(fn, scope || this);
  21306. },
  21307. /**
  21308. * Gets the number of items in the collection.
  21309. * @return {Number} The number of items in the collection.
  21310. */
  21311. getCount: function(){
  21312. return this.all.getCount();
  21313. }
  21314. });
  21315. /**
  21316. * @class Ext.ComponentManager
  21317. * @extends Ext.AbstractManager
  21318. * <p>Provides a registry of all Components (instances of {@link Ext.Component} or any subclass
  21319. * thereof) on a page so that they can be easily accessed by {@link Ext.Component component}
  21320. * {@link Ext.Component#id id} (see {@link #get}, or the convenience method {@link Ext#getCmp Ext.getCmp}).</p>
  21321. * <p>This object also provides a registry of available Component <i>classes</i>
  21322. * indexed by a mnemonic code known as the Component's {@link Ext.Component#xtype xtype}.
  21323. * The <code>xtype</code> provides a way to avoid instantiating child Components
  21324. * when creating a full, nested config object for a complete Ext page.</p>
  21325. * <p>A child Component may be specified simply as a <i>config object</i>
  21326. * as long as the correct <code>{@link Ext.Component#xtype xtype}</code> is specified so that if and when the Component
  21327. * needs rendering, the correct type can be looked up for lazy instantiation.</p>
  21328. * <p>For a list of all available <code>{@link Ext.Component#xtype xtypes}</code>, see {@link Ext.Component}.</p>
  21329. * @singleton
  21330. */
  21331. Ext.define('Ext.ComponentManager', {
  21332. extend: 'Ext.AbstractManager',
  21333. alternateClassName: 'Ext.ComponentMgr',
  21334. singleton: true,
  21335. typeName: 'xtype',
  21336. /**
  21337. * Creates a new Component from the specified config object using the
  21338. * config object's xtype to determine the class to instantiate.
  21339. * @param {Object} config A configuration object for the Component you wish to create.
  21340. * @param {Function} defaultType (optional) The constructor to provide the default Component type if
  21341. * the config object does not contain a <code>xtype</code>. (Optional if the config contains a <code>xtype</code>).
  21342. * @return {Ext.Component} The newly instantiated Component.
  21343. */
  21344. create: function(component, defaultType){
  21345. if (component instanceof Ext.AbstractComponent) {
  21346. return component;
  21347. }
  21348. else if (Ext.isString(component)) {
  21349. return Ext.createByAlias('widget.' + component);
  21350. }
  21351. else {
  21352. var type = component.xtype || defaultType,
  21353. config = component;
  21354. return Ext.createByAlias('widget.' + type, config);
  21355. }
  21356. },
  21357. registerType: function(type, cls) {
  21358. this.types[type] = cls;
  21359. cls[this.typeName] = type;
  21360. cls.prototype[this.typeName] = type;
  21361. }
  21362. });
  21363. /**
  21364. * An abstract base class which provides shared methods for Components across the Sencha product line.
  21365. *
  21366. * Please refer to sub class's documentation
  21367. * @private
  21368. */
  21369. Ext.define('Ext.AbstractComponent', {
  21370. /* Begin Definitions */
  21371. requires: [
  21372. 'Ext.ComponentQuery',
  21373. 'Ext.ComponentManager'
  21374. ],
  21375. mixins: {
  21376. observable: 'Ext.util.Observable',
  21377. animate: 'Ext.util.Animate',
  21378. state: 'Ext.state.Stateful'
  21379. },
  21380. // The "uses" property specifies class which are used in an instantiated AbstractComponent.
  21381. // They do *not* have to be loaded before this class may be defined - that is what "requires" is for.
  21382. uses: [
  21383. 'Ext.PluginManager',
  21384. 'Ext.ComponentManager',
  21385. 'Ext.Element',
  21386. 'Ext.DomHelper',
  21387. 'Ext.XTemplate',
  21388. 'Ext.ComponentQuery',
  21389. 'Ext.ComponentLoader',
  21390. 'Ext.EventManager',
  21391. 'Ext.layout.Layout',
  21392. 'Ext.layout.component.Auto',
  21393. 'Ext.LoadMask',
  21394. 'Ext.ZIndexManager'
  21395. ],
  21396. statics: {
  21397. AUTO_ID: 1000
  21398. },
  21399. /* End Definitions */
  21400. isComponent: true,
  21401. getAutoId: function() {
  21402. return ++Ext.AbstractComponent.AUTO_ID;
  21403. },
  21404. /**
  21405. * @cfg {String} id
  21406. * The **unique id of this component instance.**
  21407. *
  21408. * It should not be necessary to use this configuration except for singleton objects in your application. Components
  21409. * created with an id may be accessed globally using {@link Ext#getCmp Ext.getCmp}.
  21410. *
  21411. * Instead of using assigned ids, use the {@link #itemId} config, and {@link Ext.ComponentQuery ComponentQuery}
  21412. * which provides selector-based searching for Sencha Components analogous to DOM querying. The {@link
  21413. * Ext.container.Container Container} class contains {@link Ext.container.Container#down shortcut methods} to query
  21414. * its descendant Components by selector.
  21415. *
  21416. * Note that this id will also be used as the element id for the containing HTML element that is rendered to the
  21417. * page for this component. This allows you to write id-based CSS rules to style the specific instance of this
  21418. * component uniquely, and also to select sub-elements using this component's id as the parent.
  21419. *
  21420. * **Note**: to avoid complications imposed by a unique id also see `{@link #itemId}`.
  21421. *
  21422. * **Note**: to access the container of a Component see `{@link #ownerCt}`.
  21423. *
  21424. * Defaults to an {@link #getId auto-assigned id}.
  21425. */
  21426. /**
  21427. * @cfg {String} itemId
  21428. * An itemId can be used as an alternative way to get a reference to a component when no object reference is
  21429. * available. Instead of using an `{@link #id}` with {@link Ext}.{@link Ext#getCmp getCmp}, use `itemId` with
  21430. * {@link Ext.container.Container}.{@link Ext.container.Container#getComponent getComponent} which will retrieve
  21431. * `itemId`'s or {@link #id}'s. Since `itemId`'s are an index to the container's internal MixedCollection, the
  21432. * `itemId` is scoped locally to the container -- avoiding potential conflicts with {@link Ext.ComponentManager}
  21433. * which requires a **unique** `{@link #id}`.
  21434. *
  21435. * var c = new Ext.panel.Panel({ //
  21436. * {@link Ext.Component#height height}: 300,
  21437. * {@link #renderTo}: document.body,
  21438. * {@link Ext.container.Container#layout layout}: 'auto',
  21439. * {@link Ext.container.Container#items items}: [
  21440. * {
  21441. * itemId: 'p1',
  21442. * {@link Ext.panel.Panel#title title}: 'Panel 1',
  21443. * {@link Ext.Component#height height}: 150
  21444. * },
  21445. * {
  21446. * itemId: 'p2',
  21447. * {@link Ext.panel.Panel#title title}: 'Panel 2',
  21448. * {@link Ext.Component#height height}: 150
  21449. * }
  21450. * ]
  21451. * })
  21452. * p1 = c.{@link Ext.container.Container#getComponent getComponent}('p1'); // not the same as {@link Ext#getCmp Ext.getCmp()}
  21453. * p2 = p1.{@link #ownerCt}.{@link Ext.container.Container#getComponent getComponent}('p2'); // reference via a sibling
  21454. *
  21455. * Also see {@link #id}, `{@link Ext.container.Container#query}`, `{@link Ext.container.Container#down}` and
  21456. * `{@link Ext.container.Container#child}`.
  21457. *
  21458. * **Note**: to access the container of an item see {@link #ownerCt}.
  21459. */
  21460. /**
  21461. * @property {Ext.Container} ownerCt
  21462. * This Component's owner {@link Ext.container.Container Container} (is set automatically
  21463. * when this Component is added to a Container). Read-only.
  21464. *
  21465. * **Note**: to access items within the Container see {@link #itemId}.
  21466. */
  21467. /**
  21468. * @property {Boolean} layoutManagedWidth
  21469. * @private
  21470. * Flag set by the container layout to which this Component is added.
  21471. * If the layout manages this Component's width, it sets the value to 1.
  21472. * If it does NOT manage the width, it sets it to 2.
  21473. * If the layout MAY affect the width, but only if the owning Container has a fixed width, this is set to 0.
  21474. */
  21475. /**
  21476. * @property {Boolean} layoutManagedHeight
  21477. * @private
  21478. * Flag set by the container layout to which this Component is added.
  21479. * If the layout manages this Component's height, it sets the value to 1.
  21480. * If it does NOT manage the height, it sets it to 2.
  21481. * If the layout MAY affect the height, but only if the owning Container has a fixed height, this is set to 0.
  21482. */
  21483. /**
  21484. * @cfg {String/Object} autoEl
  21485. * A tag name or {@link Ext.DomHelper DomHelper} spec used to create the {@link #getEl Element} which will
  21486. * encapsulate this Component.
  21487. *
  21488. * You do not normally need to specify this. For the base classes {@link Ext.Component} and
  21489. * {@link Ext.container.Container}, this defaults to **'div'**. The more complex Sencha classes use a more
  21490. * complex DOM structure specified by their own {@link #renderTpl}s.
  21491. *
  21492. * This is intended to allow the developer to create application-specific utility Components encapsulated by
  21493. * different DOM elements. Example usage:
  21494. *
  21495. * {
  21496. * xtype: 'component',
  21497. * autoEl: {
  21498. * tag: 'img',
  21499. * src: 'http://www.example.com/example.jpg'
  21500. * }
  21501. * }, {
  21502. * xtype: 'component',
  21503. * autoEl: {
  21504. * tag: 'blockquote',
  21505. * html: 'autoEl is cool!'
  21506. * }
  21507. * }, {
  21508. * xtype: 'container',
  21509. * autoEl: 'ul',
  21510. * cls: 'ux-unordered-list',
  21511. * items: {
  21512. * xtype: 'component',
  21513. * autoEl: 'li',
  21514. * html: 'First list item'
  21515. * }
  21516. * }
  21517. */
  21518. /**
  21519. * @cfg {Ext.XTemplate/String/String[]} renderTpl
  21520. * An {@link Ext.XTemplate XTemplate} used to create the internal structure inside this Component's encapsulating
  21521. * {@link #getEl Element}.
  21522. *
  21523. * You do not normally need to specify this. For the base classes {@link Ext.Component} and
  21524. * {@link Ext.container.Container}, this defaults to **`null`** which means that they will be initially rendered
  21525. * with no internal structure; they render their {@link #getEl Element} empty. The more specialized ExtJS and Touch
  21526. * classes which use a more complex DOM structure, provide their own template definitions.
  21527. *
  21528. * This is intended to allow the developer to create application-specific utility Components with customized
  21529. * internal structure.
  21530. *
  21531. * Upon rendering, any created child elements may be automatically imported into object properties using the
  21532. * {@link #renderSelectors} and {@link #childEls} options.
  21533. */
  21534. renderTpl: null,
  21535. /**
  21536. * @cfg {Object} renderData
  21537. *
  21538. * The data used by {@link #renderTpl} in addition to the following property values of the component:
  21539. *
  21540. * - id
  21541. * - ui
  21542. * - uiCls
  21543. * - baseCls
  21544. * - componentCls
  21545. * - frame
  21546. *
  21547. * See {@link #renderSelectors} and {@link #childEls} for usage examples.
  21548. */
  21549. /**
  21550. * @cfg {Object} renderSelectors
  21551. * An object containing properties specifying {@link Ext.DomQuery DomQuery} selectors which identify child elements
  21552. * created by the render process.
  21553. *
  21554. * After the Component's internal structure is rendered according to the {@link #renderTpl}, this object is iterated through,
  21555. * and the found Elements are added as properties to the Component using the `renderSelector` property name.
  21556. *
  21557. * For example, a Component which renderes a title and description into its element:
  21558. *
  21559. * Ext.create('Ext.Component', {
  21560. * renderTo: Ext.getBody(),
  21561. * renderTpl: [
  21562. * '<h1 class="title">{title}</h1>',
  21563. * '<p>{desc}</p>'
  21564. * ],
  21565. * renderData: {
  21566. * title: "Error",
  21567. * desc: "Something went wrong"
  21568. * },
  21569. * renderSelectors: {
  21570. * titleEl: 'h1.title',
  21571. * descEl: 'p'
  21572. * },
  21573. * listeners: {
  21574. * afterrender: function(cmp){
  21575. * // After rendering the component will have a titleEl and descEl properties
  21576. * cmp.titleEl.setStyle({color: "red"});
  21577. * }
  21578. * }
  21579. * });
  21580. *
  21581. * For a faster, but less flexible, alternative that achieves the same end result (properties for child elements on the
  21582. * Component after render), see {@link #childEls} and {@link #addChildEls}.
  21583. */
  21584. /**
  21585. * @cfg {Object[]} childEls
  21586. * An array describing the child elements of the Component. Each member of the array
  21587. * is an object with these properties:
  21588. *
  21589. * - `name` - The property name on the Component for the child element.
  21590. * - `itemId` - The id to combine with the Component's id that is the id of the child element.
  21591. * - `id` - The id of the child element.
  21592. *
  21593. * If the array member is a string, it is equivalent to `{ name: m, itemId: m }`.
  21594. *
  21595. * For example, a Component which renders a title and body text:
  21596. *
  21597. * Ext.create('Ext.Component', {
  21598. * renderTo: Ext.getBody(),
  21599. * renderTpl: [
  21600. * '<h1 id="{id}-title">{title}</h1>',
  21601. * '<p>{msg}</p>',
  21602. * ],
  21603. * renderData: {
  21604. * title: "Error",
  21605. * msg: "Something went wrong"
  21606. * },
  21607. * childEls: ["title"],
  21608. * listeners: {
  21609. * afterrender: function(cmp){
  21610. * // After rendering the component will have a title property
  21611. * cmp.title.setStyle({color: "red"});
  21612. * }
  21613. * }
  21614. * });
  21615. *
  21616. * A more flexible, but somewhat slower, approach is {@link #renderSelectors}.
  21617. */
  21618. /**
  21619. * @cfg {String/HTMLElement/Ext.Element} renderTo
  21620. * Specify the id of the element, a DOM element or an existing Element that this component will be rendered into.
  21621. *
  21622. * **Notes:**
  21623. *
  21624. * Do *not* use this option if the Component is to be a child item of a {@link Ext.container.Container Container}.
  21625. * It is the responsibility of the {@link Ext.container.Container Container}'s
  21626. * {@link Ext.container.Container#layout layout manager} to render and manage its child items.
  21627. *
  21628. * When using this config, a call to render() is not required.
  21629. *
  21630. * See `{@link #render}` also.
  21631. */
  21632. /**
  21633. * @cfg {Boolean} frame
  21634. * Specify as `true` to have the Component inject framing elements within the Component at render time to provide a
  21635. * graphical rounded frame around the Component content.
  21636. *
  21637. * This is only necessary when running on outdated, or non standard-compliant browsers such as Microsoft's Internet
  21638. * Explorer prior to version 9 which do not support rounded corners natively.
  21639. *
  21640. * The extra space taken up by this framing is available from the read only property {@link #frameSize}.
  21641. */
  21642. /**
  21643. * @property {Object} frameSize
  21644. * Read-only property indicating the width of any framing elements which were added within the encapsulating element
  21645. * to provide graphical, rounded borders. See the {@link #frame} config.
  21646. *
  21647. * This is an object containing the frame width in pixels for all four sides of the Component containing the
  21648. * following properties:
  21649. *
  21650. * @property {Number} frameSize.top The width of the top framing element in pixels.
  21651. * @property {Number} frameSize.right The width of the right framing element in pixels.
  21652. * @property {Number} frameSize.bottom The width of the bottom framing element in pixels.
  21653. * @property {Number} frameSize.left The width of the left framing element in pixels.
  21654. */
  21655. /**
  21656. * @cfg {String/Object} componentLayout
  21657. * The sizing and positioning of a Component's internal Elements is the responsibility of the Component's layout
  21658. * manager which sizes a Component's internal structure in response to the Component being sized.
  21659. *
  21660. * Generally, developers will not use this configuration as all provided Components which need their internal
  21661. * elements sizing (Such as {@link Ext.form.field.Base input fields}) come with their own componentLayout managers.
  21662. *
  21663. * The {@link Ext.layout.container.Auto default layout manager} will be used on instances of the base Ext.Component
  21664. * class which simply sizes the Component's encapsulating element to the height and width specified in the
  21665. * {@link #setSize} method.
  21666. */
  21667. /**
  21668. * @cfg {Ext.XTemplate/Ext.Template/String/String[]} tpl
  21669. * An {@link Ext.Template}, {@link Ext.XTemplate} or an array of strings to form an Ext.XTemplate. Used in
  21670. * conjunction with the `{@link #data}` and `{@link #tplWriteMode}` configurations.
  21671. */
  21672. /**
  21673. * @cfg {Object} data
  21674. * The initial set of data to apply to the `{@link #tpl}` to update the content area of the Component.
  21675. */
  21676. /**
  21677. * @cfg {String} xtype
  21678. * The `xtype` configuration option can be used to optimize Component creation and rendering. It serves as a
  21679. * shortcut to the full componet name. For example, the component `Ext.button.Button` has an xtype of `button`.
  21680. *
  21681. * You can define your own xtype on a custom {@link Ext.Component component} by specifying the
  21682. * {@link Ext.Class#alias alias} config option with a prefix of `widget`. For example:
  21683. *
  21684. * Ext.define('PressMeButton', {
  21685. * extend: 'Ext.button.Button',
  21686. * alias: 'widget.pressmebutton',
  21687. * text: 'Press Me'
  21688. * })
  21689. *
  21690. * Any Component can be created implicitly as an object config with an xtype specified, allowing it to be
  21691. * declared and passed into the rendering pipeline without actually being instantiated as an object. Not only is
  21692. * rendering deferred, but the actual creation of the object itself is also deferred, saving memory and resources
  21693. * until they are actually needed. In complex, nested layouts containing many Components, this can make a
  21694. * noticeable improvement in performance.
  21695. *
  21696. * // Explicit creation of contained Components:
  21697. * var panel = new Ext.Panel({
  21698. * ...
  21699. * items: [
  21700. * Ext.create('Ext.button.Button', {
  21701. * text: 'OK'
  21702. * })
  21703. * ]
  21704. * };
  21705. *
  21706. * // Implicit creation using xtype:
  21707. * var panel = new Ext.Panel({
  21708. * ...
  21709. * items: [{
  21710. * xtype: 'button',
  21711. * text: 'OK'
  21712. * }]
  21713. * };
  21714. *
  21715. * In the first example, the button will always be created immediately during the panel's initialization. With
  21716. * many added Components, this approach could potentially slow the rendering of the page. In the second example,
  21717. * the button will not be created or rendered until the panel is actually displayed in the browser. If the panel
  21718. * is never displayed (for example, if it is a tab that remains hidden) then the button will never be created and
  21719. * will never consume any resources whatsoever.
  21720. */
  21721. /**
  21722. * @cfg {String} tplWriteMode
  21723. * The Ext.(X)Template method to use when updating the content area of the Component.
  21724. * See `{@link Ext.XTemplate#overwrite}` for information on default mode.
  21725. */
  21726. tplWriteMode: 'overwrite',
  21727. /**
  21728. * @cfg {String} [baseCls='x-component']
  21729. * The base CSS class to apply to this components's element. This will also be prepended to elements within this
  21730. * component like Panel's body will get a class x-panel-body. This means that if you create a subclass of Panel, and
  21731. * you want it to get all the Panels styling for the element and the body, you leave the baseCls x-panel and use
  21732. * componentCls to add specific styling for this component.
  21733. */
  21734. baseCls: Ext.baseCSSPrefix + 'component',
  21735. /**
  21736. * @cfg {String} componentCls
  21737. * CSS Class to be added to a components root level element to give distinction to it via styling.
  21738. */
  21739. /**
  21740. * @cfg {String} [cls='']
  21741. * An optional extra CSS class that will be added to this component's Element. This can be useful
  21742. * for adding customized styles to the component or any of its children using standard CSS rules.
  21743. */
  21744. /**
  21745. * @cfg {String} [overCls='']
  21746. * An optional extra CSS class that will be added to this component's Element when the mouse moves over the Element,
  21747. * and removed when the mouse moves out. This can be useful for adding customized 'active' or 'hover' styles to the
  21748. * component or any of its children using standard CSS rules.
  21749. */
  21750. /**
  21751. * @cfg {String} [disabledCls='x-item-disabled']
  21752. * CSS class to add when the Component is disabled. Defaults to 'x-item-disabled'.
  21753. */
  21754. disabledCls: Ext.baseCSSPrefix + 'item-disabled',
  21755. /**
  21756. * @cfg {String/String[]} ui
  21757. * A set style for a component. Can be a string or an Array of multiple strings (UIs)
  21758. */
  21759. ui: 'default',
  21760. /**
  21761. * @cfg {String[]} uiCls
  21762. * An array of of classNames which are currently applied to this component
  21763. * @private
  21764. */
  21765. uiCls: [],
  21766. /**
  21767. * @cfg {String} style
  21768. * A custom style specification to be applied to this component's Element. Should be a valid argument to
  21769. * {@link Ext.Element#applyStyles}.
  21770. *
  21771. * new Ext.panel.Panel({
  21772. * title: 'Some Title',
  21773. * renderTo: Ext.getBody(),
  21774. * width: 400, height: 300,
  21775. * layout: 'form',
  21776. * items: [{
  21777. * xtype: 'textarea',
  21778. * style: {
  21779. * width: '95%',
  21780. * marginBottom: '10px'
  21781. * }
  21782. * },
  21783. * new Ext.button.Button({
  21784. * text: 'Send',
  21785. * minWidth: '100',
  21786. * style: {
  21787. * marginBottom: '10px'
  21788. * }
  21789. * })
  21790. * ]
  21791. * });
  21792. */
  21793. /**
  21794. * @cfg {Number} width
  21795. * The width of this component in pixels.
  21796. */
  21797. /**
  21798. * @cfg {Number} height
  21799. * The height of this component in pixels.
  21800. */
  21801. /**
  21802. * @cfg {Number/String} border
  21803. * Specifies the border for this component. The border can be a single numeric value to apply to all sides or it can
  21804. * be a CSS style specification for each style, for example: '10 5 3 10'.
  21805. */
  21806. /**
  21807. * @cfg {Number/String} padding
  21808. * Specifies the padding for this component. The padding can be a single numeric value to apply to all sides or it
  21809. * can be a CSS style specification for each style, for example: '10 5 3 10'.
  21810. */
  21811. /**
  21812. * @cfg {Number/String} margin
  21813. * Specifies the margin for this component. The margin can be a single numeric value to apply to all sides or it can
  21814. * be a CSS style specification for each style, for example: '10 5 3 10'.
  21815. */
  21816. /**
  21817. * @cfg {Boolean} hidden
  21818. * True to hide the component.
  21819. */
  21820. hidden: false,
  21821. /**
  21822. * @cfg {Boolean} disabled
  21823. * True to disable the component.
  21824. */
  21825. disabled: false,
  21826. /**
  21827. * @cfg {Boolean} [draggable=false]
  21828. * Allows the component to be dragged.
  21829. */
  21830. /**
  21831. * @property {Boolean} draggable
  21832. * Read-only property indicating whether or not the component can be dragged
  21833. */
  21834. draggable: false,
  21835. /**
  21836. * @cfg {Boolean} floating
  21837. * Create the Component as a floating and use absolute positioning.
  21838. *
  21839. * 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
  21840. * by the global {@link Ext.WindowManager WindowManager}.
  21841. *
  21842. * 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
  21843. * ZIndexManager instance to manage its descendant floaters. If no floating ancestor can be found, the global WindowManager will be used.
  21844. *
  21845. * When a floating Component which has a ZindexManager managing descendant floaters is destroyed, those descendant floaters will also be destroyed.
  21846. */
  21847. floating: false,
  21848. /**
  21849. * @cfg {String} hideMode
  21850. * A String which specifies how this Component's encapsulating DOM element will be hidden. Values may be:
  21851. *
  21852. * - `'display'` : The Component will be hidden using the `display: none` style.
  21853. * - `'visibility'` : The Component will be hidden using the `visibility: hidden` style.
  21854. * - `'offsets'` : The Component will be hidden by absolutely positioning it out of the visible area of the document.
  21855. * This is useful when a hidden Component must maintain measurable dimensions. Hiding using `display` results in a
  21856. * Component having zero dimensions.
  21857. */
  21858. hideMode: 'display',
  21859. /**
  21860. * @cfg {String} contentEl
  21861. * Specify an existing HTML element, or the `id` of an existing HTML element to use as the content for this component.
  21862. *
  21863. * This config option is used to take an existing HTML element and place it in the layout element of a new component
  21864. * (it simply moves the specified DOM element _after the Component is rendered_ to use as the content.
  21865. *
  21866. * **Notes:**
  21867. *
  21868. * The specified HTML element is appended to the layout element of the component _after any configured
  21869. * {@link #html HTML} has been inserted_, and so the document will not contain this element at the time
  21870. * the {@link #render} event is fired.
  21871. *
  21872. * The specified HTML element used will not participate in any **`{@link Ext.container.Container#layout layout}`**
  21873. * scheme that the Component may use. It is just HTML. Layouts operate on child
  21874. * **`{@link Ext.container.Container#items items}`**.
  21875. *
  21876. * Add either the `x-hidden` or the `x-hide-display` CSS class to prevent a brief flicker of the content before it
  21877. * is rendered to the panel.
  21878. */
  21879. /**
  21880. * @cfg {String/Object} [html='']
  21881. * An HTML fragment, or a {@link Ext.DomHelper DomHelper} specification to use as the layout element content.
  21882. * The HTML content is added after the component is rendered, so the document will not contain this HTML at the time
  21883. * the {@link #render} event is fired. This content is inserted into the body _before_ any configured {@link #contentEl}
  21884. * is appended.
  21885. */
  21886. /**
  21887. * @cfg {Boolean} styleHtmlContent
  21888. * True to automatically style the html inside the content target of this component (body for panels).
  21889. */
  21890. styleHtmlContent: false,
  21891. /**
  21892. * @cfg {String} [styleHtmlCls='x-html']
  21893. * The class that is added to the content target when you set styleHtmlContent to true.
  21894. */
  21895. styleHtmlCls: Ext.baseCSSPrefix + 'html',
  21896. /**
  21897. * @cfg {Number} minHeight
  21898. * The minimum value in pixels which this Component will set its height to.
  21899. *
  21900. * **Warning:** This will override any size management applied by layout managers.
  21901. */
  21902. /**
  21903. * @cfg {Number} minWidth
  21904. * The minimum value in pixels which this Component will set its width to.
  21905. *
  21906. * **Warning:** This will override any size management applied by layout managers.
  21907. */
  21908. /**
  21909. * @cfg {Number} maxHeight
  21910. * The maximum value in pixels which this Component will set its height to.
  21911. *
  21912. * **Warning:** This will override any size management applied by layout managers.
  21913. */
  21914. /**
  21915. * @cfg {Number} maxWidth
  21916. * The maximum value in pixels which this Component will set its width to.
  21917. *
  21918. * **Warning:** This will override any size management applied by layout managers.
  21919. */
  21920. /**
  21921. * @cfg {Ext.ComponentLoader/Object} loader
  21922. * A configuration object or an instance of a {@link Ext.ComponentLoader} to load remote content for this Component.
  21923. */
  21924. /**
  21925. * @cfg {Boolean} autoShow
  21926. * True to automatically show the component upon creation. This config option may only be used for
  21927. * {@link #floating} components or components that use {@link #autoRender}. Defaults to false.
  21928. */
  21929. autoShow: false,
  21930. /**
  21931. * @cfg {Boolean/String/HTMLElement/Ext.Element} autoRender
  21932. * This config is intended mainly for non-{@link #floating} Components which may or may not be shown. Instead of using
  21933. * {@link #renderTo} in the configuration, and rendering upon construction, this allows a Component to render itself
  21934. * upon first _{@link #show}_. If {@link #floating} is true, the value of this config is omited as if it is `true`.
  21935. *
  21936. * Specify as `true` to have this Component render to the document body upon first show.
  21937. *
  21938. * Specify as an element, or the ID of an element to have this Component render to a specific element upon first
  21939. * show.
  21940. *
  21941. * **This defaults to `true` for the {@link Ext.window.Window Window} class.**
  21942. */
  21943. autoRender: false,
  21944. needsLayout: false,
  21945. // @private
  21946. allowDomMove: true,
  21947. /**
  21948. * @cfg {Object/Object[]} plugins
  21949. * An object or array of objects that will provide custom functionality for this component. The only requirement for
  21950. * a valid plugin is that it contain an init method that accepts a reference of type Ext.Component. When a component
  21951. * is created, if any plugins are available, the component will call the init method on each plugin, passing a
  21952. * reference to itself. Each plugin can then call methods or respond to events on the component as needed to provide
  21953. * its functionality.
  21954. */
  21955. /**
  21956. * @property {Boolean} rendered
  21957. * Read-only property indicating whether or not the component has been rendered.
  21958. */
  21959. rendered: false,
  21960. /**
  21961. * @property {Number} componentLayoutCounter
  21962. * @private
  21963. * The number of component layout calls made on this object.
  21964. */
  21965. componentLayoutCounter: 0,
  21966. weight: 0,
  21967. trimRe: /^\s+|\s+$/g,
  21968. spacesRe: /\s+/,
  21969. /**
  21970. * @property {Boolean} maskOnDisable
  21971. * This is an internal flag that you use when creating custom components. By default this is set to true which means
  21972. * that every component gets a mask when its disabled. Components like FieldContainer, FieldSet, Field, Button, Tab
  21973. * override this property to false since they want to implement custom disable logic.
  21974. */
  21975. maskOnDisable: true,
  21976. /**
  21977. * Creates new Component.
  21978. * @param {Object} config (optional) Config object.
  21979. */
  21980. constructor : function(config) {
  21981. var me = this,
  21982. i, len;
  21983. config = config || {};
  21984. me.initialConfig = config;
  21985. Ext.apply(me, config);
  21986. me.addEvents(
  21987. /**
  21988. * @event beforeactivate
  21989. * Fires before a Component has been visually activated. Returning false from an event listener can prevent
  21990. * the activate from occurring.
  21991. * @param {Ext.Component} this
  21992. */
  21993. 'beforeactivate',
  21994. /**
  21995. * @event activate
  21996. * Fires after a Component has been visually activated.
  21997. * @param {Ext.Component} this
  21998. */
  21999. 'activate',
  22000. /**
  22001. * @event beforedeactivate
  22002. * Fires before a Component has been visually deactivated. Returning false from an event listener can
  22003. * prevent the deactivate from occurring.
  22004. * @param {Ext.Component} this
  22005. */
  22006. 'beforedeactivate',
  22007. /**
  22008. * @event deactivate
  22009. * Fires after a Component has been visually deactivated.
  22010. * @param {Ext.Component} this
  22011. */
  22012. 'deactivate',
  22013. /**
  22014. * @event added
  22015. * Fires after a Component had been added to a Container.
  22016. * @param {Ext.Component} this
  22017. * @param {Ext.container.Container} container Parent Container
  22018. * @param {Number} pos position of Component
  22019. */
  22020. 'added',
  22021. /**
  22022. * @event disable
  22023. * Fires after the component is disabled.
  22024. * @param {Ext.Component} this
  22025. */
  22026. 'disable',
  22027. /**
  22028. * @event enable
  22029. * Fires after the component is enabled.
  22030. * @param {Ext.Component} this
  22031. */
  22032. 'enable',
  22033. /**
  22034. * @event beforeshow
  22035. * Fires before the component is shown when calling the {@link #show} method. Return false from an event
  22036. * handler to stop the show.
  22037. * @param {Ext.Component} this
  22038. */
  22039. 'beforeshow',
  22040. /**
  22041. * @event show
  22042. * Fires after the component is shown when calling the {@link #show} method.
  22043. * @param {Ext.Component} this
  22044. */
  22045. 'show',
  22046. /**
  22047. * @event beforehide
  22048. * Fires before the component is hidden when calling the {@link #hide} method. Return false from an event
  22049. * handler to stop the hide.
  22050. * @param {Ext.Component} this
  22051. */
  22052. 'beforehide',
  22053. /**
  22054. * @event hide
  22055. * Fires after the component is hidden. Fires after the component is hidden when calling the {@link #hide}
  22056. * method.
  22057. * @param {Ext.Component} this
  22058. */
  22059. 'hide',
  22060. /**
  22061. * @event removed
  22062. * Fires when a component is removed from an Ext.container.Container
  22063. * @param {Ext.Component} this
  22064. * @param {Ext.container.Container} ownerCt Container which holds the component
  22065. */
  22066. 'removed',
  22067. /**
  22068. * @event beforerender
  22069. * Fires before the component is {@link #rendered}. Return false from an event handler to stop the
  22070. * {@link #render}.
  22071. * @param {Ext.Component} this
  22072. */
  22073. 'beforerender',
  22074. /**
  22075. * @event render
  22076. * Fires after the component markup is {@link #rendered}.
  22077. * @param {Ext.Component} this
  22078. */
  22079. 'render',
  22080. /**
  22081. * @event afterrender
  22082. * Fires after the component rendering is finished.
  22083. *
  22084. * The afterrender event is fired after this Component has been {@link #rendered}, been postprocesed by any
  22085. * afterRender method defined for the Component.
  22086. * @param {Ext.Component} this
  22087. */
  22088. 'afterrender',
  22089. /**
  22090. * @event beforedestroy
  22091. * Fires before the component is {@link #destroy}ed. Return false from an event handler to stop the
  22092. * {@link #destroy}.
  22093. * @param {Ext.Component} this
  22094. */
  22095. 'beforedestroy',
  22096. /**
  22097. * @event destroy
  22098. * Fires after the component is {@link #destroy}ed.
  22099. * @param {Ext.Component} this
  22100. */
  22101. 'destroy',
  22102. /**
  22103. * @event resize
  22104. * Fires after the component is resized.
  22105. * @param {Ext.Component} this
  22106. * @param {Number} adjWidth The box-adjusted width that was set
  22107. * @param {Number} adjHeight The box-adjusted height that was set
  22108. */
  22109. 'resize',
  22110. /**
  22111. * @event move
  22112. * Fires after the component is moved.
  22113. * @param {Ext.Component} this
  22114. * @param {Number} x The new x position
  22115. * @param {Number} y The new y position
  22116. */
  22117. 'move'
  22118. );
  22119. me.getId();
  22120. me.mons = [];
  22121. me.additionalCls = [];
  22122. me.renderData = me.renderData || {};
  22123. me.renderSelectors = me.renderSelectors || {};
  22124. if (me.plugins) {
  22125. me.plugins = [].concat(me.plugins);
  22126. me.constructPlugins();
  22127. }
  22128. me.initComponent();
  22129. // ititComponent gets a chance to change the id property before registering
  22130. Ext.ComponentManager.register(me);
  22131. // Dont pass the config so that it is not applied to 'this' again
  22132. me.mixins.observable.constructor.call(me);
  22133. me.mixins.state.constructor.call(me, config);
  22134. // Save state on resize.
  22135. this.addStateEvents('resize');
  22136. // Move this into Observable?
  22137. if (me.plugins) {
  22138. me.plugins = [].concat(me.plugins);
  22139. for (i = 0, len = me.plugins.length; i < len; i++) {
  22140. me.plugins[i] = me.initPlugin(me.plugins[i]);
  22141. }
  22142. }
  22143. me.loader = me.getLoader();
  22144. if (me.renderTo) {
  22145. me.render(me.renderTo);
  22146. // EXTJSIV-1935 - should be a way to do afterShow or something, but that
  22147. // won't work. Likewise, rendering hidden and then showing (w/autoShow) has
  22148. // implications to afterRender so we cannot do that.
  22149. }
  22150. if (me.autoShow) {
  22151. me.show();
  22152. }
  22153. },
  22154. initComponent: function () {
  22155. // This is called again here to allow derived classes to add plugin configs to the
  22156. // plugins array before calling down to this, the base initComponent.
  22157. this.constructPlugins();
  22158. },
  22159. /**
  22160. * The supplied default state gathering method for the AbstractComponent class.
  22161. *
  22162. * This method returns dimension settings such as `flex`, `anchor`, `width` and `height` along with `collapsed`
  22163. * state.
  22164. *
  22165. * Subclasses which implement more complex state should call the superclass's implementation, and apply their state
  22166. * to the result if this basic state is to be saved.
  22167. *
  22168. * Note that Component state will only be saved if the Component has a {@link #stateId} and there as a StateProvider
  22169. * configured for the document.
  22170. *
  22171. * @return {Object}
  22172. */
  22173. getState: function() {
  22174. var me = this,
  22175. layout = me.ownerCt ? (me.shadowOwnerCt || me.ownerCt).getLayout() : null,
  22176. state = {
  22177. collapsed: me.collapsed
  22178. },
  22179. width = me.width,
  22180. height = me.height,
  22181. cm = me.collapseMemento,
  22182. anchors;
  22183. // If a Panel-local collapse has taken place, use remembered values as the dimensions.
  22184. // TODO: remove this coupling with Panel's privates! All collapse/expand logic should be refactored into one place.
  22185. if (me.collapsed && cm) {
  22186. if (Ext.isDefined(cm.data.width)) {
  22187. width = cm.width;
  22188. }
  22189. if (Ext.isDefined(cm.data.height)) {
  22190. height = cm.height;
  22191. }
  22192. }
  22193. // If we have flex, only store the perpendicular dimension.
  22194. if (layout && me.flex) {
  22195. state.flex = me.flex;
  22196. if (layout.perpendicularPrefix) {
  22197. state[layout.perpendicularPrefix] = me['get' + layout.perpendicularPrefixCap]();
  22198. } else {
  22199. }
  22200. }
  22201. // If we have anchor, only store dimensions which are *not* being anchored
  22202. else if (layout && me.anchor) {
  22203. state.anchor = me.anchor;
  22204. anchors = me.anchor.split(' ').concat(null);
  22205. if (!anchors[0]) {
  22206. if (me.width) {
  22207. state.width = width;
  22208. }
  22209. }
  22210. if (!anchors[1]) {
  22211. if (me.height) {
  22212. state.height = height;
  22213. }
  22214. }
  22215. }
  22216. // Store dimensions.
  22217. else {
  22218. if (me.width) {
  22219. state.width = width;
  22220. }
  22221. if (me.height) {
  22222. state.height = height;
  22223. }
  22224. }
  22225. // Don't save dimensions if they are unchanged from the original configuration.
  22226. if (state.width == me.initialConfig.width) {
  22227. delete state.width;
  22228. }
  22229. if (state.height == me.initialConfig.height) {
  22230. delete state.height;
  22231. }
  22232. // If a Box layout was managing the perpendicular dimension, don't save that dimension
  22233. if (layout && layout.align && (layout.align.indexOf('stretch') !== -1)) {
  22234. delete state[layout.perpendicularPrefix];
  22235. }
  22236. return state;
  22237. },
  22238. show: Ext.emptyFn,
  22239. animate: function(animObj) {
  22240. var me = this,
  22241. to;
  22242. animObj = animObj || {};
  22243. to = animObj.to || {};
  22244. if (Ext.fx.Manager.hasFxBlock(me.id)) {
  22245. return me;
  22246. }
  22247. // Special processing for animating Component dimensions.
  22248. if (!animObj.dynamic && (to.height || to.width)) {
  22249. var curWidth = me.getWidth(),
  22250. w = curWidth,
  22251. curHeight = me.getHeight(),
  22252. h = curHeight,
  22253. needsResize = false;
  22254. if (to.height && to.height > curHeight) {
  22255. h = to.height;
  22256. needsResize = true;
  22257. }
  22258. if (to.width && to.width > curWidth) {
  22259. w = to.width;
  22260. needsResize = true;
  22261. }
  22262. // If any dimensions are being increased, we must resize the internal structure
  22263. // of the Component, but then clip it by sizing its encapsulating element back to original dimensions.
  22264. // The animation will then progressively reveal the larger content.
  22265. if (needsResize) {
  22266. var clearWidth = !Ext.isNumber(me.width),
  22267. clearHeight = !Ext.isNumber(me.height);
  22268. me.componentLayout.childrenChanged = true;
  22269. me.setSize(w, h, me.ownerCt);
  22270. me.el.setSize(curWidth, curHeight);
  22271. if (clearWidth) {
  22272. delete me.width;
  22273. }
  22274. if (clearHeight) {
  22275. delete me.height;
  22276. }
  22277. }
  22278. }
  22279. return me.mixins.animate.animate.apply(me, arguments);
  22280. },
  22281. /**
  22282. * This method finds the topmost active layout who's processing will eventually determine the size and position of
  22283. * this Component.
  22284. *
  22285. * This method is useful when dynamically adding Components into Containers, and some processing must take place
  22286. * after the final sizing and positioning of the Component has been performed.
  22287. *
  22288. * @return {Ext.Component}
  22289. */
  22290. findLayoutController: function() {
  22291. return this.findParentBy(function(c) {
  22292. // Return true if we are at the root of the Container tree
  22293. // or this Container's layout is busy but the next one up is not.
  22294. return !c.ownerCt || (c.layout.layoutBusy && !c.ownerCt.layout.layoutBusy);
  22295. });
  22296. },
  22297. onShow : function() {
  22298. // Layout if needed
  22299. var needsLayout = this.needsLayout;
  22300. if (Ext.isObject(needsLayout)) {
  22301. this.doComponentLayout(needsLayout.width, needsLayout.height, needsLayout.isSetSize, needsLayout.ownerCt);
  22302. }
  22303. },
  22304. constructPlugin: function(plugin) {
  22305. if (plugin.ptype && typeof plugin.init != 'function') {
  22306. plugin.cmp = this;
  22307. plugin = Ext.PluginManager.create(plugin);
  22308. }
  22309. else if (typeof plugin == 'string') {
  22310. plugin = Ext.PluginManager.create({
  22311. ptype: plugin,
  22312. cmp: this
  22313. });
  22314. }
  22315. return plugin;
  22316. },
  22317. /**
  22318. * Ensures that the plugins array contains fully constructed plugin instances. This converts any configs into their
  22319. * appropriate instances.
  22320. */
  22321. constructPlugins: function() {
  22322. var me = this,
  22323. plugins = me.plugins,
  22324. i, len;
  22325. if (plugins) {
  22326. for (i = 0, len = plugins.length; i < len; i++) {
  22327. // this just returns already-constructed plugin instances...
  22328. plugins[i] = me.constructPlugin(plugins[i]);
  22329. }
  22330. }
  22331. },
  22332. // @private
  22333. initPlugin : function(plugin) {
  22334. plugin.init(this);
  22335. return plugin;
  22336. },
  22337. /**
  22338. * Handles autoRender. Floating Components may have an ownerCt. If they are asking to be constrained, constrain them
  22339. * within that ownerCt, and have their z-index managed locally. Floating Components are always rendered to
  22340. * document.body
  22341. */
  22342. doAutoRender: function() {
  22343. var me = this;
  22344. if (me.floating) {
  22345. me.render(document.body);
  22346. } else {
  22347. me.render(Ext.isBoolean(me.autoRender) ? Ext.getBody() : me.autoRender);
  22348. }
  22349. },
  22350. // @private
  22351. render : function(container, position) {
  22352. var me = this;
  22353. if (!me.rendered && me.fireEvent('beforerender', me) !== false) {
  22354. // Flag set during the render process.
  22355. // It can be used to inhibit event-driven layout calls during the render phase
  22356. me.rendering = true;
  22357. // If this.el is defined, we want to make sure we are dealing with
  22358. // an Ext Element.
  22359. if (me.el) {
  22360. me.el = Ext.get(me.el);
  22361. }
  22362. // Perform render-time processing for floating Components
  22363. if (me.floating) {
  22364. me.onFloatRender();
  22365. }
  22366. container = me.initContainer(container);
  22367. me.onRender(container, position);
  22368. // Tell the encapsulating element to hide itself in the way the Component is configured to hide
  22369. // This means DISPLAY, VISIBILITY or OFFSETS.
  22370. me.el.setVisibilityMode(Ext.Element[me.hideMode.toUpperCase()]);
  22371. if (me.overCls) {
  22372. me.el.hover(me.addOverCls, me.removeOverCls, me);
  22373. }
  22374. me.fireEvent('render', me);
  22375. me.initContent();
  22376. me.afterRender(container);
  22377. me.fireEvent('afterrender', me);
  22378. me.initEvents();
  22379. if (me.hidden) {
  22380. // Hiding during the render process should not perform any ancillary
  22381. // actions that the full hide process does; It is not hiding, it begins in a hidden state.'
  22382. // So just make the element hidden according to the configured hideMode
  22383. me.el.hide();
  22384. }
  22385. if (me.disabled) {
  22386. // pass silent so the event doesn't fire the first time.
  22387. me.disable(true);
  22388. }
  22389. // Delete the flag once the rendering is done.
  22390. delete me.rendering;
  22391. }
  22392. return me;
  22393. },
  22394. // @private
  22395. onRender : function(container, position) {
  22396. var me = this,
  22397. el = me.el,
  22398. styles = me.initStyles(),
  22399. renderTpl, renderData, i;
  22400. position = me.getInsertPosition(position);
  22401. if (!el) {
  22402. if (position) {
  22403. el = Ext.DomHelper.insertBefore(position, me.getElConfig(), true);
  22404. }
  22405. else {
  22406. el = Ext.DomHelper.append(container, me.getElConfig(), true);
  22407. }
  22408. }
  22409. else if (me.allowDomMove !== false) {
  22410. if (position) {
  22411. container.dom.insertBefore(el.dom, position);
  22412. } else {
  22413. container.dom.appendChild(el.dom);
  22414. }
  22415. }
  22416. if (Ext.scopeResetCSS && !me.ownerCt) {
  22417. // If this component's el is the body element, we add the reset class to the html tag
  22418. if (el.dom == Ext.getBody().dom) {
  22419. el.parent().addCls(Ext.baseCSSPrefix + 'reset');
  22420. }
  22421. else {
  22422. // Else we wrap this element in an element that adds the reset class.
  22423. me.resetEl = el.wrap({
  22424. cls: Ext.baseCSSPrefix + 'reset'
  22425. });
  22426. }
  22427. }
  22428. me.setUI(me.ui);
  22429. el.addCls(me.initCls());
  22430. el.setStyle(styles);
  22431. // Here we check if the component has a height set through style or css.
  22432. // If it does then we set the this.height to that value and it won't be
  22433. // considered an auto height component
  22434. // if (this.height === undefined) {
  22435. // var height = el.getHeight();
  22436. // // This hopefully means that the panel has an explicit height set in style or css
  22437. // if (height - el.getPadding('tb') - el.getBorderWidth('tb') > 0) {
  22438. // this.height = height;
  22439. // }
  22440. // }
  22441. me.el = el;
  22442. me.initFrame();
  22443. renderTpl = me.initRenderTpl();
  22444. if (renderTpl) {
  22445. renderData = me.initRenderData();
  22446. renderTpl.append(me.getTargetEl(), renderData);
  22447. }
  22448. me.applyRenderSelectors();
  22449. me.rendered = true;
  22450. },
  22451. // @private
  22452. afterRender : function() {
  22453. var me = this,
  22454. pos,
  22455. xy;
  22456. me.getComponentLayout();
  22457. // Set the size if a size is configured, or if this is the outermost Container.
  22458. // Also, if this is a collapsed Panel, it needs an initial component layout
  22459. // to lay out its header so that it can have a height determined.
  22460. if (me.collapsed || (!me.ownerCt || (me.height || me.width))) {
  22461. me.setSize(me.width, me.height);
  22462. } else {
  22463. // It is expected that child items be rendered before this method returns and
  22464. // the afterrender event fires. Since we aren't going to do the layout now, we
  22465. // must render the child items. This is handled implicitly above in the layout
  22466. // caused by setSize.
  22467. me.renderChildren();
  22468. }
  22469. // For floaters, calculate x and y if they aren't defined by aligning
  22470. // the sized element to the center of either the container or the ownerCt
  22471. if (me.floating && (me.x === undefined || me.y === undefined)) {
  22472. if (me.floatParent) {
  22473. xy = me.el.getAlignToXY(me.floatParent.getTargetEl(), 'c-c');
  22474. pos = me.floatParent.getTargetEl().translatePoints(xy[0], xy[1]);
  22475. } else {
  22476. xy = me.el.getAlignToXY(me.container, 'c-c');
  22477. pos = me.container.translatePoints(xy[0], xy[1]);
  22478. }
  22479. me.x = me.x === undefined ? pos.left: me.x;
  22480. me.y = me.y === undefined ? pos.top: me.y;
  22481. }
  22482. if (Ext.isDefined(me.x) || Ext.isDefined(me.y)) {
  22483. me.setPosition(me.x, me.y);
  22484. }
  22485. if (me.styleHtmlContent) {
  22486. me.getTargetEl().addCls(me.styleHtmlCls);
  22487. }
  22488. },
  22489. /**
  22490. * @private
  22491. * Called by Component#doAutoRender
  22492. *
  22493. * Register a Container configured `floating: true` with this Component's {@link Ext.ZIndexManager ZIndexManager}.
  22494. *
  22495. * Components added in ths way will not participate in any layout, but will be rendered
  22496. * upon first show in the way that {@link Ext.window.Window Window}s are.
  22497. */
  22498. registerFloatingItem: function(cmp) {
  22499. var me = this;
  22500. if (!me.floatingItems) {
  22501. me.floatingItems = Ext.create('Ext.ZIndexManager', me);
  22502. }
  22503. me.floatingItems.register(cmp);
  22504. },
  22505. renderChildren: function () {
  22506. var me = this,
  22507. layout = me.getComponentLayout();
  22508. me.suspendLayout = true;
  22509. layout.renderChildren();
  22510. delete me.suspendLayout;
  22511. },
  22512. frameCls: Ext.baseCSSPrefix + 'frame',
  22513. frameIdRegex: /[-]frame\d+[TMB][LCR]$/,
  22514. frameElementCls: {
  22515. tl: [],
  22516. tc: [],
  22517. tr: [],
  22518. ml: [],
  22519. mc: [],
  22520. mr: [],
  22521. bl: [],
  22522. bc: [],
  22523. br: []
  22524. },
  22525. frameTpl: [
  22526. '<tpl if="top">',
  22527. '<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>',
  22528. '<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>',
  22529. '<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>',
  22530. '<tpl if="right"></div></tpl>',
  22531. '<tpl if="left"></div></tpl>',
  22532. '</tpl>',
  22533. '<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>',
  22534. '<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>',
  22535. '<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>',
  22536. '<tpl if="right"></div></tpl>',
  22537. '<tpl if="left"></div></tpl>',
  22538. '<tpl if="bottom">',
  22539. '<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>',
  22540. '<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>',
  22541. '<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>',
  22542. '<tpl if="right"></div></tpl>',
  22543. '<tpl if="left"></div></tpl>',
  22544. '</tpl>'
  22545. ],
  22546. frameTableTpl: [
  22547. '<table><tbody>',
  22548. '<tpl if="top">',
  22549. '<tr>',
  22550. '<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>',
  22551. '<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>',
  22552. '<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>',
  22553. '</tr>',
  22554. '</tpl>',
  22555. '<tr>',
  22556. '<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>',
  22557. '<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>',
  22558. '<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>',
  22559. '</tr>',
  22560. '<tpl if="bottom">',
  22561. '<tr>',
  22562. '<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>',
  22563. '<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>',
  22564. '<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>',
  22565. '</tr>',
  22566. '</tpl>',
  22567. '</tbody></table>'
  22568. ],
  22569. /**
  22570. * @private
  22571. */
  22572. initFrame : function() {
  22573. if (Ext.supports.CSS3BorderRadius) {
  22574. return false;
  22575. }
  22576. var me = this,
  22577. frameInfo = me.getFrameInfo(),
  22578. frameWidth = frameInfo.width,
  22579. frameTpl = me.getFrameTpl(frameInfo.table),
  22580. frameGenId;
  22581. if (me.frame) {
  22582. // since we render id's into the markup and id's NEED to be unique, we have a
  22583. // simple strategy for numbering their generations.
  22584. me.frameGenId = frameGenId = (me.frameGenId || 0) + 1;
  22585. frameGenId = me.id + '-frame' + frameGenId;
  22586. // Here we render the frameTpl to this component. This inserts the 9point div or the table framing.
  22587. frameTpl.insertFirst(me.el, Ext.apply({}, {
  22588. fgid: frameGenId,
  22589. ui: me.ui,
  22590. uiCls: me.uiCls,
  22591. frameCls: me.frameCls,
  22592. baseCls: me.baseCls,
  22593. frameWidth: frameWidth,
  22594. top: !!frameInfo.top,
  22595. left: !!frameInfo.left,
  22596. right: !!frameInfo.right,
  22597. bottom: !!frameInfo.bottom
  22598. }, me.getFramePositions(frameInfo)));
  22599. // The frameBody is returned in getTargetEl, so that layouts render items to the correct target.=
  22600. me.frameBody = me.el.down('.' + me.frameCls + '-mc');
  22601. // Clean out the childEls for the old frame elements (the majority of the els)
  22602. me.removeChildEls(function (c) {
  22603. return c.id && me.frameIdRegex.test(c.id);
  22604. });
  22605. // Add the childEls for each of the new frame elements
  22606. Ext.each(['TL','TC','TR','ML','MC','MR','BL','BC','BR'], function (suffix) {
  22607. me.childEls.push({ name: 'frame' + suffix, id: frameGenId + suffix });
  22608. });
  22609. }
  22610. },
  22611. updateFrame: function() {
  22612. if (Ext.supports.CSS3BorderRadius) {
  22613. return false;
  22614. }
  22615. var me = this,
  22616. wasTable = this.frameSize && this.frameSize.table,
  22617. oldFrameTL = this.frameTL,
  22618. oldFrameBL = this.frameBL,
  22619. oldFrameML = this.frameML,
  22620. oldFrameMC = this.frameMC,
  22621. newMCClassName;
  22622. this.initFrame();
  22623. if (oldFrameMC) {
  22624. if (me.frame) {
  22625. // Reapply render selectors
  22626. delete me.frameTL;
  22627. delete me.frameTC;
  22628. delete me.frameTR;
  22629. delete me.frameML;
  22630. delete me.frameMC;
  22631. delete me.frameMR;
  22632. delete me.frameBL;
  22633. delete me.frameBC;
  22634. delete me.frameBR;
  22635. this.applyRenderSelectors();
  22636. // Store the class names set on the new mc
  22637. newMCClassName = this.frameMC.dom.className;
  22638. // Replace the new mc with the old mc
  22639. oldFrameMC.insertAfter(this.frameMC);
  22640. this.frameMC.remove();
  22641. // Restore the reference to the old frame mc as the framebody
  22642. this.frameBody = this.frameMC = oldFrameMC;
  22643. // Apply the new mc classes to the old mc element
  22644. oldFrameMC.dom.className = newMCClassName;
  22645. // Remove the old framing
  22646. if (wasTable) {
  22647. me.el.query('> table')[1].remove();
  22648. }
  22649. else {
  22650. if (oldFrameTL) {
  22651. oldFrameTL.remove();
  22652. }
  22653. if (oldFrameBL) {
  22654. oldFrameBL.remove();
  22655. }
  22656. oldFrameML.remove();
  22657. }
  22658. }
  22659. else {
  22660. // We were framed but not anymore. Move all content from the old frame to the body
  22661. }
  22662. }
  22663. else if (me.frame) {
  22664. this.applyRenderSelectors();
  22665. }
  22666. },
  22667. getFrameInfo: function() {
  22668. if (Ext.supports.CSS3BorderRadius) {
  22669. return false;
  22670. }
  22671. var me = this,
  22672. left = me.el.getStyle('background-position-x'),
  22673. top = me.el.getStyle('background-position-y'),
  22674. info, frameInfo = false, max;
  22675. // Some browsers dont support background-position-x and y, so for those
  22676. // browsers let's split background-position into two parts.
  22677. if (!left && !top) {
  22678. info = me.el.getStyle('background-position').split(' ');
  22679. left = info[0];
  22680. top = info[1];
  22681. }
  22682. // We actually pass a string in the form of '[type][tl][tr]px [type][br][bl]px' as
  22683. // the background position of this.el from the css to indicate to IE that this component needs
  22684. // framing. We parse it here and change the markup accordingly.
  22685. if (parseInt(left, 10) >= 1000000 && parseInt(top, 10) >= 1000000) {
  22686. max = Math.max;
  22687. frameInfo = {
  22688. // Table markup starts with 110, div markup with 100.
  22689. table: left.substr(0, 3) == '110',
  22690. // Determine if we are dealing with a horizontal or vertical component
  22691. vertical: top.substr(0, 3) == '110',
  22692. // Get and parse the different border radius sizes
  22693. top: max(left.substr(3, 2), left.substr(5, 2)),
  22694. right: max(left.substr(5, 2), top.substr(3, 2)),
  22695. bottom: max(top.substr(3, 2), top.substr(5, 2)),
  22696. left: max(top.substr(5, 2), left.substr(3, 2))
  22697. };
  22698. frameInfo.width = max(frameInfo.top, frameInfo.right, frameInfo.bottom, frameInfo.left);
  22699. // Just to be sure we set the background image of the el to none.
  22700. me.el.setStyle('background-image', 'none');
  22701. }
  22702. // This happens when you set frame: true explicitly without using the x-frame mixin in sass.
  22703. // This way IE can't figure out what sizes to use and thus framing can't work.
  22704. if (me.frame === true && !frameInfo) {
  22705. }
  22706. me.frame = me.frame || !!frameInfo;
  22707. me.frameSize = frameInfo || false;
  22708. return frameInfo;
  22709. },
  22710. getFramePositions: function(frameInfo) {
  22711. var me = this,
  22712. frameWidth = frameInfo.width,
  22713. dock = me.dock,
  22714. positions, tc, bc, ml, mr;
  22715. if (frameInfo.vertical) {
  22716. tc = '0 -' + (frameWidth * 0) + 'px';
  22717. bc = '0 -' + (frameWidth * 1) + 'px';
  22718. if (dock && dock == "right") {
  22719. tc = 'right -' + (frameWidth * 0) + 'px';
  22720. bc = 'right -' + (frameWidth * 1) + 'px';
  22721. }
  22722. positions = {
  22723. tl: '0 -' + (frameWidth * 0) + 'px',
  22724. tr: '0 -' + (frameWidth * 1) + 'px',
  22725. bl: '0 -' + (frameWidth * 2) + 'px',
  22726. br: '0 -' + (frameWidth * 3) + 'px',
  22727. ml: '-' + (frameWidth * 1) + 'px 0',
  22728. mr: 'right 0',
  22729. tc: tc,
  22730. bc: bc
  22731. };
  22732. } else {
  22733. ml = '-' + (frameWidth * 0) + 'px 0';
  22734. mr = 'right 0';
  22735. if (dock && dock == "bottom") {
  22736. ml = 'left bottom';
  22737. mr = 'right bottom';
  22738. }
  22739. positions = {
  22740. tl: '0 -' + (frameWidth * 2) + 'px',
  22741. tr: 'right -' + (frameWidth * 3) + 'px',
  22742. bl: '0 -' + (frameWidth * 4) + 'px',
  22743. br: 'right -' + (frameWidth * 5) + 'px',
  22744. ml: ml,
  22745. mr: mr,
  22746. tc: '0 -' + (frameWidth * 0) + 'px',
  22747. bc: '0 -' + (frameWidth * 1) + 'px'
  22748. };
  22749. }
  22750. return positions;
  22751. },
  22752. /**
  22753. * @private
  22754. */
  22755. getFrameTpl : function(table) {
  22756. return table ? this.getTpl('frameTableTpl') : this.getTpl('frameTpl');
  22757. },
  22758. /**
  22759. * Creates an array of class names from the configurations to add to this Component's `el` on render.
  22760. *
  22761. * Private, but (possibly) used by ComponentQuery for selection by class name if Component is not rendered.
  22762. *
  22763. * @return {String[]} An array of class names with which the Component's element will be rendered.
  22764. * @private
  22765. */
  22766. initCls: function() {
  22767. var me = this,
  22768. cls = [];
  22769. cls.push(me.baseCls);
  22770. if (Ext.isDefined(me.cmpCls)) {
  22771. if (Ext.isDefined(Ext.global.console)) {
  22772. Ext.global.console.warn('Ext.Component: cmpCls has been deprecated. Please use componentCls.');
  22773. }
  22774. me.componentCls = me.cmpCls;
  22775. delete me.cmpCls;
  22776. }
  22777. if (me.componentCls) {
  22778. cls.push(me.componentCls);
  22779. } else {
  22780. me.componentCls = me.baseCls;
  22781. }
  22782. if (me.cls) {
  22783. cls.push(me.cls);
  22784. delete me.cls;
  22785. }
  22786. return cls.concat(me.additionalCls);
  22787. },
  22788. /**
  22789. * Sets the UI for the component. This will remove any existing UIs on the component. It will also loop through any
  22790. * uiCls set on the component and rename them so they include the new UI
  22791. * @param {String} ui The new UI for the component
  22792. */
  22793. setUI: function(ui) {
  22794. var me = this,
  22795. oldUICls = Ext.Array.clone(me.uiCls),
  22796. newUICls = [],
  22797. classes = [],
  22798. cls,
  22799. i;
  22800. //loop through all exisiting uiCls and update the ui in them
  22801. for (i = 0; i < oldUICls.length; i++) {
  22802. cls = oldUICls[i];
  22803. classes = classes.concat(me.removeClsWithUI(cls, true));
  22804. newUICls.push(cls);
  22805. }
  22806. if (classes.length) {
  22807. me.removeCls(classes);
  22808. }
  22809. //remove the UI from the element
  22810. me.removeUIFromElement();
  22811. //set the UI
  22812. me.ui = ui;
  22813. //add the new UI to the elemend
  22814. me.addUIToElement();
  22815. //loop through all exisiting uiCls and update the ui in them
  22816. classes = [];
  22817. for (i = 0; i < newUICls.length; i++) {
  22818. cls = newUICls[i];
  22819. classes = classes.concat(me.addClsWithUI(cls, true));
  22820. }
  22821. if (classes.length) {
  22822. me.addCls(classes);
  22823. }
  22824. },
  22825. /**
  22826. * Adds a cls to the uiCls array, which will also call {@link #addUIClsToElement} and adds to all elements of this
  22827. * component.
  22828. * @param {String/String[]} cls A string or an array of strings to add to the uiCls
  22829. * @param {Object} skip (Boolean) skip True to skip adding it to the class and do it later (via the return)
  22830. */
  22831. addClsWithUI: function(cls, skip) {
  22832. var me = this,
  22833. classes = [],
  22834. i;
  22835. if (!Ext.isArray(cls)) {
  22836. cls = [cls];
  22837. }
  22838. for (i = 0; i < cls.length; i++) {
  22839. if (cls[i] && !me.hasUICls(cls[i])) {
  22840. me.uiCls = Ext.Array.clone(me.uiCls);
  22841. me.uiCls.push(cls[i]);
  22842. classes = classes.concat(me.addUIClsToElement(cls[i]));
  22843. }
  22844. }
  22845. if (skip !== true) {
  22846. me.addCls(classes);
  22847. }
  22848. return classes;
  22849. },
  22850. /**
  22851. * Removes a cls to the uiCls array, which will also call {@link #removeUIClsFromElement} and removes it from all
  22852. * elements of this component.
  22853. * @param {String/String[]} cls A string or an array of strings to remove to the uiCls
  22854. */
  22855. removeClsWithUI: function(cls, skip) {
  22856. var me = this,
  22857. classes = [],
  22858. i;
  22859. if (!Ext.isArray(cls)) {
  22860. cls = [cls];
  22861. }
  22862. for (i = 0; i < cls.length; i++) {
  22863. if (cls[i] && me.hasUICls(cls[i])) {
  22864. me.uiCls = Ext.Array.remove(me.uiCls, cls[i]);
  22865. classes = classes.concat(me.removeUIClsFromElement(cls[i]));
  22866. }
  22867. }
  22868. if (skip !== true) {
  22869. me.removeCls(classes);
  22870. }
  22871. return classes;
  22872. },
  22873. /**
  22874. * Checks if there is currently a specified uiCls
  22875. * @param {String} cls The cls to check
  22876. */
  22877. hasUICls: function(cls) {
  22878. var me = this,
  22879. uiCls = me.uiCls || [];
  22880. return Ext.Array.contains(uiCls, cls);
  22881. },
  22882. /**
  22883. * Method which adds a specified UI + uiCls to the components element. Can be overridden to remove the UI from more
  22884. * than just the components element.
  22885. * @param {String} ui The UI to remove from the element
  22886. */
  22887. addUIClsToElement: function(cls, force) {
  22888. var me = this,
  22889. result = [],
  22890. frameElementCls = me.frameElementCls;
  22891. result.push(Ext.baseCSSPrefix + cls);
  22892. result.push(me.baseCls + '-' + cls);
  22893. result.push(me.baseCls + '-' + me.ui + '-' + cls);
  22894. if (!force && me.frame && !Ext.supports.CSS3BorderRadius) {
  22895. // define each element of the frame
  22896. var els = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'],
  22897. classes, i, j, el;
  22898. // loop through each of them, and if they are defined add the ui
  22899. for (i = 0; i < els.length; i++) {
  22900. el = me['frame' + els[i].toUpperCase()];
  22901. classes = [me.baseCls + '-' + me.ui + '-' + els[i], me.baseCls + '-' + me.ui + '-' + cls + '-' + els[i]];
  22902. if (el && el.dom) {
  22903. el.addCls(classes);
  22904. } else {
  22905. for (j = 0; j < classes.length; j++) {
  22906. if (Ext.Array.indexOf(frameElementCls[els[i]], classes[j]) == -1) {
  22907. frameElementCls[els[i]].push(classes[j]);
  22908. }
  22909. }
  22910. }
  22911. }
  22912. }
  22913. me.frameElementCls = frameElementCls;
  22914. return result;
  22915. },
  22916. /**
  22917. * Method which removes a specified UI + uiCls from the components element. The cls which is added to the element
  22918. * will be: `this.baseCls + '-' + ui`
  22919. * @param {String} ui The UI to add to the element
  22920. */
  22921. removeUIClsFromElement: function(cls, force) {
  22922. var me = this,
  22923. result = [],
  22924. frameElementCls = me.frameElementCls;
  22925. result.push(Ext.baseCSSPrefix + cls);
  22926. result.push(me.baseCls + '-' + cls);
  22927. result.push(me.baseCls + '-' + me.ui + '-' + cls);
  22928. if (!force && me.frame && !Ext.supports.CSS3BorderRadius) {
  22929. // define each element of the frame
  22930. var els = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'],
  22931. i, el;
  22932. cls = me.baseCls + '-' + me.ui + '-' + cls + '-' + els[i];
  22933. // loop through each of them, and if they are defined add the ui
  22934. for (i = 0; i < els.length; i++) {
  22935. el = me['frame' + els[i].toUpperCase()];
  22936. if (el && el.dom) {
  22937. el.removeCls(cls);
  22938. } else {
  22939. Ext.Array.remove(frameElementCls[els[i]], cls);
  22940. }
  22941. }
  22942. }
  22943. me.frameElementCls = frameElementCls;
  22944. return result;
  22945. },
  22946. /**
  22947. * Method which adds a specified UI to the components element.
  22948. * @private
  22949. */
  22950. addUIToElement: function(force) {
  22951. var me = this,
  22952. frameElementCls = me.frameElementCls;
  22953. me.addCls(me.baseCls + '-' + me.ui);
  22954. if (me.frame && !Ext.supports.CSS3BorderRadius) {
  22955. // define each element of the frame
  22956. var els = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'],
  22957. i, el, cls;
  22958. // loop through each of them, and if they are defined add the ui
  22959. for (i = 0; i < els.length; i++) {
  22960. el = me['frame' + els[i].toUpperCase()];
  22961. cls = me.baseCls + '-' + me.ui + '-' + els[i];
  22962. if (el) {
  22963. el.addCls(cls);
  22964. } else {
  22965. if (!Ext.Array.contains(frameElementCls[els[i]], cls)) {
  22966. frameElementCls[els[i]].push(cls);
  22967. }
  22968. }
  22969. }
  22970. }
  22971. },
  22972. /**
  22973. * Method which removes a specified UI from the components element.
  22974. * @private
  22975. */
  22976. removeUIFromElement: function() {
  22977. var me = this,
  22978. frameElementCls = me.frameElementCls;
  22979. me.removeCls(me.baseCls + '-' + me.ui);
  22980. if (me.frame && !Ext.supports.CSS3BorderRadius) {
  22981. // define each element of the frame
  22982. var els = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'],
  22983. i, j, el, cls;
  22984. // loop through each of them, and if they are defined add the ui
  22985. for (i = 0; i < els.length; i++) {
  22986. el = me['frame' + els[i].toUpperCase()];
  22987. cls = me.baseCls + '-' + me.ui + '-' + els[i];
  22988. if (el) {
  22989. el.removeCls(cls);
  22990. } else {
  22991. Ext.Array.remove(frameElementCls[els[i]], cls);
  22992. }
  22993. }
  22994. }
  22995. },
  22996. getElConfig : function() {
  22997. if (Ext.isString(this.autoEl)) {
  22998. this.autoEl = {
  22999. tag: this.autoEl
  23000. };
  23001. }
  23002. var result = this.autoEl || {tag: 'div'};
  23003. result.id = this.id;
  23004. return result;
  23005. },
  23006. /**
  23007. * This function takes the position argument passed to onRender and returns a DOM element that you can use in the
  23008. * insertBefore.
  23009. * @param {String/Number/Ext.Element/HTMLElement} position Index, element id or element you want to put this
  23010. * component before.
  23011. * @return {HTMLElement} DOM element that you can use in the insertBefore
  23012. */
  23013. getInsertPosition: function(position) {
  23014. // Convert the position to an element to insert before
  23015. if (position !== undefined) {
  23016. if (Ext.isNumber(position)) {
  23017. position = this.container.dom.childNodes[position];
  23018. }
  23019. else {
  23020. position = Ext.getDom(position);
  23021. }
  23022. }
  23023. return position;
  23024. },
  23025. /**
  23026. * Adds ctCls to container.
  23027. * @return {Ext.Element} The initialized container
  23028. * @private
  23029. */
  23030. initContainer: function(container) {
  23031. var me = this;
  23032. // If you render a component specifying the el, we get the container
  23033. // of the el, and make sure we dont move the el around in the dom
  23034. // during the render
  23035. if (!container && me.el) {
  23036. container = me.el.dom.parentNode;
  23037. me.allowDomMove = false;
  23038. }
  23039. me.container = Ext.get(container);
  23040. if (me.ctCls) {
  23041. me.container.addCls(me.ctCls);
  23042. }
  23043. return me.container;
  23044. },
  23045. /**
  23046. * Initialized the renderData to be used when rendering the renderTpl.
  23047. * @return {Object} Object with keys and values that are going to be applied to the renderTpl
  23048. * @private
  23049. */
  23050. initRenderData: function() {
  23051. var me = this;
  23052. return Ext.applyIf(me.renderData, {
  23053. id: me.id,
  23054. ui: me.ui,
  23055. uiCls: me.uiCls,
  23056. baseCls: me.baseCls,
  23057. componentCls: me.componentCls,
  23058. frame: me.frame
  23059. });
  23060. },
  23061. /**
  23062. * @private
  23063. */
  23064. getTpl: function(name) {
  23065. var me = this,
  23066. prototype = me.self.prototype,
  23067. ownerPrototype,
  23068. tpl;
  23069. if (me.hasOwnProperty(name)) {
  23070. tpl = me[name];
  23071. if (tpl && !(tpl instanceof Ext.XTemplate)) {
  23072. me[name] = Ext.ClassManager.dynInstantiate('Ext.XTemplate', tpl);
  23073. }
  23074. return me[name];
  23075. }
  23076. if (!(prototype[name] instanceof Ext.XTemplate)) {
  23077. ownerPrototype = prototype;
  23078. do {
  23079. if (ownerPrototype.hasOwnProperty(name)) {
  23080. tpl = ownerPrototype[name];
  23081. if (tpl && !(tpl instanceof Ext.XTemplate)) {
  23082. ownerPrototype[name] = Ext.ClassManager.dynInstantiate('Ext.XTemplate', tpl);
  23083. break;
  23084. }
  23085. }
  23086. ownerPrototype = ownerPrototype.superclass;
  23087. } while (ownerPrototype);
  23088. }
  23089. return prototype[name];
  23090. },
  23091. /**
  23092. * Initializes the renderTpl.
  23093. * @return {Ext.XTemplate} The renderTpl XTemplate instance.
  23094. * @private
  23095. */
  23096. initRenderTpl: function() {
  23097. return this.getTpl('renderTpl');
  23098. },
  23099. /**
  23100. * Converts style definitions to String.
  23101. * @return {String} A CSS style string with style, padding, margin and border.
  23102. * @private
  23103. */
  23104. initStyles: function() {
  23105. var style = {},
  23106. me = this,
  23107. Element = Ext.Element;
  23108. if (Ext.isString(me.style)) {
  23109. style = Element.parseStyles(me.style);
  23110. } else {
  23111. style = Ext.apply({}, me.style);
  23112. }
  23113. // Convert the padding, margin and border properties from a space seperated string
  23114. // into a proper style string
  23115. if (me.padding !== undefined) {
  23116. style.padding = Element.unitizeBox((me.padding === true) ? 5 : me.padding);
  23117. }
  23118. if (me.margin !== undefined) {
  23119. style.margin = Element.unitizeBox((me.margin === true) ? 5 : me.margin);
  23120. }
  23121. delete me.style;
  23122. return style;
  23123. },
  23124. /**
  23125. * Initializes this components contents. It checks for the properties html, contentEl and tpl/data.
  23126. * @private
  23127. */
  23128. initContent: function() {
  23129. var me = this,
  23130. target = me.getTargetEl(),
  23131. contentEl,
  23132. pre;
  23133. if (me.html) {
  23134. target.update(Ext.DomHelper.markup(me.html));
  23135. delete me.html;
  23136. }
  23137. if (me.contentEl) {
  23138. contentEl = Ext.get(me.contentEl);
  23139. pre = Ext.baseCSSPrefix;
  23140. contentEl.removeCls([pre + 'hidden', pre + 'hide-display', pre + 'hide-offsets', pre + 'hide-nosize']);
  23141. target.appendChild(contentEl.dom);
  23142. }
  23143. if (me.tpl) {
  23144. // Make sure this.tpl is an instantiated XTemplate
  23145. if (!me.tpl.isTemplate) {
  23146. me.tpl = Ext.create('Ext.XTemplate', me.tpl);
  23147. }
  23148. if (me.data) {
  23149. me.tpl[me.tplWriteMode](target, me.data);
  23150. delete me.data;
  23151. }
  23152. }
  23153. },
  23154. // @private
  23155. initEvents : function() {
  23156. var me = this,
  23157. afterRenderEvents = me.afterRenderEvents,
  23158. el,
  23159. property,
  23160. fn = function(listeners){
  23161. me.mon(el, listeners);
  23162. };
  23163. if (afterRenderEvents) {
  23164. for (property in afterRenderEvents) {
  23165. if (afterRenderEvents.hasOwnProperty(property)) {
  23166. el = me[property];
  23167. if (el && el.on) {
  23168. Ext.each(afterRenderEvents[property], fn);
  23169. }
  23170. }
  23171. }
  23172. }
  23173. },
  23174. /**
  23175. * Adds each argument passed to this method to the {@link #childEls} array.
  23176. */
  23177. addChildEls: function () {
  23178. var me = this,
  23179. childEls = me.childEls || (me.childEls = []);
  23180. childEls.push.apply(childEls, arguments);
  23181. },
  23182. /**
  23183. * Removes items in the childEls array based on the return value of a supplied test function. The function is called
  23184. * with a entry in childEls and if the test function return true, that entry is removed. If false, that entry is
  23185. * kept.
  23186. * @param {Function} testFn The test function.
  23187. */
  23188. removeChildEls: function (testFn) {
  23189. var me = this,
  23190. old = me.childEls,
  23191. keepers = (me.childEls = []),
  23192. n, i, cel;
  23193. for (i = 0, n = old.length; i < n; ++i) {
  23194. cel = old[i];
  23195. if (!testFn(cel)) {
  23196. keepers.push(cel);
  23197. }
  23198. }
  23199. },
  23200. /**
  23201. * Sets references to elements inside the component. This applies {@link #renderSelectors}
  23202. * as well as {@link #childEls}.
  23203. * @private
  23204. */
  23205. applyRenderSelectors: function() {
  23206. var me = this,
  23207. childEls = me.childEls,
  23208. selectors = me.renderSelectors,
  23209. el = me.el,
  23210. dom = el.dom,
  23211. baseId, childName, childId, i, selector;
  23212. if (childEls) {
  23213. baseId = me.id + '-';
  23214. for (i = childEls.length; i--; ) {
  23215. childName = childId = childEls[i];
  23216. if (typeof(childName) != 'string') {
  23217. childId = childName.id || (baseId + childName.itemId);
  23218. childName = childName.name;
  23219. } else {
  23220. childId = baseId + childId;
  23221. }
  23222. // We don't use Ext.get because that is 3x (or more) slower on IE6-8. Since
  23223. // we know the el's are children of our el we use getById instead:
  23224. me[childName] = el.getById(childId);
  23225. }
  23226. }
  23227. // We still support renderSelectors. There are a few places in the framework that
  23228. // need them and they are a documented part of the API. In fact, we support mixing
  23229. // childEls and renderSelectors (no reason not to).
  23230. if (selectors) {
  23231. for (selector in selectors) {
  23232. if (selectors.hasOwnProperty(selector) && selectors[selector]) {
  23233. me[selector] = Ext.get(Ext.DomQuery.selectNode(selectors[selector], dom));
  23234. }
  23235. }
  23236. }
  23237. },
  23238. /**
  23239. * Tests whether this Component matches the selector string.
  23240. * @param {String} selector The selector string to test against.
  23241. * @return {Boolean} True if this Component matches the selector.
  23242. */
  23243. is: function(selector) {
  23244. return Ext.ComponentQuery.is(this, selector);
  23245. },
  23246. /**
  23247. * Walks up the `ownerCt` axis looking for an ancestor Container which matches the passed simple selector.
  23248. *
  23249. * Example:
  23250. *
  23251. * var owningTabPanel = grid.up('tabpanel');
  23252. *
  23253. * @param {String} [selector] The simple selector to test.
  23254. * @return {Ext.container.Container} The matching ancestor Container (or `undefined` if no match was found).
  23255. */
  23256. up: function(selector) {
  23257. var result = this.ownerCt;
  23258. if (selector) {
  23259. for (; result; result = result.ownerCt) {
  23260. if (Ext.ComponentQuery.is(result, selector)) {
  23261. return result;
  23262. }
  23263. }
  23264. }
  23265. return result;
  23266. },
  23267. /**
  23268. * Returns the next sibling of this Component.
  23269. *
  23270. * Optionally selects the next sibling which matches the passed {@link Ext.ComponentQuery ComponentQuery} selector.
  23271. *
  23272. * May also be refered to as **`next()`**
  23273. *
  23274. * Note that this is limited to siblings, and if no siblings of the item match, `null` is returned. Contrast with
  23275. * {@link #nextNode}
  23276. * @param {String} [selector] A {@link Ext.ComponentQuery ComponentQuery} selector to filter the following items.
  23277. * @return {Ext.Component} The next sibling (or the next sibling which matches the selector).
  23278. * Returns null if there is no matching sibling.
  23279. */
  23280. nextSibling: function(selector) {
  23281. var o = this.ownerCt, it, last, idx, c;
  23282. if (o) {
  23283. it = o.items;
  23284. idx = it.indexOf(this) + 1;
  23285. if (idx) {
  23286. if (selector) {
  23287. for (last = it.getCount(); idx < last; idx++) {
  23288. if ((c = it.getAt(idx)).is(selector)) {
  23289. return c;
  23290. }
  23291. }
  23292. } else {
  23293. if (idx < it.getCount()) {
  23294. return it.getAt(idx);
  23295. }
  23296. }
  23297. }
  23298. }
  23299. return null;
  23300. },
  23301. /**
  23302. * Returns the previous sibling of this Component.
  23303. *
  23304. * Optionally selects the previous sibling which matches the passed {@link Ext.ComponentQuery ComponentQuery}
  23305. * selector.
  23306. *
  23307. * May also be refered to as **`prev()`**
  23308. *
  23309. * Note that this is limited to siblings, and if no siblings of the item match, `null` is returned. Contrast with
  23310. * {@link #previousNode}
  23311. * @param {String} [selector] A {@link Ext.ComponentQuery ComponentQuery} selector to filter the preceding items.
  23312. * @return {Ext.Component} The previous sibling (or the previous sibling which matches the selector).
  23313. * Returns null if there is no matching sibling.
  23314. */
  23315. previousSibling: function(selector) {
  23316. var o = this.ownerCt, it, idx, c;
  23317. if (o) {
  23318. it = o.items;
  23319. idx = it.indexOf(this);
  23320. if (idx != -1) {
  23321. if (selector) {
  23322. for (--idx; idx >= 0; idx--) {
  23323. if ((c = it.getAt(idx)).is(selector)) {
  23324. return c;
  23325. }
  23326. }
  23327. } else {
  23328. if (idx) {
  23329. return it.getAt(--idx);
  23330. }
  23331. }
  23332. }
  23333. }
  23334. return null;
  23335. },
  23336. /**
  23337. * Returns the previous node in the Component tree in tree traversal order.
  23338. *
  23339. * Note that this is not limited to siblings, and if invoked upon a node with no matching siblings, will walk the
  23340. * tree in reverse order to attempt to find a match. Contrast with {@link #previousSibling}.
  23341. * @param {String} [selector] A {@link Ext.ComponentQuery ComponentQuery} selector to filter the preceding nodes.
  23342. * @return {Ext.Component} The previous node (or the previous node which matches the selector).
  23343. * Returns null if there is no matching node.
  23344. */
  23345. previousNode: function(selector, includeSelf) {
  23346. var node = this,
  23347. result,
  23348. it, len, i;
  23349. // If asked to include self, test me
  23350. if (includeSelf && node.is(selector)) {
  23351. return node;
  23352. }
  23353. result = this.prev(selector);
  23354. if (result) {
  23355. return result;
  23356. }
  23357. if (node.ownerCt) {
  23358. for (it = node.ownerCt.items.items, i = Ext.Array.indexOf(it, node) - 1; i > -1; i--) {
  23359. if (it[i].query) {
  23360. result = it[i].query(selector);
  23361. result = result[result.length - 1];
  23362. if (result) {
  23363. return result;
  23364. }
  23365. }
  23366. }
  23367. return node.ownerCt.previousNode(selector, true);
  23368. }
  23369. },
  23370. /**
  23371. * Returns the next node in the Component tree in tree traversal order.
  23372. *
  23373. * Note that this is not limited to siblings, and if invoked upon a node with no matching siblings, will walk the
  23374. * tree to attempt to find a match. Contrast with {@link #nextSibling}.
  23375. * @param {String} [selector] A {@link Ext.ComponentQuery ComponentQuery} selector to filter the following nodes.
  23376. * @return {Ext.Component} The next node (or the next node which matches the selector).
  23377. * Returns null if there is no matching node.
  23378. */
  23379. nextNode: function(selector, includeSelf) {
  23380. var node = this,
  23381. result,
  23382. it, len, i;
  23383. // If asked to include self, test me
  23384. if (includeSelf && node.is(selector)) {
  23385. return node;
  23386. }
  23387. result = this.next(selector);
  23388. if (result) {
  23389. return result;
  23390. }
  23391. if (node.ownerCt) {
  23392. for (it = node.ownerCt.items, i = it.indexOf(node) + 1, it = it.items, len = it.length; i < len; i++) {
  23393. if (it[i].down) {
  23394. result = it[i].down(selector);
  23395. if (result) {
  23396. return result;
  23397. }
  23398. }
  23399. }
  23400. return node.ownerCt.nextNode(selector);
  23401. }
  23402. },
  23403. /**
  23404. * Retrieves the id of this component. Will autogenerate an id if one has not already been set.
  23405. * @return {String}
  23406. */
  23407. getId : function() {
  23408. return this.id || (this.id = 'ext-comp-' + (this.getAutoId()));
  23409. },
  23410. getItemId : function() {
  23411. return this.itemId || this.id;
  23412. },
  23413. /**
  23414. * Retrieves the top level element representing this component.
  23415. * @return {Ext.core.Element}
  23416. */
  23417. getEl : function() {
  23418. return this.el;
  23419. },
  23420. /**
  23421. * This is used to determine where to insert the 'html', 'contentEl' and 'items' in this component.
  23422. * @private
  23423. */
  23424. getTargetEl: function() {
  23425. return this.frameBody || this.el;
  23426. },
  23427. /**
  23428. * Tests whether or not this Component is of a specific xtype. This can test whether this Component is descended
  23429. * from the xtype (default) or whether it is directly of the xtype specified (shallow = true).
  23430. *
  23431. * **If using your own subclasses, be aware that a Component must register its own xtype to participate in
  23432. * determination of inherited xtypes.**
  23433. *
  23434. * For a list of all available xtypes, see the {@link Ext.Component} header.
  23435. *
  23436. * Example usage:
  23437. *
  23438. * var t = new Ext.form.field.Text();
  23439. * var isText = t.isXType('textfield'); // true
  23440. * var isBoxSubclass = t.isXType('field'); // true, descended from Ext.form.field.Base
  23441. * var isBoxInstance = t.isXType('field', true); // false, not a direct Ext.form.field.Base instance
  23442. *
  23443. * @param {String} xtype The xtype to check for this Component
  23444. * @param {Boolean} [shallow=false] True to check whether this Component is directly of the specified xtype, false to
  23445. * check whether this Component is descended from the xtype.
  23446. * @return {Boolean} True if this component descends from the specified xtype, false otherwise.
  23447. */
  23448. isXType: function(xtype, shallow) {
  23449. //assume a string by default
  23450. if (Ext.isFunction(xtype)) {
  23451. xtype = xtype.xtype;
  23452. //handle being passed the class, e.g. Ext.Component
  23453. } else if (Ext.isObject(xtype)) {
  23454. xtype = xtype.statics().xtype;
  23455. //handle being passed an instance
  23456. }
  23457. return !shallow ? ('/' + this.getXTypes() + '/').indexOf('/' + xtype + '/') != -1: this.self.xtype == xtype;
  23458. },
  23459. /**
  23460. * Returns this Component's xtype hierarchy as a slash-delimited string. For a list of all available xtypes, see the
  23461. * {@link Ext.Component} header.
  23462. *
  23463. * **If using your own subclasses, be aware that a Component must register its own xtype to participate in
  23464. * determination of inherited xtypes.**
  23465. *
  23466. * Example usage:
  23467. *
  23468. * var t = new Ext.form.field.Text();
  23469. * alert(t.getXTypes()); // alerts 'component/field/textfield'
  23470. *
  23471. * @return {String} The xtype hierarchy string
  23472. */
  23473. getXTypes: function() {
  23474. var self = this.self,
  23475. xtypes, parentPrototype, parentXtypes;
  23476. if (!self.xtypes) {
  23477. xtypes = [];
  23478. parentPrototype = this;
  23479. while (parentPrototype) {
  23480. parentXtypes = parentPrototype.xtypes;
  23481. if (parentXtypes !== undefined) {
  23482. xtypes.unshift.apply(xtypes, parentXtypes);
  23483. }
  23484. parentPrototype = parentPrototype.superclass;
  23485. }
  23486. self.xtypeChain = xtypes;
  23487. self.xtypes = xtypes.join('/');
  23488. }
  23489. return self.xtypes;
  23490. },
  23491. /**
  23492. * Update the content area of a component.
  23493. * @param {String/Object} htmlOrData If this component has been configured with a template via the tpl config then
  23494. * it will use this argument as data to populate the template. If this component was not configured with a template,
  23495. * the components content area will be updated via Ext.Element update
  23496. * @param {Boolean} [loadScripts=false] Only legitimate when using the html configuration.
  23497. * @param {Function} [callback] Only legitimate when using the html configuration. Callback to execute when
  23498. * scripts have finished loading
  23499. */
  23500. update : function(htmlOrData, loadScripts, cb) {
  23501. var me = this;
  23502. if (me.tpl && !Ext.isString(htmlOrData)) {
  23503. me.data = htmlOrData;
  23504. if (me.rendered) {
  23505. me.tpl[me.tplWriteMode](me.getTargetEl(), htmlOrData || {});
  23506. }
  23507. } else {
  23508. me.html = Ext.isObject(htmlOrData) ? Ext.DomHelper.markup(htmlOrData) : htmlOrData;
  23509. if (me.rendered) {
  23510. me.getTargetEl().update(me.html, loadScripts, cb);
  23511. }
  23512. }
  23513. if (me.rendered) {
  23514. me.doComponentLayout();
  23515. }
  23516. },
  23517. /**
  23518. * Convenience function to hide or show this component by boolean.
  23519. * @param {Boolean} visible True to show, false to hide
  23520. * @return {Ext.Component} this
  23521. */
  23522. setVisible : function(visible) {
  23523. return this[visible ? 'show': 'hide']();
  23524. },
  23525. /**
  23526. * Returns true if this component is visible.
  23527. *
  23528. * @param {Boolean} [deep=false] Pass `true` to interrogate the visibility status of all parent Containers to
  23529. * determine whether this Component is truly visible to the user.
  23530. *
  23531. * Generally, to determine whether a Component is hidden, the no argument form is needed. For example when creating
  23532. * dynamically laid out UIs in a hidden Container before showing them.
  23533. *
  23534. * @return {Boolean} True if this component is visible, false otherwise.
  23535. */
  23536. isVisible: function(deep) {
  23537. var me = this,
  23538. child = me,
  23539. visible = !me.hidden,
  23540. ancestor = me.ownerCt;
  23541. // Clear hiddenOwnerCt property
  23542. me.hiddenAncestor = false;
  23543. if (me.destroyed) {
  23544. return false;
  23545. }
  23546. if (deep && visible && me.rendered && ancestor) {
  23547. while (ancestor) {
  23548. // If any ancestor is hidden, then this is hidden.
  23549. // If an ancestor Panel (only Panels have a collapse method) is collapsed,
  23550. // then its layoutTarget (body) is hidden, so this is hidden unless its within a
  23551. // docked item; they are still visible when collapsed (Unless they themseves are hidden)
  23552. if (ancestor.hidden || (ancestor.collapsed &&
  23553. !(ancestor.getDockedItems && Ext.Array.contains(ancestor.getDockedItems(), child)))) {
  23554. // Store hiddenOwnerCt property if needed
  23555. me.hiddenAncestor = ancestor;
  23556. visible = false;
  23557. break;
  23558. }
  23559. child = ancestor;
  23560. ancestor = ancestor.ownerCt;
  23561. }
  23562. }
  23563. return visible;
  23564. },
  23565. /**
  23566. * Enable the component
  23567. * @param {Boolean} [silent=false] Passing true will supress the 'enable' event from being fired.
  23568. */
  23569. enable: function(silent) {
  23570. var me = this;
  23571. if (me.rendered) {
  23572. me.el.removeCls(me.disabledCls);
  23573. me.el.dom.disabled = false;
  23574. me.onEnable();
  23575. }
  23576. me.disabled = false;
  23577. if (silent !== true) {
  23578. me.fireEvent('enable', me);
  23579. }
  23580. return me;
  23581. },
  23582. /**
  23583. * Disable the component.
  23584. * @param {Boolean} [silent=false] Passing true will supress the 'disable' event from being fired.
  23585. */
  23586. disable: function(silent) {
  23587. var me = this;
  23588. if (me.rendered) {
  23589. me.el.addCls(me.disabledCls);
  23590. me.el.dom.disabled = true;
  23591. me.onDisable();
  23592. }
  23593. me.disabled = true;
  23594. if (silent !== true) {
  23595. me.fireEvent('disable', me);
  23596. }
  23597. return me;
  23598. },
  23599. // @private
  23600. onEnable: function() {
  23601. if (this.maskOnDisable) {
  23602. this.el.unmask();
  23603. }
  23604. },
  23605. // @private
  23606. onDisable : function() {
  23607. if (this.maskOnDisable) {
  23608. this.el.mask();
  23609. }
  23610. },
  23611. /**
  23612. * Method to determine whether this Component is currently disabled.
  23613. * @return {Boolean} the disabled state of this Component.
  23614. */
  23615. isDisabled : function() {
  23616. return this.disabled;
  23617. },
  23618. /**
  23619. * Enable or disable the component.
  23620. * @param {Boolean} disabled True to disable.
  23621. */
  23622. setDisabled : function(disabled) {
  23623. return this[disabled ? 'disable': 'enable']();
  23624. },
  23625. /**
  23626. * Method to determine whether this Component is currently set to hidden.
  23627. * @return {Boolean} the hidden state of this Component.
  23628. */
  23629. isHidden : function() {
  23630. return this.hidden;
  23631. },
  23632. /**
  23633. * Adds a CSS class to the top level element representing this component.
  23634. * @param {String} cls The CSS class name to add
  23635. * @return {Ext.Component} Returns the Component to allow method chaining.
  23636. */
  23637. addCls : function(className) {
  23638. var me = this;
  23639. if (!className) {
  23640. return me;
  23641. }
  23642. if (!Ext.isArray(className)){
  23643. className = className.replace(me.trimRe, '').split(me.spacesRe);
  23644. }
  23645. if (me.rendered) {
  23646. me.el.addCls(className);
  23647. }
  23648. else {
  23649. me.additionalCls = Ext.Array.unique(me.additionalCls.concat(className));
  23650. }
  23651. return me;
  23652. },
  23653. /**
  23654. * Adds a CSS class to the top level element representing this component.
  23655. * @param {String} cls The CSS class name to add
  23656. * @return {Ext.Component} Returns the Component to allow method chaining.
  23657. */
  23658. addClass : function() {
  23659. return this.addCls.apply(this, arguments);
  23660. },
  23661. /**
  23662. * Removes a CSS class from the top level element representing this component.
  23663. * @param {Object} className
  23664. * @return {Ext.Component} Returns the Component to allow method chaining.
  23665. */
  23666. removeCls : function(className) {
  23667. var me = this;
  23668. if (!className) {
  23669. return me;
  23670. }
  23671. if (!Ext.isArray(className)){
  23672. className = className.replace(me.trimRe, '').split(me.spacesRe);
  23673. }
  23674. if (me.rendered) {
  23675. me.el.removeCls(className);
  23676. }
  23677. else if (me.additionalCls.length) {
  23678. Ext.each(className, function(cls) {
  23679. Ext.Array.remove(me.additionalCls, cls);
  23680. });
  23681. }
  23682. return me;
  23683. },
  23684. addOverCls: function() {
  23685. var me = this;
  23686. if (!me.disabled) {
  23687. me.el.addCls(me.overCls);
  23688. }
  23689. },
  23690. removeOverCls: function() {
  23691. this.el.removeCls(this.overCls);
  23692. },
  23693. addListener : function(element, listeners, scope, options) {
  23694. var me = this,
  23695. fn,
  23696. option;
  23697. if (Ext.isString(element) && (Ext.isObject(listeners) || options && options.element)) {
  23698. if (options.element) {
  23699. fn = listeners;
  23700. listeners = {};
  23701. listeners[element] = fn;
  23702. element = options.element;
  23703. if (scope) {
  23704. listeners.scope = scope;
  23705. }
  23706. for (option in options) {
  23707. if (options.hasOwnProperty(option)) {
  23708. if (me.eventOptionsRe.test(option)) {
  23709. listeners[option] = options[option];
  23710. }
  23711. }
  23712. }
  23713. }
  23714. // At this point we have a variable called element,
  23715. // and a listeners object that can be passed to on
  23716. if (me[element] && me[element].on) {
  23717. me.mon(me[element], listeners);
  23718. } else {
  23719. me.afterRenderEvents = me.afterRenderEvents || {};
  23720. if (!me.afterRenderEvents[element]) {
  23721. me.afterRenderEvents[element] = [];
  23722. }
  23723. me.afterRenderEvents[element].push(listeners);
  23724. }
  23725. }
  23726. return me.mixins.observable.addListener.apply(me, arguments);
  23727. },
  23728. // inherit docs
  23729. removeManagedListenerItem: function(isClear, managedListener, item, ename, fn, scope){
  23730. var me = this,
  23731. element = managedListener.options ? managedListener.options.element : null;
  23732. if (element) {
  23733. element = me[element];
  23734. if (element && element.un) {
  23735. if (isClear || (managedListener.item === item && managedListener.ename === ename && (!fn || managedListener.fn === fn) && (!scope || managedListener.scope === scope))) {
  23736. element.un(managedListener.ename, managedListener.fn, managedListener.scope);
  23737. if (!isClear) {
  23738. Ext.Array.remove(me.managedListeners, managedListener);
  23739. }
  23740. }
  23741. }
  23742. } else {
  23743. return me.mixins.observable.removeManagedListenerItem.apply(me, arguments);
  23744. }
  23745. },
  23746. /**
  23747. * Provides the link for Observable's fireEvent method to bubble up the ownership hierarchy.
  23748. * @return {Ext.container.Container} the Container which owns this Component.
  23749. */
  23750. getBubbleTarget : function() {
  23751. return this.ownerCt;
  23752. },
  23753. /**
  23754. * Method to determine whether this Component is floating.
  23755. * @return {Boolean} the floating state of this component.
  23756. */
  23757. isFloating : function() {
  23758. return this.floating;
  23759. },
  23760. /**
  23761. * Method to determine whether this Component is draggable.
  23762. * @return {Boolean} the draggable state of this component.
  23763. */
  23764. isDraggable : function() {
  23765. return !!this.draggable;
  23766. },
  23767. /**
  23768. * Method to determine whether this Component is droppable.
  23769. * @return {Boolean} the droppable state of this component.
  23770. */
  23771. isDroppable : function() {
  23772. return !!this.droppable;
  23773. },
  23774. /**
  23775. * @private
  23776. * Method to manage awareness of when components are added to their
  23777. * respective Container, firing an added event.
  23778. * References are established at add time rather than at render time.
  23779. * @param {Ext.container.Container} container Container which holds the component
  23780. * @param {Number} pos Position at which the component was added
  23781. */
  23782. onAdded : function(container, pos) {
  23783. this.ownerCt = container;
  23784. this.fireEvent('added', this, container, pos);
  23785. },
  23786. /**
  23787. * @private
  23788. * Method to manage awareness of when components are removed from their
  23789. * respective Container, firing an removed event. References are properly
  23790. * cleaned up after removing a component from its owning container.
  23791. */
  23792. onRemoved : function() {
  23793. var me = this;
  23794. me.fireEvent('removed', me, me.ownerCt);
  23795. delete me.ownerCt;
  23796. },
  23797. // @private
  23798. beforeDestroy : Ext.emptyFn,
  23799. // @private
  23800. // @private
  23801. onResize : Ext.emptyFn,
  23802. /**
  23803. * Sets the width and height of this Component. This method fires the {@link #resize} event. This method can accept
  23804. * either width and height as separate arguments, or you can pass a size object like `{width:10, height:20}`.
  23805. *
  23806. * @param {Number/String/Object} width The new width to set. This may be one of:
  23807. *
  23808. * - A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).
  23809. * - A String used to set the CSS width style.
  23810. * - A size object in the format `{width: widthValue, height: heightValue}`.
  23811. * - `undefined` to leave the width unchanged.
  23812. *
  23813. * @param {Number/String} height The new height to set (not required if a size object is passed as the first arg).
  23814. * This may be one of:
  23815. *
  23816. * - A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).
  23817. * - A String used to set the CSS height style. Animation may **not** be used.
  23818. * - `undefined` to leave the height unchanged.
  23819. *
  23820. * @return {Ext.Component} this
  23821. */
  23822. setSize : function(width, height) {
  23823. var me = this,
  23824. layoutCollection;
  23825. // support for standard size objects
  23826. if (Ext.isObject(width)) {
  23827. height = width.height;
  23828. width = width.width;
  23829. }
  23830. // Constrain within configured maxima
  23831. if (Ext.isNumber(width)) {
  23832. width = Ext.Number.constrain(width, me.minWidth, me.maxWidth);
  23833. }
  23834. if (Ext.isNumber(height)) {
  23835. height = Ext.Number.constrain(height, me.minHeight, me.maxHeight);
  23836. }
  23837. if (!me.rendered || !me.isVisible()) {
  23838. // If an ownerCt is hidden, add my reference onto the layoutOnShow stack. Set the needsLayout flag.
  23839. if (me.hiddenAncestor) {
  23840. layoutCollection = me.hiddenAncestor.layoutOnShow;
  23841. layoutCollection.remove(me);
  23842. layoutCollection.add(me);
  23843. }
  23844. me.needsLayout = {
  23845. width: width,
  23846. height: height,
  23847. isSetSize: true
  23848. };
  23849. if (!me.rendered) {
  23850. me.width = (width !== undefined) ? width : me.width;
  23851. me.height = (height !== undefined) ? height : me.height;
  23852. }
  23853. return me;
  23854. }
  23855. me.doComponentLayout(width, height, true);
  23856. return me;
  23857. },
  23858. isFixedWidth: function() {
  23859. var me = this,
  23860. layoutManagedWidth = me.layoutManagedWidth;
  23861. if (Ext.isDefined(me.width) || layoutManagedWidth == 1) {
  23862. return true;
  23863. }
  23864. if (layoutManagedWidth == 2) {
  23865. return false;
  23866. }
  23867. return (me.ownerCt && me.ownerCt.isFixedWidth());
  23868. },
  23869. isFixedHeight: function() {
  23870. var me = this,
  23871. layoutManagedHeight = me.layoutManagedHeight;
  23872. if (Ext.isDefined(me.height) || layoutManagedHeight == 1) {
  23873. return true;
  23874. }
  23875. if (layoutManagedHeight == 2) {
  23876. return false;
  23877. }
  23878. return (me.ownerCt && me.ownerCt.isFixedHeight());
  23879. },
  23880. setCalculatedSize : function(width, height, callingContainer) {
  23881. var me = this,
  23882. layoutCollection;
  23883. // support for standard size objects
  23884. if (Ext.isObject(width)) {
  23885. callingContainer = width.ownerCt;
  23886. height = width.height;
  23887. width = width.width;
  23888. }
  23889. // Constrain within configured maxima
  23890. if (Ext.isNumber(width)) {
  23891. width = Ext.Number.constrain(width, me.minWidth, me.maxWidth);
  23892. }
  23893. if (Ext.isNumber(height)) {
  23894. height = Ext.Number.constrain(height, me.minHeight, me.maxHeight);
  23895. }
  23896. if (!me.rendered || !me.isVisible()) {
  23897. // If an ownerCt is hidden, add my reference onto the layoutOnShow stack. Set the needsLayout flag.
  23898. if (me.hiddenAncestor) {
  23899. layoutCollection = me.hiddenAncestor.layoutOnShow;
  23900. layoutCollection.remove(me);
  23901. layoutCollection.add(me);
  23902. }
  23903. me.needsLayout = {
  23904. width: width,
  23905. height: height,
  23906. isSetSize: false,
  23907. ownerCt: callingContainer
  23908. };
  23909. return me;
  23910. }
  23911. me.doComponentLayout(width, height, false, callingContainer);
  23912. return me;
  23913. },
  23914. /**
  23915. * This method needs to be called whenever you change something on this component that requires the Component's
  23916. * layout to be recalculated.
  23917. * @param {Object} width
  23918. * @param {Object} height
  23919. * @param {Object} isSetSize
  23920. * @param {Object} callingContainer
  23921. * @return {Ext.container.Container} this
  23922. */
  23923. doComponentLayout : function(width, height, isSetSize, callingContainer) {
  23924. var me = this,
  23925. componentLayout = me.getComponentLayout(),
  23926. lastComponentSize = componentLayout.lastComponentSize || {
  23927. width: undefined,
  23928. height: undefined
  23929. };
  23930. // collapsed state is not relevant here, so no testing done.
  23931. // Only Panels have a collapse method, and that just sets the width/height such that only
  23932. // a single docked Header parallel to the collapseTo side are visible, and the Panel body is hidden.
  23933. if (me.rendered && componentLayout) {
  23934. // If no width passed, then only insert a value if the Component is NOT ALLOWED to autowidth itself.
  23935. if (!Ext.isDefined(width)) {
  23936. if (me.isFixedWidth()) {
  23937. width = Ext.isDefined(me.width) ? me.width : lastComponentSize.width;
  23938. }
  23939. }
  23940. // If no height passed, then only insert a value if the Component is NOT ALLOWED to autoheight itself.
  23941. if (!Ext.isDefined(height)) {
  23942. if (me.isFixedHeight()) {
  23943. height = Ext.isDefined(me.height) ? me.height : lastComponentSize.height;
  23944. }
  23945. }
  23946. if (isSetSize) {
  23947. me.width = width;
  23948. me.height = height;
  23949. }
  23950. componentLayout.layout(width, height, isSetSize, callingContainer);
  23951. }
  23952. return me;
  23953. },
  23954. /**
  23955. * Forces this component to redo its componentLayout.
  23956. */
  23957. forceComponentLayout: function () {
  23958. this.doComponentLayout();
  23959. },
  23960. // @private
  23961. setComponentLayout : function(layout) {
  23962. var currentLayout = this.componentLayout;
  23963. if (currentLayout && currentLayout.isLayout && currentLayout != layout) {
  23964. currentLayout.setOwner(null);
  23965. }
  23966. this.componentLayout = layout;
  23967. layout.setOwner(this);
  23968. },
  23969. getComponentLayout : function() {
  23970. var me = this;
  23971. if (!me.componentLayout || !me.componentLayout.isLayout) {
  23972. me.setComponentLayout(Ext.layout.Layout.create(me.componentLayout, 'autocomponent'));
  23973. }
  23974. return me.componentLayout;
  23975. },
  23976. /**
  23977. * Occurs after componentLayout is run.
  23978. * @param {Number} adjWidth The box-adjusted width that was set
  23979. * @param {Number} adjHeight The box-adjusted height that was set
  23980. * @param {Boolean} isSetSize Whether or not the height/width are stored on the component permanently
  23981. * @param {Ext.Component} callingContainer Container requesting the layout. Only used when isSetSize is false.
  23982. */
  23983. afterComponentLayout: function(width, height, isSetSize, callingContainer) {
  23984. var me = this,
  23985. layout = me.componentLayout,
  23986. oldSize = me.preLayoutSize;
  23987. ++me.componentLayoutCounter;
  23988. if (!oldSize || ((width !== oldSize.width) || (height !== oldSize.height))) {
  23989. me.fireEvent('resize', me, width, height);
  23990. }
  23991. },
  23992. /**
  23993. * Occurs before componentLayout is run. Returning false from this method will prevent the componentLayout from
  23994. * being executed.
  23995. * @param {Number} adjWidth The box-adjusted width that was set
  23996. * @param {Number} adjHeight The box-adjusted height that was set
  23997. * @param {Boolean} isSetSize Whether or not the height/width are stored on the component permanently
  23998. * @param {Ext.Component} callingContainer Container requesting sent the layout. Only used when isSetSize is false.
  23999. */
  24000. beforeComponentLayout: function(width, height, isSetSize, callingContainer) {
  24001. this.preLayoutSize = this.componentLayout.lastComponentSize;
  24002. return true;
  24003. },
  24004. /**
  24005. * Sets the left and top of the component. To set the page XY position instead, use
  24006. * {@link Ext.Component#setPagePosition setPagePosition}. This method fires the {@link #move} event.
  24007. * @param {Number} left The new left
  24008. * @param {Number} top The new top
  24009. * @return {Ext.Component} this
  24010. */
  24011. setPosition : function(x, y) {
  24012. var me = this;
  24013. if (Ext.isObject(x)) {
  24014. y = x.y;
  24015. x = x.x;
  24016. }
  24017. if (!me.rendered) {
  24018. return me;
  24019. }
  24020. if (x !== undefined || y !== undefined) {
  24021. me.el.setBox(x, y);
  24022. me.onPosition(x, y);
  24023. me.fireEvent('move', me, x, y);
  24024. }
  24025. return me;
  24026. },
  24027. /**
  24028. * @private
  24029. * Called after the component is moved, this method is empty by default but can be implemented by any
  24030. * subclass that needs to perform custom logic after a move occurs.
  24031. * @param {Number} x The new x position
  24032. * @param {Number} y The new y position
  24033. */
  24034. onPosition: Ext.emptyFn,
  24035. /**
  24036. * Sets the width of the component. This method fires the {@link #resize} event.
  24037. *
  24038. * @param {Number} width The new width to setThis may be one of:
  24039. *
  24040. * - A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).
  24041. * - A String used to set the CSS width style.
  24042. *
  24043. * @return {Ext.Component} this
  24044. */
  24045. setWidth : function(width) {
  24046. return this.setSize(width);
  24047. },
  24048. /**
  24049. * Sets the height of the component. This method fires the {@link #resize} event.
  24050. *
  24051. * @param {Number} height The new height to set. This may be one of:
  24052. *
  24053. * - A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).
  24054. * - A String used to set the CSS height style.
  24055. * - _undefined_ to leave the height unchanged.
  24056. *
  24057. * @return {Ext.Component} this
  24058. */
  24059. setHeight : function(height) {
  24060. return this.setSize(undefined, height);
  24061. },
  24062. /**
  24063. * Gets the current size of the component's underlying element.
  24064. * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
  24065. */
  24066. getSize : function() {
  24067. return this.el.getSize();
  24068. },
  24069. /**
  24070. * Gets the current width of the component's underlying element.
  24071. * @return {Number}
  24072. */
  24073. getWidth : function() {
  24074. return this.el.getWidth();
  24075. },
  24076. /**
  24077. * Gets the current height of the component's underlying element.
  24078. * @return {Number}
  24079. */
  24080. getHeight : function() {
  24081. return this.el.getHeight();
  24082. },
  24083. /**
  24084. * Gets the {@link Ext.ComponentLoader} for this Component.
  24085. * @return {Ext.ComponentLoader} The loader instance, null if it doesn't exist.
  24086. */
  24087. getLoader: function(){
  24088. var me = this,
  24089. autoLoad = me.autoLoad ? (Ext.isObject(me.autoLoad) ? me.autoLoad : {url: me.autoLoad}) : null,
  24090. loader = me.loader || autoLoad;
  24091. if (loader) {
  24092. if (!loader.isLoader) {
  24093. me.loader = Ext.create('Ext.ComponentLoader', Ext.apply({
  24094. target: me,
  24095. autoLoad: autoLoad
  24096. }, loader));
  24097. } else {
  24098. loader.setTarget(me);
  24099. }
  24100. return me.loader;
  24101. }
  24102. return null;
  24103. },
  24104. /**
  24105. * This method allows you to show or hide a LoadMask on top of this component.
  24106. *
  24107. * @param {Boolean/Object/String} load True to show the default LoadMask, a config object that will be passed to the
  24108. * LoadMask constructor, or a message String to show. False to hide the current LoadMask.
  24109. * @param {Boolean} [targetEl=false] True to mask the targetEl of this Component instead of the `this.el`. For example,
  24110. * setting this to true on a Panel will cause only the body to be masked.
  24111. * @return {Ext.LoadMask} The LoadMask instance that has just been shown.
  24112. */
  24113. setLoading : function(load, targetEl) {
  24114. var me = this,
  24115. config;
  24116. if (me.rendered) {
  24117. if (load !== false && !me.collapsed) {
  24118. if (Ext.isObject(load)) {
  24119. config = load;
  24120. }
  24121. else if (Ext.isString(load)) {
  24122. config = {msg: load};
  24123. }
  24124. else {
  24125. config = {};
  24126. }
  24127. me.loadMask = me.loadMask || Ext.create('Ext.LoadMask', targetEl ? me.getTargetEl() : me.el, config);
  24128. me.loadMask.show();
  24129. } else if (me.loadMask) {
  24130. Ext.destroy(me.loadMask);
  24131. me.loadMask = null;
  24132. }
  24133. }
  24134. return me.loadMask;
  24135. },
  24136. /**
  24137. * Sets the dock position of this component in its parent panel. Note that this only has effect if this item is part
  24138. * of the dockedItems collection of a parent that has a DockLayout (note that any Panel has a DockLayout by default)
  24139. * @param {Object} dock The dock position.
  24140. * @param {Boolean} [layoutParent=false] True to re-layout parent.
  24141. * @return {Ext.Component} this
  24142. */
  24143. setDocked : function(dock, layoutParent) {
  24144. var me = this;
  24145. me.dock = dock;
  24146. if (layoutParent && me.ownerCt && me.rendered) {
  24147. me.ownerCt.doComponentLayout();
  24148. }
  24149. return me;
  24150. },
  24151. onDestroy : function() {
  24152. var me = this;
  24153. if (me.monitorResize && Ext.EventManager.resizeEvent) {
  24154. Ext.EventManager.resizeEvent.removeListener(me.setSize, me);
  24155. }
  24156. // Destroying the floatingItems ZIndexManager will also destroy descendant floating Components
  24157. Ext.destroy(
  24158. me.componentLayout,
  24159. me.loadMask,
  24160. me.floatingItems
  24161. );
  24162. },
  24163. /**
  24164. * Remove any references to elements added via renderSelectors/childEls
  24165. * @private
  24166. */
  24167. cleanElementRefs: function(){
  24168. var me = this,
  24169. i = 0,
  24170. childEls = me.childEls,
  24171. selectors = me.renderSelectors,
  24172. selector,
  24173. name,
  24174. len;
  24175. if (me.rendered) {
  24176. if (childEls) {
  24177. for (len = childEls.length; i < len; ++i) {
  24178. name = childEls[i];
  24179. if (typeof(name) != 'string') {
  24180. name = name.name;
  24181. }
  24182. delete me[name];
  24183. }
  24184. }
  24185. if (selectors) {
  24186. for (selector in selectors) {
  24187. if (selectors.hasOwnProperty(selector)) {
  24188. delete me[selector];
  24189. }
  24190. }
  24191. }
  24192. }
  24193. delete me.rendered;
  24194. delete me.el;
  24195. delete me.frameBody;
  24196. },
  24197. /**
  24198. * Destroys the Component.
  24199. */
  24200. destroy : function() {
  24201. var me = this;
  24202. if (!me.isDestroyed) {
  24203. if (me.fireEvent('beforedestroy', me) !== false) {
  24204. me.destroying = true;
  24205. me.beforeDestroy();
  24206. if (me.floating) {
  24207. delete me.floatParent;
  24208. // A zIndexManager is stamped into a *floating* Component when it is added to a Container.
  24209. // If it has no zIndexManager at render time, it is assigned to the global Ext.WindowManager instance.
  24210. if (me.zIndexManager) {
  24211. me.zIndexManager.unregister(me);
  24212. }
  24213. } else if (me.ownerCt && me.ownerCt.remove) {
  24214. me.ownerCt.remove(me, false);
  24215. }
  24216. me.onDestroy();
  24217. // Attempt to destroy all plugins
  24218. Ext.destroy(me.plugins);
  24219. if (me.rendered) {
  24220. me.el.remove();
  24221. }
  24222. me.fireEvent('destroy', me);
  24223. Ext.ComponentManager.unregister(me);
  24224. me.mixins.state.destroy.call(me);
  24225. me.clearListeners();
  24226. // make sure we clean up the element references after removing all events
  24227. me.cleanElementRefs();
  24228. me.destroying = false;
  24229. me.isDestroyed = true;
  24230. }
  24231. }
  24232. },
  24233. /**
  24234. * Retrieves a plugin by its pluginId which has been bound to this component.
  24235. * @param {Object} pluginId
  24236. * @return {Ext.AbstractPlugin} plugin instance.
  24237. */
  24238. getPlugin: function(pluginId) {
  24239. var i = 0,
  24240. plugins = this.plugins,
  24241. ln = plugins.length;
  24242. for (; i < ln; i++) {
  24243. if (plugins[i].pluginId === pluginId) {
  24244. return plugins[i];
  24245. }
  24246. }
  24247. },
  24248. /**
  24249. * Determines whether this component is the descendant of a particular container.
  24250. * @param {Ext.Container} container
  24251. * @return {Boolean} True if it is.
  24252. */
  24253. isDescendantOf: function(container) {
  24254. return !!this.findParentBy(function(p){
  24255. return p === container;
  24256. });
  24257. }
  24258. }, function() {
  24259. this.createAlias({
  24260. on: 'addListener',
  24261. prev: 'previousSibling',
  24262. next: 'nextSibling'
  24263. });
  24264. });
  24265. /**
  24266. * The AbstractPlugin class is the base class from which user-implemented plugins should inherit.
  24267. *
  24268. * This class defines the essential API of plugins as used by Components by defining the following methods:
  24269. *
  24270. * - `init` : The plugin initialization method which the owning Component calls at Component initialization time.
  24271. *
  24272. * The Component passes itself as the sole parameter.
  24273. *
  24274. * Subclasses should set up bidirectional links between the plugin and its client Component here.
  24275. *
  24276. * - `destroy` : The plugin cleanup method which the owning Component calls at Component destruction time.
  24277. *
  24278. * Use this method to break links between the plugin and the Component and to free any allocated resources.
  24279. *
  24280. * - `enable` : The base implementation just sets the plugin's `disabled` flag to `false`
  24281. *
  24282. * - `disable` : The base implementation just sets the plugin's `disabled` flag to `true`
  24283. */
  24284. Ext.define('Ext.AbstractPlugin', {
  24285. disabled: false,
  24286. constructor: function(config) {
  24287. Ext.apply(this, config);
  24288. },
  24289. getCmp: function() {
  24290. return this.cmp;
  24291. },
  24292. /**
  24293. * @method
  24294. * The init method is invoked after initComponent method has been run for the client Component.
  24295. *
  24296. * The supplied implementation is empty. Subclasses should perform plugin initialization, and set up bidirectional
  24297. * links between the plugin and its client Component in their own implementation of this method.
  24298. * @param {Ext.Component} client The client Component which owns this plugin.
  24299. */
  24300. init: Ext.emptyFn,
  24301. /**
  24302. * @method
  24303. * The destroy method is invoked by the owning Component at the time the Component is being destroyed.
  24304. *
  24305. * The supplied implementation is empty. Subclasses should perform plugin cleanup in their own implementation of
  24306. * this method.
  24307. */
  24308. destroy: Ext.emptyFn,
  24309. /**
  24310. * The base implementation just sets the plugin's `disabled` flag to `false`
  24311. *
  24312. * Plugin subclasses which need more complex processing may implement an overriding implementation.
  24313. */
  24314. enable: function() {
  24315. this.disabled = false;
  24316. },
  24317. /**
  24318. * The base implementation just sets the plugin's `disabled` flag to `true`
  24319. *
  24320. * Plugin subclasses which need more complex processing may implement an overriding implementation.
  24321. */
  24322. disable: function() {
  24323. this.disabled = true;
  24324. }
  24325. });
  24326. /**
  24327. * The Connection class encapsulates a connection to the page's originating domain, allowing requests to be made either
  24328. * to a configured URL, or to a URL specified at request time.
  24329. *
  24330. * Requests made by this class are asynchronous, and will return immediately. No data from the server will be available
  24331. * to the statement immediately following the {@link #request} call. To process returned data, use a success callback
  24332. * in the request options object, or an {@link #requestcomplete event listener}.
  24333. *
  24334. * # File Uploads
  24335. *
  24336. * File uploads are not performed using normal "Ajax" techniques, that is they are not performed using XMLHttpRequests.
  24337. * Instead the form is submitted in the standard manner with the DOM &lt;form&gt; element temporarily modified to have its
  24338. * target set to refer to a dynamically generated, hidden &lt;iframe&gt; which is inserted into the document but removed
  24339. * after the return data has been gathered.
  24340. *
  24341. * The server response is parsed by the browser to create the document for the IFRAME. If the server is using JSON to
  24342. * send the return object, then the Content-Type header must be set to "text/html" in order to tell the browser to
  24343. * insert the text unchanged into the document body.
  24344. *
  24345. * Characters which are significant to an HTML parser must be sent as HTML entities, so encode `<` as `&lt;`, `&` as
  24346. * `&amp;` etc.
  24347. *
  24348. * The response text is retrieved from the document, and a fake XMLHttpRequest object is created containing a
  24349. * responseText property in order to conform to the requirements of event handlers and callbacks.
  24350. *
  24351. * Be aware that file upload packets are sent with the content type multipart/form and some server technologies
  24352. * (notably JEE) may require some custom processing in order to retrieve parameter names and parameter values from the
  24353. * packet content.
  24354. *
  24355. * Also note that it's not possible to check the response code of the hidden iframe, so the success handler will ALWAYS fire.
  24356. */
  24357. Ext.define('Ext.data.Connection', {
  24358. mixins: {
  24359. observable: 'Ext.util.Observable'
  24360. },
  24361. statics: {
  24362. requestId: 0
  24363. },
  24364. url: null,
  24365. async: true,
  24366. method: null,
  24367. username: '',
  24368. password: '',
  24369. /**
  24370. * @cfg {Boolean} disableCaching
  24371. * True to add a unique cache-buster param to GET requests.
  24372. */
  24373. disableCaching: true,
  24374. /**
  24375. * @cfg {Boolean} withCredentials
  24376. * True to set `withCredentials = true` on the XHR object
  24377. */
  24378. withCredentials: false,
  24379. /**
  24380. * @cfg {Boolean} cors
  24381. * True to enable CORS support on the XHR object. Currently the only effect of this option
  24382. * is to use the XDomainRequest object instead of XMLHttpRequest if the browser is IE8 or above.
  24383. */
  24384. cors: false,
  24385. /**
  24386. * @cfg {String} disableCachingParam
  24387. * Change the parameter which is sent went disabling caching through a cache buster.
  24388. */
  24389. disableCachingParam: '_dc',
  24390. /**
  24391. * @cfg {Number} timeout
  24392. * The timeout in milliseconds to be used for requests.
  24393. */
  24394. timeout : 30000,
  24395. /**
  24396. * @cfg {Object} extraParams
  24397. * Any parameters to be appended to the request.
  24398. */
  24399. useDefaultHeader : true,
  24400. defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8',
  24401. useDefaultXhrHeader : true,
  24402. defaultXhrHeader : 'XMLHttpRequest',
  24403. constructor : function(config) {
  24404. config = config || {};
  24405. Ext.apply(this, config);
  24406. this.addEvents(
  24407. /**
  24408. * @event beforerequest
  24409. * Fires before a network request is made to retrieve a data object.
  24410. * @param {Ext.data.Connection} conn This Connection object.
  24411. * @param {Object} options The options config object passed to the {@link #request} method.
  24412. */
  24413. 'beforerequest',
  24414. /**
  24415. * @event requestcomplete
  24416. * Fires if the request was successfully completed.
  24417. * @param {Ext.data.Connection} conn This Connection object.
  24418. * @param {Object} response The XHR object containing the response data.
  24419. * See [The XMLHttpRequest Object](http://www.w3.org/TR/XMLHttpRequest/) for details.
  24420. * @param {Object} options The options config object passed to the {@link #request} method.
  24421. */
  24422. 'requestcomplete',
  24423. /**
  24424. * @event requestexception
  24425. * Fires if an error HTTP status was returned from the server.
  24426. * See [HTTP Status Code Definitions](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
  24427. * for details of HTTP status codes.
  24428. * @param {Ext.data.Connection} conn This Connection object.
  24429. * @param {Object} response The XHR object containing the response data.
  24430. * See [The XMLHttpRequest Object](http://www.w3.org/TR/XMLHttpRequest/) for details.
  24431. * @param {Object} options The options config object passed to the {@link #request} method.
  24432. */
  24433. 'requestexception'
  24434. );
  24435. this.requests = {};
  24436. this.mixins.observable.constructor.call(this);
  24437. },
  24438. /**
  24439. * Sends an HTTP request to a remote server.
  24440. *
  24441. * **Important:** Ajax server requests are asynchronous, and this call will
  24442. * return before the response has been received. Process any returned data
  24443. * in a callback function.
  24444. *
  24445. * Ext.Ajax.request({
  24446. * url: 'ajax_demo/sample.json',
  24447. * success: function(response, opts) {
  24448. * var obj = Ext.decode(response.responseText);
  24449. * console.dir(obj);
  24450. * },
  24451. * failure: function(response, opts) {
  24452. * console.log('server-side failure with status code ' + response.status);
  24453. * }
  24454. * });
  24455. *
  24456. * To execute a callback function in the correct scope, use the `scope` option.
  24457. *
  24458. * @param {Object} options An object which may contain the following properties:
  24459. *
  24460. * (The options object may also contain any other property which might be needed to perform
  24461. * postprocessing in a callback because it is passed to callback functions.)
  24462. *
  24463. * @param {String/Function} options.url The URL to which to send the request, or a function
  24464. * to call which returns a URL string. The scope of the function is specified by the `scope` option.
  24465. * Defaults to the configured `url`.
  24466. *
  24467. * @param {Object/String/Function} options.params An object containing properties which are
  24468. * used as parameters to the request, a url encoded string or a function to call to get either. The scope
  24469. * of the function is specified by the `scope` option.
  24470. *
  24471. * @param {String} options.method The HTTP method to use
  24472. * for the request. Defaults to the configured method, or if no method was configured,
  24473. * "GET" if no parameters are being sent, and "POST" if parameters are being sent. Note that
  24474. * the method name is case-sensitive and should be all caps.
  24475. *
  24476. * @param {Function} options.callback The function to be called upon receipt of the HTTP response.
  24477. * The callback is called regardless of success or failure and is passed the following parameters:
  24478. * @param {Object} options.callback.options The parameter to the request call.
  24479. * @param {Boolean} options.callback.success True if the request succeeded.
  24480. * @param {Object} options.callback.response The XMLHttpRequest object containing the response data.
  24481. * See [www.w3.org/TR/XMLHttpRequest/](http://www.w3.org/TR/XMLHttpRequest/) for details about
  24482. * accessing elements of the response.
  24483. *
  24484. * @param {Function} options.success The function to be called upon success of the request.
  24485. * The callback is passed the following parameters:
  24486. * @param {Object} options.success.response The XMLHttpRequest object containing the response data.
  24487. * @param {Object} options.success.options The parameter to the request call.
  24488. *
  24489. * @param {Function} options.failure The function to be called upon success of the request.
  24490. * The callback is passed the following parameters:
  24491. * @param {Object} options.failure.response The XMLHttpRequest object containing the response data.
  24492. * @param {Object} options.failure.options The parameter to the request call.
  24493. *
  24494. * @param {Object} options.scope The scope in which to execute the callbacks: The "this" object for
  24495. * the callback function. If the `url`, or `params` options were specified as functions from which to
  24496. * draw values, then this also serves as the scope for those function calls. Defaults to the browser
  24497. * window.
  24498. *
  24499. * @param {Number} options.timeout The timeout in milliseconds to be used for this request.
  24500. * Defaults to 30 seconds.
  24501. *
  24502. * @param {Ext.Element/HTMLElement/String} options.form The `<form>` Element or the id of the `<form>`
  24503. * to pull parameters from.
  24504. *
  24505. * @param {Boolean} options.isUpload **Only meaningful when used with the `form` option.**
  24506. *
  24507. * True if the form object is a file upload (will be set automatically if the form was configured
  24508. * with **`enctype`** `"multipart/form-data"`).
  24509. *
  24510. * File uploads are not performed using normal "Ajax" techniques, that is they are **not**
  24511. * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
  24512. * DOM `<form>` element temporarily modified to have its [target][] set to refer to a dynamically
  24513. * generated, hidden `<iframe>` which is inserted into the document but removed after the return data
  24514. * has been gathered.
  24515. *
  24516. * The server response is parsed by the browser to create the document for the IFRAME. If the
  24517. * server is using JSON to send the return object, then the [Content-Type][] header must be set to
  24518. * "text/html" in order to tell the browser to insert the text unchanged into the document body.
  24519. *
  24520. * The response text is retrieved from the document, and a fake XMLHttpRequest object is created
  24521. * containing a `responseText` property in order to conform to the requirements of event handlers
  24522. * and callbacks.
  24523. *
  24524. * Be aware that file upload packets are sent with the content type [multipart/form][] and some server
  24525. * technologies (notably JEE) may require some custom processing in order to retrieve parameter names
  24526. * and parameter values from the packet content.
  24527. *
  24528. * [target]: http://www.w3.org/TR/REC-html40/present/frames.html#adef-target
  24529. * [Content-Type]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
  24530. * [multipart/form]: http://www.faqs.org/rfcs/rfc2388.html
  24531. *
  24532. * @param {Object} options.headers Request headers to set for the request.
  24533. *
  24534. * @param {Object} options.xmlData XML document to use for the post. Note: This will be used instead
  24535. * of params for the post data. Any params will be appended to the URL.
  24536. *
  24537. * @param {Object/String} options.jsonData JSON data to use as the post. Note: This will be used
  24538. * instead of params for the post data. Any params will be appended to the URL.
  24539. *
  24540. * @param {Boolean} options.disableCaching True to add a unique cache-buster param to GET requests.
  24541. *
  24542. * @param {Boolean} options.withCredentials True to add the withCredentials property to the XHR object
  24543. *
  24544. * @return {Object} The request object. This may be used to cancel the request.
  24545. */
  24546. request : function(options) {
  24547. options = options || {};
  24548. var me = this,
  24549. scope = options.scope || window,
  24550. username = options.username || me.username,
  24551. password = options.password || me.password || '',
  24552. async,
  24553. requestOptions,
  24554. request,
  24555. headers,
  24556. xhr;
  24557. if (me.fireEvent('beforerequest', me, options) !== false) {
  24558. requestOptions = me.setOptions(options, scope);
  24559. if (this.isFormUpload(options) === true) {
  24560. this.upload(options.form, requestOptions.url, requestOptions.data, options);
  24561. return null;
  24562. }
  24563. // if autoabort is set, cancel the current transactions
  24564. if (options.autoAbort === true || me.autoAbort) {
  24565. me.abort();
  24566. }
  24567. // create a connection object
  24568. if ((options.cors === true || me.cors === true) && Ext.isIe && Ext.ieVersion >= 8) {
  24569. xhr = new XDomainRequest();
  24570. } else {
  24571. xhr = this.getXhrInstance();
  24572. }
  24573. async = options.async !== false ? (options.async || me.async) : false;
  24574. // open the request
  24575. if (username) {
  24576. xhr.open(requestOptions.method, requestOptions.url, async, username, password);
  24577. } else {
  24578. xhr.open(requestOptions.method, requestOptions.url, async);
  24579. }
  24580. if (options.withCredentials === true || me.withCredentials === true) {
  24581. xhr.withCredentials = true;
  24582. }
  24583. headers = me.setupHeaders(xhr, options, requestOptions.data, requestOptions.params);
  24584. // create the transaction object
  24585. request = {
  24586. id: ++Ext.data.Connection.requestId,
  24587. xhr: xhr,
  24588. headers: headers,
  24589. options: options,
  24590. async: async,
  24591. timeout: setTimeout(function() {
  24592. request.timedout = true;
  24593. me.abort(request);
  24594. }, options.timeout || me.timeout)
  24595. };
  24596. me.requests[request.id] = request;
  24597. me.latestId = request.id;
  24598. // bind our statechange listener
  24599. if (async) {
  24600. xhr.onreadystatechange = Ext.Function.bind(me.onStateChange, me, [request]);
  24601. }
  24602. // start the request!
  24603. xhr.send(requestOptions.data);
  24604. if (!async) {
  24605. return this.onComplete(request);
  24606. }
  24607. return request;
  24608. } else {
  24609. Ext.callback(options.callback, options.scope, [options, undefined, undefined]);
  24610. return null;
  24611. }
  24612. },
  24613. /**
  24614. * Uploads a form using a hidden iframe.
  24615. * @param {String/HTMLElement/Ext.Element} form The form to upload
  24616. * @param {String} url The url to post to
  24617. * @param {String} params Any extra parameters to pass
  24618. * @param {Object} options The initial options
  24619. */
  24620. upload: function(form, url, params, options) {
  24621. form = Ext.getDom(form);
  24622. options = options || {};
  24623. var id = Ext.id(),
  24624. frame = document.createElement('iframe'),
  24625. hiddens = [],
  24626. encoding = 'multipart/form-data',
  24627. buf = {
  24628. target: form.target,
  24629. method: form.method,
  24630. encoding: form.encoding,
  24631. enctype: form.enctype,
  24632. action: form.action
  24633. }, hiddenItem;
  24634. /*
  24635. * Originally this behaviour was modified for Opera 10 to apply the secure URL after
  24636. * the frame had been added to the document. It seems this has since been corrected in
  24637. * Opera so the behaviour has been reverted, the URL will be set before being added.
  24638. */
  24639. Ext.fly(frame).set({
  24640. id: id,
  24641. name: id,
  24642. cls: Ext.baseCSSPrefix + 'hide-display',
  24643. src: Ext.SSL_SECURE_URL
  24644. });
  24645. document.body.appendChild(frame);
  24646. // This is required so that IE doesn't pop the response up in a new window.
  24647. if (document.frames) {
  24648. document.frames[id].name = id;
  24649. }
  24650. Ext.fly(form).set({
  24651. target: id,
  24652. method: 'POST',
  24653. enctype: encoding,
  24654. encoding: encoding,
  24655. action: url || buf.action
  24656. });
  24657. // add dynamic params
  24658. if (params) {
  24659. Ext.iterate(Ext.Object.fromQueryString(params), function(name, value){
  24660. hiddenItem = document.createElement('input');
  24661. Ext.fly(hiddenItem).set({
  24662. type: 'hidden',
  24663. value: value,
  24664. name: name
  24665. });
  24666. form.appendChild(hiddenItem);
  24667. hiddens.push(hiddenItem);
  24668. });
  24669. }
  24670. Ext.fly(frame).on('load', Ext.Function.bind(this.onUploadComplete, this, [frame, options]), null, {single: true});
  24671. form.submit();
  24672. Ext.fly(form).set(buf);
  24673. Ext.each(hiddens, function(h) {
  24674. Ext.removeNode(h);
  24675. });
  24676. },
  24677. /**
  24678. * @private
  24679. * Callback handler for the upload function. After we've submitted the form via the iframe this creates a bogus
  24680. * response object to simulate an XHR and populates its responseText from the now-loaded iframe's document body
  24681. * (or a textarea inside the body). We then clean up by removing the iframe
  24682. */
  24683. onUploadComplete: function(frame, options) {
  24684. var me = this,
  24685. // bogus response object
  24686. response = {
  24687. responseText: '',
  24688. responseXML: null
  24689. }, doc, firstChild;
  24690. try {
  24691. doc = frame.contentWindow.document || frame.contentDocument || window.frames[frame.id].document;
  24692. if (doc) {
  24693. if (doc.body) {
  24694. if (/textarea/i.test((firstChild = doc.body.firstChild || {}).tagName)) { // json response wrapped in textarea
  24695. response.responseText = firstChild.value;
  24696. } else {
  24697. response.responseText = doc.body.innerHTML;
  24698. }
  24699. }
  24700. //in IE the document may still have a body even if returns XML.
  24701. response.responseXML = doc.XMLDocument || doc;
  24702. }
  24703. } catch (e) {
  24704. }
  24705. me.fireEvent('requestcomplete', me, response, options);
  24706. Ext.callback(options.success, options.scope, [response, options]);
  24707. Ext.callback(options.callback, options.scope, [options, true, response]);
  24708. setTimeout(function(){
  24709. Ext.removeNode(frame);
  24710. }, 100);
  24711. },
  24712. /**
  24713. * Detects whether the form is intended to be used for an upload.
  24714. * @private
  24715. */
  24716. isFormUpload: function(options){
  24717. var form = this.getForm(options);
  24718. if (form) {
  24719. return (options.isUpload || (/multipart\/form-data/i).test(form.getAttribute('enctype')));
  24720. }
  24721. return false;
  24722. },
  24723. /**
  24724. * Gets the form object from options.
  24725. * @private
  24726. * @param {Object} options The request options
  24727. * @return {HTMLElement} The form, null if not passed
  24728. */
  24729. getForm: function(options){
  24730. return Ext.getDom(options.form) || null;
  24731. },
  24732. /**
  24733. * Sets various options such as the url, params for the request
  24734. * @param {Object} options The initial options
  24735. * @param {Object} scope The scope to execute in
  24736. * @return {Object} The params for the request
  24737. */
  24738. setOptions: function(options, scope){
  24739. var me = this,
  24740. params = options.params || {},
  24741. extraParams = me.extraParams,
  24742. urlParams = options.urlParams,
  24743. url = options.url || me.url,
  24744. jsonData = options.jsonData,
  24745. method,
  24746. disableCache,
  24747. data;
  24748. // allow params to be a method that returns the params object
  24749. if (Ext.isFunction(params)) {
  24750. params = params.call(scope, options);
  24751. }
  24752. // allow url to be a method that returns the actual url
  24753. if (Ext.isFunction(url)) {
  24754. url = url.call(scope, options);
  24755. }
  24756. url = this.setupUrl(options, url);
  24757. // check for xml or json data, and make sure json data is encoded
  24758. data = options.rawData || options.xmlData || jsonData || null;
  24759. if (jsonData && !Ext.isPrimitive(jsonData)) {
  24760. data = Ext.encode(data);
  24761. }
  24762. // make sure params are a url encoded string and include any extraParams if specified
  24763. if (Ext.isObject(params)) {
  24764. params = Ext.Object.toQueryString(params);
  24765. }
  24766. if (Ext.isObject(extraParams)) {
  24767. extraParams = Ext.Object.toQueryString(extraParams);
  24768. }
  24769. params = params + ((extraParams) ? ((params) ? '&' : '') + extraParams : '');
  24770. urlParams = Ext.isObject(urlParams) ? Ext.Object.toQueryString(urlParams) : urlParams;
  24771. params = this.setupParams(options, params);
  24772. // decide the proper method for this request
  24773. method = (options.method || me.method || ((params || data) ? 'POST' : 'GET')).toUpperCase();
  24774. this.setupMethod(options, method);
  24775. disableCache = options.disableCaching !== false ? (options.disableCaching || me.disableCaching) : false;
  24776. // if the method is get append date to prevent caching
  24777. if (method === 'GET' && disableCache) {
  24778. url = Ext.urlAppend(url, (options.disableCachingParam || me.disableCachingParam) + '=' + (new Date().getTime()));
  24779. }
  24780. // if the method is get or there is json/xml data append the params to the url
  24781. if ((method == 'GET' || data) && params) {
  24782. url = Ext.urlAppend(url, params);
  24783. params = null;
  24784. }
  24785. // allow params to be forced into the url
  24786. if (urlParams) {
  24787. url = Ext.urlAppend(url, urlParams);
  24788. }
  24789. return {
  24790. url: url,
  24791. method: method,
  24792. data: data || params || null
  24793. };
  24794. },
  24795. /**
  24796. * Template method for overriding url
  24797. * @template
  24798. * @private
  24799. * @param {Object} options
  24800. * @param {String} url
  24801. * @return {String} The modified url
  24802. */
  24803. setupUrl: function(options, url){
  24804. var form = this.getForm(options);
  24805. if (form) {
  24806. url = url || form.action;
  24807. }
  24808. return url;
  24809. },
  24810. /**
  24811. * Template method for overriding params
  24812. * @template
  24813. * @private
  24814. * @param {Object} options
  24815. * @param {String} params
  24816. * @return {String} The modified params
  24817. */
  24818. setupParams: function(options, params) {
  24819. var form = this.getForm(options),
  24820. serializedForm;
  24821. if (form && !this.isFormUpload(options)) {
  24822. serializedForm = Ext.Element.serializeForm(form);
  24823. params = params ? (params + '&' + serializedForm) : serializedForm;
  24824. }
  24825. return params;
  24826. },
  24827. /**
  24828. * Template method for overriding method
  24829. * @template
  24830. * @private
  24831. * @param {Object} options
  24832. * @param {String} method
  24833. * @return {String} The modified method
  24834. */
  24835. setupMethod: function(options, method){
  24836. if (this.isFormUpload(options)) {
  24837. return 'POST';
  24838. }
  24839. return method;
  24840. },
  24841. /**
  24842. * Setup all the headers for the request
  24843. * @private
  24844. * @param {Object} xhr The xhr object
  24845. * @param {Object} options The options for the request
  24846. * @param {Object} data The data for the request
  24847. * @param {Object} params The params for the request
  24848. */
  24849. setupHeaders: function(xhr, options, data, params){
  24850. var me = this,
  24851. headers = Ext.apply({}, options.headers || {}, me.defaultHeaders || {}),
  24852. contentType = me.defaultPostHeader,
  24853. jsonData = options.jsonData,
  24854. xmlData = options.xmlData,
  24855. key,
  24856. header;
  24857. if (!headers['Content-Type'] && (data || params)) {
  24858. if (data) {
  24859. if (options.rawData) {
  24860. contentType = 'text/plain';
  24861. } else {
  24862. if (xmlData && Ext.isDefined(xmlData)) {
  24863. contentType = 'text/xml';
  24864. } else if (jsonData && Ext.isDefined(jsonData)) {
  24865. contentType = 'application/json';
  24866. }
  24867. }
  24868. }
  24869. headers['Content-Type'] = contentType;
  24870. }
  24871. if (me.useDefaultXhrHeader && !headers['X-Requested-With']) {
  24872. headers['X-Requested-With'] = me.defaultXhrHeader;
  24873. }
  24874. // set up all the request headers on the xhr object
  24875. try{
  24876. for (key in headers) {
  24877. if (headers.hasOwnProperty(key)) {
  24878. header = headers[key];
  24879. xhr.setRequestHeader(key, header);
  24880. }
  24881. }
  24882. } catch(e) {
  24883. me.fireEvent('exception', key, header);
  24884. }
  24885. return headers;
  24886. },
  24887. /**
  24888. * Creates the appropriate XHR transport for the browser.
  24889. * @private
  24890. */
  24891. getXhrInstance: (function(){
  24892. var options = [function(){
  24893. return new XMLHttpRequest();
  24894. }, function(){
  24895. return new ActiveXObject('MSXML2.XMLHTTP.3.0');
  24896. }, function(){
  24897. return new ActiveXObject('MSXML2.XMLHTTP');
  24898. }, function(){
  24899. return new ActiveXObject('Microsoft.XMLHTTP');
  24900. }], i = 0,
  24901. len = options.length,
  24902. xhr;
  24903. for(; i < len; ++i) {
  24904. try{
  24905. xhr = options[i];
  24906. xhr();
  24907. break;
  24908. }catch(e){}
  24909. }
  24910. return xhr;
  24911. })(),
  24912. /**
  24913. * Determines whether this object has a request outstanding.
  24914. * @param {Object} [request] Defaults to the last transaction
  24915. * @return {Boolean} True if there is an outstanding request.
  24916. */
  24917. isLoading : function(request) {
  24918. if (!request) {
  24919. request = this.getLatest();
  24920. }
  24921. if (!(request && request.xhr)) {
  24922. return false;
  24923. }
  24924. // if there is a connection and readyState is not 0 or 4
  24925. var state = request.xhr.readyState;
  24926. return !(state === 0 || state == 4);
  24927. },
  24928. /**
  24929. * Aborts an active request.
  24930. * @param {Object} [request] Defaults to the last request
  24931. */
  24932. abort : function(request) {
  24933. var me = this;
  24934. if (!request) {
  24935. request = me.getLatest();
  24936. }
  24937. if (request && me.isLoading(request)) {
  24938. /*
  24939. * Clear out the onreadystatechange here, this allows us
  24940. * greater control, the browser may/may not fire the function
  24941. * depending on a series of conditions.
  24942. */
  24943. request.xhr.onreadystatechange = null;
  24944. request.xhr.abort();
  24945. me.clearTimeout(request);
  24946. if (!request.timedout) {
  24947. request.aborted = true;
  24948. }
  24949. me.onComplete(request);
  24950. me.cleanup(request);
  24951. }
  24952. },
  24953. /**
  24954. * Aborts all active requests
  24955. */
  24956. abortAll: function(){
  24957. var requests = this.requests,
  24958. id;
  24959. for (id in requests) {
  24960. if (requests.hasOwnProperty(id)) {
  24961. this.abort(requests[id]);
  24962. }
  24963. }
  24964. },
  24965. /**
  24966. * Gets the most recent request
  24967. * @private
  24968. * @return {Object} The request. Null if there is no recent request
  24969. */
  24970. getLatest: function(){
  24971. var id = this.latestId,
  24972. request;
  24973. if (id) {
  24974. request = this.requests[id];
  24975. }
  24976. return request || null;
  24977. },
  24978. /**
  24979. * Fires when the state of the xhr changes
  24980. * @private
  24981. * @param {Object} request The request
  24982. */
  24983. onStateChange : function(request) {
  24984. if (request.xhr.readyState == 4) {
  24985. this.clearTimeout(request);
  24986. this.onComplete(request);
  24987. this.cleanup(request);
  24988. }
  24989. },
  24990. /**
  24991. * Clears t