PageRenderTime 108ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/ext-4.0.7/builds/ext-foundation-dev.js

https://bitbucket.org/srogerf/javascript
JavaScript | 8848 lines | 5299 code | 741 blank | 2808 comment | 557 complexity | 1d768b28a5617b02c3abcaf2ee7d8efa 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. if (!superclass) {
  149. Ext.Error.raise({
  150. sourceClass: 'Ext',
  151. sourceMethod: 'extend',
  152. msg: 'Attempting to extend from a class which has not been loaded on the page.'
  153. });
  154. }
  155. // We create a new temporary class
  156. var F = function() {},
  157. subclassProto, superclassProto = superclass.prototype;
  158. F.prototype = superclassProto;
  159. subclassProto = subclass.prototype = new F();
  160. subclassProto.constructor = subclass;
  161. subclass.superclass = superclassProto;
  162. if (superclassProto.constructor === objectConstructor) {
  163. superclassProto.constructor = superclass;
  164. }
  165. subclass.override = function(overrides) {
  166. Ext.override(subclass, overrides);
  167. };
  168. subclassProto.override = inlineOverrides;
  169. subclassProto.proto = subclassProto;
  170. subclass.override(overrides);
  171. subclass.extend = function(o) {
  172. return Ext.extend(subclass, o);
  173. };
  174. return subclass;
  175. };
  176. }(),
  177. /**
  178. * Proxy to {@link Ext.Base#override}. Please refer {@link Ext.Base#override} for further details.
  179. Ext.define('My.cool.Class', {
  180. sayHi: function() {
  181. alert('Hi!');
  182. }
  183. }
  184. Ext.override(My.cool.Class, {
  185. sayHi: function() {
  186. alert('About to say...');
  187. this.callOverridden();
  188. }
  189. });
  190. var cool = new My.cool.Class();
  191. cool.sayHi(); // alerts 'About to say...'
  192. // alerts 'Hi!'
  193. * Please note that `this.callOverridden()` only works if the class was previously
  194. * created with {@link Ext#define)
  195. *
  196. * @param {Object} cls The class to override
  197. * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
  198. * containing one or more methods.
  199. * @method override
  200. * @markdown
  201. */
  202. override: function(cls, overrides) {
  203. if (cls.prototype.$className) {
  204. return cls.override(overrides);
  205. }
  206. else {
  207. Ext.apply(cls.prototype, overrides);
  208. }
  209. }
  210. });
  211. // A full set of static methods to do type checking
  212. Ext.apply(Ext, {
  213. /**
  214. * Returns the given value itself if it's not empty, as described in {@link Ext#isEmpty}; returns the default
  215. * value (second argument) otherwise.
  216. *
  217. * @param {Object} value The value to test
  218. * @param {Object} defaultValue The value to return if the original value is empty
  219. * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
  220. * @return {Object} value, if non-empty, else defaultValue
  221. */
  222. valueFrom: function(value, defaultValue, allowBlank){
  223. return Ext.isEmpty(value, allowBlank) ? defaultValue : value;
  224. },
  225. /**
  226. * Returns the type of the given variable in string format. List of possible values are:
  227. *
  228. * - `undefined`: If the given value is `undefined`
  229. * - `null`: If the given value is `null`
  230. * - `string`: If the given value is a string
  231. * - `number`: If the given value is a number
  232. * - `boolean`: If the given value is a boolean value
  233. * - `date`: If the given value is a `Date` object
  234. * - `function`: If the given value is a function reference
  235. * - `object`: If the given value is an object
  236. * - `array`: If the given value is an array
  237. * - `regexp`: If the given value is a regular expression
  238. * - `element`: If the given value is a DOM Element
  239. * - `textnode`: If the given value is a DOM text node and contains something other than whitespace
  240. * - `whitespace`: If the given value is a DOM text node and contains only whitespace
  241. *
  242. * @param {Object} value
  243. * @return {String}
  244. * @markdown
  245. */
  246. typeOf: function(value) {
  247. if (value === null) {
  248. return 'null';
  249. }
  250. var type = typeof value;
  251. if (type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean') {
  252. return type;
  253. }
  254. var typeToString = toString.call(value);
  255. switch(typeToString) {
  256. case '[object Array]':
  257. return 'array';
  258. case '[object Date]':
  259. return 'date';
  260. case '[object Boolean]':
  261. return 'boolean';
  262. case '[object Number]':
  263. return 'number';
  264. case '[object RegExp]':
  265. return 'regexp';
  266. }
  267. if (type === 'function') {
  268. return 'function';
  269. }
  270. if (type === 'object') {
  271. if (value.nodeType !== undefined) {
  272. if (value.nodeType === 3) {
  273. return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace';
  274. }
  275. else {
  276. return 'element';
  277. }
  278. }
  279. return 'object';
  280. }
  281. Ext.Error.raise({
  282. sourceClass: 'Ext',
  283. sourceMethod: 'typeOf',
  284. msg: 'Failed to determine the type of the specified value "' + value + '". This is most likely a bug.'
  285. });
  286. },
  287. /**
  288. * Returns true if the passed value is empty, false otherwise. The value is deemed to be empty if it is either:
  289. *
  290. * - `null`
  291. * - `undefined`
  292. * - a zero-length array
  293. * - a zero-length string (Unless the `allowEmptyString` parameter is set to `true`)
  294. *
  295. * @param {Object} value The value to test
  296. * @param {Boolean} allowEmptyString (optional) true to allow empty strings (defaults to false)
  297. * @return {Boolean}
  298. * @markdown
  299. */
  300. isEmpty: function(value, allowEmptyString) {
  301. return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Ext.isArray(value) && value.length === 0);
  302. },
  303. /**
  304. * Returns true if the passed value is a JavaScript Array, false otherwise.
  305. *
  306. * @param {Object} target The target to test
  307. * @return {Boolean}
  308. * @method
  309. */
  310. isArray: ('isArray' in Array) ? Array.isArray : function(value) {
  311. return toString.call(value) === '[object Array]';
  312. },
  313. /**
  314. * Returns true if the passed value is a JavaScript Date object, false otherwise.
  315. * @param {Object} object The object to test
  316. * @return {Boolean}
  317. */
  318. isDate: function(value) {
  319. return toString.call(value) === '[object Date]';
  320. },
  321. /**
  322. * Returns true if the passed value is a JavaScript Object, false otherwise.
  323. * @param {Object} value The value to test
  324. * @return {Boolean}
  325. * @method
  326. */
  327. isObject: (toString.call(null) === '[object Object]') ?
  328. function(value) {
  329. // check ownerDocument here as well to exclude DOM nodes
  330. return value !== null && value !== undefined && toString.call(value) === '[object Object]' && value.ownerDocument === undefined;
  331. } :
  332. function(value) {
  333. return toString.call(value) === '[object Object]';
  334. },
  335. /**
  336. * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean.
  337. * @param {Object} value The value to test
  338. * @return {Boolean}
  339. */
  340. isPrimitive: function(value) {
  341. var type = typeof value;
  342. return type === 'string' || type === 'number' || type === 'boolean';
  343. },
  344. /**
  345. * Returns true if the passed value is a JavaScript Function, false otherwise.
  346. * @param {Object} value The value to test
  347. * @return {Boolean}
  348. * @method
  349. */
  350. isFunction:
  351. // Safari 3.x and 4.x returns 'function' for typeof <NodeList>, hence we need to fall back to using
  352. // Object.prorotype.toString (slower)
  353. (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') ? function(value) {
  354. return toString.call(value) === '[object Function]';
  355. } : function(value) {
  356. return typeof value === 'function';
  357. },
  358. /**
  359. * Returns true if the passed value is a number. Returns false for non-finite numbers.
  360. * @param {Object} value The value to test
  361. * @return {Boolean}
  362. */
  363. isNumber: function(value) {
  364. return typeof value === 'number' && isFinite(value);
  365. },
  366. /**
  367. * Validates that a value is numeric.
  368. * @param {Object} value Examples: 1, '1', '2.34'
  369. * @return {Boolean} True if numeric, false otherwise
  370. */
  371. isNumeric: function(value) {
  372. return !isNaN(parseFloat(value)) && isFinite(value);
  373. },
  374. /**
  375. * Returns true if the passed value is a string.
  376. * @param {Object} value The value to test
  377. * @return {Boolean}
  378. */
  379. isString: function(value) {
  380. return typeof value === 'string';
  381. },
  382. /**
  383. * Returns true if the passed value is a boolean.
  384. *
  385. * @param {Object} value The value to test
  386. * @return {Boolean}
  387. */
  388. isBoolean: function(value) {
  389. return typeof value === 'boolean';
  390. },
  391. /**
  392. * Returns true if the passed value is an HTMLElement
  393. * @param {Object} value The value to test
  394. * @return {Boolean}
  395. */
  396. isElement: function(value) {
  397. return value ? value.nodeType === 1 : false;
  398. },
  399. /**
  400. * Returns true if the passed value is a TextNode
  401. * @param {Object} value The value to test
  402. * @return {Boolean}
  403. */
  404. isTextNode: function(value) {
  405. return value ? value.nodeName === "#text" : false;
  406. },
  407. /**
  408. * Returns true if the passed value is defined.
  409. * @param {Object} value The value to test
  410. * @return {Boolean}
  411. */
  412. isDefined: function(value) {
  413. return typeof value !== 'undefined';
  414. },
  415. /**
  416. * Returns true if the passed value is iterable, false otherwise
  417. * @param {Object} value The value to test
  418. * @return {Boolean}
  419. */
  420. isIterable: function(value) {
  421. return (value && typeof value !== 'string') ? value.length !== undefined : false;
  422. }
  423. });
  424. Ext.apply(Ext, {
  425. /**
  426. * Clone almost any type of variable including array, object, DOM nodes and Date without keeping the old reference
  427. * @param {Object} item The variable to clone
  428. * @return {Object} clone
  429. */
  430. clone: function(item) {
  431. if (item === null || item === undefined) {
  432. return item;
  433. }
  434. // DOM nodes
  435. // TODO proxy this to Ext.Element.clone to handle automatic id attribute changing
  436. // recursively
  437. if (item.nodeType && item.cloneNode) {
  438. return item.cloneNode(true);
  439. }
  440. var type = toString.call(item);
  441. // Date
  442. if (type === '[object Date]') {
  443. return new Date(item.getTime());
  444. }
  445. var i, j, k, clone, key;
  446. // Array
  447. if (type === '[object Array]') {
  448. i = item.length;
  449. clone = [];
  450. while (i--) {
  451. clone[i] = Ext.clone(item[i]);
  452. }
  453. }
  454. // Object
  455. else if (type === '[object Object]' && item.constructor === Object) {
  456. clone = {};
  457. for (key in item) {
  458. clone[key] = Ext.clone(item[key]);
  459. }
  460. if (enumerables) {
  461. for (j = enumerables.length; j--;) {
  462. k = enumerables[j];
  463. clone[k] = item[k];
  464. }
  465. }
  466. }
  467. return clone || item;
  468. },
  469. /**
  470. * @private
  471. * Generate a unique reference of Ext in the global scope, useful for sandboxing
  472. */
  473. getUniqueGlobalNamespace: function() {
  474. var uniqueGlobalNamespace = this.uniqueGlobalNamespace;
  475. if (uniqueGlobalNamespace === undefined) {
  476. var i = 0;
  477. do {
  478. uniqueGlobalNamespace = 'ExtBox' + (++i);
  479. } while (Ext.global[uniqueGlobalNamespace] !== undefined);
  480. Ext.global[uniqueGlobalNamespace] = Ext;
  481. this.uniqueGlobalNamespace = uniqueGlobalNamespace;
  482. }
  483. return uniqueGlobalNamespace;
  484. },
  485. /**
  486. * @private
  487. */
  488. functionFactory: function() {
  489. var args = Array.prototype.slice.call(arguments);
  490. if (args.length > 0) {
  491. args[args.length - 1] = 'var Ext=window.' + this.getUniqueGlobalNamespace() + ';' +
  492. args[args.length - 1];
  493. }
  494. return Function.prototype.constructor.apply(Function.prototype, args);
  495. }
  496. });
  497. /**
  498. * Old alias to {@link Ext#typeOf}
  499. * @deprecated 4.0.0 Use {@link Ext#typeOf} instead
  500. * @method
  501. * @alias Ext#typeOf
  502. */
  503. Ext.type = Ext.typeOf;
  504. })();
  505. /**
  506. * @author Jacky Nguyen <jacky@sencha.com>
  507. * @docauthor Jacky Nguyen <jacky@sencha.com>
  508. * @class Ext.Version
  509. *
  510. * A utility class that wrap around a string version number and provide convenient
  511. * method to perform comparison. See also: {@link Ext.Version#compare compare}. Example:
  512. var version = new Ext.Version('1.0.2beta');
  513. console.log("Version is " + version); // Version is 1.0.2beta
  514. console.log(version.getMajor()); // 1
  515. console.log(version.getMinor()); // 0
  516. console.log(version.getPatch()); // 2
  517. console.log(version.getBuild()); // 0
  518. console.log(version.getRelease()); // beta
  519. console.log(version.isGreaterThan('1.0.1')); // True
  520. console.log(version.isGreaterThan('1.0.2alpha')); // True
  521. console.log(version.isGreaterThan('1.0.2RC')); // False
  522. console.log(version.isGreaterThan('1.0.2')); // False
  523. console.log(version.isLessThan('1.0.2')); // True
  524. console.log(version.match(1.0)); // True
  525. console.log(version.match('1.0.2')); // True
  526. * @markdown
  527. */
  528. (function() {
  529. // Current core version
  530. var version = '4.0.7', Version;
  531. Ext.Version = Version = Ext.extend(Object, {
  532. /**
  533. * @param {String/Number} version The version number in the follow standard format: major[.minor[.patch[.build[release]]]]
  534. * Examples: 1.0 or 1.2.3beta or 1.2.3.4RC
  535. * @return {Ext.Version} this
  536. */
  537. constructor: function(version) {
  538. var parts, releaseStartIndex;
  539. if (version instanceof Version) {
  540. return version;
  541. }
  542. this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, '');
  543. releaseStartIndex = this.version.search(/([^\d\.])/);
  544. if (releaseStartIndex !== -1) {
  545. this.release = this.version.substr(releaseStartIndex, version.length);
  546. this.shortVersion = this.version.substr(0, releaseStartIndex);
  547. }
  548. this.shortVersion = this.shortVersion.replace(/[^\d]/g, '');
  549. parts = this.version.split('.');
  550. this.major = parseInt(parts.shift() || 0, 10);
  551. this.minor = parseInt(parts.shift() || 0, 10);
  552. this.patch = parseInt(parts.shift() || 0, 10);
  553. this.build = parseInt(parts.shift() || 0, 10);
  554. return this;
  555. },
  556. /**
  557. * Override the native toString method
  558. * @private
  559. * @return {String} version
  560. */
  561. toString: function() {
  562. return this.version;
  563. },
  564. /**
  565. * Override the native valueOf method
  566. * @private
  567. * @return {String} version
  568. */
  569. valueOf: function() {
  570. return this.version;
  571. },
  572. /**
  573. * Returns the major component value
  574. * @return {Number} major
  575. */
  576. getMajor: function() {
  577. return this.major || 0;
  578. },
  579. /**
  580. * Returns the minor component value
  581. * @return {Number} minor
  582. */
  583. getMinor: function() {
  584. return this.minor || 0;
  585. },
  586. /**
  587. * Returns the patch component value
  588. * @return {Number} patch
  589. */
  590. getPatch: function() {
  591. return this.patch || 0;
  592. },
  593. /**
  594. * Returns the build component value
  595. * @return {Number} build
  596. */
  597. getBuild: function() {
  598. return this.build || 0;
  599. },
  600. /**
  601. * Returns the release component value
  602. * @return {Number} release
  603. */
  604. getRelease: function() {
  605. return this.release || '';
  606. },
  607. /**
  608. * Returns whether this version if greater than the supplied argument
  609. * @param {String/Number} target The version to compare with
  610. * @return {Boolean} True if this version if greater than the target, false otherwise
  611. */
  612. isGreaterThan: function(target) {
  613. return Version.compare(this.version, target) === 1;
  614. },
  615. /**
  616. * Returns whether this version if smaller than the supplied argument
  617. * @param {String/Number} target The version to compare with
  618. * @return {Boolean} True if this version if smaller than the target, false otherwise
  619. */
  620. isLessThan: function(target) {
  621. return Version.compare(this.version, target) === -1;
  622. },
  623. /**
  624. * Returns whether this version equals to the supplied argument
  625. * @param {String/Number} target The version to compare with
  626. * @return {Boolean} True if this version equals to the target, false otherwise
  627. */
  628. equals: function(target) {
  629. return Version.compare(this.version, target) === 0;
  630. },
  631. /**
  632. * Returns whether this version matches the supplied argument. Example:
  633. * <pre><code>
  634. * var version = new Ext.Version('1.0.2beta');
  635. * console.log(version.match(1)); // True
  636. * console.log(version.match(1.0)); // True
  637. * console.log(version.match('1.0.2')); // True
  638. * console.log(version.match('1.0.2RC')); // False
  639. * </code></pre>
  640. * @param {String/Number} target The version to compare with
  641. * @return {Boolean} True if this version matches the target, false otherwise
  642. */
  643. match: function(target) {
  644. target = String(target);
  645. return this.version.substr(0, target.length) === target;
  646. },
  647. /**
  648. * Returns this format: [major, minor, patch, build, release]. Useful for comparison
  649. * @return {Number[]}
  650. */
  651. toArray: function() {
  652. return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()];
  653. },
  654. /**
  655. * Returns shortVersion version without dots and release
  656. * @return {String}
  657. */
  658. getShortVersion: function() {
  659. return this.shortVersion;
  660. }
  661. });
  662. Ext.apply(Version, {
  663. // @private
  664. releaseValueMap: {
  665. 'dev': -6,
  666. 'alpha': -5,
  667. 'a': -5,
  668. 'beta': -4,
  669. 'b': -4,
  670. 'rc': -3,
  671. '#': -2,
  672. 'p': -1,
  673. 'pl': -1
  674. },
  675. /**
  676. * Converts a version component to a comparable value
  677. *
  678. * @static
  679. * @param {Object} value The value to convert
  680. * @return {Object}
  681. */
  682. getComponentValue: function(value) {
  683. return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10));
  684. },
  685. /**
  686. * Compare 2 specified versions, starting from left to right. If a part contains special version strings,
  687. * they are handled in the following order:
  688. * 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else'
  689. *
  690. * @static
  691. * @param {String} current The current version to compare to
  692. * @param {String} target The target version to compare to
  693. * @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent
  694. */
  695. compare: function(current, target) {
  696. var currentValue, targetValue, i;
  697. current = new Version(current).toArray();
  698. target = new Version(target).toArray();
  699. for (i = 0; i < Math.max(current.length, target.length); i++) {
  700. currentValue = this.getComponentValue(current[i]);
  701. targetValue = this.getComponentValue(target[i]);
  702. if (currentValue < targetValue) {
  703. return -1;
  704. } else if (currentValue > targetValue) {
  705. return 1;
  706. }
  707. }
  708. return 0;
  709. }
  710. });
  711. Ext.apply(Ext, {
  712. /**
  713. * @private
  714. */
  715. versions: {},
  716. /**
  717. * @private
  718. */
  719. lastRegisteredVersion: null,
  720. /**
  721. * Set version number for the given package name.
  722. *
  723. * @param {String} packageName The package name, for example: 'core', 'touch', 'extjs'
  724. * @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev'
  725. * @return {Ext}
  726. */
  727. setVersion: function(packageName, version) {
  728. Ext.versions[packageName] = new Version(version);
  729. Ext.lastRegisteredVersion = Ext.versions[packageName];
  730. return this;
  731. },
  732. /**
  733. * Get the version number of the supplied package name; will return the last registered version
  734. * (last Ext.setVersion call) if there's no package name given.
  735. *
  736. * @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs'
  737. * @return {Ext.Version} The version
  738. */
  739. getVersion: function(packageName) {
  740. if (packageName === undefined) {
  741. return Ext.lastRegisteredVersion;
  742. }
  743. return Ext.versions[packageName];
  744. },
  745. /**
  746. * Create a closure for deprecated code.
  747. *
  748. // This means Ext.oldMethod is only supported in 4.0.0beta and older.
  749. // If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC',
  750. // the closure will not be invoked
  751. Ext.deprecate('extjs', '4.0.0beta', function() {
  752. Ext.oldMethod = Ext.newMethod;
  753. ...
  754. });
  755. * @param {String} packageName The package name
  756. * @param {String} since The last version before it's deprecated
  757. * @param {Function} closure The callback function to be executed with the specified version is less than the current version
  758. * @param {Object} scope The execution scope (<tt>this</tt>) if the closure
  759. * @markdown
  760. */
  761. deprecate: function(packageName, since, closure, scope) {
  762. if (Version.compare(Ext.getVersion(packageName), since) < 1) {
  763. closure.call(scope);
  764. }
  765. }
  766. }); // End Versioning
  767. Ext.setVersion('core', version);
  768. })();
  769. /**
  770. * @class Ext.String
  771. *
  772. * A collection of useful static methods to deal with strings
  773. * @singleton
  774. */
  775. Ext.String = {
  776. 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,
  777. escapeRe: /('|\\)/g,
  778. formatRe: /\{(\d+)\}/g,
  779. escapeRegexRe: /([-.*+?^${}()|[\]\/\\])/g,
  780. /**
  781. * Convert certain characters (&, <, >, and ") to their HTML character equivalents for literal display in web pages.
  782. * @param {String} value The string to encode
  783. * @return {String} The encoded text
  784. * @method
  785. */
  786. htmlEncode: (function() {
  787. var entities = {
  788. '&': '&amp;',
  789. '>': '&gt;',
  790. '<': '&lt;',
  791. '"': '&quot;'
  792. }, keys = [], p, regex;
  793. for (p in entities) {
  794. keys.push(p);
  795. }
  796. regex = new RegExp('(' + keys.join('|') + ')', 'g');
  797. return function(value) {
  798. return (!value) ? value : String(value).replace(regex, function(match, capture) {
  799. return entities[capture];
  800. });
  801. };
  802. })(),
  803. /**
  804. * Convert certain characters (&, <, >, and ") from their HTML character equivalents.
  805. * @param {String} value The string to decode
  806. * @return {String} The decoded text
  807. * @method
  808. */
  809. htmlDecode: (function() {
  810. var entities = {
  811. '&amp;': '&',
  812. '&gt;': '>',
  813. '&lt;': '<',
  814. '&quot;': '"'
  815. }, keys = [], p, regex;
  816. for (p in entities) {
  817. keys.push(p);
  818. }
  819. regex = new RegExp('(' + keys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
  820. return function(value) {
  821. return (!value) ? value : String(value).replace(regex, function(match, capture) {
  822. if (capture in entities) {
  823. return entities[capture];
  824. } else {
  825. return String.fromCharCode(parseInt(capture.substr(2), 10));
  826. }
  827. });
  828. };
  829. })(),
  830. /**
  831. * Appends content to the query string of a URL, handling logic for whether to place
  832. * a question mark or ampersand.
  833. * @param {String} url The URL to append to.
  834. * @param {String} string The content to append to the URL.
  835. * @return (String) The resulting URL
  836. */
  837. urlAppend : function(url, string) {
  838. if (!Ext.isEmpty(string)) {
  839. return url + (url.indexOf('?') === -1 ? '?' : '&') + string;
  840. }
  841. return url;
  842. },
  843. /**
  844. * Trims whitespace from either end of a string, leaving spaces within the string intact. Example:
  845. * @example
  846. var s = ' foo bar ';
  847. alert('-' + s + '-'); //alerts "- foo bar -"
  848. alert('-' + Ext.String.trim(s) + '-'); //alerts "-foo bar-"
  849. * @param {String} string The string to escape
  850. * @return {String} The trimmed string
  851. */
  852. trim: function(string) {
  853. return string.replace(Ext.String.trimRegex, "");
  854. },
  855. /**
  856. * Capitalize the given string
  857. * @param {String} string
  858. * @return {String}
  859. */
  860. capitalize: function(string) {
  861. return string.charAt(0).toUpperCase() + string.substr(1);
  862. },
  863. /**
  864. * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
  865. * @param {String} value The string to truncate
  866. * @param {Number} length The maximum length to allow before truncating
  867. * @param {Boolean} word True to try to find a common word break
  868. * @return {String} The converted text
  869. */
  870. ellipsis: function(value, len, word) {
  871. if (value && value.length > len) {
  872. if (word) {
  873. var vs = value.substr(0, len - 2),
  874. index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
  875. if (index !== -1 && index >= (len - 15)) {
  876. return vs.substr(0, index) + "...";
  877. }
  878. }
  879. return value.substr(0, len - 3) + "...";
  880. }
  881. return value;
  882. },
  883. /**
  884. * Escapes the passed string for use in a regular expression
  885. * @param {String} string
  886. * @return {String}
  887. */
  888. escapeRegex: function(string) {
  889. return string.replace(Ext.String.escapeRegexRe, "\\$1");
  890. },
  891. /**
  892. * Escapes the passed string for ' and \
  893. * @param {String} string The string to escape
  894. * @return {String} The escaped string
  895. */
  896. escape: function(string) {
  897. return string.replace(Ext.String.escapeRe, "\\$1");
  898. },
  899. /**
  900. * Utility function that allows you to easily switch a string between two alternating values. The passed value
  901. * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
  902. * they are already different, the first value passed in is returned. Note that this method returns the new value
  903. * but does not change the current string.
  904. * <pre><code>
  905. // alternate sort directions
  906. sort = Ext.String.toggle(sort, 'ASC', 'DESC');
  907. // instead of conditional logic:
  908. sort = (sort == 'ASC' ? 'DESC' : 'ASC');
  909. </code></pre>
  910. * @param {String} string The current string
  911. * @param {String} value The value to compare to the current string
  912. * @param {String} other The new value to use if the string already equals the first value passed in
  913. * @return {String} The new value
  914. */
  915. toggle: function(string, value, other) {
  916. return string === value ? other : value;
  917. },
  918. /**
  919. * Pads the left side of a string with a specified character. This is especially useful
  920. * for normalizing number and date strings. Example usage:
  921. *
  922. * <pre><code>
  923. var s = Ext.String.leftPad('123', 5, '0');
  924. // s now contains the string: '00123'
  925. </code></pre>
  926. * @param {String} string The original string
  927. * @param {Number} size The total length of the output string
  928. * @param {String} character (optional) The character with which to pad the original string (defaults to empty string " ")
  929. * @return {String} The padded string
  930. */
  931. leftPad: function(string, size, character) {
  932. var result = String(string);
  933. character = character || " ";
  934. while (result.length < size) {
  935. result = character + result;
  936. }
  937. return result;
  938. },
  939. /**
  940. * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
  941. * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
  942. * <pre><code>
  943. var cls = 'my-class', text = 'Some text';
  944. var s = Ext.String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text);
  945. // s now contains the string: '&lt;div class="my-class">Some text&lt;/div>'
  946. </code></pre>
  947. * @param {String} string The tokenized string to be formatted
  948. * @param {String} value1 The value to replace token {0}
  949. * @param {String} value2 Etc...
  950. * @return {String} The formatted string
  951. */
  952. format: function(format) {
  953. var args = Ext.Array.toArray(arguments, 1);
  954. return format.replace(Ext.String.formatRe, function(m, i) {
  955. return args[i];
  956. });
  957. },
  958. /**
  959. * Returns a string with a specified number of repititions a given string pattern.
  960. * The pattern be separated by a different string.
  961. *
  962. * var s = Ext.String.repeat('---', 4); // = '------------'
  963. * var t = Ext.String.repeat('--', 3, '/'); // = '--/--/--'
  964. *
  965. * @param {String} pattern The pattern to repeat.
  966. * @param {Number} count The number of times to repeat the pattern (may be 0).
  967. * @param {String} sep An option string to separate each pattern.
  968. */
  969. repeat: function(pattern, count, sep) {
  970. for (var buf = [], i = count; i--; ) {
  971. buf.push(pattern);
  972. }
  973. return buf.join(sep || '');
  974. }
  975. };
  976. /**
  977. * @class Ext.Number
  978. *
  979. * A collection of useful static methods to deal with numbers
  980. * @singleton
  981. */
  982. (function() {
  983. var isToFixedBroken = (0.9).toFixed() !== '1';
  984. Ext.Number = {
  985. /**
  986. * Checks whether or not the passed number is within a desired range. If the number is already within the
  987. * range it is returned, otherwise the min or max value is returned depending on which side of the range is
  988. * exceeded. Note that this method returns the constrained value but does not change the current number.
  989. * @param {Number} number The number to check
  990. * @param {Number} min The minimum number in the range
  991. * @param {Number} max The maximum number in the range
  992. * @return {Number} The constrained value if outside the range, otherwise the current value
  993. */
  994. constrain: function(number, min, max) {
  995. number = parseFloat(number);
  996. if (!isNaN(min)) {
  997. number = Math.max(number, min);
  998. }
  999. if (!isNaN(max)) {
  1000. number = Math.min(number, max);
  1001. }
  1002. return number;
  1003. },
  1004. /**
  1005. * Snaps the passed number between stopping points based upon a passed increment value.
  1006. * @param {Number} value The unsnapped value.
  1007. * @param {Number} increment The increment by which the value must move.
  1008. * @param {Number} minValue The minimum value to which the returned value must be constrained. Overrides the increment..
  1009. * @param {Number} maxValue The maximum value to which the returned value must be constrained. Overrides the increment..
  1010. * @return {Number} The value of the nearest snap target.
  1011. */
  1012. snap : function(value, increment, minValue, maxValue) {
  1013. var newValue = value,
  1014. m;
  1015. if (!(increment && value)) {
  1016. return value;
  1017. }
  1018. m = value % increment;
  1019. if (m !== 0) {
  1020. newValue -= m;
  1021. if (m * 2 >= increment) {
  1022. newValue += increment;
  1023. } else if (m * 2 < -increment) {
  1024. newValue -= increment;
  1025. }
  1026. }
  1027. return Ext.Number.constrain(newValue, minValue, maxValue);
  1028. },
  1029. /**
  1030. * Formats a number using fixed-point notation
  1031. * @param {Number} value The number to format
  1032. * @param {Number} precision The number of digits to show after the decimal point
  1033. */
  1034. toFixed: function(value, precision) {
  1035. if (isToFixedBroken) {
  1036. precision = precision || 0;
  1037. var pow = Math.pow(10, precision);
  1038. return (Math.round(value * pow) / pow).toFixed(precision);
  1039. }
  1040. return value.toFixed(precision);
  1041. },
  1042. /**
  1043. * Validate that a value is numeric and convert it to a number if necessary. Returns the specified default value if
  1044. * it is not.
  1045. Ext.Number.from('1.23', 1); // returns 1.23
  1046. Ext.Number.from('abc', 1); // returns 1
  1047. * @param {Object} value
  1048. * @param {Number} defaultValue The value to return if the original value is non-numeric
  1049. * @return {Number} value, if numeric, defaultValue otherwise
  1050. */
  1051. from: function(value, defaultValue) {
  1052. if (isFinite(value)) {
  1053. value = parseFloat(value);
  1054. }
  1055. return !isNaN(value) ? value : defaultValue;
  1056. }
  1057. };
  1058. })();
  1059. /**
  1060. * @deprecated 4.0.0 Please use {@link Ext.Number#from} instead.
  1061. * @member Ext
  1062. * @method num
  1063. * @alias Ext.Number#from
  1064. */
  1065. Ext.num = function() {
  1066. return Ext.Number.from.apply(this, arguments);
  1067. };
  1068. /**
  1069. * @class Ext.Array
  1070. * @singleton
  1071. * @author Jacky Nguyen <jacky@sencha.com>
  1072. * @docauthor Jacky Nguyen <jacky@sencha.com>
  1073. *
  1074. * A set of useful static methods to deal with arrays; provide missing methods for older browsers.
  1075. */
  1076. (function() {
  1077. var arrayPrototype = Array.prototype,
  1078. slice = arrayPrototype.slice,
  1079. supportsSplice = function () {
  1080. var array = [],
  1081. lengthBefore,
  1082. j = 20;
  1083. if (!array.splice) {
  1084. return false;
  1085. }
  1086. // This detects a bug in IE8 splice method:
  1087. // see http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/6e946d03-e09f-4b22-a4dd-cd5e276bf05a/
  1088. while (j--) {
  1089. array.push("A");
  1090. }
  1091. 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");
  1092. lengthBefore = array.length; //41
  1093. array.splice(13, 0, "XXX"); // add one element
  1094. if (lengthBefore+1 != array.length) {
  1095. return false;
  1096. }
  1097. // end IE8 bug
  1098. return true;
  1099. }(),
  1100. supportsForEach = 'forEach' in arrayPrototype,
  1101. supportsMap = 'map' in arrayPrototype,
  1102. supportsIndexOf = 'indexOf' in arrayPrototype,
  1103. supportsEvery = 'every' in arrayPrototype,
  1104. supportsSome = 'some' in arrayPrototype,
  1105. supportsFilter = 'filter' in arrayPrototype,
  1106. supportsSort = function() {
  1107. var a = [1,2,3,4,5].sort(function(){ return 0; });
  1108. return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
  1109. }(),
  1110. supportsSliceOnNodeList = true,
  1111. ExtArray;
  1112. try {
  1113. // IE 6 - 8 will throw an error when using Array.prototype.slice on NodeList
  1114. if (typeof document !== 'undefined') {
  1115. slice.call(document.getElementsByTagName('body'));
  1116. }
  1117. } catch (e) {
  1118. supportsSliceOnNodeList = false;
  1119. }
  1120. function fixArrayIndex (array, index) {
  1121. return (index < 0) ? Math.max(0, array.length + index)
  1122. : Math.min(array.length, index);
  1123. }
  1124. /*
  1125. Does the same work as splice, but with a slightly more convenient signature. The splice
  1126. method has bugs in IE8, so this is the implementation we use on that platform.
  1127. The rippling of items in the array can be tricky. Consider two use cases:
  1128. index=2
  1129. removeCount=2
  1130. /=====\
  1131. +---+---+---+---+---+---+---+---+
  1132. | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  1133. +---+---+---+---+---+---+---+---+
  1134. / \/ \/ \/ \
  1135. / /\ /\ /\ \
  1136. / / \/ \/ \ +--------------------------+
  1137. / / /\ /\ +--------------------------+ \
  1138. / / / \/ +--------------------------+ \ \
  1139. / / / /+--------------------------+ \ \ \
  1140. / / / / \ \ \ \
  1141. v v v v v v v v
  1142. +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
  1143. | 0 | 1 | 4 | 5 | 6 | 7 | | 0 | 1 | a | b | c | 4 | 5 | 6 | 7 |
  1144. +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
  1145. A B \=========/
  1146. insert=[a,b,c]
  1147. In case A, it is obvious that copying of [4,5,6,7] must be left-to-right so
  1148. that we don't end up with [0,1,6,7,6,7]. In case B, we have the opposite; we
  1149. must go right-to-left or else we would end up with [0,1,a,b,c,4,4,4,4].
  1150. */
  1151. function replaceSim (array, index, removeCount, insert) {
  1152. var add = insert ? insert.length : 0,
  1153. length = array.length,
  1154. pos = fixArrayIndex(array, index);
  1155. // we try to use Array.push when we can for efficiency...
  1156. if (pos === length) {
  1157. if (add) {
  1158. array.push.apply(array, insert);
  1159. }
  1160. } else {
  1161. var remove = Math.min(removeCount, length - pos),
  1162. tailOldPos = pos + remove,
  1163. tailNewPos = tailOldPos + add - remove,
  1164. tailCount = length - tailOldPos,
  1165. lengthAfterRemove = length - remove,
  1166. i;
  1167. if (tailNewPos < tailOldPos) { // case A
  1168. for (i = 0; i < tailCount; ++i) {
  1169. array[tailNewPos+i] = array[tailOldPos+i];
  1170. }
  1171. } else if (tailNewPos > tailOldPos) { // case B
  1172. for (i = tailCount; i--; ) {
  1173. array[tailNewPos+i] = array[tailOldPos+i];
  1174. }
  1175. } // else, add == remove (nothing to do)
  1176. if (add && pos === lengthAfterRemove) {
  1177. array.length = lengthAfterRemove; // truncate array
  1178. array.push.apply(array, insert);
  1179. } else {
  1180. array.length = lengthAfterRemove + add; // reserves space
  1181. for (i = 0; i < add; ++i) {
  1182. array[pos+i] = insert[i];
  1183. }
  1184. }
  1185. }
  1186. return array;
  1187. }
  1188. function replaceNative (array, index, removeCount, insert) {
  1189. if (insert && insert.length) {
  1190. if (index < array.length) {
  1191. array.splice.apply(array, [index, removeCount].concat(insert));
  1192. } else {
  1193. array.push.apply(array, insert);
  1194. }
  1195. } else {
  1196. array.splice(index, removeCount);
  1197. }
  1198. return array;
  1199. }
  1200. function eraseSim (array, index, removeCount) {
  1201. return replaceSim(array, index, removeCount);
  1202. }
  1203. function eraseNative (array, index, removeCount) {
  1204. array.splice(index, removeCount);
  1205. return array;
  1206. }
  1207. function spliceSim (array, index, removeCount) {
  1208. var pos = fixArrayIndex(array, index),
  1209. removed = array.slice(index, fixArrayIndex(array, pos+removeCount));
  1210. if (arguments.length < 4) {
  1211. replaceSim(array, pos, removeCount);
  1212. } else {
  1213. replaceSim(array, pos, removeCount, slice.call(arguments, 3));
  1214. }
  1215. return removed;
  1216. }
  1217. function spliceNative (array) {
  1218. return array.splice.apply(array, slice.call(arguments, 1));
  1219. }
  1220. var erase = supportsSplice ? eraseNative : eraseSim,
  1221. replace = supportsSplice ? replaceNative : replaceSim,
  1222. splice = supportsSplice ? spliceNative : spliceSim;
  1223. // NOTE: from here on, use erase, replace or splice (not native methods)...
  1224. ExtArray = Ext.Array = {
  1225. /**
  1226. * Iterates an array or an iterable value and invoke the given callback function for each item.
  1227. *
  1228. * var countries = ['Vietnam', 'Singapore', 'United States', 'Russia'];
  1229. *
  1230. * Ext.Array.each(countries, function(name, index, countriesItSelf) {
  1231. * console.log(name);
  1232. * });
  1233. *
  1234. * var sum = function() {
  1235. * var sum = 0;
  1236. *
  1237. * Ext.Array.each(arguments, function(value) {
  1238. * sum += value;
  1239. * });
  1240. *
  1241. * return sum;
  1242. * };
  1243. *
  1244. * sum(1, 2, 3); // returns 6
  1245. *
  1246. * The iteration can be stopped by returning false in the function callback.
  1247. *
  1248. * Ext.Array.each(countries, function(name, index, countriesItSelf) {
  1249. * if (name === 'Singapore') {
  1250. * return false; // break here
  1251. * }
  1252. * });
  1253. *
  1254. * {@link Ext#each Ext.each} is alias for {@link Ext.Array#each Ext.Array.each}
  1255. *
  1256. * @param {Array/NodeList/Object} iterable The value to be iterated. If this
  1257. * argument is not iterable, the callback function is called once.
  1258. * @param {Function} fn The callback function. If it returns false, the iteration stops and this method returns
  1259. * the current `index`.
  1260. * @param {Object} fn.item The item at the current `index` in the passed `array`
  1261. * @param {Number} fn.index The current `index` within the `array`
  1262. * @param {Array} fn.allItems The `array` itself which was passed as the first argument
  1263. * @param {Boolean} fn.return Return false to stop iteration.
  1264. * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
  1265. * @param {Boolean} reverse (Optional) Reverse the iteration order (loop from the end to the beginning)
  1266. * Defaults false
  1267. * @return {Boolean} See description for the `fn` parameter.
  1268. */
  1269. each: function(array, fn, scope, reverse) {
  1270. array = ExtArray.from(array);
  1271. var i,
  1272. ln = array.length;
  1273. if (reverse !== true) {
  1274. for (i = 0; i < ln; i++) {
  1275. if (fn.call(scope || array[i], array[i], i, array) === false) {
  1276. return i;
  1277. }
  1278. }
  1279. }
  1280. else {
  1281. for (i = ln - 1; i > -1; i--) {
  1282. if (fn.call(scope || array[i], array[i], i, array) === false) {
  1283. return i;
  1284. }
  1285. }
  1286. }
  1287. return true;
  1288. },
  1289. /**
  1290. * Iterates an array and invoke the given callback function for each item. Note that this will simply
  1291. * delegate to the native Array.prototype.forEach method if supported. It doesn't support stopping the
  1292. * iteration by returning false in the callback function like {@link Ext.Array#each}. However, performance
  1293. * could be much better in modern browsers comparing with {@link Ext.Array#each}
  1294. *
  1295. * @param {Array} array The array to iterate
  1296. * @param {Function} fn The callback function.
  1297. * @param {Object} fn.item The item at the current `index` in the passed `array`
  1298. * @param {Number} fn.index The current `index` within the `array`
  1299. * @param {Array} fn.allItems The `array` itself which was passed as the first argument
  1300. * @param {Object} scope (Optional) The execution scope (`this`) in which the specified function is executed.
  1301. */
  1302. forEach: function(array, fn, scope) {
  1303. if (supportsForEach) {
  1304. return array.forEach(fn, scope);
  1305. }
  1306. var i = 0,
  1307. ln = array.length;
  1308. for (; i < ln; i++) {
  1309. fn.call(scope, array[i], i, array);
  1310. }
  1311. },
  1312. /**
  1313. * Get the index of the provided `item` in the given `array`, a supplement for the
  1314. * missing arrayPrototype.indexOf in Internet Explorer.
  1315. *
  1316. * @param {Array} array The array to check
  1317. * @param {Object} item The item to look for
  1318. * @param {Number} from (Optional) The index at which to begin the search
  1319. * @return {Number} The index of item in the array (or -1 if it is not found)
  1320. */
  1321. indexOf: function(array, item, from) {
  1322. if (supportsIndexOf) {
  1323. return array.indexOf(item, from);
  1324. }
  1325. var i, length = array.length;
  1326. for (i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++) {
  1327. if (array[i] === item) {
  1328. return i;
  1329. }
  1330. }
  1331. return -1;
  1332. },
  1333. /**
  1334. * Checks whether or not the given `array` contains the specified `item`
  1335. *
  1336. * @param {Array} array The array to check
  1337. * @param {Object} item The item to look for
  1338. * @return {Boolean} True if the array contains the item, false otherwise
  1339. */
  1340. contains: function(array, item) {
  1341. if (supportsIndexOf) {
  1342. return array.indexOf(item) !== -1;
  1343. }
  1344. var i, ln;
  1345. for (i = 0, ln = array.length; i < ln; i++) {
  1346. if (array[i] === item) {
  1347. return true;
  1348. }
  1349. }
  1350. return false;
  1351. },
  1352. /**
  1353. * Converts any iterable (numeric indices and a length property) into a true array.
  1354. *
  1355. * function test() {
  1356. * var args = Ext.Array.toArray(arguments),
  1357. * fromSecondToLastArgs = Ext.Array.toArray(arguments, 1);
  1358. *
  1359. * alert(args.join(' '));
  1360. * alert(fromSecondToLastArgs.join(' '));
  1361. * }
  1362. *
  1363. * test('just', 'testing', 'here'); // alerts 'just testing here';
  1364. * // alerts 'testing here';
  1365. *
  1366. * Ext.Array.toArray(document.getElementsByTagName('div')); // will convert the NodeList into an array
  1367. * Ext.Array.toArray('splitted'); // returns ['s', 'p', 'l', 'i', 't', 't', 'e', 'd']
  1368. * Ext.Array.toArray('splitted', 0, 3); // returns ['s', 'p', 'l', 'i']
  1369. *
  1370. * {@link Ext#toArray Ext.toArray} is alias for {@link Ext.Array#toArray Ext.Array.toArray}
  1371. *
  1372. * @param {Object} iterable the iterable object to be turned into a true Array.
  1373. * @param {Number} start (Optional) a zero-based index that specifies the start of extraction. Defaults to 0
  1374. * @param {Number} end (Optional) a zero-based index that specifies the end of extraction. Defaults to the last
  1375. * index of the iterable value
  1376. * @return {Array} array
  1377. */
  1378. toArray: function(iterable, start, end){
  1379. if (!iterable || !iterable.length) {
  1380. return [];
  1381. }
  1382. if (typeof iterable === 'string') {
  1383. iterable = iterable.split('');
  1384. }
  1385. if (supportsSliceOnNodeList) {
  1386. return slice.call(iterable, start || 0, end || iterable.length);
  1387. }
  1388. var array = [],
  1389. i;
  1390. start = start || 0;
  1391. end = end ? ((end < 0) ? iterable.length + end : end) : iterable.length;
  1392. for (i = start; i < end; i++) {
  1393. array.push(iterable[i]);
  1394. }
  1395. return array;
  1396. },
  1397. /**
  1398. * Plucks the value of a property from each item in the Array. Example:
  1399. *
  1400. * Ext.Array.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className]
  1401. *
  1402. * @param {Array/NodeList} array The Array of items to pluck the value from.
  1403. * @param {String} propertyName The property name to pluck from each element.
  1404. * @return {Array} The value from each item in the Array.
  1405. */
  1406. pluck: function(array, propertyName) {
  1407. var ret = [],
  1408. i, ln, item;
  1409. for (i = 0, ln = array.length; i < ln; i++) {
  1410. item = array[i];
  1411. ret.push(item[propertyName]);
  1412. }
  1413. return ret;
  1414. },
  1415. /**
  1416. * Creates a new array with the results of calling a provided function on every element in this array.
  1417. *
  1418. * @param {Array} array
  1419. * @param {Function} fn Callback function for each item
  1420. * @param {Object} scope Callback function scope
  1421. * @return {Array} results
  1422. */
  1423. map: function(array, fn, scope) {
  1424. if (supportsMap) {
  1425. return array.map(fn, scope);
  1426. }
  1427. var results = [],
  1428. i = 0,
  1429. len = array.length;
  1430. for (; i < len; i++) {
  1431. results[i] = fn.call(scope, array[i], i, array);
  1432. }
  1433. return results;
  1434. },
  1435. /**
  1436. * Executes the specified function for each array element until the function returns a falsy value.
  1437. * If such an item is found, the function will return false immediately.
  1438. * Otherwise, it will return true.
  1439. *
  1440. * @param {Array} array
  1441. * @param {Function} fn Callback function for each item
  1442. * @param {Object} scope Callback function scope
  1443. * @return {Boolean} True if no false value is returned by the callback function.
  1444. */
  1445. every: function(array, fn, scope) {
  1446. if (!fn) {
  1447. Ext.Error.raise('Ext.Array.every must have a callback function passed as second argument.');
  1448. }
  1449. if (supportsEvery) {
  1450. return array.every(fn, scope);
  1451. }
  1452. var i = 0,
  1453. ln = array.length;
  1454. for (; i < ln; ++i) {
  1455. if (!fn.call(scope, array[i], i, array)) {
  1456. return false;
  1457. }
  1458. }
  1459. return true;
  1460. },
  1461. /**
  1462. * Executes the specified function for each array element until the function returns a truthy value.
  1463. * If such an item is found, the function will return true immediately. Otherwise, it will return false.
  1464. *
  1465. * @param {Array} array
  1466. * @param {Function} fn Callback function for each item
  1467. * @param {Object} scope Callback function scope
  1468. * @return {Boolean} True if the callback function returns a truthy value.
  1469. */
  1470. some: function(array, fn, scope) {
  1471. if (!fn) {
  1472. Ext.Error.raise('Ext.Array.some must have a callback function passed as second argument.');
  1473. }
  1474. if (supportsSome) {
  1475. return array.some(fn, scope);
  1476. }
  1477. var i = 0,
  1478. ln = array.length;
  1479. for (; i < ln; ++i) {
  1480. if (fn.call(scope, array[i], i, array)) {
  1481. return true;
  1482. }
  1483. }
  1484. return false;
  1485. },
  1486. /**
  1487. * Filter through an array and remove empty item as defined in {@link Ext#isEmpty Ext.isEmpty}
  1488. *
  1489. * See {@link Ext.Array#filter}
  1490. *
  1491. * @param {Array} array
  1492. * @return {Array} results
  1493. */
  1494. clean: function(array) {
  1495. var results = [],
  1496. i = 0,
  1497. ln = array.length,
  1498. item;
  1499. for (; i < ln; i++) {
  1500. item = array[i];
  1501. if (!Ext.isEmpty(item)) {
  1502. results.push(item);
  1503. }
  1504. }
  1505. return results;
  1506. },
  1507. /**
  1508. * Returns a new array with unique items
  1509. *
  1510. * @param {Array} array
  1511. * @return {Array} results
  1512. */
  1513. unique: function(array) {
  1514. var clone = [],
  1515. i = 0,
  1516. ln = array.length,
  1517. item;
  1518. for (; i < ln; i++) {
  1519. item = array[i];
  1520. if (ExtArray.indexOf(clone, item) === -1) {
  1521. clone.push(item);
  1522. }
  1523. }
  1524. return clone;
  1525. },
  1526. /**
  1527. * Creates a new array with all of the elements of this array for which
  1528. * the provided filtering function returns true.
  1529. *
  1530. * @param {Array} array
  1531. * @param {Function} fn Callback function for each item
  1532. * @param {Object} scope Callback function scope
  1533. * @return {Array} results
  1534. */
  1535. filter: function(array, fn, scope) {
  1536. if (supportsFilter) {
  1537. return array.filter(fn, scope);
  1538. }
  1539. var results = [],
  1540. i = 0,
  1541. ln = array.length;
  1542. for (; i < ln; i++) {
  1543. if (fn.call(scope, array[i], i, array)) {
  1544. results.push(array[i]);
  1545. }
  1546. }
  1547. return results;
  1548. },
  1549. /**
  1550. * Converts a value to an array if it's not already an array; returns:
  1551. *
  1552. * - An empty array if given value is `undefined` or `null`
  1553. * - Itself if given value is already an array
  1554. * - An array copy if given value is {@link Ext#isIterable iterable} (arguments, NodeList and alike)
  1555. * - An array with one item which is the given value, otherwise
  1556. *
  1557. * @param {Object} value The value to convert to an array if it's not already is an array
  1558. * @param {Boolean} newReference (Optional) True to clone the given array and return a new reference if necessary,
  1559. * defaults to false
  1560. * @return {Array} array
  1561. */
  1562. from: function(value, newReference) {
  1563. if (value === undefined || value === null) {
  1564. return [];
  1565. }
  1566. if (Ext.isArray(value)) {
  1567. return (newReference) ? slice.call(value) : value;
  1568. }
  1569. if (value && value.length !== undefined && typeof value !== 'string') {
  1570. return Ext.toArray(value);
  1571. }
  1572. return [value];
  1573. },
  1574. /**
  1575. * Removes the specified item from the array if it exists
  1576. *
  1577. * @param {Array} array The array
  1578. * @param {Object} item The item to remove
  1579. * @return {Array} The passed array itself
  1580. */
  1581. remove: function(array, item) {
  1582. var index = ExtArray.indexOf(array, item);
  1583. if (index !== -1) {
  1584. erase(array, index, 1);
  1585. }
  1586. return array;
  1587. },
  1588. /**
  1589. * Push an item into the array only if the array doesn't contain it yet
  1590. *
  1591. * @param {Array} array The array
  1592. * @param {Object} item The item to include
  1593. */
  1594. include: function(array, item) {
  1595. if (!ExtArray.contains(array, item)) {
  1596. array.push(item);
  1597. }
  1598. },
  1599. /**
  1600. * Clone a flat array without referencing the previous one. Note that this is different
  1601. * from Ext.clone since it doesn't handle recursive cloning. It's simply a convenient, easy-to-remember method
  1602. * for Array.prototype.slice.call(array)
  1603. *
  1604. * @param {Array} array The array
  1605. * @return {Array} The clone array
  1606. */
  1607. clone: function(array) {
  1608. return slice.call(array);
  1609. },
  1610. /**
  1611. * Merge multiple arrays into one with unique items.
  1612. *
  1613. * {@link Ext.Array#union} is alias for {@link Ext.Array#merge}
  1614. *
  1615. * @param {Array} array1
  1616. * @param {Array} array2
  1617. * @param {Array} etc
  1618. * @return {Array} merged
  1619. */
  1620. merge: function() {
  1621. var args = slice.call(arguments),
  1622. array = [],
  1623. i, ln;
  1624. for (i = 0, ln = args.length; i < ln; i++) {
  1625. array = array.concat(args[i]);
  1626. }
  1627. return ExtArray.unique(array);
  1628. },
  1629. /**
  1630. * Merge multiple arrays into one with unique items that exist in all of the arrays.
  1631. *
  1632. * @param {Array} array1
  1633. * @param {Array} array2
  1634. * @param {Array} etc
  1635. * @return {Array} intersect
  1636. */
  1637. intersect: function() {
  1638. var intersect = [],
  1639. arrays = slice.call(arguments),
  1640. i, j, k, minArray, array, x, y, ln, arraysLn, arrayLn;
  1641. if (!arrays.length) {
  1642. return intersect;
  1643. }
  1644. // Find the smallest array
  1645. for (i = x = 0,ln = arrays.length; i < ln,array = arrays[i]; i++) {
  1646. if (!minArray || array.length < minArray.length) {
  1647. minArray = array;
  1648. x = i;
  1649. }
  1650. }
  1651. minArray = ExtArray.unique(minArray);
  1652. erase(arrays, x, 1);
  1653. // Use the smallest unique'd array as the anchor loop. If the other array(s) do contain
  1654. // an item in the small array, we're likely to find it before reaching the end
  1655. // of the inner loop and can terminate the search early.
  1656. for (i = 0,ln = minArray.length; i < ln,x = minArray[i]; i++) {
  1657. var count = 0;
  1658. for (j = 0,arraysLn = arrays.length; j < arraysLn,array = arrays[j]; j++) {
  1659. for (k = 0,arrayLn = array.length; k < arrayLn,y = array[k]; k++) {
  1660. if (x === y) {
  1661. count++;
  1662. break;
  1663. }
  1664. }
  1665. }
  1666. if (count === arraysLn) {
  1667. intersect.push(x);
  1668. }
  1669. }
  1670. return intersect;
  1671. },
  1672. /**
  1673. * Perform a set difference A-B by subtracting all items in array B from array A.
  1674. *
  1675. * @param {Array} arrayA
  1676. * @param {Array} arrayB
  1677. * @return {Array} difference
  1678. */
  1679. difference: function(arrayA, arrayB) {
  1680. var clone = slice.call(arrayA),
  1681. ln = clone.length,
  1682. i, j, lnB;
  1683. for (i = 0,lnB = arrayB.length; i < lnB; i++) {
  1684. for (j = 0; j < ln; j++) {
  1685. if (clone[j] === arrayB[i]) {
  1686. erase(clone, j, 1);
  1687. j--;
  1688. ln--;
  1689. }
  1690. }
  1691. }
  1692. return clone;
  1693. },
  1694. /**
  1695. * Returns a shallow copy of a part of an array. This is equivalent to the native
  1696. * call "Array.prototype.slice.call(array, begin, end)". This is often used when "array"
  1697. * is "arguments" since the arguments object does not supply a slice method but can
  1698. * be the context object to Array.prototype.slice.
  1699. *
  1700. * @param {Array} array The array (or arguments object).
  1701. * @param {Number} begin The index at which to begin. Negative values are offsets from
  1702. * the end of the array.
  1703. * @param {Number} end The index at which to end. The copied items do not include
  1704. * end. Negative values are offsets from the end of the array. If end is omitted,
  1705. * all items up to the end of the array are copied.
  1706. * @return {Array} The copied piece of the array.
  1707. */
  1708. // Note: IE6 will return [] on slice.call(x, undefined).
  1709. slice: ([1,2].slice(1, undefined).length ?
  1710. function (array, begin, end) {
  1711. return slice.call(array, begin, end);
  1712. } :
  1713. // at least IE6 uses arguments.length for variadic signature
  1714. function (array, begin, end) {
  1715. // After tested for IE 6, the one below is of the best performance
  1716. // see http://jsperf.com/slice-fix
  1717. if (typeof begin === 'undefined') {
  1718. return slice.call(array);
  1719. }
  1720. if (typeof end === 'undefined') {
  1721. return slice.call(array, begin);
  1722. }
  1723. return slice.call(array, begin, end);
  1724. }
  1725. ),
  1726. /**
  1727. * Sorts the elements of an Array.
  1728. * By default, this method sorts the elements alphabetically and ascending.
  1729. *
  1730. * @param {Array} array The array to sort.
  1731. * @param {Function} sortFn (optional) The comparison function.
  1732. * @return {Array} The sorted array.
  1733. */
  1734. sort: function(array, sortFn) {
  1735. if (supportsSort) {
  1736. if (sortFn) {
  1737. return array.sort(sortFn);
  1738. } else {
  1739. return array.sort();
  1740. }
  1741. }
  1742. var length = array.length,
  1743. i = 0,
  1744. comparison,
  1745. j, min, tmp;
  1746. for (; i < length; i++) {
  1747. min = i;
  1748. for (j = i + 1; j < length; j++) {
  1749. if (sortFn) {
  1750. comparison = sortFn(array[j], array[min]);
  1751. if (comparison < 0) {
  1752. min = j;
  1753. }
  1754. } else if (array[j] < array[min]) {
  1755. min = j;
  1756. }
  1757. }
  1758. if (min !== i) {
  1759. tmp = array[i];
  1760. array[i] = array[min];
  1761. array[min] = tmp;
  1762. }
  1763. }
  1764. return array;
  1765. },
  1766. /**
  1767. * Recursively flattens into 1-d Array. Injects Arrays inline.
  1768. *
  1769. * @param {Array} array The array to flatten
  1770. * @return {Array} The 1-d array.
  1771. */
  1772. flatten: function(array) {
  1773. var worker = [];
  1774. function rFlatten(a) {
  1775. var i, ln, v;
  1776. for (i = 0, ln = a.length; i < ln; i++) {
  1777. v = a[i];
  1778. if (Ext.isArray(v)) {
  1779. rFlatten(v);
  1780. } else {
  1781. worker.push(v);
  1782. }
  1783. }
  1784. return worker;
  1785. }
  1786. return rFlatten(array);
  1787. },
  1788. /**
  1789. * Returns the minimum value in the Array.
  1790. *
  1791. * @param {Array/NodeList} array The Array from which to select the minimum value.
  1792. * @param {Function} comparisonFn (optional) a function to perform the comparision which determines minimization.
  1793. * If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1
  1794. * @return {Object} minValue The minimum value
  1795. */
  1796. min: function(array, comparisonFn) {
  1797. var min = array[0],
  1798. i, ln, item;
  1799. for (i = 0, ln = array.length; i < ln; i++) {
  1800. item = array[i];
  1801. if (comparisonFn) {
  1802. if (comparisonFn(min, item) === 1) {
  1803. min = item;
  1804. }
  1805. }
  1806. else {
  1807. if (item < min) {
  1808. min = item;
  1809. }
  1810. }
  1811. }
  1812. return min;
  1813. },
  1814. /**
  1815. * Returns the maximum value in the Array.
  1816. *
  1817. * @param {Array/NodeList} array The Array from which to select the maximum value.
  1818. * @param {Function} comparisonFn (optional) a function to perform the comparision which determines maximization.
  1819. * If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1
  1820. * @return {Object} maxValue The maximum value
  1821. */
  1822. max: function(array, comparisonFn) {
  1823. var max = array[0],
  1824. i, ln, item;
  1825. for (i = 0, ln = array.length; i < ln; i++) {
  1826. item = array[i];
  1827. if (comparisonFn) {
  1828. if (comparisonFn(max, item) === -1) {
  1829. max = item;
  1830. }
  1831. }
  1832. else {
  1833. if (item > max) {
  1834. max = item;
  1835. }
  1836. }
  1837. }
  1838. return max;
  1839. },
  1840. /**
  1841. * Calculates the mean of all items in the array.
  1842. *
  1843. * @param {Array} array The Array to calculate the mean value of.
  1844. * @return {Number} The mean.
  1845. */
  1846. mean: function(array) {
  1847. return array.length > 0 ? ExtArray.sum(array) / array.length : undefined;
  1848. },
  1849. /**
  1850. * Calculates the sum of all items in the given array.
  1851. *
  1852. * @param {Array} array The Array to calculate the sum value of.
  1853. * @return {Number} The sum.
  1854. */
  1855. sum: function(array) {
  1856. var sum = 0,
  1857. i, ln, item;
  1858. for (i = 0,ln = array.length; i < ln; i++) {
  1859. item = array[i];
  1860. sum += item;
  1861. }
  1862. return sum;
  1863. },
  1864. _replaceSim: replaceSim, // for unit testing
  1865. _spliceSim: spliceSim,
  1866. /**
  1867. * Removes items from an array. This is functionally equivalent to the splice method
  1868. * of Array, but works around bugs in IE8's splice method and does not copy the
  1869. * removed elements in order to return them (because very often they are ignored).
  1870. *
  1871. * @param {Array} array The Array on which to replace.
  1872. * @param {Number} index The index in the array at which to operate.
  1873. * @param {Number} removeCount The number of items to remove at index.
  1874. * @return {Array} The array passed.
  1875. * @method
  1876. */
  1877. erase: erase,
  1878. /**
  1879. * Inserts items in to an array.
  1880. *
  1881. * @param {Array} array The Array on which to replace.
  1882. * @param {Number} index The index in the array at which to operate.
  1883. * @param {Array} items The array of items to insert at index.
  1884. * @return {Array} The array passed.
  1885. */
  1886. insert: function (array, index, items) {
  1887. return replace(array, index, 0, items);
  1888. },
  1889. /**
  1890. * Replaces items in an array. This is functionally equivalent to the splice method
  1891. * of Array, but works around bugs in IE8's splice method and is often more convenient
  1892. * to call because it accepts an array of items to insert rather than use a variadic
  1893. * argument list.
  1894. *
  1895. * @param {Array} array The Array on which to replace.
  1896. * @param {Number} index The index in the array at which to operate.
  1897. * @param {Number} removeCount The number of items to remove at index (can be 0).
  1898. * @param {Array} insert (optional) An array of items to insert at index.
  1899. * @return {Array} The array passed.
  1900. * @method
  1901. */
  1902. replace: replace,
  1903. /**
  1904. * Replaces items in an array. This is equivalent to the splice method of Array, but
  1905. * works around bugs in IE8's splice method. The signature is exactly the same as the
  1906. * splice method except that the array is the first argument. All arguments following
  1907. * removeCount are inserted in the array at index.
  1908. *
  1909. * @param {Array} array The Array on which to replace.
  1910. * @param {Number} index The index in the array at which to operate.
  1911. * @param {Number} removeCount The number of items to remove at index (can be 0).
  1912. * @return {Array} An array containing the removed items.
  1913. * @method
  1914. */
  1915. splice: splice
  1916. };
  1917. /**
  1918. * @method
  1919. * @member Ext
  1920. * @alias Ext.Array#each
  1921. */
  1922. Ext.each = ExtArray.each;
  1923. /**
  1924. * @method
  1925. * @member Ext.Array
  1926. * @alias Ext.Array#merge
  1927. */
  1928. ExtArray.union = ExtArray.merge;
  1929. /**
  1930. * Old alias to {@link Ext.Array#min}
  1931. * @deprecated 4.0.0 Use {@link Ext.Array#min} instead
  1932. * @method
  1933. * @member Ext
  1934. * @alias Ext.Array#min
  1935. */
  1936. Ext.min = ExtArray.min;
  1937. /**
  1938. * Old alias to {@link Ext.Array#max}
  1939. * @deprecated 4.0.0 Use {@link Ext.Array#max} instead
  1940. * @method
  1941. * @member Ext
  1942. * @alias Ext.Array#max
  1943. */
  1944. Ext.max = ExtArray.max;
  1945. /**
  1946. * Old alias to {@link Ext.Array#sum}
  1947. * @deprecated 4.0.0 Use {@link Ext.Array#sum} instead
  1948. * @method
  1949. * @member Ext
  1950. * @alias Ext.Array#sum
  1951. */
  1952. Ext.sum = ExtArray.sum;
  1953. /**
  1954. * Old alias to {@link Ext.Array#mean}
  1955. * @deprecated 4.0.0 Use {@link Ext.Array#mean} instead
  1956. * @method
  1957. * @member Ext
  1958. * @alias Ext.Array#mean
  1959. */
  1960. Ext.mean = ExtArray.mean;
  1961. /**
  1962. * Old alias to {@link Ext.Array#flatten}
  1963. * @deprecated 4.0.0 Use {@link Ext.Array#flatten} instead
  1964. * @method
  1965. * @member Ext
  1966. * @alias Ext.Array#flatten
  1967. */
  1968. Ext.flatten = ExtArray.flatten;
  1969. /**
  1970. * Old alias to {@link Ext.Array#clean}
  1971. * @deprecated 4.0.0 Use {@link Ext.Array#clean} instead
  1972. * @method
  1973. * @member Ext
  1974. * @alias Ext.Array#clean
  1975. */
  1976. Ext.clean = ExtArray.clean;
  1977. /**
  1978. * Old alias to {@link Ext.Array#unique}
  1979. * @deprecated 4.0.0 Use {@link Ext.Array#unique} instead
  1980. * @method
  1981. * @member Ext
  1982. * @alias Ext.Array#unique
  1983. */
  1984. Ext.unique = ExtArray.unique;
  1985. /**
  1986. * Old alias to {@link Ext.Array#pluck Ext.Array.pluck}
  1987. * @deprecated 4.0.0 Use {@link Ext.Array#pluck Ext.Array.pluck} instead
  1988. * @method
  1989. * @member Ext
  1990. * @alias Ext.Array#pluck
  1991. */
  1992. Ext.pluck = ExtArray.pluck;
  1993. /**
  1994. * @method
  1995. * @member Ext
  1996. * @alias Ext.Array#toArray
  1997. */
  1998. Ext.toArray = function() {
  1999. return ExtArray.toArray.apply(ExtArray, arguments);
  2000. };
  2001. })();
  2002. /**
  2003. * @class Ext.Function
  2004. *
  2005. * A collection of useful static methods to deal with function callbacks
  2006. * @singleton
  2007. */
  2008. Ext.Function = {
  2009. /**
  2010. * A very commonly used method throughout the framework. It acts as a wrapper around another method
  2011. * which originally accepts 2 arguments for `name` and `value`.
  2012. * The wrapped function then allows "flexible" value setting of either:
  2013. *
  2014. * - `name` and `value` as 2 arguments
  2015. * - one single object argument with multiple key - value pairs
  2016. *
  2017. * For example:
  2018. *
  2019. * var setValue = Ext.Function.flexSetter(function(name, value) {
  2020. * this[name] = value;
  2021. * });
  2022. *
  2023. * // Afterwards
  2024. * // Setting a single name - value
  2025. * setValue('name1', 'value1');
  2026. *
  2027. * // Settings multiple name - value pairs
  2028. * setValue({
  2029. * name1: 'value1',
  2030. * name2: 'value2',
  2031. * name3: 'value3'
  2032. * });
  2033. *
  2034. * @param {Function} setter
  2035. * @returns {Function} flexSetter
  2036. */
  2037. flexSetter: function(fn) {
  2038. return function(a, b) {
  2039. var k, i;
  2040. if (a === null) {
  2041. return this;
  2042. }
  2043. if (typeof a !== 'string') {
  2044. for (k in a) {
  2045. if (a.hasOwnProperty(k)) {
  2046. fn.call(this, k, a[k]);
  2047. }
  2048. }
  2049. if (Ext.enumerables) {
  2050. for (i = Ext.enumerables.length; i--;) {
  2051. k = Ext.enumerables[i];
  2052. if (a.hasOwnProperty(k)) {
  2053. fn.call(this, k, a[k]);
  2054. }
  2055. }
  2056. }
  2057. } else {
  2058. fn.call(this, a, b);
  2059. }
  2060. return this;
  2061. };
  2062. },
  2063. /**
  2064. * Create a new function from the provided `fn`, change `this` to the provided scope, optionally
  2065. * overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2066. *
  2067. * {@link Ext#bind Ext.bind} is alias for {@link Ext.Function#bind Ext.Function.bind}
  2068. *
  2069. * @param {Function} fn The function to delegate.
  2070. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2071. * **If omitted, defaults to the browser window.**
  2072. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2073. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2074. * if a number the args are inserted at the specified position
  2075. * @return {Function} The new function
  2076. */
  2077. bind: function(fn, scope, args, appendArgs) {
  2078. if (arguments.length === 2) {
  2079. return function() {
  2080. return fn.apply(scope, arguments);
  2081. }
  2082. }
  2083. var method = fn,
  2084. slice = Array.prototype.slice;
  2085. return function() {
  2086. var callArgs = args || arguments;
  2087. if (appendArgs === true) {
  2088. callArgs = slice.call(arguments, 0);
  2089. callArgs = callArgs.concat(args);
  2090. }
  2091. else if (typeof appendArgs == 'number') {
  2092. callArgs = slice.call(arguments, 0); // copy arguments first
  2093. Ext.Array.insert(callArgs, appendArgs, args);
  2094. }
  2095. return method.apply(scope || window, callArgs);
  2096. };
  2097. },
  2098. /**
  2099. * Create a new function from the provided `fn`, the arguments of which are pre-set to `args`.
  2100. * New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones.
  2101. * This is especially useful when creating callbacks.
  2102. *
  2103. * For example:
  2104. *
  2105. * var originalFunction = function(){
  2106. * alert(Ext.Array.from(arguments).join(' '));
  2107. * };
  2108. *
  2109. * var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']);
  2110. *
  2111. * callback(); // alerts 'Hello World'
  2112. * callback('by Me'); // alerts 'Hello World by Me'
  2113. *
  2114. * {@link Ext#pass Ext.pass} is alias for {@link Ext.Function#pass Ext.Function.pass}
  2115. *
  2116. * @param {Function} fn The original function
  2117. * @param {Array} args The arguments to pass to new callback
  2118. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2119. * @return {Function} The new callback function
  2120. */
  2121. pass: function(fn, args, scope) {
  2122. if (args) {
  2123. args = Ext.Array.from(args);
  2124. }
  2125. return function() {
  2126. return fn.apply(scope, args.concat(Ext.Array.toArray(arguments)));
  2127. };
  2128. },
  2129. /**
  2130. * Create an alias to the provided method property with name `methodName` of `object`.
  2131. * Note that the execution scope will still be bound to the provided `object` itself.
  2132. *
  2133. * @param {Object/Function} object
  2134. * @param {String} methodName
  2135. * @return {Function} aliasFn
  2136. */
  2137. alias: function(object, methodName) {
  2138. return function() {
  2139. return object[methodName].apply(object, arguments);
  2140. };
  2141. },
  2142. /**
  2143. * Creates an interceptor function. The passed function is called before the original one. If it returns false,
  2144. * the original one is not called. The resulting function returns the results of the original function.
  2145. * The passed function is called with the parameters of the original function. Example usage:
  2146. *
  2147. * var sayHi = function(name){
  2148. * alert('Hi, ' + name);
  2149. * }
  2150. *
  2151. * sayHi('Fred'); // alerts "Hi, Fred"
  2152. *
  2153. * // create a new function that validates input without
  2154. * // directly modifying the original function:
  2155. * var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){
  2156. * return name == 'Brian';
  2157. * });
  2158. *
  2159. * sayHiToFriend('Fred'); // no alert
  2160. * sayHiToFriend('Brian'); // alerts "Hi, Brian"
  2161. *
  2162. * @param {Function} origFn The original function.
  2163. * @param {Function} newFn The function to call before the original
  2164. * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
  2165. * **If omitted, defaults to the scope in which the original function is called or the browser window.**
  2166. * @param {Object} returnValue (optional) The value to return if the passed function return false (defaults to null).
  2167. * @return {Function} The new function
  2168. */
  2169. createInterceptor: function(origFn, newFn, scope, returnValue) {
  2170. var method = origFn;
  2171. if (!Ext.isFunction(newFn)) {
  2172. return origFn;
  2173. }
  2174. else {
  2175. return function() {
  2176. var me = this,
  2177. args = arguments;
  2178. newFn.target = me;
  2179. newFn.method = origFn;
  2180. return (newFn.apply(scope || me || window, args) !== false) ? origFn.apply(me || window, args) : returnValue || null;
  2181. };
  2182. }
  2183. },
  2184. /**
  2185. * Creates a delegate (callback) which, when called, executes after a specific delay.
  2186. *
  2187. * @param {Function} fn The function which will be called on a delay when the returned function is called.
  2188. * Optionally, a replacement (or additional) argument list may be specified.
  2189. * @param {Number} delay The number of milliseconds to defer execution by whenever called.
  2190. * @param {Object} scope (optional) The scope (`this` reference) used by the function at execution time.
  2191. * @param {Array} args (optional) Override arguments for the call. (Defaults to the arguments passed by the caller)
  2192. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2193. * if a number the args are inserted at the specified position.
  2194. * @return {Function} A function which, when called, executes the original function after the specified delay.
  2195. */
  2196. createDelayed: function(fn, delay, scope, args, appendArgs) {
  2197. if (scope || args) {
  2198. fn = Ext.Function.bind(fn, scope, args, appendArgs);
  2199. }
  2200. return function() {
  2201. var me = this;
  2202. setTimeout(function() {
  2203. fn.apply(me, arguments);
  2204. }, delay);
  2205. };
  2206. },
  2207. /**
  2208. * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
  2209. *
  2210. * var sayHi = function(name){
  2211. * alert('Hi, ' + name);
  2212. * }
  2213. *
  2214. * // executes immediately:
  2215. * sayHi('Fred');
  2216. *
  2217. * // executes after 2 seconds:
  2218. * Ext.Function.defer(sayHi, 2000, this, ['Fred']);
  2219. *
  2220. * // this syntax is sometimes useful for deferring
  2221. * // execution of an anonymous function:
  2222. * Ext.Function.defer(function(){
  2223. * alert('Anonymous');
  2224. * }, 100);
  2225. *
  2226. * {@link Ext#defer Ext.defer} is alias for {@link Ext.Function#defer Ext.Function.defer}
  2227. *
  2228. * @param {Function} fn The function to defer.
  2229. * @param {Number} millis The number of milliseconds for the setTimeout call
  2230. * (if less than or equal to 0 the function is executed immediately)
  2231. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2232. * **If omitted, defaults to the browser window.**
  2233. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2234. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2235. * if a number the args are inserted at the specified position
  2236. * @return {Number} The timeout id that can be used with clearTimeout
  2237. */
  2238. defer: function(fn, millis, obj, args, appendArgs) {
  2239. fn = Ext.Function.bind(fn, obj, args, appendArgs);
  2240. if (millis > 0) {
  2241. return setTimeout(fn, millis);
  2242. }
  2243. fn();
  2244. return 0;
  2245. },
  2246. /**
  2247. * Create a combined function call sequence of the original function + the passed function.
  2248. * The resulting function returns the results of the original function.
  2249. * The passed function is called with the parameters of the original function. Example usage:
  2250. *
  2251. * var sayHi = function(name){
  2252. * alert('Hi, ' + name);
  2253. * }
  2254. *
  2255. * sayHi('Fred'); // alerts "Hi, Fred"
  2256. *
  2257. * var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){
  2258. * alert('Bye, ' + name);
  2259. * });
  2260. *
  2261. * sayGoodbye('Fred'); // both alerts show
  2262. *
  2263. * @param {Function} origFn The original function.
  2264. * @param {Function} newFn The function to sequence
  2265. * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
  2266. * If omitted, defaults to the scope in which the original function is called or the browser window.
  2267. * @return {Function} The new function
  2268. */
  2269. createSequence: function(origFn, newFn, scope) {
  2270. if (!Ext.isFunction(newFn)) {
  2271. return origFn;
  2272. }
  2273. else {
  2274. return function() {
  2275. var retval = origFn.apply(this || window, arguments);
  2276. newFn.apply(scope || this || window, arguments);
  2277. return retval;
  2278. };
  2279. }
  2280. },
  2281. /**
  2282. * Creates a delegate function, optionally with a bound scope which, when called, buffers
  2283. * the execution of the passed function for the configured number of milliseconds.
  2284. * If called again within that period, the impending invocation will be canceled, and the
  2285. * timeout period will begin again.
  2286. *
  2287. * @param {Function} fn The function to invoke on a buffered timer.
  2288. * @param {Number} buffer The number of milliseconds by which to buffer the invocation of the
  2289. * function.
  2290. * @param {Object} scope (optional) The scope (`this` reference) in which
  2291. * the passed function is executed. If omitted, defaults to the scope specified by the caller.
  2292. * @param {Array} args (optional) Override arguments for the call. Defaults to the arguments
  2293. * passed by the caller.
  2294. * @return {Function} A function which invokes the passed function after buffering for the specified time.
  2295. */
  2296. createBuffered: function(fn, buffer, scope, args) {
  2297. return function(){
  2298. var timerId;
  2299. return function() {
  2300. var me = this;
  2301. if (timerId) {
  2302. clearTimeout(timerId);
  2303. timerId = null;
  2304. }
  2305. timerId = setTimeout(function(){
  2306. fn.apply(scope || me, args || arguments);
  2307. }, buffer);
  2308. };
  2309. }();
  2310. },
  2311. /**
  2312. * Creates a throttled version of the passed function which, when called repeatedly and
  2313. * rapidly, invokes the passed function only after a certain interval has elapsed since the
  2314. * previous invocation.
  2315. *
  2316. * This is useful for wrapping functions which may be called repeatedly, such as
  2317. * a handler of a mouse move event when the processing is expensive.
  2318. *
  2319. * @param {Function} fn The function to execute at a regular time interval.
  2320. * @param {Number} interval The interval **in milliseconds** on which the passed function is executed.
  2321. * @param {Object} scope (optional) The scope (`this` reference) in which
  2322. * the passed function is executed. If omitted, defaults to the scope specified by the caller.
  2323. * @returns {Function} A function which invokes the passed function at the specified interval.
  2324. */
  2325. createThrottled: function(fn, interval, scope) {
  2326. var lastCallTime, elapsed, lastArgs, timer, execute = function() {
  2327. fn.apply(scope || this, lastArgs);
  2328. lastCallTime = new Date().getTime();
  2329. };
  2330. return function() {
  2331. elapsed = new Date().getTime() - lastCallTime;
  2332. lastArgs = arguments;
  2333. clearTimeout(timer);
  2334. if (!lastCallTime || (elapsed >= interval)) {
  2335. execute();
  2336. } else {
  2337. timer = setTimeout(execute, interval - elapsed);
  2338. }
  2339. };
  2340. },
  2341. /**
  2342. * Adds behavior to an existing method that is executed before the
  2343. * original behavior of the function. For example:
  2344. *
  2345. * var soup = {
  2346. * contents: [],
  2347. * add: function(ingredient) {
  2348. * this.contents.push(ingredient);
  2349. * }
  2350. * };
  2351. * Ext.Function.interceptBefore(soup, "add", function(ingredient){
  2352. * if (!this.contents.length && ingredient !== "water") {
  2353. * // Always add water to start with
  2354. * this.contents.push("water");
  2355. * }
  2356. * });
  2357. * soup.add("onions");
  2358. * soup.add("salt");
  2359. * soup.contents; // will contain: water, onions, salt
  2360. *
  2361. * @param {Object} object The target object
  2362. * @param {String} methodName Name of the method to override
  2363. * @param {Function} fn Function with the new behavior. It will
  2364. * be called with the same arguments as the original method. The
  2365. * return value of this function will be the return value of the
  2366. * new method.
  2367. * @return {Function} The new function just created.
  2368. */
  2369. interceptBefore: function(object, methodName, fn) {
  2370. var method = object[methodName] || Ext.emptyFn;
  2371. return object[methodName] = function() {
  2372. var ret = fn.apply(this, arguments);
  2373. method.apply(this, arguments);
  2374. return ret;
  2375. };
  2376. },
  2377. /**
  2378. * Adds behavior to an existing method that is executed after the
  2379. * original behavior of the function. For example:
  2380. *
  2381. * var soup = {
  2382. * contents: [],
  2383. * add: function(ingredient) {
  2384. * this.contents.push(ingredient);
  2385. * }
  2386. * };
  2387. * Ext.Function.interceptAfter(soup, "add", function(ingredient){
  2388. * // Always add a bit of extra salt
  2389. * this.contents.push("salt");
  2390. * });
  2391. * soup.add("water");
  2392. * soup.add("onions");
  2393. * soup.contents; // will contain: water, salt, onions, salt
  2394. *
  2395. * @param {Object} object The target object
  2396. * @param {String} methodName Name of the method to override
  2397. * @param {Function} fn Function with the new behavior. It will
  2398. * be called with the same arguments as the original method. The
  2399. * return value of this function will be the return value of the
  2400. * new method.
  2401. * @return {Function} The new function just created.
  2402. */
  2403. interceptAfter: function(object, methodName, fn) {
  2404. var method = object[methodName] || Ext.emptyFn;
  2405. return object[methodName] = function() {
  2406. method.apply(this, arguments);
  2407. return fn.apply(this, arguments);
  2408. };
  2409. }
  2410. };
  2411. /**
  2412. * @method
  2413. * @member Ext
  2414. * @alias Ext.Function#defer
  2415. */
  2416. Ext.defer = Ext.Function.alias(Ext.Function, 'defer');
  2417. /**
  2418. * @method
  2419. * @member Ext
  2420. * @alias Ext.Function#pass
  2421. */
  2422. Ext.pass = Ext.Function.alias(Ext.Function, 'pass');
  2423. /**
  2424. * @method
  2425. * @member Ext
  2426. * @alias Ext.Function#bind
  2427. */
  2428. Ext.bind = Ext.Function.alias(Ext.Function, 'bind');
  2429. /**
  2430. * @author Jacky Nguyen <jacky@sencha.com>
  2431. * @docauthor Jacky Nguyen <jacky@sencha.com>
  2432. * @class Ext.Object
  2433. *
  2434. * A collection of useful static methods to deal with objects.
  2435. *
  2436. * @singleton
  2437. */
  2438. (function() {
  2439. var ExtObject = Ext.Object = {
  2440. /**
  2441. * Converts a `name` - `value` pair to an array of objects with support for nested structures. Useful to construct
  2442. * query strings. For example:
  2443. *
  2444. * var objects = Ext.Object.toQueryObjects('hobbies', ['reading', 'cooking', 'swimming']);
  2445. *
  2446. * // objects then equals:
  2447. * [
  2448. * { name: 'hobbies', value: 'reading' },
  2449. * { name: 'hobbies', value: 'cooking' },
  2450. * { name: 'hobbies', value: 'swimming' },
  2451. * ];
  2452. *
  2453. * var objects = Ext.Object.toQueryObjects('dateOfBirth', {
  2454. * day: 3,
  2455. * month: 8,
  2456. * year: 1987,
  2457. * extra: {
  2458. * hour: 4
  2459. * minute: 30
  2460. * }
  2461. * }, true); // Recursive
  2462. *
  2463. * // objects then equals:
  2464. * [
  2465. * { name: 'dateOfBirth[day]', value: 3 },
  2466. * { name: 'dateOfBirth[month]', value: 8 },
  2467. * { name: 'dateOfBirth[year]', value: 1987 },
  2468. * { name: 'dateOfBirth[extra][hour]', value: 4 },
  2469. * { name: 'dateOfBirth[extra][minute]', value: 30 },
  2470. * ];
  2471. *
  2472. * @param {String} name
  2473. * @param {Object/Array} value
  2474. * @param {Boolean} [recursive=false] True to traverse object recursively
  2475. * @return {Array}
  2476. */
  2477. toQueryObjects: function(name, value, recursive) {
  2478. var self = ExtObject.toQueryObjects,
  2479. objects = [],
  2480. i, ln;
  2481. if (Ext.isArray(value)) {
  2482. for (i = 0, ln = value.length; i < ln; i++) {
  2483. if (recursive) {
  2484. objects = objects.concat(self(name + '[' + i + ']', value[i], true));
  2485. }
  2486. else {
  2487. objects.push({
  2488. name: name,
  2489. value: value[i]
  2490. });
  2491. }
  2492. }
  2493. }
  2494. else if (Ext.isObject(value)) {
  2495. for (i in value) {
  2496. if (value.hasOwnProperty(i)) {
  2497. if (recursive) {
  2498. objects = objects.concat(self(name + '[' + i + ']', value[i], true));
  2499. }
  2500. else {
  2501. objects.push({
  2502. name: name,
  2503. value: value[i]
  2504. });
  2505. }
  2506. }
  2507. }
  2508. }
  2509. else {
  2510. objects.push({
  2511. name: name,
  2512. value: value
  2513. });
  2514. }
  2515. return objects;
  2516. },
  2517. /**
  2518. * Takes an object and converts it to an encoded query string.
  2519. *
  2520. * Non-recursive:
  2521. *
  2522. * Ext.Object.toQueryString({foo: 1, bar: 2}); // returns "foo=1&bar=2"
  2523. * Ext.Object.toQueryString({foo: null, bar: 2}); // returns "foo=&bar=2"
  2524. * Ext.Object.toQueryString({'some price': '$300'}); // returns "some%20price=%24300"
  2525. * Ext.Object.toQueryString({date: new Date(2011, 0, 1)}); // returns "date=%222011-01-01T00%3A00%3A00%22"
  2526. * Ext.Object.toQueryString({colors: ['red', 'green', 'blue']}); // returns "colors=red&colors=green&colors=blue"
  2527. *
  2528. * Recursive:
  2529. *
  2530. * Ext.Object.toQueryString({
  2531. * username: 'Jacky',
  2532. * dateOfBirth: {
  2533. * day: 1,
  2534. * month: 2,
  2535. * year: 1911
  2536. * },
  2537. * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
  2538. * }, true); // returns the following string (broken down and url-decoded for ease of reading purpose):
  2539. * // username=Jacky
  2540. * // &dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911
  2541. * // &hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff
  2542. *
  2543. * @param {Object} object The object to encode
  2544. * @param {Boolean} [recursive=false] Whether or not to interpret the object in recursive format.
  2545. * (PHP / Ruby on Rails servers and similar).
  2546. * @return {String} queryString
  2547. */
  2548. toQueryString: function(object, recursive) {
  2549. var paramObjects = [],
  2550. params = [],
  2551. i, j, ln, paramObject, value;
  2552. for (i in object) {
  2553. if (object.hasOwnProperty(i)) {
  2554. paramObjects = paramObjects.concat(ExtObject.toQueryObjects(i, object[i], recursive));
  2555. }
  2556. }
  2557. for (j = 0, ln = paramObjects.length; j < ln; j++) {
  2558. paramObject = paramObjects[j];
  2559. value = paramObject.value;
  2560. if (Ext.isEmpty(value)) {
  2561. value = '';
  2562. }
  2563. else if (Ext.isDate(value)) {
  2564. value = Ext.Date.toString(value);
  2565. }
  2566. params.push(encodeURIComponent(paramObject.name) + '=' + encodeURIComponent(String(value)));
  2567. }
  2568. return params.join('&');
  2569. },
  2570. /**
  2571. * Converts a query string back into an object.
  2572. *
  2573. * Non-recursive:
  2574. *
  2575. * Ext.Object.fromQueryString(foo=1&bar=2); // returns {foo: 1, bar: 2}
  2576. * Ext.Object.fromQueryString(foo=&bar=2); // returns {foo: null, bar: 2}
  2577. * Ext.Object.fromQueryString(some%20price=%24300); // returns {'some price': '$300'}
  2578. * Ext.Object.fromQueryString(colors=red&colors=green&colors=blue); // returns {colors: ['red', 'green', 'blue']}
  2579. *
  2580. * Recursive:
  2581. *
  2582. * 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);
  2583. * // returns
  2584. * {
  2585. * username: 'Jacky',
  2586. * dateOfBirth: {
  2587. * day: '1',
  2588. * month: '2',
  2589. * year: '1911'
  2590. * },
  2591. * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
  2592. * }
  2593. *
  2594. * @param {String} queryString The query string to decode
  2595. * @param {Boolean} [recursive=false] Whether or not to recursively decode the string. This format is supported by
  2596. * PHP / Ruby on Rails servers and similar.
  2597. * @return {Object}
  2598. */
  2599. fromQueryString: function(queryString, recursive) {
  2600. var parts = queryString.replace(/^\?/, '').split('&'),
  2601. object = {},
  2602. temp, components, name, value, i, ln,
  2603. part, j, subLn, matchedKeys, matchedName,
  2604. keys, key, nextKey;
  2605. for (i = 0, ln = parts.length; i < ln; i++) {
  2606. part = parts[i];
  2607. if (part.length > 0) {
  2608. components = part.split('=');
  2609. name = decodeURIComponent(components[0]);
  2610. value = (components[1] !== undefined) ? decodeURIComponent(components[1]) : '';
  2611. if (!recursive) {
  2612. if (object.hasOwnProperty(name)) {
  2613. if (!Ext.isArray(object[name])) {
  2614. object[name] = [object[name]];
  2615. }
  2616. object[name].push(value);
  2617. }
  2618. else {
  2619. object[name] = value;
  2620. }
  2621. }
  2622. else {
  2623. matchedKeys = name.match(/(\[):?([^\]]*)\]/g);
  2624. matchedName = name.match(/^([^\[]+)/);
  2625. if (!matchedName) {
  2626. Ext.Error.raise({
  2627. sourceClass: "Ext.Object",
  2628. sourceMethod: "fromQueryString",
  2629. queryString: queryString,
  2630. recursive: recursive,
  2631. msg: 'Malformed query string given, failed parsing name from "' + part + '"'
  2632. });
  2633. }
  2634. name = matchedName[0];
  2635. keys = [];
  2636. if (matchedKeys === null) {
  2637. object[name] = value;
  2638. continue;
  2639. }
  2640. for (j = 0, subLn = matchedKeys.length; j < subLn; j++) {
  2641. key = matchedKeys[j];
  2642. key = (key.length === 2) ? '' : key.substring(1, key.length - 1);
  2643. keys.push(key);
  2644. }
  2645. keys.unshift(name);
  2646. temp = object;
  2647. for (j = 0, subLn = keys.length; j < subLn; j++) {
  2648. key = keys[j];
  2649. if (j === subLn - 1) {
  2650. if (Ext.isArray(temp) && key === '') {
  2651. temp.push(value);
  2652. }
  2653. else {
  2654. temp[key] = value;
  2655. }
  2656. }
  2657. else {
  2658. if (temp[key] === undefined || typeof temp[key] === 'string') {
  2659. nextKey = keys[j+1];
  2660. temp[key] = (Ext.isNumeric(nextKey) || nextKey === '') ? [] : {};
  2661. }
  2662. temp = temp[key];
  2663. }
  2664. }
  2665. }
  2666. }
  2667. }
  2668. return object;
  2669. },
  2670. /**
  2671. * Iterates through an object and invokes the given callback function for each iteration.
  2672. * The iteration can be stopped by returning `false` in the callback function. For example:
  2673. *
  2674. * var person = {
  2675. * name: 'Jacky'
  2676. * hairColor: 'black'
  2677. * loves: ['food', 'sleeping', 'wife']
  2678. * };
  2679. *
  2680. * Ext.Object.each(person, function(key, value, myself) {
  2681. * console.log(key + ":" + value);
  2682. *
  2683. * if (key === 'hairColor') {
  2684. * return false; // stop the iteration
  2685. * }
  2686. * });
  2687. *
  2688. * @param {Object} object The object to iterate
  2689. * @param {Function} fn The callback function.
  2690. * @param {String} fn.key
  2691. * @param {Object} fn.value
  2692. * @param {Object} fn.object The object itself
  2693. * @param {Object} [scope] The execution scope (`this`) of the callback function
  2694. */
  2695. each: function(object, fn, scope) {
  2696. for (var property in object) {
  2697. if (object.hasOwnProperty(property)) {
  2698. if (fn.call(scope || object, property, object[property], object) === false) {
  2699. return;
  2700. }
  2701. }
  2702. }
  2703. },
  2704. /**
  2705. * Merges any number of objects recursively without referencing them or their children.
  2706. *
  2707. * var extjs = {
  2708. * companyName: 'Ext JS',
  2709. * products: ['Ext JS', 'Ext GWT', 'Ext Designer'],
  2710. * isSuperCool: true
  2711. * office: {
  2712. * size: 2000,
  2713. * location: 'Palo Alto',
  2714. * isFun: true
  2715. * }
  2716. * };
  2717. *
  2718. * var newStuff = {
  2719. * companyName: 'Sencha Inc.',
  2720. * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
  2721. * office: {
  2722. * size: 40000,
  2723. * location: 'Redwood City'
  2724. * }
  2725. * };
  2726. *
  2727. * var sencha = Ext.Object.merge(extjs, newStuff);
  2728. *
  2729. * // extjs and sencha then equals to
  2730. * {
  2731. * companyName: 'Sencha Inc.',
  2732. * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
  2733. * isSuperCool: true
  2734. * office: {
  2735. * size: 30000,
  2736. * location: 'Redwood City'
  2737. * isFun: true
  2738. * }
  2739. * }
  2740. *
  2741. * @param {Object...} object Any number of objects to merge.
  2742. * @return {Object} merged The object that is created as a result of merging all the objects passed in.
  2743. */
  2744. merge: function(source, key, value) {
  2745. if (typeof key === 'string') {
  2746. if (value && value.constructor === Object) {
  2747. if (source[key] && source[key].constructor === Object) {
  2748. ExtObject.merge(source[key], value);
  2749. }
  2750. else {
  2751. source[key] = Ext.clone(value);
  2752. }
  2753. }
  2754. else {
  2755. source[key] = value;
  2756. }
  2757. return source;
  2758. }
  2759. var i = 1,
  2760. ln = arguments.length,
  2761. object, property;
  2762. for (; i < ln; i++) {
  2763. object = arguments[i];
  2764. for (property in object) {
  2765. if (object.hasOwnProperty(property)) {
  2766. ExtObject.merge(source, property, object[property]);
  2767. }
  2768. }
  2769. }
  2770. return source;
  2771. },
  2772. /**
  2773. * Returns the first matching key corresponding to the given value.
  2774. * If no matching value is found, null is returned.
  2775. *
  2776. * var person = {
  2777. * name: 'Jacky',
  2778. * loves: 'food'
  2779. * };
  2780. *
  2781. * alert(Ext.Object.getKey(person, 'food')); // alerts 'loves'
  2782. *
  2783. * @param {Object} object
  2784. * @param {Object} value The value to find
  2785. */
  2786. getKey: function(object, value) {
  2787. for (var property in object) {
  2788. if (object.hasOwnProperty(property) && object[property] === value) {
  2789. return property;
  2790. }
  2791. }
  2792. return null;
  2793. },
  2794. /**
  2795. * Gets all values of the given object as an array.
  2796. *
  2797. * var values = Ext.Object.getValues({
  2798. * name: 'Jacky',
  2799. * loves: 'food'
  2800. * }); // ['Jacky', 'food']
  2801. *
  2802. * @param {Object} object
  2803. * @return {Array} An array of values from the object
  2804. */
  2805. getValues: function(object) {
  2806. var values = [],
  2807. property;
  2808. for (property in object) {
  2809. if (object.hasOwnProperty(property)) {
  2810. values.push(object[property]);
  2811. }
  2812. }
  2813. return values;
  2814. },
  2815. /**
  2816. * Gets all keys of the given object as an array.
  2817. *
  2818. * var values = Ext.Object.getKeys({
  2819. * name: 'Jacky',
  2820. * loves: 'food'
  2821. * }); // ['name', 'loves']
  2822. *
  2823. * @param {Object} object
  2824. * @return {String[]} An array of keys from the object
  2825. * @method
  2826. */
  2827. getKeys: ('keys' in Object.prototype) ? Object.keys : function(object) {
  2828. var keys = [],
  2829. property;
  2830. for (property in object) {
  2831. if (object.hasOwnProperty(property)) {
  2832. keys.push(property);
  2833. }
  2834. }
  2835. return keys;
  2836. },
  2837. /**
  2838. * Gets the total number of this object's own properties
  2839. *
  2840. * var size = Ext.Object.getSize({
  2841. * name: 'Jacky',
  2842. * loves: 'food'
  2843. * }); // size equals 2
  2844. *
  2845. * @param {Object} object
  2846. * @return {Number} size
  2847. */
  2848. getSize: function(object) {
  2849. var size = 0,
  2850. property;
  2851. for (property in object) {
  2852. if (object.hasOwnProperty(property)) {
  2853. size++;
  2854. }
  2855. }
  2856. return size;
  2857. }
  2858. };
  2859. /**
  2860. * A convenient alias method for {@link Ext.Object#merge}.
  2861. *
  2862. * @member Ext
  2863. * @method merge
  2864. * @alias Ext.Object#merge
  2865. */
  2866. Ext.merge = Ext.Object.merge;
  2867. /**
  2868. * Alias for {@link Ext.Object#toQueryString}.
  2869. *
  2870. * @member Ext
  2871. * @method urlEncode
  2872. * @alias Ext.Object#toQueryString
  2873. * @deprecated 4.0.0 Use {@link Ext.Object#toQueryString} instead
  2874. */
  2875. Ext.urlEncode = function() {
  2876. var args = Ext.Array.from(arguments),
  2877. prefix = '';
  2878. // Support for the old `pre` argument
  2879. if ((typeof args[1] === 'string')) {
  2880. prefix = args[1] + '&';
  2881. args[1] = false;
  2882. }
  2883. return prefix + Ext.Object.toQueryString.apply(Ext.Object, args);
  2884. };
  2885. /**
  2886. * Alias for {@link Ext.Object#fromQueryString}.
  2887. *
  2888. * @member Ext
  2889. * @method urlDecode
  2890. * @alias Ext.Object#fromQueryString
  2891. * @deprecated 4.0.0 Use {@link Ext.Object#fromQueryString} instead
  2892. */
  2893. Ext.urlDecode = function() {
  2894. return Ext.Object.fromQueryString.apply(Ext.Object, arguments);
  2895. };
  2896. })();
  2897. /**
  2898. * @class Ext.Date
  2899. * A set of useful static methods to deal with date
  2900. * Note that if Ext.Date is required and loaded, it will copy all methods / properties to
  2901. * this object for convenience
  2902. *
  2903. * The date parsing and formatting syntax contains a subset of
  2904. * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
  2905. * supported will provide results equivalent to their PHP versions.
  2906. *
  2907. * The following is a list of all currently supported formats:
  2908. * <pre class="">
  2909. Format Description Example returned values
  2910. ------ ----------------------------------------------------------------------- -----------------------
  2911. d Day of the month, 2 digits with leading zeros 01 to 31
  2912. D A short textual representation of the day of the week Mon to Sun
  2913. j Day of the month without leading zeros 1 to 31
  2914. l A full textual representation of the day of the week Sunday to Saturday
  2915. N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
  2916. S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
  2917. w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday)
  2918. z The day of the year (starting from 0) 0 to 364 (365 in leap years)
  2919. W ISO-8601 week number of year, weeks starting on Monday 01 to 53
  2920. F A full textual representation of a month, such as January or March January to December
  2921. m Numeric representation of a month, with leading zeros 01 to 12
  2922. M A short textual representation of a month Jan to Dec
  2923. n Numeric representation of a month, without leading zeros 1 to 12
  2924. t Number of days in the given month 28 to 31
  2925. L Whether it&#39;s a leap year 1 if it is a leap year, 0 otherwise.
  2926. o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004
  2927. belongs to the previous or next year, that year is used instead)
  2928. Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
  2929. y A two digit representation of a year Examples: 99 or 03
  2930. a Lowercase Ante meridiem and Post meridiem am or pm
  2931. A Uppercase Ante meridiem and Post meridiem AM or PM
  2932. g 12-hour format of an hour without leading zeros 1 to 12
  2933. G 24-hour format of an hour without leading zeros 0 to 23
  2934. h 12-hour format of an hour with leading zeros 01 to 12
  2935. H 24-hour format of an hour with leading zeros 00 to 23
  2936. i Minutes, with leading zeros 00 to 59
  2937. s Seconds, with leading zeros 00 to 59
  2938. u Decimal fraction of a second Examples:
  2939. (minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or
  2940. 100 (i.e. 0.100s) or
  2941. 999 (i.e. 0.999s) or
  2942. 999876543210 (i.e. 0.999876543210s)
  2943. O Difference to Greenwich time (GMT) in hours and minutes Example: +1030
  2944. P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00
  2945. T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ...
  2946. Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400
  2947. c ISO 8601 date
  2948. Notes: Examples:
  2949. 1) If unspecified, the month / day defaults to the current month / day, 1991 or
  2950. the time defaults to midnight, while the timezone defaults to the 1992-10 or
  2951. browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
  2952. and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or
  2953. are optional. 1995-07-18T17:21:28-02:00 or
  2954. 2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or
  2955. least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or
  2956. of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or
  2957. Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or
  2958. date-time granularity which are supported, or see 2000-02-13T21:25:33
  2959. http://www.w3.org/TR/NOTE-datetime for more info. 2001-01-12 22:26:34
  2960. U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463
  2961. MS Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
  2962. \/Date(1238606590509+0800)\/
  2963. </pre>
  2964. *
  2965. * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
  2966. * <pre><code>
  2967. // Sample date:
  2968. // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
  2969. var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
  2970. console.log(Ext.Date.format(dt, 'Y-m-d')); // 2007-01-10
  2971. console.log(Ext.Date.format(dt, 'F j, Y, g:i a')); // January 10, 2007, 3:05 pm
  2972. 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
  2973. </code></pre>
  2974. *
  2975. * Here are some standard date/time patterns that you might find helpful. They
  2976. * are not part of the source of Ext.Date, but to use them you can simply copy this
  2977. * block of code into any script that is included after Ext.Date and they will also become
  2978. * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
  2979. * <pre><code>
  2980. Ext.Date.patterns = {
  2981. ISO8601Long:"Y-m-d H:i:s",
  2982. ISO8601Short:"Y-m-d",
  2983. ShortDate: "n/j/Y",
  2984. LongDate: "l, F d, Y",
  2985. FullDateTime: "l, F d, Y g:i:s A",
  2986. MonthDay: "F d",
  2987. ShortTime: "g:i A",
  2988. LongTime: "g:i:s A",
  2989. SortableDateTime: "Y-m-d\\TH:i:s",
  2990. UniversalSortableDateTime: "Y-m-d H:i:sO",
  2991. YearMonth: "F, Y"
  2992. };
  2993. </code></pre>
  2994. *
  2995. * Example usage:
  2996. * <pre><code>
  2997. var dt = new Date();
  2998. console.log(Ext.Date.format(dt, Ext.Date.patterns.ShortDate));
  2999. </code></pre>
  3000. * <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
  3001. * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
  3002. * @singleton
  3003. */
  3004. /*
  3005. * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
  3006. * (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)
  3007. * They generate precompiled functions from format patterns instead of parsing and
  3008. * processing each pattern every time a date is formatted. These functions are available
  3009. * on every Date object.
  3010. */
  3011. (function() {
  3012. // create private copy of Ext's Ext.util.Format.format() method
  3013. // - to remove unnecessary dependency
  3014. // - to resolve namespace conflict with MS-Ajax's implementation
  3015. function xf(format) {
  3016. var args = Array.prototype.slice.call(arguments, 1);
  3017. return format.replace(/\{(\d+)\}/g, function(m, i) {
  3018. return args[i];
  3019. });
  3020. }
  3021. Ext.Date = {
  3022. /**
  3023. * Returns the current timestamp
  3024. * @return {Date} The current timestamp
  3025. * @method
  3026. */
  3027. now: Date.now || function() {
  3028. return +new Date();
  3029. },
  3030. /**
  3031. * @private
  3032. * Private for now
  3033. */
  3034. toString: function(date) {
  3035. var pad = Ext.String.leftPad;
  3036. return date.getFullYear() + "-"
  3037. + pad(date.getMonth() + 1, 2, '0') + "-"
  3038. + pad(date.getDate(), 2, '0') + "T"
  3039. + pad(date.getHours(), 2, '0') + ":"
  3040. + pad(date.getMinutes(), 2, '0') + ":"
  3041. + pad(date.getSeconds(), 2, '0');
  3042. },
  3043. /**
  3044. * Returns the number of milliseconds between two dates
  3045. * @param {Date} dateA The first date
  3046. * @param {Date} dateB (optional) The second date, defaults to now
  3047. * @return {Number} The difference in milliseconds
  3048. */
  3049. getElapsed: function(dateA, dateB) {
  3050. return Math.abs(dateA - (dateB || new Date()));
  3051. },
  3052. /**
  3053. * Global flag which determines if strict date parsing should be used.
  3054. * Strict date parsing will not roll-over invalid dates, which is the
  3055. * default behaviour of javascript Date objects.
  3056. * (see {@link #parse} for more information)
  3057. * Defaults to <tt>false</tt>.
  3058. * @type Boolean
  3059. */
  3060. useStrict: false,
  3061. // private
  3062. formatCodeToRegex: function(character, currentGroup) {
  3063. // Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below)
  3064. var p = utilDate.parseCodes[character];
  3065. if (p) {
  3066. p = typeof p == 'function'? p() : p;
  3067. utilDate.parseCodes[character] = p; // reassign function result to prevent repeated execution
  3068. }
  3069. return p ? Ext.applyIf({
  3070. c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
  3071. }, p) : {
  3072. g: 0,
  3073. c: null,
  3074. s: Ext.String.escapeRegex(character) // treat unrecognised characters as literals
  3075. };
  3076. },
  3077. /**
  3078. * <p>An object hash in which each property is a date parsing function. The property name is the
  3079. * format string which that function parses.</p>
  3080. * <p>This object is automatically populated with date parsing functions as
  3081. * date formats are requested for Ext standard formatting strings.</p>
  3082. * <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
  3083. * may be used as a format string to {@link #parse}.<p>
  3084. * <p>Example:</p><pre><code>
  3085. Ext.Date.parseFunctions['x-date-format'] = myDateParser;
  3086. </code></pre>
  3087. * <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
  3088. * <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
  3089. * <li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
  3090. * (i.e. prevent javascript Date "rollover") (The default must be false).
  3091. * Invalid date strings should return null when parsed.</div></li>
  3092. * </ul></div></p>
  3093. * <p>To enable Dates to also be <i>formatted</i> according to that format, a corresponding
  3094. * formatting function must be placed into the {@link #formatFunctions} property.
  3095. * @property parseFunctions
  3096. * @type Object
  3097. */
  3098. parseFunctions: {
  3099. "MS": function(input, strict) {
  3100. // note: the timezone offset is ignored since the MS Ajax server sends
  3101. // a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
  3102. var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/');
  3103. var r = (input || '').match(re);
  3104. return r? new Date(((r[1] || '') + r[2]) * 1) : null;
  3105. }
  3106. },
  3107. parseRegexes: [],
  3108. /**
  3109. * <p>An object hash in which each property is a date formatting function. The property name is the
  3110. * format string which corresponds to the produced formatted date string.</p>
  3111. * <p>This object is automatically populated with date formatting functions as
  3112. * date formats are requested for Ext standard formatting strings.</p>
  3113. * <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
  3114. * may be used as a format string to {@link #format}. Example:</p><pre><code>
  3115. Ext.Date.formatFunctions['x-date-format'] = myDateFormatter;
  3116. </code></pre>
  3117. * <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>
  3118. * <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
  3119. * </ul></div></p>
  3120. * <p>To enable date strings to also be <i>parsed</i> according to that format, a corresponding
  3121. * parsing function must be placed into the {@link #parseFunctions} property.
  3122. * @property formatFunctions
  3123. * @type Object
  3124. */
  3125. formatFunctions: {
  3126. "MS": function() {
  3127. // UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF))
  3128. return '\\/Date(' + this.getTime() + ')\\/';
  3129. }
  3130. },
  3131. y2kYear : 50,
  3132. /**
  3133. * Date interval constant
  3134. * @type String
  3135. */
  3136. MILLI : "ms",
  3137. /**
  3138. * Date interval constant
  3139. * @type String
  3140. */
  3141. SECOND : "s",
  3142. /**
  3143. * Date interval constant
  3144. * @type String
  3145. */
  3146. MINUTE : "mi",
  3147. /** Date interval constant
  3148. * @type String
  3149. */
  3150. HOUR : "h",
  3151. /**
  3152. * Date interval constant
  3153. * @type String
  3154. */
  3155. DAY : "d",
  3156. /**
  3157. * Date interval constant
  3158. * @type String
  3159. */
  3160. MONTH : "mo",
  3161. /**
  3162. * Date interval constant
  3163. * @type String
  3164. */
  3165. YEAR : "y",
  3166. /**
  3167. * <p>An object hash containing default date values used during date parsing.</p>
  3168. * <p>The following properties are available:<div class="mdetail-params"><ul>
  3169. * <li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
  3170. * <li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
  3171. * <li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
  3172. * <li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
  3173. * <li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
  3174. * <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
  3175. * <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
  3176. * </ul></div></p>
  3177. * <p>Override these properties to customize the default date values used by the {@link #parse} method.</p>
  3178. * <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt>
  3179. * and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect.
  3180. * It is the responsiblity of the developer to account for this.</b></p>
  3181. * Example Usage:
  3182. * <pre><code>
  3183. // set default day value to the first day of the month
  3184. Ext.Date.defaults.d = 1;
  3185. // parse a February date string containing only year and month values.
  3186. // setting the default day value to 1 prevents weird date rollover issues
  3187. // when attempting to parse the following date string on, for example, March 31st 2009.
  3188. Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
  3189. </code></pre>
  3190. * @property defaults
  3191. * @type Object
  3192. */
  3193. defaults: {},
  3194. /**
  3195. * @property {String[]} dayNames
  3196. * An array of textual day names.
  3197. * Override these values for international dates.
  3198. * Example:
  3199. * <pre><code>
  3200. Ext.Date.dayNames = [
  3201. 'SundayInYourLang',
  3202. 'MondayInYourLang',
  3203. ...
  3204. ];
  3205. </code></pre>
  3206. */
  3207. dayNames : [
  3208. "Sunday",
  3209. "Monday",
  3210. "Tuesday",
  3211. "Wednesday",
  3212. "Thursday",
  3213. "Friday",
  3214. "Saturday"
  3215. ],
  3216. /**
  3217. * @property {String[]} monthNames
  3218. * An array of textual month names.
  3219. * Override these values for international dates.
  3220. * Example:
  3221. * <pre><code>
  3222. Ext.Date.monthNames = [
  3223. 'JanInYourLang',
  3224. 'FebInYourLang',
  3225. ...
  3226. ];
  3227. </code></pre>
  3228. */
  3229. monthNames : [
  3230. "January",
  3231. "February",
  3232. "March",
  3233. "April",
  3234. "May",
  3235. "June",
  3236. "July",
  3237. "August",
  3238. "September",
  3239. "October",
  3240. "November",
  3241. "December"
  3242. ],
  3243. /**
  3244. * @property {Object} monthNumbers
  3245. * An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).
  3246. * Override these values for international dates.
  3247. * Example:
  3248. * <pre><code>
  3249. Ext.Date.monthNumbers = {
  3250. 'ShortJanNameInYourLang':0,
  3251. 'ShortFebNameInYourLang':1,
  3252. ...
  3253. };
  3254. </code></pre>
  3255. */
  3256. monthNumbers : {
  3257. Jan:0,
  3258. Feb:1,
  3259. Mar:2,
  3260. Apr:3,
  3261. May:4,
  3262. Jun:5,
  3263. Jul:6,
  3264. Aug:7,
  3265. Sep:8,
  3266. Oct:9,
  3267. Nov:10,
  3268. Dec:11
  3269. },
  3270. /**
  3271. * @property {String} defaultFormat
  3272. * <p>The date format string that the {@link Ext.util.Format#dateRenderer}
  3273. * and {@link Ext.util.Format#date} functions use. See {@link Ext.Date} for details.</p>
  3274. * <p>This may be overridden in a locale file.</p>
  3275. */
  3276. defaultFormat : "m/d/Y",
  3277. /**
  3278. * Get the short month name for the given month number.
  3279. * Override this function for international dates.
  3280. * @param {Number} month A zero-based javascript month number.
  3281. * @return {String} The short month name.
  3282. */
  3283. getShortMonthName : function(month) {
  3284. return utilDate.monthNames[month].substring(0, 3);
  3285. },
  3286. /**
  3287. * Get the short day name for the given day number.
  3288. * Override this function for international dates.
  3289. * @param {Number} day A zero-based javascript day number.
  3290. * @return {String} The short day name.
  3291. */
  3292. getShortDayName : function(day) {
  3293. return utilDate.dayNames[day].substring(0, 3);
  3294. },
  3295. /**
  3296. * Get the zero-based javascript month number for the given short/full month name.
  3297. * Override this function for international dates.
  3298. * @param {String} name The short/full month name.
  3299. * @return {Number} The zero-based javascript month number.
  3300. */
  3301. getMonthNumber : function(name) {
  3302. // handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive)
  3303. return utilDate.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
  3304. },
  3305. /**
  3306. * Checks if the specified format contains hour information
  3307. * @param {String} format The format to check
  3308. * @return {Boolean} True if the format contains hour information
  3309. * @method
  3310. */
  3311. formatContainsHourInfo : (function(){
  3312. var stripEscapeRe = /(\\.)/g,
  3313. hourInfoRe = /([gGhHisucUOPZ]|MS)/;
  3314. return function(format){
  3315. return hourInfoRe.test(format.replace(stripEscapeRe, ''));
  3316. };
  3317. })(),
  3318. /**
  3319. * Checks if the specified format contains information about
  3320. * anything other than the time.
  3321. * @param {String} format The format to check
  3322. * @return {Boolean} True if the format contains information about
  3323. * date/day information.
  3324. * @method
  3325. */
  3326. formatContainsDateInfo : (function(){
  3327. var stripEscapeRe = /(\\.)/g,
  3328. dateInfoRe = /([djzmnYycU]|MS)/;
  3329. return function(format){
  3330. return dateInfoRe.test(format.replace(stripEscapeRe, ''));
  3331. };
  3332. })(),
  3333. /**
  3334. * The base format-code to formatting-function hashmap used by the {@link #format} method.
  3335. * Formatting functions are strings (or functions which return strings) which
  3336. * will return the appropriate value when evaluated in the context of the Date object
  3337. * from which the {@link #format} method is called.
  3338. * Add to / override these mappings for custom date formatting.
  3339. * Note: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found.
  3340. * Example:
  3341. * <pre><code>
  3342. Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
  3343. console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
  3344. </code></pre>
  3345. * @type Object
  3346. */
  3347. formatCodes : {
  3348. d: "Ext.String.leftPad(this.getDate(), 2, '0')",
  3349. D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name
  3350. j: "this.getDate()",
  3351. l: "Ext.Date.dayNames[this.getDay()]",
  3352. N: "(this.getDay() ? this.getDay() : 7)",
  3353. S: "Ext.Date.getSuffix(this)",
  3354. w: "this.getDay()",
  3355. z: "Ext.Date.getDayOfYear(this)",
  3356. W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')",
  3357. F: "Ext.Date.monthNames[this.getMonth()]",
  3358. m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')",
  3359. M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name
  3360. n: "(this.getMonth() + 1)",
  3361. t: "Ext.Date.getDaysInMonth(this)",
  3362. L: "(Ext.Date.isLeapYear(this) ? 1 : 0)",
  3363. o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))",
  3364. Y: "Ext.String.leftPad(this.getFullYear(), 4, '0')",
  3365. y: "('' + this.getFullYear()).substring(2, 4)",
  3366. a: "(this.getHours() < 12 ? 'am' : 'pm')",
  3367. A: "(this.getHours() < 12 ? 'AM' : 'PM')",
  3368. g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
  3369. G: "this.getHours()",
  3370. h: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
  3371. H: "Ext.String.leftPad(this.getHours(), 2, '0')",
  3372. i: "Ext.String.leftPad(this.getMinutes(), 2, '0')",
  3373. s: "Ext.String.leftPad(this.getSeconds(), 2, '0')",
  3374. u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')",
  3375. O: "Ext.Date.getGMTOffset(this)",
  3376. P: "Ext.Date.getGMTOffset(this, true)",
  3377. T: "Ext.Date.getTimezone(this)",
  3378. Z: "(this.getTimezoneOffset() * -60)",
  3379. c: function() { // ISO-8601 -- GMT format
  3380. for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
  3381. var e = c.charAt(i);
  3382. code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal
  3383. }
  3384. return code.join(" + ");
  3385. },
  3386. /*
  3387. c: function() { // ISO-8601 -- UTC format
  3388. return [
  3389. "this.getUTCFullYear()", "'-'",
  3390. "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
  3391. "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')",
  3392. "'T'",
  3393. "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'",
  3394. "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
  3395. "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')",
  3396. "'Z'"
  3397. ].join(" + ");
  3398. },
  3399. */
  3400. U: "Math.round(this.getTime() / 1000)"
  3401. },
  3402. /**
  3403. * Checks if the passed Date parameters will cause a javascript Date "rollover".
  3404. * @param {Number} year 4-digit year
  3405. * @param {Number} month 1-based month-of-year
  3406. * @param {Number} day Day of month
  3407. * @param {Number} hour (optional) Hour
  3408. * @param {Number} minute (optional) Minute
  3409. * @param {Number} second (optional) Second
  3410. * @param {Number} millisecond (optional) Millisecond
  3411. * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise.
  3412. */
  3413. isValid : function(y, m, d, h, i, s, ms) {
  3414. // setup defaults
  3415. h = h || 0;
  3416. i = i || 0;
  3417. s = s || 0;
  3418. ms = ms || 0;
  3419. // Special handling for year < 100
  3420. var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.YEAR, y < 100 ? y - 100 : 0);
  3421. return y == dt.getFullYear() &&
  3422. m == dt.getMonth() + 1 &&
  3423. d == dt.getDate() &&
  3424. h == dt.getHours() &&
  3425. i == dt.getMinutes() &&
  3426. s == dt.getSeconds() &&
  3427. ms == dt.getMilliseconds();
  3428. },
  3429. /**
  3430. * Parses the passed string using the specified date format.
  3431. * Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
  3432. * The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
  3433. * which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash,
  3434. * the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
  3435. * Keep in mind that the input date string must precisely match the specified format string
  3436. * in order for the parse operation to be successful (failed parse operations return a null value).
  3437. * <p>Example:</p><pre><code>
  3438. //dt = Fri May 25 2007 (current date)
  3439. var dt = new Date();
  3440. //dt = Thu May 25 2006 (today&#39;s month/day in 2006)
  3441. dt = Ext.Date.parse("2006", "Y");
  3442. //dt = Sun Jan 15 2006 (all date parts specified)
  3443. dt = Ext.Date.parse("2006-01-15", "Y-m-d");
  3444. //dt = Sun Jan 15 2006 15:20:01
  3445. dt = Ext.Date.parse("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
  3446. // attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
  3447. dt = Ext.Date.parse("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
  3448. </code></pre>
  3449. * @param {String} input The raw date string.
  3450. * @param {String} format The expected date string format.
  3451. * @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover")
  3452. (defaults to false). Invalid date strings will return null when parsed.
  3453. * @return {Date} The parsed Date.
  3454. */
  3455. parse : function(input, format, strict) {
  3456. var p = utilDate.parseFunctions;
  3457. if (p[format] == null) {
  3458. utilDate.createParser(format);
  3459. }
  3460. return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict);
  3461. },
  3462. // Backwards compat
  3463. parseDate: function(input, format, strict){
  3464. return utilDate.parse(input, format, strict);
  3465. },
  3466. // private
  3467. getFormatCode : function(character) {
  3468. var f = utilDate.formatCodes[character];
  3469. if (f) {
  3470. f = typeof f == 'function'? f() : f;
  3471. utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution
  3472. }
  3473. // note: unknown characters are treated as literals
  3474. return f || ("'" + Ext.String.escape(character) + "'");
  3475. },
  3476. // private
  3477. createFormat : function(format) {
  3478. var code = [],
  3479. special = false,
  3480. ch = '';
  3481. for (var i = 0; i < format.length; ++i) {
  3482. ch = format.charAt(i);
  3483. if (!special && ch == "\\") {
  3484. special = true;
  3485. } else if (special) {
  3486. special = false;
  3487. code.push("'" + Ext.String.escape(ch) + "'");
  3488. } else {
  3489. code.push(utilDate.getFormatCode(ch));
  3490. }
  3491. }
  3492. utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+'));
  3493. },
  3494. // private
  3495. createParser : (function() {
  3496. var code = [
  3497. "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
  3498. "def = Ext.Date.defaults,",
  3499. "results = String(input).match(Ext.Date.parseRegexes[{0}]);", // either null, or an array of matched strings
  3500. "if(results){",
  3501. "{1}",
  3502. "if(u != null){", // i.e. unix time is defined
  3503. "v = new Date(u * 1000);", // give top priority to UNIX time
  3504. "}else{",
  3505. // create Date object representing midnight of the current day;
  3506. // this will provide us with our date defaults
  3507. // (note: clearTime() handles Daylight Saving Time automatically)
  3508. "dt = Ext.Date.clearTime(new Date);",
  3509. // date calculations (note: these calculations create a dependency on Ext.Number.from())
  3510. "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));",
  3511. "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));",
  3512. "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));",
  3513. // time calculations (note: these calculations create a dependency on Ext.Number.from())
  3514. "h = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));",
  3515. "i = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));",
  3516. "s = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));",
  3517. "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));",
  3518. "if(z >= 0 && y >= 0){",
  3519. // both the year and zero-based day of year are defined and >= 0.
  3520. // these 2 values alone provide sufficient info to create a full date object
  3521. // create Date object representing January 1st for the given year
  3522. // handle years < 100 appropriately
  3523. "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
  3524. // then add day of year, checking for Date "rollover" if necessary
  3525. "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);",
  3526. "}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
  3527. "v = null;", // invalid date, so return null
  3528. "}else{",
  3529. // plain old Date object
  3530. // handle years < 100 properly
  3531. "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
  3532. "}",
  3533. "}",
  3534. "}",
  3535. "if(v){",
  3536. // favour UTC offset over GMT offset
  3537. "if(zz != null){",
  3538. // reset to UTC, then add offset
  3539. "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
  3540. "}else if(o){",
  3541. // reset to GMT, then add offset
  3542. "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
  3543. "}",
  3544. "}",
  3545. "return v;"
  3546. ].join('\n');
  3547. return function(format) {
  3548. var regexNum = utilDate.parseRegexes.length,
  3549. currentGroup = 1,
  3550. calc = [],
  3551. regex = [],
  3552. special = false,
  3553. ch = "";
  3554. for (var i = 0; i < format.length; ++i) {
  3555. ch = format.charAt(i);
  3556. if (!special && ch == "\\") {
  3557. special = true;
  3558. } else if (special) {
  3559. special = false;
  3560. regex.push(Ext.String.escape(ch));
  3561. } else {
  3562. var obj = utilDate.formatCodeToRegex(ch, currentGroup);
  3563. currentGroup += obj.g;
  3564. regex.push(obj.s);
  3565. if (obj.g && obj.c) {
  3566. calc.push(obj.c);
  3567. }
  3568. }
  3569. }
  3570. utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i');
  3571. utilDate.parseFunctions[format] = Ext.functionFactory("input", "strict", xf(code, regexNum, calc.join('')));
  3572. };
  3573. })(),
  3574. // private
  3575. parseCodes : {
  3576. /*
  3577. * Notes:
  3578. * g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)
  3579. * c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)
  3580. * s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'
  3581. */
  3582. d: {
  3583. g:1,
  3584. c:"d = parseInt(results[{0}], 10);\n",
  3585. s:"(\\d{2})" // day of month with leading zeroes (01 - 31)
  3586. },
  3587. j: {
  3588. g:1,
  3589. c:"d = parseInt(results[{0}], 10);\n",
  3590. s:"(\\d{1,2})" // day of month without leading zeroes (1 - 31)
  3591. },
  3592. D: function() {
  3593. for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names
  3594. return {
  3595. g:0,
  3596. c:null,
  3597. s:"(?:" + a.join("|") +")"
  3598. };
  3599. },
  3600. l: function() {
  3601. return {
  3602. g:0,
  3603. c:null,
  3604. s:"(?:" + utilDate.dayNames.join("|") + ")"
  3605. };
  3606. },
  3607. N: {
  3608. g:0,
  3609. c:null,
  3610. s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))
  3611. },
  3612. S: {
  3613. g:0,
  3614. c:null,
  3615. s:"(?:st|nd|rd|th)"
  3616. },
  3617. w: {
  3618. g:0,
  3619. c:null,
  3620. s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday))
  3621. },
  3622. z: {
  3623. g:1,
  3624. c:"z = parseInt(results[{0}], 10);\n",
  3625. s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years))
  3626. },
  3627. W: {
  3628. g:0,
  3629. c:null,
  3630. s:"(?:\\d{2})" // ISO-8601 week number (with leading zero)
  3631. },
  3632. F: function() {
  3633. return {
  3634. g:1,
  3635. c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
  3636. s:"(" + utilDate.monthNames.join("|") + ")"
  3637. };
  3638. },
  3639. M: function() {
  3640. for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names
  3641. return Ext.applyIf({
  3642. s:"(" + a.join("|") + ")"
  3643. }, utilDate.formatCodeToRegex("F"));
  3644. },
  3645. m: {
  3646. g:1,
  3647. c:"m = parseInt(results[{0}], 10) - 1;\n",
  3648. s:"(\\d{2})" // month number with leading zeros (01 - 12)
  3649. },
  3650. n: {
  3651. g:1,
  3652. c:"m = parseInt(results[{0}], 10) - 1;\n",
  3653. s:"(\\d{1,2})" // month number without leading zeros (1 - 12)
  3654. },
  3655. t: {
  3656. g:0,
  3657. c:null,
  3658. s:"(?:\\d{2})" // no. of days in the month (28 - 31)
  3659. },
  3660. L: {
  3661. g:0,
  3662. c:null,
  3663. s:"(?:1|0)"
  3664. },
  3665. o: function() {
  3666. return utilDate.formatCodeToRegex("Y");
  3667. },
  3668. Y: {
  3669. g:1,
  3670. c:"y = parseInt(results[{0}], 10);\n",
  3671. s:"(\\d{4})" // 4-digit year
  3672. },
  3673. y: {
  3674. g:1,
  3675. c:"var ty = parseInt(results[{0}], 10);\n"
  3676. + "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
  3677. s:"(\\d{1,2})"
  3678. },
  3679. /*
  3680. * In the am/pm parsing routines, we allow both upper and lower case
  3681. * even though it doesn't exactly match the spec. It gives much more flexibility
  3682. * in being able to specify case insensitive regexes.
  3683. */
  3684. a: {
  3685. g:1,
  3686. c:"if (/(am)/i.test(results[{0}])) {\n"
  3687. + "if (!h || h == 12) { h = 0; }\n"
  3688. + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
  3689. s:"(am|pm|AM|PM)"
  3690. },
  3691. A: {
  3692. g:1,
  3693. c:"if (/(am)/i.test(results[{0}])) {\n"
  3694. + "if (!h || h == 12) { h = 0; }\n"
  3695. + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
  3696. s:"(AM|PM|am|pm)"
  3697. },
  3698. g: function() {
  3699. return utilDate.formatCodeToRegex("G");
  3700. },
  3701. G: {
  3702. g:1,
  3703. c:"h = parseInt(results[{0}], 10);\n",
  3704. s:"(\\d{1,2})" // 24-hr format of an hour without leading zeroes (0 - 23)
  3705. },
  3706. h: function() {
  3707. return utilDate.formatCodeToRegex("H");
  3708. },
  3709. H: {
  3710. g:1,
  3711. c:"h = parseInt(results[{0}], 10);\n",
  3712. s:"(\\d{2})" // 24-hr format of an hour with leading zeroes (00 - 23)
  3713. },
  3714. i: {
  3715. g:1,
  3716. c:"i = parseInt(results[{0}], 10);\n",
  3717. s:"(\\d{2})" // minutes with leading zeros (00 - 59)
  3718. },
  3719. s: {
  3720. g:1,
  3721. c:"s = parseInt(results[{0}], 10);\n",
  3722. s:"(\\d{2})" // seconds with leading zeros (00 - 59)
  3723. },
  3724. u: {
  3725. g:1,
  3726. c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",
  3727. s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
  3728. },
  3729. O: {
  3730. g:1,
  3731. c:[
  3732. "o = results[{0}];",
  3733. "var sn = o.substring(0,1),", // get + / - sign
  3734. "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
  3735. "mn = o.substring(3,5) % 60;", // get minutes
  3736. "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
  3737. ].join("\n"),
  3738. s: "([+\-]\\d{4})" // GMT offset in hrs and mins
  3739. },
  3740. P: {
  3741. g:1,
  3742. c:[
  3743. "o = results[{0}];",
  3744. "var sn = o.substring(0,1),", // get + / - sign
  3745. "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
  3746. "mn = o.substring(4,6) % 60;", // get minutes
  3747. "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
  3748. ].join("\n"),
  3749. s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
  3750. },
  3751. T: {
  3752. g:0,
  3753. c:null,
  3754. s:"[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars
  3755. },
  3756. Z: {
  3757. g:1,
  3758. c:"zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400
  3759. + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n",
  3760. s:"([+\-]?\\d{1,5})" // leading '+' sign is optional for UTC offset
  3761. },
  3762. c: function() {
  3763. var calc = [],
  3764. arr = [
  3765. utilDate.formatCodeToRegex("Y", 1), // year
  3766. utilDate.formatCodeToRegex("m", 2), // month
  3767. utilDate.formatCodeToRegex("d", 3), // day
  3768. utilDate.formatCodeToRegex("h", 4), // hour
  3769. utilDate.formatCodeToRegex("i", 5), // minute
  3770. utilDate.formatCodeToRegex("s", 6), // second
  3771. {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)
  3772. {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
  3773. "if(results[8]) {", // timezone specified
  3774. "if(results[8] == 'Z'){",
  3775. "zz = 0;", // UTC
  3776. "}else if (results[8].indexOf(':') > -1){",
  3777. utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator
  3778. "}else{",
  3779. utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator
  3780. "}",
  3781. "}"
  3782. ].join('\n')}
  3783. ];
  3784. for (var i = 0, l = arr.length; i < l; ++i) {
  3785. calc.push(arr[i].c);
  3786. }
  3787. return {
  3788. g:1,
  3789. c:calc.join(""),
  3790. s:[
  3791. arr[0].s, // year (required)
  3792. "(?:", "-", arr[1].s, // month (optional)
  3793. "(?:", "-", arr[2].s, // day (optional)
  3794. "(?:",
  3795. "(?:T| )?", // time delimiter -- either a "T" or a single blank space
  3796. 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
  3797. "(?::", arr[5].s, ")?", // seconds (optional)
  3798. "(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional)
  3799. "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional)
  3800. ")?",
  3801. ")?",
  3802. ")?"
  3803. ].join("")
  3804. };
  3805. },
  3806. U: {
  3807. g:1,
  3808. c:"u = parseInt(results[{0}], 10);\n",
  3809. s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
  3810. }
  3811. },
  3812. //Old Ext.Date prototype methods.
  3813. // private
  3814. dateFormat: function(date, format) {
  3815. return utilDate.format(date, format);
  3816. },
  3817. /**
  3818. * Formats a date given the supplied format string.
  3819. * @param {Date} date The date to format
  3820. * @param {String} format The format string
  3821. * @return {String} The formatted date
  3822. */
  3823. format: function(date, format) {
  3824. if (utilDate.formatFunctions[format] == null) {
  3825. utilDate.createFormat(format);
  3826. }
  3827. var result = utilDate.formatFunctions[format].call(date);
  3828. return result + '';
  3829. },
  3830. /**
  3831. * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
  3832. *
  3833. * Note: The date string returned by the javascript Date object's toString() method varies
  3834. * between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
  3835. * For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
  3836. * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
  3837. * (which may or may not be present), failing which it proceeds to get the timezone abbreviation
  3838. * from the GMT offset portion of the date string.
  3839. * @param {Date} date The date
  3840. * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
  3841. */
  3842. getTimezone : function(date) {
  3843. // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
  3844. //
  3845. // Opera : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
  3846. // 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)
  3847. // FF : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone
  3848. // IE : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev
  3849. // IE : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev
  3850. //
  3851. // this crazy regex attempts to guess the correct timezone abbreviation despite these differences.
  3852. // step 1: (?:\((.*)\) -- find timezone in parentheses
  3853. // 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
  3854. // step 3: remove all non uppercase characters found in step 1 and 2
  3855. return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
  3856. },
  3857. /**
  3858. * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
  3859. * @param {Date} date The date
  3860. * @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
  3861. * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
  3862. */
  3863. getGMTOffset : function(date, colon) {
  3864. var offset = date.getTimezoneOffset();
  3865. return (offset > 0 ? "-" : "+")
  3866. + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0")
  3867. + (colon ? ":" : "")
  3868. + Ext.String.leftPad(Math.abs(offset % 60), 2, "0");
  3869. },
  3870. /**
  3871. * Get the numeric day number of the year, adjusted for leap year.
  3872. * @param {Date} date The date
  3873. * @return {Number} 0 to 364 (365 in leap years).
  3874. */
  3875. getDayOfYear: function(date) {
  3876. var num = 0,
  3877. d = Ext.Date.clone(date),
  3878. m = date.getMonth(),
  3879. i;
  3880. for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
  3881. num += utilDate.getDaysInMonth(d);
  3882. }
  3883. return num + date.getDate() - 1;
  3884. },
  3885. /**
  3886. * Get the numeric ISO-8601 week number of the year.
  3887. * (equivalent to the format specifier 'W', but without a leading zero).
  3888. * @param {Date} date The date
  3889. * @return {Number} 1 to 53
  3890. * @method
  3891. */
  3892. getWeekOfYear : (function() {
  3893. // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
  3894. var ms1d = 864e5, // milliseconds in a day
  3895. ms7d = 7 * ms1d; // milliseconds in a week
  3896. return function(date) { // return a closure so constants get calculated only once
  3897. var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number
  3898. AWN = Math.floor(DC3 / 7), // an Absolute Week Number
  3899. Wyr = new Date(AWN * ms7d).getUTCFullYear();
  3900. return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
  3901. };
  3902. })(),
  3903. /**
  3904. * Checks if the current date falls within a leap year.
  3905. * @param {Date} date The date
  3906. * @return {Boolean} True if the current date falls within a leap year, false otherwise.
  3907. */
  3908. isLeapYear : function(date) {
  3909. var year = date.getFullYear();
  3910. return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
  3911. },
  3912. /**
  3913. * Get the first day of the current month, adjusted for leap year. The returned value
  3914. * is the numeric day index within the week (0-6) which can be used in conjunction with
  3915. * the {@link #monthNames} array to retrieve the textual day name.
  3916. * Example:
  3917. * <pre><code>
  3918. var dt = new Date('1/10/2007'),
  3919. firstDay = Ext.Date.getFirstDayOfMonth(dt);
  3920. console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
  3921. * </code></pre>
  3922. * @param {Date} date The date
  3923. * @return {Number} The day number (0-6).
  3924. */
  3925. getFirstDayOfMonth : function(date) {
  3926. var day = (date.getDay() - (date.getDate() - 1)) % 7;
  3927. return (day < 0) ? (day + 7) : day;
  3928. },
  3929. /**
  3930. * Get the last day of the current month, adjusted for leap year. The returned value
  3931. * is the numeric day index within the week (0-6) which can be used in conjunction with
  3932. * the {@link #monthNames} array to retrieve the textual day name.
  3933. * Example:
  3934. * <pre><code>
  3935. var dt = new Date('1/10/2007'),
  3936. lastDay = Ext.Date.getLastDayOfMonth(dt);
  3937. console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
  3938. * </code></pre>
  3939. * @param {Date} date The date
  3940. * @return {Number} The day number (0-6).
  3941. */
  3942. getLastDayOfMonth : function(date) {
  3943. return utilDate.getLastDateOfMonth(date).getDay();
  3944. },
  3945. /**
  3946. * Get the date of the first day of the month in which this date resides.
  3947. * @param {Date} date The date
  3948. * @return {Date}
  3949. */
  3950. getFirstDateOfMonth : function(date) {
  3951. return new Date(date.getFullYear(), date.getMonth(), 1);
  3952. },
  3953. /**
  3954. * Get the date of the last day of the month in which this date resides.
  3955. * @param {Date} date The date
  3956. * @return {Date}
  3957. */
  3958. getLastDateOfMonth : function(date) {
  3959. return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date));
  3960. },
  3961. /**
  3962. * Get the number of days in the current month, adjusted for leap year.
  3963. * @param {Date} date The date
  3964. * @return {Number} The number of days in the month.
  3965. * @method
  3966. */
  3967. getDaysInMonth: (function() {
  3968. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  3969. return function(date) { // return a closure for efficiency
  3970. var m = date.getMonth();
  3971. return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m];
  3972. };
  3973. })(),
  3974. /**
  3975. * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
  3976. * @param {Date} date The date
  3977. * @return {String} 'st, 'nd', 'rd' or 'th'.
  3978. */
  3979. getSuffix : function(date) {
  3980. switch (date.getDate()) {
  3981. case 1:
  3982. case 21:
  3983. case 31:
  3984. return "st";
  3985. case 2:
  3986. case 22:
  3987. return "nd";
  3988. case 3:
  3989. case 23:
  3990. return "rd";
  3991. default:
  3992. return "th";
  3993. }
  3994. },
  3995. /**
  3996. * Creates and returns a new Date instance with the exact same date value as the called instance.
  3997. * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
  3998. * variable will also be changed. When the intention is to create a new variable that will not
  3999. * modify the original instance, you should create a clone.
  4000. *
  4001. * Example of correctly cloning a date:
  4002. * <pre><code>
  4003. //wrong way:
  4004. var orig = new Date('10/1/2006');
  4005. var copy = orig;
  4006. copy.setDate(5);
  4007. console.log(orig); //returns 'Thu Oct 05 2006'!
  4008. //correct way:
  4009. var orig = new Date('10/1/2006'),
  4010. copy = Ext.Date.clone(orig);
  4011. copy.setDate(5);
  4012. console.log(orig); //returns 'Thu Oct 01 2006'
  4013. * </code></pre>
  4014. * @param {Date} date The date
  4015. * @return {Date} The new Date instance.
  4016. */
  4017. clone : function(date) {
  4018. return new Date(date.getTime());
  4019. },
  4020. /**
  4021. * Checks if the current date is affected by Daylight Saving Time (DST).
  4022. * @param {Date} date The date
  4023. * @return {Boolean} True if the current date is affected by DST.
  4024. */
  4025. isDST : function(date) {
  4026. // adapted from http://sencha.com/forum/showthread.php?p=247172#post247172
  4027. // courtesy of @geoffrey.mcgill
  4028. return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset();
  4029. },
  4030. /**
  4031. * Attempts to clear all time information from this Date by setting the time to midnight of the same day,
  4032. * automatically adjusting for Daylight Saving Time (DST) where applicable.
  4033. * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
  4034. * @param {Date} date The date
  4035. * @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
  4036. * @return {Date} this or the clone.
  4037. */
  4038. clearTime : function(date, clone) {
  4039. if (clone) {
  4040. return Ext.Date.clearTime(Ext.Date.clone(date));
  4041. }
  4042. // get current date before clearing time
  4043. var d = date.getDate();
  4044. // clear time
  4045. date.setHours(0);
  4046. date.setMinutes(0);
  4047. date.setSeconds(0);
  4048. date.setMilliseconds(0);
  4049. if (date.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
  4050. // note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
  4051. // refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule
  4052. // increment hour until cloned date == current date
  4053. for (var hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr));
  4054. date.setDate(d);
  4055. date.setHours(c.getHours());
  4056. }
  4057. return date;
  4058. },
  4059. /**
  4060. * Provides a convenient method for performing basic date arithmetic. This method
  4061. * does not modify the Date instance being called - it creates and returns
  4062. * a new Date instance containing the resulting date value.
  4063. *
  4064. * Examples:
  4065. * <pre><code>
  4066. // Basic usage:
  4067. var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
  4068. console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
  4069. // Negative values will be subtracted:
  4070. var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
  4071. console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
  4072. * </code></pre>
  4073. *
  4074. * @param {Date} date The date to modify
  4075. * @param {String} interval A valid date interval enum value.
  4076. * @param {Number} value The amount to add to the current date.
  4077. * @return {Date} The new Date instance.
  4078. */
  4079. add : function(date, interval, value) {
  4080. var d = Ext.Date.clone(date),
  4081. Date = Ext.Date;
  4082. if (!interval || value === 0) return d;
  4083. switch(interval.toLowerCase()) {
  4084. case Ext.Date.MILLI:
  4085. d.setMilliseconds(d.getMilliseconds() + value);
  4086. break;
  4087. case Ext.Date.SECOND:
  4088. d.setSeconds(d.getSeconds() + value);
  4089. break;
  4090. case Ext.Date.MINUTE:
  4091. d.setMinutes(d.getMinutes() + value);
  4092. break;
  4093. case Ext.Date.HOUR:
  4094. d.setHours(d.getHours() + value);
  4095. break;
  4096. case Ext.Date.DAY:
  4097. d.setDate(d.getDate() + value);
  4098. break;
  4099. case Ext.Date.MONTH:
  4100. var day = date.getDate();
  4101. if (day > 28) {
  4102. day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), 'mo', value)).getDate());
  4103. }
  4104. d.setDate(day);
  4105. d.setMonth(date.getMonth() + value);
  4106. break;
  4107. case Ext.Date.YEAR:
  4108. d.setFullYear(date.getFullYear() + value);
  4109. break;
  4110. }
  4111. return d;
  4112. },
  4113. /**
  4114. * Checks if a date falls on or between the given start and end dates.
  4115. * @param {Date} date The date to check
  4116. * @param {Date} start Start date
  4117. * @param {Date} end End date
  4118. * @return {Boolean} true if this date falls on or between the given start and end dates.
  4119. */
  4120. between : function(date, start, end) {
  4121. var t = date.getTime();
  4122. return start.getTime() <= t && t <= end.getTime();
  4123. },
  4124. //Maintains compatibility with old static and prototype window.Date methods.
  4125. compat: function() {
  4126. var nativeDate = window.Date,
  4127. p, u,
  4128. 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'],
  4129. proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'];
  4130. //Append statics
  4131. Ext.Array.forEach(statics, function(s) {
  4132. nativeDate[s] = utilDate[s];
  4133. });
  4134. //Append to prototype
  4135. Ext.Array.forEach(proto, function(s) {
  4136. nativeDate.prototype[s] = function() {
  4137. var args = Array.prototype.slice.call(arguments);
  4138. args.unshift(this);
  4139. return utilDate[s].apply(utilDate, args);
  4140. };
  4141. });
  4142. }
  4143. };
  4144. var utilDate = Ext.Date;
  4145. })();
  4146. /**
  4147. * @author Jacky Nguyen <jacky@sencha.com>
  4148. * @docauthor Jacky Nguyen <jacky@sencha.com>
  4149. * @class Ext.Base
  4150. *
  4151. * The root of all classes created with {@link Ext#define}.
  4152. *
  4153. * Ext.Base is the building block of all Ext classes. All classes in Ext inherit from Ext.Base.
  4154. * All prototype and static members of this class are inherited by all other classes.
  4155. */
  4156. (function(flexSetter) {
  4157. var Base = Ext.Base = function() {};
  4158. Base.prototype = {
  4159. $className: 'Ext.Base',
  4160. $class: Base,
  4161. /**
  4162. * Get the reference to the current class from which this object was instantiated. Unlike {@link Ext.Base#statics},
  4163. * `this.self` is scope-dependent and it's meant to be used for dynamic inheritance. See {@link Ext.Base#statics}
  4164. * for a detailed comparison
  4165. *
  4166. * Ext.define('My.Cat', {
  4167. * statics: {
  4168. * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
  4169. * },
  4170. *
  4171. * constructor: function() {
  4172. * alert(this.self.speciesName); / dependent on 'this'
  4173. *
  4174. * return this;
  4175. * },
  4176. *
  4177. * clone: function() {
  4178. * return new this.self();
  4179. * }
  4180. * });
  4181. *
  4182. *
  4183. * Ext.define('My.SnowLeopard', {
  4184. * extend: 'My.Cat',
  4185. * statics: {
  4186. * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
  4187. * }
  4188. * });
  4189. *
  4190. * var cat = new My.Cat(); // alerts 'Cat'
  4191. * var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard'
  4192. *
  4193. * var clone = snowLeopard.clone();
  4194. * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
  4195. *
  4196. * @type Ext.Class
  4197. * @protected
  4198. */
  4199. self: Base,
  4200. // Default constructor, simply returns `this`
  4201. constructor: function() {
  4202. return this;
  4203. },
  4204. //<feature classSystem.config>
  4205. /**
  4206. * Initialize configuration for this class. a typical example:
  4207. *
  4208. * Ext.define('My.awesome.Class', {
  4209. * // The default config
  4210. * config: {
  4211. * name: 'Awesome',
  4212. * isAwesome: true
  4213. * },
  4214. *
  4215. * constructor: function(config) {
  4216. * this.initConfig(config);
  4217. *
  4218. * return this;
  4219. * }
  4220. * });
  4221. *
  4222. * var awesome = new My.awesome.Class({
  4223. * name: 'Super Awesome'
  4224. * });
  4225. *
  4226. * alert(awesome.getName()); // 'Super Awesome'
  4227. *
  4228. * @protected
  4229. * @param {Object} config
  4230. * @return {Object} mixins The mixin prototypes as key - value pairs
  4231. */
  4232. initConfig: function(config) {
  4233. if (!this.$configInited) {
  4234. this.config = Ext.Object.merge({}, this.config || {}, config || {});
  4235. this.applyConfig(this.config);
  4236. this.$configInited = true;
  4237. }
  4238. return this;
  4239. },
  4240. /**
  4241. * @private
  4242. */
  4243. setConfig: function(config) {
  4244. this.applyConfig(config || {});
  4245. return this;
  4246. },
  4247. /**
  4248. * @private
  4249. */
  4250. applyConfig: flexSetter(function(name, value) {
  4251. var setter = 'set' + Ext.String.capitalize(name);
  4252. if (typeof this[setter] === 'function') {
  4253. this[setter].call(this, value);
  4254. }
  4255. return this;
  4256. }),
  4257. //</feature>
  4258. /**
  4259. * Call the parent's overridden method. For example:
  4260. *
  4261. * Ext.define('My.own.A', {
  4262. * constructor: function(test) {
  4263. * alert(test);
  4264. * }
  4265. * });
  4266. *
  4267. * Ext.define('My.own.B', {
  4268. * extend: 'My.own.A',
  4269. *
  4270. * constructor: function(test) {
  4271. * alert(test);
  4272. *
  4273. * this.callParent([test + 1]);
  4274. * }
  4275. * });
  4276. *
  4277. * Ext.define('My.own.C', {
  4278. * extend: 'My.own.B',
  4279. *
  4280. * constructor: function() {
  4281. * alert("Going to call parent's overriden constructor...");
  4282. *
  4283. * this.callParent(arguments);
  4284. * }
  4285. * });
  4286. *
  4287. * var a = new My.own.A(1); // alerts '1'
  4288. * var b = new My.own.B(1); // alerts '1', then alerts '2'
  4289. * var c = new My.own.C(2); // alerts "Going to call parent's overriden constructor..."
  4290. * // alerts '2', then alerts '3'
  4291. *
  4292. * @protected
  4293. * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
  4294. * from the current method, for example: `this.callParent(arguments)`
  4295. * @return {Object} Returns the result from the superclass' method
  4296. */
  4297. callParent: function(args) {
  4298. var method = this.callParent.caller,
  4299. parentClass, methodName;
  4300. if (!method.$owner) {
  4301. if (!method.caller) {
  4302. Ext.Error.raise({
  4303. sourceClass: Ext.getClassName(this),
  4304. sourceMethod: "callParent",
  4305. msg: "Attempting to call a protected method from the public scope, which is not allowed"
  4306. });
  4307. }
  4308. method = method.caller;
  4309. }
  4310. parentClass = method.$owner.superclass;
  4311. methodName = method.$name;
  4312. if (!(methodName in parentClass)) {
  4313. Ext.Error.raise({
  4314. sourceClass: Ext.getClassName(this),
  4315. sourceMethod: methodName,
  4316. msg: "this.callParent() was called but there's no such method (" + methodName +
  4317. ") found in the parent class (" + (Ext.getClassName(parentClass) || 'Object') + ")"
  4318. });
  4319. }
  4320. return parentClass[methodName].apply(this, args || []);
  4321. },
  4322. /**
  4323. * Get the reference to the class from which this object was instantiated. Note that unlike {@link Ext.Base#self},
  4324. * `this.statics()` is scope-independent and it always returns the class from which it was called, regardless of what
  4325. * `this` points to during run-time
  4326. *
  4327. * Ext.define('My.Cat', {
  4328. * statics: {
  4329. * totalCreated: 0,
  4330. * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
  4331. * },
  4332. *
  4333. * constructor: function() {
  4334. * var statics = this.statics();
  4335. *
  4336. * alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to
  4337. * // equivalent to: My.Cat.speciesName
  4338. *
  4339. * alert(this.self.speciesName); // dependent on 'this'
  4340. *
  4341. * statics.totalCreated++;
  4342. *
  4343. * return this;
  4344. * },
  4345. *
  4346. * clone: function() {
  4347. * var cloned = new this.self; // dependent on 'this'
  4348. *
  4349. * cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName
  4350. *
  4351. * return cloned;
  4352. * }
  4353. * });
  4354. *
  4355. *
  4356. * Ext.define('My.SnowLeopard', {
  4357. * extend: 'My.Cat',
  4358. *
  4359. * statics: {
  4360. * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
  4361. * },
  4362. *
  4363. * constructor: function() {
  4364. * this.callParent();
  4365. * }
  4366. * });
  4367. *
  4368. * var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat'
  4369. *
  4370. * var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'
  4371. *
  4372. * var clone = snowLeopard.clone();
  4373. * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
  4374. * alert(clone.groupName); // alerts 'Cat'
  4375. *
  4376. * alert(My.Cat.totalCreated); // alerts 3
  4377. *
  4378. * @protected
  4379. * @return {Ext.Class}
  4380. */
  4381. statics: function() {
  4382. var method = this.statics.caller,
  4383. self = this.self;
  4384. if (!method) {
  4385. return self;
  4386. }
  4387. return method.$owner;
  4388. },
  4389. /**
  4390. * Call the original method that was previously overridden with {@link Ext.Base#override}
  4391. *
  4392. * Ext.define('My.Cat', {
  4393. * constructor: function() {
  4394. * alert("I'm a cat!");
  4395. *
  4396. * return this;
  4397. * }
  4398. * });
  4399. *
  4400. * My.Cat.override({
  4401. * constructor: function() {
  4402. * alert("I'm going to be a cat!");
  4403. *
  4404. * var instance = this.callOverridden();
  4405. *
  4406. * alert("Meeeeoooowwww");
  4407. *
  4408. * return instance;
  4409. * }
  4410. * });
  4411. *
  4412. * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
  4413. * // alerts "I'm a cat!"
  4414. * // alerts "Meeeeoooowwww"
  4415. *
  4416. * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
  4417. * @return {Object} Returns the result after calling the overridden method
  4418. * @protected
  4419. */
  4420. callOverridden: function(args) {
  4421. var method = this.callOverridden.caller;
  4422. if (!method.$owner) {
  4423. Ext.Error.raise({
  4424. sourceClass: Ext.getClassName(this),
  4425. sourceMethod: "callOverridden",
  4426. msg: "Attempting to call a protected method from the public scope, which is not allowed"
  4427. });
  4428. }
  4429. if (!method.$previous) {
  4430. Ext.Error.raise({
  4431. sourceClass: Ext.getClassName(this),
  4432. sourceMethod: "callOverridden",
  4433. msg: "this.callOverridden was called in '" + method.$name +
  4434. "' but this method has never been overridden"
  4435. });
  4436. }
  4437. return method.$previous.apply(this, args || []);
  4438. },
  4439. destroy: function() {}
  4440. };
  4441. // These static properties will be copied to every newly created class with {@link Ext#define}
  4442. Ext.apply(Ext.Base, {
  4443. /**
  4444. * Create a new instance of this Class.
  4445. *
  4446. * Ext.define('My.cool.Class', {
  4447. * ...
  4448. * });
  4449. *
  4450. * My.cool.Class.create({
  4451. * someConfig: true
  4452. * });
  4453. *
  4454. * All parameters are passed to the constructor of the class.
  4455. *
  4456. * @return {Object} the created instance.
  4457. * @static
  4458. * @inheritable
  4459. */
  4460. create: function() {
  4461. return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0)));
  4462. },
  4463. /**
  4464. * @private
  4465. * @inheritable
  4466. */
  4467. own: function(name, value) {
  4468. if (typeof value == 'function') {
  4469. this.ownMethod(name, value);
  4470. }
  4471. else {
  4472. this.prototype[name] = value;
  4473. }
  4474. },
  4475. /**
  4476. * @private
  4477. * @inheritable
  4478. */
  4479. ownMethod: function(name, fn) {
  4480. var originalFn;
  4481. if (typeof fn.$owner !== 'undefined' && fn !== Ext.emptyFn) {
  4482. originalFn = fn;
  4483. fn = function() {
  4484. return originalFn.apply(this, arguments);
  4485. };
  4486. }
  4487. var className;
  4488. className = Ext.getClassName(this);
  4489. if (className) {
  4490. fn.displayName = className + '#' + name;
  4491. }
  4492. fn.$owner = this;
  4493. fn.$name = name;
  4494. this.prototype[name] = fn;
  4495. },
  4496. /**
  4497. * Add / override static properties of this class.
  4498. *
  4499. * Ext.define('My.cool.Class', {
  4500. * ...
  4501. * });
  4502. *
  4503. * My.cool.Class.addStatics({
  4504. * someProperty: 'someValue', // My.cool.Class.someProperty = 'someValue'
  4505. * method1: function() { ... }, // My.cool.Class.method1 = function() { ... };
  4506. * method2: function() { ... } // My.cool.Class.method2 = function() { ... };
  4507. * });
  4508. *
  4509. * @param {Object} members
  4510. * @return {Ext.Base} this
  4511. * @static
  4512. * @inheritable
  4513. */
  4514. addStatics: function(members) {
  4515. for (var name in members) {
  4516. if (members.hasOwnProperty(name)) {
  4517. this[name] = members[name];
  4518. }
  4519. }
  4520. return this;
  4521. },
  4522. /**
  4523. * @private
  4524. * @param {Object} members
  4525. */
  4526. addInheritableStatics: function(members) {
  4527. var inheritableStatics,
  4528. hasInheritableStatics,
  4529. prototype = this.prototype,
  4530. name, member;
  4531. inheritableStatics = prototype.$inheritableStatics;
  4532. hasInheritableStatics = prototype.$hasInheritableStatics;
  4533. if (!inheritableStatics) {
  4534. inheritableStatics = prototype.$inheritableStatics = [];
  4535. hasInheritableStatics = prototype.$hasInheritableStatics = {};
  4536. }
  4537. var className = Ext.getClassName(this);
  4538. for (name in members) {
  4539. if (members.hasOwnProperty(name)) {
  4540. member = members[name];
  4541. if (typeof member == 'function') {
  4542. member.displayName = className + '.' + name;
  4543. }
  4544. this[name] = member;
  4545. if (!hasInheritableStatics[name]) {
  4546. hasInheritableStatics[name] = true;
  4547. inheritableStatics.push(name);
  4548. }
  4549. }
  4550. }
  4551. return this;
  4552. },
  4553. /**
  4554. * Add methods / properties to the prototype of this class.
  4555. *
  4556. * Ext.define('My.awesome.Cat', {
  4557. * constructor: function() {
  4558. * ...
  4559. * }
  4560. * });
  4561. *
  4562. * My.awesome.Cat.implement({
  4563. * meow: function() {
  4564. * alert('Meowww...');
  4565. * }
  4566. * });
  4567. *
  4568. * var kitty = new My.awesome.Cat;
  4569. * kitty.meow();
  4570. *
  4571. * @param {Object} members
  4572. * @static
  4573. * @inheritable
  4574. */
  4575. implement: function(members) {
  4576. var prototype = this.prototype,
  4577. enumerables = Ext.enumerables,
  4578. name, i, member;
  4579. var className = Ext.getClassName(this);
  4580. for (name in members) {
  4581. if (members.hasOwnProperty(name)) {
  4582. member = members[name];
  4583. if (typeof member === 'function') {
  4584. member.$owner = this;
  4585. member.$name = name;
  4586. if (className) {
  4587. member.displayName = className + '#' + name;
  4588. }
  4589. }
  4590. prototype[name] = member;
  4591. }
  4592. }
  4593. if (enumerables) {
  4594. for (i = enumerables.length; i--;) {
  4595. name = enumerables[i];
  4596. if (members.hasOwnProperty(name)) {
  4597. member = members[name];
  4598. member.$owner = this;
  4599. member.$name = name;
  4600. prototype[name] = member;
  4601. }
  4602. }
  4603. }
  4604. },
  4605. /**
  4606. * Borrow another class' members to the prototype of this class.
  4607. *
  4608. * Ext.define('Bank', {
  4609. * money: '$$$',
  4610. * printMoney: function() {
  4611. * alert('$$$$$$$');
  4612. * }
  4613. * });
  4614. *
  4615. * Ext.define('Thief', {
  4616. * ...
  4617. * });
  4618. *
  4619. * Thief.borrow(Bank, ['money', 'printMoney']);
  4620. *
  4621. * var steve = new Thief();
  4622. *
  4623. * alert(steve.money); // alerts '$$$'
  4624. * steve.printMoney(); // alerts '$$$$$$$'
  4625. *
  4626. * @param {Ext.Base} fromClass The class to borrow members from
  4627. * @param {String/String[]} members The names of the members to borrow
  4628. * @return {Ext.Base} this
  4629. * @static
  4630. * @inheritable
  4631. */
  4632. borrow: function(fromClass, members) {
  4633. var fromPrototype = fromClass.prototype,
  4634. i, ln, member;
  4635. members = Ext.Array.from(members);
  4636. for (i = 0, ln = members.length; i < ln; i++) {
  4637. member = members[i];
  4638. this.own(member, fromPrototype[member]);
  4639. }
  4640. return this;
  4641. },
  4642. /**
  4643. * Override prototype members of this class. Overridden methods can be invoked via
  4644. * {@link Ext.Base#callOverridden}
  4645. *
  4646. * Ext.define('My.Cat', {
  4647. * constructor: function() {
  4648. * alert("I'm a cat!");
  4649. *
  4650. * return this;
  4651. * }
  4652. * });
  4653. *
  4654. * My.Cat.override({
  4655. * constructor: function() {
  4656. * alert("I'm going to be a cat!");
  4657. *
  4658. * var instance = this.callOverridden();
  4659. *
  4660. * alert("Meeeeoooowwww");
  4661. *
  4662. * return instance;
  4663. * }
  4664. * });
  4665. *
  4666. * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
  4667. * // alerts "I'm a cat!"
  4668. * // alerts "Meeeeoooowwww"
  4669. *
  4670. * @param {Object} members
  4671. * @return {Ext.Base} this
  4672. * @static
  4673. * @inheritable
  4674. */
  4675. override: function(members) {
  4676. var prototype = this.prototype,
  4677. enumerables = Ext.enumerables,
  4678. name, i, member, previous;
  4679. if (arguments.length === 2) {
  4680. name = members;
  4681. member = arguments[1];
  4682. if (typeof member == 'function') {
  4683. if (typeof prototype[name] == 'function') {
  4684. previous = prototype[name];
  4685. member.$previous = previous;
  4686. }
  4687. this.ownMethod(name, member);
  4688. }
  4689. else {
  4690. prototype[name] = member;
  4691. }
  4692. return this;
  4693. }
  4694. for (name in members) {
  4695. if (members.hasOwnProperty(name)) {
  4696. member = members[name];
  4697. if (typeof member === 'function') {
  4698. if (typeof prototype[name] === 'function') {
  4699. previous = prototype[name];
  4700. member.$previous = previous;
  4701. }
  4702. this.ownMethod(name, member);
  4703. }
  4704. else {
  4705. prototype[name] = member;
  4706. }
  4707. }
  4708. }
  4709. if (enumerables) {
  4710. for (i = enumerables.length; i--;) {
  4711. name = enumerables[i];
  4712. if (members.hasOwnProperty(name)) {
  4713. if (typeof prototype[name] !== 'undefined') {
  4714. previous = prototype[name];
  4715. members[name].$previous = previous;
  4716. }
  4717. this.ownMethod(name, members[name]);
  4718. }
  4719. }
  4720. }
  4721. return this;
  4722. },
  4723. //<feature classSystem.mixins>
  4724. /**
  4725. * Used internally by the mixins pre-processor
  4726. * @private
  4727. * @inheritable
  4728. */
  4729. mixin: function(name, cls) {
  4730. var mixin = cls.prototype,
  4731. my = this.prototype,
  4732. key, fn;
  4733. for (key in mixin) {
  4734. if (mixin.hasOwnProperty(key)) {
  4735. if (typeof my[key] === 'undefined' && key !== 'mixins' && key !== 'mixinId') {
  4736. if (typeof mixin[key] === 'function') {
  4737. fn = mixin[key];
  4738. if (typeof fn.$owner === 'undefined') {
  4739. this.ownMethod(key, fn);
  4740. }
  4741. else {
  4742. my[key] = fn;
  4743. }
  4744. }
  4745. else {
  4746. my[key] = mixin[key];
  4747. }
  4748. }
  4749. //<feature classSystem.config>
  4750. else if (key === 'config' && my.config && mixin.config) {
  4751. Ext.Object.merge(my.config, mixin.config);
  4752. }
  4753. //</feature>
  4754. }
  4755. }
  4756. if (typeof mixin.onClassMixedIn !== 'undefined') {
  4757. mixin.onClassMixedIn.call(cls, this);
  4758. }
  4759. if (!my.hasOwnProperty('mixins')) {
  4760. if ('mixins' in my) {
  4761. my.mixins = Ext.Object.merge({}, my.mixins);
  4762. }
  4763. else {
  4764. my.mixins = {};
  4765. }
  4766. }
  4767. my.mixins[name] = mixin;
  4768. },
  4769. //</feature>
  4770. /**
  4771. * Get the current class' name in string format.
  4772. *
  4773. * Ext.define('My.cool.Class', {
  4774. * constructor: function() {
  4775. * alert(this.self.getName()); // alerts 'My.cool.Class'
  4776. * }
  4777. * });
  4778. *
  4779. * My.cool.Class.getName(); // 'My.cool.Class'
  4780. *
  4781. * @return {String} className
  4782. * @static
  4783. * @inheritable
  4784. */
  4785. getName: function() {
  4786. return Ext.getClassName(this);
  4787. },
  4788. /**
  4789. * Create aliases for existing prototype methods. Example:
  4790. *
  4791. * Ext.define('My.cool.Class', {
  4792. * method1: function() { ... },
  4793. * method2: function() { ... }
  4794. * });
  4795. *
  4796. * var test = new My.cool.Class();
  4797. *
  4798. * My.cool.Class.createAlias({
  4799. * method3: 'method1',
  4800. * method4: 'method2'
  4801. * });
  4802. *
  4803. * test.method3(); // test.method1()
  4804. *
  4805. * My.cool.Class.createAlias('method5', 'method3');
  4806. *
  4807. * test.method5(); // test.method3() -> test.method1()
  4808. *
  4809. * @param {String/Object} alias The new method name, or an object to set multiple aliases. See
  4810. * {@link Ext.Function#flexSetter flexSetter}
  4811. * @param {String/Object} origin The original method name
  4812. * @static
  4813. * @inheritable
  4814. * @method
  4815. */
  4816. createAlias: flexSetter(function(alias, origin) {
  4817. this.prototype[alias] = function() {
  4818. return this[origin].apply(this, arguments);
  4819. }
  4820. })
  4821. });
  4822. })(Ext.Function.flexSetter);
  4823. /**
  4824. * @author Jacky Nguyen <jacky@sencha.com>
  4825. * @docauthor Jacky Nguyen <jacky@sencha.com>
  4826. * @class Ext.Class
  4827. *
  4828. * Handles class creation throughout the framework. This is a low level factory that is used by Ext.ClassManager and generally
  4829. * should not be used directly. If you choose to use Ext.Class you will lose out on the namespace, aliasing and depency loading
  4830. * features made available by Ext.ClassManager. The only time you would use Ext.Class directly is to create an anonymous class.
  4831. *
  4832. * If you wish to create a class you should use {@link Ext#define Ext.define} which aliases
  4833. * {@link Ext.ClassManager#create Ext.ClassManager.create} to enable namespacing and dynamic dependency resolution.
  4834. *
  4835. * Ext.Class is the factory and **not** the superclass of everything. For the base class that **all** Ext classes inherit
  4836. * from, see {@link Ext.Base}.
  4837. */
  4838. (function() {
  4839. var Class,
  4840. Base = Ext.Base,
  4841. baseStaticProperties = [],
  4842. baseStaticProperty;
  4843. for (baseStaticProperty in Base) {
  4844. if (Base.hasOwnProperty(baseStaticProperty)) {
  4845. baseStaticProperties.push(baseStaticProperty);
  4846. }
  4847. }
  4848. /**
  4849. * @method constructor
  4850. * Creates new class.
  4851. * @param {Object} classData An object represent the properties of this class
  4852. * @param {Function} createdFn (Optional) The callback function to be executed when this class is fully created.
  4853. * Note that the creation process can be asynchronous depending on the pre-processors used.
  4854. * @return {Ext.Base} The newly created class
  4855. */
  4856. Ext.Class = Class = function(newClass, classData, onClassCreated) {
  4857. if (typeof newClass != 'function') {
  4858. onClassCreated = classData;
  4859. classData = newClass;
  4860. newClass = function() {
  4861. return this.constructor.apply(this, arguments);
  4862. };
  4863. }
  4864. if (!classData) {
  4865. classData = {};
  4866. }
  4867. var preprocessorStack = classData.preprocessors || Class.getDefaultPreprocessors(),
  4868. registeredPreprocessors = Class.getPreprocessors(),
  4869. index = 0,
  4870. preprocessors = [],
  4871. preprocessor, staticPropertyName, process, i, j, ln;
  4872. for (i = 0, ln = baseStaticProperties.length; i < ln; i++) {
  4873. staticPropertyName = baseStaticProperties[i];
  4874. newClass[staticPropertyName] = Base[staticPropertyName];
  4875. }
  4876. delete classData.preprocessors;
  4877. for (j = 0, ln = preprocessorStack.length; j < ln; j++) {
  4878. preprocessor = preprocessorStack[j];
  4879. if (typeof preprocessor == 'string') {
  4880. preprocessor = registeredPreprocessors[preprocessor];
  4881. if (!preprocessor.always) {
  4882. if (classData.hasOwnProperty(preprocessor.name)) {
  4883. preprocessors.push(preprocessor.fn);
  4884. }
  4885. }
  4886. else {
  4887. preprocessors.push(preprocessor.fn);
  4888. }
  4889. }
  4890. else {
  4891. preprocessors.push(preprocessor);
  4892. }
  4893. }
  4894. classData.onClassCreated = onClassCreated || Ext.emptyFn;
  4895. classData.onBeforeClassCreated = function(cls, data) {
  4896. onClassCreated = data.onClassCreated;
  4897. delete data.onBeforeClassCreated;
  4898. delete data.onClassCreated;
  4899. cls.implement(data);
  4900. onClassCreated.call(cls, cls);
  4901. };
  4902. process = function(cls, data) {
  4903. preprocessor = preprocessors[index++];
  4904. if (!preprocessor) {
  4905. data.onBeforeClassCreated.apply(this, arguments);
  4906. return;
  4907. }
  4908. if (preprocessor.call(this, cls, data, process) !== false) {
  4909. process.apply(this, arguments);
  4910. }
  4911. };
  4912. process.call(Class, newClass, classData);
  4913. return newClass;
  4914. };
  4915. Ext.apply(Class, {
  4916. /** @private */
  4917. preprocessors: {},
  4918. /**
  4919. * Register a new pre-processor to be used during the class creation process
  4920. *
  4921. * @member Ext.Class
  4922. * @param {String} name The pre-processor's name
  4923. * @param {Function} fn The callback function to be executed. Typical format:
  4924. *
  4925. * function(cls, data, fn) {
  4926. * // Your code here
  4927. *
  4928. * // Execute this when the processing is finished.
  4929. * // Asynchronous processing is perfectly ok
  4930. * if (fn) {
  4931. * fn.call(this, cls, data);
  4932. * }
  4933. * });
  4934. *
  4935. * @param {Function} fn.cls The created class
  4936. * @param {Object} fn.data The set of properties passed in {@link Ext.Class} constructor
  4937. * @param {Function} fn.fn The callback function that **must** to be executed when this pre-processor finishes,
  4938. * regardless of whether the processing is synchronous or aynchronous
  4939. *
  4940. * @return {Ext.Class} this
  4941. * @static
  4942. */
  4943. registerPreprocessor: function(name, fn, always) {
  4944. this.preprocessors[name] = {
  4945. name: name,
  4946. always: always || false,
  4947. fn: fn
  4948. };
  4949. return this;
  4950. },
  4951. /**
  4952. * Retrieve a pre-processor callback function by its name, which has been registered before
  4953. *
  4954. * @param {String} name
  4955. * @return {Function} preprocessor
  4956. * @static
  4957. */
  4958. getPreprocessor: function(name) {
  4959. return this.preprocessors[name];
  4960. },
  4961. getPreprocessors: function() {
  4962. return this.preprocessors;
  4963. },
  4964. /**
  4965. * Retrieve the array stack of default pre-processors
  4966. *
  4967. * @return {Function[]} defaultPreprocessors
  4968. * @static
  4969. */
  4970. getDefaultPreprocessors: function() {
  4971. return this.defaultPreprocessors || [];
  4972. },
  4973. /**
  4974. * Set the default array stack of default pre-processors
  4975. *
  4976. * @param {Function/Function[]} preprocessors
  4977. * @return {Ext.Class} this
  4978. * @static
  4979. */
  4980. setDefaultPreprocessors: function(preprocessors) {
  4981. this.defaultPreprocessors = Ext.Array.from(preprocessors);
  4982. return this;
  4983. },
  4984. /**
  4985. * Inserts this pre-processor at a specific position in the stack, optionally relative to
  4986. * any existing pre-processor. For example:
  4987. *
  4988. * Ext.Class.registerPreprocessor('debug', function(cls, data, fn) {
  4989. * // Your code here
  4990. *
  4991. * if (fn) {
  4992. * fn.call(this, cls, data);
  4993. * }
  4994. * }).setDefaultPreprocessorPosition('debug', 'last');
  4995. *
  4996. * @param {String} name The pre-processor name. Note that it needs to be registered with
  4997. * {@link #registerPreprocessor registerPreprocessor} before this
  4998. * @param {String} offset The insertion position. Four possible values are:
  4999. * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
  5000. * @param {String} relativeName
  5001. * @return {Ext.Class} this
  5002. * @static
  5003. */
  5004. setDefaultPreprocessorPosition: function(name, offset, relativeName) {
  5005. var defaultPreprocessors = this.defaultPreprocessors,
  5006. index;
  5007. if (typeof offset == 'string') {
  5008. if (offset === 'first') {
  5009. defaultPreprocessors.unshift(name);
  5010. return this;
  5011. }
  5012. else if (offset === 'last') {
  5013. defaultPreprocessors.push(name);
  5014. return this;
  5015. }
  5016. offset = (offset === 'after') ? 1 : -1;
  5017. }
  5018. index = Ext.Array.indexOf(defaultPreprocessors, relativeName);
  5019. if (index !== -1) {
  5020. Ext.Array.splice(defaultPreprocessors, Math.max(0, index + offset), 0, name);
  5021. }
  5022. return this;
  5023. }
  5024. });
  5025. /**
  5026. * @cfg {String} extend
  5027. * The parent class that this class extends. For example:
  5028. *
  5029. * Ext.define('Person', {
  5030. * say: function(text) { alert(text); }
  5031. * });
  5032. *
  5033. * Ext.define('Developer', {
  5034. * extend: 'Person',
  5035. * say: function(text) { this.callParent(["print "+text]); }
  5036. * });
  5037. */
  5038. Class.registerPreprocessor('extend', function(cls, data) {
  5039. var extend = data.extend,
  5040. base = Ext.Base,
  5041. basePrototype = base.prototype,
  5042. prototype = function() {},
  5043. parent, i, k, ln, staticName, parentStatics,
  5044. parentPrototype, clsPrototype;
  5045. if (extend && extend !== Object) {
  5046. parent = extend;
  5047. }
  5048. else {
  5049. parent = base;
  5050. }
  5051. parentPrototype = parent.prototype;
  5052. prototype.prototype = parentPrototype;
  5053. clsPrototype = cls.prototype = new prototype();
  5054. if (!('$class' in parent)) {
  5055. for (i in basePrototype) {
  5056. if (!parentPrototype[i]) {
  5057. parentPrototype[i] = basePrototype[i];
  5058. }
  5059. }
  5060. }
  5061. clsPrototype.self = cls;
  5062. cls.superclass = clsPrototype.superclass = parentPrototype;
  5063. delete data.extend;
  5064. //<feature classSystem.inheritableStatics>
  5065. // Statics inheritance
  5066. parentStatics = parentPrototype.$inheritableStatics;
  5067. if (parentStatics) {
  5068. for (k = 0, ln = parentStatics.length; k < ln; k++) {
  5069. staticName = parentStatics[k];
  5070. if (!cls.hasOwnProperty(staticName)) {
  5071. cls[staticName] = parent[staticName];
  5072. }
  5073. }
  5074. }
  5075. //</feature>
  5076. //<feature classSystem.config>
  5077. // Merge the parent class' config object without referencing it
  5078. if (parentPrototype.config) {
  5079. clsPrototype.config = Ext.Object.merge({}, parentPrototype.config);
  5080. }
  5081. else {
  5082. clsPrototype.config = {};
  5083. }
  5084. //</feature>
  5085. //<feature classSystem.onClassExtended>
  5086. if (clsPrototype.$onExtended) {
  5087. clsPrototype.$onExtended.call(cls, cls, data);
  5088. }
  5089. if (data.onClassExtended) {
  5090. clsPrototype.$onExtended = data.onClassExtended;
  5091. delete data.onClassExtended;
  5092. }
  5093. //</feature>
  5094. }, true);
  5095. //<feature classSystem.statics>
  5096. /**
  5097. * @cfg {Object} statics
  5098. * List of static methods for this class. For example:
  5099. *
  5100. * Ext.define('Computer', {
  5101. * statics: {
  5102. * factory: function(brand) {
  5103. * // 'this' in static methods refer to the class itself
  5104. * return new this(brand);
  5105. * }
  5106. * },
  5107. *
  5108. * constructor: function() { ... }
  5109. * });
  5110. *
  5111. * var dellComputer = Computer.factory('Dell');
  5112. */
  5113. Class.registerPreprocessor('statics', function(cls, data) {
  5114. cls.addStatics(data.statics);
  5115. delete data.statics;
  5116. });
  5117. //</feature>
  5118. //<feature classSystem.inheritableStatics>
  5119. /**
  5120. * @cfg {Object} inheritableStatics
  5121. * List of inheritable static methods for this class.
  5122. * Otherwise just like {@link #statics} but subclasses inherit these methods.
  5123. */
  5124. Class.registerPreprocessor('inheritableStatics', function(cls, data) {
  5125. cls.addInheritableStatics(data.inheritableStatics);
  5126. delete data.inheritableStatics;
  5127. });
  5128. //</feature>
  5129. //<feature classSystem.config>
  5130. /**
  5131. * @cfg {Object} config
  5132. * List of configuration options with their default values, for which automatically
  5133. * accessor methods are generated. For example:
  5134. *
  5135. * Ext.define('SmartPhone', {
  5136. * config: {
  5137. * hasTouchScreen: false,
  5138. * operatingSystem: 'Other',
  5139. * price: 500
  5140. * },
  5141. * constructor: function(cfg) {
  5142. * this.initConfig(cfg);
  5143. * }
  5144. * });
  5145. *
  5146. * var iPhone = new SmartPhone({
  5147. * hasTouchScreen: true,
  5148. * operatingSystem: 'iOS'
  5149. * });
  5150. *
  5151. * iPhone.getPrice(); // 500;
  5152. * iPhone.getOperatingSystem(); // 'iOS'
  5153. * iPhone.getHasTouchScreen(); // true;
  5154. * iPhone.hasTouchScreen(); // true
  5155. */
  5156. Class.registerPreprocessor('config', function(cls, data) {
  5157. var prototype = cls.prototype;
  5158. Ext.Object.each(data.config, function(name) {
  5159. var cName = name.charAt(0).toUpperCase() + name.substr(1),
  5160. pName = name,
  5161. apply = 'apply' + cName,
  5162. setter = 'set' + cName,
  5163. getter = 'get' + cName;
  5164. if (!(apply in prototype) && !data.hasOwnProperty(apply)) {
  5165. data[apply] = function(val) {
  5166. return val;
  5167. };
  5168. }
  5169. if (!(setter in prototype) && !data.hasOwnProperty(setter)) {
  5170. data[setter] = function(val) {
  5171. var ret = this[apply].call(this, val, this[pName]);
  5172. if (typeof ret != 'undefined') {
  5173. this[pName] = ret;
  5174. }
  5175. return this;
  5176. };
  5177. }
  5178. if (!(getter in prototype) && !data.hasOwnProperty(getter)) {
  5179. data[getter] = function() {
  5180. return this[pName];
  5181. };
  5182. }
  5183. });
  5184. Ext.Object.merge(prototype.config, data.config);
  5185. delete data.config;
  5186. });
  5187. //</feature>
  5188. //<feature classSystem.mixins>
  5189. /**
  5190. * @cfg {Object} mixins
  5191. * List of classes to mix into this class. For example:
  5192. *
  5193. * Ext.define('CanSing', {
  5194. * sing: function() {
  5195. * alert("I'm on the highway to hell...")
  5196. * }
  5197. * });
  5198. *
  5199. * Ext.define('Musician', {
  5200. * extend: 'Person',
  5201. *
  5202. * mixins: {
  5203. * canSing: 'CanSing'
  5204. * }
  5205. * })
  5206. */
  5207. Class.registerPreprocessor('mixins', function(cls, data) {
  5208. var mixins = data.mixins,
  5209. name, mixin, i, ln;
  5210. delete data.mixins;
  5211. Ext.Function.interceptBefore(data, 'onClassCreated', function(cls) {
  5212. if (mixins instanceof Array) {
  5213. for (i = 0,ln = mixins.length; i < ln; i++) {
  5214. mixin = mixins[i];
  5215. name = mixin.prototype.mixinId || mixin.$className;
  5216. cls.mixin(name, mixin);
  5217. }
  5218. }
  5219. else {
  5220. for (name in mixins) {
  5221. if (mixins.hasOwnProperty(name)) {
  5222. cls.mixin(name, mixins[name]);
  5223. }
  5224. }
  5225. }
  5226. });
  5227. });
  5228. //</feature>
  5229. Class.setDefaultPreprocessors([
  5230. 'extend'
  5231. //<feature classSystem.statics>
  5232. ,'statics'
  5233. //</feature>
  5234. //<feature classSystem.inheritableStatics>
  5235. ,'inheritableStatics'
  5236. //</feature>
  5237. //<feature classSystem.config>
  5238. ,'config'
  5239. //</feature>
  5240. //<feature classSystem.mixins>
  5241. ,'mixins'
  5242. //</feature>
  5243. ]);
  5244. //<feature classSystem.backwardsCompatible>
  5245. // Backwards compatible
  5246. Ext.extend = function(subclass, superclass, members) {
  5247. if (arguments.length === 2 && Ext.isObject(superclass)) {
  5248. members = superclass;
  5249. superclass = subclass;
  5250. subclass = null;
  5251. }
  5252. var cls;
  5253. if (!superclass) {
  5254. Ext.Error.raise("Attempting to extend from a class which has not been loaded on the page.");
  5255. }
  5256. members.extend = superclass;
  5257. members.preprocessors = [
  5258. 'extend'
  5259. //<feature classSystem.statics>
  5260. ,'statics'
  5261. //</feature>
  5262. //<feature classSystem.inheritableStatics>
  5263. ,'inheritableStatics'
  5264. //</feature>
  5265. //<feature classSystem.mixins>
  5266. ,'mixins'
  5267. //</feature>
  5268. //<feature classSystem.config>
  5269. ,'config'
  5270. //</feature>
  5271. ];
  5272. if (subclass) {
  5273. cls = new Class(subclass, members);
  5274. }
  5275. else {
  5276. cls = new Class(members);
  5277. }
  5278. cls.prototype.override = function(o) {
  5279. for (var m in o) {
  5280. if (o.hasOwnProperty(m)) {
  5281. this[m] = o[m];
  5282. }
  5283. }
  5284. };
  5285. return cls;
  5286. };
  5287. //</feature>
  5288. })();
  5289. /**
  5290. * @author Jacky Nguyen <jacky@sencha.com>
  5291. * @docauthor Jacky Nguyen <jacky@sencha.com>
  5292. * @class Ext.ClassManager
  5293. *
  5294. * Ext.ClassManager manages all classes and handles mapping from string class name to
  5295. * actual class objects throughout the whole framework. It is not generally accessed directly, rather through
  5296. * these convenient shorthands:
  5297. *
  5298. * - {@link Ext#define Ext.define}
  5299. * - {@link Ext#create Ext.create}
  5300. * - {@link Ext#widget Ext.widget}
  5301. * - {@link Ext#getClass Ext.getClass}
  5302. * - {@link Ext#getClassName Ext.getClassName}
  5303. *
  5304. * # Basic syntax:
  5305. *
  5306. * Ext.define(className, properties);
  5307. *
  5308. * in which `properties` is an object represent a collection of properties that apply to the class. See
  5309. * {@link Ext.ClassManager#create} for more detailed instructions.
  5310. *
  5311. * Ext.define('Person', {
  5312. * name: 'Unknown',
  5313. *
  5314. * constructor: function(name) {
  5315. * if (name) {
  5316. * this.name = name;
  5317. * }
  5318. *
  5319. * return this;
  5320. * },
  5321. *
  5322. * eat: function(foodType) {
  5323. * alert("I'm eating: " + foodType);
  5324. *
  5325. * return this;
  5326. * }
  5327. * });
  5328. *
  5329. * var aaron = new Person("Aaron");
  5330. * aaron.eat("Sandwich"); // alert("I'm eating: Sandwich");
  5331. *
  5332. * Ext.Class has a powerful set of extensible {@link Ext.Class#registerPreprocessor pre-processors} which takes care of
  5333. * everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc.
  5334. *
  5335. * # Inheritance:
  5336. *
  5337. * Ext.define('Developer', {
  5338. * extend: 'Person',
  5339. *
  5340. * constructor: function(name, isGeek) {
  5341. * this.isGeek = isGeek;
  5342. *
  5343. * // Apply a method from the parent class' prototype
  5344. * this.callParent([name]);
  5345. *
  5346. * return this;
  5347. *
  5348. * },
  5349. *
  5350. * code: function(language) {
  5351. * alert("I'm coding in: " + language);
  5352. *
  5353. * this.eat("Bugs");
  5354. *
  5355. * return this;
  5356. * }
  5357. * });
  5358. *
  5359. * var jacky = new Developer("Jacky", true);
  5360. * jacky.code("JavaScript"); // alert("I'm coding in: JavaScript");
  5361. * // alert("I'm eating: Bugs");
  5362. *
  5363. * See {@link Ext.Base#callParent} for more details on calling superclass' methods
  5364. *
  5365. * # Mixins:
  5366. *
  5367. * Ext.define('CanPlayGuitar', {
  5368. * playGuitar: function() {
  5369. * alert("F#...G...D...A");
  5370. * }
  5371. * });
  5372. *
  5373. * Ext.define('CanComposeSongs', {
  5374. * composeSongs: function() { ... }
  5375. * });
  5376. *
  5377. * Ext.define('CanSing', {
  5378. * sing: function() {
  5379. * alert("I'm on the highway to hell...")
  5380. * }
  5381. * });
  5382. *
  5383. * Ext.define('Musician', {
  5384. * extend: 'Person',
  5385. *
  5386. * mixins: {
  5387. * canPlayGuitar: 'CanPlayGuitar',
  5388. * canComposeSongs: 'CanComposeSongs',
  5389. * canSing: 'CanSing'
  5390. * }
  5391. * })
  5392. *
  5393. * Ext.define('CoolPerson', {
  5394. * extend: 'Person',
  5395. *
  5396. * mixins: {
  5397. * canPlayGuitar: 'CanPlayGuitar',
  5398. * canSing: 'CanSing'
  5399. * },
  5400. *
  5401. * sing: function() {
  5402. * alert("Ahem....");
  5403. *
  5404. * this.mixins.canSing.sing.call(this);
  5405. *
  5406. * alert("[Playing guitar at the same time...]");
  5407. *
  5408. * this.playGuitar();
  5409. * }
  5410. * });
  5411. *
  5412. * var me = new CoolPerson("Jacky");
  5413. *
  5414. * me.sing(); // alert("Ahem...");
  5415. * // alert("I'm on the highway to hell...");
  5416. * // alert("[Playing guitar at the same time...]");
  5417. * // alert("F#...G...D...A");
  5418. *
  5419. * # Config:
  5420. *
  5421. * Ext.define('SmartPhone', {
  5422. * config: {
  5423. * hasTouchScreen: false,
  5424. * operatingSystem: 'Other',
  5425. * price: 500
  5426. * },
  5427. *
  5428. * isExpensive: false,
  5429. *
  5430. * constructor: function(config) {
  5431. * this.initConfig(config);
  5432. *
  5433. * return this;
  5434. * },
  5435. *
  5436. * applyPrice: function(price) {
  5437. * this.isExpensive = (price > 500);
  5438. *
  5439. * return price;
  5440. * },
  5441. *
  5442. * applyOperatingSystem: function(operatingSystem) {
  5443. * if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) {
  5444. * return 'Other';
  5445. * }
  5446. *
  5447. * return operatingSystem;
  5448. * }
  5449. * });
  5450. *
  5451. * var iPhone = new SmartPhone({
  5452. * hasTouchScreen: true,
  5453. * operatingSystem: 'iOS'
  5454. * });
  5455. *
  5456. * iPhone.getPrice(); // 500;
  5457. * iPhone.getOperatingSystem(); // 'iOS'
  5458. * iPhone.getHasTouchScreen(); // true;
  5459. * iPhone.hasTouchScreen(); // true
  5460. *
  5461. * iPhone.isExpensive; // false;
  5462. * iPhone.setPrice(600);
  5463. * iPhone.getPrice(); // 600
  5464. * iPhone.isExpensive; // true;
  5465. *
  5466. * iPhone.setOperatingSystem('AlienOS');
  5467. * iPhone.getOperatingSystem(); // 'Other'
  5468. *
  5469. * # Statics:
  5470. *
  5471. * Ext.define('Computer', {
  5472. * statics: {
  5473. * factory: function(brand) {
  5474. * // 'this' in static methods refer to the class itself
  5475. * return new this(brand);
  5476. * }
  5477. * },
  5478. *
  5479. * constructor: function() { ... }
  5480. * });
  5481. *
  5482. * var dellComputer = Computer.factory('Dell');
  5483. *
  5484. * Also see {@link Ext.Base#statics} and {@link Ext.Base#self} for more details on accessing
  5485. * static properties within class methods
  5486. *
  5487. * @singleton
  5488. */
  5489. (function(Class, alias) {
  5490. var slice = Array.prototype.slice;
  5491. var Manager = Ext.ClassManager = {
  5492. /**
  5493. * @property {Object} classes
  5494. * All classes which were defined through the ClassManager. Keys are the
  5495. * name of the classes and the values are references to the classes.
  5496. * @private
  5497. */
  5498. classes: {},
  5499. /**
  5500. * @private
  5501. */
  5502. existCache: {},
  5503. /**
  5504. * @private
  5505. */
  5506. namespaceRewrites: [{
  5507. from: 'Ext.',
  5508. to: Ext
  5509. }],
  5510. /**
  5511. * @private
  5512. */
  5513. maps: {
  5514. alternateToName: {},
  5515. aliasToName: {},
  5516. nameToAliases: {}
  5517. },
  5518. /** @private */
  5519. enableNamespaceParseCache: true,
  5520. /** @private */
  5521. namespaceParseCache: {},
  5522. /** @private */
  5523. instantiators: [],
  5524. /** @private */
  5525. instantiationCounts: {},
  5526. /**
  5527. * Checks if a class has already been created.
  5528. *
  5529. * @param {String} className
  5530. * @return {Boolean} exist
  5531. */
  5532. isCreated: function(className) {
  5533. var i, ln, part, root, parts;
  5534. if (typeof className !== 'string' || className.length < 1) {
  5535. Ext.Error.raise({
  5536. sourceClass: "Ext.ClassManager",
  5537. sourceMethod: "exist",
  5538. msg: "Invalid classname, must be a string and must not be empty"
  5539. });
  5540. }
  5541. if (this.classes.hasOwnProperty(className) || this.existCache.hasOwnProperty(className)) {
  5542. return true;
  5543. }
  5544. root = Ext.global;
  5545. parts = this.parseNamespace(className);
  5546. for (i = 0, ln = parts.length; i < ln; i++) {
  5547. part = parts[i];
  5548. if (typeof part !== 'string') {
  5549. root = part;
  5550. } else {
  5551. if (!root || !root[part]) {
  5552. return false;
  5553. }
  5554. root = root[part];
  5555. }
  5556. }
  5557. Ext.Loader.historyPush(className);
  5558. this.existCache[className] = true;
  5559. return true;
  5560. },
  5561. /**
  5562. * Supports namespace rewriting
  5563. * @private
  5564. */
  5565. parseNamespace: function(namespace) {
  5566. if (typeof namespace !== 'string') {
  5567. Ext.Error.raise({
  5568. sourceClass: "Ext.ClassManager",
  5569. sourceMethod: "parseNamespace",
  5570. msg: "Invalid namespace, must be a string"
  5571. });
  5572. }
  5573. var cache = this.namespaceParseCache;
  5574. if (this.enableNamespaceParseCache) {
  5575. if (cache.hasOwnProperty(namespace)) {
  5576. return cache[namespace];
  5577. }
  5578. }
  5579. var parts = [],
  5580. rewrites = this.namespaceRewrites,
  5581. rewrite, from, to, i, ln, root = Ext.global;
  5582. for (i = 0, ln = rewrites.length; i < ln; i++) {
  5583. rewrite = rewrites[i];
  5584. from = rewrite.from;
  5585. to = rewrite.to;
  5586. if (namespace === from || namespace.substring(0, from.length) === from) {
  5587. namespace = namespace.substring(from.length);
  5588. if (typeof to !== 'string') {
  5589. root = to;
  5590. } else {
  5591. parts = parts.concat(to.split('.'));
  5592. }
  5593. break;
  5594. }
  5595. }
  5596. parts.push(root);
  5597. parts = parts.concat(namespace.split('.'));
  5598. if (this.enableNamespaceParseCache) {
  5599. cache[namespace] = parts;
  5600. }
  5601. return parts;
  5602. },
  5603. /**
  5604. * Creates a namespace and assign the `value` to the created object
  5605. *
  5606. * Ext.ClassManager.setNamespace('MyCompany.pkg.Example', someObject);
  5607. *
  5608. * alert(MyCompany.pkg.Example === someObject); // alerts true
  5609. *
  5610. * @param {String} name
  5611. * @param {Object} value
  5612. */
  5613. setNamespace: function(name, value) {
  5614. var root = Ext.global,
  5615. parts = this.parseNamespace(name),
  5616. ln = parts.length - 1,
  5617. leaf = parts[ln],
  5618. i, part;
  5619. for (i = 0; i < ln; i++) {
  5620. part = parts[i];
  5621. if (typeof part !== 'string') {
  5622. root = part;
  5623. } else {
  5624. if (!root[part]) {
  5625. root[part] = {};
  5626. }
  5627. root = root[part];
  5628. }
  5629. }
  5630. root[leaf] = value;
  5631. return root[leaf];
  5632. },
  5633. /**
  5634. * The new Ext.ns, supports namespace rewriting
  5635. * @private
  5636. */
  5637. createNamespaces: function() {
  5638. var root = Ext.global,
  5639. parts, part, i, j, ln, subLn;
  5640. for (i = 0, ln = arguments.length; i < ln; i++) {
  5641. parts = this.parseNamespace(arguments[i]);
  5642. for (j = 0, subLn = parts.length; j < subLn; j++) {
  5643. part = parts[j];
  5644. if (typeof part !== 'string') {
  5645. root = part;
  5646. } else {
  5647. if (!root[part]) {
  5648. root[part] = {};
  5649. }
  5650. root = root[part];
  5651. }
  5652. }
  5653. }
  5654. return root;
  5655. },
  5656. /**
  5657. * Sets a name reference to a class.
  5658. *
  5659. * @param {String} name
  5660. * @param {Object} value
  5661. * @return {Ext.ClassManager} this
  5662. */
  5663. set: function(name, value) {
  5664. var targetName = this.getName(value);
  5665. this.classes[name] = this.setNamespace(name, value);
  5666. if (targetName && targetName !== name) {
  5667. this.maps.alternateToName[name] = targetName;
  5668. }
  5669. return this;
  5670. },
  5671. /**
  5672. * Retrieve a class by its name.
  5673. *
  5674. * @param {String} name
  5675. * @return {Ext.Class} class
  5676. */
  5677. get: function(name) {
  5678. if (this.classes.hasOwnProperty(name)) {
  5679. return this.classes[name];
  5680. }
  5681. var root = Ext.global,
  5682. parts = this.parseNamespace(name),
  5683. part, i, ln;
  5684. for (i = 0, ln = parts.length; i < ln; i++) {
  5685. part = parts[i];
  5686. if (typeof part !== 'string') {
  5687. root = part;
  5688. } else {
  5689. if (!root || !root[part]) {
  5690. return null;
  5691. }
  5692. root = root[part];
  5693. }
  5694. }
  5695. return root;
  5696. },
  5697. /**
  5698. * Register the alias for a class.
  5699. *
  5700. * @param {Ext.Class/String} cls a reference to a class or a className
  5701. * @param {String} alias Alias to use when referring to this class
  5702. */
  5703. setAlias: function(cls, alias) {
  5704. var aliasToNameMap = this.maps.aliasToName,
  5705. nameToAliasesMap = this.maps.nameToAliases,
  5706. className;
  5707. if (typeof cls === 'string') {
  5708. className = cls;
  5709. } else {
  5710. className = this.getName(cls);
  5711. }
  5712. if (alias && aliasToNameMap[alias] !== className) {
  5713. if (aliasToNameMap.hasOwnProperty(alias) && Ext.isDefined(Ext.global.console)) {
  5714. Ext.global.console.log("[Ext.ClassManager] Overriding existing alias: '" + alias + "' " +
  5715. "of: '" + aliasToNameMap[alias] + "' with: '" + className + "'. Be sure it's intentional.");
  5716. }
  5717. aliasToNameMap[alias] = className;
  5718. }
  5719. if (!nameToAliasesMap[className]) {
  5720. nameToAliasesMap[className] = [];
  5721. }
  5722. if (alias) {
  5723. Ext.Array.include(nameToAliasesMap[className], alias);
  5724. }
  5725. return this;
  5726. },
  5727. /**
  5728. * Get a reference to the class by its alias.
  5729. *
  5730. * @param {String} alias
  5731. * @return {Ext.Class} class
  5732. */
  5733. getByAlias: function(alias) {
  5734. return this.get(this.getNameByAlias(alias));
  5735. },
  5736. /**
  5737. * Get the name of a class by its alias.
  5738. *
  5739. * @param {String} alias
  5740. * @return {String} className
  5741. */
  5742. getNameByAlias: function(alias) {
  5743. return this.maps.aliasToName[alias] || '';
  5744. },
  5745. /**
  5746. * Get the name of a class by its alternate name.
  5747. *
  5748. * @param {String} alternate
  5749. * @return {String} className
  5750. */
  5751. getNameByAlternate: function(alternate) {
  5752. return this.maps.alternateToName[alternate] || '';
  5753. },
  5754. /**
  5755. * Get the aliases of a class by the class name
  5756. *
  5757. * @param {String} name
  5758. * @return {String[]} aliases
  5759. */
  5760. getAliasesByName: function(name) {
  5761. return this.maps.nameToAliases[name] || [];
  5762. },
  5763. /**
  5764. * Get the name of the class by its reference or its instance.
  5765. *
  5766. * Ext.ClassManager.getName(Ext.Action); // returns "Ext.Action"
  5767. *
  5768. * {@link Ext#getClassName Ext.getClassName} is alias for {@link Ext.ClassManager#getName Ext.ClassManager.getName}.
  5769. *
  5770. * @param {Ext.Class/Object} object
  5771. * @return {String} className
  5772. */
  5773. getName: function(object) {
  5774. return object && object.$className || '';
  5775. },
  5776. /**
  5777. * Get the class of the provided object; returns null if it's not an instance
  5778. * of any class created with Ext.define.
  5779. *
  5780. * var component = new Ext.Component();
  5781. *
  5782. * Ext.ClassManager.getClass(component); // returns Ext.Component
  5783. *
  5784. * {@link Ext#getClass Ext.getClass} is alias for {@link Ext.ClassManager#getClass Ext.ClassManager.getClass}.
  5785. *
  5786. * @param {Object} object
  5787. * @return {Ext.Class} class
  5788. */
  5789. getClass: function(object) {
  5790. return object && object.self || null;
  5791. },
  5792. /**
  5793. * Defines a class.
  5794. *
  5795. * {@link Ext#define Ext.define} and {@link Ext.ClassManager#create Ext.ClassManager.create} are almost aliases
  5796. * of each other, with the only exception that Ext.define allows definition of {@link Ext.Class#override overrides}.
  5797. * To avoid trouble, always use Ext.define.
  5798. *
  5799. * Ext.define('My.awesome.Class', {
  5800. * someProperty: 'something',
  5801. * someMethod: function() { ... }
  5802. * ...
  5803. *
  5804. * }, function() {
  5805. * alert('Created!');
  5806. * alert(this === My.awesome.Class); // alerts true
  5807. *
  5808. * var myInstance = new this();
  5809. * });
  5810. *
  5811. * @param {String} className The class name to create in string dot-namespaced format, for example:
  5812. * `My.very.awesome.Class`, `FeedViewer.plugin.CoolPager`. It is highly recommended to follow this simple convention:
  5813. *
  5814. * - The root and the class name are 'CamelCased'
  5815. * - Everything else is lower-cased
  5816. *
  5817. * @param {Object} data The key-value pairs of properties to apply to this class. Property names can be of any valid
  5818. * strings, except those in the reserved list below:
  5819. *
  5820. * - {@link Ext.Base#self self}
  5821. * - {@link Ext.Class#alias alias}
  5822. * - {@link Ext.Class#alternateClassName alternateClassName}
  5823. * - {@link Ext.Class#config config}
  5824. * - {@link Ext.Class#extend extend}
  5825. * - {@link Ext.Class#inheritableStatics inheritableStatics}
  5826. * - {@link Ext.Class#mixins mixins}
  5827. * - {@link Ext.Class#override override} (only when using {@link Ext#define Ext.define})
  5828. * - {@link Ext.Class#requires requires}
  5829. * - {@link Ext.Class#singleton singleton}
  5830. * - {@link Ext.Class#statics statics}
  5831. * - {@link Ext.Class#uses uses}
  5832. *
  5833. * @param {Function} [createdFn] callback to execute after the class is created, the execution scope of which
  5834. * (`this`) will be the newly created class itself.
  5835. *
  5836. * @return {Ext.Base}
  5837. */
  5838. create: function(className, data, createdFn) {
  5839. var manager = this;
  5840. if (typeof className !== 'string') {
  5841. Ext.Error.raise({
  5842. sourceClass: "Ext",
  5843. sourceMethod: "define",
  5844. msg: "Invalid class name '" + className + "' specified, must be a non-empty string"
  5845. });
  5846. }
  5847. data.$className = className;
  5848. return new Class(data, function() {
  5849. var postprocessorStack = data.postprocessors || manager.defaultPostprocessors,
  5850. registeredPostprocessors = manager.postprocessors,
  5851. index = 0,
  5852. postprocessors = [],
  5853. postprocessor, process, i, ln;
  5854. delete data.postprocessors;
  5855. for (i = 0, ln = postprocessorStack.length; i < ln; i++) {
  5856. postprocessor = postprocessorStack[i];
  5857. if (typeof postprocessor === 'string') {
  5858. postprocessor = registeredPostprocessors[postprocessor];
  5859. if (!postprocessor.always) {
  5860. if (data[postprocessor.name] !== undefined) {
  5861. postprocessors.push(postprocessor.fn);
  5862. }
  5863. }
  5864. else {
  5865. postprocessors.push(postprocessor.fn);
  5866. }
  5867. }
  5868. else {
  5869. postprocessors.push(postprocessor);
  5870. }
  5871. }
  5872. process = function(clsName, cls, clsData) {
  5873. postprocessor = postprocessors[index++];
  5874. if (!postprocessor) {
  5875. manager.set(className, cls);
  5876. Ext.Loader.historyPush(className);
  5877. if (createdFn) {
  5878. createdFn.call(cls, cls);
  5879. }
  5880. return;
  5881. }
  5882. if (postprocessor.call(this, clsName, cls, clsData, process) !== false) {
  5883. process.apply(this, arguments);
  5884. }
  5885. };
  5886. process.call(manager, className, this, data);
  5887. });
  5888. },
  5889. /**
  5890. * Instantiate a class by its alias.
  5891. *
  5892. * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
  5893. * attempt to load the class via synchronous loading.
  5894. *
  5895. * var window = Ext.ClassManager.instantiateByAlias('widget.window', { width: 600, height: 800, ... });
  5896. *
  5897. * {@link Ext#createByAlias Ext.createByAlias} is alias for {@link Ext.ClassManager#instantiateByAlias Ext.ClassManager.instantiateByAlias}.
  5898. *
  5899. * @param {String} alias
  5900. * @param {Object...} args Additional arguments after the alias will be passed to the
  5901. * class constructor.
  5902. * @return {Object} instance
  5903. */
  5904. instantiateByAlias: function() {
  5905. var alias = arguments[0],
  5906. args = slice.call(arguments),
  5907. className = this.getNameByAlias(alias);
  5908. if (!className) {
  5909. className = this.maps.aliasToName[alias];
  5910. if (!className) {
  5911. Ext.Error.raise({
  5912. sourceClass: "Ext",
  5913. sourceMethod: "createByAlias",
  5914. msg: "Cannot create an instance of unrecognized alias: " + alias
  5915. });
  5916. }
  5917. if (Ext.global.console) {
  5918. Ext.global.console.warn("[Ext.Loader] Synchronously loading '" + className + "'; consider adding " +
  5919. "Ext.require('" + alias + "') above Ext.onReady");
  5920. }
  5921. Ext.syncRequire(className);
  5922. }
  5923. args[0] = className;
  5924. return this.instantiate.apply(this, args);
  5925. },
  5926. /**
  5927. * Instantiate a class by either full name, alias or alternate name.
  5928. *
  5929. * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
  5930. * attempt to load the class via synchronous loading.
  5931. *
  5932. * For example, all these three lines return the same result:
  5933. *
  5934. * // alias
  5935. * var window = Ext.ClassManager.instantiate('widget.window', { width: 600, height: 800, ... });
  5936. *
  5937. * // alternate name
  5938. * var window = Ext.ClassManager.instantiate('Ext.Window', { width: 600, height: 800, ... });
  5939. *
  5940. * // full class name
  5941. * var window = Ext.ClassManager.instantiate('Ext.window.Window', { width: 600, height: 800, ... });
  5942. *
  5943. * {@link Ext#create Ext.create} is alias for {@link Ext.ClassManager#instantiate Ext.ClassManager.instantiate}.
  5944. *
  5945. * @param {String} name
  5946. * @param {Object...} args Additional arguments after the name will be passed to the class' constructor.
  5947. * @return {Object} instance
  5948. */
  5949. instantiate: function() {
  5950. var name = arguments[0],
  5951. args = slice.call(arguments, 1),
  5952. alias = name,
  5953. possibleName, cls;
  5954. if (typeof name !== 'function') {
  5955. if ((typeof name !== 'string' || name.length < 1)) {
  5956. Ext.Error.raise({
  5957. sourceClass: "Ext",
  5958. sourceMethod: "create",
  5959. msg: "Invalid class name or alias '" + name + "' specified, must be a non-empty string"
  5960. });
  5961. }
  5962. cls = this.get(name);
  5963. }
  5964. else {
  5965. cls = name;
  5966. }
  5967. // No record of this class name, it's possibly an alias, so look it up
  5968. if (!cls) {
  5969. possibleName = this.getNameByAlias(name);
  5970. if (possibleName) {
  5971. name = possibleName;
  5972. cls = this.get(name);
  5973. }
  5974. }
  5975. // Still no record of this class name, it's possibly an alternate name, so look it up
  5976. if (!cls) {
  5977. possibleName = this.getNameByAlternate(name);
  5978. if (possibleName) {
  5979. name = possibleName;
  5980. cls = this.get(name);
  5981. }
  5982. }
  5983. // Still not existing at this point, try to load it via synchronous mode as the last resort
  5984. if (!cls) {
  5985. if (Ext.global.console) {
  5986. Ext.global.console.warn("[Ext.Loader] Synchronously loading '" + name + "'; consider adding " +
  5987. "Ext.require('" + ((possibleName) ? alias : name) + "') above Ext.onReady");
  5988. }
  5989. Ext.syncRequire(name);
  5990. cls = this.get(name);
  5991. }
  5992. if (!cls) {
  5993. Ext.Error.raise({
  5994. sourceClass: "Ext",
  5995. sourceMethod: "create",
  5996. msg: "Cannot create an instance of unrecognized class name / alias: " + alias
  5997. });
  5998. }
  5999. if (typeof cls !== 'function') {
  6000. Ext.Error.raise({
  6001. sourceClass: "Ext",
  6002. sourceMethod: "create",
  6003. msg: "'" + name + "' is a singleton and cannot be instantiated"
  6004. });
  6005. }
  6006. if (!this.instantiationCounts[name]) {
  6007. this.instantiationCounts[name] = 0;
  6008. }
  6009. this.instantiationCounts[name]++;
  6010. return this.getInstantiator(args.length)(cls, args);
  6011. },
  6012. /**
  6013. * @private
  6014. * @param name
  6015. * @param args
  6016. */
  6017. dynInstantiate: function(name, args) {
  6018. args = Ext.Array.from(args, true);
  6019. args.unshift(name);
  6020. return this.instantiate.apply(this, args);
  6021. },
  6022. /**
  6023. * @private
  6024. * @param length
  6025. */
  6026. getInstantiator: function(length) {
  6027. if (!this.instantiators[length]) {
  6028. var i = length,
  6029. args = [];
  6030. for (i = 0; i < length; i++) {
  6031. args.push('a['+i+']');
  6032. }
  6033. this.instantiators[length] = new Function('c', 'a', 'return new c('+args.join(',')+')');
  6034. }
  6035. return this.instantiators[length];
  6036. },
  6037. /**
  6038. * @private
  6039. */
  6040. postprocessors: {},
  6041. /**
  6042. * @private
  6043. */
  6044. defaultPostprocessors: [],
  6045. /**
  6046. * Register a post-processor function.
  6047. *
  6048. * @param {String} name
  6049. * @param {Function} postprocessor
  6050. */
  6051. registerPostprocessor: function(name, fn, always) {
  6052. this.postprocessors[name] = {
  6053. name: name,
  6054. always: always || false,
  6055. fn: fn
  6056. };
  6057. return this;
  6058. },
  6059. /**
  6060. * Set the default post processors array stack which are applied to every class.
  6061. *
  6062. * @param {String/String[]} The name of a registered post processor or an array of registered names.
  6063. * @return {Ext.ClassManager} this
  6064. */
  6065. setDefaultPostprocessors: function(postprocessors) {
  6066. this.defaultPostprocessors = Ext.Array.from(postprocessors);
  6067. return this;
  6068. },
  6069. /**
  6070. * Insert this post-processor at a specific position in the stack, optionally relative to
  6071. * any existing post-processor
  6072. *
  6073. * @param {String} name The post-processor name. Note that it needs to be registered with
  6074. * {@link Ext.ClassManager#registerPostprocessor} before this
  6075. * @param {String} offset The insertion position. Four possible values are:
  6076. * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
  6077. * @param {String} relativeName
  6078. * @return {Ext.ClassManager} this
  6079. */
  6080. setDefaultPostprocessorPosition: function(name, offset, relativeName) {
  6081. var defaultPostprocessors = this.defaultPostprocessors,
  6082. index;
  6083. if (typeof offset === 'string') {
  6084. if (offset === 'first') {
  6085. defaultPostprocessors.unshift(name);
  6086. return this;
  6087. }
  6088. else if (offset === 'last') {
  6089. defaultPostprocessors.push(name);
  6090. return this;
  6091. }
  6092. offset = (offset === 'after') ? 1 : -1;
  6093. }
  6094. index = Ext.Array.indexOf(defaultPostprocessors, relativeName);
  6095. if (index !== -1) {
  6096. Ext.Array.splice(defaultPostprocessors, Math.max(0, index + offset), 0, name);
  6097. }
  6098. return this;
  6099. },
  6100. /**
  6101. * Converts a string expression to an array of matching class names. An expression can either refers to class aliases
  6102. * or class names. Expressions support wildcards:
  6103. *
  6104. * // returns ['Ext.window.Window']
  6105. * var window = Ext.ClassManager.getNamesByExpression('widget.window');
  6106. *
  6107. * // returns ['widget.panel', 'widget.window', ...]
  6108. * var allWidgets = Ext.ClassManager.getNamesByExpression('widget.*');
  6109. *
  6110. * // returns ['Ext.data.Store', 'Ext.data.ArrayProxy', ...]
  6111. * var allData = Ext.ClassManager.getNamesByExpression('Ext.data.*');
  6112. *
  6113. * @param {String} expression
  6114. * @return {String[]} classNames
  6115. */
  6116. getNamesByExpression: function(expression) {
  6117. var nameToAliasesMap = this.maps.nameToAliases,
  6118. names = [],
  6119. name, alias, aliases, possibleName, regex, i, ln;
  6120. if (typeof expression !== 'string' || expression.length < 1) {
  6121. Ext.Error.raise({
  6122. sourceClass: "Ext.ClassManager",
  6123. sourceMethod: "getNamesByExpression",
  6124. msg: "Expression " + expression + " is invalid, must be a non-empty string"
  6125. });
  6126. }
  6127. if (expression.indexOf('*') !== -1) {
  6128. expression = expression.replace(/\*/g, '(.*?)');
  6129. regex = new RegExp('^' + expression + '$');
  6130. for (name in nameToAliasesMap) {
  6131. if (nameToAliasesMap.hasOwnProperty(name)) {
  6132. aliases = nameToAliasesMap[name];
  6133. if (name.search(regex) !== -1) {
  6134. names.push(name);
  6135. }
  6136. else {
  6137. for (i = 0, ln = aliases.length; i < ln; i++) {
  6138. alias = aliases[i];
  6139. if (alias.search(regex) !== -1) {
  6140. names.push(name);
  6141. break;
  6142. }
  6143. }
  6144. }
  6145. }
  6146. }
  6147. } else {
  6148. possibleName = this.getNameByAlias(expression);
  6149. if (possibleName) {
  6150. names.push(possibleName);
  6151. } else {
  6152. possibleName = this.getNameByAlternate(expression);
  6153. if (possibleName) {
  6154. names.push(possibleName);
  6155. } else {
  6156. names.push(expression);
  6157. }
  6158. }
  6159. }
  6160. return names;
  6161. }
  6162. };
  6163. var defaultPostprocessors = Manager.defaultPostprocessors;
  6164. //<feature classSystem.alias>
  6165. /**
  6166. * @cfg {String[]} alias
  6167. * @member Ext.Class
  6168. * List of short aliases for class names. Most useful for defining xtypes for widgets:
  6169. *
  6170. * Ext.define('MyApp.CoolPanel', {
  6171. * extend: 'Ext.panel.Panel',
  6172. * alias: ['widget.coolpanel'],
  6173. * title: 'Yeah!'
  6174. * });
  6175. *
  6176. * // Using Ext.create
  6177. * Ext.widget('widget.coolpanel');
  6178. * // Using the shorthand for widgets and in xtypes
  6179. * Ext.widget('panel', {
  6180. * items: [
  6181. * {xtype: 'coolpanel', html: 'Foo'},
  6182. * {xtype: 'coolpanel', html: 'Bar'}
  6183. * ]
  6184. * });
  6185. */
  6186. Manager.registerPostprocessor('alias', function(name, cls, data) {
  6187. var aliases = data.alias,
  6188. i, ln;
  6189. delete data.alias;
  6190. for (i = 0, ln = aliases.length; i < ln; i++) {
  6191. alias = aliases[i];
  6192. this.setAlias(cls, alias);
  6193. }
  6194. });
  6195. /**
  6196. * @cfg {Boolean} singleton
  6197. * @member Ext.Class
  6198. * When set to true, the class will be instantiated as singleton. For example:
  6199. *
  6200. * Ext.define('Logger', {
  6201. * singleton: true,
  6202. * log: function(msg) {
  6203. * console.log(msg);
  6204. * }
  6205. * });
  6206. *
  6207. * Logger.log('Hello');
  6208. */
  6209. Manager.registerPostprocessor('singleton', function(name, cls, data, fn) {
  6210. fn.call(this, name, new cls(), data);
  6211. return false;
  6212. });
  6213. /**
  6214. * @cfg {String/String[]} alternateClassName
  6215. * @member Ext.Class
  6216. * Defines alternate names for this class. For example:
  6217. *
  6218. * Ext.define('Developer', {
  6219. * alternateClassName: ['Coder', 'Hacker'],
  6220. * code: function(msg) {
  6221. * alert('Typing... ' + msg);
  6222. * }
  6223. * });
  6224. *
  6225. * var joe = Ext.create('Developer');
  6226. * joe.code('stackoverflow');
  6227. *
  6228. * var rms = Ext.create('Hacker');
  6229. * rms.code('hack hack');
  6230. */
  6231. Manager.registerPostprocessor('alternateClassName', function(name, cls, data) {
  6232. var alternates = data.alternateClassName,
  6233. i, ln, alternate;
  6234. if (!(alternates instanceof Array)) {
  6235. alternates = [alternates];
  6236. }
  6237. for (i = 0, ln = alternates.length; i < ln; i++) {
  6238. alternate = alternates[i];
  6239. if (typeof alternate !== 'string') {
  6240. Ext.Error.raise({
  6241. sourceClass: "Ext",
  6242. sourceMethod: "define",
  6243. msg: "Invalid alternate of: '" + alternate + "' for class: '" + name + "'; must be a valid string"
  6244. });
  6245. }
  6246. this.set(alternate, cls);
  6247. }
  6248. });
  6249. Manager.setDefaultPostprocessors(['alias', 'singleton', 'alternateClassName']);
  6250. Ext.apply(Ext, {
  6251. /**
  6252. * @method
  6253. * @member Ext
  6254. * @alias Ext.ClassManager#instantiate
  6255. */
  6256. create: alias(Manager, 'instantiate'),
  6257. /**
  6258. * @private
  6259. * API to be stablized
  6260. *
  6261. * @param {Object} item
  6262. * @param {String} namespace
  6263. */
  6264. factory: function(item, namespace) {
  6265. if (item instanceof Array) {
  6266. var i, ln;
  6267. for (i = 0, ln = item.length; i < ln; i++) {
  6268. item[i] = Ext.factory(item[i], namespace);
  6269. }
  6270. return item;
  6271. }
  6272. var isString = (typeof item === 'string');
  6273. if (isString || (item instanceof Object && item.constructor === Object)) {
  6274. var name, config = {};
  6275. if (isString) {
  6276. name = item;
  6277. }
  6278. else {
  6279. name = item.className;
  6280. config = item;
  6281. delete config.className;
  6282. }
  6283. if (namespace !== undefined && name.indexOf(namespace) === -1) {
  6284. name = namespace + '.' + Ext.String.capitalize(name);
  6285. }
  6286. return Ext.create(name, config);
  6287. }
  6288. if (typeof item === 'function') {
  6289. return Ext.create(item);
  6290. }
  6291. return item;
  6292. },
  6293. /**
  6294. * Convenient shorthand to create a widget by its xtype, also see {@link Ext.ClassManager#instantiateByAlias}
  6295. *
  6296. * var button = Ext.widget('button'); // Equivalent to Ext.create('widget.button')
  6297. * var panel = Ext.widget('panel'); // Equivalent to Ext.create('widget.panel')
  6298. *
  6299. * @method
  6300. * @member Ext
  6301. * @param {String} name xtype of the widget to create.
  6302. * @param {Object...} args arguments for the widget constructor.
  6303. * @return {Object} widget instance
  6304. */
  6305. widget: function(name) {
  6306. var args = slice.call(arguments);
  6307. args[0] = 'widget.' + name;
  6308. return Manager.instantiateByAlias.apply(Manager, args);
  6309. },
  6310. /**
  6311. * @method
  6312. * @member Ext
  6313. * @alias Ext.ClassManager#instantiateByAlias
  6314. */
  6315. createByAlias: alias(Manager, 'instantiateByAlias'),
  6316. /**
  6317. * @cfg {String} override
  6318. * @member Ext.Class
  6319. *
  6320. * Defines an override applied to a class. Note that **overrides can only be created using
  6321. * {@link Ext#define}.** {@link Ext.ClassManager#create} only creates classes.
  6322. *
  6323. * To define an override, include the override property. The content of an override is
  6324. * aggregated with the specified class in order to extend or modify that class. This can be
  6325. * as simple as setting default property values or it can extend and/or replace methods.
  6326. * This can also extend the statics of the class.
  6327. *
  6328. * One use for an override is to break a large class into manageable pieces.
  6329. *
  6330. * // File: /src/app/Panel.js
  6331. *
  6332. * Ext.define('My.app.Panel', {
  6333. * extend: 'Ext.panel.Panel',
  6334. * requires: [
  6335. * 'My.app.PanelPart2',
  6336. * 'My.app.PanelPart3'
  6337. * ]
  6338. *
  6339. * constructor: function (config) {
  6340. * this.callSuper(arguments); // calls Ext.panel.Panel's constructor
  6341. * //...
  6342. * },
  6343. *
  6344. * statics: {
  6345. * method: function () {
  6346. * return 'abc';
  6347. * }
  6348. * }
  6349. * });
  6350. *
  6351. * // File: /src/app/PanelPart2.js
  6352. * Ext.define('My.app.PanelPart2', {
  6353. * override: 'My.app.Panel',
  6354. *
  6355. * constructor: function (config) {
  6356. * this.callSuper(arguments); // calls My.app.Panel's constructor
  6357. * //...
  6358. * }
  6359. * });
  6360. *
  6361. * Another use of overrides is to provide optional parts of classes that can be
  6362. * independently required. In this case, the class may even be unaware of the
  6363. * override altogether.
  6364. *
  6365. * Ext.define('My.ux.CoolTip', {
  6366. * override: 'Ext.tip.ToolTip',
  6367. *
  6368. * constructor: function (config) {
  6369. * this.callSuper(arguments); // calls Ext.tip.ToolTip's constructor
  6370. * //...
  6371. * }
  6372. * });
  6373. *
  6374. * The above override can now be required as normal.
  6375. *
  6376. * Ext.define('My.app.App', {
  6377. * requires: [
  6378. * 'My.ux.CoolTip'
  6379. * ]
  6380. * });
  6381. *
  6382. * Overrides can also contain statics:
  6383. *
  6384. * Ext.define('My.app.BarMod', {
  6385. * override: 'Ext.foo.Bar',
  6386. *
  6387. * statics: {
  6388. * method: function (x) {
  6389. * return this.callSuper([x * 2]); // call Ext.foo.Bar.method
  6390. * }
  6391. * }
  6392. * });
  6393. *
  6394. * IMPORTANT: An override is only included in a build if the class it overrides is
  6395. * required. Otherwise, the override, like the target class, is not included.
  6396. */
  6397. /**
  6398. * @method
  6399. *
  6400. * @member Ext
  6401. * @alias Ext.ClassManager#create
  6402. */
  6403. define: function (className, data, createdFn) {
  6404. if (!data.override) {
  6405. return Manager.create.apply(Manager, arguments);
  6406. }
  6407. var requires = data.requires,
  6408. uses = data.uses,
  6409. overrideName = className;
  6410. className = data.override;
  6411. // hoist any 'requires' or 'uses' from the body onto the faux class:
  6412. data = Ext.apply({}, data);
  6413. delete data.requires;
  6414. delete data.uses;
  6415. delete data.override;
  6416. // make sure className is in the requires list:
  6417. if (typeof requires == 'string') {
  6418. requires = [ className, requires ];
  6419. } else if (requires) {
  6420. requires = requires.slice(0);
  6421. requires.unshift(className);
  6422. } else {
  6423. requires = [ className ];
  6424. }
  6425. // TODO - we need to rework this to allow the override to not require the target class
  6426. // and rather 'wait' for it in such a way that if the target class is not in the build,
  6427. // neither are any of its overrides.
  6428. //
  6429. // Also, this should process the overrides for a class ASAP (ideally before any derived
  6430. // classes) if the target class 'requires' the overrides. Without some special handling, the
  6431. // overrides so required will be processed before the class and have to be bufferred even
  6432. // in a build.
  6433. //
  6434. // TODO - we should probably support the "config" processor on an override (to config new
  6435. // functionaliy like Aria) and maybe inheritableStatics (although static is now supported
  6436. // by callSuper). If inheritableStatics causes those statics to be included on derived class
  6437. // constructors, that probably means "no" to this since an override can come after other
  6438. // classes extend the target.
  6439. return Manager.create(overrideName, {
  6440. requires: requires,
  6441. uses: uses,
  6442. isPartial: true,
  6443. constructor: function () {
  6444. throw new Error("Cannot create override '" + overrideName + "'");
  6445. }
  6446. }, function () {
  6447. var cls = Manager.get(className);
  6448. if (cls.override) { // if (normal class)
  6449. cls.override(data);
  6450. } else { // else (singleton)
  6451. cls.self.override(data);
  6452. }
  6453. if (createdFn) {
  6454. // called once the override is applied and with the context of the
  6455. // overridden class (the override itself is a meaningless, name-only
  6456. // thing).
  6457. createdFn.call(cls);
  6458. }
  6459. });
  6460. },
  6461. /**
  6462. * @method
  6463. * @member Ext
  6464. * @alias Ext.ClassManager#getName
  6465. */
  6466. getClassName: alias(Manager, 'getName'),
  6467. /**
  6468. * Returns the displayName property or className or object.
  6469. * When all else fails, returns "Anonymous".
  6470. * @param {Object} object
  6471. * @return {String}
  6472. */
  6473. getDisplayName: function(object) {
  6474. if (object.displayName) {
  6475. return object.displayName;
  6476. }
  6477. if (object.$name && object.$class) {
  6478. return Ext.getClassName(object.$class) + '#' + object.$name;
  6479. }
  6480. if (object.$className) {
  6481. return object.$className;
  6482. }
  6483. return 'Anonymous';
  6484. },
  6485. /**
  6486. * @method
  6487. * @member Ext
  6488. * @alias Ext.ClassManager#getClass
  6489. */
  6490. getClass: alias(Manager, 'getClass'),
  6491. /**
  6492. * Creates namespaces to be used for scoping variables and classes so that they are not global.
  6493. * Specifying the last node of a namespace implicitly creates all other nodes. Usage:
  6494. *
  6495. * Ext.namespace('Company', 'Company.data');
  6496. *
  6497. * // equivalent and preferable to the above syntax
  6498. * Ext.namespace('Company.data');
  6499. *
  6500. * Company.Widget = function() { ... };
  6501. *
  6502. * Company.data.CustomStore = function(config) { ... };
  6503. *
  6504. * @method
  6505. * @member Ext
  6506. * @param {String} namespace1
  6507. * @param {String} namespace2
  6508. * @param {String} etc
  6509. * @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created)
  6510. */
  6511. namespace: alias(Manager, 'createNamespaces')
  6512. });
  6513. /**
  6514. * Old name for {@link Ext#widget}.
  6515. * @deprecated 4.0.0 Use {@link Ext#widget} instead.
  6516. * @method
  6517. * @member Ext
  6518. * @alias Ext#widget
  6519. */
  6520. Ext.createWidget = Ext.widget;
  6521. /**
  6522. * Convenient alias for {@link Ext#namespace Ext.namespace}
  6523. * @method
  6524. * @member Ext
  6525. * @alias Ext#namespace
  6526. */
  6527. Ext.ns = Ext.namespace;
  6528. Class.registerPreprocessor('className', function(cls, data) {
  6529. if (data.$className) {
  6530. cls.$className = data.$className;
  6531. cls.displayName = cls.$className;
  6532. }
  6533. }, true);
  6534. Class.setDefaultPreprocessorPosition('className', 'first');
  6535. Class.registerPreprocessor('xtype', function(cls, data) {
  6536. var xtypes = Ext.Array.from(data.xtype),
  6537. widgetPrefix = 'widget.',
  6538. aliases = Ext.Array.from(data.alias),
  6539. i, ln, xtype;
  6540. data.xtype = xtypes[0];
  6541. data.xtypes = xtypes;
  6542. aliases = data.alias